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/exception.h"
153 #include "wine/unicode.h"
156 # include "wsnwlink.h"
160 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
161 # define sipx_network sipx_addr.x_net
162 # define sipx_node sipx_addr.x_host.c_host
163 #endif /* __FreeBSD__ */
166 #define INADDR_NONE ~0UL
169 WINE_DEFAULT_DEBUG_CHANNEL(winsock);
170 WINE_DECLARE_DEBUG_CHANNEL(winediag);
172 /* critical section to protect some non-reentrant net function */
173 static CRITICAL_SECTION csWSgetXXXbyYYY;
174 static CRITICAL_SECTION_DEBUG critsect_debug =
176 0, 0, &csWSgetXXXbyYYY,
177 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
178 0, 0, { (DWORD_PTR)(__FILE__ ": csWSgetXXXbyYYY") }
180 static CRITICAL_SECTION csWSgetXXXbyYYY = { &critsect_debug, -1, 0, 0, 0, 0 };
182 union generic_unix_sockaddr
184 struct sockaddr addr;
185 char data[128]; /* should be big enough for all families */
188 static inline const char *debugstr_sockaddr( const struct WS_sockaddr *a )
190 if (!a) return "(nil)";
191 switch (a->sa_family)
194 return wine_dbg_sprintf("{ family AF_INET, address %s, port %d }",
195 inet_ntoa(((const struct sockaddr_in *)a)->sin_addr),
196 ntohs(((const struct sockaddr_in *)a)->sin_port));
201 struct WS_sockaddr_in6 *sin = (struct WS_sockaddr_in6 *)a;
203 p = WS_inet_ntop( WS_AF_INET6, &sin->sin6_addr, buf, sizeof(buf) );
205 p = "(unknown IPv6 address)";
206 return wine_dbg_sprintf("{ family AF_INET6, address %s, port %d }",
207 p, ntohs(sin->sin6_port));
213 memcpy( &addr, ((const SOCKADDR_IRDA *)a)->irdaDeviceID, sizeof(addr) );
214 addr = ntohl( addr );
215 return wine_dbg_sprintf("{ family AF_IRDA, addr %08x, name %s }",
217 ((const SOCKADDR_IRDA *)a)->irdaServiceName);
220 return wine_dbg_sprintf("{ family %d }", a->sa_family);
224 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
225 #define SOCKET2HANDLE(s) ((HANDLE)(s))
226 #define HANDLE2SOCKET(h) ((SOCKET)(h))
228 /****************************************************************
229 * Async IO declarations
230 ****************************************************************/
232 typedef struct ws2_async
236 LPWSAOVERLAPPED user_overlapped;
237 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
238 IO_STATUS_BLOCK local_iosb;
239 struct WS_sockaddr *addr;
242 int val; /* for send operations */
243 int *ptr; /* for recv operations */
246 unsigned int n_iovecs;
247 unsigned int first_iovec;
248 struct iovec iovec[1];
251 /****************************************************************/
253 /* ----------------------------------- internal data */
255 /* ws_... struct conversion flags */
257 typedef struct /* WSAAsyncSelect() control struct */
259 HANDLE service, event, sock;
265 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
266 #define WS_MAX_UDP_DATAGRAM 1024
267 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
269 /* hostent's, servent's and protent's are stored in one buffer per thread,
270 * as documented on MSDN for the functions that return any of the buffers */
271 struct per_thread_data
274 struct WS_hostent *he_buffer;
275 struct WS_servent *se_buffer;
276 struct WS_protoent *pe_buffer;
282 /* internal: routing description information */
289 static INT num_startup; /* reference counter */
290 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
292 /* function prototypes */
293 static struct WS_hostent *WS_create_he(char *name, int aliases, int addresses, int fill_addresses);
294 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
295 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
296 static struct WS_servent *WS_dup_se(const struct servent* p_se);
298 int WSAIOCTL_GetInterfaceCount(void);
299 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
301 #define MAP_OPTION(opt) { WS_##opt, opt }
303 static const int ws_sock_map[][2] =
305 MAP_OPTION( SO_DEBUG ),
306 MAP_OPTION( SO_ACCEPTCONN ),
307 MAP_OPTION( SO_REUSEADDR ),
308 MAP_OPTION( SO_KEEPALIVE ),
309 MAP_OPTION( SO_DONTROUTE ),
310 MAP_OPTION( SO_BROADCAST ),
311 MAP_OPTION( SO_LINGER ),
312 MAP_OPTION( SO_OOBINLINE ),
313 MAP_OPTION( SO_SNDBUF ),
314 MAP_OPTION( SO_RCVBUF ),
315 MAP_OPTION( SO_ERROR ),
316 MAP_OPTION( SO_TYPE ),
318 MAP_OPTION( SO_RCVTIMEO ),
321 MAP_OPTION( SO_SNDTIMEO ),
325 static const int ws_tcp_map[][2] =
328 MAP_OPTION( TCP_NODELAY ),
332 static const int ws_ip_map[][2] =
334 MAP_OPTION( IP_MULTICAST_IF ),
335 MAP_OPTION( IP_MULTICAST_TTL ),
336 MAP_OPTION( IP_MULTICAST_LOOP ),
337 MAP_OPTION( IP_ADD_MEMBERSHIP ),
338 MAP_OPTION( IP_DROP_MEMBERSHIP ),
339 MAP_OPTION( IP_OPTIONS ),
341 MAP_OPTION( IP_HDRINCL ),
343 MAP_OPTION( IP_TOS ),
344 MAP_OPTION( IP_TTL ),
347 static const int ws_ipv6_map[][2] =
349 #ifdef IPV6_ADD_MEMBERSHIP
350 MAP_OPTION( IPV6_ADD_MEMBERSHIP ),
352 #ifdef IPV6_DROP_MEMBERSHIP
353 MAP_OPTION( IPV6_DROP_MEMBERSHIP ),
355 MAP_OPTION( IPV6_MULTICAST_IF ),
356 MAP_OPTION( IPV6_MULTICAST_HOPS ),
357 MAP_OPTION( IPV6_MULTICAST_LOOP ),
358 MAP_OPTION( IPV6_UNICAST_HOPS ),
359 MAP_OPTION( IPV6_V6ONLY ),
362 static const int ws_af_map[][2] =
364 MAP_OPTION( AF_UNSPEC ),
365 MAP_OPTION( AF_INET ),
366 MAP_OPTION( AF_INET6 ),
368 MAP_OPTION( AF_IPX ),
371 MAP_OPTION( AF_IRDA ),
373 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
376 static const int ws_socktype_map[][2] =
378 MAP_OPTION( SOCK_DGRAM ),
379 MAP_OPTION( SOCK_STREAM ),
380 MAP_OPTION( SOCK_RAW ),
381 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
384 static const int ws_proto_map[][2] =
386 MAP_OPTION( IPPROTO_IP ),
387 MAP_OPTION( IPPROTO_TCP ),
388 MAP_OPTION( IPPROTO_UDP ),
389 MAP_OPTION( IPPROTO_ICMP ),
390 MAP_OPTION( IPPROTO_IGMP ),
391 MAP_OPTION( IPPROTO_RAW ),
392 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
395 static const int ws_aiflag_map[][2] =
397 MAP_OPTION( AI_PASSIVE ),
398 MAP_OPTION( AI_CANONNAME ),
399 MAP_OPTION( AI_NUMERICHOST ),
400 /* Linux/UNIX knows a lot more. But Windows only
401 * has 3 as far as I could see. -Marcus
405 static const int ws_niflag_map[][2] =
407 MAP_OPTION( NI_NOFQDN ),
408 MAP_OPTION( NI_NUMERICHOST ),
409 MAP_OPTION( NI_NAMEREQD ),
410 MAP_OPTION( NI_NUMERICSERV ),
411 MAP_OPTION( NI_DGRAM ),
414 static const int ws_eai_map[][2] =
416 MAP_OPTION( EAI_AGAIN ),
417 MAP_OPTION( EAI_BADFLAGS ),
418 MAP_OPTION( EAI_FAIL ),
419 MAP_OPTION( EAI_FAMILY ),
420 MAP_OPTION( EAI_MEMORY ),
421 /* Note: EAI_NODATA is deprecated, but still
422 * used by Windows and Linux... We map the newer
423 * EAI_NONAME to EAI_NODATA for now until Windows
427 MAP_OPTION( EAI_NODATA ),
430 { WS_EAI_NODATA, EAI_NONAME },
433 MAP_OPTION( EAI_SERVICE ),
434 MAP_OPTION( EAI_SOCKTYPE ),
438 static const char magic_loopback_addr[] = {127, 12, 34, 56};
440 /* ----------------------------------- error handling */
442 static NTSTATUS sock_get_ntstatus( int err )
446 case EBADF: return STATUS_INVALID_HANDLE;
447 case EBUSY: return STATUS_DEVICE_BUSY;
449 case EACCES: return STATUS_ACCESS_DENIED;
450 case EFAULT: return STATUS_NO_MEMORY;
451 case EINVAL: return STATUS_INVALID_PARAMETER;
453 case EMFILE: return STATUS_TOO_MANY_OPENED_FILES;
454 case EWOULDBLOCK: return STATUS_CANT_WAIT;
455 case EINPROGRESS: return STATUS_PENDING;
456 case EALREADY: return STATUS_NETWORK_BUSY;
457 case ENOTSOCK: return STATUS_OBJECT_TYPE_MISMATCH;
458 case EDESTADDRREQ: return STATUS_INVALID_PARAMETER;
459 case EMSGSIZE: return STATUS_BUFFER_OVERFLOW;
460 case EPROTONOSUPPORT:
461 case ESOCKTNOSUPPORT:
464 case EPROTOTYPE: return STATUS_NOT_SUPPORTED;
465 case ENOPROTOOPT: return STATUS_INVALID_PARAMETER;
466 case EOPNOTSUPP: return STATUS_NOT_SUPPORTED;
467 case EADDRINUSE: return STATUS_ADDRESS_ALREADY_ASSOCIATED;
468 case EADDRNOTAVAIL: return STATUS_INVALID_PARAMETER;
469 case ECONNREFUSED: return STATUS_CONNECTION_REFUSED;
470 case ESHUTDOWN: return STATUS_PIPE_DISCONNECTED;
471 case ENOTCONN: return STATUS_CONNECTION_DISCONNECTED;
472 case ETIMEDOUT: return STATUS_IO_TIMEOUT;
473 case ENETUNREACH: return STATUS_NETWORK_UNREACHABLE;
474 case ENETDOWN: return STATUS_NETWORK_BUSY;
476 case ECONNRESET: return STATUS_CONNECTION_RESET;
477 case ECONNABORTED: return STATUS_CONNECTION_ABORTED;
479 case 0: return STATUS_SUCCESS;
481 WARN("Unknown errno %d!\n", err);
482 return STATUS_UNSUCCESSFUL;
486 static UINT sock_get_error( int err )
490 case EINTR: return WSAEINTR;
491 case EBADF: return WSAEBADF;
493 case EACCES: return WSAEACCES;
494 case EFAULT: return WSAEFAULT;
495 case EINVAL: return WSAEINVAL;
496 case EMFILE: return WSAEMFILE;
497 case EWOULDBLOCK: return WSAEWOULDBLOCK;
498 case EINPROGRESS: return WSAEINPROGRESS;
499 case EALREADY: return WSAEALREADY;
500 case ENOTSOCK: return WSAENOTSOCK;
501 case EDESTADDRREQ: return WSAEDESTADDRREQ;
502 case EMSGSIZE: return WSAEMSGSIZE;
503 case EPROTOTYPE: return WSAEPROTOTYPE;
504 case ENOPROTOOPT: return WSAENOPROTOOPT;
505 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
506 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
507 case EOPNOTSUPP: return WSAEOPNOTSUPP;
508 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
509 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
510 case EADDRINUSE: return WSAEADDRINUSE;
511 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
512 case ENETDOWN: return WSAENETDOWN;
513 case ENETUNREACH: return WSAENETUNREACH;
514 case ENETRESET: return WSAENETRESET;
515 case ECONNABORTED: return WSAECONNABORTED;
517 case ECONNRESET: return WSAECONNRESET;
518 case ENOBUFS: return WSAENOBUFS;
519 case EISCONN: return WSAEISCONN;
520 case ENOTCONN: return WSAENOTCONN;
521 case ESHUTDOWN: return WSAESHUTDOWN;
522 case ETOOMANYREFS: return WSAETOOMANYREFS;
523 case ETIMEDOUT: return WSAETIMEDOUT;
524 case ECONNREFUSED: return WSAECONNREFUSED;
525 case ELOOP: return WSAELOOP;
526 case ENAMETOOLONG: return WSAENAMETOOLONG;
527 case EHOSTDOWN: return WSAEHOSTDOWN;
528 case EHOSTUNREACH: return WSAEHOSTUNREACH;
529 case ENOTEMPTY: return WSAENOTEMPTY;
531 case EPROCLIM: return WSAEPROCLIM;
534 case EUSERS: return WSAEUSERS;
537 case EDQUOT: return WSAEDQUOT;
540 case ESTALE: return WSAESTALE;
543 case EREMOTE: return WSAEREMOTE;
546 /* just in case we ever get here and there are no problems */
549 WARN("Unknown errno %d!\n", err);
550 return WSAEOPNOTSUPP;
554 static UINT wsaErrno(void)
556 int loc_errno = errno;
557 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
559 return sock_get_error( loc_errno );
562 /* most ws2 overlapped functions return an ntstatus-based error code */
563 static NTSTATUS wsaErrStatus(void)
565 int loc_errno = errno;
566 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
568 return sock_get_ntstatus(loc_errno);
571 static UINT wsaHerrno(int loc_errno)
573 WARN("h_errno %d.\n", loc_errno);
577 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
578 case TRY_AGAIN: return WSATRY_AGAIN;
579 case NO_RECOVERY: return WSANO_RECOVERY;
580 case NO_DATA: return WSANO_DATA;
581 case ENOBUFS: return WSAENOBUFS;
585 WARN("Unknown h_errno %d!\n", loc_errno);
586 return WSAEOPNOTSUPP;
590 static inline DWORD NtStatusToWSAError( const DWORD status )
592 /* We only need to cover the status codes set by server async request handling */
596 case STATUS_SUCCESS: wserr = 0; break;
597 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
598 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
599 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
600 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
601 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
602 case STATUS_NETWORK_BUSY: wserr = WSAEALREADY; break;
603 case STATUS_NETWORK_UNREACHABLE: wserr = WSAENETUNREACH; break;
604 case STATUS_CONNECTION_REFUSED: wserr = WSAECONNREFUSED; break;
605 case STATUS_CONNECTION_DISCONNECTED: wserr = WSAENOTCONN; break;
606 case STATUS_CONNECTION_RESET: wserr = WSAECONNRESET; break;
607 case STATUS_CONNECTION_ABORTED: wserr = WSAECONNABORTED; break;
608 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
609 case STATUS_ADDRESS_ALREADY_ASSOCIATED: wserr = WSAEADDRINUSE; break;
610 case STATUS_IO_TIMEOUT:
611 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
612 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
613 case STATUS_ACCESS_DENIED: wserr = WSAEACCES; break;
614 case STATUS_TOO_MANY_OPENED_FILES: wserr = WSAEMFILE; break;
615 case STATUS_CANT_WAIT: wserr = WSAEWOULDBLOCK; break;
616 case STATUS_BUFFER_OVERFLOW: wserr = WSAEMSGSIZE; break;
617 case STATUS_NOT_SUPPORTED: wserr = WSAEOPNOTSUPP; break;
620 wserr = RtlNtStatusToDosError( status );
621 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
626 /* set last error code from NT status without mapping WSA errors */
627 static inline unsigned int set_error( unsigned int err )
631 err = NtStatusToWSAError( err );
637 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
640 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
645 static inline void release_sock_fd( SOCKET s, int fd )
647 wine_server_release_fd( SOCKET2HANDLE(s), fd );
650 static void _enable_event( HANDLE s, unsigned int event,
651 unsigned int sstate, unsigned int cstate )
653 SERVER_START_REQ( enable_socket_event )
655 req->handle = wine_server_obj_handle( s );
657 req->sstate = sstate;
658 req->cstate = cstate;
659 wine_server_call( req );
664 static int _is_blocking(SOCKET s)
667 SERVER_START_REQ( get_socket_event )
669 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
670 req->service = FALSE;
672 wine_server_call( req );
673 ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
679 static unsigned int _get_sock_mask(SOCKET s)
682 SERVER_START_REQ( get_socket_event )
684 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
685 req->service = FALSE;
687 wine_server_call( req );
694 static void _sync_sock_state(SOCKET s)
696 /* do a dummy wineserver request in order to let
697 the wineserver run through its select loop once */
698 (void)_is_blocking(s);
701 static int _get_sock_error(SOCKET s, unsigned int bit)
703 int events[FD_MAX_EVENTS];
705 SERVER_START_REQ( get_socket_event )
707 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
708 req->service = FALSE;
710 wine_server_set_reply( req, events, sizeof(events) );
711 wine_server_call( req );
717 static struct per_thread_data *get_per_thread_data(void)
719 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
720 /* lazy initialization */
723 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
724 NtCurrentTeb()->WinSockData = ptb;
729 static void free_per_thread_data(void)
731 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
735 /* delete scratch buffers */
736 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
737 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
738 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
739 ptb->he_buffer = NULL;
740 ptb->se_buffer = NULL;
741 ptb->pe_buffer = NULL;
743 HeapFree( GetProcessHeap(), 0, ptb );
744 NtCurrentTeb()->WinSockData = NULL;
747 /***********************************************************************
748 * DllMain (WS2_32.init)
750 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
752 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
754 case DLL_PROCESS_ATTACH:
756 case DLL_PROCESS_DETACH:
757 free_per_thread_data();
760 case DLL_THREAD_DETACH:
761 free_per_thread_data();
767 /***********************************************************************
770 * Converts socket flags from Windows format.
771 * Return 1 if converted, 0 if not (error).
773 static int convert_sockopt(INT *level, INT *optname)
780 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
781 if( ws_sock_map[i][0] == *optname )
783 *optname = ws_sock_map[i][1];
787 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
790 *level = IPPROTO_TCP;
791 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
792 if ( ws_tcp_map[i][0] == *optname )
794 *optname = ws_tcp_map[i][1];
798 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
802 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
803 if (ws_ip_map[i][0] == *optname )
805 *optname = ws_ip_map[i][1];
809 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
811 case WS_IPPROTO_IPV6:
812 *level = IPPROTO_IPV6;
813 for(i=0; i<sizeof(ws_ipv6_map)/sizeof(ws_ipv6_map[0]); i++) {
814 if (ws_ipv6_map[i][0] == *optname )
816 *optname = ws_ipv6_map[i][1];
820 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname);
822 default: FIXME("Unimplemented or unknown socket level\n");
827 /* ----------------------------------- Per-thread info (or per-process?) */
829 static char *strdup_lower(const char *str)
832 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
836 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
839 else SetLastError(WSAENOBUFS);
843 static inline int sock_error_p(int s)
845 unsigned int optval, optlen;
847 optlen = sizeof(optval);
848 getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
849 if (optval) WARN("\t[%i] error: %d\n", s, optval);
853 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
854 * from an fd and return the value converted to milli seconds
855 * or -1 if there is an infinite time out */
856 static inline int get_rcvsnd_timeo( int fd, int optname)
859 unsigned int len = sizeof(tv);
860 int ret = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
862 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
863 if( ret <= 0 ) /* tv == {0,0} means infinite time out */
868 /* macro wrappers for portability */
870 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
872 #define GET_RCVTIMEO(fd) (-1)
876 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
878 #define GET_SNDTIMEO(fd) (-1)
881 /* utility: given an fd, will block until one of the events occurs */
882 static inline int do_block( int fd, int events, int timeout )
890 while ((ret = poll(&pfd, 1, timeout)) < 0)
901 convert_af_w2u(int windowsaf) {
904 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
905 if (ws_af_map[i][0] == windowsaf)
906 return ws_af_map[i][1];
907 FIXME("unhandled Windows address family %d\n", windowsaf);
912 convert_af_u2w(int unixaf) {
915 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
916 if (ws_af_map[i][1] == unixaf)
917 return ws_af_map[i][0];
918 FIXME("unhandled UNIX address family %d\n", unixaf);
923 convert_proto_w2u(int windowsproto) {
926 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
927 if (ws_proto_map[i][0] == windowsproto)
928 return ws_proto_map[i][1];
929 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
934 convert_proto_u2w(int unixproto) {
937 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
938 if (ws_proto_map[i][1] == unixproto)
939 return ws_proto_map[i][0];
940 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
945 convert_socktype_w2u(int windowssocktype) {
948 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
949 if (ws_socktype_map[i][0] == windowssocktype)
950 return ws_socktype_map[i][1];
951 FIXME("unhandled Windows socket type %d\n", windowssocktype);
956 convert_socktype_u2w(int unixsocktype) {
959 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
960 if (ws_socktype_map[i][1] == unixsocktype)
961 return ws_socktype_map[i][0];
962 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
966 /* ----------------------------------- API -----
968 * Init / cleanup / error checking.
971 /***********************************************************************
972 * WSAStartup (WS2_32.115)
974 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
976 TRACE("verReq=%x\n", wVersionRequested);
978 if (LOBYTE(wVersionRequested) < 1)
979 return WSAVERNOTSUPPORTED;
981 if (!lpWSAData) return WSAEINVAL;
985 /* that's the whole of the negotiation for now */
986 lpWSAData->wVersion = wVersionRequested;
987 /* return winsock information */
988 lpWSAData->wHighVersion = 0x0202;
989 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
990 strcpy(lpWSAData->szSystemStatus, "Running" );
991 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
992 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
993 /* don't do anything with lpWSAData->lpVendorInfo */
994 /* (some apps don't allocate the space for this field) */
996 TRACE("succeeded\n");
1001 /***********************************************************************
1002 * WSACleanup (WS2_32.116)
1004 INT WINAPI WSACleanup(void)
1010 SetLastError(WSANOTINITIALISED);
1011 return SOCKET_ERROR;
1015 /***********************************************************************
1016 * WSAGetLastError (WS2_32.111)
1018 INT WINAPI WSAGetLastError(void)
1020 return GetLastError();
1023 /***********************************************************************
1024 * WSASetLastError (WS2_32.112)
1026 void WINAPI WSASetLastError(INT iError) {
1027 SetLastError(iError);
1030 static struct WS_hostent *check_buffer_he(int size)
1032 struct per_thread_data * ptb = get_per_thread_data();
1035 if (ptb->he_len >= size ) return ptb->he_buffer;
1036 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1038 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
1039 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
1040 return ptb->he_buffer;
1043 static struct WS_servent *check_buffer_se(int size)
1045 struct per_thread_data * ptb = get_per_thread_data();
1048 if (ptb->se_len >= size ) return ptb->se_buffer;
1049 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1051 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
1052 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
1053 return ptb->se_buffer;
1056 static struct WS_protoent *check_buffer_pe(int size)
1058 struct per_thread_data * ptb = get_per_thread_data();
1061 if (ptb->pe_len >= size ) return ptb->pe_buffer;
1062 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1064 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
1065 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
1066 return ptb->pe_buffer;
1069 /* ----------------------------------- i/o APIs */
1071 static inline BOOL supported_pf(int pf)
1092 /**********************************************************************/
1094 /* Returns the length of the converted address if successful, 0 if it was too small to
1097 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
1098 union generic_unix_sockaddr *uaddr)
1100 unsigned int uaddrlen = 0;
1102 switch (wsaddr->sa_family)
1107 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
1108 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
1110 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
1113 uaddrlen = sizeof(struct sockaddr_ipx);
1114 memset( uaddr, 0, uaddrlen );
1115 uipx->sipx_family=AF_IPX;
1116 uipx->sipx_port=wsipx->sa_socket;
1117 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1120 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
1121 #ifdef IPX_FRAME_NONE
1122 uipx->sipx_type=IPX_FRAME_NONE;
1128 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
1129 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
1131 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1132 * scope_id, one without.
1134 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
1135 uaddrlen = sizeof(struct sockaddr_in6);
1136 memset( uaddr, 0, uaddrlen );
1137 uin6->sin6_family = AF_INET6;
1138 uin6->sin6_port = win6->sin6_port;
1139 uin6->sin6_flowinfo = win6->sin6_flowinfo;
1140 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1141 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
1143 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
1146 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
1150 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
1151 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
1153 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
1155 uaddrlen = sizeof(struct sockaddr_in);
1156 memset( uaddr, 0, uaddrlen );
1157 uin->sin_family = AF_INET;
1158 uin->sin_port = win->sin_port;
1159 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
1164 struct sockaddr_irda *uin = (struct sockaddr_irda *)uaddr;
1165 const SOCKADDR_IRDA *win = (const SOCKADDR_IRDA *)wsaddr;
1167 if (wsaddrlen < sizeof(SOCKADDR_IRDA))
1169 uaddrlen = sizeof(struct sockaddr_irda);
1170 memset( uaddr, 0, uaddrlen );
1171 uin->sir_family = AF_IRDA;
1172 if (!strncmp( win->irdaServiceName, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1174 unsigned int lsap_sel;
1176 sscanf( win->irdaServiceName, "LSAP-SEL%u", &lsap_sel );
1177 uin->sir_lsap_sel = lsap_sel;
1181 uin->sir_lsap_sel = LSAP_ANY;
1182 memcpy( uin->sir_name, win->irdaServiceName, 25 );
1184 memcpy( &uin->sir_addr, win->irdaDeviceID, sizeof(uin->sir_addr) );
1188 case WS_AF_UNSPEC: {
1189 /* Try to determine the needed space by the passed windows sockaddr space */
1190 switch (wsaddrlen) {
1191 default: /* likely a ipv4 address */
1192 case sizeof(struct WS_sockaddr_in):
1193 uaddrlen = sizeof(struct sockaddr_in);
1196 case sizeof(struct WS_sockaddr_ipx):
1197 uaddrlen = sizeof(struct sockaddr_ipx);
1201 case sizeof(SOCKADDR_IRDA):
1202 uaddrlen = sizeof(struct sockaddr_irda);
1205 case sizeof(struct WS_sockaddr_in6):
1206 case sizeof(struct WS_sockaddr_in6_old):
1207 uaddrlen = sizeof(struct sockaddr_in6);
1210 memset( uaddr, 0, uaddrlen );
1214 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
1220 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
1222 switch (uaddr->sa_family)
1226 FIXME("don't know how to tell if IPX socket is bound, assuming it is!\n");
1231 static const struct sockaddr_in6 emptyAddr;
1232 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
1233 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
1237 static const struct sockaddr_in emptyAddr;
1238 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
1239 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
1244 FIXME("unknown address family %d\n", uaddr->sa_family);
1249 /* Returns 0 if successful, -1 if the buffer is too small */
1250 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
1254 switch(uaddr->sa_family)
1259 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
1260 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
1263 switch (*wsaddrlen) /* how much can we copy? */
1267 *wsaddrlen = sizeof(*wsipx);
1268 wsipx->sa_socket=uipx->sipx_port;
1272 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
1280 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1286 wsipx->sa_family=WS_AF_IPX;
1298 const struct sockaddr_irda *uin = (const struct sockaddr_irda *)uaddr;
1299 SOCKADDR_IRDA *win = (SOCKADDR_IRDA *)wsaddr;
1301 if (*wsaddrlen < sizeof(SOCKADDR_IRDA))
1303 win->irdaAddressFamily = WS_AF_IRDA;
1304 memcpy( win->irdaDeviceID, &uin->sir_addr, sizeof(win->irdaDeviceID) );
1305 if (uin->sir_lsap_sel != LSAP_ANY)
1306 sprintf( win->irdaServiceName, "LSAP-SEL%u", uin->sir_lsap_sel );
1308 memcpy( win->irdaServiceName, uin->sir_name,
1309 sizeof(win->irdaServiceName) );
1314 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1315 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1317 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1319 win6old->sin6_family = WS_AF_INET6;
1320 win6old->sin6_port = uin6->sin6_port;
1321 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1322 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1323 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1324 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1325 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1326 win6->sin6_scope_id = uin6->sin6_scope_id;
1327 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1330 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1332 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1337 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1338 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1340 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1342 win->sin_family = WS_AF_INET;
1343 win->sin_port = uin->sin_port;
1344 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1345 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1346 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1350 memset(wsaddr,0,*wsaddrlen);
1354 FIXME("Unknown address family %d\n", uaddr->sa_family);
1360 /**************************************************************************
1361 * Functions for handling overlapped I/O
1362 **************************************************************************/
1364 /* user APC called upon async completion */
1365 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1367 ws2_async *wsa = arg;
1369 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
1370 iosb->Information, wsa->user_overlapped,
1372 HeapFree( GetProcessHeap(), 0, wsa );
1375 /***********************************************************************
1376 * WS2_recv (INTERNAL)
1378 * Workhorse for both synchronous and asynchronous recv() operations.
1380 static int WS2_recv( int fd, struct ws2_async *wsa )
1383 union generic_unix_sockaddr unix_sockaddr;
1386 hdr.msg_name = NULL;
1390 hdr.msg_namelen = sizeof(unix_sockaddr);
1391 hdr.msg_name = &unix_sockaddr;
1394 hdr.msg_namelen = 0;
1396 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1397 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1398 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1399 hdr.msg_accrights = NULL;
1400 hdr.msg_accrightslen = 0;
1402 hdr.msg_control = NULL;
1403 hdr.msg_controllen = 0;
1407 if ( (n = recvmsg(fd, &hdr, wsa->flags)) == -1 )
1410 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
1411 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
1413 * quoting linux 2.6 net/ipv4/tcp.c:
1414 * "According to UNIX98, msg_name/msg_namelen are ignored
1415 * on connected socket. I was just happy when found this 8) --ANK"
1417 * likewise MSDN says that lpFrom and lpFromlen are ignored for
1418 * connection-oriented sockets, so don't try to update lpFrom.
1420 if (wsa->addr && hdr.msg_namelen)
1421 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
1426 /***********************************************************************
1427 * WS2_async_recv (INTERNAL)
1429 * Handler for overlapped recv() operations.
1431 static NTSTATUS WS2_async_recv( void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1433 ws2_async* wsa = user;
1438 case STATUS_ALERTED:
1439 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
1442 result = WS2_recv( fd, wsa );
1443 wine_server_release_fd( wsa->hSocket, fd );
1446 status = STATUS_SUCCESS;
1447 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1451 if (errno == EINTR || errno == EAGAIN)
1453 status = STATUS_PENDING;
1454 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1459 status = wsaErrStatus();
1464 if (status != STATUS_PENDING)
1466 iosb->u.Status = status;
1467 iosb->Information = result;
1468 *apc = ws2_async_apc;
1473 /***********************************************************************
1474 * WS2_send (INTERNAL)
1476 * Workhorse for both synchronous and asynchronous send() operations.
1478 static int WS2_send( int fd, struct ws2_async *wsa )
1481 union generic_unix_sockaddr unix_addr;
1483 hdr.msg_name = NULL;
1484 hdr.msg_namelen = 0;
1488 hdr.msg_name = &unix_addr;
1489 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
1490 if ( !hdr.msg_namelen )
1496 #if defined(HAVE_IPX) && defined(SOL_IPX)
1497 if(wsa->addr->sa_family == WS_AF_IPX)
1499 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
1501 unsigned int len=sizeof(int);
1503 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
1504 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
1505 * the packet type and then we can retrieve it using getsockopt. After that we can set the
1506 * ipx type in the sockaddr_opx structure with the stored value.
1508 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
1509 uipx->sipx_type = val;
1514 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1515 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1516 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1517 hdr.msg_accrights = NULL;
1518 hdr.msg_accrightslen = 0;
1520 hdr.msg_control = NULL;
1521 hdr.msg_controllen = 0;
1525 return sendmsg(fd, &hdr, wsa->flags);
1528 /***********************************************************************
1529 * WS2_async_send (INTERNAL)
1531 * Handler for overlapped send() operations.
1533 static NTSTATUS WS2_async_send(void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1535 ws2_async* wsa = user;
1540 case STATUS_ALERTED:
1541 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
1544 /* check to see if the data is ready (non-blocking) */
1545 result = WS2_send( fd, wsa );
1546 wine_server_release_fd( wsa->hSocket, fd );
1550 int totalLength = 0;
1552 status = STATUS_SUCCESS;
1553 for (i = 0; i < wsa->n_iovecs; i++)
1554 totalLength += wsa->iovec[i].iov_len;
1555 if (result < totalLength)
1556 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1560 if (errno == EINTR || errno == EAGAIN)
1562 status = STATUS_PENDING;
1563 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1567 status = wsaErrStatus();
1573 if (status != STATUS_PENDING)
1575 iosb->u.Status = status;
1576 iosb->Information = result;
1577 *apc = ws2_async_apc;
1582 /***********************************************************************
1583 * WS2_async_shutdown (INTERNAL)
1585 * Handler for shutdown() operations on overlapped sockets.
1587 static NTSTATUS WS2_async_shutdown( void* user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc )
1589 ws2_async* wsa = user;
1594 case STATUS_ALERTED:
1595 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
1598 switch ( wsa->type )
1600 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
1601 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
1603 status = err ? wsaErrStatus() : STATUS_SUCCESS;
1604 wine_server_release_fd( wsa->hSocket, fd );
1607 iosb->u.Status = status;
1608 iosb->Information = 0;
1609 *apc = ws2_async_apc;
1613 /***********************************************************************
1614 * WS2_register_async_shutdown (INTERNAL)
1616 * Helper function for WS_shutdown() on overlapped sockets.
1618 static int WS2_register_async_shutdown( SOCKET s, int type )
1620 struct ws2_async *wsa;
1623 TRACE("s %ld type %d\n", s, type);
1625 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
1629 wsa->hSocket = SOCKET2HANDLE(s);
1631 wsa->completion_func = NULL;
1633 SERVER_START_REQ( register_async )
1636 req->async.handle = wine_server_obj_handle( wsa->hSocket );
1637 req->async.callback = wine_server_client_ptr( WS2_async_shutdown );
1638 req->async.iosb = wine_server_client_ptr( &wsa->local_iosb );
1639 req->async.arg = wine_server_client_ptr( wsa );
1640 req->async.cvalue = 0;
1641 status = wine_server_call( req );
1645 if (status != STATUS_PENDING)
1647 HeapFree( GetProcessHeap(), 0, wsa );
1648 return NtStatusToWSAError( status );
1653 /***********************************************************************
1656 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr,
1663 TRACE("socket %04lx\n", s );
1664 is_blocking = _is_blocking(s);
1667 /* try accepting first (if there is a deferred connection) */
1668 SERVER_START_REQ( accept_socket )
1670 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1671 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
1672 req->attributes = OBJ_INHERIT;
1673 status = wine_server_call( req );
1674 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
1679 if (addr) WS_getpeername(as, addr, addrlen32);
1682 if (is_blocking && status == STATUS_CANT_WAIT)
1684 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1686 do_block(fd, POLLIN, -1);
1687 _sync_sock_state(s); /* let wineserver notice connection */
1688 release_sock_fd( s, fd );
1690 } while (is_blocking && status == STATUS_CANT_WAIT);
1693 return INVALID_SOCKET;
1696 /***********************************************************************
1699 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
1701 int fd = get_sock_fd( s, 0, NULL );
1702 int res = SOCKET_ERROR;
1704 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1708 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
1710 SetLastError(WSAEAFNOSUPPORT);
1714 union generic_unix_sockaddr uaddr;
1715 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1718 SetLastError(WSAEFAULT);
1723 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
1724 if (name->sa_family == WS_AF_INET6 &&
1725 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
1728 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
1730 release_sock_fd( s, fd );
1731 SetLastError(WSAEAFNOSUPPORT);
1732 return SOCKET_ERROR;
1736 if (name->sa_family == WS_AF_INET)
1738 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
1739 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
1741 /* Trying to bind to the default host interface, using
1742 * INADDR_ANY instead*/
1743 WARN("Trying to bind to magic IP address, using "
1744 "INADDR_ANY instead.\n");
1745 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
1748 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
1750 int loc_errno = errno;
1751 WARN("\tfailure - errno = %i\n", errno);
1756 SetLastError(WSAENOTSOCK);
1759 SetLastError(WSAEINVAL);
1762 SetLastError(wsaErrno());
1768 res=0; /* success */
1772 release_sock_fd( s, fd );
1777 /***********************************************************************
1778 * closesocket (WS2_32.3)
1780 int WINAPI WS_closesocket(SOCKET s)
1782 TRACE("socket %04lx\n", s);
1783 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
1784 return SOCKET_ERROR;
1787 /***********************************************************************
1788 * connect (WS2_32.4)
1790 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
1792 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1794 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1798 union generic_unix_sockaddr uaddr;
1799 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1803 SetLastError(WSAEFAULT);
1807 if (name->sa_family == WS_AF_INET)
1809 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
1810 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
1812 /* Trying to connect to magic replace-loopback address,
1813 * assuming we really want to connect to localhost */
1814 TRACE("Trying to connect to magic IP address, using "
1815 "INADDR_LOOPBACK instead.\n");
1816 in4->sin_addr.s_addr = htonl(WS_INADDR_LOOPBACK);
1820 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
1821 goto connect_success;
1824 if (errno == EINPROGRESS)
1826 /* tell wineserver that a connection is in progress */
1827 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1828 FD_CONNECT|FD_READ|FD_WRITE,
1829 FD_WINE_CONNECTED|FD_WINE_LISTENING);
1830 if (_is_blocking(s))
1834 do_block(fd, POLLIN | POLLOUT, -1);
1835 _sync_sock_state(s); /* let wineserver notice connection */
1836 /* retrieve any error codes from it */
1837 result = _get_sock_error(s, FD_CONNECT_BIT);
1839 SetLastError(NtStatusToWSAError(result));
1842 goto connect_success;
1847 SetLastError(WSAEWOULDBLOCK);
1852 SetLastError(wsaErrno());
1854 release_sock_fd( s, fd );
1856 return SOCKET_ERROR;
1859 release_sock_fd( s, fd );
1860 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1861 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
1862 FD_CONNECT|FD_WINE_LISTENING);
1866 /***********************************************************************
1867 * WSAConnect (WS2_32.30)
1869 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
1870 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
1871 LPQOS lpSQOS, LPQOS lpGQOS )
1873 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
1874 FIXME("unsupported parameters!\n");
1875 return WS_connect( s, name, namelen );
1879 /***********************************************************************
1880 * getpeername (WS2_32.5)
1882 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
1887 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, namelen?*namelen:0);
1889 fd = get_sock_fd( s, 0, NULL );
1894 union generic_unix_sockaddr uaddr;
1895 unsigned int uaddrlen = sizeof(uaddr);
1897 if (getpeername(fd, &uaddr.addr, &uaddrlen) == 0)
1899 if (!name || !namelen)
1900 SetLastError(WSAEFAULT);
1901 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
1902 /* The buffer was too small */
1903 SetLastError(WSAEFAULT);
1908 SetLastError(wsaErrno());
1909 release_sock_fd( s, fd );
1914 /***********************************************************************
1915 * getsockname (WS2_32.6)
1917 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
1922 TRACE("socket: %04lx, ptr %p, len %8x\n", s, name, *namelen);
1924 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1925 if( (name == NULL) || (namelen == NULL) )
1927 SetLastError( WSAEFAULT );
1928 return SOCKET_ERROR;
1931 fd = get_sock_fd( s, 0, NULL );
1936 union generic_unix_sockaddr uaddr;
1937 unsigned int uaddrlen = sizeof(uaddr);
1939 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
1941 SetLastError(wsaErrno());
1943 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
1945 SetLastError(WSAEINVAL);
1947 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
1949 /* The buffer was too small */
1950 SetLastError(WSAEFAULT);
1956 release_sock_fd( s, fd );
1961 /***********************************************************************
1962 * getsockopt (WS2_32.7)
1964 INT WINAPI WS_getsockopt(SOCKET s, INT level,
1965 INT optname, char *optval, INT *optlen)
1970 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
1971 s, level, optname, optval, *optlen);
1979 /* Handle common cases. The special cases are below, sorted
1981 case WS_SO_ACCEPTCONN:
1982 case WS_SO_BROADCAST:
1985 case WS_SO_KEEPALIVE:
1986 case WS_SO_OOBINLINE:
1988 case WS_SO_REUSEADDR:
1991 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1992 return SOCKET_ERROR;
1993 convert_sockopt(&level, &optname);
1994 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
1996 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1999 release_sock_fd( s, fd );
2002 case WS_SO_DONTLINGER:
2004 struct linger lingval;
2005 unsigned int len = sizeof(struct linger);
2007 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
2009 SetLastError(WSAEFAULT);
2010 return SOCKET_ERROR;
2012 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2013 return SOCKET_ERROR;
2015 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
2017 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2022 *(BOOL *)optval = (lingval.l_onoff) ? FALSE : TRUE;
2023 *optlen = sizeof(BOOL);
2026 release_sock_fd( s, fd );
2030 /* As mentioned in setsockopt, Windows ignores this, so we
2031 * always return true here */
2032 case WS_SO_DONTROUTE:
2033 if (!optlen || *optlen < sizeof(BOOL) || !optval)
2035 SetLastError(WSAEFAULT);
2036 return SOCKET_ERROR;
2038 *(BOOL *)optval = TRUE;
2039 *optlen = sizeof(BOOL);
2044 struct linger lingval;
2045 unsigned int len = sizeof(struct linger);
2047 /* struct linger and LINGER have different sizes */
2048 if (!optlen || *optlen < sizeof(LINGER) || !optval)
2050 SetLastError(WSAEFAULT);
2051 return SOCKET_ERROR;
2053 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2054 return SOCKET_ERROR;
2056 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
2058 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2063 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
2064 ((LINGER *)optval)->l_linger = lingval.l_linger;
2065 *optlen = sizeof(struct linger);
2068 release_sock_fd( s, fd );
2072 case WS_SO_MAX_MSG_SIZE:
2073 if (!optlen || *optlen < sizeof(int) || !optval)
2075 SetLastError(WSAEFAULT);
2076 return SOCKET_ERROR;
2078 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
2079 *(int *)optval = 65507;
2080 *optlen = sizeof(int);
2083 /* SO_OPENTYPE does not require a valid socket handle. */
2084 case WS_SO_OPENTYPE:
2085 if (!optlen || *optlen < sizeof(int) || !optval)
2087 SetLastError(WSAEFAULT);
2088 return SOCKET_ERROR;
2090 *(int *)optval = get_per_thread_data()->opentype;
2091 *optlen = sizeof(int);
2092 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
2096 case WS_SO_RCVTIMEO:
2099 case WS_SO_SNDTIMEO:
2101 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
2104 unsigned int len = sizeof(struct timeval);
2106 if (!optlen || *optlen < sizeof(int)|| !optval)
2108 SetLastError(WSAEFAULT);
2109 return SOCKET_ERROR;
2111 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2112 return SOCKET_ERROR;
2114 convert_sockopt(&level, &optname);
2115 if (getsockopt(fd, level, optname, &tv, &len) != 0 )
2117 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2122 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
2123 *optlen = sizeof(int);
2126 release_sock_fd( s, fd );
2131 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
2132 SetLastError(WSAENOPROTOOPT);
2133 return SOCKET_ERROR;
2134 } /* end switch(optname) */
2135 }/* end case WS_SOL_SOCKET */
2139 struct WS_sockaddr_ipx addr;
2140 IPX_ADDRESS_DATA *data;
2145 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
2147 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (unsigned int*)optlen) == -1)
2154 socklen_t len=sizeof(struct ipx);
2155 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
2158 *optval = (int)val.ipx_pt;
2161 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
2162 release_sock_fd( s, fd );
2167 * On a Win2000 system with one network card there are usually
2168 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
2169 * Using this call you can then retrieve info about this all.
2170 * In case of Linux it is a bit different. Usually you have
2171 * only "one" device active and further it is not possible to
2172 * query things like the linkspeed.
2174 FIXME("IPX_ADDRESS\n");
2175 namelen = sizeof(struct WS_sockaddr_ipx);
2176 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
2177 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
2179 data = (IPX_ADDRESS_DATA*)optval;
2180 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
2181 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
2182 data->adapternum = 0;
2183 data->wan = FALSE; /* We are not on a wan for now .. */
2184 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
2185 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
2186 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
2187 * note 1MB = 1000kB in this case */
2190 case IPX_MAX_ADAPTER_NUM:
2191 FIXME("IPX_MAX_ADAPTER_NUM\n");
2192 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
2196 FIXME("IPX optname:%x\n", optname);
2197 return SOCKET_ERROR;
2198 }/* end switch(optname) */
2199 } /* end case NSPROTO_IPX */
2206 case WS_IRLMP_ENUMDEVICES:
2208 static const int MAX_IRDA_DEVICES = 10;
2209 char buf[sizeof(struct irda_device_list) +
2210 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
2212 socklen_t len = sizeof(buf);
2214 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2215 return SOCKET_ERROR;
2216 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
2219 SetLastError(wsaErrno());
2220 return SOCKET_ERROR;
2224 struct irda_device_list *src = (struct irda_device_list *)buf;
2225 DEVICELIST *dst = (DEVICELIST *)optval;
2226 INT needed = sizeof(DEVICELIST), i;
2229 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
2230 if (*optlen < needed)
2232 SetLastError(WSAEFAULT);
2233 return SOCKET_ERROR;
2236 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
2237 dst->numDevice = src->len;
2238 for (i = 0; i < src->len; i++)
2240 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
2241 src->dev[i].saddr, src->dev[i].daddr,
2242 src->dev[i].info, src->dev[i].hints[0],
2243 src->dev[i].hints[1]);
2244 memcpy( dst->Device[i].irdaDeviceID,
2246 sizeof(dst->Device[i].irdaDeviceID) ) ;
2247 memcpy( dst->Device[i].irdaDeviceName,
2249 sizeof(dst->Device[i].irdaDeviceName) ) ;
2250 memcpy( &dst->Device[i].irdaDeviceHints1,
2251 &src->dev[i].hints[0],
2252 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
2253 memcpy( &dst->Device[i].irdaDeviceHints2,
2254 &src->dev[i].hints[1],
2255 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
2256 dst->Device[i].irdaCharSet = src->dev[i].charset;
2262 FIXME("IrDA optname:0x%x\n", optname);
2263 return SOCKET_ERROR;
2265 break; /* case WS_SOL_IRLMP */
2268 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
2269 case WS_IPPROTO_TCP:
2272 case WS_TCP_NODELAY:
2273 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2274 return SOCKET_ERROR;
2275 convert_sockopt(&level, &optname);
2276 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2278 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2281 release_sock_fd( s, fd );
2284 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
2285 return SOCKET_ERROR;
2290 case WS_IP_ADD_MEMBERSHIP:
2291 case WS_IP_DROP_MEMBERSHIP:
2295 case WS_IP_MULTICAST_IF:
2296 case WS_IP_MULTICAST_LOOP:
2297 case WS_IP_MULTICAST_TTL:
2301 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2302 return SOCKET_ERROR;
2303 convert_sockopt(&level, &optname);
2304 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2306 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2309 release_sock_fd( s, fd );
2311 case WS_IP_DONTFRAGMENT:
2312 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
2313 *(BOOL*)optval = FALSE;
2316 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
2317 return SOCKET_ERROR;
2319 case WS_IPPROTO_IPV6:
2322 #ifdef IPV6_ADD_MEMBERSHIP
2323 case WS_IPV6_ADD_MEMBERSHIP:
2325 #ifdef IPV6_DROP_MEMBERSHIP
2326 case WS_IPV6_DROP_MEMBERSHIP:
2328 case WS_IPV6_MULTICAST_IF:
2329 case WS_IPV6_MULTICAST_HOPS:
2330 case WS_IPV6_MULTICAST_LOOP:
2331 case WS_IPV6_UNICAST_HOPS:
2332 case WS_IPV6_V6ONLY:
2333 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2334 return SOCKET_ERROR;
2335 convert_sockopt(&level, &optname);
2336 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2338 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2341 release_sock_fd( s, fd );
2343 case WS_IPV6_DONTFRAG:
2344 FIXME("WS_IPV6_DONTFRAG is always false!\n");
2345 *(BOOL*)optval = FALSE;
2348 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
2349 return SOCKET_ERROR;
2352 WARN("Unknown level: 0x%08x\n", level);
2353 SetLastError(WSAEINVAL);
2354 return SOCKET_ERROR;
2355 } /* end switch(level) */
2358 /***********************************************************************
2361 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
2363 return htonl(hostlong);
2367 /***********************************************************************
2370 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
2372 return htons(hostshort);
2375 /***********************************************************************
2376 * WSAHtonl (WS2_32.46)
2377 * From MSDN description of error codes, this function should also
2378 * check if WinSock has been initialized and the socket is a valid
2379 * socket. But why? This function only translates a host byte order
2380 * u_long into a network byte order u_long...
2382 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
2386 *lpnetlong = htonl(hostlong);
2389 WSASetLastError(WSAEFAULT);
2390 return SOCKET_ERROR;
2393 /***********************************************************************
2394 * WSAHtons (WS2_32.47)
2395 * From MSDN description of error codes, this function should also
2396 * check if WinSock has been initialized and the socket is a valid
2397 * socket. But why? This function only translates a host byte order
2398 * u_short into a network byte order u_short...
2400 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
2405 *lpnetshort = htons(hostshort);
2408 WSASetLastError(WSAEFAULT);
2409 return SOCKET_ERROR;
2413 /***********************************************************************
2414 * inet_addr (WS2_32.11)
2416 WS_u_long WINAPI WS_inet_addr(const char *cp)
2418 if (!cp) return INADDR_NONE;
2419 return inet_addr(cp);
2423 /***********************************************************************
2426 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
2428 return ntohl(netlong);
2432 /***********************************************************************
2435 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
2437 return ntohs(netshort);
2441 /***********************************************************************
2442 * inet_ntoa (WS2_32.12)
2444 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
2446 /* use "buffer for dummies" here because some applications have a
2447 * propensity to decode addresses in ws_hostent structure without
2448 * saving them first...
2450 static char dbuffer[16]; /* Yes, 16: 4*3 digits + 3 '.' + 1 '\0' */
2452 char* s = inet_ntoa(*((struct in_addr*)&in));
2458 SetLastError(wsaErrno());
2462 /**********************************************************************
2463 * WSAIoctl (WS2_32.50)
2466 INT WINAPI WSAIoctl(SOCKET s,
2467 DWORD dwIoControlCode,
2470 LPVOID lpbOutBuffer,
2472 LPDWORD lpcbBytesReturned,
2473 LPWSAOVERLAPPED lpOverlapped,
2474 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
2476 TRACE("%ld, 0x%08x, %p, %d, %p, %d, %p, %p, %p\n",
2477 s, dwIoControlCode, lpvInBuffer, cbInBuffer, lpbOutBuffer,
2478 cbOutBuffer, lpcbBytesReturned, lpOverlapped, lpCompletionRoutine);
2480 switch( dwIoControlCode )
2483 if (cbInBuffer != sizeof(WS_u_long)) {
2484 WSASetLastError(WSAEFAULT);
2485 return SOCKET_ERROR;
2487 return WS_ioctlsocket( s, WS_FIONBIO, lpvInBuffer);
2490 if (cbOutBuffer != sizeof(WS_u_long)) {
2491 WSASetLastError(WSAEFAULT);
2492 return SOCKET_ERROR;
2494 return WS_ioctlsocket( s, WS_FIONREAD, lpbOutBuffer);
2496 case WS_SIO_GET_INTERFACE_LIST:
2498 INTERFACE_INFO* intArray = (INTERFACE_INFO*)lpbOutBuffer;
2499 DWORD size, numInt, apiReturn;
2502 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
2506 WSASetLastError(WSAEFAULT);
2507 return SOCKET_ERROR;
2509 if (!lpcbBytesReturned)
2511 WSASetLastError(WSAEFAULT);
2512 return SOCKET_ERROR;
2515 fd = get_sock_fd( s, 0, NULL );
2516 if (fd == -1) return SOCKET_ERROR;
2518 apiReturn = GetAdaptersInfo(NULL, &size);
2519 if (apiReturn == ERROR_NO_DATA)
2523 else if (apiReturn == ERROR_BUFFER_OVERFLOW)
2525 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
2529 if (GetAdaptersInfo(table, &size) == NO_ERROR)
2531 PIP_ADAPTER_INFO ptr;
2533 if (size*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > cbOutBuffer)
2535 WARN("Buffer too small = %u, cbOutBuffer = %u\n", size, cbOutBuffer);
2536 HeapFree(GetProcessHeap(),0,table);
2537 release_sock_fd( s, fd );
2538 WSASetLastError(WSAEFAULT);
2539 return SOCKET_ERROR;
2541 for (ptr = table, numInt = 0; ptr;
2542 ptr = ptr->Next, intArray++, numInt++)
2544 unsigned int addr, mask, bcast;
2545 struct ifreq ifInfo;
2547 /* Socket Status Flags */
2548 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
2549 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
2551 ERR("Error obtaining status flags for socket!\n");
2552 HeapFree(GetProcessHeap(),0,table);
2553 release_sock_fd( s, fd );
2554 WSASetLastError(WSAEINVAL);
2555 return SOCKET_ERROR;
2559 /* set flags; the values of IFF_* are not the same
2560 under Linux and Windows, therefore must generate
2562 intArray->iiFlags = 0;
2563 if (ifInfo.ifr_flags & IFF_BROADCAST)
2564 intArray->iiFlags |= WS_IFF_BROADCAST;
2565 #ifdef IFF_POINTOPOINT
2566 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
2567 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
2569 if (ifInfo.ifr_flags & IFF_LOOPBACK)
2570 intArray->iiFlags |= WS_IFF_LOOPBACK;
2571 if (ifInfo.ifr_flags & IFF_UP)
2572 intArray->iiFlags |= WS_IFF_UP;
2573 if (ifInfo.ifr_flags & IFF_MULTICAST)
2574 intArray->iiFlags |= WS_IFF_MULTICAST;
2577 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
2578 mask = inet_addr(ptr->IpAddressList.IpMask.String);
2579 bcast = addr | ~mask;
2580 intArray->iiAddress.AddressIn.sin_family = AF_INET;
2581 intArray->iiAddress.AddressIn.sin_port = 0;
2582 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
2584 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
2585 intArray->iiNetmask.AddressIn.sin_port = 0;
2586 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
2588 intArray->iiBroadcastAddress.AddressIn.sin_family =
2590 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
2591 intArray->iiBroadcastAddress.AddressIn.sin_addr.
2597 ERR("Unable to get interface table!\n");
2598 release_sock_fd( s, fd );
2599 HeapFree(GetProcessHeap(),0,table);
2600 WSASetLastError(WSAEINVAL);
2601 return SOCKET_ERROR;
2603 HeapFree(GetProcessHeap(),0,table);
2607 release_sock_fd( s, fd );
2608 WSASetLastError(WSAEINVAL);
2609 return SOCKET_ERROR;
2614 ERR("Unable to get interface table!\n");
2615 release_sock_fd( s, fd );
2616 WSASetLastError(WSAEINVAL);
2617 return SOCKET_ERROR;
2619 /* Calculate the size of the array being returned */
2620 *lpcbBytesReturned = sizeof(INTERFACE_INFO) * numInt;
2621 release_sock_fd( s, fd );
2625 case WS_SIO_ADDRESS_LIST_CHANGE:
2626 FIXME("-> SIO_ADDRESS_LIST_CHANGE request: stub\n");
2627 /* FIXME: error and return code depend on whether socket was created
2628 * with WSA_FLAG_OVERLAPPED, but there is no easy way to get this */
2631 case WS_SIO_ADDRESS_LIST_QUERY:
2635 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
2637 if (!lpcbBytesReturned)
2639 WSASetLastError(WSAEFAULT);
2640 return SOCKET_ERROR;
2643 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
2645 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
2648 if (!table || GetAdaptersInfo(table, &size))
2650 HeapFree(GetProcessHeap(), 0, table);
2651 WSASetLastError(WSAEINVAL);
2652 return SOCKET_ERROR;
2655 for (p = table, num = 0; p; p = p->Next)
2656 if (p->IpAddressList.IpAddress.String[0]) num++;
2658 need = sizeof(SOCKET_ADDRESS_LIST) + sizeof(SOCKET_ADDRESS) * (num - 1);
2659 need += sizeof(SOCKADDR) * num;
2660 *lpcbBytesReturned = need;
2662 if (need > cbOutBuffer)
2664 HeapFree(GetProcessHeap(), 0, table);
2665 WSASetLastError(WSAEFAULT);
2666 return SOCKET_ERROR;
2673 SOCKET_ADDRESS_LIST *sa_list = (SOCKET_ADDRESS_LIST *)lpbOutBuffer;
2674 SOCKADDR_IN *sockaddr;
2676 sa = sa_list->Address;
2677 sockaddr = (SOCKADDR_IN *)((char *)sa + num * sizeof(SOCKET_ADDRESS));
2678 sa_list->iAddressCount = num;
2680 for (p = table, i = 0; p; p = p->Next)
2682 if (!p->IpAddressList.IpAddress.String[0]) continue;
2684 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
2685 sa[i].iSockaddrLength = sizeof(SOCKADDR);
2687 sockaddr[i].sin_family = AF_INET;
2688 sockaddr[i].sin_port = 0;
2689 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
2694 HeapFree(GetProcessHeap(), 0, table);
2699 WARN("unable to get IP address list\n");
2700 WSASetLastError(WSAEINVAL);
2701 return SOCKET_ERROR;
2705 FIXME("SIO_FLUSH: stub.\n");
2708 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
2710 static const GUID connectex_guid = WSAID_CONNECTEX;
2711 static const GUID disconnectex_guid = WSAID_DISCONNECTEX;
2712 static const GUID acceptex_guid = WSAID_ACCEPTEX;
2713 static const GUID getaccepexsockaddrs_guid = WSAID_GETACCEPTEXSOCKADDRS;
2714 static const GUID transmitfile_guid = WSAID_TRANSMITFILE;
2715 static const GUID transmitpackets_guid = WSAID_TRANSMITPACKETS;
2716 static const GUID wsarecvmsg_guid = WSAID_WSARECVMSG;
2717 static const GUID wsasendmsg_guid = WSAID_WSASENDMSG;
2719 if ( IsEqualGUID(&connectex_guid, lpvInBuffer) )
2721 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented ConnectEx\n");
2723 else if ( IsEqualGUID(&disconnectex_guid, lpvInBuffer) )
2725 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented DisconnectEx\n");
2727 else if ( IsEqualGUID(&acceptex_guid, lpvInBuffer) )
2729 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented AcceptEx\n");
2731 else if ( IsEqualGUID(&getaccepexsockaddrs_guid, lpvInBuffer) )
2733 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented GetAcceptExSockaddrs\n");
2735 else if ( IsEqualGUID(&transmitfile_guid, lpvInBuffer) )
2737 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitFile\n");
2739 else if ( IsEqualGUID(&transmitpackets_guid, lpvInBuffer) )
2741 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitPackets\n");
2743 else if ( IsEqualGUID(&wsarecvmsg_guid, lpvInBuffer) )
2745 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented WSARecvMsg\n");
2747 else if ( IsEqualGUID(&wsasendmsg_guid, lpvInBuffer) )
2749 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented WSASendMsg\n");
2752 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(lpvInBuffer));
2754 WSASetLastError(WSAEOPNOTSUPP);
2755 return SOCKET_ERROR;
2758 case WS_SIO_KEEPALIVE_VALS:
2761 struct tcp_keepalive *k = lpvInBuffer;
2762 int keepalive = k->onoff ? 1 : 0;
2763 int keepidle = k->keepalivetime / 1000;
2764 int keepintvl = k->keepaliveinterval / 1000;
2768 WSASetLastError(WSAEINVAL);
2769 return SOCKET_ERROR;
2772 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
2774 fd = get_sock_fd(s, 0, NULL);
2775 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
2777 release_sock_fd(s, fd);
2778 WSASetLastError(WSAEINVAL);
2779 return SOCKET_ERROR;
2781 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
2782 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
2784 release_sock_fd(s, fd);
2785 WSASetLastError(WSAEINVAL);
2786 return SOCKET_ERROR;
2788 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
2790 release_sock_fd(s, fd);
2791 WSASetLastError(WSAEINVAL);
2792 return SOCKET_ERROR;
2795 FIXME("ignoring keepalive interval and timeout\n");
2798 release_sock_fd(s, fd);
2802 FIXME("unsupported WS_IOCTL cmd (%08x)\n", dwIoControlCode);
2803 WSASetLastError(WSAEOPNOTSUPP);
2804 return SOCKET_ERROR;
2811 /***********************************************************************
2812 * ioctlsocket (WS2_32.10)
2814 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
2819 TRACE("socket %04lx, cmd %08x, ptr %p\n", s, cmd, argp);
2820 /* broken apps like defcon pass the argp value directly instead of a pointer to it */
2821 if(IS_INTRESOURCE(argp))
2823 SetLastError(WSAEFAULT);
2824 return SOCKET_ERROR;
2834 if( _get_sock_mask(s) )
2836 /* AsyncSelect()'ed sockets are always nonblocking */
2837 if (*argp) return 0;
2838 SetLastError(WSAEINVAL);
2839 return SOCKET_ERROR;
2842 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
2844 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
2852 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
2853 SetLastError(WSAEINVAL);
2854 return SOCKET_ERROR;
2856 case SIOCGIFBRDADDR:
2857 case SIOCGIFNETMASK:
2859 /* These don't need any special handling. They are used by
2860 WsControl, and are here to suppress an unnecessary warning. */
2864 /* Netscape tries hard to use bogus ioctl 0x667e */
2865 /* FIXME: 0x667e above is ('f' << 8) | 126, and is a low word of
2866 * FIONBIO (_IOW('f', 126, u_long)), how that should be handled?
2868 WARN("\tunknown WS_IOCTL cmd (%08x)\n", cmd);
2872 fd = get_sock_fd( s, 0, NULL );
2875 if( ioctl(fd, newcmd, (char*)argp ) == 0 )
2877 release_sock_fd( s, fd );
2880 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2881 release_sock_fd( s, fd );
2883 return SOCKET_ERROR;
2886 /***********************************************************************
2887 * listen (WS2_32.13)
2889 int WINAPI WS_listen(SOCKET s, int backlog)
2891 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2893 TRACE("socket %04lx, backlog %d\n", s, backlog);
2896 if (listen(fd, backlog) == 0)
2898 release_sock_fd( s, fd );
2899 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
2901 FD_CONNECT|FD_WINE_CONNECTED);
2904 SetLastError(wsaErrno());
2905 release_sock_fd( s, fd );
2907 return SOCKET_ERROR;
2910 /***********************************************************************
2913 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
2915 DWORD n, dwFlags = flags;
2921 if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
2922 return SOCKET_ERROR;
2927 /***********************************************************************
2928 * recvfrom (WS2_32.17)
2930 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
2931 struct WS_sockaddr *from, int *fromlen)
2933 DWORD n, dwFlags = flags;
2939 if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL) == SOCKET_ERROR )
2940 return SOCKET_ERROR;
2945 /* allocate a poll array for the corresponding fd sets */
2946 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
2947 const WS_fd_set *exceptfds, int *count_ptr )
2949 unsigned int i, j = 0, count = 0;
2952 if (readfds) count += readfds->fd_count;
2953 if (writefds) count += writefds->fd_count;
2954 if (exceptfds) count += exceptfds->fd_count;
2956 if (!count) return NULL;
2957 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0])))) return NULL;
2959 for (i = 0; i < readfds->fd_count; i++, j++)
2961 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
2962 fds[j].events = POLLIN;
2966 for (i = 0; i < writefds->fd_count; i++, j++)
2968 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
2969 fds[j].events = POLLOUT;
2973 for (i = 0; i < exceptfds->fd_count; i++, j++)
2975 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
2976 fds[j].events = POLLHUP;
2982 /* release the file descriptor obtained in fd_sets_to_poll */
2983 /* must be called with the original fd_set arrays, before calling get_poll_results */
2984 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
2985 const WS_fd_set *exceptfds, struct pollfd *fds )
2987 unsigned int i, j = 0;
2991 for (i = 0; i < readfds->fd_count; i++, j++)
2992 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
2996 for (i = 0; i < writefds->fd_count; i++, j++)
2997 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
3001 for (i = 0; i < exceptfds->fd_count; i++, j++)
3002 if (fds[j].fd != -1)
3004 /* make sure we have a real error before releasing the fd */
3005 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
3006 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
3011 /* map the poll results back into the Windows fd sets */
3012 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
3013 const struct pollfd *fds )
3015 unsigned int i, j = 0, k, total = 0;
3019 for (i = k = 0; i < readfds->fd_count; i++, j++)
3020 if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
3021 readfds->fd_count = k;
3026 for (i = k = 0; i < writefds->fd_count; i++, j++)
3027 if (fds[j].revents) writefds->fd_array[k++] = writefds->fd_array[i];
3028 writefds->fd_count = k;
3033 for (i = k = 0; i < exceptfds->fd_count; i++, j++)
3034 if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
3035 exceptfds->fd_count = k;
3042 /***********************************************************************
3043 * select (WS2_32.18)
3045 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
3046 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
3047 const struct WS_timeval* ws_timeout)
3049 struct pollfd *pollfds;
3050 struct timeval tv1, tv2;
3052 int count, ret, timeout = -1;
3054 TRACE("read %p, write %p, excp %p timeout %p\n",
3055 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
3057 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )) && count)
3059 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
3060 return SOCKET_ERROR;
3065 torig = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
3067 gettimeofday( &tv1, 0 );
3070 while ((ret = poll( pollfds, count, timeout )) < 0)
3074 if (!ws_timeout) continue;
3075 gettimeofday( &tv2, 0 );
3077 tv2.tv_sec -= tv1.tv_sec;
3078 tv2.tv_usec -= tv1.tv_usec;
3079 if (tv2.tv_usec < 0)
3081 tv2.tv_usec += 1000000;
3085 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
3086 if (timeout <= 0) break;
3089 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
3091 if (ret == -1) SetLastError(wsaErrno());
3092 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
3093 HeapFree( GetProcessHeap(), 0, pollfds );
3097 /* helper to send completion messages for client-only i/o operation case */
3098 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
3103 SERVER_START_REQ( add_fd_completion )
3105 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
3106 req->cvalue = CompletionValue;
3107 req->status = CompletionStatus;
3108 req->information = Information;
3109 status = wine_server_call( req );
3115 /***********************************************************************
3118 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
3124 wsabuf.buf = (char*) buf;
3126 if ( WSASendTo( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
3127 return SOCKET_ERROR;
3132 /***********************************************************************
3133 * WSASend (WS2_32.72)
3135 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3136 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
3137 LPWSAOVERLAPPED lpOverlapped,
3138 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3140 return WSASendTo( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
3141 NULL, 0, lpOverlapped, lpCompletionRoutine );
3144 /***********************************************************************
3145 * WSASendDisconnect (WS2_32.73)
3147 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
3149 return WS_shutdown( s, SD_SEND );
3153 /***********************************************************************
3154 * WSASendTo (WS2_32.74)
3156 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3157 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
3158 const struct WS_sockaddr *to, int tolen,
3159 LPWSAOVERLAPPED lpOverlapped,
3160 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3162 unsigned int i, options;
3164 struct ws2_async *wsa;
3165 int totalLength = 0;
3166 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
3168 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
3169 s, lpBuffers, dwBufferCount, dwFlags,
3170 to, tolen, lpOverlapped, lpCompletionRoutine);
3172 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
3173 TRACE( "fd=%d, options=%x\n", fd, options );
3175 if ( fd == -1 ) return SOCKET_ERROR;
3177 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
3183 wsa->hSocket = SOCKET2HANDLE(s);
3184 wsa->addr = (struct WS_sockaddr *)to;
3185 wsa->addrlen.val = tolen;
3186 wsa->flags = dwFlags;
3187 wsa->n_iovecs = dwBufferCount;
3188 wsa->first_iovec = 0;
3189 for ( i = 0; i < dwBufferCount; i++ )
3191 wsa->iovec[i].iov_base = lpBuffers[i].buf;
3192 wsa->iovec[i].iov_len = lpBuffers[i].len;
3193 totalLength += lpBuffers[i].len;
3196 if (!lpNumberOfBytesSent)
3204 n = WS2_send( fd, wsa );
3205 if (n != -1 || errno != EINTR) break;
3207 if (n == -1 && errno != EAGAIN)
3209 int loc_errno = errno;
3211 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
3215 if ((lpOverlapped || lpCompletionRoutine) &&
3216 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
3218 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
3220 wsa->user_overlapped = lpOverlapped;
3221 wsa->completion_func = lpCompletionRoutine;
3222 release_sock_fd( s, fd );
3226 iosb->u.Status = STATUS_PENDING;
3227 iosb->Information = 0;
3229 SERVER_START_REQ( register_async )
3231 req->type = ASYNC_TYPE_WRITE;
3232 req->async.handle = wine_server_obj_handle( wsa->hSocket );
3233 req->async.callback = wine_server_client_ptr( WS2_async_send );
3234 req->async.iosb = wine_server_client_ptr( iosb );
3235 req->async.arg = wine_server_client_ptr( wsa );
3236 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
3237 req->async.cvalue = cvalue;
3238 err = wine_server_call( req );
3242 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
3243 WSASetLastError( NtStatusToWSAError( err ));
3244 return SOCKET_ERROR;
3247 iosb->u.Status = STATUS_SUCCESS;
3248 iosb->Information = n;
3249 *lpNumberOfBytesSent = n;
3250 if (!wsa->completion_func)
3252 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
3253 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
3254 HeapFree( GetProcessHeap(), 0, wsa );
3256 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
3257 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
3262 if ( _is_blocking(s) )
3264 /* On a blocking non-overlapped stream socket,
3265 * sending blocks until the entire buffer is sent. */
3266 DWORD timeout_start = GetTickCount();
3268 *lpNumberOfBytesSent = 0;
3270 while (wsa->first_iovec < dwBufferCount)
3273 int timeout = GET_SNDTIMEO(fd);
3277 *lpNumberOfBytesSent += n;
3278 while (wsa->first_iovec < dwBufferCount && wsa->iovec[wsa->first_iovec].iov_len <= n)
3279 n -= wsa->iovec[wsa->first_iovec++].iov_len;
3280 if (wsa->first_iovec >= dwBufferCount) break;
3281 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
3282 wsa->iovec[wsa->first_iovec].iov_len -= n;
3287 timeout -= GetTickCount() - timeout_start;
3288 if (timeout < 0) timeout = 0;
3292 pfd.events = POLLOUT;
3294 if (!timeout || !poll( &pfd, 1, timeout ))
3297 goto error; /* msdn says a timeout in send is fatal */
3300 n = WS2_send( fd, wsa );
3301 if (n == -1 && errno != EAGAIN && errno != EINTR)
3308 else /* non-blocking */
3310 if (n < totalLength)
3311 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
3314 err = WSAEWOULDBLOCK;
3317 *lpNumberOfBytesSent = n;
3320 TRACE(" -> %i bytes\n", *lpNumberOfBytesSent);
3322 HeapFree( GetProcessHeap(), 0, wsa );
3323 release_sock_fd( s, fd );
3328 HeapFree( GetProcessHeap(), 0, wsa );
3329 release_sock_fd( s, fd );
3330 WARN(" -> ERROR %d\n", err);
3331 WSASetLastError(err);
3332 return SOCKET_ERROR;
3335 /***********************************************************************
3336 * sendto (WS2_32.20)
3338 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
3339 const struct WS_sockaddr *to, int tolen)
3345 wsabuf.buf = (char*) buf;
3347 if ( WSASendTo(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
3348 return SOCKET_ERROR;
3353 /***********************************************************************
3354 * setsockopt (WS2_32.21)
3356 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
3357 const char *optval, int optlen)
3361 struct linger linger;
3362 struct timeval tval;
3364 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
3365 s, level, optname, optval, optlen);
3367 /* some broken apps pass the value directly instead of a pointer to it */
3368 if(IS_INTRESOURCE(optval))
3370 SetLastError(WSAEFAULT);
3371 return SOCKET_ERROR;
3379 /* Some options need some conversion before they can be sent to
3380 * setsockopt. The conversions are done here, then they will fall though
3381 * to the general case. Special options that are not passed to
3382 * setsockopt follow below that.*/
3384 case WS_SO_DONTLINGER:
3385 linger.l_onoff = *((const int*)optval) ? 0: 1;
3386 linger.l_linger = 0;
3388 optname = SO_LINGER;
3389 optval = (char*)&linger;
3390 optlen = sizeof(struct linger);
3394 linger.l_onoff = ((LINGER*)optval)->l_onoff;
3395 linger.l_linger = ((LINGER*)optval)->l_linger;
3396 /* FIXME: what is documented behavior if SO_LINGER optval
3399 optname = SO_LINGER;
3400 optval = (char*)&linger;
3401 optlen = sizeof(struct linger);
3405 if (*(const int*)optval < 2048)
3407 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
3412 /* The options listed here don't need any special handling. Thanks to
3413 * the conversion happening above, options from there will fall through
3415 case WS_SO_ACCEPTCONN:
3416 case WS_SO_BROADCAST:
3418 case WS_SO_KEEPALIVE:
3419 case WS_SO_OOBINLINE:
3420 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
3421 * however, using it the BSD way fixes bug 8513 and seems to be what
3422 * most programmers assume, anyway */
3423 case WS_SO_REUSEADDR:
3426 convert_sockopt(&level, &optname);
3429 /* SO_DEBUG is a privileged operation, ignore it. */
3431 TRACE("Ignoring SO_DEBUG\n");
3434 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
3435 * socket. According to MSDN, this option is silently ignored.*/
3436 case WS_SO_DONTROUTE:
3437 TRACE("Ignoring SO_DONTROUTE\n");
3440 /* Stops two sockets from being bound to the same port. Always happens
3441 * on unix systems, so just drop it. */
3442 case WS_SO_EXCLUSIVEADDRUSE:
3443 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
3446 /* SO_OPENTYPE does not require a valid socket handle. */
3447 case WS_SO_OPENTYPE:
3448 if (!optlen || optlen < sizeof(int) || !optval)
3450 SetLastError(WSAEFAULT);
3451 return SOCKET_ERROR;
3453 get_per_thread_data()->opentype = *(const int *)optval;
3454 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
3458 case WS_SO_RCVTIMEO:
3461 case WS_SO_SNDTIMEO:
3463 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
3464 if (optval && optlen == sizeof(UINT32)) {
3465 /* WinSock passes milliseconds instead of struct timeval */
3466 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
3467 tval.tv_sec = *(const UINT32*)optval / 1000;
3468 /* min of 500 milliseconds */
3469 if (tval.tv_sec == 0 && tval.tv_usec && tval.tv_usec < 500000)
3470 tval.tv_usec = 500000;
3471 optlen = sizeof(struct timeval);
3472 optval = (char*)&tval;
3473 } else if (optlen == sizeof(struct timeval)) {
3474 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
3476 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
3479 convert_sockopt(&level, &optname);
3484 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
3485 SetLastError(WSAENOPROTOOPT);
3486 return SOCKET_ERROR;
3488 break; /* case WS_SOL_SOCKET */
3495 fd = get_sock_fd( s, 0, NULL );
3496 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", *(const int*)optval, fd);
3498 /* We try to set the ipx type on ipx socket level. */
3500 if(setsockopt(fd, SOL_IPX, IPX_TYPE, optval, optlen) == -1)
3502 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
3503 release_sock_fd( s, fd );
3504 return SOCKET_ERROR;
3509 /* Should we retrieve val using a getsockopt call and then
3510 * set the modified one? */
3511 val.ipx_pt = *optval;
3512 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
3515 release_sock_fd( s, fd );
3518 case IPX_FILTERPTYPE:
3519 /* Sets the receive filter packet type, at the moment we don't support it */
3520 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
3521 /* Returning 0 is better for now than returning a SOCKET_ERROR */
3525 FIXME("opt_name:%x\n", optname);
3526 return SOCKET_ERROR;
3528 break; /* case NSPROTO_IPX */
3531 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3532 case WS_IPPROTO_TCP:
3535 case WS_TCP_NODELAY:
3536 convert_sockopt(&level, &optname);
3539 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
3540 return SOCKET_ERROR;
3547 case WS_IP_ADD_MEMBERSHIP:
3548 case WS_IP_DROP_MEMBERSHIP:
3552 case WS_IP_MULTICAST_IF:
3553 case WS_IP_MULTICAST_LOOP:
3554 case WS_IP_MULTICAST_TTL:
3558 convert_sockopt(&level, &optname);
3560 case WS_IP_DONTFRAGMENT:
3561 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
3564 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
3565 return SOCKET_ERROR;
3569 case WS_IPPROTO_IPV6:
3572 #ifdef IPV6_ADD_MEMBERSHIP
3573 case WS_IPV6_ADD_MEMBERSHIP:
3575 #ifdef IPV6_DROP_MEMBERSHIP
3576 case WS_IPV6_DROP_MEMBERSHIP:
3578 case WS_IPV6_MULTICAST_IF:
3579 case WS_IPV6_MULTICAST_HOPS:
3580 case WS_IPV6_MULTICAST_LOOP:
3581 case WS_IPV6_UNICAST_HOPS:
3582 case WS_IPV6_V6ONLY:
3583 convert_sockopt(&level, &optname);
3585 case WS_IPV6_DONTFRAG:
3586 FIXME("IPV6_DONTFRAG is silently ignored!\n");
3589 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
3590 return SOCKET_ERROR;
3595 WARN("Unknown level: 0x%08x\n", level);
3596 SetLastError(WSAEINVAL);
3597 return SOCKET_ERROR;
3598 } /* end switch(level) */
3600 /* avoid endianness issues if argument is a 16-bit int */
3601 if (optval && optlen < sizeof(int))
3603 woptval= *((const INT16 *) optval);
3604 optval= (char*) &woptval;
3607 fd = get_sock_fd( s, 0, NULL );
3608 if (fd == -1) return SOCKET_ERROR;
3610 if (setsockopt(fd, level, optname, optval, optlen) == 0)
3612 release_sock_fd( s, fd );
3615 TRACE("Setting socket error, %d\n", wsaErrno());
3616 SetLastError(wsaErrno());
3617 release_sock_fd( s, fd );
3619 return SOCKET_ERROR;
3622 /***********************************************************************
3623 * shutdown (WS2_32.22)
3625 int WINAPI WS_shutdown(SOCKET s, int how)
3627 int fd, err = WSAENOTSOCK;
3628 unsigned int options, clear_flags = 0;
3630 fd = get_sock_fd( s, 0, &options );
3631 TRACE("socket %04lx, how %i %x\n", s, how, options );
3634 return SOCKET_ERROR;
3638 case 0: /* drop receives */
3639 clear_flags |= FD_READ;
3641 case 1: /* drop sends */
3642 clear_flags |= FD_WRITE;
3644 case 2: /* drop all */
3645 clear_flags |= FD_READ|FD_WRITE;
3647 clear_flags |= FD_WINE_LISTENING;
3650 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
3655 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3658 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3662 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3663 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3666 if (err) goto error;
3668 else /* non-overlapped mode */
3670 if ( shutdown( fd, how ) )
3677 release_sock_fd( s, fd );
3678 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3679 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
3683 release_sock_fd( s, fd );
3684 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3685 WSASetLastError( err );
3686 return SOCKET_ERROR;
3689 /***********************************************************************
3690 * socket (WS2_32.23)
3692 SOCKET WINAPI WS_socket(int af, int type, int protocol)
3694 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
3696 return WSASocketA( af, type, protocol, NULL, 0,
3697 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
3701 /***********************************************************************
3702 * gethostbyaddr (WS2_32.51)
3704 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
3706 struct WS_hostent *retval = NULL;
3707 struct hostent* host;
3709 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3712 struct hostent hostentry;
3715 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3717 int res = gethostbyaddr_r(addr, len, type,
3718 &hostentry, extrabuf, ebufsize, &host, &locerr);
3719 if( res != ERANGE) break;
3721 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3723 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3725 EnterCriticalSection( &csWSgetXXXbyYYY );
3726 host = gethostbyaddr(addr, len, type);
3727 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3729 if( host != NULL ) retval = WS_dup_he(host);
3730 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3731 HeapFree(GetProcessHeap(),0,extrabuf);
3733 LeaveCriticalSection( &csWSgetXXXbyYYY );
3735 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
3739 /***********************************************************************
3740 * WS_get_local_ips (INTERNAL)
3742 * Returns the list of local IP addresses by going through the network
3743 * adapters and using the local routing table to sort the addresses
3744 * from highest routing priority to lowest routing priority. This
3745 * functionality is inferred from the description for obtaining local
3746 * IP addresses given in the Knowledge Base Article Q160215.
3748 * Please note that the returned hostent is only freed when the thread
3749 * closes and is replaced if another hostent is requested.
3751 static struct WS_hostent* WS_get_local_ips( char *hostname )
3753 int last_metric, numroutes = 0, i, j;
3754 PIP_ADAPTER_INFO adapters = NULL, k;
3755 struct WS_hostent *hostlist = NULL;
3756 PMIB_IPFORWARDTABLE routes = NULL;
3757 struct route *route_addrs = NULL;
3758 DWORD adap_size, route_size;
3760 /* Obtain the size of the adapter list and routing table, also allocate memory */
3761 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
3763 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
3765 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
3766 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
3767 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
3768 if (adapters == NULL || routes == NULL || route_addrs == NULL)
3770 /* Obtain the adapter list and the full routing table */
3771 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
3773 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
3775 /* Store the interface associated with each route */
3776 for (i = 0; i < routes->dwNumEntries; i++)
3778 DWORD ifindex, ifmetric, exists = FALSE;
3780 if (routes->table[i].dwForwardType != MIB_IPROUTE_TYPE_DIRECT)
3782 ifindex = routes->table[i].dwForwardIfIndex;
3783 ifmetric = routes->table[i].dwForwardMetric1;
3784 /* Only store the lowest valued metric for an interface */
3785 for (j = 0; j < numroutes; j++)
3787 if (route_addrs[j].interface == ifindex)
3789 if (route_addrs[j].metric > ifmetric)
3790 route_addrs[j].metric = ifmetric;
3796 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
3797 if (route_addrs == NULL)
3798 goto cleanup; /* Memory allocation error, fail gracefully */
3799 route_addrs[numroutes].interface = ifindex;
3800 route_addrs[numroutes].metric = ifmetric;
3801 /* If no IP is found in the next step (for whatever reason)
3802 * then fall back to the magic loopback address.
3804 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
3808 goto cleanup; /* No routes, fall back to the Magic IP */
3809 /* Find the IP address associated with each found interface */
3810 for (i = 0; i < numroutes; i++)
3812 for (k = adapters; k != NULL; k = k->Next)
3814 char *ip = k->IpAddressList.IpAddress.String;
3816 if (route_addrs[i].interface == k->Index)
3817 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
3820 /* Allocate a hostent and enough memory for all the IPs,
3821 * including the NULL at the end of the list.
3823 hostlist = WS_create_he(hostname, 1, numroutes+1, TRUE);
3824 if (hostlist == NULL)
3825 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
3826 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
3827 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
3828 hostlist->h_addrtype = AF_INET;
3829 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
3830 /* Reorder the entries when placing them in the host list, Windows expects
3831 * the IP list in order from highest priority to lowest (the critical thing
3832 * is that most applications expect the first IP to be the default route).
3835 for (i = 0; i < numroutes; i++)
3837 struct in_addr addr;
3838 int metric = 0xFFFF;
3840 memcpy(&addr, magic_loopback_addr, 4);
3841 for (j = 0; j < numroutes; j++)
3843 int this_metric = route_addrs[j].metric;
3845 if (this_metric > last_metric && this_metric < metric)
3847 addr = route_addrs[j].addr;
3848 metric = this_metric;
3851 last_metric = metric;
3852 (*(struct in_addr *) hostlist->h_addr_list[i]) = addr;
3855 /* Cleanup all allocated memory except the address list,
3856 * the address list is used by the calling app.
3859 HeapFree(GetProcessHeap(), 0, route_addrs);
3860 HeapFree(GetProcessHeap(), 0, adapters);
3861 HeapFree(GetProcessHeap(), 0, routes);
3865 /***********************************************************************
3866 * gethostbyname (WS2_32.52)
3868 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
3870 struct WS_hostent *retval = NULL;
3871 struct hostent* host;
3872 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3875 struct hostent hostentry;
3876 int locerr = ENOBUFS;
3879 if( gethostname( hostname, 100) == -1) {
3880 SetLastError( WSAENOBUFS); /* appropriate ? */
3883 if( !name || !name[0]) {
3886 /* If the hostname of the local machine is requested then return the
3887 * complete list of local IP addresses */
3888 if(strcmp(name, hostname) == 0)
3889 retval = WS_get_local_ips(hostname);
3890 /* If any other hostname was requested (or the routing table lookup failed)
3891 * then return the IP found by the host OS */
3894 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3896 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3898 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
3899 if( res != ERANGE) break;
3901 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3903 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3905 EnterCriticalSection( &csWSgetXXXbyYYY );
3906 host = gethostbyname(name);
3907 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3909 if (host) retval = WS_dup_he(host);
3910 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3911 HeapFree(GetProcessHeap(),0,extrabuf);
3913 LeaveCriticalSection( &csWSgetXXXbyYYY );
3916 if (retval && retval->h_addr_list[0][0] == 127 &&
3917 strcmp(name, "localhost") != 0)
3919 /* hostname != "localhost" but has loopback address. replace by our
3920 * special address.*/
3921 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
3923 TRACE( "%s ret %p\n", debugstr_a(name), retval );
3928 /***********************************************************************
3929 * getprotobyname (WS2_32.53)
3931 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
3933 struct WS_protoent* retval = NULL;
3934 #ifdef HAVE_GETPROTOBYNAME
3935 struct protoent* proto;
3936 EnterCriticalSection( &csWSgetXXXbyYYY );
3937 if( (proto = getprotobyname(name)) != NULL )
3939 retval = WS_dup_pe(proto);
3942 MESSAGE("protocol %s not found; You might want to add "
3943 "this to /etc/protocols\n", debugstr_a(name) );
3944 SetLastError(WSANO_DATA);
3946 LeaveCriticalSection( &csWSgetXXXbyYYY );
3948 TRACE( "%s ret %p\n", debugstr_a(name), retval );
3953 /***********************************************************************
3954 * getprotobynumber (WS2_32.54)
3956 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
3958 struct WS_protoent* retval = NULL;
3959 #ifdef HAVE_GETPROTOBYNUMBER
3960 struct protoent* proto;
3961 EnterCriticalSection( &csWSgetXXXbyYYY );
3962 if( (proto = getprotobynumber(number)) != NULL )
3964 retval = WS_dup_pe(proto);
3967 MESSAGE("protocol number %d not found; You might want to add "
3968 "this to /etc/protocols\n", number );
3969 SetLastError(WSANO_DATA);
3971 LeaveCriticalSection( &csWSgetXXXbyYYY );
3973 TRACE("%i ret %p\n", number, retval);
3978 /***********************************************************************
3979 * getservbyname (WS2_32.55)
3981 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
3983 struct WS_servent* retval = NULL;
3984 struct servent* serv;
3986 char *proto_str = NULL;
3988 if (!(name_str = strdup_lower(name))) return NULL;
3990 if (proto && *proto)
3992 if (!(proto_str = strdup_lower(proto)))
3994 HeapFree( GetProcessHeap(), 0, name_str );
3999 EnterCriticalSection( &csWSgetXXXbyYYY );
4000 serv = getservbyname(name_str, proto_str);
4003 retval = WS_dup_se(serv);
4005 else SetLastError(WSANO_DATA);
4006 LeaveCriticalSection( &csWSgetXXXbyYYY );
4007 HeapFree( GetProcessHeap(), 0, proto_str );
4008 HeapFree( GetProcessHeap(), 0, name_str );
4009 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
4013 /***********************************************************************
4014 * freeaddrinfo (WS2_32.@)
4016 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
4019 struct WS_addrinfo *next;
4021 HeapFree(GetProcessHeap(),0,res->ai_canonname);
4022 HeapFree(GetProcessHeap(),0,res->ai_addr);
4023 next = res->ai_next;
4024 HeapFree(GetProcessHeap(),0,res);
4029 /* helper functions for getaddrinfo()/getnameinfo() */
4030 static int convert_aiflag_w2u(int winflags) {
4034 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
4035 if (ws_aiflag_map[i][0] & winflags) {
4036 unixflags |= ws_aiflag_map[i][1];
4037 winflags &= ~ws_aiflag_map[i][0];
4040 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
4044 static int convert_niflag_w2u(int winflags) {
4048 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
4049 if (ws_niflag_map[i][0] & winflags) {
4050 unixflags |= ws_niflag_map[i][1];
4051 winflags &= ~ws_niflag_map[i][0];
4054 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
4058 static int convert_aiflag_u2w(int unixflags) {
4062 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
4063 if (ws_aiflag_map[i][1] & unixflags) {
4064 winflags |= ws_aiflag_map[i][0];
4065 unixflags &= ~ws_aiflag_map[i][1];
4067 if (unixflags) /* will warn usually */
4068 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
4072 static int convert_eai_u2w(int unixret) {
4075 for (i=0;ws_eai_map[i][0];i++)
4076 if (ws_eai_map[i][1] == unixret)
4077 return ws_eai_map[i][0];
4081 /***********************************************************************
4082 * getaddrinfo (WS2_32.@)
4084 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
4086 #ifdef HAVE_GETADDRINFO
4087 struct addrinfo *unixaires = NULL;
4089 struct addrinfo unixhints, *punixhints = NULL;
4090 CHAR *node = NULL, *serv = NULL;
4093 if (!(node = strdup_lower(nodename))) return WSA_NOT_ENOUGH_MEMORY;
4096 if (!(serv = strdup_lower(servname))) {
4097 HeapFree(GetProcessHeap(), 0, node);
4098 return WSA_NOT_ENOUGH_MEMORY;
4103 punixhints = &unixhints;
4105 memset(&unixhints, 0, sizeof(unixhints));
4106 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
4107 if (hints->ai_family == 0) /* wildcard, specific to getaddrinfo() */
4108 punixhints->ai_family = 0;
4110 punixhints->ai_family = convert_af_w2u(hints->ai_family);
4111 if (hints->ai_socktype == 0) /* wildcard, specific to getaddrinfo() */
4112 punixhints->ai_socktype = 0;
4114 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
4115 if (hints->ai_protocol == 0) /* wildcard, specific to getaddrinfo() */
4116 punixhints->ai_protocol = 0;
4118 punixhints->ai_protocol = convert_proto_w2u(hints->ai_protocol);
4121 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
4122 result = getaddrinfo(nodename, servname, punixhints, &unixaires);
4124 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
4126 HeapFree(GetProcessHeap(), 0, node);
4127 HeapFree(GetProcessHeap(), 0, serv);
4130 struct addrinfo *xuai = unixaires;
4131 struct WS_addrinfo **xai = res;
4135 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
4141 *xai = ai;xai = &ai->ai_next;
4142 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
4143 ai->ai_family = convert_af_u2w(xuai->ai_family);
4144 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
4145 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
4146 if (xuai->ai_canonname) {
4147 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
4148 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
4149 if (!ai->ai_canonname)
4151 strcpy(ai->ai_canonname,xuai->ai_canonname);
4153 len = xuai->ai_addrlen;
4154 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
4157 ai->ai_addrlen = len;
4159 int winlen = ai->ai_addrlen;
4161 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
4162 ai->ai_addrlen = winlen;
4166 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
4169 ai->ai_addrlen = len;
4171 xuai = xuai->ai_next;
4173 freeaddrinfo(unixaires);
4175 result = convert_eai_u2w(result);
4181 if (*res) WS_freeaddrinfo(*res);
4182 if (unixaires) freeaddrinfo(unixaires);
4184 return WSA_NOT_ENOUGH_MEMORY;
4186 FIXME("getaddrinfo() failed, not found during buildtime.\n");
4191 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
4193 struct WS_addrinfoW *ret;
4195 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
4196 ret->ai_flags = ai->ai_flags;
4197 ret->ai_family = ai->ai_family;
4198 ret->ai_socktype = ai->ai_socktype;
4199 ret->ai_protocol = ai->ai_protocol;
4200 ret->ai_addrlen = ai->ai_addrlen;
4201 ret->ai_canonname = NULL;
4202 ret->ai_addr = NULL;
4203 ret->ai_next = NULL;
4204 if (ai->ai_canonname)
4206 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
4207 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
4209 HeapFree(GetProcessHeap(), 0, ret);
4212 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
4216 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
4218 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
4219 HeapFree(GetProcessHeap(), 0, ret);
4222 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
4227 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
4229 struct WS_addrinfoW *ret, *infoW;
4231 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
4232 while (info->ai_next)
4234 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
4239 infoW = infoW->ai_next;
4240 info = info->ai_next;
4245 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
4247 struct WS_addrinfo *ret;
4249 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
4250 ret->ai_flags = ai->ai_flags;
4251 ret->ai_family = ai->ai_family;
4252 ret->ai_socktype = ai->ai_socktype;
4253 ret->ai_protocol = ai->ai_protocol;
4254 ret->ai_addrlen = ai->ai_addrlen;
4255 ret->ai_canonname = NULL;
4256 ret->ai_addr = NULL;
4257 ret->ai_next = NULL;
4258 if (ai->ai_canonname)
4260 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
4261 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
4263 HeapFree(GetProcessHeap(), 0, ret);
4266 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
4270 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
4272 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
4273 HeapFree(GetProcessHeap(), 0, ret);
4276 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
4281 /***********************************************************************
4282 * GetAddrInfoW (WS2_32.@)
4284 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
4287 char *nodenameA, *servnameA = NULL;
4288 struct WS_addrinfo *resA, *hintsA = NULL;
4290 if (!nodename) return WSAHOST_NOT_FOUND;
4292 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
4293 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
4294 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
4298 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
4299 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
4301 HeapFree(GetProcessHeap(), 0, nodenameA);
4304 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
4307 if (hints) hintsA = addrinfo_WtoA(hints);
4308 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
4309 WS_freeaddrinfo(hintsA);
4313 *res = addrinfo_list_AtoW(resA);
4314 WS_freeaddrinfo(resA);
4317 HeapFree(GetProcessHeap(), 0, nodenameA);
4318 HeapFree(GetProcessHeap(), 0, servnameA);
4322 /***********************************************************************
4323 * FreeAddrInfoW (WS2_32.@)
4325 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
4330 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
4331 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
4333 HeapFree(GetProcessHeap(), 0, ai);
4338 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
4339 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
4341 #ifdef HAVE_GETNAMEINFO
4343 union generic_unix_sockaddr sa_u;
4346 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
4347 serv, servlen, flags);
4349 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
4352 WSASetLastError(WSAEFAULT);
4353 return WSA_NOT_ENOUGH_MEMORY;
4355 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
4356 return convert_eai_u2w(ret);
4358 FIXME("getnameinfo() failed, not found during buildtime.\n");
4363 /***********************************************************************
4364 * getservbyport (WS2_32.56)
4366 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
4368 struct WS_servent* retval = NULL;
4369 #ifdef HAVE_GETSERVBYPORT
4370 struct servent* serv;
4371 char *proto_str = NULL;
4373 if (proto && *proto)
4375 if (!(proto_str = strdup_lower(proto))) return NULL;
4377 EnterCriticalSection( &csWSgetXXXbyYYY );
4378 if( (serv = getservbyport(port, proto_str)) != NULL ) {
4379 retval = WS_dup_se(serv);
4381 else SetLastError(WSANO_DATA);
4382 LeaveCriticalSection( &csWSgetXXXbyYYY );
4383 HeapFree( GetProcessHeap(), 0, proto_str );
4385 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
4390 /***********************************************************************
4391 * gethostname (WS2_32.57)
4393 int WINAPI WS_gethostname(char *name, int namelen)
4395 TRACE("name %p, len %d\n", name, namelen);
4397 if (gethostname(name, namelen) == 0)
4399 TRACE("<- '%s'\n", name);
4402 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
4403 TRACE("<- ERROR !\n");
4404 return SOCKET_ERROR;
4408 /* ------------------------------------- Windows sockets extensions -- *
4410 * ------------------------------------------------------------------- */
4412 /***********************************************************************
4413 * WSAEnumNetworkEvents (WS2_32.36)
4415 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
4419 int errors[FD_MAX_EVENTS];
4421 TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
4423 SERVER_START_REQ( get_socket_event )
4425 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
4426 req->service = TRUE;
4427 req->c_event = wine_server_obj_handle( hEvent );
4428 wine_server_set_reply( req, errors, sizeof(errors) );
4429 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
4434 for (i = 0; i < FD_MAX_EVENTS; i++)
4435 lpEvent->iErrorCode[i] = NtStatusToWSAError(errors[i]);
4438 SetLastError(WSAEINVAL);
4439 return SOCKET_ERROR;
4442 /***********************************************************************
4443 * WSAEventSelect (WS2_32.39)
4445 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
4449 TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
4451 SERVER_START_REQ( set_socket_event )
4453 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
4455 req->event = wine_server_obj_handle( hEvent );
4458 ret = wine_server_call( req );
4462 SetLastError(WSAEINVAL);
4463 return SOCKET_ERROR;
4466 /**********************************************************************
4467 * WSAGetOverlappedResult (WS2_32.40)
4469 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
4470 LPDWORD lpcbTransfer, BOOL fWait,
4475 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
4476 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
4478 if ( lpOverlapped == NULL )
4480 ERR( "Invalid pointer\n" );
4481 WSASetLastError(WSA_INVALID_PARAMETER);
4485 status = lpOverlapped->Internal;
4486 if (status == STATUS_PENDING)
4490 SetLastError( WSA_IO_INCOMPLETE );
4494 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
4495 INFINITE ) == WAIT_FAILED)
4497 status = lpOverlapped->Internal;
4501 *lpcbTransfer = lpOverlapped->InternalHigh;
4504 *lpdwFlags = lpOverlapped->u.s.Offset;
4506 if (status) SetLastError( RtlNtStatusToDosError(status) );
4511 /***********************************************************************
4512 * WSAAsyncSelect (WS2_32.101)
4514 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
4518 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
4520 SERVER_START_REQ( set_socket_event )
4522 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
4525 req->window = wine_server_user_handle( hWnd );
4527 ret = wine_server_call( req );
4531 SetLastError(WSAEINVAL);
4532 return SOCKET_ERROR;
4535 /***********************************************************************
4536 * WSACreateEvent (WS2_32.31)
4539 WSAEVENT WINAPI WSACreateEvent(void)
4541 /* Create a manual-reset event, with initial state: unsignaled */
4544 return CreateEventW(NULL, TRUE, FALSE, NULL);
4547 /***********************************************************************
4548 * WSACloseEvent (WS2_32.29)
4551 BOOL WINAPI WSACloseEvent(WSAEVENT event)
4553 TRACE ("event=%p\n", event);
4555 return CloseHandle(event);
4558 /***********************************************************************
4559 * WSASocketA (WS2_32.78)
4562 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
4563 LPWSAPROTOCOL_INFOA lpProtocolInfo,
4564 GROUP g, DWORD dwFlags)
4567 WSAPROTOCOL_INFOW info;
4569 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
4570 af, type, protocol, lpProtocolInfo, g, dwFlags);
4572 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
4574 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
4575 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
4576 info.szProtocol, WSAPROTOCOL_LEN + 1);
4580 WSASetLastError( WSAEINVAL);
4581 return SOCKET_ERROR;
4584 return WSASocketW(af, type, protocol, &info, g, dwFlags);
4587 /***********************************************************************
4588 * WSASocketW (WS2_32.79)
4591 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
4592 LPWSAPROTOCOL_INFOW lpProtocolInfo,
4593 GROUP g, DWORD dwFlags)
4598 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
4599 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
4602 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
4603 af, type, protocol, lpProtocolInfo, g, dwFlags );
4605 /* hack for WSADuplicateSocket */
4606 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
4607 ret = lpProtocolInfo->dwCatalogEntryId;
4608 TRACE("\tgot duplicate %04lx\n", ret);
4612 /* convert the socket family and type */
4613 af = convert_af_w2u(af);
4614 type = convert_socktype_w2u(type);
4618 if (af == FROM_PROTOCOL_INFO)
4619 af = lpProtocolInfo->iAddressFamily;
4620 if (type == FROM_PROTOCOL_INFO)
4621 type = lpProtocolInfo->iSocketType;
4622 if (protocol == FROM_PROTOCOL_INFO)
4623 protocol = lpProtocolInfo->iProtocol;
4626 if ( af == AF_UNSPEC) /* did they not specify the address family? */
4630 if (type == SOCK_STREAM) { af = AF_INET; break; }
4632 if (type == SOCK_DGRAM) { af = AF_INET; break; }
4633 default: SetLastError(WSAEPROTOTYPE); return INVALID_SOCKET;
4636 SERVER_START_REQ( create_socket )
4640 req->protocol = protocol;
4641 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
4642 req->attributes = OBJ_INHERIT;
4643 req->flags = dwFlags;
4644 set_error( wine_server_call( req ) );
4645 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
4650 TRACE("\tcreated %04lx\n", ret );
4654 if (GetLastError() == WSAEACCES) /* raw socket denied */
4656 if (type == SOCK_RAW)
4657 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
4659 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
4660 SetLastError(WSAESOCKTNOSUPPORT);
4663 WARN("\t\tfailed!\n");
4664 return INVALID_SOCKET;
4667 /***********************************************************************
4668 * WSAJoinLeaf (WS2_32.58)
4671 SOCKET WINAPI WSAJoinLeaf(
4673 const struct WS_sockaddr *addr,
4675 LPWSABUF lpCallerData,
4676 LPWSABUF lpCalleeData,
4682 return INVALID_SOCKET;
4685 /***********************************************************************
4686 * __WSAFDIsSet (WS2_32.151)
4688 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
4690 int i = set->fd_count;
4692 TRACE("(%ld,%p(%i))\n", s, set, i);
4695 if (set->fd_array[i] == s) return 1;
4699 /***********************************************************************
4700 * WSAIsBlocking (WS2_32.114)
4702 BOOL WINAPI WSAIsBlocking(void)
4704 /* By default WinSock should set all its sockets to non-blocking mode
4705 * and poll in PeekMessage loop when processing "blocking" ones. This
4706 * function is supposed to tell if the program is in this loop. Our
4707 * blocking calls are truly blocking so we always return FALSE.
4709 * Note: It is allowed to call this function without prior WSAStartup().
4716 /***********************************************************************
4717 * WSACancelBlockingCall (WS2_32.113)
4719 INT WINAPI WSACancelBlockingCall(void)
4725 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
4727 FIXME("How was this called?\n");
4732 /***********************************************************************
4733 * WSASetBlockingHook (WS2_32.109)
4735 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
4737 FARPROC prev = blocking_hook;
4738 blocking_hook = lpBlockFunc;
4739 TRACE("hook %p\n", lpBlockFunc);
4744 /***********************************************************************
4745 * WSAUnhookBlockingHook (WS2_32.110)
4747 INT WINAPI WSAUnhookBlockingHook(void)
4749 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
4754 /* ----------------------------------- end of API stuff */
4756 /* ----------------------------------- helper functions -
4758 * TODO: Merge WS_dup_..() stuff into one function that
4759 * would operate with a generic structure containing internal
4760 * pointers (via a template of some kind).
4763 static int list_size(char** l, int item_size)
4768 j += (item_size) ? item_size : strlen(l[i]) + 1;
4769 j += (i + 1) * sizeof(char*); }
4773 static int list_dup(char** l_src, char** l_to, int item_size)
4778 for (i = 0; l_src[i]; i++) ;
4779 p = (char *)(l_to + i + 1);
4780 for (i = 0; l_src[i]; i++)
4782 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
4783 memcpy(p, l_src[i], count);
4788 return p - (char *)l_to;
4793 /* create a hostent entry
4795 * Creates the entry with enough memory for the name, aliases
4796 * addresses, and the address pointers. Also copies the name
4797 * and sets up all the pointers. If "fill_addresses" is set then
4798 * sufficient memory for the addresses is also allocated and the
4799 * address pointers are set to this memory.
4801 * NOTE: The alias and address lists must be allocated with room
4802 * for the NULL item terminating the list. This is true even if
4803 * the list has no items ("aliases" and "addresses" must be
4804 * at least "1", a truly empty list is invalid).
4806 static struct WS_hostent *WS_create_he(char *name, int aliases, int addresses, int fill_addresses)
4808 struct WS_hostent *p_to;
4811 int size = (sizeof(struct WS_hostent) +
4813 sizeof(char *)*aliases +
4814 sizeof(char *)*addresses);
4816 /* Allocate enough memory for the addresses */
4818 size += sizeof(struct in_addr)*addresses;
4820 if (!(p_to = check_buffer_he(size))) return NULL;
4821 memset(p_to, 0, size);
4823 p = (char *)(p_to + 1);
4828 p_to->h_aliases = (char **)p;
4829 p += sizeof(char *)*aliases;
4830 p_to->h_addr_list = (char **)p;
4831 p += sizeof(char *)*addresses;
4836 /* NOTE: h_aliases must be filled in manually, leave these
4837 * pointers NULL (already set to NULL by memset earlier).
4840 /* Fill in the list of address pointers */
4841 for (i = 0; i < addresses; i++)
4842 p_to->h_addr_list[i] = (p += sizeof(struct in_addr));
4843 p += sizeof(struct in_addr);
4848 /* duplicate hostent entry
4849 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
4850 * Ditto for protoent and servent.
4852 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
4854 int addresses = list_size(p_he->h_addr_list, p_he->h_length);
4855 int aliases = list_size(p_he->h_aliases, 0);
4856 struct WS_hostent *p_to;
4858 p_to = WS_create_he(p_he->h_name, aliases, addresses, FALSE);
4860 if (!p_to) return NULL;
4861 p_to->h_addrtype = p_he->h_addrtype;
4862 p_to->h_length = p_he->h_length;
4864 list_dup(p_he->h_aliases, p_to->h_aliases, 0);
4865 list_dup(p_he->h_addr_list, p_to->h_addr_list, p_he->h_length);
4869 /* ----- protoent */
4871 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
4874 struct WS_protoent *p_to;
4876 int size = (sizeof(*p_pe) +
4877 strlen(p_pe->p_name) + 1 +
4878 list_size(p_pe->p_aliases, 0));
4880 if (!(p_to = check_buffer_pe(size))) return NULL;
4881 p_to->p_proto = p_pe->p_proto;
4883 p = (char *)(p_to + 1);
4885 strcpy(p, p_pe->p_name);
4888 p_to->p_aliases = (char **)p;
4889 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
4895 static struct WS_servent *WS_dup_se(const struct servent* p_se)
4898 struct WS_servent *p_to;
4900 int size = (sizeof(*p_se) +
4901 strlen(p_se->s_proto) + 1 +
4902 strlen(p_se->s_name) + 1 +
4903 list_size(p_se->s_aliases, 0));
4905 if (!(p_to = check_buffer_se(size))) return NULL;
4906 p_to->s_port = p_se->s_port;
4908 p = (char *)(p_to + 1);
4910 strcpy(p, p_se->s_name);
4914 strcpy(p, p_se->s_proto);
4917 p_to->s_aliases = (char **)p;
4918 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
4923 /***********************************************************************
4924 * WSARecv (WS2_32.67)
4926 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4927 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
4928 LPWSAOVERLAPPED lpOverlapped,
4929 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
4931 return WSARecvFrom(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
4932 NULL, NULL, lpOverlapped, lpCompletionRoutine);
4935 /***********************************************************************
4936 * WSARecvFrom (WS2_32.69)
4938 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4939 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
4940 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
4941 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4944 unsigned int i, options;
4946 struct ws2_async *wsa;
4947 DWORD timeout_start = GetTickCount();
4948 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
4950 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
4951 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
4952 (lpFromlen ? *lpFromlen : -1),
4953 lpOverlapped, lpCompletionRoutine);
4955 fd = get_sock_fd( s, FILE_READ_DATA, &options );
4956 TRACE( "fd=%d, options=%x\n", fd, options );
4958 if (fd == -1) return SOCKET_ERROR;
4960 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
4966 wsa->hSocket = SOCKET2HANDLE(s);
4967 wsa->flags = *lpFlags;
4969 wsa->addrlen.ptr = lpFromlen;
4970 wsa->n_iovecs = dwBufferCount;
4971 wsa->first_iovec = 0;
4972 for (i = 0; i < dwBufferCount; i++)
4974 /* check buffer first to trigger write watches */
4975 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
4980 wsa->iovec[i].iov_base = lpBuffers[i].buf;
4981 wsa->iovec[i].iov_len = lpBuffers[i].len;
4986 n = WS2_recv( fd, wsa );
4989 if (errno == EINTR) continue;
4990 if (errno != EAGAIN)
4992 int loc_errno = errno;
4994 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
4999 *lpNumberOfBytesRecvd = n;
5001 if ((lpOverlapped || lpCompletionRoutine) &&
5002 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
5004 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
5006 wsa->user_overlapped = lpOverlapped;
5007 wsa->completion_func = lpCompletionRoutine;
5008 release_sock_fd( s, fd );
5012 iosb->u.Status = STATUS_PENDING;
5013 iosb->Information = 0;
5015 SERVER_START_REQ( register_async )
5017 req->type = ASYNC_TYPE_READ;
5018 req->async.handle = wine_server_obj_handle( wsa->hSocket );
5019 req->async.callback = wine_server_client_ptr( WS2_async_recv );
5020 req->async.iosb = wine_server_client_ptr( iosb );
5021 req->async.arg = wine_server_client_ptr( wsa );
5022 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
5023 req->async.cvalue = cvalue;
5024 err = wine_server_call( req );
5028 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
5029 WSASetLastError( NtStatusToWSAError( err ));
5030 return SOCKET_ERROR;
5033 iosb->u.Status = STATUS_SUCCESS;
5034 iosb->Information = n;
5035 if (!wsa->completion_func)
5037 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
5038 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
5039 HeapFree( GetProcessHeap(), 0, wsa );
5041 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
5042 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
5043 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5049 if ( _is_blocking(s) )
5052 int timeout = GET_RCVTIMEO(fd);
5055 timeout -= GetTickCount() - timeout_start;
5056 if (timeout < 0) timeout = 0;
5060 pfd.events = POLLIN;
5061 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
5063 if (!timeout || !poll( &pfd, 1, timeout ))
5066 /* a timeout is not fatal */
5067 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5073 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5074 err = WSAEWOULDBLOCK;
5079 TRACE(" -> %i bytes\n", n);
5080 HeapFree( GetProcessHeap(), 0, wsa );
5081 release_sock_fd( s, fd );
5082 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5087 HeapFree( GetProcessHeap(), 0, wsa );
5088 release_sock_fd( s, fd );
5089 WARN(" -> ERROR %d\n", err);
5090 WSASetLastError( err );
5091 return SOCKET_ERROR;
5094 /***********************************************************************
5095 * WSCInstallProvider (WS2_32.88)
5097 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
5098 LPCWSTR lpszProviderDllPath,
5099 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
5100 DWORD dwNumberOfEntries,
5103 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
5104 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
5105 dwNumberOfEntries, lpErrno);
5111 /***********************************************************************
5112 * WSCDeinstallProvider (WS2_32.83)
5114 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
5116 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
5122 /***********************************************************************
5123 * WSAAccept (WS2_32.26)
5125 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
5126 LPCONDITIONPROC lpfnCondition, DWORD dwCallbackData)
5129 int ret = 0, size = 0;
5130 WSABUF CallerId, CallerData, CalleeId, CalleeData;
5131 /* QOS SQOS, GQOS; */
5134 SOCKADDR src_addr, dst_addr;
5136 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %d\n",
5137 s, addr, addrlen, lpfnCondition, dwCallbackData);
5140 size = sizeof(src_addr);
5141 cs = WS_accept(s, &src_addr, &size);
5143 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
5145 if (!lpfnCondition) return cs;
5147 CallerId.buf = (char *)&src_addr;
5148 CallerId.len = sizeof(src_addr);
5150 CallerData.buf = NULL;
5153 WS_getsockname(cs, &dst_addr, &size);
5155 CalleeId.buf = (char *)&dst_addr;
5156 CalleeId.len = sizeof(dst_addr);
5159 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
5160 &CalleeId, &CalleeData, &g, dwCallbackData);
5165 if (addr && addrlen)
5166 addr = memcpy(addr, &src_addr, (*addrlen > size) ? size : *addrlen );
5169 SERVER_START_REQ( set_socket_deferred )
5171 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5172 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
5173 if ( !wine_server_call_err ( req ) )
5175 SetLastError( WSATRY_AGAIN );
5176 WS_closesocket( cs );
5180 return SOCKET_ERROR;
5183 SetLastError(WSAECONNREFUSED);
5184 return SOCKET_ERROR;
5186 FIXME("Unknown return type from Condition function\n");
5187 SetLastError(WSAENOTSOCK);
5188 return SOCKET_ERROR;
5192 /***********************************************************************
5193 * WSADuplicateSocketA (WS2_32.32)
5195 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
5199 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
5200 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
5201 /* FIXME: WS_getsockopt(s, WS_SOL_SOCKET, SO_PROTOCOL_INFO, lpProtocolInfo, sizeof(*lpProtocolInfo)); */
5202 /* I don't know what the real Windoze does next, this is a hack */
5203 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
5204 * the target use the global duplicate, or we could copy a reference to us to the structure
5205 * and let the target duplicate it from us, but let's do it as simple as possible */
5206 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
5207 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
5208 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
5209 0, FALSE, DUPLICATE_SAME_ACCESS);
5210 CloseHandle(hProcess);
5211 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
5215 /***********************************************************************
5216 * WSADuplicateSocketW (WS2_32.33)
5218 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
5222 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
5224 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
5225 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
5226 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
5227 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
5228 0, FALSE, DUPLICATE_SAME_ACCESS);
5229 CloseHandle(hProcess);
5230 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
5234 /***********************************************************************
5235 * WSAInstallServiceClassA (WS2_32.48)
5237 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
5239 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
5240 WSASetLastError(WSAEACCES);
5241 return SOCKET_ERROR;
5244 /***********************************************************************
5245 * WSAInstallServiceClassW (WS2_32.49)
5247 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
5249 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
5250 WSASetLastError(WSAEACCES);
5251 return SOCKET_ERROR;
5254 /***********************************************************************
5255 * WSARemoveServiceClass (WS2_32.70)
5257 int WINAPI WSARemoveServiceClass(LPGUID info)
5259 FIXME("Request to remove service %p\n",info);
5260 WSASetLastError(WSATYPE_NOT_FOUND);
5261 return SOCKET_ERROR;
5264 /***********************************************************************
5265 * inet_ntop (WS2_32.@)
5267 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
5269 #ifdef HAVE_INET_NTOP
5270 struct WS_in6_addr *in6;
5271 struct WS_in_addr *in;
5274 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
5277 WSASetLastError( STATUS_INVALID_PARAMETER );
5286 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
5292 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
5296 WSASetLastError( WSAEAFNOSUPPORT );
5300 if (!pdst) WSASetLastError( STATUS_INVALID_PARAMETER );
5303 FIXME( "not supported on this platform\n" );
5304 WSASetLastError( WSAEAFNOSUPPORT );
5309 /***********************************************************************
5310 * WSAStringToAddressA (WS2_32.80)
5312 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
5314 LPWSAPROTOCOL_INFOA lpProtocolInfo,
5315 LPSOCKADDR lpAddress,
5316 LPINT lpAddressLength)
5319 LPSTR workBuffer=NULL,ptrPort;
5321 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
5322 lpProtocolInfo, lpAddress, lpAddressLength );
5324 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
5328 WSASetLastError(WSAEINVAL);
5329 return SOCKET_ERROR;
5333 FIXME("ProtocolInfo not implemented.\n");
5335 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
5336 strlen(AddressString) + 1);
5339 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5340 return SOCKET_ERROR;
5343 strcpy(workBuffer, AddressString);
5345 switch(AddressFamily)
5349 struct in_addr inetaddr;
5351 /* If lpAddressLength is too small, tell caller the size we need */
5352 if (*lpAddressLength < sizeof(SOCKADDR_IN))
5354 *lpAddressLength = sizeof(SOCKADDR_IN);
5358 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
5360 ((LPSOCKADDR_IN)lpAddress)->sin_family = AF_INET;
5362 ptrPort = strchr(workBuffer, ':');
5365 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
5370 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
5373 if(inet_aton(workBuffer, &inetaddr) > 0)
5375 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
5386 struct in6_addr inetaddr;
5387 /* If lpAddressLength is too small, tell caller the size we need */
5388 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
5390 *lpAddressLength = sizeof(SOCKADDR_IN6);
5394 #ifdef HAVE_INET_PTON
5395 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
5397 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
5399 /* This one is a bit tricky. An IPv6 address contains colons, so the
5400 * check from IPv4 doesn't work like that. However, IPv6 addresses that
5401 * contain a port are written with braces like [fd12:3456:7890::1]:12345
5402 * so what we will do is to look for ']', check if the next char is a
5403 * colon, and if it is, parse the port as in IPv4. */
5405 ptrPort = strchr(workBuffer, ']');
5406 if(ptrPort && *(++ptrPort) == ':')
5408 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort+1));
5413 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
5416 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
5418 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
5419 sizeof(struct in6_addr));
5423 #endif /* HAVE_INET_PTON */
5429 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
5430 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
5434 HeapFree(GetProcessHeap(), 0, workBuffer);
5437 WSASetLastError(res);
5438 return SOCKET_ERROR;
5441 /***********************************************************************
5442 * WSAStringToAddressW (WS2_32.81)
5444 * Does anybody know if this functions allows to use hebrew/arabic/chinese... digits?
5445 * If this should be the case, it would be required to map these digits
5446 * to Unicode digits (0-9) using FoldString first.
5448 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
5450 LPWSAPROTOCOL_INFOW lpProtocolInfo,
5451 LPSOCKADDR lpAddress,
5452 LPINT lpAddressLength)
5455 LPSTR workBuffer=NULL;
5456 WSAPROTOCOL_INFOA infoA;
5457 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
5459 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
5460 lpAddress, lpAddressLength );
5462 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
5464 /* if ProtocolInfo is available - convert to ANSI variant */
5467 lpProtoInfoA = &infoA;
5468 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
5470 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
5471 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
5473 WSASetLastError( WSAEINVAL);
5474 return SOCKET_ERROR;
5480 /* Translate AddressString to ANSI code page - assumes that only
5481 standard digits 0-9 are used with this API call */
5482 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
5483 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
5487 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
5488 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
5489 lpAddress,lpAddressLength);
5490 HeapFree( GetProcessHeap(), 0, workBuffer );
5494 res = WSA_NOT_ENOUGH_MEMORY;
5499 WSASetLastError(res);
5500 return SOCKET_ERROR;
5503 /***********************************************************************
5504 * WSAAddressToStringA (WS2_32.27)
5506 * See WSAAddressToStringW
5508 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
5509 LPWSAPROTOCOL_INFOA info, LPSTR string,
5513 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
5516 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
5518 if (!sockaddr) return SOCKET_ERROR;
5519 if (!string || !lenstr) return SOCKET_ERROR;
5521 switch(sockaddr->sa_family)
5524 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
5525 sprintf( buffer, "%u.%u.%u.%u:%u",
5526 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
5527 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
5528 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
5529 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
5530 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
5532 p = strchr( buffer, ':' );
5533 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
5538 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
5541 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
5542 if ((sockaddr6->sin6_port))
5543 strcpy(buffer, "[");
5544 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, buffer+strlen(buffer), sizeof(buffer)))
5546 WSASetLastError(WSAEINVAL);
5547 return SOCKET_ERROR;
5549 if ((sockaddr6->sin6_scope_id))
5550 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
5551 if ((sockaddr6->sin6_port))
5552 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
5557 WSASetLastError(WSAEINVAL);
5558 return SOCKET_ERROR;
5561 size = strlen( buffer ) + 1;
5566 WSASetLastError(WSAEFAULT);
5567 return SOCKET_ERROR;
5571 strcpy( string, buffer );
5575 /***********************************************************************
5576 * WSAAddressToStringW (WS2_32.28)
5578 * Convert a sockaddr address into a readable address string.
5581 * sockaddr [I] Pointer to a sockaddr structure.
5582 * len [I] Size of the sockaddr structure.
5583 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
5584 * string [I/O] Pointer to a buffer to receive the address string.
5585 * lenstr [I/O] Size of the receive buffer in WCHARs.
5589 * Failure: SOCKET_ERROR
5592 * The 'info' parameter is ignored.
5594 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
5595 LPWSAPROTOCOL_INFOW info, LPWSTR string,
5600 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
5603 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
5606 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
5608 if (ret) return ret;
5610 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
5615 WSASetLastError(WSAEFAULT);
5616 return SOCKET_ERROR;
5620 lstrcpyW( string, buffer );
5624 /***********************************************************************
5625 * WSAEnumNameSpaceProvidersA (WS2_32.34)
5627 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
5629 FIXME( "(%p %p) Stub!\n", len, buffer );
5633 /***********************************************************************
5634 * WSAEnumNameSpaceProvidersW (WS2_32.35)
5636 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
5638 FIXME( "(%p %p) Stub!\n", len, buffer );
5642 /***********************************************************************
5643 * WSAGetQOSByName (WS2_32.41)
5645 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
5647 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
5651 /***********************************************************************
5652 * WSAGetServiceClassInfoA (WS2_32.42)
5654 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
5655 LPWSASERVICECLASSINFOA info )
5657 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
5659 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5660 return SOCKET_ERROR;
5663 /***********************************************************************
5664 * WSAGetServiceClassInfoW (WS2_32.43)
5666 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
5667 LPWSASERVICECLASSINFOW info )
5669 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
5671 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5672 return SOCKET_ERROR;
5675 /***********************************************************************
5676 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
5678 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
5680 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
5681 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5682 return SOCKET_ERROR;
5685 /***********************************************************************
5686 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
5688 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
5690 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
5691 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5692 return SOCKET_ERROR;
5695 /***********************************************************************
5696 * WSALookupServiceBeginA (WS2_32.59)
5698 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
5699 DWORD dwControlFlags,
5702 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
5704 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5705 return SOCKET_ERROR;
5708 /***********************************************************************
5709 * WSALookupServiceBeginW (WS2_32.60)
5711 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
5712 DWORD dwControlFlags,
5715 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
5717 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5718 return SOCKET_ERROR;
5721 /***********************************************************************
5722 * WSALookupServiceBeginW (WS2_32.61)
5724 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
5726 FIXME("(%p) Stub!\n", lookup );
5730 /***********************************************************************
5731 * WSALookupServiceNextA (WS2_32.62)
5733 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
5735 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
5739 /***********************************************************************
5740 * WSALookupServiceNextW (WS2_32.63)
5742 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
5744 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
5748 /***********************************************************************
5749 * WSANtohl (WS2_32.64)
5751 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
5753 TRACE( "(0x%04lx 0x%08x %p)\n", s, netlong, lphostlong );
5755 if (!lphostlong) return WSAEFAULT;
5757 *lphostlong = ntohl( netlong );
5761 /***********************************************************************
5762 * WSANtohs (WS2_32.65)
5764 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
5766 TRACE( "(0x%04lx 0x%08x %p)\n", s, netshort, lphostshort );
5768 if (!lphostshort) return WSAEFAULT;
5770 *lphostshort = ntohs( netshort );
5774 /***********************************************************************
5775 * WSAProviderConfigChange (WS2_32.66)
5777 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
5778 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
5780 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
5781 return SOCKET_ERROR;
5784 /***********************************************************************
5785 * WSARecvDisconnect (WS2_32.68)
5787 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
5789 TRACE( "(0x%04lx %p)\n", s, disconnectdata );
5791 return WS_shutdown( s, 0 );
5794 /***********************************************************************
5795 * WSASetServiceA (WS2_32.76)
5797 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
5799 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
5803 /***********************************************************************
5804 * WSASetServiceW (WS2_32.77)
5806 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
5808 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
5812 /***********************************************************************
5813 * WSCEnableNSProvider (WS2_32.84)
5815 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
5817 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
5821 /***********************************************************************
5822 * WSCGetProviderPath (WS2_32.86)
5824 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
5826 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
5828 if (!errcode || !provider || !len) return WSAEFAULT;
5830 *errcode = WSAEINVAL;
5831 return SOCKET_ERROR;
5834 /***********************************************************************
5835 * WSCInstallNameSpace (WS2_32.87)
5837 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
5838 DWORD version, LPGUID provider )
5840 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
5841 namespace, version, debugstr_guid(provider) );
5845 /***********************************************************************
5846 * WSCUnInstallNameSpace (WS2_32.89)
5848 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
5850 FIXME("(%p) Stub!\n", lpProviderId);
5854 /***********************************************************************
5855 * WSCWriteProviderOrder (WS2_32.91)
5857 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
5859 FIXME("(%p 0x%08x) Stub!\n", entry, number);