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);
174 * The actual definition of WSASendTo/WSARecvFrom, wrapped in a different
175 * function name, so that internal calls from ws2_32 itself will not trigger
176 * programs like Garena, which hooks WSASendTo/WSARecvFrom calls.
178 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
179 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
180 const struct WS_sockaddr *to, int tolen,
181 LPWSAOVERLAPPED lpOverlapped,
182 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine );
184 static int WS2_recvfrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
185 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
186 struct WS_sockaddr *lpFrom,
187 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
188 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine );
190 /* critical section to protect some non-reentrant net function */
191 static CRITICAL_SECTION csWSgetXXXbyYYY;
192 static CRITICAL_SECTION_DEBUG critsect_debug =
194 0, 0, &csWSgetXXXbyYYY,
195 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
196 0, 0, { (DWORD_PTR)(__FILE__ ": csWSgetXXXbyYYY") }
198 static CRITICAL_SECTION csWSgetXXXbyYYY = { &critsect_debug, -1, 0, 0, 0, 0 };
200 union generic_unix_sockaddr
202 struct sockaddr addr;
203 char data[128]; /* should be big enough for all families */
206 static inline const char *debugstr_sockaddr( const struct WS_sockaddr *a )
208 if (!a) return "(nil)";
209 switch (a->sa_family)
212 return wine_dbg_sprintf("{ family AF_INET, address %s, port %d }",
213 inet_ntoa(((const struct sockaddr_in *)a)->sin_addr),
214 ntohs(((const struct sockaddr_in *)a)->sin_port));
219 struct WS_sockaddr_in6 *sin = (struct WS_sockaddr_in6 *)a;
221 p = WS_inet_ntop( WS_AF_INET6, &sin->sin6_addr, buf, sizeof(buf) );
223 p = "(unknown IPv6 address)";
224 return wine_dbg_sprintf("{ family AF_INET6, address %s, port %d }",
225 p, ntohs(sin->sin6_port));
231 memcpy( &addr, ((const SOCKADDR_IRDA *)a)->irdaDeviceID, sizeof(addr) );
232 addr = ntohl( addr );
233 return wine_dbg_sprintf("{ family AF_IRDA, addr %08x, name %s }",
235 ((const SOCKADDR_IRDA *)a)->irdaServiceName);
238 return wine_dbg_sprintf("{ family %d }", a->sa_family);
242 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
243 #define SOCKET2HANDLE(s) ((HANDLE)(s))
244 #define HANDLE2SOCKET(h) ((SOCKET)(h))
246 /****************************************************************
247 * Async IO declarations
248 ****************************************************************/
250 typedef struct ws2_async
254 LPWSAOVERLAPPED user_overlapped;
255 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
256 IO_STATUS_BLOCK local_iosb;
257 struct WS_sockaddr *addr;
260 int val; /* for send operations */
261 int *ptr; /* for recv operations */
264 unsigned int n_iovecs;
265 unsigned int first_iovec;
266 struct iovec iovec[1];
269 typedef struct ws2_accept_async
271 HANDLE listen_socket;
272 HANDLE accept_socket;
273 LPOVERLAPPED user_overlapped;
275 PVOID buf; /* buffer to write data to */
279 struct ws2_async *read;
282 /****************************************************************/
284 /* ----------------------------------- internal data */
286 /* ws_... struct conversion flags */
288 typedef struct /* WSAAsyncSelect() control struct */
290 HANDLE service, event, sock;
296 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
297 #define WS_MAX_UDP_DATAGRAM 1024
298 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
300 /* hostent's, servent's and protent's are stored in one buffer per thread,
301 * as documented on MSDN for the functions that return any of the buffers */
302 struct per_thread_data
305 struct WS_hostent *he_buffer;
306 struct WS_servent *se_buffer;
307 struct WS_protoent *pe_buffer;
313 /* internal: routing description information */
320 static INT num_startup; /* reference counter */
321 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
323 /* function prototypes */
324 static struct WS_hostent *WS_create_he(char *name, int aliases, int addresses, int fill_addresses);
325 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
326 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
327 static struct WS_servent *WS_dup_se(const struct servent* p_se);
329 int WSAIOCTL_GetInterfaceCount(void);
330 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
332 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus, ULONG Information );
334 #define MAP_OPTION(opt) { WS_##opt, opt }
336 static const int ws_sock_map[][2] =
338 MAP_OPTION( SO_DEBUG ),
339 MAP_OPTION( SO_ACCEPTCONN ),
340 MAP_OPTION( SO_REUSEADDR ),
341 MAP_OPTION( SO_KEEPALIVE ),
342 MAP_OPTION( SO_DONTROUTE ),
343 MAP_OPTION( SO_BROADCAST ),
344 MAP_OPTION( SO_LINGER ),
345 MAP_OPTION( SO_OOBINLINE ),
346 MAP_OPTION( SO_SNDBUF ),
347 MAP_OPTION( SO_RCVBUF ),
348 MAP_OPTION( SO_ERROR ),
349 MAP_OPTION( SO_TYPE ),
351 MAP_OPTION( SO_RCVTIMEO ),
354 MAP_OPTION( SO_SNDTIMEO ),
358 static const int ws_tcp_map[][2] =
361 MAP_OPTION( TCP_NODELAY ),
365 static const int ws_ip_map[][2] =
367 MAP_OPTION( IP_MULTICAST_IF ),
368 MAP_OPTION( IP_MULTICAST_TTL ),
369 MAP_OPTION( IP_MULTICAST_LOOP ),
370 MAP_OPTION( IP_ADD_MEMBERSHIP ),
371 MAP_OPTION( IP_DROP_MEMBERSHIP ),
372 MAP_OPTION( IP_OPTIONS ),
374 MAP_OPTION( IP_HDRINCL ),
376 MAP_OPTION( IP_TOS ),
377 MAP_OPTION( IP_TTL ),
380 static const int ws_ipv6_map[][2] =
382 #ifdef IPV6_ADD_MEMBERSHIP
383 MAP_OPTION( IPV6_ADD_MEMBERSHIP ),
385 #ifdef IPV6_DROP_MEMBERSHIP
386 MAP_OPTION( IPV6_DROP_MEMBERSHIP ),
388 MAP_OPTION( IPV6_MULTICAST_IF ),
389 MAP_OPTION( IPV6_MULTICAST_HOPS ),
390 MAP_OPTION( IPV6_MULTICAST_LOOP ),
391 MAP_OPTION( IPV6_UNICAST_HOPS ),
392 MAP_OPTION( IPV6_V6ONLY ),
395 static const int ws_af_map[][2] =
397 MAP_OPTION( AF_UNSPEC ),
398 MAP_OPTION( AF_INET ),
399 MAP_OPTION( AF_INET6 ),
401 MAP_OPTION( AF_IPX ),
404 MAP_OPTION( AF_IRDA ),
406 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
409 static const int ws_socktype_map[][2] =
411 MAP_OPTION( SOCK_DGRAM ),
412 MAP_OPTION( SOCK_STREAM ),
413 MAP_OPTION( SOCK_RAW ),
414 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
417 static const int ws_proto_map[][2] =
419 MAP_OPTION( IPPROTO_IP ),
420 MAP_OPTION( IPPROTO_TCP ),
421 MAP_OPTION( IPPROTO_UDP ),
422 MAP_OPTION( IPPROTO_ICMP ),
423 MAP_OPTION( IPPROTO_IGMP ),
424 MAP_OPTION( IPPROTO_RAW ),
425 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
428 static const int ws_aiflag_map[][2] =
430 MAP_OPTION( AI_PASSIVE ),
431 MAP_OPTION( AI_CANONNAME ),
432 MAP_OPTION( AI_NUMERICHOST ),
433 /* Linux/UNIX knows a lot more. But Windows only
434 * has 3 as far as I could see. -Marcus
438 static const int ws_niflag_map[][2] =
440 MAP_OPTION( NI_NOFQDN ),
441 MAP_OPTION( NI_NUMERICHOST ),
442 MAP_OPTION( NI_NAMEREQD ),
443 MAP_OPTION( NI_NUMERICSERV ),
444 MAP_OPTION( NI_DGRAM ),
447 static const int ws_eai_map[][2] =
449 MAP_OPTION( EAI_AGAIN ),
450 MAP_OPTION( EAI_BADFLAGS ),
451 MAP_OPTION( EAI_FAIL ),
452 MAP_OPTION( EAI_FAMILY ),
453 MAP_OPTION( EAI_MEMORY ),
454 /* Note: EAI_NODATA is deprecated, but still
455 * used by Windows and Linux... We map the newer
456 * EAI_NONAME to EAI_NODATA for now until Windows
460 MAP_OPTION( EAI_NODATA ),
463 { WS_EAI_NODATA, EAI_NONAME },
466 MAP_OPTION( EAI_SERVICE ),
467 MAP_OPTION( EAI_SOCKTYPE ),
471 static const char magic_loopback_addr[] = {127, 12, 34, 56};
473 /* ----------------------------------- error handling */
475 static NTSTATUS sock_get_ntstatus( int err )
479 case EBADF: return STATUS_INVALID_HANDLE;
480 case EBUSY: return STATUS_DEVICE_BUSY;
482 case EACCES: return STATUS_ACCESS_DENIED;
483 case EFAULT: return STATUS_NO_MEMORY;
484 case EINVAL: return STATUS_INVALID_PARAMETER;
486 case EMFILE: return STATUS_TOO_MANY_OPENED_FILES;
487 case EWOULDBLOCK: return STATUS_CANT_WAIT;
488 case EINPROGRESS: return STATUS_PENDING;
489 case EALREADY: return STATUS_NETWORK_BUSY;
490 case ENOTSOCK: return STATUS_OBJECT_TYPE_MISMATCH;
491 case EDESTADDRREQ: return STATUS_INVALID_PARAMETER;
492 case EMSGSIZE: return STATUS_BUFFER_OVERFLOW;
493 case EPROTONOSUPPORT:
494 case ESOCKTNOSUPPORT:
497 case EPROTOTYPE: return STATUS_NOT_SUPPORTED;
498 case ENOPROTOOPT: return STATUS_INVALID_PARAMETER;
499 case EOPNOTSUPP: return STATUS_NOT_SUPPORTED;
500 case EADDRINUSE: return STATUS_ADDRESS_ALREADY_ASSOCIATED;
501 case EADDRNOTAVAIL: return STATUS_INVALID_PARAMETER;
502 case ECONNREFUSED: return STATUS_CONNECTION_REFUSED;
503 case ESHUTDOWN: return STATUS_PIPE_DISCONNECTED;
504 case ENOTCONN: return STATUS_CONNECTION_DISCONNECTED;
505 case ETIMEDOUT: return STATUS_IO_TIMEOUT;
506 case ENETUNREACH: return STATUS_NETWORK_UNREACHABLE;
507 case ENETDOWN: return STATUS_NETWORK_BUSY;
509 case ECONNRESET: return STATUS_CONNECTION_RESET;
510 case ECONNABORTED: return STATUS_CONNECTION_ABORTED;
512 case 0: return STATUS_SUCCESS;
514 WARN("Unknown errno %d!\n", err);
515 return STATUS_UNSUCCESSFUL;
519 static UINT sock_get_error( int err )
523 case EINTR: return WSAEINTR;
524 case EBADF: return WSAEBADF;
526 case EACCES: return WSAEACCES;
527 case EFAULT: return WSAEFAULT;
528 case EINVAL: return WSAEINVAL;
529 case EMFILE: return WSAEMFILE;
530 case EWOULDBLOCK: return WSAEWOULDBLOCK;
531 case EINPROGRESS: return WSAEINPROGRESS;
532 case EALREADY: return WSAEALREADY;
533 case ENOTSOCK: return WSAENOTSOCK;
534 case EDESTADDRREQ: return WSAEDESTADDRREQ;
535 case EMSGSIZE: return WSAEMSGSIZE;
536 case EPROTOTYPE: return WSAEPROTOTYPE;
537 case ENOPROTOOPT: return WSAENOPROTOOPT;
538 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
539 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
540 case EOPNOTSUPP: return WSAEOPNOTSUPP;
541 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
542 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
543 case EADDRINUSE: return WSAEADDRINUSE;
544 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
545 case ENETDOWN: return WSAENETDOWN;
546 case ENETUNREACH: return WSAENETUNREACH;
547 case ENETRESET: return WSAENETRESET;
548 case ECONNABORTED: return WSAECONNABORTED;
550 case ECONNRESET: return WSAECONNRESET;
551 case ENOBUFS: return WSAENOBUFS;
552 case EISCONN: return WSAEISCONN;
553 case ENOTCONN: return WSAENOTCONN;
554 case ESHUTDOWN: return WSAESHUTDOWN;
555 case ETOOMANYREFS: return WSAETOOMANYREFS;
556 case ETIMEDOUT: return WSAETIMEDOUT;
557 case ECONNREFUSED: return WSAECONNREFUSED;
558 case ELOOP: return WSAELOOP;
559 case ENAMETOOLONG: return WSAENAMETOOLONG;
560 case EHOSTDOWN: return WSAEHOSTDOWN;
561 case EHOSTUNREACH: return WSAEHOSTUNREACH;
562 case ENOTEMPTY: return WSAENOTEMPTY;
564 case EPROCLIM: return WSAEPROCLIM;
567 case EUSERS: return WSAEUSERS;
570 case EDQUOT: return WSAEDQUOT;
573 case ESTALE: return WSAESTALE;
576 case EREMOTE: return WSAEREMOTE;
579 /* just in case we ever get here and there are no problems */
582 WARN("Unknown errno %d!\n", err);
583 return WSAEOPNOTSUPP;
587 static UINT wsaErrno(void)
589 int loc_errno = errno;
590 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
592 return sock_get_error( loc_errno );
595 /* most ws2 overlapped functions return an ntstatus-based error code */
596 static NTSTATUS wsaErrStatus(void)
598 int loc_errno = errno;
599 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
601 return sock_get_ntstatus(loc_errno);
604 static UINT wsaHerrno(int loc_errno)
606 WARN("h_errno %d.\n", loc_errno);
610 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
611 case TRY_AGAIN: return WSATRY_AGAIN;
612 case NO_RECOVERY: return WSANO_RECOVERY;
613 case NO_DATA: return WSANO_DATA;
614 case ENOBUFS: return WSAENOBUFS;
618 WARN("Unknown h_errno %d!\n", loc_errno);
619 return WSAEOPNOTSUPP;
623 static inline DWORD NtStatusToWSAError( const DWORD status )
625 /* We only need to cover the status codes set by server async request handling */
629 case STATUS_SUCCESS: wserr = 0; break;
630 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
631 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
632 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
633 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
634 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
635 case STATUS_NETWORK_BUSY: wserr = WSAEALREADY; break;
636 case STATUS_NETWORK_UNREACHABLE: wserr = WSAENETUNREACH; break;
637 case STATUS_CONNECTION_REFUSED: wserr = WSAECONNREFUSED; break;
638 case STATUS_CONNECTION_DISCONNECTED: wserr = WSAENOTCONN; break;
639 case STATUS_CONNECTION_RESET: wserr = WSAECONNRESET; break;
640 case STATUS_CONNECTION_ABORTED: wserr = WSAECONNABORTED; break;
641 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
642 case STATUS_ADDRESS_ALREADY_ASSOCIATED: wserr = WSAEADDRINUSE; break;
643 case STATUS_IO_TIMEOUT:
644 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
645 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
646 case STATUS_ACCESS_DENIED: wserr = WSAEACCES; break;
647 case STATUS_TOO_MANY_OPENED_FILES: wserr = WSAEMFILE; break;
648 case STATUS_CANT_WAIT: wserr = WSAEWOULDBLOCK; break;
649 case STATUS_BUFFER_OVERFLOW: wserr = WSAEMSGSIZE; break;
650 case STATUS_NOT_SUPPORTED: wserr = WSAEOPNOTSUPP; break;
651 case STATUS_HOST_UNREACHABLE: wserr = WSAEHOSTUNREACH; break;
654 wserr = RtlNtStatusToDosError( status );
655 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
660 /* set last error code from NT status without mapping WSA errors */
661 static inline unsigned int set_error( unsigned int err )
665 err = NtStatusToWSAError( err );
671 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
674 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
679 static inline void release_sock_fd( SOCKET s, int fd )
681 wine_server_release_fd( SOCKET2HANDLE(s), fd );
684 static void _enable_event( HANDLE s, unsigned int event,
685 unsigned int sstate, unsigned int cstate )
687 SERVER_START_REQ( enable_socket_event )
689 req->handle = wine_server_obj_handle( s );
691 req->sstate = sstate;
692 req->cstate = cstate;
693 wine_server_call( req );
698 static int _is_blocking(SOCKET s)
701 SERVER_START_REQ( get_socket_event )
703 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
704 req->service = FALSE;
706 wine_server_call( req );
707 ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
713 static unsigned int _get_sock_mask(SOCKET s)
716 SERVER_START_REQ( get_socket_event )
718 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
719 req->service = FALSE;
721 wine_server_call( req );
728 static void _sync_sock_state(SOCKET s)
730 /* do a dummy wineserver request in order to let
731 the wineserver run through its select loop once */
732 (void)_is_blocking(s);
735 static int _get_sock_error(SOCKET s, unsigned int bit)
737 int events[FD_MAX_EVENTS];
739 SERVER_START_REQ( get_socket_event )
741 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
742 req->service = FALSE;
744 wine_server_set_reply( req, events, sizeof(events) );
745 wine_server_call( req );
751 static struct per_thread_data *get_per_thread_data(void)
753 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
754 /* lazy initialization */
757 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
758 NtCurrentTeb()->WinSockData = ptb;
763 static void free_per_thread_data(void)
765 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
769 /* delete scratch buffers */
770 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
771 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
772 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
773 ptb->he_buffer = NULL;
774 ptb->se_buffer = NULL;
775 ptb->pe_buffer = NULL;
777 HeapFree( GetProcessHeap(), 0, ptb );
778 NtCurrentTeb()->WinSockData = NULL;
781 /***********************************************************************
782 * DllMain (WS2_32.init)
784 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
786 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
788 case DLL_PROCESS_ATTACH:
790 case DLL_PROCESS_DETACH:
791 free_per_thread_data();
794 case DLL_THREAD_DETACH:
795 free_per_thread_data();
801 /***********************************************************************
804 * Converts socket flags from Windows format.
805 * Return 1 if converted, 0 if not (error).
807 static int convert_sockopt(INT *level, INT *optname)
814 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
815 if( ws_sock_map[i][0] == *optname )
817 *optname = ws_sock_map[i][1];
821 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
824 *level = IPPROTO_TCP;
825 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
826 if ( ws_tcp_map[i][0] == *optname )
828 *optname = ws_tcp_map[i][1];
832 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
836 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
837 if (ws_ip_map[i][0] == *optname )
839 *optname = ws_ip_map[i][1];
843 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
845 case WS_IPPROTO_IPV6:
846 *level = IPPROTO_IPV6;
847 for(i=0; i<sizeof(ws_ipv6_map)/sizeof(ws_ipv6_map[0]); i++) {
848 if (ws_ipv6_map[i][0] == *optname )
850 *optname = ws_ipv6_map[i][1];
854 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname);
856 default: FIXME("Unimplemented or unknown socket level\n");
861 /* ----------------------------------- Per-thread info (or per-process?) */
863 static char *strdup_lower(const char *str)
866 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
870 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
873 else SetLastError(WSAENOBUFS);
877 static inline int sock_error_p(int s)
879 unsigned int optval, optlen;
881 optlen = sizeof(optval);
882 getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
883 if (optval) WARN("\t[%i] error: %d\n", s, optval);
887 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
888 * from an fd and return the value converted to milli seconds
889 * or -1 if there is an infinite time out */
890 static inline int get_rcvsnd_timeo( int fd, int optname)
893 unsigned int len = sizeof(tv);
894 int ret = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
896 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
897 if( ret <= 0 ) /* tv == {0,0} means infinite time out */
902 /* macro wrappers for portability */
904 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
906 #define GET_RCVTIMEO(fd) (-1)
910 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
912 #define GET_SNDTIMEO(fd) (-1)
915 /* utility: given an fd, will block until one of the events occurs */
916 static inline int do_block( int fd, int events, int timeout )
924 while ((ret = poll(&pfd, 1, timeout)) < 0)
935 convert_af_w2u(int windowsaf) {
938 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
939 if (ws_af_map[i][0] == windowsaf)
940 return ws_af_map[i][1];
941 FIXME("unhandled Windows address family %d\n", windowsaf);
946 convert_af_u2w(int unixaf) {
949 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
950 if (ws_af_map[i][1] == unixaf)
951 return ws_af_map[i][0];
952 FIXME("unhandled UNIX address family %d\n", unixaf);
957 convert_proto_w2u(int windowsproto) {
960 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
961 if (ws_proto_map[i][0] == windowsproto)
962 return ws_proto_map[i][1];
963 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
968 convert_proto_u2w(int unixproto) {
971 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
972 if (ws_proto_map[i][1] == unixproto)
973 return ws_proto_map[i][0];
974 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
979 convert_socktype_w2u(int windowssocktype) {
982 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
983 if (ws_socktype_map[i][0] == windowssocktype)
984 return ws_socktype_map[i][1];
985 FIXME("unhandled Windows socket type %d\n", windowssocktype);
990 convert_socktype_u2w(int unixsocktype) {
993 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
994 if (ws_socktype_map[i][1] == unixsocktype)
995 return ws_socktype_map[i][0];
996 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
1000 /* ----------------------------------- API -----
1002 * Init / cleanup / error checking.
1005 /***********************************************************************
1006 * WSAStartup (WS2_32.115)
1008 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
1010 TRACE("verReq=%x\n", wVersionRequested);
1012 if (LOBYTE(wVersionRequested) < 1)
1013 return WSAVERNOTSUPPORTED;
1015 if (!lpWSAData) return WSAEINVAL;
1019 /* that's the whole of the negotiation for now */
1020 lpWSAData->wVersion = wVersionRequested;
1021 /* return winsock information */
1022 lpWSAData->wHighVersion = 0x0202;
1023 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
1024 strcpy(lpWSAData->szSystemStatus, "Running" );
1025 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
1026 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
1027 /* don't do anything with lpWSAData->lpVendorInfo */
1028 /* (some apps don't allocate the space for this field) */
1030 TRACE("succeeded\n");
1035 /***********************************************************************
1036 * WSACleanup (WS2_32.116)
1038 INT WINAPI WSACleanup(void)
1044 SetLastError(WSANOTINITIALISED);
1045 return SOCKET_ERROR;
1049 /***********************************************************************
1050 * WSAGetLastError (WS2_32.111)
1052 INT WINAPI WSAGetLastError(void)
1054 return GetLastError();
1057 /***********************************************************************
1058 * WSASetLastError (WS2_32.112)
1060 void WINAPI WSASetLastError(INT iError) {
1061 SetLastError(iError);
1064 static struct WS_hostent *check_buffer_he(int size)
1066 struct per_thread_data * ptb = get_per_thread_data();
1069 if (ptb->he_len >= size ) return ptb->he_buffer;
1070 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1072 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
1073 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
1074 return ptb->he_buffer;
1077 static struct WS_servent *check_buffer_se(int size)
1079 struct per_thread_data * ptb = get_per_thread_data();
1082 if (ptb->se_len >= size ) return ptb->se_buffer;
1083 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1085 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
1086 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
1087 return ptb->se_buffer;
1090 static struct WS_protoent *check_buffer_pe(int size)
1092 struct per_thread_data * ptb = get_per_thread_data();
1095 if (ptb->pe_len >= size ) return ptb->pe_buffer;
1096 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1098 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
1099 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
1100 return ptb->pe_buffer;
1103 /* ----------------------------------- i/o APIs */
1105 static inline BOOL supported_pf(int pf)
1126 /**********************************************************************/
1128 /* Returns the length of the converted address if successful, 0 if it was too small to
1131 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
1132 union generic_unix_sockaddr *uaddr)
1134 unsigned int uaddrlen = 0;
1136 switch (wsaddr->sa_family)
1141 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
1142 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
1144 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
1147 uaddrlen = sizeof(struct sockaddr_ipx);
1148 memset( uaddr, 0, uaddrlen );
1149 uipx->sipx_family=AF_IPX;
1150 uipx->sipx_port=wsipx->sa_socket;
1151 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1154 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
1155 #ifdef IPX_FRAME_NONE
1156 uipx->sipx_type=IPX_FRAME_NONE;
1162 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
1163 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
1165 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1166 * scope_id, one without.
1168 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
1169 uaddrlen = sizeof(struct sockaddr_in6);
1170 memset( uaddr, 0, uaddrlen );
1171 uin6->sin6_family = AF_INET6;
1172 uin6->sin6_port = win6->sin6_port;
1173 uin6->sin6_flowinfo = win6->sin6_flowinfo;
1174 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1175 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
1177 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
1180 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
1184 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
1185 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
1187 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
1189 uaddrlen = sizeof(struct sockaddr_in);
1190 memset( uaddr, 0, uaddrlen );
1191 uin->sin_family = AF_INET;
1192 uin->sin_port = win->sin_port;
1193 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
1198 struct sockaddr_irda *uin = (struct sockaddr_irda *)uaddr;
1199 const SOCKADDR_IRDA *win = (const SOCKADDR_IRDA *)wsaddr;
1201 if (wsaddrlen < sizeof(SOCKADDR_IRDA))
1203 uaddrlen = sizeof(struct sockaddr_irda);
1204 memset( uaddr, 0, uaddrlen );
1205 uin->sir_family = AF_IRDA;
1206 if (!strncmp( win->irdaServiceName, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1208 unsigned int lsap_sel = 0;
1210 sscanf( win->irdaServiceName, "LSAP-SEL%u", &lsap_sel );
1211 uin->sir_lsap_sel = lsap_sel;
1215 uin->sir_lsap_sel = LSAP_ANY;
1216 memcpy( uin->sir_name, win->irdaServiceName, 25 );
1218 memcpy( &uin->sir_addr, win->irdaDeviceID, sizeof(uin->sir_addr) );
1222 case WS_AF_UNSPEC: {
1223 /* Try to determine the needed space by the passed windows sockaddr space */
1224 switch (wsaddrlen) {
1225 default: /* likely a ipv4 address */
1226 case sizeof(struct WS_sockaddr_in):
1227 uaddrlen = sizeof(struct sockaddr_in);
1230 case sizeof(struct WS_sockaddr_ipx):
1231 uaddrlen = sizeof(struct sockaddr_ipx);
1235 case sizeof(SOCKADDR_IRDA):
1236 uaddrlen = sizeof(struct sockaddr_irda);
1239 case sizeof(struct WS_sockaddr_in6):
1240 case sizeof(struct WS_sockaddr_in6_old):
1241 uaddrlen = sizeof(struct sockaddr_in6);
1244 memset( uaddr, 0, uaddrlen );
1248 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
1254 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
1256 switch (uaddr->sa_family)
1260 FIXME("don't know how to tell if IPX socket is bound, assuming it is!\n");
1265 static const struct sockaddr_in6 emptyAddr;
1266 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
1267 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
1271 static const struct sockaddr_in emptyAddr;
1272 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
1273 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
1278 FIXME("unknown address family %d\n", uaddr->sa_family);
1283 /* Returns 0 if successful, -1 if the buffer is too small */
1284 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
1288 switch(uaddr->sa_family)
1293 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
1294 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
1297 switch (*wsaddrlen) /* how much can we copy? */
1301 *wsaddrlen = sizeof(*wsipx);
1302 wsipx->sa_socket=uipx->sipx_port;
1306 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
1314 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1320 wsipx->sa_family=WS_AF_IPX;
1332 const struct sockaddr_irda *uin = (const struct sockaddr_irda *)uaddr;
1333 SOCKADDR_IRDA *win = (SOCKADDR_IRDA *)wsaddr;
1335 if (*wsaddrlen < sizeof(SOCKADDR_IRDA))
1337 win->irdaAddressFamily = WS_AF_IRDA;
1338 memcpy( win->irdaDeviceID, &uin->sir_addr, sizeof(win->irdaDeviceID) );
1339 if (uin->sir_lsap_sel != LSAP_ANY)
1340 sprintf( win->irdaServiceName, "LSAP-SEL%u", uin->sir_lsap_sel );
1342 memcpy( win->irdaServiceName, uin->sir_name,
1343 sizeof(win->irdaServiceName) );
1348 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1349 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1351 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1353 win6old->sin6_family = WS_AF_INET6;
1354 win6old->sin6_port = uin6->sin6_port;
1355 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1356 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1357 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1358 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1359 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1360 win6->sin6_scope_id = uin6->sin6_scope_id;
1361 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1364 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1366 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1371 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1372 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1374 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1376 win->sin_family = WS_AF_INET;
1377 win->sin_port = uin->sin_port;
1378 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1379 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1380 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1384 memset(wsaddr,0,*wsaddrlen);
1388 FIXME("Unknown address family %d\n", uaddr->sa_family);
1394 /**************************************************************************
1395 * Functions for handling overlapped I/O
1396 **************************************************************************/
1398 /* user APC called upon async completion */
1399 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1401 ws2_async *wsa = arg;
1403 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
1404 iosb->Information, wsa->user_overlapped,
1406 HeapFree( GetProcessHeap(), 0, wsa );
1409 /***********************************************************************
1410 * WS2_recv (INTERNAL)
1412 * Workhorse for both synchronous and asynchronous recv() operations.
1414 static int WS2_recv( int fd, struct ws2_async *wsa )
1417 union generic_unix_sockaddr unix_sockaddr;
1420 hdr.msg_name = NULL;
1424 hdr.msg_namelen = sizeof(unix_sockaddr);
1425 hdr.msg_name = &unix_sockaddr;
1428 hdr.msg_namelen = 0;
1430 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1431 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1432 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1433 hdr.msg_accrights = NULL;
1434 hdr.msg_accrightslen = 0;
1436 hdr.msg_control = NULL;
1437 hdr.msg_controllen = 0;
1441 if ( (n = recvmsg(fd, &hdr, wsa->flags)) == -1 )
1444 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
1445 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
1447 * quoting linux 2.6 net/ipv4/tcp.c:
1448 * "According to UNIX98, msg_name/msg_namelen are ignored
1449 * on connected socket. I was just happy when found this 8) --ANK"
1451 * likewise MSDN says that lpFrom and lpFromlen are ignored for
1452 * connection-oriented sockets, so don't try to update lpFrom.
1454 if (wsa->addr && hdr.msg_namelen)
1455 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
1460 /***********************************************************************
1461 * WS2_async_recv (INTERNAL)
1463 * Handler for overlapped recv() operations.
1465 static NTSTATUS WS2_async_recv( void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1467 ws2_async* wsa = user;
1472 case STATUS_ALERTED:
1473 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
1476 result = WS2_recv( fd, wsa );
1477 wine_server_release_fd( wsa->hSocket, fd );
1480 status = STATUS_SUCCESS;
1481 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1485 if (errno == EINTR || errno == EAGAIN)
1487 status = STATUS_PENDING;
1488 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1493 status = wsaErrStatus();
1498 if (status != STATUS_PENDING)
1500 iosb->u.Status = status;
1501 iosb->Information = result;
1502 *apc = ws2_async_apc;
1507 /* user APC called upon async accept completion */
1508 static void WINAPI ws2_async_accept_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1510 struct ws2_accept_async *wsa = arg;
1512 HeapFree( GetProcessHeap(), 0, wsa->read );
1513 HeapFree( GetProcessHeap(), 0, wsa );
1516 /***********************************************************************
1517 * WS2_async_accept_recv (INTERNAL)
1519 * This function is used to finish the read part of an accept request. It is
1520 * needed to place the completion on the correct socket (listener).
1522 static NTSTATUS WS2_async_accept_recv( void *arg, IO_STATUS_BLOCK *iosb, NTSTATUS status, void **apc )
1525 struct ws2_accept_async *wsa = arg;
1527 status = WS2_async_recv( wsa->read, iosb, status, &junk );
1528 if (status == STATUS_PENDING)
1531 if (wsa->user_overlapped->hEvent)
1532 SetEvent(wsa->user_overlapped->hEvent);
1534 WS_AddCompletion( HANDLE2SOCKET(wsa->listen_socket), wsa->cvalue, iosb->u.Status, iosb->Information );
1536 *apc = ws2_async_accept_apc;
1540 /***********************************************************************
1541 * WS2_async_accept (INTERNAL)
1543 * This is the function called to satisfy the AcceptEx callback
1545 static NTSTATUS WS2_async_accept( void *arg, IO_STATUS_BLOCK *iosb, NTSTATUS status, void **apc )
1547 struct ws2_accept_async *wsa = arg;
1551 TRACE("status: 0x%x listen: %p, accept: %p\n", status, wsa->listen_socket, wsa->accept_socket);
1553 if (status == STATUS_ALERTED)
1555 SERVER_START_REQ( accept_into_socket )
1557 req->lhandle = wine_server_obj_handle( wsa->listen_socket );
1558 req->ahandle = wine_server_obj_handle( wsa->accept_socket );
1559 status = wine_server_call( req );
1563 if (status == STATUS_CANT_WAIT)
1564 return STATUS_PENDING;
1566 if (status == STATUS_INVALID_HANDLE)
1568 FIXME("AcceptEx accepting socket closed but request was not cancelled");
1569 status = STATUS_CANCELLED;
1572 else if (status == STATUS_HANDLES_CLOSED)
1573 status = STATUS_CANCELLED; /* strange windows behavior */
1575 if (status != STATUS_SUCCESS)
1578 /* WS2 Spec says size param is extra 16 bytes long...what do we put in it? */
1579 addr = ((char *)wsa->buf) + wsa->data_len;
1580 len = wsa->local_len - sizeof(int);
1581 WS_getpeername(HANDLE2SOCKET(wsa->accept_socket),
1582 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
1585 addr += wsa->local_len;
1586 len = wsa->remote_len - sizeof(int);
1587 WS_getsockname(HANDLE2SOCKET(wsa->accept_socket),
1588 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
1594 SERVER_START_REQ( register_async )
1596 req->type = ASYNC_TYPE_READ;
1597 req->async.handle = wine_server_obj_handle( wsa->accept_socket );
1598 req->async.callback = wine_server_client_ptr( WS2_async_accept_recv );
1599 req->async.iosb = wine_server_client_ptr( iosb );
1600 req->async.arg = wine_server_client_ptr( wsa );
1601 status = wine_server_call( req );
1605 if (status != STATUS_PENDING)
1608 return STATUS_SUCCESS;
1611 iosb->u.Status = status;
1612 iosb->Information = 0;
1614 if (wsa->user_overlapped->hEvent)
1615 SetEvent(wsa->user_overlapped->hEvent);
1617 WS_AddCompletion( HANDLE2SOCKET(wsa->listen_socket), wsa->cvalue, iosb->u.Status, iosb->Information );
1619 *apc = ws2_async_accept_apc;
1623 /***********************************************************************
1624 * WS2_send (INTERNAL)
1626 * Workhorse for both synchronous and asynchronous send() operations.
1628 static int WS2_send( int fd, struct ws2_async *wsa )
1631 union generic_unix_sockaddr unix_addr;
1633 hdr.msg_name = NULL;
1634 hdr.msg_namelen = 0;
1638 hdr.msg_name = &unix_addr;
1639 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
1640 if ( !hdr.msg_namelen )
1646 #if defined(HAVE_IPX) && defined(SOL_IPX)
1647 if(wsa->addr->sa_family == WS_AF_IPX)
1649 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
1651 unsigned int len=sizeof(int);
1653 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
1654 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
1655 * the packet type and then we can retrieve it using getsockopt. After that we can set the
1656 * ipx type in the sockaddr_opx structure with the stored value.
1658 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
1659 uipx->sipx_type = val;
1664 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1665 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1666 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1667 hdr.msg_accrights = NULL;
1668 hdr.msg_accrightslen = 0;
1670 hdr.msg_control = NULL;
1671 hdr.msg_controllen = 0;
1675 return sendmsg(fd, &hdr, wsa->flags);
1678 /***********************************************************************
1679 * WS2_async_send (INTERNAL)
1681 * Handler for overlapped send() operations.
1683 static NTSTATUS WS2_async_send(void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1685 ws2_async* wsa = user;
1690 case STATUS_ALERTED:
1691 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
1694 /* check to see if the data is ready (non-blocking) */
1695 result = WS2_send( fd, wsa );
1696 wine_server_release_fd( wsa->hSocket, fd );
1700 int totalLength = 0;
1702 status = STATUS_SUCCESS;
1703 for (i = 0; i < wsa->n_iovecs; i++)
1704 totalLength += wsa->iovec[i].iov_len;
1705 if (result < totalLength)
1706 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1710 if (errno == EINTR || errno == EAGAIN)
1712 status = STATUS_PENDING;
1713 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1717 status = wsaErrStatus();
1723 if (status != STATUS_PENDING)
1725 iosb->u.Status = status;
1726 iosb->Information = result;
1727 *apc = ws2_async_apc;
1732 /***********************************************************************
1733 * WS2_async_shutdown (INTERNAL)
1735 * Handler for shutdown() operations on overlapped sockets.
1737 static NTSTATUS WS2_async_shutdown( void* user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc )
1739 ws2_async* wsa = user;
1744 case STATUS_ALERTED:
1745 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
1748 switch ( wsa->type )
1750 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
1751 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
1753 status = err ? wsaErrStatus() : STATUS_SUCCESS;
1754 wine_server_release_fd( wsa->hSocket, fd );
1757 iosb->u.Status = status;
1758 iosb->Information = 0;
1759 *apc = ws2_async_apc;
1763 /***********************************************************************
1764 * WS2_register_async_shutdown (INTERNAL)
1766 * Helper function for WS_shutdown() on overlapped sockets.
1768 static int WS2_register_async_shutdown( SOCKET s, int type )
1770 struct ws2_async *wsa;
1773 TRACE("s %ld type %d\n", s, type);
1775 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
1779 wsa->hSocket = SOCKET2HANDLE(s);
1781 wsa->completion_func = NULL;
1783 SERVER_START_REQ( register_async )
1786 req->async.handle = wine_server_obj_handle( wsa->hSocket );
1787 req->async.callback = wine_server_client_ptr( WS2_async_shutdown );
1788 req->async.iosb = wine_server_client_ptr( &wsa->local_iosb );
1789 req->async.arg = wine_server_client_ptr( wsa );
1790 req->async.cvalue = 0;
1791 status = wine_server_call( req );
1795 if (status != STATUS_PENDING)
1797 HeapFree( GetProcessHeap(), 0, wsa );
1798 return NtStatusToWSAError( status );
1803 /***********************************************************************
1806 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr,
1813 TRACE("socket %04lx\n", s );
1814 is_blocking = _is_blocking(s);
1817 /* try accepting first (if there is a deferred connection) */
1818 SERVER_START_REQ( accept_socket )
1820 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1821 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
1822 req->attributes = OBJ_INHERIT;
1823 status = wine_server_call( req );
1824 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
1829 if (addr) WS_getpeername(as, addr, addrlen32);
1832 if (is_blocking && status == STATUS_CANT_WAIT)
1834 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1836 do_block(fd, POLLIN, -1);
1837 _sync_sock_state(s); /* let wineserver notice connection */
1838 release_sock_fd( s, fd );
1840 } while (is_blocking && status == STATUS_CANT_WAIT);
1843 return INVALID_SOCKET;
1846 /***********************************************************************
1849 BOOL WINAPI WS2_AcceptEx(SOCKET listener, SOCKET acceptor, PVOID dest, DWORD dest_len,
1850 DWORD local_addr_len, DWORD rem_addr_len, LPDWORD received,
1851 LPOVERLAPPED overlapped)
1854 struct ws2_accept_async *wsa;
1856 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
1858 TRACE("(%lx, %lx, %p, %d, %d, %d, %p, %p)\n", listener, acceptor, dest, dest_len, local_addr_len,
1859 rem_addr_len, received, overlapped);
1863 SetLastError(WSAEINVAL);
1869 SetLastError(WSA_INVALID_PARAMETER);
1873 fd = get_sock_fd( listener, FILE_READ_DATA, NULL );
1876 SetLastError(WSAENOTSOCK);
1879 release_sock_fd( listener, fd );
1881 fd = get_sock_fd( acceptor, FILE_READ_DATA, NULL );
1884 SetLastError(WSAEINVAL);
1887 release_sock_fd( acceptor, fd );
1889 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
1892 SetLastError(WSAEFAULT);
1896 wsa->listen_socket = SOCKET2HANDLE(listener);
1897 wsa->accept_socket = SOCKET2HANDLE(acceptor);
1898 wsa->user_overlapped = overlapped;
1899 wsa->cvalue = cvalue;
1901 wsa->data_len = dest_len;
1902 wsa->local_len = local_addr_len;
1903 wsa->remote_len = rem_addr_len;
1908 /* set up a read request if we need it */
1909 wsa->read = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[1]) );
1912 HeapFree( GetProcessHeap(), 0, wsa );
1913 SetLastError(WSAEFAULT);
1917 wsa->read->hSocket = wsa->accept_socket;
1918 wsa->read->flags = 0;
1919 wsa->read->addr = NULL;
1920 wsa->read->addrlen.ptr = NULL;
1921 wsa->read->n_iovecs = 1;
1922 wsa->read->first_iovec = 0;
1923 wsa->read->iovec[0].iov_base = wsa->buf;
1924 wsa->read->iovec[0].iov_len = wsa->data_len;
1927 SERVER_START_REQ( register_async )
1929 req->type = ASYNC_TYPE_READ;
1930 req->async.handle = wine_server_obj_handle( SOCKET2HANDLE(listener) );
1931 req->async.callback = wine_server_client_ptr( WS2_async_accept );
1932 req->async.iosb = wine_server_client_ptr( overlapped );
1933 req->async.arg = wine_server_client_ptr( wsa );
1934 /* We don't set event or completion since we may also have to read */
1935 status = wine_server_call( req );
1939 if(status != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
1941 SetLastError( NtStatusToWSAError(status) );
1945 /***********************************************************************
1946 * GetAcceptExSockaddrs
1948 void WINAPI WS2_GetAcceptExSockaddrs(PVOID buffer, DWORD data_size, DWORD local_size, DWORD remote_size,
1949 struct WS_sockaddr **local_addr, LPINT local_addr_len,
1950 struct WS_sockaddr **remote_addr, LPINT remote_addr_len)
1952 char *cbuf = buffer;
1953 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer, data_size, local_size, remote_size, local_addr,
1954 local_addr_len, remote_addr, remote_addr_len );
1957 *local_addr_len = *(int *) cbuf;
1958 *local_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
1962 *remote_addr_len = *(int *) cbuf;
1963 *remote_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
1966 /***********************************************************************
1969 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
1971 int fd = get_sock_fd( s, 0, NULL );
1972 int res = SOCKET_ERROR;
1974 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1978 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
1980 SetLastError(WSAEAFNOSUPPORT);
1984 union generic_unix_sockaddr uaddr;
1985 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1988 SetLastError(WSAEFAULT);
1993 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
1994 if (name->sa_family == WS_AF_INET6 &&
1995 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
1998 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
2000 release_sock_fd( s, fd );
2001 SetLastError(WSAEAFNOSUPPORT);
2002 return SOCKET_ERROR;
2006 if (name->sa_family == WS_AF_INET)
2008 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2009 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2011 /* Trying to bind to the default host interface, using
2012 * INADDR_ANY instead*/
2013 WARN("Trying to bind to magic IP address, using "
2014 "INADDR_ANY instead.\n");
2015 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
2018 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
2020 int loc_errno = errno;
2021 WARN("\tfailure - errno = %i\n", errno);
2026 SetLastError(WSAENOTSOCK);
2029 SetLastError(WSAEINVAL);
2032 SetLastError(wsaErrno());
2038 res=0; /* success */
2042 release_sock_fd( s, fd );
2047 /***********************************************************************
2048 * closesocket (WS2_32.3)
2050 int WINAPI WS_closesocket(SOCKET s)
2052 TRACE("socket %04lx\n", s);
2053 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
2054 return SOCKET_ERROR;
2057 static int do_connect(int fd, const struct WS_sockaddr* name, int namelen)
2059 union generic_unix_sockaddr uaddr;
2060 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2065 if (name->sa_family == WS_AF_INET)
2067 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2068 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2070 /* Trying to connect to magic replace-loopback address,
2071 * assuming we really want to connect to localhost */
2072 TRACE("Trying to connect to magic IP address, using "
2073 "INADDR_LOOPBACK instead.\n");
2074 in4->sin_addr.s_addr = htonl(WS_INADDR_LOOPBACK);
2078 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
2084 /***********************************************************************
2085 * connect (WS2_32.4)
2087 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
2089 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2091 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2095 int ret = do_connect(fd, name, namelen);
2097 goto connect_success;
2099 if (ret == WSAEINPROGRESS)
2101 /* tell wineserver that a connection is in progress */
2102 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2104 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2105 if (_is_blocking(s))
2109 do_block(fd, POLLIN | POLLOUT, -1);
2110 _sync_sock_state(s); /* let wineserver notice connection */
2111 /* retrieve any error codes from it */
2112 result = _get_sock_error(s, FD_CONNECT_BIT);
2114 SetLastError(NtStatusToWSAError(result));
2117 goto connect_success;
2122 SetLastError(WSAEWOULDBLOCK);
2129 release_sock_fd( s, fd );
2131 return SOCKET_ERROR;
2134 release_sock_fd( s, fd );
2135 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2136 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2137 FD_CONNECT|FD_WINE_LISTENING);
2141 /***********************************************************************
2142 * WSAConnect (WS2_32.30)
2144 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
2145 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
2146 LPQOS lpSQOS, LPQOS lpGQOS )
2148 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
2149 FIXME("unsupported parameters!\n");
2150 return WS_connect( s, name, namelen );
2153 /***********************************************************************
2156 static BOOL WINAPI WS2_ConnectEx(SOCKET s, const struct WS_sockaddr* name, int namelen,
2157 PVOID sendBuf, DWORD sendBufLen, LPDWORD sent, LPOVERLAPPED ov)
2159 int fd, ret, status;
2163 SetLastError( ERROR_INVALID_PARAMETER );
2167 fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2170 SetLastError( WSAENOTSOCK );
2174 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
2175 s, name, debugstr_sockaddr(name), namelen, sendBuf, sendBufLen, ov);
2177 /* FIXME: technically the socket has to be bound */
2178 ret = do_connect(fd, name, namelen);
2183 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2184 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2185 FD_CONNECT|FD_WINE_LISTENING);
2187 wsabuf.len = sendBufLen;
2188 wsabuf.buf = (char*) sendBuf;
2190 /* WSASend takes care of completion if need be */
2191 if (WSASend(s, &wsabuf, sendBuf ? 1 : 0, sent, 0, ov, NULL) != SOCKET_ERROR)
2192 goto connection_success;
2194 else if (ret == WSAEINPROGRESS)
2196 struct ws2_async *wsa;
2197 ULONG_PTR cvalue = (((ULONG_PTR)ov->hEvent & 1) == 0) ? (ULONG_PTR)ov : 0;
2199 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2201 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2203 /* Indirectly call WSASend */
2204 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) )))
2206 SetLastError(WSAEFAULT);
2210 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)ov;
2211 iosb->u.Status = STATUS_PENDING;
2212 iosb->Information = 0;
2214 wsa->hSocket = SOCKET2HANDLE(s);
2216 wsa->addrlen.val = 0;
2218 wsa->n_iovecs = sendBuf ? 1 : 0;
2219 wsa->first_iovec = 0;
2220 wsa->completion_func = NULL;
2221 wsa->iovec[0].iov_base = sendBuf;
2222 wsa->iovec[0].iov_len = sendBufLen;
2224 SERVER_START_REQ( register_async )
2226 req->type = ASYNC_TYPE_WRITE;
2227 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2228 req->async.callback = wine_server_client_ptr( WS2_async_send );
2229 req->async.iosb = wine_server_client_ptr( iosb );
2230 req->async.arg = wine_server_client_ptr( wsa );
2231 req->async.event = wine_server_obj_handle( ov->hEvent );
2232 req->async.cvalue = cvalue;
2233 status = wine_server_call( req );
2237 if (status != STATUS_PENDING) HeapFree(GetProcessHeap(), 0, wsa);
2239 /* If the connect already failed */
2240 if (status == STATUS_PIPE_DISCONNECTED)
2241 status = _get_sock_error(s, FD_CONNECT_BIT);
2242 SetLastError( NtStatusToWSAError(status) );
2250 release_sock_fd( s, fd );
2254 release_sock_fd( s, fd );
2259 /***********************************************************************
2260 * getpeername (WS2_32.5)
2262 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
2267 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, namelen?*namelen:0);
2269 fd = get_sock_fd( s, 0, NULL );
2274 union generic_unix_sockaddr uaddr;
2275 unsigned int uaddrlen = sizeof(uaddr);
2277 if (getpeername(fd, &uaddr.addr, &uaddrlen) == 0)
2279 if (!name || !namelen)
2280 SetLastError(WSAEFAULT);
2281 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
2282 /* The buffer was too small */
2283 SetLastError(WSAEFAULT);
2288 SetLastError(wsaErrno());
2289 release_sock_fd( s, fd );
2294 /***********************************************************************
2295 * getsockname (WS2_32.6)
2297 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
2302 TRACE("socket: %04lx, ptr %p, len %8x\n", s, name, *namelen);
2304 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
2305 if( (name == NULL) || (namelen == NULL) )
2307 SetLastError( WSAEFAULT );
2308 return SOCKET_ERROR;
2311 fd = get_sock_fd( s, 0, NULL );
2316 union generic_unix_sockaddr uaddr;
2317 unsigned int uaddrlen = sizeof(uaddr);
2319 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
2321 SetLastError(wsaErrno());
2323 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
2325 SetLastError(WSAEINVAL);
2327 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
2329 /* The buffer was too small */
2330 SetLastError(WSAEFAULT);
2336 release_sock_fd( s, fd );
2341 /***********************************************************************
2342 * getsockopt (WS2_32.7)
2344 INT WINAPI WS_getsockopt(SOCKET s, INT level,
2345 INT optname, char *optval, INT *optlen)
2350 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
2351 s, level, optname, optval, *optlen);
2359 /* Handle common cases. The special cases are below, sorted
2361 case WS_SO_ACCEPTCONN:
2362 case WS_SO_BROADCAST:
2365 case WS_SO_KEEPALIVE:
2366 case WS_SO_OOBINLINE:
2368 case WS_SO_REUSEADDR:
2371 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2372 return SOCKET_ERROR;
2373 convert_sockopt(&level, &optname);
2374 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2376 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2379 release_sock_fd( s, fd );
2382 case WS_SO_DONTLINGER:
2384 struct linger lingval;
2385 unsigned int len = sizeof(struct linger);
2387 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
2389 SetLastError(WSAEFAULT);
2390 return SOCKET_ERROR;
2392 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2393 return SOCKET_ERROR;
2395 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
2397 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2402 *(BOOL *)optval = (lingval.l_onoff) ? FALSE : TRUE;
2403 *optlen = sizeof(BOOL);
2406 release_sock_fd( s, fd );
2410 /* As mentioned in setsockopt, Windows ignores this, so we
2411 * always return true here */
2412 case WS_SO_DONTROUTE:
2413 if (!optlen || *optlen < sizeof(BOOL) || !optval)
2415 SetLastError(WSAEFAULT);
2416 return SOCKET_ERROR;
2418 *(BOOL *)optval = TRUE;
2419 *optlen = sizeof(BOOL);
2424 struct linger lingval;
2425 unsigned int len = sizeof(struct linger);
2427 /* struct linger and LINGER have different sizes */
2428 if (!optlen || *optlen < sizeof(LINGER) || !optval)
2430 SetLastError(WSAEFAULT);
2431 return SOCKET_ERROR;
2433 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2434 return SOCKET_ERROR;
2436 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
2438 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2443 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
2444 ((LINGER *)optval)->l_linger = lingval.l_linger;
2445 *optlen = sizeof(struct linger);
2448 release_sock_fd( s, fd );
2452 case WS_SO_MAX_MSG_SIZE:
2453 if (!optlen || *optlen < sizeof(int) || !optval)
2455 SetLastError(WSAEFAULT);
2456 return SOCKET_ERROR;
2458 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
2459 *(int *)optval = 65507;
2460 *optlen = sizeof(int);
2463 /* SO_OPENTYPE does not require a valid socket handle. */
2464 case WS_SO_OPENTYPE:
2465 if (!optlen || *optlen < sizeof(int) || !optval)
2467 SetLastError(WSAEFAULT);
2468 return SOCKET_ERROR;
2470 *(int *)optval = get_per_thread_data()->opentype;
2471 *optlen = sizeof(int);
2472 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
2476 case WS_SO_RCVTIMEO:
2479 case WS_SO_SNDTIMEO:
2481 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
2484 unsigned int len = sizeof(struct timeval);
2486 if (!optlen || *optlen < sizeof(int)|| !optval)
2488 SetLastError(WSAEFAULT);
2489 return SOCKET_ERROR;
2491 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2492 return SOCKET_ERROR;
2494 convert_sockopt(&level, &optname);
2495 if (getsockopt(fd, level, optname, &tv, &len) != 0 )
2497 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2502 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
2503 *optlen = sizeof(int);
2506 release_sock_fd( s, fd );
2511 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
2512 SetLastError(WSAENOPROTOOPT);
2513 return SOCKET_ERROR;
2514 } /* end switch(optname) */
2515 }/* end case WS_SOL_SOCKET */
2519 struct WS_sockaddr_ipx addr;
2520 IPX_ADDRESS_DATA *data;
2525 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
2527 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (unsigned int*)optlen) == -1)
2534 socklen_t len=sizeof(struct ipx);
2535 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
2538 *optval = (int)val.ipx_pt;
2541 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
2542 release_sock_fd( s, fd );
2547 * On a Win2000 system with one network card there are usually
2548 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
2549 * Using this call you can then retrieve info about this all.
2550 * In case of Linux it is a bit different. Usually you have
2551 * only "one" device active and further it is not possible to
2552 * query things like the linkspeed.
2554 FIXME("IPX_ADDRESS\n");
2555 namelen = sizeof(struct WS_sockaddr_ipx);
2556 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
2557 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
2559 data = (IPX_ADDRESS_DATA*)optval;
2560 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
2561 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
2562 data->adapternum = 0;
2563 data->wan = FALSE; /* We are not on a wan for now .. */
2564 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
2565 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
2566 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
2567 * note 1MB = 1000kB in this case */
2570 case IPX_MAX_ADAPTER_NUM:
2571 FIXME("IPX_MAX_ADAPTER_NUM\n");
2572 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
2576 FIXME("IPX optname:%x\n", optname);
2577 return SOCKET_ERROR;
2578 }/* end switch(optname) */
2579 } /* end case NSPROTO_IPX */
2586 case WS_IRLMP_ENUMDEVICES:
2588 static const int MAX_IRDA_DEVICES = 10;
2589 char buf[sizeof(struct irda_device_list) +
2590 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
2592 socklen_t len = sizeof(buf);
2594 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2595 return SOCKET_ERROR;
2596 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
2599 SetLastError(wsaErrno());
2600 return SOCKET_ERROR;
2604 struct irda_device_list *src = (struct irda_device_list *)buf;
2605 DEVICELIST *dst = (DEVICELIST *)optval;
2606 INT needed = sizeof(DEVICELIST), i;
2609 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
2610 if (*optlen < needed)
2612 SetLastError(WSAEFAULT);
2613 return SOCKET_ERROR;
2616 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
2617 dst->numDevice = src->len;
2618 for (i = 0; i < src->len; i++)
2620 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
2621 src->dev[i].saddr, src->dev[i].daddr,
2622 src->dev[i].info, src->dev[i].hints[0],
2623 src->dev[i].hints[1]);
2624 memcpy( dst->Device[i].irdaDeviceID,
2626 sizeof(dst->Device[i].irdaDeviceID) ) ;
2627 memcpy( dst->Device[i].irdaDeviceName,
2629 sizeof(dst->Device[i].irdaDeviceName) ) ;
2630 memcpy( &dst->Device[i].irdaDeviceHints1,
2631 &src->dev[i].hints[0],
2632 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
2633 memcpy( &dst->Device[i].irdaDeviceHints2,
2634 &src->dev[i].hints[1],
2635 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
2636 dst->Device[i].irdaCharSet = src->dev[i].charset;
2642 FIXME("IrDA optname:0x%x\n", optname);
2643 return SOCKET_ERROR;
2645 break; /* case WS_SOL_IRLMP */
2648 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
2649 case WS_IPPROTO_TCP:
2652 case WS_TCP_NODELAY:
2653 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2654 return SOCKET_ERROR;
2655 convert_sockopt(&level, &optname);
2656 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2658 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2661 release_sock_fd( s, fd );
2664 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
2665 return SOCKET_ERROR;
2670 case WS_IP_ADD_MEMBERSHIP:
2671 case WS_IP_DROP_MEMBERSHIP:
2675 case WS_IP_MULTICAST_IF:
2676 case WS_IP_MULTICAST_LOOP:
2677 case WS_IP_MULTICAST_TTL:
2681 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2682 return SOCKET_ERROR;
2683 convert_sockopt(&level, &optname);
2684 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2686 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2689 release_sock_fd( s, fd );
2691 case WS_IP_DONTFRAGMENT:
2692 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
2693 *(BOOL*)optval = FALSE;
2696 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
2697 return SOCKET_ERROR;
2699 case WS_IPPROTO_IPV6:
2702 #ifdef IPV6_ADD_MEMBERSHIP
2703 case WS_IPV6_ADD_MEMBERSHIP:
2705 #ifdef IPV6_DROP_MEMBERSHIP
2706 case WS_IPV6_DROP_MEMBERSHIP:
2708 case WS_IPV6_MULTICAST_IF:
2709 case WS_IPV6_MULTICAST_HOPS:
2710 case WS_IPV6_MULTICAST_LOOP:
2711 case WS_IPV6_UNICAST_HOPS:
2712 case WS_IPV6_V6ONLY:
2713 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2714 return SOCKET_ERROR;
2715 convert_sockopt(&level, &optname);
2716 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2718 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2721 release_sock_fd( s, fd );
2723 case WS_IPV6_DONTFRAG:
2724 FIXME("WS_IPV6_DONTFRAG is always false!\n");
2725 *(BOOL*)optval = FALSE;
2728 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
2729 return SOCKET_ERROR;
2732 WARN("Unknown level: 0x%08x\n", level);
2733 SetLastError(WSAEINVAL);
2734 return SOCKET_ERROR;
2735 } /* end switch(level) */
2738 /***********************************************************************
2741 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
2743 return htonl(hostlong);
2747 /***********************************************************************
2750 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
2752 return htons(hostshort);
2755 /***********************************************************************
2756 * WSAHtonl (WS2_32.46)
2757 * From MSDN description of error codes, this function should also
2758 * check if WinSock has been initialized and the socket is a valid
2759 * socket. But why? This function only translates a host byte order
2760 * u_long into a network byte order u_long...
2762 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
2766 *lpnetlong = htonl(hostlong);
2769 WSASetLastError(WSAEFAULT);
2770 return SOCKET_ERROR;
2773 /***********************************************************************
2774 * WSAHtons (WS2_32.47)
2775 * From MSDN description of error codes, this function should also
2776 * check if WinSock has been initialized and the socket is a valid
2777 * socket. But why? This function only translates a host byte order
2778 * u_short into a network byte order u_short...
2780 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
2785 *lpnetshort = htons(hostshort);
2788 WSASetLastError(WSAEFAULT);
2789 return SOCKET_ERROR;
2793 /***********************************************************************
2794 * inet_addr (WS2_32.11)
2796 WS_u_long WINAPI WS_inet_addr(const char *cp)
2798 if (!cp) return INADDR_NONE;
2799 return inet_addr(cp);
2803 /***********************************************************************
2806 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
2808 return ntohl(netlong);
2812 /***********************************************************************
2815 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
2817 return ntohs(netshort);
2821 /***********************************************************************
2822 * inet_ntoa (WS2_32.12)
2824 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
2826 /* use "buffer for dummies" here because some applications have a
2827 * propensity to decode addresses in ws_hostent structure without
2828 * saving them first...
2830 static char dbuffer[16]; /* Yes, 16: 4*3 digits + 3 '.' + 1 '\0' */
2832 char* s = inet_ntoa(*((struct in_addr*)&in));
2838 SetLastError(wsaErrno());
2842 static const char *debugstr_wsaioctl(DWORD ioctl)
2844 switch(ioctl & 0x18000000)
2848 BYTE size = (ioctl >> 16) & WS_IOCPARM_MASK;
2849 char x = (ioctl & 0xff00) >> 8;
2850 BYTE y = ioctl & 0xff;
2851 const char *buf_type;
2854 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
2858 sprintf(args, "%d, %d", x, y);
2862 sprintf(args, "'%c', %d, %d", x, y, size);
2866 sprintf(args, "'%c', %d, %d", x, y, size);
2870 sprintf(args, "'%c', %d, %d", x, y, size);
2873 return wine_dbg_sprintf("%s(%s)", buf_type, args);
2877 USHORT code = ioctl & 0xffff;
2878 const char *family, *buf_type;
2880 /* This switch looks redundant, but isn't: the case WS_IOC_UNIX
2881 * is handled differently than all others.
2883 switch(ioctl & 0x18000000)
2888 case WS_IOC_PROTOCOL:
2889 family = "IOC_PROTOCOL";
2892 family = "IOC_VENDOR";
2895 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
2898 buf_type = "_WSAIO";
2901 buf_type = "_WSAIORW";
2904 buf_type = "_WSAIOW";
2907 buf_type = "_WSAIOR";
2913 return wine_dbg_sprintf("%s(%s, %d)", buf_type, family, code);
2918 /**********************************************************************
2919 * WSAIoctl (WS2_32.50)
2922 INT WINAPI WSAIoctl(SOCKET s,
2923 DWORD dwIoControlCode,
2926 LPVOID lpbOutBuffer,
2928 LPDWORD lpcbBytesReturned,
2929 LPWSAOVERLAPPED lpOverlapped,
2930 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
2932 TRACE("%ld, 0x%08x, %p, %d, %p, %d, %p, %p, %p\n",
2933 s, dwIoControlCode, lpvInBuffer, cbInBuffer, lpbOutBuffer,
2934 cbOutBuffer, lpcbBytesReturned, lpOverlapped, lpCompletionRoutine);
2936 switch( dwIoControlCode )
2939 if (cbInBuffer != sizeof(WS_u_long)) {
2940 WSASetLastError(WSAEFAULT);
2941 return SOCKET_ERROR;
2943 return WS_ioctlsocket( s, WS_FIONBIO, lpvInBuffer);
2946 if (cbOutBuffer != sizeof(WS_u_long)) {
2947 WSASetLastError(WSAEFAULT);
2948 return SOCKET_ERROR;
2950 return WS_ioctlsocket( s, WS_FIONREAD, lpbOutBuffer);
2952 case WS_SIO_GET_INTERFACE_LIST:
2954 INTERFACE_INFO* intArray = (INTERFACE_INFO*)lpbOutBuffer;
2955 DWORD size, numInt, apiReturn;
2958 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
2962 WSASetLastError(WSAEFAULT);
2963 return SOCKET_ERROR;
2965 if (!lpcbBytesReturned)
2967 WSASetLastError(WSAEFAULT);
2968 return SOCKET_ERROR;
2971 fd = get_sock_fd( s, 0, NULL );
2972 if (fd == -1) return SOCKET_ERROR;
2974 apiReturn = GetAdaptersInfo(NULL, &size);
2975 if (apiReturn == ERROR_NO_DATA)
2979 else if (apiReturn == ERROR_BUFFER_OVERFLOW)
2981 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
2985 if (GetAdaptersInfo(table, &size) == NO_ERROR)
2987 PIP_ADAPTER_INFO ptr;
2989 if (size*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > cbOutBuffer)
2991 WARN("Buffer too small = %u, cbOutBuffer = %u\n", size, cbOutBuffer);
2992 HeapFree(GetProcessHeap(),0,table);
2993 release_sock_fd( s, fd );
2994 WSASetLastError(WSAEFAULT);
2995 return SOCKET_ERROR;
2997 for (ptr = table, numInt = 0; ptr;
2998 ptr = ptr->Next, intArray++, numInt++)
3000 unsigned int addr, mask, bcast;
3001 struct ifreq ifInfo;
3003 /* Socket Status Flags */
3004 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
3005 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
3007 ERR("Error obtaining status flags for socket!\n");
3008 HeapFree(GetProcessHeap(),0,table);
3009 release_sock_fd( s, fd );
3010 WSASetLastError(WSAEINVAL);
3011 return SOCKET_ERROR;
3015 /* set flags; the values of IFF_* are not the same
3016 under Linux and Windows, therefore must generate
3018 intArray->iiFlags = 0;
3019 if (ifInfo.ifr_flags & IFF_BROADCAST)
3020 intArray->iiFlags |= WS_IFF_BROADCAST;
3021 #ifdef IFF_POINTOPOINT
3022 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
3023 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
3025 if (ifInfo.ifr_flags & IFF_LOOPBACK)
3026 intArray->iiFlags |= WS_IFF_LOOPBACK;
3027 if (ifInfo.ifr_flags & IFF_UP)
3028 intArray->iiFlags |= WS_IFF_UP;
3029 if (ifInfo.ifr_flags & IFF_MULTICAST)
3030 intArray->iiFlags |= WS_IFF_MULTICAST;
3033 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
3034 mask = inet_addr(ptr->IpAddressList.IpMask.String);
3035 bcast = addr | ~mask;
3036 intArray->iiAddress.AddressIn.sin_family = AF_INET;
3037 intArray->iiAddress.AddressIn.sin_port = 0;
3038 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
3040 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
3041 intArray->iiNetmask.AddressIn.sin_port = 0;
3042 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
3044 intArray->iiBroadcastAddress.AddressIn.sin_family =
3046 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
3047 intArray->iiBroadcastAddress.AddressIn.sin_addr.
3053 ERR("Unable to get interface table!\n");
3054 release_sock_fd( s, fd );
3055 HeapFree(GetProcessHeap(),0,table);
3056 WSASetLastError(WSAEINVAL);
3057 return SOCKET_ERROR;
3059 HeapFree(GetProcessHeap(),0,table);
3063 release_sock_fd( s, fd );
3064 WSASetLastError(WSAEINVAL);
3065 return SOCKET_ERROR;
3070 ERR("Unable to get interface table!\n");
3071 release_sock_fd( s, fd );
3072 WSASetLastError(WSAEINVAL);
3073 return SOCKET_ERROR;
3075 /* Calculate the size of the array being returned */
3076 *lpcbBytesReturned = sizeof(INTERFACE_INFO) * numInt;
3077 release_sock_fd( s, fd );
3081 case WS_SIO_ADDRESS_LIST_CHANGE:
3082 FIXME("-> SIO_ADDRESS_LIST_CHANGE request: stub\n");
3083 /* FIXME: error and return code depend on whether socket was created
3084 * with WSA_FLAG_OVERLAPPED, but there is no easy way to get this */
3087 case WS_SIO_ADDRESS_LIST_QUERY:
3091 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
3093 if (!lpcbBytesReturned)
3095 WSASetLastError(WSAEFAULT);
3096 return SOCKET_ERROR;
3099 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
3101 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
3104 if (!table || GetAdaptersInfo(table, &size))
3106 HeapFree(GetProcessHeap(), 0, table);
3107 WSASetLastError(WSAEINVAL);
3108 return SOCKET_ERROR;
3111 for (p = table, num = 0; p; p = p->Next)
3112 if (p->IpAddressList.IpAddress.String[0]) num++;
3114 need = sizeof(SOCKET_ADDRESS_LIST) + sizeof(SOCKET_ADDRESS) * (num - 1);
3115 need += sizeof(SOCKADDR) * num;
3116 *lpcbBytesReturned = need;
3118 if (need > cbOutBuffer)
3120 HeapFree(GetProcessHeap(), 0, table);
3121 WSASetLastError(WSAEFAULT);
3122 return SOCKET_ERROR;
3129 SOCKET_ADDRESS_LIST *sa_list = (SOCKET_ADDRESS_LIST *)lpbOutBuffer;
3130 SOCKADDR_IN *sockaddr;
3132 sa = sa_list->Address;
3133 sockaddr = (SOCKADDR_IN *)((char *)sa + num * sizeof(SOCKET_ADDRESS));
3134 sa_list->iAddressCount = num;
3136 for (p = table, i = 0; p; p = p->Next)
3138 if (!p->IpAddressList.IpAddress.String[0]) continue;
3140 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
3141 sa[i].iSockaddrLength = sizeof(SOCKADDR);
3143 sockaddr[i].sin_family = AF_INET;
3144 sockaddr[i].sin_port = 0;
3145 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
3150 HeapFree(GetProcessHeap(), 0, table);
3155 WARN("unable to get IP address list\n");
3156 WSASetLastError(WSAEINVAL);
3157 return SOCKET_ERROR;
3161 FIXME("SIO_FLUSH: stub.\n");
3164 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
3166 static const GUID connectex_guid = WSAID_CONNECTEX;
3167 static const GUID disconnectex_guid = WSAID_DISCONNECTEX;
3168 static const GUID acceptex_guid = WSAID_ACCEPTEX;
3169 static const GUID getaccepexsockaddrs_guid = WSAID_GETACCEPTEXSOCKADDRS;
3170 static const GUID transmitfile_guid = WSAID_TRANSMITFILE;
3171 static const GUID transmitpackets_guid = WSAID_TRANSMITPACKETS;
3172 static const GUID wsarecvmsg_guid = WSAID_WSARECVMSG;
3173 static const GUID wsasendmsg_guid = WSAID_WSASENDMSG;
3175 if ( IsEqualGUID(&connectex_guid, lpvInBuffer) )
3177 *(LPFN_CONNECTEX *)lpbOutBuffer = WS2_ConnectEx;
3180 else if ( IsEqualGUID(&disconnectex_guid, lpvInBuffer) )
3182 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented DisconnectEx\n");
3184 else if ( IsEqualGUID(&acceptex_guid, lpvInBuffer) )
3186 *(LPFN_ACCEPTEX *)lpbOutBuffer = WS2_AcceptEx;
3189 else if ( IsEqualGUID(&getaccepexsockaddrs_guid, lpvInBuffer) )
3191 *(LPFN_GETACCEPTEXSOCKADDRS *)lpbOutBuffer = WS2_GetAcceptExSockaddrs;
3194 else if ( IsEqualGUID(&transmitfile_guid, lpvInBuffer) )
3196 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitFile\n");
3198 else if ( IsEqualGUID(&transmitpackets_guid, lpvInBuffer) )
3200 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitPackets\n");
3202 else if ( IsEqualGUID(&wsarecvmsg_guid, lpvInBuffer) )
3204 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented WSARecvMsg\n");
3206 else if ( IsEqualGUID(&wsasendmsg_guid, lpvInBuffer) )
3208 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented WSASendMsg\n");
3211 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(lpvInBuffer));
3213 WSASetLastError(WSAEOPNOTSUPP);
3214 return SOCKET_ERROR;
3217 case WS_SIO_KEEPALIVE_VALS:
3220 struct tcp_keepalive *k = lpvInBuffer;
3221 int keepalive = k->onoff ? 1 : 0;
3222 int keepidle = k->keepalivetime / 1000;
3223 int keepintvl = k->keepaliveinterval / 1000;
3227 WSASetLastError(WSAEINVAL);
3228 return SOCKET_ERROR;
3231 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
3233 fd = get_sock_fd(s, 0, NULL);
3234 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
3236 release_sock_fd(s, fd);
3237 WSASetLastError(WSAEINVAL);
3238 return SOCKET_ERROR;
3240 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
3241 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
3243 release_sock_fd(s, fd);
3244 WSASetLastError(WSAEINVAL);
3245 return SOCKET_ERROR;
3247 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
3249 release_sock_fd(s, fd);
3250 WSASetLastError(WSAEINVAL);
3251 return SOCKET_ERROR;
3254 FIXME("ignoring keepalive interval and timeout\n");
3257 release_sock_fd(s, fd);
3260 case WS_SIO_UDP_CONNRESET:
3261 FIXME("WS_SIO_UDP_CONNRESET stub\n");
3264 FIXME("unsupported WS_IOCTL cmd (%s)\n",
3265 debugstr_wsaioctl(dwIoControlCode));
3266 WSASetLastError(WSAEOPNOTSUPP);
3267 return SOCKET_ERROR;
3274 /***********************************************************************
3275 * ioctlsocket (WS2_32.10)
3277 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
3282 TRACE("socket %04lx, cmd %08x, ptr %p\n", s, cmd, argp);
3283 /* broken apps like defcon pass the argp value directly instead of a pointer to it */
3284 if(IS_INTRESOURCE(argp))
3286 SetLastError(WSAEFAULT);
3287 return SOCKET_ERROR;
3297 if( _get_sock_mask(s) )
3299 /* AsyncSelect()'ed sockets are always nonblocking */
3300 if (*argp) return 0;
3301 SetLastError(WSAEINVAL);
3302 return SOCKET_ERROR;
3305 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
3307 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
3315 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
3316 SetLastError(WSAEINVAL);
3317 return SOCKET_ERROR;
3319 case SIOCGIFBRDADDR:
3320 case SIOCGIFNETMASK:
3322 /* These don't need any special handling. They are used by
3323 WsControl, and are here to suppress an unnecessary warning. */
3327 /* Netscape tries hard to use bogus ioctl 0x667e */
3328 /* FIXME: 0x667e above is ('f' << 8) | 126, and is a low word of
3329 * FIONBIO (_IOW('f', 126, u_long)), how that should be handled?
3331 WARN("\tunknown WS_IOCTL cmd (%08x)\n", cmd);
3335 fd = get_sock_fd( s, 0, NULL );
3338 if( ioctl(fd, newcmd, (char*)argp ) == 0 )
3340 release_sock_fd( s, fd );
3343 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3344 release_sock_fd( s, fd );
3346 return SOCKET_ERROR;
3349 /***********************************************************************
3350 * listen (WS2_32.13)
3352 int WINAPI WS_listen(SOCKET s, int backlog)
3354 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
3356 TRACE("socket %04lx, backlog %d\n", s, backlog);
3359 if (listen(fd, backlog) == 0)
3361 release_sock_fd( s, fd );
3362 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
3364 FD_CONNECT|FD_WINE_CONNECTED);
3367 SetLastError(wsaErrno());
3368 release_sock_fd( s, fd );
3370 return SOCKET_ERROR;
3373 /***********************************************************************
3376 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
3378 DWORD n, dwFlags = flags;
3384 if ( WS2_recvfrom(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
3385 return SOCKET_ERROR;
3390 /***********************************************************************
3391 * recvfrom (WS2_32.17)
3393 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
3394 struct WS_sockaddr *from, int *fromlen)
3396 DWORD n, dwFlags = flags;
3402 if ( WS2_recvfrom(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL) == SOCKET_ERROR )
3403 return SOCKET_ERROR;
3408 /* allocate a poll array for the corresponding fd sets */
3409 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
3410 const WS_fd_set *exceptfds, int *count_ptr )
3412 unsigned int i, j = 0, count = 0;
3415 if (readfds) count += readfds->fd_count;
3416 if (writefds) count += writefds->fd_count;
3417 if (exceptfds) count += exceptfds->fd_count;
3419 if (!count) return NULL;
3420 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0]))))
3422 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
3426 for (i = 0; i < readfds->fd_count; i++, j++)
3428 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
3429 if (fds[j].fd == -1) goto failed;
3430 fds[j].events = POLLIN;
3434 for (i = 0; i < writefds->fd_count; i++, j++)
3436 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
3437 if (fds[j].fd == -1) goto failed;
3438 fds[j].events = POLLOUT;
3442 for (i = 0; i < exceptfds->fd_count; i++, j++)
3444 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
3445 if (fds[j].fd == -1) goto failed;
3446 fds[j].events = POLLHUP;
3455 for (i = 0; i < readfds->fd_count && j < count; i++, j++)
3456 release_sock_fd( readfds->fd_array[i], fds[j].fd );
3458 for (i = 0; i < writefds->fd_count && j < count; i++, j++)
3459 release_sock_fd( writefds->fd_array[i], fds[j].fd );
3461 for (i = 0; i < exceptfds->fd_count && j < count; i++, j++)
3462 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
3463 HeapFree( GetProcessHeap(), 0, fds );
3467 /* release the file descriptor obtained in fd_sets_to_poll */
3468 /* must be called with the original fd_set arrays, before calling get_poll_results */
3469 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
3470 const WS_fd_set *exceptfds, struct pollfd *fds )
3472 unsigned int i, j = 0;
3476 for (i = 0; i < readfds->fd_count; i++, j++)
3477 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
3481 for (i = 0; i < writefds->fd_count; i++, j++)
3482 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
3486 for (i = 0; i < exceptfds->fd_count; i++, j++)
3487 if (fds[j].fd != -1)
3489 /* make sure we have a real error before releasing the fd */
3490 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
3491 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
3496 /* map the poll results back into the Windows fd sets */
3497 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
3498 const struct pollfd *fds )
3500 unsigned int i, j = 0, k, total = 0;
3504 for (i = k = 0; i < readfds->fd_count; i++, j++)
3505 if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
3506 readfds->fd_count = k;
3511 for (i = k = 0; i < writefds->fd_count; i++, j++)
3512 if (fds[j].revents) writefds->fd_array[k++] = writefds->fd_array[i];
3513 writefds->fd_count = k;
3518 for (i = k = 0; i < exceptfds->fd_count; i++, j++)
3519 if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
3520 exceptfds->fd_count = k;
3527 /***********************************************************************
3528 * select (WS2_32.18)
3530 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
3531 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
3532 const struct WS_timeval* ws_timeout)
3534 struct pollfd *pollfds;
3535 struct timeval tv1, tv2;
3537 int count, ret, timeout = -1;
3539 TRACE("read %p, write %p, excp %p timeout %p\n",
3540 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
3542 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )) && count)
3543 return SOCKET_ERROR;
3547 torig = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
3549 gettimeofday( &tv1, 0 );
3552 while ((ret = poll( pollfds, count, timeout )) < 0)
3556 if (!ws_timeout) continue;
3557 gettimeofday( &tv2, 0 );
3559 tv2.tv_sec -= tv1.tv_sec;
3560 tv2.tv_usec -= tv1.tv_usec;
3561 if (tv2.tv_usec < 0)
3563 tv2.tv_usec += 1000000;
3567 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
3568 if (timeout <= 0) break;
3571 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
3573 if (ret == -1) SetLastError(wsaErrno());
3574 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
3575 HeapFree( GetProcessHeap(), 0, pollfds );
3579 /* helper to send completion messages for client-only i/o operation case */
3580 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
3583 SERVER_START_REQ( add_fd_completion )
3585 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
3586 req->cvalue = CompletionValue;
3587 req->status = CompletionStatus;
3588 req->information = Information;
3589 wine_server_call( req );
3595 /***********************************************************************
3598 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
3604 wsabuf.buf = (char*) buf;
3606 if ( WS2_sendto( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
3607 return SOCKET_ERROR;
3612 /***********************************************************************
3613 * WSASend (WS2_32.72)
3615 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3616 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
3617 LPWSAOVERLAPPED lpOverlapped,
3618 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3620 return WS2_sendto( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
3621 NULL, 0, lpOverlapped, lpCompletionRoutine );
3624 /***********************************************************************
3625 * WSASendDisconnect (WS2_32.73)
3627 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
3629 return WS_shutdown( s, SD_SEND );
3633 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3634 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
3635 const struct WS_sockaddr *to, int tolen,
3636 LPWSAOVERLAPPED lpOverlapped,
3637 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3639 unsigned int i, options;
3641 struct ws2_async *wsa;
3642 int totalLength = 0;
3643 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
3645 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
3646 s, lpBuffers, dwBufferCount, dwFlags,
3647 to, tolen, lpOverlapped, lpCompletionRoutine);
3649 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
3650 TRACE( "fd=%d, options=%x\n", fd, options );
3652 if ( fd == -1 ) return SOCKET_ERROR;
3654 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
3660 wsa->hSocket = SOCKET2HANDLE(s);
3661 wsa->addr = (struct WS_sockaddr *)to;
3662 wsa->addrlen.val = tolen;
3663 wsa->flags = dwFlags;
3664 wsa->n_iovecs = dwBufferCount;
3665 wsa->first_iovec = 0;
3666 for ( i = 0; i < dwBufferCount; i++ )
3668 wsa->iovec[i].iov_base = lpBuffers[i].buf;
3669 wsa->iovec[i].iov_len = lpBuffers[i].len;
3670 totalLength += lpBuffers[i].len;
3673 if (!lpNumberOfBytesSent)
3681 n = WS2_send( fd, wsa );
3682 if (n != -1 || errno != EINTR) break;
3684 if (n == -1 && errno != EAGAIN)
3686 int loc_errno = errno;
3688 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
3692 if ((lpOverlapped || lpCompletionRoutine) &&
3693 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
3695 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
3697 wsa->user_overlapped = lpOverlapped;
3698 wsa->completion_func = lpCompletionRoutine;
3699 release_sock_fd( s, fd );
3703 iosb->u.Status = STATUS_PENDING;
3704 iosb->Information = 0;
3706 SERVER_START_REQ( register_async )
3708 req->type = ASYNC_TYPE_WRITE;
3709 req->async.handle = wine_server_obj_handle( wsa->hSocket );
3710 req->async.callback = wine_server_client_ptr( WS2_async_send );
3711 req->async.iosb = wine_server_client_ptr( iosb );
3712 req->async.arg = wine_server_client_ptr( wsa );
3713 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
3714 req->async.cvalue = cvalue;
3715 err = wine_server_call( req );
3719 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
3720 WSASetLastError( NtStatusToWSAError( err ));
3721 return SOCKET_ERROR;
3724 iosb->u.Status = STATUS_SUCCESS;
3725 iosb->Information = n;
3726 *lpNumberOfBytesSent = n;
3727 if (!wsa->completion_func)
3729 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
3730 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
3731 HeapFree( GetProcessHeap(), 0, wsa );
3733 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
3734 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
3739 if ( _is_blocking(s) )
3741 /* On a blocking non-overlapped stream socket,
3742 * sending blocks until the entire buffer is sent. */
3743 DWORD timeout_start = GetTickCount();
3745 *lpNumberOfBytesSent = 0;
3747 while (wsa->first_iovec < dwBufferCount)
3750 int timeout = GET_SNDTIMEO(fd);
3754 *lpNumberOfBytesSent += n;
3755 while (wsa->first_iovec < dwBufferCount && wsa->iovec[wsa->first_iovec].iov_len <= n)
3756 n -= wsa->iovec[wsa->first_iovec++].iov_len;
3757 if (wsa->first_iovec >= dwBufferCount) break;
3758 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
3759 wsa->iovec[wsa->first_iovec].iov_len -= n;
3764 timeout -= GetTickCount() - timeout_start;
3765 if (timeout < 0) timeout = 0;
3769 pfd.events = POLLOUT;
3771 if (!timeout || !poll( &pfd, 1, timeout ))
3774 goto error; /* msdn says a timeout in send is fatal */
3777 n = WS2_send( fd, wsa );
3778 if (n == -1 && errno != EAGAIN && errno != EINTR)
3785 else /* non-blocking */
3787 if (n < totalLength)
3788 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
3791 err = WSAEWOULDBLOCK;
3794 *lpNumberOfBytesSent = n;
3797 TRACE(" -> %i bytes\n", *lpNumberOfBytesSent);
3799 HeapFree( GetProcessHeap(), 0, wsa );
3800 release_sock_fd( s, fd );
3805 HeapFree( GetProcessHeap(), 0, wsa );
3806 release_sock_fd( s, fd );
3807 WARN(" -> ERROR %d\n", err);
3808 WSASetLastError(err);
3809 return SOCKET_ERROR;
3812 /***********************************************************************
3813 * WSASendTo (WS2_32.74)
3815 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3816 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
3817 const struct WS_sockaddr *to, int tolen,
3818 LPWSAOVERLAPPED lpOverlapped,
3819 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3821 return WS2_sendto( s, lpBuffers, dwBufferCount,
3822 lpNumberOfBytesSent, dwFlags,
3824 lpOverlapped, lpCompletionRoutine );
3827 /***********************************************************************
3828 * sendto (WS2_32.20)
3830 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
3831 const struct WS_sockaddr *to, int tolen)
3837 wsabuf.buf = (char*) buf;
3839 if ( WS2_sendto(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
3840 return SOCKET_ERROR;
3845 /***********************************************************************
3846 * setsockopt (WS2_32.21)
3848 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
3849 const char *optval, int optlen)
3853 struct linger linger;
3854 struct timeval tval;
3856 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
3857 s, level, optname, optval, optlen);
3859 /* some broken apps pass the value directly instead of a pointer to it */
3860 if(optlen && IS_INTRESOURCE(optval))
3862 SetLastError(WSAEFAULT);
3863 return SOCKET_ERROR;
3871 /* Some options need some conversion before they can be sent to
3872 * setsockopt. The conversions are done here, then they will fall though
3873 * to the general case. Special options that are not passed to
3874 * setsockopt follow below that.*/
3876 case WS_SO_DONTLINGER:
3877 linger.l_onoff = *((const int*)optval) ? 0: 1;
3878 linger.l_linger = 0;
3880 optname = SO_LINGER;
3881 optval = (char*)&linger;
3882 optlen = sizeof(struct linger);
3886 linger.l_onoff = ((LINGER*)optval)->l_onoff;
3887 linger.l_linger = ((LINGER*)optval)->l_linger;
3888 /* FIXME: what is documented behavior if SO_LINGER optval
3891 optname = SO_LINGER;
3892 optval = (char*)&linger;
3893 optlen = sizeof(struct linger);
3897 if (*(const int*)optval < 2048)
3899 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
3904 /* The options listed here don't need any special handling. Thanks to
3905 * the conversion happening above, options from there will fall through
3907 case WS_SO_ACCEPTCONN:
3908 case WS_SO_BROADCAST:
3910 case WS_SO_KEEPALIVE:
3911 case WS_SO_OOBINLINE:
3912 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
3913 * however, using it the BSD way fixes bug 8513 and seems to be what
3914 * most programmers assume, anyway */
3915 case WS_SO_REUSEADDR:
3918 convert_sockopt(&level, &optname);
3921 /* SO_DEBUG is a privileged operation, ignore it. */
3923 TRACE("Ignoring SO_DEBUG\n");
3926 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
3927 * socket. According to MSDN, this option is silently ignored.*/
3928 case WS_SO_DONTROUTE:
3929 TRACE("Ignoring SO_DONTROUTE\n");
3932 /* Stops two sockets from being bound to the same port. Always happens
3933 * on unix systems, so just drop it. */
3934 case WS_SO_EXCLUSIVEADDRUSE:
3935 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
3938 /* After a ConnectEx call succeeds, the socket can't be used with half of the
3939 * normal winsock functions on windows. We don't have that problem. */
3940 case WS_SO_UPDATE_CONNECT_CONTEXT:
3941 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
3944 /* SO_OPENTYPE does not require a valid socket handle. */
3945 case WS_SO_OPENTYPE:
3946 if (!optlen || optlen < sizeof(int) || !optval)
3948 SetLastError(WSAEFAULT);
3949 return SOCKET_ERROR;
3951 get_per_thread_data()->opentype = *(const int *)optval;
3952 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
3956 case WS_SO_RCVTIMEO:
3959 case WS_SO_SNDTIMEO:
3961 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
3962 if (optval && optlen == sizeof(UINT32)) {
3963 /* WinSock passes milliseconds instead of struct timeval */
3964 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
3965 tval.tv_sec = *(const UINT32*)optval / 1000;
3966 /* min of 500 milliseconds */
3967 if (tval.tv_sec == 0 && tval.tv_usec && tval.tv_usec < 500000)
3968 tval.tv_usec = 500000;
3969 optlen = sizeof(struct timeval);
3970 optval = (char*)&tval;
3971 } else if (optlen == sizeof(struct timeval)) {
3972 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
3974 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
3977 convert_sockopt(&level, &optname);
3982 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
3983 SetLastError(WSAENOPROTOOPT);
3984 return SOCKET_ERROR;
3986 break; /* case WS_SOL_SOCKET */
3993 fd = get_sock_fd( s, 0, NULL );
3994 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", *(const int*)optval, fd);
3996 /* We try to set the ipx type on ipx socket level. */
3998 if(setsockopt(fd, SOL_IPX, IPX_TYPE, optval, optlen) == -1)
4000 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
4001 release_sock_fd( s, fd );
4002 return SOCKET_ERROR;
4007 /* Should we retrieve val using a getsockopt call and then
4008 * set the modified one? */
4009 val.ipx_pt = *optval;
4010 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
4013 release_sock_fd( s, fd );
4016 case IPX_FILTERPTYPE:
4017 /* Sets the receive filter packet type, at the moment we don't support it */
4018 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
4019 /* Returning 0 is better for now than returning a SOCKET_ERROR */
4023 FIXME("opt_name:%x\n", optname);
4024 return SOCKET_ERROR;
4026 break; /* case NSPROTO_IPX */
4029 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
4030 case WS_IPPROTO_TCP:
4033 case WS_TCP_NODELAY:
4034 convert_sockopt(&level, &optname);
4037 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
4038 return SOCKET_ERROR;
4045 case WS_IP_ADD_MEMBERSHIP:
4046 case WS_IP_DROP_MEMBERSHIP:
4050 case WS_IP_MULTICAST_IF:
4051 case WS_IP_MULTICAST_LOOP:
4052 case WS_IP_MULTICAST_TTL:
4056 convert_sockopt(&level, &optname);
4058 case WS_IP_DONTFRAGMENT:
4059 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
4062 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
4063 return SOCKET_ERROR;
4067 case WS_IPPROTO_IPV6:
4070 #ifdef IPV6_ADD_MEMBERSHIP
4071 case WS_IPV6_ADD_MEMBERSHIP:
4073 #ifdef IPV6_DROP_MEMBERSHIP
4074 case WS_IPV6_DROP_MEMBERSHIP:
4076 case WS_IPV6_MULTICAST_IF:
4077 case WS_IPV6_MULTICAST_HOPS:
4078 case WS_IPV6_MULTICAST_LOOP:
4079 case WS_IPV6_UNICAST_HOPS:
4080 case WS_IPV6_V6ONLY:
4081 convert_sockopt(&level, &optname);
4083 case WS_IPV6_DONTFRAG:
4084 FIXME("IPV6_DONTFRAG is silently ignored!\n");
4087 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
4088 return SOCKET_ERROR;
4093 WARN("Unknown level: 0x%08x\n", level);
4094 SetLastError(WSAEINVAL);
4095 return SOCKET_ERROR;
4096 } /* end switch(level) */
4098 /* avoid endianness issues if argument is a 16-bit int */
4099 if (optval && optlen < sizeof(int))
4101 woptval= *((const INT16 *) optval);
4102 optval= (char*) &woptval;
4105 fd = get_sock_fd( s, 0, NULL );
4106 if (fd == -1) return SOCKET_ERROR;
4108 if (setsockopt(fd, level, optname, optval, optlen) == 0)
4110 release_sock_fd( s, fd );
4113 TRACE("Setting socket error, %d\n", wsaErrno());
4114 SetLastError(wsaErrno());
4115 release_sock_fd( s, fd );
4117 return SOCKET_ERROR;
4120 /***********************************************************************
4121 * shutdown (WS2_32.22)
4123 int WINAPI WS_shutdown(SOCKET s, int how)
4125 int fd, err = WSAENOTSOCK;
4126 unsigned int options, clear_flags = 0;
4128 fd = get_sock_fd( s, 0, &options );
4129 TRACE("socket %04lx, how %i %x\n", s, how, options );
4132 return SOCKET_ERROR;
4136 case 0: /* drop receives */
4137 clear_flags |= FD_READ;
4139 case 1: /* drop sends */
4140 clear_flags |= FD_WRITE;
4142 case 2: /* drop all */
4143 clear_flags |= FD_READ|FD_WRITE;
4145 clear_flags |= FD_WINE_LISTENING;
4148 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
4153 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
4156 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
4160 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
4161 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
4164 if (err) goto error;
4166 else /* non-overlapped mode */
4168 if ( shutdown( fd, how ) )
4175 release_sock_fd( s, fd );
4176 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
4177 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
4181 release_sock_fd( s, fd );
4182 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
4183 WSASetLastError( err );
4184 return SOCKET_ERROR;
4187 /***********************************************************************
4188 * socket (WS2_32.23)
4190 SOCKET WINAPI WS_socket(int af, int type, int protocol)
4192 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
4194 return WSASocketA( af, type, protocol, NULL, 0,
4195 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
4199 /***********************************************************************
4200 * gethostbyaddr (WS2_32.51)
4202 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
4204 struct WS_hostent *retval = NULL;
4205 struct hostent* host;
4207 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4210 struct hostent hostentry;
4213 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
4215 int res = gethostbyaddr_r(addr, len, type,
4216 &hostentry, extrabuf, ebufsize, &host, &locerr);
4217 if( res != ERANGE) break;
4219 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
4221 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
4223 EnterCriticalSection( &csWSgetXXXbyYYY );
4224 host = gethostbyaddr(addr, len, type);
4225 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
4227 if( host != NULL ) retval = WS_dup_he(host);
4228 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4229 HeapFree(GetProcessHeap(),0,extrabuf);
4231 LeaveCriticalSection( &csWSgetXXXbyYYY );
4233 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
4237 /***********************************************************************
4238 * WS_get_local_ips (INTERNAL)
4240 * Returns the list of local IP addresses by going through the network
4241 * adapters and using the local routing table to sort the addresses
4242 * from highest routing priority to lowest routing priority. This
4243 * functionality is inferred from the description for obtaining local
4244 * IP addresses given in the Knowledge Base Article Q160215.
4246 * Please note that the returned hostent is only freed when the thread
4247 * closes and is replaced if another hostent is requested.
4249 static struct WS_hostent* WS_get_local_ips( char *hostname )
4251 int last_metric, numroutes = 0, i, j;
4252 PIP_ADAPTER_INFO adapters = NULL, k;
4253 struct WS_hostent *hostlist = NULL;
4254 PMIB_IPFORWARDTABLE routes = NULL;
4255 struct route *route_addrs = NULL;
4256 DWORD adap_size, route_size;
4258 /* Obtain the size of the adapter list and routing table, also allocate memory */
4259 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
4261 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
4263 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
4264 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
4265 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
4266 if (adapters == NULL || routes == NULL || route_addrs == NULL)
4268 /* Obtain the adapter list and the full routing table */
4269 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
4271 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
4273 /* Store the interface associated with each route */
4274 for (i = 0; i < routes->dwNumEntries; i++)
4276 DWORD ifindex, ifmetric, exists = FALSE;
4278 if (routes->table[i].dwForwardType != MIB_IPROUTE_TYPE_DIRECT)
4280 ifindex = routes->table[i].dwForwardIfIndex;
4281 ifmetric = routes->table[i].dwForwardMetric1;
4282 /* Only store the lowest valued metric for an interface */
4283 for (j = 0; j < numroutes; j++)
4285 if (route_addrs[j].interface == ifindex)
4287 if (route_addrs[j].metric > ifmetric)
4288 route_addrs[j].metric = ifmetric;
4294 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
4295 if (route_addrs == NULL)
4296 goto cleanup; /* Memory allocation error, fail gracefully */
4297 route_addrs[numroutes].interface = ifindex;
4298 route_addrs[numroutes].metric = ifmetric;
4299 /* If no IP is found in the next step (for whatever reason)
4300 * then fall back to the magic loopback address.
4302 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
4306 goto cleanup; /* No routes, fall back to the Magic IP */
4307 /* Find the IP address associated with each found interface */
4308 for (i = 0; i < numroutes; i++)
4310 for (k = adapters; k != NULL; k = k->Next)
4312 char *ip = k->IpAddressList.IpAddress.String;
4314 if (route_addrs[i].interface == k->Index)
4315 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
4318 /* Allocate a hostent and enough memory for all the IPs,
4319 * including the NULL at the end of the list.
4321 hostlist = WS_create_he(hostname, 1, numroutes+1, TRUE);
4322 if (hostlist == NULL)
4323 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
4324 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
4325 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
4326 hostlist->h_addrtype = AF_INET;
4327 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
4328 /* Reorder the entries when placing them in the host list, Windows expects
4329 * the IP list in order from highest priority to lowest (the critical thing
4330 * is that most applications expect the first IP to be the default route).
4333 for (i = 0; i < numroutes; i++)
4335 struct in_addr addr;
4336 int metric = 0xFFFF;
4338 memcpy(&addr, magic_loopback_addr, 4);
4339 for (j = 0; j < numroutes; j++)
4341 int this_metric = route_addrs[j].metric;
4343 if (this_metric > last_metric && this_metric < metric)
4345 addr = route_addrs[j].addr;
4346 metric = this_metric;
4349 last_metric = metric;
4350 (*(struct in_addr *) hostlist->h_addr_list[i]) = addr;
4353 /* Cleanup all allocated memory except the address list,
4354 * the address list is used by the calling app.
4357 HeapFree(GetProcessHeap(), 0, route_addrs);
4358 HeapFree(GetProcessHeap(), 0, adapters);
4359 HeapFree(GetProcessHeap(), 0, routes);
4363 /***********************************************************************
4364 * gethostbyname (WS2_32.52)
4366 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
4368 struct WS_hostent *retval = NULL;
4369 struct hostent* host;
4370 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4373 struct hostent hostentry;
4374 int locerr = ENOBUFS;
4377 if( gethostname( hostname, 100) == -1) {
4378 SetLastError( WSAENOBUFS); /* appropriate ? */
4381 if( !name || !name[0]) {
4384 /* If the hostname of the local machine is requested then return the
4385 * complete list of local IP addresses */
4386 if(strcmp(name, hostname) == 0)
4387 retval = WS_get_local_ips(hostname);
4388 /* If any other hostname was requested (or the routing table lookup failed)
4389 * then return the IP found by the host OS */
4392 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4394 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
4396 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
4397 if( res != ERANGE) break;
4399 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
4401 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
4403 EnterCriticalSection( &csWSgetXXXbyYYY );
4404 host = gethostbyname(name);
4405 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
4407 if (host) retval = WS_dup_he(host);
4408 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4409 HeapFree(GetProcessHeap(),0,extrabuf);
4411 LeaveCriticalSection( &csWSgetXXXbyYYY );
4414 if (retval && retval->h_addr_list[0][0] == 127 &&
4415 strcmp(name, "localhost") != 0)
4417 /* hostname != "localhost" but has loopback address. replace by our
4418 * special address.*/
4419 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
4421 TRACE( "%s ret %p\n", debugstr_a(name), retval );
4426 /***********************************************************************
4427 * getprotobyname (WS2_32.53)
4429 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
4431 struct WS_protoent* retval = NULL;
4432 #ifdef HAVE_GETPROTOBYNAME
4433 struct protoent* proto;
4434 EnterCriticalSection( &csWSgetXXXbyYYY );
4435 if( (proto = getprotobyname(name)) != NULL )
4437 retval = WS_dup_pe(proto);
4440 MESSAGE("protocol %s not found; You might want to add "
4441 "this to /etc/protocols\n", debugstr_a(name) );
4442 SetLastError(WSANO_DATA);
4444 LeaveCriticalSection( &csWSgetXXXbyYYY );
4446 TRACE( "%s ret %p\n", debugstr_a(name), retval );
4451 /***********************************************************************
4452 * getprotobynumber (WS2_32.54)
4454 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
4456 struct WS_protoent* retval = NULL;
4457 #ifdef HAVE_GETPROTOBYNUMBER
4458 struct protoent* proto;
4459 EnterCriticalSection( &csWSgetXXXbyYYY );
4460 if( (proto = getprotobynumber(number)) != NULL )
4462 retval = WS_dup_pe(proto);
4465 MESSAGE("protocol number %d not found; You might want to add "
4466 "this to /etc/protocols\n", number );
4467 SetLastError(WSANO_DATA);
4469 LeaveCriticalSection( &csWSgetXXXbyYYY );
4471 TRACE("%i ret %p\n", number, retval);
4476 /***********************************************************************
4477 * getservbyname (WS2_32.55)
4479 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
4481 struct WS_servent* retval = NULL;
4482 struct servent* serv;
4484 char *proto_str = NULL;
4486 if (!(name_str = strdup_lower(name))) return NULL;
4488 if (proto && *proto)
4490 if (!(proto_str = strdup_lower(proto)))
4492 HeapFree( GetProcessHeap(), 0, name_str );
4497 EnterCriticalSection( &csWSgetXXXbyYYY );
4498 serv = getservbyname(name_str, proto_str);
4501 retval = WS_dup_se(serv);
4503 else SetLastError(WSANO_DATA);
4504 LeaveCriticalSection( &csWSgetXXXbyYYY );
4505 HeapFree( GetProcessHeap(), 0, proto_str );
4506 HeapFree( GetProcessHeap(), 0, name_str );
4507 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
4511 /***********************************************************************
4512 * freeaddrinfo (WS2_32.@)
4514 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
4517 struct WS_addrinfo *next;
4519 HeapFree(GetProcessHeap(),0,res->ai_canonname);
4520 HeapFree(GetProcessHeap(),0,res->ai_addr);
4521 next = res->ai_next;
4522 HeapFree(GetProcessHeap(),0,res);
4527 /* helper functions for getaddrinfo()/getnameinfo() */
4528 static int convert_aiflag_w2u(int winflags) {
4532 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
4533 if (ws_aiflag_map[i][0] & winflags) {
4534 unixflags |= ws_aiflag_map[i][1];
4535 winflags &= ~ws_aiflag_map[i][0];
4538 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
4542 static int convert_niflag_w2u(int winflags) {
4546 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
4547 if (ws_niflag_map[i][0] & winflags) {
4548 unixflags |= ws_niflag_map[i][1];
4549 winflags &= ~ws_niflag_map[i][0];
4552 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
4556 static int convert_aiflag_u2w(int unixflags) {
4560 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
4561 if (ws_aiflag_map[i][1] & unixflags) {
4562 winflags |= ws_aiflag_map[i][0];
4563 unixflags &= ~ws_aiflag_map[i][1];
4565 if (unixflags) /* will warn usually */
4566 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
4570 static int convert_eai_u2w(int unixret) {
4573 for (i=0;ws_eai_map[i][0];i++)
4574 if (ws_eai_map[i][1] == unixret)
4575 return ws_eai_map[i][0];
4579 /***********************************************************************
4580 * getaddrinfo (WS2_32.@)
4582 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
4584 #ifdef HAVE_GETADDRINFO
4585 struct addrinfo *unixaires = NULL;
4587 struct addrinfo unixhints, *punixhints = NULL;
4588 CHAR *node = NULL, *serv = NULL;
4591 if (!(node = strdup_lower(nodename))) return WSA_NOT_ENOUGH_MEMORY;
4594 if (!(serv = strdup_lower(servname))) {
4595 HeapFree(GetProcessHeap(), 0, node);
4596 return WSA_NOT_ENOUGH_MEMORY;
4601 punixhints = &unixhints;
4603 memset(&unixhints, 0, sizeof(unixhints));
4604 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
4605 if (hints->ai_family == 0) /* wildcard, specific to getaddrinfo() */
4606 punixhints->ai_family = 0;
4608 punixhints->ai_family = convert_af_w2u(hints->ai_family);
4609 if (hints->ai_socktype == 0) /* wildcard, specific to getaddrinfo() */
4610 punixhints->ai_socktype = 0;
4612 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
4613 if (hints->ai_protocol == 0) /* wildcard, specific to getaddrinfo() */
4614 punixhints->ai_protocol = 0;
4616 punixhints->ai_protocol = convert_proto_w2u(hints->ai_protocol);
4619 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
4620 result = getaddrinfo(nodename, servname, punixhints, &unixaires);
4622 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
4624 HeapFree(GetProcessHeap(), 0, node);
4625 HeapFree(GetProcessHeap(), 0, serv);
4628 struct addrinfo *xuai = unixaires;
4629 struct WS_addrinfo **xai = res;
4633 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
4639 *xai = ai;xai = &ai->ai_next;
4640 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
4641 ai->ai_family = convert_af_u2w(xuai->ai_family);
4642 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
4643 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
4644 if (xuai->ai_canonname) {
4645 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
4646 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
4647 if (!ai->ai_canonname)
4649 strcpy(ai->ai_canonname,xuai->ai_canonname);
4651 len = xuai->ai_addrlen;
4652 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
4655 ai->ai_addrlen = len;
4657 int winlen = ai->ai_addrlen;
4659 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
4660 ai->ai_addrlen = winlen;
4664 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
4667 ai->ai_addrlen = len;
4669 xuai = xuai->ai_next;
4671 freeaddrinfo(unixaires);
4673 result = convert_eai_u2w(result);
4679 if (*res) WS_freeaddrinfo(*res);
4680 if (unixaires) freeaddrinfo(unixaires);
4682 return WSA_NOT_ENOUGH_MEMORY;
4684 FIXME("getaddrinfo() failed, not found during buildtime.\n");
4689 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
4691 struct WS_addrinfoW *ret;
4693 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
4694 ret->ai_flags = ai->ai_flags;
4695 ret->ai_family = ai->ai_family;
4696 ret->ai_socktype = ai->ai_socktype;
4697 ret->ai_protocol = ai->ai_protocol;
4698 ret->ai_addrlen = ai->ai_addrlen;
4699 ret->ai_canonname = NULL;
4700 ret->ai_addr = NULL;
4701 ret->ai_next = NULL;
4702 if (ai->ai_canonname)
4704 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
4705 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
4707 HeapFree(GetProcessHeap(), 0, ret);
4710 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
4714 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
4716 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
4717 HeapFree(GetProcessHeap(), 0, ret);
4720 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
4725 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
4727 struct WS_addrinfoW *ret, *infoW;
4729 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
4730 while (info->ai_next)
4732 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
4737 infoW = infoW->ai_next;
4738 info = info->ai_next;
4743 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
4745 struct WS_addrinfo *ret;
4747 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
4748 ret->ai_flags = ai->ai_flags;
4749 ret->ai_family = ai->ai_family;
4750 ret->ai_socktype = ai->ai_socktype;
4751 ret->ai_protocol = ai->ai_protocol;
4752 ret->ai_addrlen = ai->ai_addrlen;
4753 ret->ai_canonname = NULL;
4754 ret->ai_addr = NULL;
4755 ret->ai_next = NULL;
4756 if (ai->ai_canonname)
4758 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
4759 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
4761 HeapFree(GetProcessHeap(), 0, ret);
4764 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
4768 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
4770 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
4771 HeapFree(GetProcessHeap(), 0, ret);
4774 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
4779 /***********************************************************************
4780 * GetAddrInfoW (WS2_32.@)
4782 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
4785 char *nodenameA, *servnameA = NULL;
4786 struct WS_addrinfo *resA, *hintsA = NULL;
4788 if (!nodename) return WSAHOST_NOT_FOUND;
4790 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
4791 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
4792 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
4796 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
4797 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
4799 HeapFree(GetProcessHeap(), 0, nodenameA);
4802 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
4805 if (hints) hintsA = addrinfo_WtoA(hints);
4806 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
4807 WS_freeaddrinfo(hintsA);
4811 *res = addrinfo_list_AtoW(resA);
4812 WS_freeaddrinfo(resA);
4815 HeapFree(GetProcessHeap(), 0, nodenameA);
4816 HeapFree(GetProcessHeap(), 0, servnameA);
4820 /***********************************************************************
4821 * FreeAddrInfoW (WS2_32.@)
4823 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
4828 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
4829 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
4831 HeapFree(GetProcessHeap(), 0, ai);
4836 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
4837 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
4839 #ifdef HAVE_GETNAMEINFO
4841 union generic_unix_sockaddr sa_u;
4844 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
4845 serv, servlen, flags);
4847 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
4850 WSASetLastError(WSAEFAULT);
4851 return WSA_NOT_ENOUGH_MEMORY;
4853 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
4854 return convert_eai_u2w(ret);
4856 FIXME("getnameinfo() failed, not found during buildtime.\n");
4861 /***********************************************************************
4862 * getservbyport (WS2_32.56)
4864 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
4866 struct WS_servent* retval = NULL;
4867 #ifdef HAVE_GETSERVBYPORT
4868 struct servent* serv;
4869 char *proto_str = NULL;
4871 if (proto && *proto)
4873 if (!(proto_str = strdup_lower(proto))) return NULL;
4875 EnterCriticalSection( &csWSgetXXXbyYYY );
4876 if( (serv = getservbyport(port, proto_str)) != NULL ) {
4877 retval = WS_dup_se(serv);
4879 else SetLastError(WSANO_DATA);
4880 LeaveCriticalSection( &csWSgetXXXbyYYY );
4881 HeapFree( GetProcessHeap(), 0, proto_str );
4883 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
4888 /***********************************************************************
4889 * gethostname (WS2_32.57)
4891 int WINAPI WS_gethostname(char *name, int namelen)
4893 TRACE("name %p, len %d\n", name, namelen);
4895 if (gethostname(name, namelen) == 0)
4897 TRACE("<- '%s'\n", name);
4900 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
4901 TRACE("<- ERROR !\n");
4902 return SOCKET_ERROR;
4906 /* ------------------------------------- Windows sockets extensions -- *
4908 * ------------------------------------------------------------------- */
4910 /***********************************************************************
4911 * WSAEnumNetworkEvents (WS2_32.36)
4913 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
4917 int errors[FD_MAX_EVENTS];
4919 TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
4921 SERVER_START_REQ( get_socket_event )
4923 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
4924 req->service = TRUE;
4925 req->c_event = wine_server_obj_handle( hEvent );
4926 wine_server_set_reply( req, errors, sizeof(errors) );
4927 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
4932 for (i = 0; i < FD_MAX_EVENTS; i++)
4933 lpEvent->iErrorCode[i] = NtStatusToWSAError(errors[i]);
4936 SetLastError(WSAEINVAL);
4937 return SOCKET_ERROR;
4940 /***********************************************************************
4941 * WSAEventSelect (WS2_32.39)
4943 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
4947 TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
4949 SERVER_START_REQ( set_socket_event )
4951 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
4953 req->event = wine_server_obj_handle( hEvent );
4956 ret = wine_server_call( req );
4960 SetLastError(WSAEINVAL);
4961 return SOCKET_ERROR;
4964 /**********************************************************************
4965 * WSAGetOverlappedResult (WS2_32.40)
4967 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
4968 LPDWORD lpcbTransfer, BOOL fWait,
4973 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
4974 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
4976 if ( lpOverlapped == NULL )
4978 ERR( "Invalid pointer\n" );
4979 WSASetLastError(WSA_INVALID_PARAMETER);
4983 status = lpOverlapped->Internal;
4984 if (status == STATUS_PENDING)
4988 SetLastError( WSA_IO_INCOMPLETE );
4992 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
4993 INFINITE ) == WAIT_FAILED)
4995 status = lpOverlapped->Internal;
4999 *lpcbTransfer = lpOverlapped->InternalHigh;
5002 *lpdwFlags = lpOverlapped->u.s.Offset;
5004 if (status) SetLastError( RtlNtStatusToDosError(status) );
5009 /***********************************************************************
5010 * WSAAsyncSelect (WS2_32.101)
5012 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
5016 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
5018 SERVER_START_REQ( set_socket_event )
5020 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5023 req->window = wine_server_user_handle( hWnd );
5025 ret = wine_server_call( req );
5029 SetLastError(WSAEINVAL);
5030 return SOCKET_ERROR;
5033 /***********************************************************************
5034 * WSACreateEvent (WS2_32.31)
5037 WSAEVENT WINAPI WSACreateEvent(void)
5039 /* Create a manual-reset event, with initial state: unsignaled */
5042 return CreateEventW(NULL, TRUE, FALSE, NULL);
5045 /***********************************************************************
5046 * WSACloseEvent (WS2_32.29)
5049 BOOL WINAPI WSACloseEvent(WSAEVENT event)
5051 TRACE ("event=%p\n", event);
5053 return CloseHandle(event);
5056 /***********************************************************************
5057 * WSASocketA (WS2_32.78)
5060 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
5061 LPWSAPROTOCOL_INFOA lpProtocolInfo,
5062 GROUP g, DWORD dwFlags)
5065 WSAPROTOCOL_INFOW info;
5067 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
5068 af, type, protocol, lpProtocolInfo, g, dwFlags);
5070 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
5072 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
5073 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
5074 info.szProtocol, WSAPROTOCOL_LEN + 1);
5078 WSASetLastError( WSAEINVAL);
5079 return SOCKET_ERROR;
5082 return WSASocketW(af, type, protocol, &info, g, dwFlags);
5085 /***********************************************************************
5086 * WSASocketW (WS2_32.79)
5089 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
5090 LPWSAPROTOCOL_INFOW lpProtocolInfo,
5091 GROUP g, DWORD dwFlags)
5096 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
5097 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
5100 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
5101 af, type, protocol, lpProtocolInfo, g, dwFlags );
5103 /* hack for WSADuplicateSocket */
5104 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
5105 ret = lpProtocolInfo->dwCatalogEntryId;
5106 TRACE("\tgot duplicate %04lx\n", ret);
5110 /* convert the socket family and type */
5111 af = convert_af_w2u(af);
5112 type = convert_socktype_w2u(type);
5116 if (af == FROM_PROTOCOL_INFO)
5117 af = lpProtocolInfo->iAddressFamily;
5118 if (type == FROM_PROTOCOL_INFO)
5119 type = lpProtocolInfo->iSocketType;
5120 if (protocol == FROM_PROTOCOL_INFO)
5121 protocol = lpProtocolInfo->iProtocol;
5124 if ( af == AF_UNSPEC) /* did they not specify the address family? */
5128 if (type == SOCK_STREAM) { af = AF_INET; break; }
5130 if (type == SOCK_DGRAM) { af = AF_INET; break; }
5131 default: SetLastError(WSAEPROTOTYPE); return INVALID_SOCKET;
5134 SERVER_START_REQ( create_socket )
5138 req->protocol = protocol;
5139 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
5140 req->attributes = OBJ_INHERIT;
5141 req->flags = dwFlags;
5142 set_error( wine_server_call( req ) );
5143 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
5148 TRACE("\tcreated %04lx\n", ret );
5152 if (GetLastError() == WSAEACCES) /* raw socket denied */
5154 if (type == SOCK_RAW)
5155 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
5157 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
5158 SetLastError(WSAESOCKTNOSUPPORT);
5161 WARN("\t\tfailed!\n");
5162 return INVALID_SOCKET;
5165 /***********************************************************************
5166 * WSAJoinLeaf (WS2_32.58)
5169 SOCKET WINAPI WSAJoinLeaf(
5171 const struct WS_sockaddr *addr,
5173 LPWSABUF lpCallerData,
5174 LPWSABUF lpCalleeData,
5180 return INVALID_SOCKET;
5183 /***********************************************************************
5184 * __WSAFDIsSet (WS2_32.151)
5186 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
5188 int i = set->fd_count;
5190 TRACE("(%ld,%p(%i))\n", s, set, i);
5193 if (set->fd_array[i] == s) return 1;
5197 /***********************************************************************
5198 * WSAIsBlocking (WS2_32.114)
5200 BOOL WINAPI WSAIsBlocking(void)
5202 /* By default WinSock should set all its sockets to non-blocking mode
5203 * and poll in PeekMessage loop when processing "blocking" ones. This
5204 * function is supposed to tell if the program is in this loop. Our
5205 * blocking calls are truly blocking so we always return FALSE.
5207 * Note: It is allowed to call this function without prior WSAStartup().
5214 /***********************************************************************
5215 * WSACancelBlockingCall (WS2_32.113)
5217 INT WINAPI WSACancelBlockingCall(void)
5223 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
5225 FIXME("How was this called?\n");
5230 /***********************************************************************
5231 * WSASetBlockingHook (WS2_32.109)
5233 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
5235 FARPROC prev = blocking_hook;
5236 blocking_hook = lpBlockFunc;
5237 TRACE("hook %p\n", lpBlockFunc);
5242 /***********************************************************************
5243 * WSAUnhookBlockingHook (WS2_32.110)
5245 INT WINAPI WSAUnhookBlockingHook(void)
5247 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
5252 /* ----------------------------------- end of API stuff */
5254 /* ----------------------------------- helper functions -
5256 * TODO: Merge WS_dup_..() stuff into one function that
5257 * would operate with a generic structure containing internal
5258 * pointers (via a template of some kind).
5261 static int list_size(char** l, int item_size)
5266 j += (item_size) ? item_size : strlen(l[i]) + 1;
5267 j += (i + 1) * sizeof(char*); }
5271 static int list_dup(char** l_src, char** l_to, int item_size)
5276 for (i = 0; l_src[i]; i++) ;
5277 p = (char *)(l_to + i + 1);
5278 for (i = 0; l_src[i]; i++)
5280 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
5281 memcpy(p, l_src[i], count);
5286 return p - (char *)l_to;
5291 /* create a hostent entry
5293 * Creates the entry with enough memory for the name, aliases
5294 * addresses, and the address pointers. Also copies the name
5295 * and sets up all the pointers. If "fill_addresses" is set then
5296 * sufficient memory for the addresses is also allocated and the
5297 * address pointers are set to this memory.
5299 * NOTE: The alias and address lists must be allocated with room
5300 * for the NULL item terminating the list. This is true even if
5301 * the list has no items ("aliases" and "addresses" must be
5302 * at least "1", a truly empty list is invalid).
5304 static struct WS_hostent *WS_create_he(char *name, int aliases, int addresses, int fill_addresses)
5306 struct WS_hostent *p_to;
5309 int size = (sizeof(struct WS_hostent) +
5311 sizeof(char *)*aliases +
5312 sizeof(char *)*addresses);
5314 /* Allocate enough memory for the addresses */
5316 size += sizeof(struct in_addr)*addresses;
5318 if (!(p_to = check_buffer_he(size))) return NULL;
5319 memset(p_to, 0, size);
5321 p = (char *)(p_to + 1);
5326 p_to->h_aliases = (char **)p;
5327 p += sizeof(char *)*aliases;
5328 p_to->h_addr_list = (char **)p;
5329 p += sizeof(char *)*addresses;
5334 /* NOTE: h_aliases must be filled in manually, leave these
5335 * pointers NULL (already set to NULL by memset earlier).
5338 /* Fill in the list of address pointers */
5339 for (i = 0; i < addresses; i++)
5340 p_to->h_addr_list[i] = (p += sizeof(struct in_addr));
5341 p += sizeof(struct in_addr);
5346 /* duplicate hostent entry
5347 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
5348 * Ditto for protoent and servent.
5350 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
5352 int addresses = list_size(p_he->h_addr_list, p_he->h_length);
5353 int aliases = list_size(p_he->h_aliases, 0);
5354 struct WS_hostent *p_to;
5356 p_to = WS_create_he(p_he->h_name, aliases, addresses, FALSE);
5358 if (!p_to) return NULL;
5359 p_to->h_addrtype = p_he->h_addrtype;
5360 p_to->h_length = p_he->h_length;
5362 list_dup(p_he->h_aliases, p_to->h_aliases, 0);
5363 list_dup(p_he->h_addr_list, p_to->h_addr_list, p_he->h_length);
5367 /* ----- protoent */
5369 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
5372 struct WS_protoent *p_to;
5374 int size = (sizeof(*p_pe) +
5375 strlen(p_pe->p_name) + 1 +
5376 list_size(p_pe->p_aliases, 0));
5378 if (!(p_to = check_buffer_pe(size))) return NULL;
5379 p_to->p_proto = p_pe->p_proto;
5381 p = (char *)(p_to + 1);
5383 strcpy(p, p_pe->p_name);
5386 p_to->p_aliases = (char **)p;
5387 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
5393 static struct WS_servent *WS_dup_se(const struct servent* p_se)
5396 struct WS_servent *p_to;
5398 int size = (sizeof(*p_se) +
5399 strlen(p_se->s_proto) + 1 +
5400 strlen(p_se->s_name) + 1 +
5401 list_size(p_se->s_aliases, 0));
5403 if (!(p_to = check_buffer_se(size))) return NULL;
5404 p_to->s_port = p_se->s_port;
5406 p = (char *)(p_to + 1);
5408 strcpy(p, p_se->s_name);
5412 strcpy(p, p_se->s_proto);
5415 p_to->s_aliases = (char **)p;
5416 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
5421 /***********************************************************************
5422 * WSARecv (WS2_32.67)
5424 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5425 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
5426 LPWSAOVERLAPPED lpOverlapped,
5427 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
5429 return WS2_recvfrom(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
5430 NULL, NULL, lpOverlapped, lpCompletionRoutine);
5433 static int WS2_recvfrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5434 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
5435 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
5436 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5439 unsigned int i, options;
5441 struct ws2_async *wsa;
5442 DWORD timeout_start = GetTickCount();
5443 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
5445 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
5446 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
5447 (lpFromlen ? *lpFromlen : -1),
5448 lpOverlapped, lpCompletionRoutine);
5450 fd = get_sock_fd( s, FILE_READ_DATA, &options );
5451 TRACE( "fd=%d, options=%x\n", fd, options );
5453 if (fd == -1) return SOCKET_ERROR;
5455 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
5461 wsa->hSocket = SOCKET2HANDLE(s);
5462 wsa->flags = *lpFlags;
5464 wsa->addrlen.ptr = lpFromlen;
5465 wsa->n_iovecs = dwBufferCount;
5466 wsa->first_iovec = 0;
5467 for (i = 0; i < dwBufferCount; i++)
5469 /* check buffer first to trigger write watches */
5470 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
5475 wsa->iovec[i].iov_base = lpBuffers[i].buf;
5476 wsa->iovec[i].iov_len = lpBuffers[i].len;
5481 n = WS2_recv( fd, wsa );
5484 if (errno == EINTR) continue;
5485 if (errno != EAGAIN)
5487 int loc_errno = errno;
5489 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
5494 *lpNumberOfBytesRecvd = n;
5496 if ((lpOverlapped || lpCompletionRoutine) &&
5497 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
5499 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
5501 wsa->user_overlapped = lpOverlapped;
5502 wsa->completion_func = lpCompletionRoutine;
5503 release_sock_fd( s, fd );
5507 iosb->u.Status = STATUS_PENDING;
5508 iosb->Information = 0;
5510 SERVER_START_REQ( register_async )
5512 req->type = ASYNC_TYPE_READ;
5513 req->async.handle = wine_server_obj_handle( wsa->hSocket );
5514 req->async.callback = wine_server_client_ptr( WS2_async_recv );
5515 req->async.iosb = wine_server_client_ptr( iosb );
5516 req->async.arg = wine_server_client_ptr( wsa );
5517 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
5518 req->async.cvalue = cvalue;
5519 err = wine_server_call( req );
5523 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
5524 WSASetLastError( NtStatusToWSAError( err ));
5525 return SOCKET_ERROR;
5528 iosb->u.Status = STATUS_SUCCESS;
5529 iosb->Information = n;
5530 if (!wsa->completion_func)
5532 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
5533 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
5534 HeapFree( GetProcessHeap(), 0, wsa );
5536 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
5537 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
5538 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5544 if ( _is_blocking(s) )
5547 int timeout = GET_RCVTIMEO(fd);
5550 timeout -= GetTickCount() - timeout_start;
5551 if (timeout < 0) timeout = 0;
5555 pfd.events = POLLIN;
5556 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
5558 if (!timeout || !poll( &pfd, 1, timeout ))
5561 /* a timeout is not fatal */
5562 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5568 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5569 err = WSAEWOULDBLOCK;
5574 TRACE(" -> %i bytes\n", n);
5575 HeapFree( GetProcessHeap(), 0, wsa );
5576 release_sock_fd( s, fd );
5577 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5582 HeapFree( GetProcessHeap(), 0, wsa );
5583 release_sock_fd( s, fd );
5584 WARN(" -> ERROR %d\n", err);
5585 WSASetLastError( err );
5586 return SOCKET_ERROR;
5589 /***********************************************************************
5590 * WSARecvFrom (WS2_32.69)
5592 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5593 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
5594 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
5595 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5598 return WS2_recvfrom( s, lpBuffers, dwBufferCount,
5599 lpNumberOfBytesRecvd, lpFlags,
5601 lpOverlapped, lpCompletionRoutine );
5604 /***********************************************************************
5605 * WSCInstallProvider (WS2_32.88)
5607 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
5608 LPCWSTR lpszProviderDllPath,
5609 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
5610 DWORD dwNumberOfEntries,
5613 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
5614 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
5615 dwNumberOfEntries, lpErrno);
5621 /***********************************************************************
5622 * WSCDeinstallProvider (WS2_32.83)
5624 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
5626 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
5632 /***********************************************************************
5633 * WSAAccept (WS2_32.26)
5635 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
5636 LPCONDITIONPROC lpfnCondition, DWORD dwCallbackData)
5639 int ret = 0, size = 0;
5640 WSABUF CallerId, CallerData, CalleeId, CalleeData;
5641 /* QOS SQOS, GQOS; */
5644 SOCKADDR src_addr, dst_addr;
5646 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %d\n",
5647 s, addr, addrlen, lpfnCondition, dwCallbackData);
5650 size = sizeof(src_addr);
5651 cs = WS_accept(s, &src_addr, &size);
5653 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
5655 if (!lpfnCondition) return cs;
5657 CallerId.buf = (char *)&src_addr;
5658 CallerId.len = sizeof(src_addr);
5660 CallerData.buf = NULL;
5663 WS_getsockname(cs, &dst_addr, &size);
5665 CalleeId.buf = (char *)&dst_addr;
5666 CalleeId.len = sizeof(dst_addr);
5669 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
5670 &CalleeId, &CalleeData, &g, dwCallbackData);
5675 if (addr && addrlen)
5676 addr = memcpy(addr, &src_addr, (*addrlen > size) ? size : *addrlen );
5679 SERVER_START_REQ( set_socket_deferred )
5681 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5682 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
5683 if ( !wine_server_call_err ( req ) )
5685 SetLastError( WSATRY_AGAIN );
5686 WS_closesocket( cs );
5690 return SOCKET_ERROR;
5693 SetLastError(WSAECONNREFUSED);
5694 return SOCKET_ERROR;
5696 FIXME("Unknown return type from Condition function\n");
5697 SetLastError(WSAENOTSOCK);
5698 return SOCKET_ERROR;
5702 /***********************************************************************
5703 * WSADuplicateSocketA (WS2_32.32)
5705 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
5709 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
5710 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
5711 /* FIXME: WS_getsockopt(s, WS_SOL_SOCKET, SO_PROTOCOL_INFO, lpProtocolInfo, sizeof(*lpProtocolInfo)); */
5712 /* I don't know what the real Windoze does next, this is a hack */
5713 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
5714 * the target use the global duplicate, or we could copy a reference to us to the structure
5715 * and let the target duplicate it from us, but let's do it as simple as possible */
5716 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
5717 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
5718 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
5719 0, FALSE, DUPLICATE_SAME_ACCESS);
5720 CloseHandle(hProcess);
5721 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
5725 /***********************************************************************
5726 * WSADuplicateSocketW (WS2_32.33)
5728 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
5732 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
5734 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
5735 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
5736 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
5737 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
5738 0, FALSE, DUPLICATE_SAME_ACCESS);
5739 CloseHandle(hProcess);
5740 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
5744 /***********************************************************************
5745 * WSAInstallServiceClassA (WS2_32.48)
5747 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
5749 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
5750 WSASetLastError(WSAEACCES);
5751 return SOCKET_ERROR;
5754 /***********************************************************************
5755 * WSAInstallServiceClassW (WS2_32.49)
5757 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
5759 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
5760 WSASetLastError(WSAEACCES);
5761 return SOCKET_ERROR;
5764 /***********************************************************************
5765 * WSARemoveServiceClass (WS2_32.70)
5767 int WINAPI WSARemoveServiceClass(LPGUID info)
5769 FIXME("Request to remove service %p\n",info);
5770 WSASetLastError(WSATYPE_NOT_FOUND);
5771 return SOCKET_ERROR;
5774 /***********************************************************************
5775 * inet_ntop (WS2_32.@)
5777 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
5779 #ifdef HAVE_INET_NTOP
5780 struct WS_in6_addr *in6;
5781 struct WS_in_addr *in;
5784 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
5787 WSASetLastError( STATUS_INVALID_PARAMETER );
5796 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
5802 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
5806 WSASetLastError( WSAEAFNOSUPPORT );
5810 if (!pdst) WSASetLastError( STATUS_INVALID_PARAMETER );
5813 FIXME( "not supported on this platform\n" );
5814 WSASetLastError( WSAEAFNOSUPPORT );
5819 /***********************************************************************
5820 * WSAStringToAddressA (WS2_32.80)
5822 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
5824 LPWSAPROTOCOL_INFOA lpProtocolInfo,
5825 LPSOCKADDR lpAddress,
5826 LPINT lpAddressLength)
5829 LPSTR workBuffer=NULL,ptrPort;
5831 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
5832 lpProtocolInfo, lpAddress, lpAddressLength );
5834 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
5838 WSASetLastError(WSAEINVAL);
5839 return SOCKET_ERROR;
5843 FIXME("ProtocolInfo not implemented.\n");
5845 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
5846 strlen(AddressString) + 1);
5849 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5850 return SOCKET_ERROR;
5853 strcpy(workBuffer, AddressString);
5855 switch(AddressFamily)
5859 struct in_addr inetaddr;
5861 /* If lpAddressLength is too small, tell caller the size we need */
5862 if (*lpAddressLength < sizeof(SOCKADDR_IN))
5864 *lpAddressLength = sizeof(SOCKADDR_IN);
5868 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
5870 ((LPSOCKADDR_IN)lpAddress)->sin_family = AF_INET;
5872 ptrPort = strchr(workBuffer, ':');
5875 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
5880 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
5883 if(inet_aton(workBuffer, &inetaddr) > 0)
5885 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
5896 struct in6_addr inetaddr;
5897 /* If lpAddressLength is too small, tell caller the size we need */
5898 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
5900 *lpAddressLength = sizeof(SOCKADDR_IN6);
5904 #ifdef HAVE_INET_PTON
5905 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
5907 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
5909 /* This one is a bit tricky. An IPv6 address contains colons, so the
5910 * check from IPv4 doesn't work like that. However, IPv6 addresses that
5911 * contain a port are written with braces like [fd12:3456:7890::1]:12345
5912 * so what we will do is to look for ']', check if the next char is a
5913 * colon, and if it is, parse the port as in IPv4. */
5915 ptrPort = strchr(workBuffer, ']');
5916 if(ptrPort && *(++ptrPort) == ':')
5918 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort+1));
5923 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
5926 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
5928 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
5929 sizeof(struct in6_addr));
5933 #endif /* HAVE_INET_PTON */
5939 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
5940 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
5944 HeapFree(GetProcessHeap(), 0, workBuffer);
5947 WSASetLastError(res);
5948 return SOCKET_ERROR;
5951 /***********************************************************************
5952 * WSAStringToAddressW (WS2_32.81)
5954 * Does anybody know if this functions allows to use hebrew/arabic/chinese... digits?
5955 * If this should be the case, it would be required to map these digits
5956 * to Unicode digits (0-9) using FoldString first.
5958 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
5960 LPWSAPROTOCOL_INFOW lpProtocolInfo,
5961 LPSOCKADDR lpAddress,
5962 LPINT lpAddressLength)
5965 LPSTR workBuffer=NULL;
5966 WSAPROTOCOL_INFOA infoA;
5967 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
5969 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
5970 lpAddress, lpAddressLength );
5972 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
5974 /* if ProtocolInfo is available - convert to ANSI variant */
5977 lpProtoInfoA = &infoA;
5978 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
5980 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
5981 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
5983 WSASetLastError( WSAEINVAL);
5984 return SOCKET_ERROR;
5990 /* Translate AddressString to ANSI code page - assumes that only
5991 standard digits 0-9 are used with this API call */
5992 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
5993 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
5997 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
5998 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
5999 lpAddress,lpAddressLength);
6000 HeapFree( GetProcessHeap(), 0, workBuffer );
6004 res = WSA_NOT_ENOUGH_MEMORY;
6009 WSASetLastError(res);
6010 return SOCKET_ERROR;
6013 /***********************************************************************
6014 * WSAAddressToStringA (WS2_32.27)
6016 * See WSAAddressToStringW
6018 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
6019 LPWSAPROTOCOL_INFOA info, LPSTR string,
6023 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
6026 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
6028 if (!sockaddr) return SOCKET_ERROR;
6029 if (!string || !lenstr) return SOCKET_ERROR;
6031 switch(sockaddr->sa_family)
6034 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
6035 sprintf( buffer, "%u.%u.%u.%u:%u",
6036 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
6037 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
6038 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
6039 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
6040 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
6042 p = strchr( buffer, ':' );
6043 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
6048 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
6051 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
6052 if ((sockaddr6->sin6_port))
6053 strcpy(buffer, "[");
6054 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, buffer+strlen(buffer), sizeof(buffer)))
6056 WSASetLastError(WSAEINVAL);
6057 return SOCKET_ERROR;
6059 if ((sockaddr6->sin6_scope_id))
6060 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
6061 if ((sockaddr6->sin6_port))
6062 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
6067 WSASetLastError(WSAEINVAL);
6068 return SOCKET_ERROR;
6071 size = strlen( buffer ) + 1;
6076 WSASetLastError(WSAEFAULT);
6077 return SOCKET_ERROR;
6081 strcpy( string, buffer );
6085 /***********************************************************************
6086 * WSAAddressToStringW (WS2_32.28)
6088 * Convert a sockaddr address into a readable address string.
6091 * sockaddr [I] Pointer to a sockaddr structure.
6092 * len [I] Size of the sockaddr structure.
6093 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
6094 * string [I/O] Pointer to a buffer to receive the address string.
6095 * lenstr [I/O] Size of the receive buffer in WCHARs.
6099 * Failure: SOCKET_ERROR
6102 * The 'info' parameter is ignored.
6104 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
6105 LPWSAPROTOCOL_INFOW info, LPWSTR string,
6110 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
6113 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
6116 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
6118 if (ret) return ret;
6120 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
6125 WSASetLastError(WSAEFAULT);
6126 return SOCKET_ERROR;
6130 lstrcpyW( string, buffer );
6134 /***********************************************************************
6135 * WSAEnumNameSpaceProvidersA (WS2_32.34)
6137 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
6139 FIXME( "(%p %p) Stub!\n", len, buffer );
6143 /***********************************************************************
6144 * WSAEnumNameSpaceProvidersW (WS2_32.35)
6146 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
6148 FIXME( "(%p %p) Stub!\n", len, buffer );
6152 /***********************************************************************
6153 * WSAGetQOSByName (WS2_32.41)
6155 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
6157 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
6161 /***********************************************************************
6162 * WSAGetServiceClassInfoA (WS2_32.42)
6164 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
6165 LPWSASERVICECLASSINFOA info )
6167 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
6169 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6170 return SOCKET_ERROR;
6173 /***********************************************************************
6174 * WSAGetServiceClassInfoW (WS2_32.43)
6176 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
6177 LPWSASERVICECLASSINFOW info )
6179 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
6181 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6182 return SOCKET_ERROR;
6185 /***********************************************************************
6186 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
6188 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
6190 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
6191 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6192 return SOCKET_ERROR;
6195 /***********************************************************************
6196 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
6198 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
6200 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
6201 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6202 return SOCKET_ERROR;
6205 /***********************************************************************
6206 * WSALookupServiceBeginA (WS2_32.59)
6208 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
6209 DWORD dwControlFlags,
6212 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
6214 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6215 return SOCKET_ERROR;
6218 /***********************************************************************
6219 * WSALookupServiceBeginW (WS2_32.60)
6221 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
6222 DWORD dwControlFlags,
6225 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
6227 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6228 return SOCKET_ERROR;
6231 /***********************************************************************
6232 * WSALookupServiceBeginW (WS2_32.61)
6234 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
6236 FIXME("(%p) Stub!\n", lookup );
6240 /***********************************************************************
6241 * WSALookupServiceNextA (WS2_32.62)
6243 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
6245 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
6249 /***********************************************************************
6250 * WSALookupServiceNextW (WS2_32.63)
6252 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
6254 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
6258 /***********************************************************************
6259 * WSANtohl (WS2_32.64)
6261 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
6263 TRACE( "(0x%04lx 0x%08x %p)\n", s, netlong, lphostlong );
6265 if (!lphostlong) return WSAEFAULT;
6267 *lphostlong = ntohl( netlong );
6271 /***********************************************************************
6272 * WSANtohs (WS2_32.65)
6274 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
6276 TRACE( "(0x%04lx 0x%08x %p)\n", s, netshort, lphostshort );
6278 if (!lphostshort) return WSAEFAULT;
6280 *lphostshort = ntohs( netshort );
6284 /***********************************************************************
6285 * WSAProviderConfigChange (WS2_32.66)
6287 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
6288 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
6290 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
6291 return SOCKET_ERROR;
6294 /***********************************************************************
6295 * WSARecvDisconnect (WS2_32.68)
6297 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
6299 TRACE( "(0x%04lx %p)\n", s, disconnectdata );
6301 return WS_shutdown( s, 0 );
6304 /***********************************************************************
6305 * WSASetServiceA (WS2_32.76)
6307 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
6309 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
6313 /***********************************************************************
6314 * WSASetServiceW (WS2_32.77)
6316 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
6318 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
6322 /***********************************************************************
6323 * WSCEnableNSProvider (WS2_32.84)
6325 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
6327 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
6331 /***********************************************************************
6332 * WSCGetProviderPath (WS2_32.86)
6334 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
6336 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
6338 if (!errcode || !provider || !len) return WSAEFAULT;
6340 *errcode = WSAEINVAL;
6341 return SOCKET_ERROR;
6344 /***********************************************************************
6345 * WSCInstallNameSpace (WS2_32.87)
6347 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
6348 DWORD version, LPGUID provider )
6350 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
6351 namespace, version, debugstr_guid(provider) );
6355 /***********************************************************************
6356 * WSCUnInstallNameSpace (WS2_32.89)
6358 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
6360 FIXME("(%p) Stub!\n", lpProviderId);
6364 /***********************************************************************
6365 * WSCWriteProviderOrder (WS2_32.91)
6367 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
6369 FIXME("(%p 0x%08x) Stub!\n", entry, number);
6373 /***********************************************************************
6374 * WSANSPIoctl (WS2_32.91)
6376 INT WINAPI WSANSPIoctl( HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer,
6377 DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer,
6378 LPDWORD lpcbBytesReturned, LPWSACOMPLETION lpCompletion )
6380 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup, dwControlCode,
6381 lpvInBuffer, cbInBuffer, lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpCompletion);
6382 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6383 return SOCKET_ERROR;