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 static 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 static 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 /* After a AcceptEx call succeeds, the socket can't be used with half of the
3945 * normal winsock functions on windows. We don't have that problem. */
3946 case WS_SO_UPDATE_ACCEPT_CONTEXT:
3947 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
3950 /* SO_OPENTYPE does not require a valid socket handle. */
3951 case WS_SO_OPENTYPE:
3952 if (!optlen || optlen < sizeof(int) || !optval)
3954 SetLastError(WSAEFAULT);
3955 return SOCKET_ERROR;
3957 get_per_thread_data()->opentype = *(const int *)optval;
3958 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
3962 case WS_SO_RCVTIMEO:
3965 case WS_SO_SNDTIMEO:
3967 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
3968 if (optval && optlen == sizeof(UINT32)) {
3969 /* WinSock passes milliseconds instead of struct timeval */
3970 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
3971 tval.tv_sec = *(const UINT32*)optval / 1000;
3972 /* min of 500 milliseconds */
3973 if (tval.tv_sec == 0 && tval.tv_usec && tval.tv_usec < 500000)
3974 tval.tv_usec = 500000;
3975 optlen = sizeof(struct timeval);
3976 optval = (char*)&tval;
3977 } else if (optlen == sizeof(struct timeval)) {
3978 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
3980 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
3983 convert_sockopt(&level, &optname);
3988 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
3989 SetLastError(WSAENOPROTOOPT);
3990 return SOCKET_ERROR;
3992 break; /* case WS_SOL_SOCKET */
3999 fd = get_sock_fd( s, 0, NULL );
4000 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", *(const int*)optval, fd);
4002 /* We try to set the ipx type on ipx socket level. */
4004 if(setsockopt(fd, SOL_IPX, IPX_TYPE, optval, optlen) == -1)
4006 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
4007 release_sock_fd( s, fd );
4008 return SOCKET_ERROR;
4013 /* Should we retrieve val using a getsockopt call and then
4014 * set the modified one? */
4015 val.ipx_pt = *optval;
4016 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
4019 release_sock_fd( s, fd );
4022 case IPX_FILTERPTYPE:
4023 /* Sets the receive filter packet type, at the moment we don't support it */
4024 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
4025 /* Returning 0 is better for now than returning a SOCKET_ERROR */
4029 FIXME("opt_name:%x\n", optname);
4030 return SOCKET_ERROR;
4032 break; /* case NSPROTO_IPX */
4035 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
4036 case WS_IPPROTO_TCP:
4039 case WS_TCP_NODELAY:
4040 convert_sockopt(&level, &optname);
4043 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
4044 return SOCKET_ERROR;
4051 case WS_IP_ADD_MEMBERSHIP:
4052 case WS_IP_DROP_MEMBERSHIP:
4056 case WS_IP_MULTICAST_IF:
4057 case WS_IP_MULTICAST_LOOP:
4058 case WS_IP_MULTICAST_TTL:
4062 convert_sockopt(&level, &optname);
4064 case WS_IP_DONTFRAGMENT:
4065 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
4068 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
4069 return SOCKET_ERROR;
4073 case WS_IPPROTO_IPV6:
4076 #ifdef IPV6_ADD_MEMBERSHIP
4077 case WS_IPV6_ADD_MEMBERSHIP:
4079 #ifdef IPV6_DROP_MEMBERSHIP
4080 case WS_IPV6_DROP_MEMBERSHIP:
4082 case WS_IPV6_MULTICAST_IF:
4083 case WS_IPV6_MULTICAST_HOPS:
4084 case WS_IPV6_MULTICAST_LOOP:
4085 case WS_IPV6_UNICAST_HOPS:
4086 case WS_IPV6_V6ONLY:
4087 convert_sockopt(&level, &optname);
4089 case WS_IPV6_DONTFRAG:
4090 FIXME("IPV6_DONTFRAG is silently ignored!\n");
4093 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
4094 return SOCKET_ERROR;
4099 WARN("Unknown level: 0x%08x\n", level);
4100 SetLastError(WSAEINVAL);
4101 return SOCKET_ERROR;
4102 } /* end switch(level) */
4104 /* avoid endianness issues if argument is a 16-bit int */
4105 if (optval && optlen < sizeof(int))
4107 woptval= *((const INT16 *) optval);
4108 optval= (char*) &woptval;
4111 fd = get_sock_fd( s, 0, NULL );
4112 if (fd == -1) return SOCKET_ERROR;
4114 if (setsockopt(fd, level, optname, optval, optlen) == 0)
4116 release_sock_fd( s, fd );
4119 TRACE("Setting socket error, %d\n", wsaErrno());
4120 SetLastError(wsaErrno());
4121 release_sock_fd( s, fd );
4123 return SOCKET_ERROR;
4126 /***********************************************************************
4127 * shutdown (WS2_32.22)
4129 int WINAPI WS_shutdown(SOCKET s, int how)
4131 int fd, err = WSAENOTSOCK;
4132 unsigned int options, clear_flags = 0;
4134 fd = get_sock_fd( s, 0, &options );
4135 TRACE("socket %04lx, how %i %x\n", s, how, options );
4138 return SOCKET_ERROR;
4142 case 0: /* drop receives */
4143 clear_flags |= FD_READ;
4145 case 1: /* drop sends */
4146 clear_flags |= FD_WRITE;
4148 case 2: /* drop all */
4149 clear_flags |= FD_READ|FD_WRITE;
4151 clear_flags |= FD_WINE_LISTENING;
4154 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
4159 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
4162 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
4166 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
4167 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
4170 if (err) goto error;
4172 else /* non-overlapped mode */
4174 if ( shutdown( fd, how ) )
4181 release_sock_fd( s, fd );
4182 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
4183 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
4187 release_sock_fd( s, fd );
4188 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
4189 WSASetLastError( err );
4190 return SOCKET_ERROR;
4193 /***********************************************************************
4194 * socket (WS2_32.23)
4196 SOCKET WINAPI WS_socket(int af, int type, int protocol)
4198 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
4200 return WSASocketA( af, type, protocol, NULL, 0,
4201 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
4205 /***********************************************************************
4206 * gethostbyaddr (WS2_32.51)
4208 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
4210 struct WS_hostent *retval = NULL;
4211 struct hostent* host;
4213 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4216 struct hostent hostentry;
4219 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
4221 int res = gethostbyaddr_r(addr, len, type,
4222 &hostentry, extrabuf, ebufsize, &host, &locerr);
4223 if( res != ERANGE) break;
4225 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
4227 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
4229 EnterCriticalSection( &csWSgetXXXbyYYY );
4230 host = gethostbyaddr(addr, len, type);
4231 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
4233 if( host != NULL ) retval = WS_dup_he(host);
4234 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4235 HeapFree(GetProcessHeap(),0,extrabuf);
4237 LeaveCriticalSection( &csWSgetXXXbyYYY );
4239 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
4243 /***********************************************************************
4244 * WS_get_local_ips (INTERNAL)
4246 * Returns the list of local IP addresses by going through the network
4247 * adapters and using the local routing table to sort the addresses
4248 * from highest routing priority to lowest routing priority. This
4249 * functionality is inferred from the description for obtaining local
4250 * IP addresses given in the Knowledge Base Article Q160215.
4252 * Please note that the returned hostent is only freed when the thread
4253 * closes and is replaced if another hostent is requested.
4255 static struct WS_hostent* WS_get_local_ips( char *hostname )
4257 int last_metric, numroutes = 0, i, j;
4258 PIP_ADAPTER_INFO adapters = NULL, k;
4259 struct WS_hostent *hostlist = NULL;
4260 PMIB_IPFORWARDTABLE routes = NULL;
4261 struct route *route_addrs = NULL;
4262 DWORD adap_size, route_size;
4264 /* Obtain the size of the adapter list and routing table, also allocate memory */
4265 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
4267 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
4269 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
4270 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
4271 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
4272 if (adapters == NULL || routes == NULL || route_addrs == NULL)
4274 /* Obtain the adapter list and the full routing table */
4275 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
4277 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
4279 /* Store the interface associated with each route */
4280 for (i = 0; i < routes->dwNumEntries; i++)
4282 DWORD ifindex, ifmetric, exists = FALSE;
4284 if (routes->table[i].dwForwardType != MIB_IPROUTE_TYPE_DIRECT)
4286 ifindex = routes->table[i].dwForwardIfIndex;
4287 ifmetric = routes->table[i].dwForwardMetric1;
4288 /* Only store the lowest valued metric for an interface */
4289 for (j = 0; j < numroutes; j++)
4291 if (route_addrs[j].interface == ifindex)
4293 if (route_addrs[j].metric > ifmetric)
4294 route_addrs[j].metric = ifmetric;
4300 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
4301 if (route_addrs == NULL)
4302 goto cleanup; /* Memory allocation error, fail gracefully */
4303 route_addrs[numroutes].interface = ifindex;
4304 route_addrs[numroutes].metric = ifmetric;
4305 /* If no IP is found in the next step (for whatever reason)
4306 * then fall back to the magic loopback address.
4308 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
4312 goto cleanup; /* No routes, fall back to the Magic IP */
4313 /* Find the IP address associated with each found interface */
4314 for (i = 0; i < numroutes; i++)
4316 for (k = adapters; k != NULL; k = k->Next)
4318 char *ip = k->IpAddressList.IpAddress.String;
4320 if (route_addrs[i].interface == k->Index)
4321 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
4324 /* Allocate a hostent and enough memory for all the IPs,
4325 * including the NULL at the end of the list.
4327 hostlist = WS_create_he(hostname, 1, numroutes+1, TRUE);
4328 if (hostlist == NULL)
4329 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
4330 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
4331 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
4332 hostlist->h_addrtype = AF_INET;
4333 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
4334 /* Reorder the entries when placing them in the host list, Windows expects
4335 * the IP list in order from highest priority to lowest (the critical thing
4336 * is that most applications expect the first IP to be the default route).
4339 for (i = 0; i < numroutes; i++)
4341 struct in_addr addr;
4342 int metric = 0xFFFF;
4344 memcpy(&addr, magic_loopback_addr, 4);
4345 for (j = 0; j < numroutes; j++)
4347 int this_metric = route_addrs[j].metric;
4349 if (this_metric > last_metric && this_metric < metric)
4351 addr = route_addrs[j].addr;
4352 metric = this_metric;
4355 last_metric = metric;
4356 (*(struct in_addr *) hostlist->h_addr_list[i]) = addr;
4359 /* Cleanup all allocated memory except the address list,
4360 * the address list is used by the calling app.
4363 HeapFree(GetProcessHeap(), 0, route_addrs);
4364 HeapFree(GetProcessHeap(), 0, adapters);
4365 HeapFree(GetProcessHeap(), 0, routes);
4369 /***********************************************************************
4370 * gethostbyname (WS2_32.52)
4372 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
4374 struct WS_hostent *retval = NULL;
4375 struct hostent* host;
4376 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4379 struct hostent hostentry;
4380 int locerr = ENOBUFS;
4383 if( gethostname( hostname, 100) == -1) {
4384 SetLastError( WSAENOBUFS); /* appropriate ? */
4387 if( !name || !name[0]) {
4390 /* If the hostname of the local machine is requested then return the
4391 * complete list of local IP addresses */
4392 if(strcmp(name, hostname) == 0)
4393 retval = WS_get_local_ips(hostname);
4394 /* If any other hostname was requested (or the routing table lookup failed)
4395 * then return the IP found by the host OS */
4398 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4400 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
4402 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
4403 if( res != ERANGE) break;
4405 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
4407 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
4409 EnterCriticalSection( &csWSgetXXXbyYYY );
4410 host = gethostbyname(name);
4411 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
4413 if (host) retval = WS_dup_he(host);
4414 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4415 HeapFree(GetProcessHeap(),0,extrabuf);
4417 LeaveCriticalSection( &csWSgetXXXbyYYY );
4420 if (retval && retval->h_addr_list[0][0] == 127 &&
4421 strcmp(name, "localhost") != 0)
4423 /* hostname != "localhost" but has loopback address. replace by our
4424 * special address.*/
4425 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
4427 TRACE( "%s ret %p\n", debugstr_a(name), retval );
4432 /***********************************************************************
4433 * getprotobyname (WS2_32.53)
4435 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
4437 struct WS_protoent* retval = NULL;
4438 #ifdef HAVE_GETPROTOBYNAME
4439 struct protoent* proto;
4440 EnterCriticalSection( &csWSgetXXXbyYYY );
4441 if( (proto = getprotobyname(name)) != NULL )
4443 retval = WS_dup_pe(proto);
4446 MESSAGE("protocol %s not found; You might want to add "
4447 "this to /etc/protocols\n", debugstr_a(name) );
4448 SetLastError(WSANO_DATA);
4450 LeaveCriticalSection( &csWSgetXXXbyYYY );
4452 TRACE( "%s ret %p\n", debugstr_a(name), retval );
4457 /***********************************************************************
4458 * getprotobynumber (WS2_32.54)
4460 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
4462 struct WS_protoent* retval = NULL;
4463 #ifdef HAVE_GETPROTOBYNUMBER
4464 struct protoent* proto;
4465 EnterCriticalSection( &csWSgetXXXbyYYY );
4466 if( (proto = getprotobynumber(number)) != NULL )
4468 retval = WS_dup_pe(proto);
4471 MESSAGE("protocol number %d not found; You might want to add "
4472 "this to /etc/protocols\n", number );
4473 SetLastError(WSANO_DATA);
4475 LeaveCriticalSection( &csWSgetXXXbyYYY );
4477 TRACE("%i ret %p\n", number, retval);
4482 /***********************************************************************
4483 * getservbyname (WS2_32.55)
4485 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
4487 struct WS_servent* retval = NULL;
4488 struct servent* serv;
4490 char *proto_str = NULL;
4492 if (!(name_str = strdup_lower(name))) return NULL;
4494 if (proto && *proto)
4496 if (!(proto_str = strdup_lower(proto)))
4498 HeapFree( GetProcessHeap(), 0, name_str );
4503 EnterCriticalSection( &csWSgetXXXbyYYY );
4504 serv = getservbyname(name_str, proto_str);
4507 retval = WS_dup_se(serv);
4509 else SetLastError(WSANO_DATA);
4510 LeaveCriticalSection( &csWSgetXXXbyYYY );
4511 HeapFree( GetProcessHeap(), 0, proto_str );
4512 HeapFree( GetProcessHeap(), 0, name_str );
4513 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
4517 /***********************************************************************
4518 * freeaddrinfo (WS2_32.@)
4520 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
4523 struct WS_addrinfo *next;
4525 HeapFree(GetProcessHeap(),0,res->ai_canonname);
4526 HeapFree(GetProcessHeap(),0,res->ai_addr);
4527 next = res->ai_next;
4528 HeapFree(GetProcessHeap(),0,res);
4533 /* helper functions for getaddrinfo()/getnameinfo() */
4534 static int convert_aiflag_w2u(int winflags) {
4538 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
4539 if (ws_aiflag_map[i][0] & winflags) {
4540 unixflags |= ws_aiflag_map[i][1];
4541 winflags &= ~ws_aiflag_map[i][0];
4544 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
4548 static int convert_niflag_w2u(int winflags) {
4552 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
4553 if (ws_niflag_map[i][0] & winflags) {
4554 unixflags |= ws_niflag_map[i][1];
4555 winflags &= ~ws_niflag_map[i][0];
4558 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
4562 static int convert_aiflag_u2w(int unixflags) {
4566 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
4567 if (ws_aiflag_map[i][1] & unixflags) {
4568 winflags |= ws_aiflag_map[i][0];
4569 unixflags &= ~ws_aiflag_map[i][1];
4571 if (unixflags) /* will warn usually */
4572 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
4576 static int convert_eai_u2w(int unixret) {
4579 for (i=0;ws_eai_map[i][0];i++)
4580 if (ws_eai_map[i][1] == unixret)
4581 return ws_eai_map[i][0];
4585 /***********************************************************************
4586 * getaddrinfo (WS2_32.@)
4588 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
4590 #ifdef HAVE_GETADDRINFO
4591 struct addrinfo *unixaires = NULL;
4593 struct addrinfo unixhints, *punixhints = NULL;
4594 CHAR *node = NULL, *serv = NULL;
4597 if (!(node = strdup_lower(nodename))) return WSA_NOT_ENOUGH_MEMORY;
4600 if (!(serv = strdup_lower(servname))) {
4601 HeapFree(GetProcessHeap(), 0, node);
4602 return WSA_NOT_ENOUGH_MEMORY;
4607 punixhints = &unixhints;
4609 memset(&unixhints, 0, sizeof(unixhints));
4610 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
4611 if (hints->ai_family == 0) /* wildcard, specific to getaddrinfo() */
4612 punixhints->ai_family = 0;
4614 punixhints->ai_family = convert_af_w2u(hints->ai_family);
4615 if (hints->ai_socktype == 0) /* wildcard, specific to getaddrinfo() */
4616 punixhints->ai_socktype = 0;
4618 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
4619 if (hints->ai_protocol == 0) /* wildcard, specific to getaddrinfo() */
4620 punixhints->ai_protocol = 0;
4622 punixhints->ai_protocol = convert_proto_w2u(hints->ai_protocol);
4625 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
4626 result = getaddrinfo(nodename, servname, punixhints, &unixaires);
4628 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
4630 HeapFree(GetProcessHeap(), 0, node);
4631 HeapFree(GetProcessHeap(), 0, serv);
4634 struct addrinfo *xuai = unixaires;
4635 struct WS_addrinfo **xai = res;
4639 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
4645 *xai = ai;xai = &ai->ai_next;
4646 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
4647 ai->ai_family = convert_af_u2w(xuai->ai_family);
4648 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
4649 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
4650 if (xuai->ai_canonname) {
4651 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
4652 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
4653 if (!ai->ai_canonname)
4655 strcpy(ai->ai_canonname,xuai->ai_canonname);
4657 len = xuai->ai_addrlen;
4658 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
4661 ai->ai_addrlen = len;
4663 int winlen = ai->ai_addrlen;
4665 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
4666 ai->ai_addrlen = winlen;
4670 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
4673 ai->ai_addrlen = len;
4675 xuai = xuai->ai_next;
4677 freeaddrinfo(unixaires);
4679 result = convert_eai_u2w(result);
4685 if (*res) WS_freeaddrinfo(*res);
4686 if (unixaires) freeaddrinfo(unixaires);
4688 return WSA_NOT_ENOUGH_MEMORY;
4690 FIXME("getaddrinfo() failed, not found during buildtime.\n");
4695 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
4697 struct WS_addrinfoW *ret;
4699 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
4700 ret->ai_flags = ai->ai_flags;
4701 ret->ai_family = ai->ai_family;
4702 ret->ai_socktype = ai->ai_socktype;
4703 ret->ai_protocol = ai->ai_protocol;
4704 ret->ai_addrlen = ai->ai_addrlen;
4705 ret->ai_canonname = NULL;
4706 ret->ai_addr = NULL;
4707 ret->ai_next = NULL;
4708 if (ai->ai_canonname)
4710 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
4711 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
4713 HeapFree(GetProcessHeap(), 0, ret);
4716 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
4720 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
4722 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
4723 HeapFree(GetProcessHeap(), 0, ret);
4726 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
4731 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
4733 struct WS_addrinfoW *ret, *infoW;
4735 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
4736 while (info->ai_next)
4738 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
4743 infoW = infoW->ai_next;
4744 info = info->ai_next;
4749 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
4751 struct WS_addrinfo *ret;
4753 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
4754 ret->ai_flags = ai->ai_flags;
4755 ret->ai_family = ai->ai_family;
4756 ret->ai_socktype = ai->ai_socktype;
4757 ret->ai_protocol = ai->ai_protocol;
4758 ret->ai_addrlen = ai->ai_addrlen;
4759 ret->ai_canonname = NULL;
4760 ret->ai_addr = NULL;
4761 ret->ai_next = NULL;
4762 if (ai->ai_canonname)
4764 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
4765 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
4767 HeapFree(GetProcessHeap(), 0, ret);
4770 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
4774 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
4776 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
4777 HeapFree(GetProcessHeap(), 0, ret);
4780 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
4785 /***********************************************************************
4786 * GetAddrInfoW (WS2_32.@)
4788 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
4791 char *nodenameA, *servnameA = NULL;
4792 struct WS_addrinfo *resA, *hintsA = NULL;
4794 if (!nodename) return WSAHOST_NOT_FOUND;
4796 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
4797 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
4798 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
4802 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
4803 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
4805 HeapFree(GetProcessHeap(), 0, nodenameA);
4808 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
4811 if (hints) hintsA = addrinfo_WtoA(hints);
4812 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
4813 WS_freeaddrinfo(hintsA);
4817 *res = addrinfo_list_AtoW(resA);
4818 WS_freeaddrinfo(resA);
4821 HeapFree(GetProcessHeap(), 0, nodenameA);
4822 HeapFree(GetProcessHeap(), 0, servnameA);
4826 /***********************************************************************
4827 * FreeAddrInfoW (WS2_32.@)
4829 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
4834 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
4835 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
4837 HeapFree(GetProcessHeap(), 0, ai);
4842 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
4843 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
4845 #ifdef HAVE_GETNAMEINFO
4847 union generic_unix_sockaddr sa_u;
4850 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
4851 serv, servlen, flags);
4853 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
4856 WSASetLastError(WSAEFAULT);
4857 return WSA_NOT_ENOUGH_MEMORY;
4859 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
4860 return convert_eai_u2w(ret);
4862 FIXME("getnameinfo() failed, not found during buildtime.\n");
4867 /***********************************************************************
4868 * getservbyport (WS2_32.56)
4870 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
4872 struct WS_servent* retval = NULL;
4873 #ifdef HAVE_GETSERVBYPORT
4874 struct servent* serv;
4875 char *proto_str = NULL;
4877 if (proto && *proto)
4879 if (!(proto_str = strdup_lower(proto))) return NULL;
4881 EnterCriticalSection( &csWSgetXXXbyYYY );
4882 if( (serv = getservbyport(port, proto_str)) != NULL ) {
4883 retval = WS_dup_se(serv);
4885 else SetLastError(WSANO_DATA);
4886 LeaveCriticalSection( &csWSgetXXXbyYYY );
4887 HeapFree( GetProcessHeap(), 0, proto_str );
4889 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
4894 /***********************************************************************
4895 * gethostname (WS2_32.57)
4897 int WINAPI WS_gethostname(char *name, int namelen)
4899 TRACE("name %p, len %d\n", name, namelen);
4901 if (gethostname(name, namelen) == 0)
4903 TRACE("<- '%s'\n", name);
4906 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
4907 TRACE("<- ERROR !\n");
4908 return SOCKET_ERROR;
4912 /* ------------------------------------- Windows sockets extensions -- *
4914 * ------------------------------------------------------------------- */
4916 /***********************************************************************
4917 * WSAEnumNetworkEvents (WS2_32.36)
4919 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
4923 int errors[FD_MAX_EVENTS];
4925 TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
4927 SERVER_START_REQ( get_socket_event )
4929 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
4930 req->service = TRUE;
4931 req->c_event = wine_server_obj_handle( hEvent );
4932 wine_server_set_reply( req, errors, sizeof(errors) );
4933 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
4938 for (i = 0; i < FD_MAX_EVENTS; i++)
4939 lpEvent->iErrorCode[i] = NtStatusToWSAError(errors[i]);
4942 SetLastError(WSAEINVAL);
4943 return SOCKET_ERROR;
4946 /***********************************************************************
4947 * WSAEventSelect (WS2_32.39)
4949 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
4953 TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
4955 SERVER_START_REQ( set_socket_event )
4957 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
4959 req->event = wine_server_obj_handle( hEvent );
4962 ret = wine_server_call( req );
4966 SetLastError(WSAEINVAL);
4967 return SOCKET_ERROR;
4970 /**********************************************************************
4971 * WSAGetOverlappedResult (WS2_32.40)
4973 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
4974 LPDWORD lpcbTransfer, BOOL fWait,
4979 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
4980 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
4982 if ( lpOverlapped == NULL )
4984 ERR( "Invalid pointer\n" );
4985 WSASetLastError(WSA_INVALID_PARAMETER);
4989 status = lpOverlapped->Internal;
4990 if (status == STATUS_PENDING)
4994 SetLastError( WSA_IO_INCOMPLETE );
4998 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
4999 INFINITE ) == WAIT_FAILED)
5001 status = lpOverlapped->Internal;
5005 *lpcbTransfer = lpOverlapped->InternalHigh;
5008 *lpdwFlags = lpOverlapped->u.s.Offset;
5010 if (status) SetLastError( RtlNtStatusToDosError(status) );
5015 /***********************************************************************
5016 * WSAAsyncSelect (WS2_32.101)
5018 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
5022 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
5024 SERVER_START_REQ( set_socket_event )
5026 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5029 req->window = wine_server_user_handle( hWnd );
5031 ret = wine_server_call( req );
5035 SetLastError(WSAEINVAL);
5036 return SOCKET_ERROR;
5039 /***********************************************************************
5040 * WSACreateEvent (WS2_32.31)
5043 WSAEVENT WINAPI WSACreateEvent(void)
5045 /* Create a manual-reset event, with initial state: unsignaled */
5048 return CreateEventW(NULL, TRUE, FALSE, NULL);
5051 /***********************************************************************
5052 * WSACloseEvent (WS2_32.29)
5055 BOOL WINAPI WSACloseEvent(WSAEVENT event)
5057 TRACE ("event=%p\n", event);
5059 return CloseHandle(event);
5062 /***********************************************************************
5063 * WSASocketA (WS2_32.78)
5066 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
5067 LPWSAPROTOCOL_INFOA lpProtocolInfo,
5068 GROUP g, DWORD dwFlags)
5071 WSAPROTOCOL_INFOW info;
5073 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
5074 af, type, protocol, lpProtocolInfo, g, dwFlags);
5076 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
5078 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
5079 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
5080 info.szProtocol, WSAPROTOCOL_LEN + 1);
5084 WSASetLastError( WSAEINVAL);
5085 return SOCKET_ERROR;
5088 return WSASocketW(af, type, protocol, &info, g, dwFlags);
5091 /***********************************************************************
5092 * WSASocketW (WS2_32.79)
5095 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
5096 LPWSAPROTOCOL_INFOW lpProtocolInfo,
5097 GROUP g, DWORD dwFlags)
5102 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
5103 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
5106 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
5107 af, type, protocol, lpProtocolInfo, g, dwFlags );
5109 /* hack for WSADuplicateSocket */
5110 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
5111 ret = lpProtocolInfo->dwCatalogEntryId;
5112 TRACE("\tgot duplicate %04lx\n", ret);
5116 /* convert the socket family and type */
5117 af = convert_af_w2u(af);
5118 type = convert_socktype_w2u(type);
5122 if (af == FROM_PROTOCOL_INFO)
5123 af = lpProtocolInfo->iAddressFamily;
5124 if (type == FROM_PROTOCOL_INFO)
5125 type = lpProtocolInfo->iSocketType;
5126 if (protocol == FROM_PROTOCOL_INFO)
5127 protocol = lpProtocolInfo->iProtocol;
5130 if ( af == AF_UNSPEC) /* did they not specify the address family? */
5134 if (type == SOCK_STREAM) { af = AF_INET; break; }
5136 if (type == SOCK_DGRAM) { af = AF_INET; break; }
5137 default: SetLastError(WSAEPROTOTYPE); return INVALID_SOCKET;
5140 SERVER_START_REQ( create_socket )
5144 req->protocol = protocol;
5145 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
5146 req->attributes = OBJ_INHERIT;
5147 req->flags = dwFlags;
5148 set_error( wine_server_call( req ) );
5149 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
5154 TRACE("\tcreated %04lx\n", ret );
5158 if (GetLastError() == WSAEACCES) /* raw socket denied */
5160 if (type == SOCK_RAW)
5161 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
5163 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
5164 SetLastError(WSAESOCKTNOSUPPORT);
5167 WARN("\t\tfailed!\n");
5168 return INVALID_SOCKET;
5171 /***********************************************************************
5172 * WSAJoinLeaf (WS2_32.58)
5175 SOCKET WINAPI WSAJoinLeaf(
5177 const struct WS_sockaddr *addr,
5179 LPWSABUF lpCallerData,
5180 LPWSABUF lpCalleeData,
5186 return INVALID_SOCKET;
5189 /***********************************************************************
5190 * __WSAFDIsSet (WS2_32.151)
5192 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
5194 int i = set->fd_count;
5196 TRACE("(%ld,%p(%i))\n", s, set, i);
5199 if (set->fd_array[i] == s) return 1;
5203 /***********************************************************************
5204 * WSAIsBlocking (WS2_32.114)
5206 BOOL WINAPI WSAIsBlocking(void)
5208 /* By default WinSock should set all its sockets to non-blocking mode
5209 * and poll in PeekMessage loop when processing "blocking" ones. This
5210 * function is supposed to tell if the program is in this loop. Our
5211 * blocking calls are truly blocking so we always return FALSE.
5213 * Note: It is allowed to call this function without prior WSAStartup().
5220 /***********************************************************************
5221 * WSACancelBlockingCall (WS2_32.113)
5223 INT WINAPI WSACancelBlockingCall(void)
5229 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
5231 FIXME("How was this called?\n");
5236 /***********************************************************************
5237 * WSASetBlockingHook (WS2_32.109)
5239 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
5241 FARPROC prev = blocking_hook;
5242 blocking_hook = lpBlockFunc;
5243 TRACE("hook %p\n", lpBlockFunc);
5248 /***********************************************************************
5249 * WSAUnhookBlockingHook (WS2_32.110)
5251 INT WINAPI WSAUnhookBlockingHook(void)
5253 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
5258 /* ----------------------------------- end of API stuff */
5260 /* ----------------------------------- helper functions -
5262 * TODO: Merge WS_dup_..() stuff into one function that
5263 * would operate with a generic structure containing internal
5264 * pointers (via a template of some kind).
5267 static int list_size(char** l, int item_size)
5272 j += (item_size) ? item_size : strlen(l[i]) + 1;
5273 j += (i + 1) * sizeof(char*); }
5277 static int list_dup(char** l_src, char** l_to, int item_size)
5282 for (i = 0; l_src[i]; i++) ;
5283 p = (char *)(l_to + i + 1);
5284 for (i = 0; l_src[i]; i++)
5286 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
5287 memcpy(p, l_src[i], count);
5292 return p - (char *)l_to;
5297 /* create a hostent entry
5299 * Creates the entry with enough memory for the name, aliases
5300 * addresses, and the address pointers. Also copies the name
5301 * and sets up all the pointers. If "fill_addresses" is set then
5302 * sufficient memory for the addresses is also allocated and the
5303 * address pointers are set to this memory.
5305 * NOTE: The alias and address lists must be allocated with room
5306 * for the NULL item terminating the list. This is true even if
5307 * the list has no items ("aliases" and "addresses" must be
5308 * at least "1", a truly empty list is invalid).
5310 static struct WS_hostent *WS_create_he(char *name, int aliases, int addresses, int fill_addresses)
5312 struct WS_hostent *p_to;
5315 int size = (sizeof(struct WS_hostent) +
5317 sizeof(char *)*aliases +
5318 sizeof(char *)*addresses);
5320 /* Allocate enough memory for the addresses */
5322 size += sizeof(struct in_addr)*addresses;
5324 if (!(p_to = check_buffer_he(size))) return NULL;
5325 memset(p_to, 0, size);
5327 p = (char *)(p_to + 1);
5332 p_to->h_aliases = (char **)p;
5333 p += sizeof(char *)*aliases;
5334 p_to->h_addr_list = (char **)p;
5335 p += sizeof(char *)*addresses;
5340 /* NOTE: h_aliases must be filled in manually, leave these
5341 * pointers NULL (already set to NULL by memset earlier).
5344 /* Fill in the list of address pointers */
5345 for (i = 0; i < addresses; i++)
5346 p_to->h_addr_list[i] = (p += sizeof(struct in_addr));
5347 p += sizeof(struct in_addr);
5352 /* duplicate hostent entry
5353 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
5354 * Ditto for protoent and servent.
5356 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
5358 int addresses = list_size(p_he->h_addr_list, p_he->h_length);
5359 int aliases = list_size(p_he->h_aliases, 0);
5360 struct WS_hostent *p_to;
5362 p_to = WS_create_he(p_he->h_name, aliases, addresses, FALSE);
5364 if (!p_to) return NULL;
5365 p_to->h_addrtype = p_he->h_addrtype;
5366 p_to->h_length = p_he->h_length;
5368 list_dup(p_he->h_aliases, p_to->h_aliases, 0);
5369 list_dup(p_he->h_addr_list, p_to->h_addr_list, p_he->h_length);
5373 /* ----- protoent */
5375 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
5378 struct WS_protoent *p_to;
5380 int size = (sizeof(*p_pe) +
5381 strlen(p_pe->p_name) + 1 +
5382 list_size(p_pe->p_aliases, 0));
5384 if (!(p_to = check_buffer_pe(size))) return NULL;
5385 p_to->p_proto = p_pe->p_proto;
5387 p = (char *)(p_to + 1);
5389 strcpy(p, p_pe->p_name);
5392 p_to->p_aliases = (char **)p;
5393 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
5399 static struct WS_servent *WS_dup_se(const struct servent* p_se)
5402 struct WS_servent *p_to;
5404 int size = (sizeof(*p_se) +
5405 strlen(p_se->s_proto) + 1 +
5406 strlen(p_se->s_name) + 1 +
5407 list_size(p_se->s_aliases, 0));
5409 if (!(p_to = check_buffer_se(size))) return NULL;
5410 p_to->s_port = p_se->s_port;
5412 p = (char *)(p_to + 1);
5414 strcpy(p, p_se->s_name);
5418 strcpy(p, p_se->s_proto);
5421 p_to->s_aliases = (char **)p;
5422 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
5427 /***********************************************************************
5428 * WSARecv (WS2_32.67)
5430 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5431 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
5432 LPWSAOVERLAPPED lpOverlapped,
5433 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
5435 return WS2_recvfrom(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
5436 NULL, NULL, lpOverlapped, lpCompletionRoutine);
5439 static int WS2_recvfrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5440 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
5441 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
5442 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5445 unsigned int i, options;
5447 struct ws2_async *wsa;
5448 DWORD timeout_start = GetTickCount();
5449 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
5451 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
5452 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
5453 (lpFromlen ? *lpFromlen : -1),
5454 lpOverlapped, lpCompletionRoutine);
5456 fd = get_sock_fd( s, FILE_READ_DATA, &options );
5457 TRACE( "fd=%d, options=%x\n", fd, options );
5459 if (fd == -1) return SOCKET_ERROR;
5461 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
5467 wsa->hSocket = SOCKET2HANDLE(s);
5468 wsa->flags = *lpFlags;
5470 wsa->addrlen.ptr = lpFromlen;
5471 wsa->n_iovecs = dwBufferCount;
5472 wsa->first_iovec = 0;
5473 for (i = 0; i < dwBufferCount; i++)
5475 /* check buffer first to trigger write watches */
5476 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
5481 wsa->iovec[i].iov_base = lpBuffers[i].buf;
5482 wsa->iovec[i].iov_len = lpBuffers[i].len;
5487 n = WS2_recv( fd, wsa );
5490 if (errno == EINTR) continue;
5491 if (errno != EAGAIN)
5493 int loc_errno = errno;
5495 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
5500 *lpNumberOfBytesRecvd = n;
5502 if ((lpOverlapped || lpCompletionRoutine) &&
5503 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
5505 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
5507 wsa->user_overlapped = lpOverlapped;
5508 wsa->completion_func = lpCompletionRoutine;
5509 release_sock_fd( s, fd );
5513 iosb->u.Status = STATUS_PENDING;
5514 iosb->Information = 0;
5516 SERVER_START_REQ( register_async )
5518 req->type = ASYNC_TYPE_READ;
5519 req->async.handle = wine_server_obj_handle( wsa->hSocket );
5520 req->async.callback = wine_server_client_ptr( WS2_async_recv );
5521 req->async.iosb = wine_server_client_ptr( iosb );
5522 req->async.arg = wine_server_client_ptr( wsa );
5523 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
5524 req->async.cvalue = cvalue;
5525 err = wine_server_call( req );
5529 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
5530 WSASetLastError( NtStatusToWSAError( err ));
5531 return SOCKET_ERROR;
5534 iosb->u.Status = STATUS_SUCCESS;
5535 iosb->Information = n;
5536 if (!wsa->completion_func)
5538 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
5539 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
5540 HeapFree( GetProcessHeap(), 0, wsa );
5542 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
5543 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
5544 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5550 if ( _is_blocking(s) )
5553 int timeout = GET_RCVTIMEO(fd);
5556 timeout -= GetTickCount() - timeout_start;
5557 if (timeout < 0) timeout = 0;
5561 pfd.events = POLLIN;
5562 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
5564 if (!timeout || !poll( &pfd, 1, timeout ))
5567 /* a timeout is not fatal */
5568 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5574 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5575 err = WSAEWOULDBLOCK;
5580 TRACE(" -> %i bytes\n", n);
5581 HeapFree( GetProcessHeap(), 0, wsa );
5582 release_sock_fd( s, fd );
5583 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5588 HeapFree( GetProcessHeap(), 0, wsa );
5589 release_sock_fd( s, fd );
5590 WARN(" -> ERROR %d\n", err);
5591 WSASetLastError( err );
5592 return SOCKET_ERROR;
5595 /***********************************************************************
5596 * WSARecvFrom (WS2_32.69)
5598 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5599 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
5600 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
5601 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5604 return WS2_recvfrom( s, lpBuffers, dwBufferCount,
5605 lpNumberOfBytesRecvd, lpFlags,
5607 lpOverlapped, lpCompletionRoutine );
5610 /***********************************************************************
5611 * WSCInstallProvider (WS2_32.88)
5613 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
5614 LPCWSTR lpszProviderDllPath,
5615 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
5616 DWORD dwNumberOfEntries,
5619 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
5620 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
5621 dwNumberOfEntries, lpErrno);
5627 /***********************************************************************
5628 * WSCDeinstallProvider (WS2_32.83)
5630 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
5632 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
5638 /***********************************************************************
5639 * WSAAccept (WS2_32.26)
5641 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
5642 LPCONDITIONPROC lpfnCondition, DWORD dwCallbackData)
5645 int ret = 0, size = 0;
5646 WSABUF CallerId, CallerData, CalleeId, CalleeData;
5647 /* QOS SQOS, GQOS; */
5650 SOCKADDR src_addr, dst_addr;
5652 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %d\n",
5653 s, addr, addrlen, lpfnCondition, dwCallbackData);
5656 size = sizeof(src_addr);
5657 cs = WS_accept(s, &src_addr, &size);
5659 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
5661 if (!lpfnCondition) return cs;
5663 CallerId.buf = (char *)&src_addr;
5664 CallerId.len = sizeof(src_addr);
5666 CallerData.buf = NULL;
5669 WS_getsockname(cs, &dst_addr, &size);
5671 CalleeId.buf = (char *)&dst_addr;
5672 CalleeId.len = sizeof(dst_addr);
5675 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
5676 &CalleeId, &CalleeData, &g, dwCallbackData);
5681 if (addr && addrlen)
5682 addr = memcpy(addr, &src_addr, (*addrlen > size) ? size : *addrlen );
5685 SERVER_START_REQ( set_socket_deferred )
5687 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5688 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
5689 if ( !wine_server_call_err ( req ) )
5691 SetLastError( WSATRY_AGAIN );
5692 WS_closesocket( cs );
5696 return SOCKET_ERROR;
5699 SetLastError(WSAECONNREFUSED);
5700 return SOCKET_ERROR;
5702 FIXME("Unknown return type from Condition function\n");
5703 SetLastError(WSAENOTSOCK);
5704 return SOCKET_ERROR;
5708 /***********************************************************************
5709 * WSADuplicateSocketA (WS2_32.32)
5711 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
5715 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
5716 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
5717 /* FIXME: WS_getsockopt(s, WS_SOL_SOCKET, SO_PROTOCOL_INFO, lpProtocolInfo, sizeof(*lpProtocolInfo)); */
5718 /* I don't know what the real Windoze does next, this is a hack */
5719 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
5720 * the target use the global duplicate, or we could copy a reference to us to the structure
5721 * and let the target duplicate it from us, but let's do it as simple as possible */
5722 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
5723 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
5724 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
5725 0, FALSE, DUPLICATE_SAME_ACCESS);
5726 CloseHandle(hProcess);
5727 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
5731 /***********************************************************************
5732 * WSADuplicateSocketW (WS2_32.33)
5734 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
5738 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
5740 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
5741 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
5742 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
5743 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
5744 0, FALSE, DUPLICATE_SAME_ACCESS);
5745 CloseHandle(hProcess);
5746 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
5750 /***********************************************************************
5751 * WSAInstallServiceClassA (WS2_32.48)
5753 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
5755 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
5756 WSASetLastError(WSAEACCES);
5757 return SOCKET_ERROR;
5760 /***********************************************************************
5761 * WSAInstallServiceClassW (WS2_32.49)
5763 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
5765 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
5766 WSASetLastError(WSAEACCES);
5767 return SOCKET_ERROR;
5770 /***********************************************************************
5771 * WSARemoveServiceClass (WS2_32.70)
5773 int WINAPI WSARemoveServiceClass(LPGUID info)
5775 FIXME("Request to remove service %p\n",info);
5776 WSASetLastError(WSATYPE_NOT_FOUND);
5777 return SOCKET_ERROR;
5780 /***********************************************************************
5781 * inet_ntop (WS2_32.@)
5783 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
5785 #ifdef HAVE_INET_NTOP
5786 struct WS_in6_addr *in6;
5787 struct WS_in_addr *in;
5790 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
5793 WSASetLastError( STATUS_INVALID_PARAMETER );
5802 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
5808 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
5812 WSASetLastError( WSAEAFNOSUPPORT );
5816 if (!pdst) WSASetLastError( STATUS_INVALID_PARAMETER );
5819 FIXME( "not supported on this platform\n" );
5820 WSASetLastError( WSAEAFNOSUPPORT );
5825 /***********************************************************************
5826 * WSAStringToAddressA (WS2_32.80)
5828 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
5830 LPWSAPROTOCOL_INFOA lpProtocolInfo,
5831 LPSOCKADDR lpAddress,
5832 LPINT lpAddressLength)
5835 LPSTR workBuffer=NULL,ptrPort;
5837 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
5838 lpProtocolInfo, lpAddress, lpAddressLength );
5840 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
5844 WSASetLastError(WSAEINVAL);
5845 return SOCKET_ERROR;
5849 FIXME("ProtocolInfo not implemented.\n");
5851 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
5852 strlen(AddressString) + 1);
5855 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5856 return SOCKET_ERROR;
5859 strcpy(workBuffer, AddressString);
5861 switch(AddressFamily)
5865 struct in_addr inetaddr;
5867 /* If lpAddressLength is too small, tell caller the size we need */
5868 if (*lpAddressLength < sizeof(SOCKADDR_IN))
5870 *lpAddressLength = sizeof(SOCKADDR_IN);
5874 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
5876 ((LPSOCKADDR_IN)lpAddress)->sin_family = AF_INET;
5878 ptrPort = strchr(workBuffer, ':');
5881 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
5886 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
5889 if(inet_aton(workBuffer, &inetaddr) > 0)
5891 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
5902 struct in6_addr inetaddr;
5903 /* If lpAddressLength is too small, tell caller the size we need */
5904 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
5906 *lpAddressLength = sizeof(SOCKADDR_IN6);
5910 #ifdef HAVE_INET_PTON
5911 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
5913 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
5915 /* This one is a bit tricky. An IPv6 address contains colons, so the
5916 * check from IPv4 doesn't work like that. However, IPv6 addresses that
5917 * contain a port are written with braces like [fd12:3456:7890::1]:12345
5918 * so what we will do is to look for ']', check if the next char is a
5919 * colon, and if it is, parse the port as in IPv4. */
5921 ptrPort = strchr(workBuffer, ']');
5922 if(ptrPort && *(++ptrPort) == ':')
5924 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort+1));
5929 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
5932 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
5934 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
5935 sizeof(struct in6_addr));
5939 #endif /* HAVE_INET_PTON */
5945 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
5946 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
5950 HeapFree(GetProcessHeap(), 0, workBuffer);
5953 WSASetLastError(res);
5954 return SOCKET_ERROR;
5957 /***********************************************************************
5958 * WSAStringToAddressW (WS2_32.81)
5960 * Does anybody know if this functions allows to use hebrew/arabic/chinese... digits?
5961 * If this should be the case, it would be required to map these digits
5962 * to Unicode digits (0-9) using FoldString first.
5964 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
5966 LPWSAPROTOCOL_INFOW lpProtocolInfo,
5967 LPSOCKADDR lpAddress,
5968 LPINT lpAddressLength)
5971 LPSTR workBuffer=NULL;
5972 WSAPROTOCOL_INFOA infoA;
5973 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
5975 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
5976 lpAddress, lpAddressLength );
5978 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
5980 /* if ProtocolInfo is available - convert to ANSI variant */
5983 lpProtoInfoA = &infoA;
5984 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
5986 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
5987 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
5989 WSASetLastError( WSAEINVAL);
5990 return SOCKET_ERROR;
5996 /* Translate AddressString to ANSI code page - assumes that only
5997 standard digits 0-9 are used with this API call */
5998 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
5999 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
6003 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
6004 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
6005 lpAddress,lpAddressLength);
6006 HeapFree( GetProcessHeap(), 0, workBuffer );
6010 res = WSA_NOT_ENOUGH_MEMORY;
6015 WSASetLastError(res);
6016 return SOCKET_ERROR;
6019 /***********************************************************************
6020 * WSAAddressToStringA (WS2_32.27)
6022 * See WSAAddressToStringW
6024 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
6025 LPWSAPROTOCOL_INFOA info, LPSTR string,
6029 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
6032 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
6034 if (!sockaddr) return SOCKET_ERROR;
6035 if (!string || !lenstr) return SOCKET_ERROR;
6037 switch(sockaddr->sa_family)
6040 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
6041 sprintf( buffer, "%u.%u.%u.%u:%u",
6042 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
6043 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
6044 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
6045 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
6046 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
6048 p = strchr( buffer, ':' );
6049 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
6054 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
6057 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
6058 if ((sockaddr6->sin6_port))
6059 strcpy(buffer, "[");
6060 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, buffer+strlen(buffer), sizeof(buffer)))
6062 WSASetLastError(WSAEINVAL);
6063 return SOCKET_ERROR;
6065 if ((sockaddr6->sin6_scope_id))
6066 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
6067 if ((sockaddr6->sin6_port))
6068 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
6073 WSASetLastError(WSAEINVAL);
6074 return SOCKET_ERROR;
6077 size = strlen( buffer ) + 1;
6082 WSASetLastError(WSAEFAULT);
6083 return SOCKET_ERROR;
6087 strcpy( string, buffer );
6091 /***********************************************************************
6092 * WSAAddressToStringW (WS2_32.28)
6094 * Convert a sockaddr address into a readable address string.
6097 * sockaddr [I] Pointer to a sockaddr structure.
6098 * len [I] Size of the sockaddr structure.
6099 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
6100 * string [I/O] Pointer to a buffer to receive the address string.
6101 * lenstr [I/O] Size of the receive buffer in WCHARs.
6105 * Failure: SOCKET_ERROR
6108 * The 'info' parameter is ignored.
6110 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
6111 LPWSAPROTOCOL_INFOW info, LPWSTR string,
6116 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
6119 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
6122 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
6124 if (ret) return ret;
6126 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
6131 WSASetLastError(WSAEFAULT);
6132 return SOCKET_ERROR;
6136 lstrcpyW( string, buffer );
6140 /***********************************************************************
6141 * WSAEnumNameSpaceProvidersA (WS2_32.34)
6143 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
6145 FIXME( "(%p %p) Stub!\n", len, buffer );
6149 /***********************************************************************
6150 * WSAEnumNameSpaceProvidersW (WS2_32.35)
6152 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
6154 FIXME( "(%p %p) Stub!\n", len, buffer );
6158 /***********************************************************************
6159 * WSAGetQOSByName (WS2_32.41)
6161 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
6163 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
6167 /***********************************************************************
6168 * WSAGetServiceClassInfoA (WS2_32.42)
6170 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
6171 LPWSASERVICECLASSINFOA info )
6173 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
6175 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6176 return SOCKET_ERROR;
6179 /***********************************************************************
6180 * WSAGetServiceClassInfoW (WS2_32.43)
6182 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
6183 LPWSASERVICECLASSINFOW info )
6185 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
6187 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6188 return SOCKET_ERROR;
6191 /***********************************************************************
6192 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
6194 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
6196 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
6197 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6198 return SOCKET_ERROR;
6201 /***********************************************************************
6202 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
6204 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
6206 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
6207 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6208 return SOCKET_ERROR;
6211 /***********************************************************************
6212 * WSALookupServiceBeginA (WS2_32.59)
6214 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
6215 DWORD dwControlFlags,
6218 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
6220 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6221 return SOCKET_ERROR;
6224 /***********************************************************************
6225 * WSALookupServiceBeginW (WS2_32.60)
6227 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
6228 DWORD dwControlFlags,
6231 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
6233 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6234 return SOCKET_ERROR;
6237 /***********************************************************************
6238 * WSALookupServiceBeginW (WS2_32.61)
6240 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
6242 FIXME("(%p) Stub!\n", lookup );
6246 /***********************************************************************
6247 * WSALookupServiceNextA (WS2_32.62)
6249 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
6251 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
6255 /***********************************************************************
6256 * WSALookupServiceNextW (WS2_32.63)
6258 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
6260 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
6264 /***********************************************************************
6265 * WSANtohl (WS2_32.64)
6267 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
6269 TRACE( "(0x%04lx 0x%08x %p)\n", s, netlong, lphostlong );
6271 if (!lphostlong) return WSAEFAULT;
6273 *lphostlong = ntohl( netlong );
6277 /***********************************************************************
6278 * WSANtohs (WS2_32.65)
6280 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
6282 TRACE( "(0x%04lx 0x%08x %p)\n", s, netshort, lphostshort );
6284 if (!lphostshort) return WSAEFAULT;
6286 *lphostshort = ntohs( netshort );
6290 /***********************************************************************
6291 * WSAProviderConfigChange (WS2_32.66)
6293 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
6294 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
6296 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
6297 return SOCKET_ERROR;
6300 /***********************************************************************
6301 * WSARecvDisconnect (WS2_32.68)
6303 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
6305 TRACE( "(0x%04lx %p)\n", s, disconnectdata );
6307 return WS_shutdown( s, 0 );
6310 /***********************************************************************
6311 * WSASetServiceA (WS2_32.76)
6313 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
6315 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
6319 /***********************************************************************
6320 * WSASetServiceW (WS2_32.77)
6322 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
6324 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
6328 /***********************************************************************
6329 * WSCEnableNSProvider (WS2_32.84)
6331 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
6333 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
6337 /***********************************************************************
6338 * WSCGetProviderPath (WS2_32.86)
6340 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
6342 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
6344 if (!errcode || !provider || !len) return WSAEFAULT;
6346 *errcode = WSAEINVAL;
6347 return SOCKET_ERROR;
6350 /***********************************************************************
6351 * WSCInstallNameSpace (WS2_32.87)
6353 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
6354 DWORD version, LPGUID provider )
6356 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
6357 namespace, version, debugstr_guid(provider) );
6361 /***********************************************************************
6362 * WSCUnInstallNameSpace (WS2_32.89)
6364 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
6366 FIXME("(%p) Stub!\n", lpProviderId);
6370 /***********************************************************************
6371 * WSCWriteProviderOrder (WS2_32.91)
6373 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
6375 FIXME("(%p 0x%08x) Stub!\n", entry, number);
6379 /***********************************************************************
6380 * WSANSPIoctl (WS2_32.91)
6382 INT WINAPI WSANSPIoctl( HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer,
6383 DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer,
6384 LPDWORD lpcbBytesReturned, LPWSACOMPLETION lpCompletion )
6386 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup, dwControlCode,
6387 lpvInBuffer, cbInBuffer, lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpCompletion);
6388 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6389 return SOCKET_ERROR;