2 * based on Windows Sockets 1.1 specs
3 * (ftp.microsoft.com:/Advsys/winsock/spec11/WINSOCK.TXT)
5 * Copyright (C) 1993,1994,1996,1997 John Brezak, Erik Bos, Alex Korobka.
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 * NOTE: If you make any changes to fix a particular app, make sure
22 * they don't break something else like Netscape or telnet and ftp
23 * clients and servers (www.winsite.com got a lot of those).
27 #include "wine/port.h"
31 #include <sys/types.h>
35 #ifdef HAVE_SYS_IOCTL_H
36 # include <sys/ioctl.h>
38 #ifdef HAVE_SYS_FILIO_H
39 # include <sys/filio.h>
41 #ifdef HAVE_SYS_SOCKIO_H
42 # include <sys/sockio.h>
46 # include <sys/so_ioctl.h>
49 #ifdef HAVE_SYS_PARAM_H
50 # include <sys/param.h>
56 #ifdef HAVE_SYS_WAIT_H
57 # include <sys/wait.h>
62 #ifdef HAVE_SYS_SOCKET_H
63 #include <sys/socket.h>
65 #ifdef HAVE_NETINET_IN_H
66 # include <netinet/in.h>
68 #ifdef HAVE_NETINET_TCP_H
69 # include <netinet/tcp.h>
71 #ifdef HAVE_ARPA_INET_H
72 # include <arpa/inet.h>
77 #ifdef HAVE_SYS_ERRNO_H
78 #include <sys/errno.h>
87 #ifdef HAVE_ARPA_NAMESER_H
88 # include <arpa/nameser.h>
97 # include <netipx/ipx.h>
100 #ifdef HAVE_IPX_LINUX
101 # include <asm/types.h>
102 # include <linux/ipx.h>
106 #ifdef HAVE_SYS_TIME_H
107 # include <sys/time.h>
110 #include "wine/winbase16.h"
113 #include "winerror.h"
114 #include "winsock2.h"
115 #include "ws2tcpip.h"
117 #include "wine/winsock16.h"
120 #include "wine/server.h"
121 #include "wine/debug.h"
124 # define sipx_network sipx_addr.x_net
125 # define sipx_node sipx_addr.x_host.c_host
126 #endif /* __FreeBSD__ */
128 WINE_DEFAULT_DEBUG_CHANNEL(winsock);
130 /* critical section to protect some non-rentrant net function */
131 extern CRITICAL_SECTION csWSgetXXXbyYYY;
133 #define DEBUG_SOCKADDR 0
134 #define dump_sockaddr(a) \
135 DPRINTF("sockaddr_in: family %d, address %s, port %d\n", \
136 ((struct sockaddr_in *)a)->sin_family, \
137 inet_ntoa(((struct sockaddr_in *)a)->sin_addr), \
138 ntohs(((struct sockaddr_in *)a)->sin_port))
140 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
141 #define SOCKET2HANDLE(s) ((HANDLE)(s))
142 #define HANDLE2SOCKET(h) ((SOCKET)(h))
144 /****************************************************************
145 * Async IO declarations
146 ****************************************************************/
149 static DWORD ws2_async_get_status (const struct async_private *ovp);
150 static DWORD ws2_async_get_count (const struct async_private *ovp);
151 static void ws2_async_set_status (struct async_private *ovp, const DWORD status);
152 static void CALLBACK ws2_async_call_completion (ULONG_PTR data);
153 static void ws2_async_cleanup ( struct async_private *ovp );
155 static struct async_ops ws2_async_ops =
157 ws2_async_get_status,
158 ws2_async_set_status,
160 ws2_async_call_completion,
164 static struct async_ops ws2_nocomp_async_ops =
166 ws2_async_get_status,
167 ws2_async_set_status,
169 NULL, /* call_completion */
173 typedef struct ws2_async
176 LPWSAOVERLAPPED overlapped;
177 LPWSAOVERLAPPED user_overlapped;
178 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
181 struct WS_sockaddr *addr;
183 int val; /* for send operations */
184 int *ptr; /* for recv operations */
189 /****************************************************************/
191 /* ----------------------------------- internal data */
193 /* ws_... struct conversion flags */
195 #define WS_DUP_LINEAR 0x0001
196 #define WS_DUP_SEGPTR 0x0002 /* internal pointers are SEGPTRs */
197 /* by default, internal pointers are linear */
198 typedef struct /* WSAAsyncSelect() control struct */
200 HANDLE service, event, sock;
206 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
207 #define WS_MAX_UDP_DATAGRAM 1024
209 #define PROCFS_NETDEV_FILE "/proc/net/dev" /* Points to the file in the /proc fs
210 that lists the network devices.
211 Do we need an #ifdef LINUX for this? */
213 static void *he_buffer; /* typecast for Win16/32 ws_hostent */
214 static SEGPTR he_buffer_seg;
215 static void *se_buffer; /* typecast for Win16/32 ws_servent */
216 static SEGPTR se_buffer_seg;
217 static void *pe_buffer; /* typecast for Win16/32 ws_protoent */
218 static SEGPTR pe_buffer_seg;
219 static char* local_buffer;
220 static SEGPTR dbuffer_seg;
221 static INT num_startup; /* reference counter */
222 static FARPROC blocking_hook;
224 /* function prototypes */
225 static int WS_dup_he(struct hostent* p_he, int flag);
226 static int WS_dup_pe(struct protoent* p_pe, int flag);
227 static int WS_dup_se(struct servent* p_se, int flag);
229 typedef void WIN_hostent;
230 typedef void WIN_protoent;
231 typedef void WIN_servent;
233 int WSAIOCTL_GetInterfaceCount(void);
234 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
236 UINT16 wsaErrno(void);
237 UINT16 wsaHerrno(int errnr);
239 static HANDLE _WSHeap = 0;
241 #define WS_ALLOC(size) \
242 HeapAlloc(_WSHeap, HEAP_ZERO_MEMORY, (size) )
243 #define WS_FREE(ptr) \
244 HeapFree(_WSHeap, 0, (ptr) )
246 static INT _ws_sock_ops[] =
247 { WS_SO_DEBUG, WS_SO_REUSEADDR, WS_SO_KEEPALIVE, WS_SO_DONTROUTE,
248 WS_SO_BROADCAST, WS_SO_LINGER, WS_SO_OOBINLINE, WS_SO_SNDBUF,
249 WS_SO_RCVBUF, WS_SO_ERROR, WS_SO_TYPE,
257 static int _px_sock_ops[] =
258 { SO_DEBUG, SO_REUSEADDR, SO_KEEPALIVE, SO_DONTROUTE, SO_BROADCAST,
259 SO_LINGER, SO_OOBINLINE, SO_SNDBUF, SO_RCVBUF, SO_ERROR, SO_TYPE,
268 static INT _ws_tcp_ops[] = {
274 static int _px_tcp_ops[] = {
281 static DWORD opentype_tls_index = -1; /* TLS index for SO_OPENTYPE flag */
283 inline static DWORD NtStatusToWSAError ( const DWORD status )
285 /* We only need to cover the status codes set by server async request handling */
289 case STATUS_SUCCESS: wserr = 0; break;
290 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
291 case STATUS_INVALID_HANDLE: wserr = WSAENOTSOCK; break; /* WSAEBADF ? */
292 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
293 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
294 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
295 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
296 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
298 if ( status >= WSABASEERR && status <= WSABASEERR+1004 )
299 /* It is not a NT status code but a winsock error */
303 wserr = RtlNtStatusToDosError( status );
304 FIXME ( "Status code %08lx converted to DOS error code %lx\n", status, wserr );
310 /* set last error code from NT status without mapping WSA errors */
311 inline static unsigned int set_error( unsigned int err )
315 err = NtStatusToWSAError ( err );
321 static char* check_buffer(int size);
323 inline static int _get_sock_fd(SOCKET s)
327 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), GENERIC_READ, &fd, NULL, NULL ) ))
332 inline static int _get_sock_fd_type( SOCKET s, DWORD access, enum fd_type *type, int *flags )
335 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, type, flags ) )) return -1;
336 if ( ( (access & GENERIC_READ) && (*flags & FD_FLAG_RECV_SHUTDOWN ) ) ||
337 ( (access & GENERIC_WRITE) && (*flags & FD_FLAG_SEND_SHUTDOWN ) ) )
340 WSASetLastError ( WSAESHUTDOWN );
346 static void _enable_event( HANDLE s, unsigned int event,
347 unsigned int sstate, unsigned int cstate )
349 SERVER_START_REQ( enable_socket_event )
353 req->sstate = sstate;
354 req->cstate = cstate;
355 wine_server_call( req );
360 static int _is_blocking(SOCKET s)
363 SERVER_START_REQ( get_socket_event )
365 req->handle = SOCKET2HANDLE(s);
366 req->service = FALSE;
368 wine_server_call( req );
369 ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
375 static unsigned int _get_sock_mask(SOCKET s)
378 SERVER_START_REQ( get_socket_event )
380 req->handle = SOCKET2HANDLE(s);
381 req->service = FALSE;
383 wine_server_call( req );
390 static void _sync_sock_state(SOCKET s)
392 /* do a dummy wineserver request in order to let
393 the wineserver run through its select loop once */
394 (void)_is_blocking(s);
397 static int _get_sock_error(SOCKET s, unsigned int bit)
399 int events[FD_MAX_EVENTS];
401 SERVER_START_REQ( get_socket_event )
403 req->handle = SOCKET2HANDLE(s);
404 req->service = FALSE;
406 wine_server_set_reply( req, events, sizeof(events) );
407 wine_server_call( req );
413 static void WINSOCK_DeleteIData(void)
415 /* delete scratch buffers */
417 UnMapLS( he_buffer_seg );
418 UnMapLS( se_buffer_seg );
419 UnMapLS( pe_buffer_seg );
420 UnMapLS( dbuffer_seg );
421 if (he_buffer) HeapFree( GetProcessHeap(), 0, he_buffer );
422 if (se_buffer) HeapFree( GetProcessHeap(), 0, se_buffer );
423 if (pe_buffer) HeapFree( GetProcessHeap(), 0, pe_buffer );
424 if (local_buffer) HeapFree( GetProcessHeap(), 0, local_buffer );
436 /***********************************************************************
437 * DllMain (WS2_32.init)
439 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
441 TRACE("%p 0x%lx %p\n", hInstDLL, fdwReason, fImpLoad);
443 case DLL_PROCESS_ATTACH:
444 opentype_tls_index = TlsAlloc();
446 case DLL_PROCESS_DETACH:
447 TlsFree( opentype_tls_index );
448 WINSOCK_DeleteIData();
454 /***********************************************************************
457 * Converts socket flags from Windows format.
458 * Return 1 if converted, 0 if not (error).
460 static int convert_sockopt(INT *level, INT *optname)
467 for(i=0; _ws_sock_ops[i]; i++)
468 if( _ws_sock_ops[i] == *optname ) break;
469 if( _ws_sock_ops[i] ) {
470 *optname = _px_sock_ops[i];
473 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
476 *level = IPPROTO_TCP;
477 for(i=0; _ws_tcp_ops[i]; i++)
478 if ( _ws_tcp_ops[i] == *optname ) break;
479 if( _ws_tcp_ops[i] ) {
480 *optname = _px_tcp_ops[i];
483 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
489 /* ----------------------------------- Per-thread info (or per-process?) */
491 static int wsi_strtolo(const char* name, const char* opt)
493 /* Stuff a lowercase copy of the string into the local buffer */
495 int i = strlen(name) + 2;
496 char* p = check_buffer(i + ((opt)?strlen(opt):0));
500 do *p++ = tolower(*name); while(*name++);
501 i = (p - local_buffer);
502 if( opt ) do *p++ = tolower(*opt); while(*opt++);
508 static fd_set* fd_set_import( fd_set* fds, void* wsfds, int* highfd, int lfd[], BOOL b32 )
510 /* translate Winsock fd set into local fd set */
514 #define wsfds16 ((ws_fd_set16*)wsfds)
515 #define wsfds32 ((WS_fd_set*)wsfds)
519 count = b32 ? wsfds32->fd_count : wsfds16->fd_count;
521 for( i = 0; i < count; i++ )
523 int s = (b32) ? wsfds32->fd_array[i]
524 : wsfds16->fd_array[i];
525 int fd = _get_sock_fd(s);
529 if( fd > *highfd ) *highfd = fd;
541 inline static int sock_error_p(int s)
543 unsigned int optval, optlen;
545 optlen = sizeof(optval);
546 getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
547 if (optval) WARN("\t[%i] error: %d\n", s, optval);
551 static int fd_set_export( fd_set* fds, fd_set* exceptfds, void* wsfds, int lfd[], BOOL b32 )
555 /* translate local fd set into Winsock fd set, adding
556 * errors to exceptfds (only if app requested it) */
560 #define wsfds16 ((ws_fd_set16*)wsfds)
561 #define wsfds32 ((WS_fd_set*)wsfds)
562 int i, j, count = (b32) ? wsfds32->fd_count : wsfds16->fd_count;
564 for( i = 0, j = 0; i < count; i++ )
569 if( FD_ISSET(fd, fds) )
571 if ( exceptfds && sock_error_p(fd) )
573 FD_SET(fd, exceptfds);
577 wsfds32->fd_array[j++] = wsfds32->fd_array[i];
579 wsfds16->fd_array[j++] = wsfds16->fd_array[i];
586 if( b32 ) wsfds32->fd_count = j;
587 else wsfds16->fd_count = j;
596 static void fd_set_unimport( void* wsfds, int lfd[], BOOL b32 )
600 #define wsfds16 ((ws_fd_set16*)wsfds)
601 #define wsfds32 ((WS_fd_set*)wsfds)
602 int i, count = (b32) ? wsfds32->fd_count : wsfds16->fd_count;
604 for( i = 0; i < count; i++ )
614 static int do_block( int fd, int mask )
625 i = select( fd+1, &fds[0], &fds[1], &fds[2], NULL );
626 if (i <= 0) return -1;
629 if (FD_ISSET(fd, &fds[i]))
634 void* __ws_memalloc( int size )
636 return WS_ALLOC(size);
639 void __ws_memfree(void* ptr)
645 /* ----------------------------------- API -----
647 * Init / cleanup / error checking.
650 /***********************************************************************
651 * WSAStartup (WINSOCK.115)
653 * Create socket control struct, attach it to the global list and
654 * update a pointer in the task struct.
656 INT16 WINAPI WSAStartup16(UINT16 wVersionRequested, LPWSADATA16 lpWSAData)
658 static const WSADATA16 data =
664 #elif defined(__NetBSD__)
668 #elif defined(__FreeBSD__)
670 #elif defined(__OpenBSD__)
675 WS_MAX_SOCKETS_PER_PROCESS,
680 TRACE("verReq=%x\n", wVersionRequested);
682 if (LOBYTE(wVersionRequested) < 1 || (LOBYTE(wVersionRequested) == 1 &&
683 HIBYTE(wVersionRequested) < 1)) return WSAVERNOTSUPPORTED;
685 if (!lpWSAData) return WSAEINVAL;
687 /* initialize socket heap */
691 _WSHeap = HeapCreate(HEAP_ZERO_MEMORY, 8120, 32768);
694 ERR("Fatal: failed to create WinSock heap\n");
698 if( _WSHeap == 0 ) return WSASYSNOTREADY;
702 /* return winsock information */
704 memcpy(lpWSAData, &data, sizeof(data));
706 TRACE("succeeded\n");
710 /***********************************************************************
711 * WSAStartup (WS2_32.115)
713 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
715 TRACE("verReq=%x\n", wVersionRequested);
717 if (LOBYTE(wVersionRequested) < 1)
718 return WSAVERNOTSUPPORTED;
720 if (!lpWSAData) return WSAEINVAL;
722 /* initialize socket heap */
726 _WSHeap = HeapCreate(HEAP_ZERO_MEMORY, 8120, 32768);
729 ERR("Fatal: failed to create WinSock heap\n");
733 if( _WSHeap == 0 ) return WSASYSNOTREADY;
737 /* that's the whole of the negotiation for now */
738 lpWSAData->wVersion = wVersionRequested;
739 /* return winsock information */
740 lpWSAData->wHighVersion = 0x0202;
741 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
742 strcpy(lpWSAData->szSystemStatus, "Running" );
743 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
744 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
745 /* don't do anything with lpWSAData->lpVendorInfo */
746 /* (some apps don't allocate the space for this field) */
748 TRACE("succeeded\n");
753 /***********************************************************************
754 * WSACleanup (WINSOCK.116)
755 * WSACleanup (WS2_32.116)
757 INT WINAPI WSACleanup(void)
761 if (--num_startup > 0) return 0;
762 WINSOCK_DeleteIData();
765 SetLastError(WSANOTINITIALISED);
770 /***********************************************************************
771 * WSAGetLastError (WINSOCK.111)
772 * WSAGetLastError (WS2_32.111)
774 INT WINAPI WSAGetLastError(void)
776 return GetLastError();
779 /***********************************************************************
780 * WSASetLastError (WS2_32.112)
782 void WINAPI WSASetLastError(INT iError) {
783 SetLastError(iError);
786 /***********************************************************************
787 * WSASetLastError (WINSOCK.112)
789 void WINAPI WSASetLastError16(INT16 iError)
791 WSASetLastError(iError);
794 static char* check_buffer(int size)
796 static int local_buflen;
800 if (local_buflen >= size ) return local_buffer;
801 HeapFree( GetProcessHeap(), 0, local_buffer );
803 local_buffer = HeapAlloc( GetProcessHeap(), 0, (local_buflen = size) );
807 static struct ws_hostent* check_buffer_he(int size)
812 if (he_len >= size ) return he_buffer;
813 UnMapLS( he_buffer_seg );
814 HeapFree( GetProcessHeap(), 0, he_buffer );
816 he_buffer = HeapAlloc( GetProcessHeap(), 0, (he_len = size) );
817 he_buffer_seg = MapLS( he_buffer );
821 static void* check_buffer_se(int size)
826 if (se_len >= size ) return se_buffer;
827 UnMapLS( se_buffer_seg );
828 HeapFree( GetProcessHeap(), 0, se_buffer );
830 se_buffer = HeapAlloc( GetProcessHeap(), 0, (se_len = size) );
831 se_buffer_seg = MapLS( se_buffer );
835 static struct ws_protoent* check_buffer_pe(int size)
840 if (pe_len >= size ) return pe_buffer;
841 UnMapLS( pe_buffer_seg );
842 HeapFree( GetProcessHeap(), 0, pe_buffer );
844 pe_buffer = HeapAlloc( GetProcessHeap(), 0, (pe_len = size) );
845 pe_buffer_seg = MapLS( he_buffer );
849 /* ----------------------------------- i/o APIs */
852 #define SUPPORTED_PF(pf) ((pf)==WS_AF_INET || (pf)== WS_AF_IPX)
854 #define SUPPORTED_PF(pf) ((pf)==WS_AF_INET)
858 /**********************************************************************/
860 /* Returns the converted address if successful, NULL if it was too small to
861 * start with. Note that the returned pointer may be the original pointer
862 * if no conversion is necessary.
864 static const struct sockaddr* ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen, int *uaddrlen)
866 switch (wsaddr->sa_family)
871 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
872 struct sockaddr_ipx* uipx;
874 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
877 *uaddrlen=sizeof(struct sockaddr_ipx);
878 uipx=malloc(*uaddrlen);
879 uipx->sipx_family=AF_IPX;
880 uipx->sipx_port=wsipx->sa_socket;
881 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
884 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
885 #ifdef IPX_FRAME_NONE
886 uipx->sipx_type=IPX_FRAME_NONE;
888 memset(&uipx->sipx_zero,0,sizeof uipx->sipx_zero);
889 return (const struct sockaddr*)uipx;
894 if (wsaddrlen<sizeof(struct WS_sockaddr))
897 /* No conversion needed, just return the original address */
899 return (const struct sockaddr*)wsaddr;
904 /* Allocates a Unix sockaddr structure to receive the data */
905 inline struct sockaddr* ws_sockaddr_alloc(const struct WS_sockaddr* wsaddr, int* wsaddrlen, int* uaddrlen)
909 ERR( "WINE shouldn't pass a NULL wsaddr! Attempting to continue\n" );
911 /* This is not strictly the right thing to do. Hope it works however */
920 *uaddrlen=max(sizeof(struct sockaddr),*wsaddrlen);
922 return malloc(*uaddrlen);
925 /* Returns 0 if successful, -1 if the buffer is too small */
926 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, int uaddrlen, struct WS_sockaddr* wsaddr, int* wsaddrlen)
930 switch(uaddr->sa_family)
935 struct sockaddr_ipx* uipx=(struct sockaddr_ipx*)uaddr;
936 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
939 switch (*wsaddrlen) /* how much can we copy? */
944 wsipx->sa_socket=uipx->sipx_port;
948 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
956 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
962 wsipx->sa_family=WS_AF_IPX;
974 /* No conversion needed */
975 memcpy(wsaddr,uaddr,*wsaddrlen);
976 if (*wsaddrlen<uaddrlen) {
986 /* to be called to free the memory allocated by ws_sockaddr_ws2u or
989 inline void ws_sockaddr_free(const struct sockaddr* uaddr, const struct WS_sockaddr* wsaddr)
991 if (uaddr!=NULL && uaddr!=(const struct sockaddr*)wsaddr)
995 /**************************************************************************
996 * Functions for handling overlapped I/O
997 **************************************************************************/
999 static DWORD ws2_async_get_status (const struct async_private *ovp)
1001 return ((ws2_async*) ovp)->overlapped->Internal;
1004 static VOID ws2_async_set_status (struct async_private *ovp, const DWORD status)
1006 ((ws2_async*) ovp)->overlapped->Internal = status;
1009 static DWORD ws2_async_get_count (const struct async_private *ovp)
1011 return ((ws2_async*) ovp)->overlapped->InternalHigh;
1014 static void ws2_async_cleanup ( struct async_private *ap )
1016 struct ws2_async *as = (struct ws2_async*) ap;
1018 TRACE ( "as: %p uovl %p ovl %p\n", as, as->user_overlapped, as->overlapped );
1019 if ( !as->user_overlapped )
1021 if ( as->overlapped->hEvent != INVALID_HANDLE_VALUE )
1022 WSACloseEvent ( as->overlapped->hEvent );
1023 HeapFree ( GetProcessHeap(), 0, as->overlapped );
1027 HeapFree ( GetProcessHeap(), 0, as->iovec );
1029 HeapFree ( GetProcessHeap(), 0, as );
1032 static void CALLBACK ws2_async_call_completion (ULONG_PTR data)
1034 ws2_async* as = (ws2_async*) data;
1036 TRACE ("data: %p\n", as);
1038 as->completion_func ( NtStatusToWSAError (as->overlapped->Internal),
1039 as->overlapped->InternalHigh,
1040 as->user_overlapped,
1042 ws2_async_cleanup ( &as->async );
1045 /***********************************************************************
1046 * WS2_make_async (INTERNAL)
1049 static void WS2_async_recv (async_private *as);
1050 static void WS2_async_send (async_private *as);
1052 inline static struct ws2_async*
1053 WS2_make_async (SOCKET s, int fd, int type, struct iovec *iovec, DWORD dwBufferCount,
1054 LPDWORD lpFlags, struct WS_sockaddr *addr,
1055 LPINT addrlen, LPWSAOVERLAPPED lpOverlapped,
1056 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
1058 struct ws2_async *wsa = HeapAlloc ( GetProcessHeap(), 0, sizeof ( ws2_async ) );
1060 TRACE ( "wsa %p\n", wsa );
1065 wsa->async.ops = ( lpCompletionRoutine ? &ws2_async_ops : &ws2_nocomp_async_ops );
1066 wsa->async.handle = (HANDLE) s;
1068 wsa->async.type = type;
1071 case ASYNC_TYPE_READ:
1072 wsa->flags = *lpFlags;
1073 wsa->async.func = WS2_async_recv;
1074 wsa->addrlen.ptr = addrlen;
1076 case ASYNC_TYPE_WRITE:
1078 wsa->async.func = WS2_async_send;
1079 wsa->addrlen.val = *addrlen;
1082 ERR ("Invalid async type: %d\n", type);
1084 wsa->user_overlapped = lpOverlapped;
1085 wsa->completion_func = lpCompletionRoutine;
1087 wsa->n_iovecs = dwBufferCount;
1092 wsa->overlapped = lpOverlapped;
1093 wsa->async.event = ( lpCompletionRoutine ? INVALID_HANDLE_VALUE : lpOverlapped->hEvent );
1097 wsa->overlapped = HeapAlloc ( GetProcessHeap(), 0,
1098 sizeof (WSAOVERLAPPED) );
1099 if ( !wsa->overlapped )
1101 wsa->async.event = wsa->overlapped->hEvent = INVALID_HANDLE_VALUE;
1104 wsa->overlapped->InternalHigh = 0;
1105 TRACE ( "wsa %p, ops %p, h %p, ev %p, fd %d, func %p, ov %p, uov %p, cfunc %p\n",
1106 wsa, wsa->async.ops, wsa->async.handle, wsa->async.event, wsa->async.fd, wsa->async.func,
1107 wsa->overlapped, wsa->user_overlapped, wsa->completion_func );
1113 HeapFree ( GetProcessHeap(), 0, wsa );
1117 /***********************************************************************
1118 * WS2_recv (INTERNAL)
1120 * Work horse for both synchronous and asynchronous recv() operations.
1122 static int WS2_recv ( int fd, struct iovec* iov, int count,
1123 struct WS_sockaddr *lpFrom, LPINT lpFromlen,
1128 TRACE ( "fd %d, iovec %p, count %d addr %p, len %p, flags %lx\n",
1129 fd, iov, count, lpFrom, lpFromlen, *lpFlags);
1131 hdr.msg_name = NULL;
1136 dump_sockaddr (lpFrom);
1139 hdr.msg_namelen = *lpFromlen;
1140 hdr.msg_name = ws_sockaddr_alloc ( lpFrom, lpFromlen, &hdr.msg_namelen );
1141 if ( !hdr.msg_name )
1143 WSASetLastError ( WSAEFAULT );
1149 hdr.msg_namelen = 0;
1152 hdr.msg_iovlen = count;
1153 #ifdef HAVE_MSGHDR_ACCRIGHTS
1154 hdr.msg_accrights = NULL;
1155 hdr.msg_accrightslen = 0;
1157 hdr.msg_control = NULL;
1158 hdr.msg_controllen = 0;
1162 if ( (n = recvmsg (fd, &hdr, *lpFlags)) == -1 )
1164 TRACE ( "recvmsg error %d\n", errno);
1169 ws_sockaddr_u2ws ( hdr.msg_name, hdr.msg_namelen,
1170 lpFrom, lpFromlen ) != 0 )
1172 /* The from buffer was too small, but we read the data
1173 * anyway. Is that really bad?
1175 WSASetLastError ( WSAEFAULT );
1176 WARN ( "Address buffer too small\n" );
1181 ws_sockaddr_free ( hdr.msg_name, lpFrom );
1182 TRACE ("-> %d\n", n);
1186 /***********************************************************************
1187 * WS2_async_recv (INTERNAL)
1189 * Handler for overlapped recv() operations.
1191 static void WS2_async_recv ( async_private *as )
1193 ws2_async* wsa = (ws2_async*) as;
1196 TRACE ( "async %p\n", wsa );
1198 if ( wsa->overlapped->Internal != STATUS_PENDING )
1200 TRACE ( "status: %ld\n", wsa->overlapped->Internal );
1204 result = WS2_recv ( wsa->async.fd, wsa->iovec, wsa->n_iovecs,
1205 wsa->addr, wsa->addrlen.ptr, &wsa->flags );
1209 wsa->overlapped->Internal = STATUS_SUCCESS;
1210 wsa->overlapped->InternalHigh = result;
1211 TRACE ( "received %d bytes\n", result );
1212 _enable_event ( wsa->async.handle, FD_READ, 0, 0 );
1217 if ( err == WSAEINTR || err == WSAEWOULDBLOCK ) /* errno: EINTR / EAGAIN */
1219 wsa->overlapped->Internal = STATUS_PENDING;
1220 _enable_event ( wsa->async.handle, FD_READ, 0, 0 );
1221 TRACE ( "still pending\n" );
1225 wsa->overlapped->Internal = err;
1226 TRACE ( "Error: %x\n", err );
1230 /***********************************************************************
1231 * WS2_send (INTERNAL)
1233 * Work horse for both synchronous and asynchronous send() operations.
1235 static int WS2_send ( int fd, struct iovec* iov, int count,
1236 const struct WS_sockaddr *to, INT tolen, DWORD dwFlags )
1240 TRACE ( "fd %d, iovec %p, count %d addr %p, len %d, flags %lx\n",
1241 fd, iov, count, to, tolen, dwFlags);
1243 hdr.msg_name = NULL;
1250 hdr.msg_name = (struct sockaddr*) ws_sockaddr_ws2u ( to, tolen, &hdr.msg_namelen );
1251 if ( !hdr.msg_name )
1253 WSASetLastError ( WSAEFAULT );
1258 hdr.msg_namelen = 0;
1261 hdr.msg_iovlen = count;
1262 #ifdef HAVE_MSGHDR_ACCRIGHTS
1263 hdr.msg_accrights = NULL;
1264 hdr.msg_accrightslen = 0;
1266 hdr.msg_control = NULL;
1267 hdr.msg_controllen = 0;
1271 n = sendmsg (fd, &hdr, dwFlags);
1274 ws_sockaddr_free ( hdr.msg_name, to );
1278 /***********************************************************************
1279 * WS2_async_send (INTERNAL)
1281 * Handler for overlapped send() operations.
1283 static void WS2_async_send ( async_private *as )
1285 ws2_async* wsa = (ws2_async*) as;
1288 TRACE ( "async %p\n", wsa );
1290 if ( wsa->overlapped->Internal != STATUS_PENDING )
1292 TRACE ( "status: %ld\n", wsa->overlapped->Internal );
1296 result = WS2_send ( wsa->async.fd, wsa->iovec, wsa->n_iovecs,
1297 wsa->addr, wsa->addrlen.val, wsa->flags );
1301 wsa->overlapped->Internal = STATUS_SUCCESS;
1302 wsa->overlapped->InternalHigh = result;
1303 TRACE ( "sent %d bytes\n", result );
1304 _enable_event ( wsa->async.handle, FD_WRITE, 0, 0 );
1309 if ( err == WSAEINTR )
1311 wsa->overlapped->Internal = STATUS_PENDING;
1312 _enable_event ( wsa->async.handle, FD_WRITE, 0, 0 );
1313 TRACE ( "still pending\n" );
1317 /* We set the status to a winsock error code and check for that
1318 later in NtStatusToWSAError () */
1319 wsa->overlapped->Internal = err;
1320 TRACE ( "Error: %x\n", err );
1324 /***********************************************************************
1325 * WS2_async_shutdown (INTERNAL)
1327 * Handler for shutdown() operations on overlapped sockets.
1329 static void WS2_async_shutdown ( async_private *as )
1331 ws2_async* wsa = (ws2_async*) as;
1334 TRACE ( "async %p %d\n", wsa, wsa->async.type );
1335 switch ( wsa->async.type )
1337 case ASYNC_TYPE_READ:
1338 err = shutdown ( wsa->async.fd, 0 );
1340 case ASYNC_TYPE_WRITE:
1341 err = shutdown ( wsa->async.fd, 1 );
1344 ERR ("invalid type: %d\n", wsa->async.type );
1348 wsa->overlapped->Internal = wsaErrno ();
1350 wsa->overlapped->Internal = STATUS_SUCCESS;
1353 /***********************************************************************
1354 * WS2_register_async_shutdown (INTERNAL)
1356 * Helper function for WS_shutdown() on overlapped sockets.
1358 static int WS2_register_async_shutdown ( SOCKET s, int fd, int type )
1360 struct ws2_async *wsa;
1361 int ret, err = WSAEFAULT;
1364 LPWSAOVERLAPPED ovl = HeapAlloc (GetProcessHeap(), 0, sizeof ( WSAOVERLAPPED ));
1366 TRACE ("s %d fd %d type %d\n", s, fd, type);
1370 ovl->hEvent = WSACreateEvent ();
1371 if ( ovl->hEvent == WSA_INVALID_EVENT )
1374 wsa = WS2_make_async ( s, fd, type, NULL, 0,
1375 &dwflags, NULL, &len, ovl, NULL );
1379 /* Hack: this will cause ws2_async_cleanup() to free the overlapped structure */
1380 wsa->user_overlapped = NULL;
1381 wsa->async.func = WS2_async_shutdown;
1382 if ( (ret = register_new_async ( &wsa->async )) )
1384 err = NtStatusToWSAError ( ret );
1387 /* Try immediate completion */
1388 while ( WaitForSingleObjectEx ( ovl->hEvent, 0, TRUE ) == STATUS_USER_APC );
1392 WSACloseEvent ( ovl->hEvent );
1394 HeapFree ( GetProcessHeap(), 0, ovl );
1399 /***********************************************************************
1402 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr,
1405 int fd = _get_sock_fd(s);
1407 TRACE("socket %04x\n", (UINT16)s );
1411 if (_is_blocking(s))
1415 _sync_sock_state(s); /* let wineserver notice connection */
1416 /* retrieve any error codes from it */
1417 SetLastError(_get_sock_error(s, FD_ACCEPT_BIT));
1418 /* FIXME: care about the error? */
1421 SERVER_START_REQ( accept_socket )
1423 req->lhandle = SOCKET2HANDLE(s);
1424 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
1425 req->inherit = TRUE;
1426 set_error( wine_server_call( req ) );
1427 as = HANDLE2SOCKET( reply->handle );
1433 WS_getpeername(as, addr, addrlen32);
1439 SetLastError(WSAENOTSOCK);
1441 return INVALID_SOCKET;
1444 /***********************************************************************
1445 * accept (WINSOCK.1)
1447 SOCKET16 WINAPI WINSOCK_accept16(SOCKET16 s, struct WS_sockaddr* addr,
1450 INT addrlen32 = addrlen16 ? *addrlen16 : 0;
1451 SOCKET retSocket = WS_accept( s, addr, &addrlen32 );
1452 if( addrlen16 ) *addrlen16 = (INT16)addrlen32;
1453 return (SOCKET16)retSocket;
1456 /***********************************************************************
1459 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
1461 int fd = _get_sock_fd(s);
1464 TRACE("socket %04x, ptr %p, length %d\n", s, name, namelen);
1466 dump_sockaddr(name);
1472 if (!name || !SUPPORTED_PF(name->sa_family))
1474 SetLastError(WSAEAFNOSUPPORT);
1478 const struct sockaddr* uaddr;
1481 uaddr=ws_sockaddr_ws2u(name,namelen,&uaddrlen);
1484 SetLastError(WSAEFAULT);
1489 /* The game GrandPrixLegends binds more than one time, but does
1490 * not do a SO_REUSEADDR - Stevens says this is ok */
1491 FIXME( "Setting WS_SO_REUSEADDR on socket before we binding it\n");
1492 WS_setsockopt( s, WS_SOL_SOCKET, WS_SO_REUSEADDR, (char*)&on, sizeof(on) );
1494 if (bind(fd, uaddr, uaddrlen) < 0)
1496 int loc_errno = errno;
1497 WARN("\tfailure - errno = %i\n", errno);
1502 SetLastError(WSAENOTSOCK);
1505 SetLastError(WSAEINVAL);
1508 SetLastError(wsaErrno());
1514 res=0; /* success */
1516 ws_sockaddr_free(uaddr,name);
1523 SetLastError(WSAENOTSOCK);
1528 /***********************************************************************
1531 INT16 WINAPI WINSOCK_bind16(SOCKET16 s, struct WS_sockaddr *name, INT16 namelen)
1533 return (INT16)WS_bind( s, name, namelen );
1536 /***********************************************************************
1537 * closesocket (WS2_32.3)
1539 int WINAPI WS_closesocket(SOCKET s)
1541 TRACE("socket %08x\n", s);
1542 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
1543 return SOCKET_ERROR;
1546 /***********************************************************************
1547 * closesocket (WINSOCK.3)
1549 INT16 WINAPI WINSOCK_closesocket16(SOCKET16 s)
1551 return (INT16)WS_closesocket(s);
1554 /***********************************************************************
1555 * connect (WS2_32.4)
1557 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
1559 int fd = _get_sock_fd(s);
1561 TRACE("socket %04x, ptr %p, length %d\n", s, name, namelen);
1563 dump_sockaddr(name);
1568 const struct sockaddr* uaddr;
1571 uaddr=ws_sockaddr_ws2u(name,namelen,&uaddrlen);
1574 SetLastError(WSAEFAULT);
1580 rc=connect(fd, uaddr, uaddrlen);
1581 ws_sockaddr_free(uaddr,name);
1583 goto connect_success;
1586 if (errno == EINPROGRESS)
1588 /* tell wineserver that a connection is in progress */
1589 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1590 FD_CONNECT|FD_READ|FD_WRITE,
1591 FD_WINE_CONNECTED|FD_WINE_LISTENING);
1592 if (_is_blocking(s))
1597 _sync_sock_state(s); /* let wineserver notice connection */
1598 /* retrieve any error codes from it */
1599 result = _get_sock_error(s, FD_CONNECT_BIT);
1601 SetLastError(result);
1604 goto connect_success;
1609 SetLastError(WSAEWOULDBLOCK);
1614 SetLastError(wsaErrno());
1620 SetLastError(WSAENOTSOCK);
1622 return SOCKET_ERROR;
1626 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1627 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
1628 FD_CONNECT|FD_WINE_LISTENING);
1632 /***********************************************************************
1633 * connect (WINSOCK.4)
1635 INT16 WINAPI WINSOCK_connect16(SOCKET16 s, struct WS_sockaddr *name, INT16 namelen)
1637 return (INT16)WS_connect( s, name, namelen );
1640 /***********************************************************************
1641 * WSAConnect (WS2_32.30)
1643 int WINAPI WSAConnect ( SOCKET s, const struct WS_sockaddr* name, int namelen,
1644 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
1645 LPQOS lpSQOS, LPQOS lpGQOS )
1647 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
1648 FIXME ("unsupported parameters!\n");
1649 return WS_connect ( s, name, namelen );
1653 /***********************************************************************
1654 * getpeername (WS2_32.5)
1656 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
1661 TRACE("socket: %04x, ptr %p, len %8x\n", s, name, *namelen);
1663 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1664 if( (name == NULL) || (namelen == NULL) )
1666 SetLastError( WSAEFAULT );
1667 return SOCKET_ERROR;
1670 fd = _get_sock_fd(s);
1675 struct sockaddr* uaddr;
1678 uaddr=ws_sockaddr_alloc(name,namelen,&uaddrlen);
1679 if (getpeername(fd, uaddr, &uaddrlen) != 0)
1681 SetLastError(wsaErrno());
1683 else if (ws_sockaddr_u2ws(uaddr,uaddrlen,name,namelen) != 0)
1685 /* The buffer was too small */
1686 SetLastError(WSAEFAULT);
1692 ws_sockaddr_free(uaddr,name);
1697 SetLastError(WSAENOTSOCK);
1702 /***********************************************************************
1703 * getpeername (WINSOCK.5)
1705 INT16 WINAPI WINSOCK_getpeername16(SOCKET16 s, struct WS_sockaddr *name,
1708 INT namelen32 = *namelen16;
1709 INT retVal = WS_getpeername( s, name, &namelen32 );
1712 dump_sockaddr(name);
1715 *namelen16 = namelen32;
1716 return (INT16)retVal;
1719 /***********************************************************************
1720 * getsockname (WS2_32.6)
1722 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
1727 TRACE("socket: %04x, ptr %p, len %8x\n", s, name, *namelen);
1729 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1730 if( (name == NULL) || (namelen == NULL) )
1732 SetLastError( WSAEFAULT );
1733 return SOCKET_ERROR;
1736 fd = _get_sock_fd(s);
1741 struct sockaddr* uaddr;
1744 uaddr=ws_sockaddr_alloc(name,namelen,&uaddrlen);
1745 if (getsockname(fd, uaddr, &uaddrlen) != 0)
1747 SetLastError(wsaErrno());
1749 else if (ws_sockaddr_u2ws(uaddr,uaddrlen,name,namelen) != 0)
1751 /* The buffer was too small */
1752 SetLastError(WSAEFAULT);
1762 SetLastError(WSAENOTSOCK);
1767 /***********************************************************************
1768 * getsockname (WINSOCK.6)
1770 INT16 WINAPI WINSOCK_getsockname16(SOCKET16 s, struct WS_sockaddr *name,
1777 INT namelen32 = *namelen16;
1778 retVal = WS_getsockname( s, name, &namelen32 );
1779 *namelen16 = namelen32;
1782 dump_sockaddr(name);
1786 else retVal = SOCKET_ERROR;
1787 return (INT16)retVal;
1791 /***********************************************************************
1792 * getsockopt (WS2_32.7)
1794 INT WINAPI WS_getsockopt(SOCKET s, INT level,
1795 INT optname, char *optval, INT *optlen)
1799 TRACE("socket: %04x, level 0x%x, name 0x%x, ptr %8x, len %d\n", s, level,
1800 (int) optname, (int) optval, (int) *optlen);
1801 /* SO_OPENTYPE does not require a valid socket handle. */
1802 if (level == WS_SOL_SOCKET && optname == WS_SO_OPENTYPE)
1804 if (!optlen || *optlen < sizeof(int) || !optval)
1806 SetLastError(WSAEFAULT);
1807 return SOCKET_ERROR;
1809 *(int *)optval = (int)TlsGetValue( opentype_tls_index );
1810 *optlen = sizeof(int);
1811 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
1815 fd = _get_sock_fd(s);
1818 if (!convert_sockopt(&level, &optname)) {
1819 SetLastError(WSAENOPROTOOPT); /* Unknown option */
1821 if (getsockopt(fd, (int) level, optname, optval, optlen) == 0 )
1826 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1830 return SOCKET_ERROR;
1834 /***********************************************************************
1835 * getsockopt (WINSOCK.7)
1837 INT16 WINAPI WINSOCK_getsockopt16(SOCKET16 s, INT16 level,
1838 INT16 optname, char *optval, INT16 *optlen)
1843 if( optlen ) optlen32 = *optlen; else p = NULL;
1844 retVal = WS_getsockopt( s, (UINT16)level, optname, optval, p );
1845 if( optlen ) *optlen = optlen32;
1846 return (INT16)retVal;
1850 /***********************************************************************
1854 u_long WINAPI WS_htonl(u_long hostlong)
1856 return htonl(hostlong);
1860 /***********************************************************************
1864 u_short WINAPI WS_htons(u_short hostshort)
1866 return htons(hostshort);
1870 /***********************************************************************
1871 * inet_addr (WINSOCK.10)
1872 * inet_addr (WS2_32.11)
1874 u_long WINAPI WS_inet_addr(const char *cp)
1876 return inet_addr(cp);
1880 /***********************************************************************
1881 * ntohl (WINSOCK.14)
1884 u_long WINAPI WS_ntohl(u_long netlong)
1886 return ntohl(netlong);
1890 /***********************************************************************
1891 * ntohs (WINSOCK.15)
1894 u_short WINAPI WS_ntohs(u_short netshort)
1896 return ntohs(netshort);
1900 /***********************************************************************
1901 * inet_ntoa (WS2_32.12)
1903 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
1905 /* use "buffer for dummies" here because some applications have
1906 * propensity to decode addresses in ws_hostent structure without
1907 * saving them first...
1909 static char dbuffer[16]; /* Yes, 16: 4*3 digits + 3 '.' + 1 '\0' */
1911 char* s = inet_ntoa(*((struct in_addr*)&in));
1917 SetLastError(wsaErrno());
1921 /***********************************************************************
1922 * inet_ntoa (WINSOCK.11)
1924 SEGPTR WINAPI WINSOCK_inet_ntoa16(struct in_addr in)
1927 if (!(retVal = WS_inet_ntoa(*((struct WS_in_addr*)&in)))) return 0;
1928 if (!dbuffer_seg) dbuffer_seg = MapLS( retVal );
1933 /**********************************************************************
1934 * WSAIoctl (WS2_32.50)
1937 * FIXME: Only SIO_GET_INTERFACE_LIST option implemented.
1939 INT WINAPI WSAIoctl (SOCKET s,
1940 DWORD dwIoControlCode,
1943 LPVOID lpbOutBuffer,
1945 LPDWORD lpcbBytesReturned,
1946 LPWSAOVERLAPPED lpOverlapped,
1947 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
1949 int fd = _get_sock_fd(s);
1953 switch( dwIoControlCode )
1955 case SIO_GET_INTERFACE_LIST:
1957 INTERFACE_INFO* intArray = (INTERFACE_INFO*)lpbOutBuffer;
1959 struct ifreq ifInfo;
1963 TRACE ("-> SIO_GET_INTERFACE_LIST request\n");
1965 numInt = WSAIOCTL_GetInterfaceCount();
1968 ERR ("Unable to open /proc filesystem to determine number of network interfaces!\n");
1970 WSASetLastError(WSAEINVAL);
1971 return (SOCKET_ERROR);
1974 for (i=0; i<numInt; i++)
1976 if (!WSAIOCTL_GetInterfaceName(i, ifName))
1978 ERR ("Error parsing /proc filesystem!\n");
1980 WSASetLastError(WSAEINVAL);
1981 return (SOCKET_ERROR);
1984 ifInfo.ifr_addr.sa_family = AF_INET;
1987 strcpy (ifInfo.ifr_name, ifName);
1988 if (ioctl(fd, SIOCGIFADDR, &ifInfo) < 0)
1990 ERR ("Error obtaining IP address\n");
1992 WSASetLastError(WSAEINVAL);
1993 return (SOCKET_ERROR);
1997 struct WS_sockaddr_in *ipTemp = (struct WS_sockaddr_in *)&ifInfo.ifr_addr;
1999 intArray->iiAddress.AddressIn.sin_family = AF_INET;
2000 intArray->iiAddress.AddressIn.sin_port = ipTemp->sin_port;
2001 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr = ipTemp->sin_addr.S_un.S_addr;
2004 /* Broadcast Address */
2005 strcpy (ifInfo.ifr_name, ifName);
2006 if (ioctl(fd, SIOCGIFBRDADDR, &ifInfo) < 0)
2008 ERR ("Error obtaining Broadcast IP address\n");
2010 WSASetLastError(WSAEINVAL);
2011 return (SOCKET_ERROR);
2015 struct WS_sockaddr_in *ipTemp = (struct WS_sockaddr_in *)&ifInfo.ifr_broadaddr;
2017 intArray->iiBroadcastAddress.AddressIn.sin_family = AF_INET;
2018 intArray->iiBroadcastAddress.AddressIn.sin_port = ipTemp->sin_port;
2019 intArray->iiBroadcastAddress.AddressIn.sin_addr.WS_s_addr = ipTemp->sin_addr.S_un.S_addr;
2023 strcpy (ifInfo.ifr_name, ifName);
2024 if (ioctl(fd, SIOCGIFNETMASK, &ifInfo) < 0)
2026 ERR ("Error obtaining Subnet IP address\n");
2028 WSASetLastError(WSAEINVAL);
2029 return (SOCKET_ERROR);
2033 /* Trying to avoid some compile problems across platforms.
2034 (Linux, FreeBSD, Solaris...) */
2037 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
2038 intArray->iiNetmask.AddressIn.sin_port = 0;
2039 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr = 0;
2040 ERR ("Unable to determine Netmask on your platform!\n");
2042 struct WS_sockaddr_in *ipTemp = (struct WS_sockaddr_in *)&ifInfo.ifr_addr;
2044 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
2045 intArray->iiNetmask.AddressIn.sin_port = ipTemp->sin_port;
2046 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr = ipTemp->sin_addr.S_un.S_addr;
2049 struct WS_sockaddr_in *ipTemp = (struct WS_sockaddr_in *)&ifInfo.ifr_netmask;
2051 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
2052 intArray->iiNetmask.AddressIn.sin_port = ipTemp->sin_port;
2053 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr = ipTemp->sin_addr.S_un.S_addr;
2057 /* Socket Status Flags */
2058 strcpy(ifInfo.ifr_name, ifName);
2059 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
2061 ERR ("Error obtaining status flags for socket!\n");
2063 WSASetLastError(WSAEINVAL);
2064 return (SOCKET_ERROR);
2068 /* FIXME - Is this the right flag to use? */
2069 intArray->iiFlags = ifInfo.ifr_flags;
2071 intArray++; /* Prepare for another interface */
2074 /* Calculate the size of the array being returned */
2075 *lpcbBytesReturned = sizeof(INTERFACE_INFO) * numInt;
2081 WARN("\tunsupported WS_IOCTL cmd (%08lx)\n", dwIoControlCode);
2083 WSASetLastError(WSAEOPNOTSUPP);
2084 return (SOCKET_ERROR);
2088 /* Function executed with no errors */
2094 WSASetLastError(WSAENOTSOCK);
2095 return (SOCKET_ERROR);
2101 Helper function for WSAIoctl - Get count of the number of interfaces
2102 by parsing /proc filesystem.
2104 int WSAIOCTL_GetInterfaceCount(void)
2107 char buf[512]; /* Size doesn't matter, something big */
2111 /* Open /proc filesystem file for network devices */
2112 procfs = fopen(PROCFS_NETDEV_FILE, "r");
2115 /* If we can't open the file, return an error */
2119 /* Omit first two lines, they are only headers */
2120 fgets(buf, sizeof buf, procfs);
2121 fgets(buf, sizeof buf, procfs);
2123 while (fgets(buf, sizeof buf, procfs))
2125 /* Each line in the file represents a network interface */
2135 Helper function for WSAIoctl - Get name of device from interface number
2136 by parsing /proc filesystem.
2138 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName)
2141 char buf[512]; /* Size doesn't matter, something big */
2144 /* Open /proc filesystem file for network devices */
2145 procfs = fopen(PROCFS_NETDEV_FILE, "r");
2148 /* If we can't open the file, return an error */
2152 /* Omit first two lines, they are only headers */
2153 fgets(buf, sizeof(buf), procfs);
2154 fgets(buf, sizeof(buf), procfs);
2156 for (i=0; i<intNumber; i++)
2158 /* Skip the lines that don't interest us. */
2159 fgets(buf, sizeof(buf), procfs);
2161 fgets(buf, sizeof(buf), procfs); /* This is the line we want */
2164 /* Parse out the line, grabbing only the name of the device
2165 to the intName variable
2167 The Line comes in like this: (we only care about the device name)
2168 lo: 21970 377 0 0 0 0 0 0 21970 377 0 0 0 0 0 0
2171 while (isspace(buf[i])) /* Skip initial space(s) */
2178 if (isspace(buf[i]))
2183 if (buf[i] == ':') /* FIXME: Not sure if this block (alias detection) works properly */
2185 /* This interface could be an alias... */
2187 char *dotname = intName;
2188 *intName++ = buf[i++];
2190 while (isdigit(buf[i]))
2192 *intName++ = buf[i++];
2197 /* ... It wasn't, so back up */
2212 *intName++ = buf[i++];
2221 /***********************************************************************
2222 * ioctlsocket (WS2_32.10)
2224 int WINAPI WS_ioctlsocket(SOCKET s, long cmd, u_long *argp)
2226 int fd = _get_sock_fd(s);
2228 TRACE("socket %04x, cmd %08lx, ptr %8x\n", s, cmd, (unsigned) argp);
2241 if( _get_sock_mask(s) )
2243 /* AsyncSelect()'ed sockets are always nonblocking */
2248 SetLastError(WSAEINVAL);
2250 return SOCKET_ERROR;
2254 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
2256 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
2263 case WS__IOW('f',125,u_long):
2264 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
2265 SetLastError(WSAEINVAL);
2266 return SOCKET_ERROR;
2268 case SIOCGIFBRDADDR:
2269 case SIOCGIFNETMASK:
2271 /* These don't need any special handling. They are used by
2272 WsControl, and are here to suppress an unecessary warning. */
2277 /* Netscape tries hard to use bogus ioctl 0x667e */
2278 WARN("\tunknown WS_IOCTL cmd (%08lx)\n", cmd);
2280 if( ioctl(fd, newcmd, (char*)argp ) == 0 )
2285 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2288 return SOCKET_ERROR;
2291 /***********************************************************************
2292 * ioctlsocket (WINSOCK.12)
2294 INT16 WINAPI WINSOCK_ioctlsocket16(SOCKET16 s, LONG cmd, ULONG *argp)
2296 return (INT16)WS_ioctlsocket( s, cmd, argp );
2300 /***********************************************************************
2301 * listen (WS2_32.13)
2303 int WINAPI WS_listen(SOCKET s, int backlog)
2305 int fd = _get_sock_fd(s);
2307 TRACE("socket %04x, backlog %d\n", s, backlog);
2310 if (listen(fd, backlog) == 0)
2313 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
2315 FD_CONNECT|FD_WINE_CONNECTED);
2318 SetLastError(wsaErrno());
2320 else SetLastError(WSAENOTSOCK);
2321 return SOCKET_ERROR;
2324 /***********************************************************************
2325 * listen (WINSOCK.13)
2327 INT16 WINAPI WINSOCK_listen16(SOCKET16 s, INT16 backlog)
2329 return (INT16)WS_listen( s, backlog );
2333 /***********************************************************************
2336 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
2338 DWORD n, dwFlags = flags;
2344 if ( WSARecvFrom (s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
2345 return SOCKET_ERROR;
2350 /***********************************************************************
2353 INT16 WINAPI WINSOCK_recv16(SOCKET16 s, char *buf, INT16 len, INT16 flags)
2355 return (INT16)WS_recv( s, buf, len, flags );
2359 /***********************************************************************
2360 * recvfrom (WS2_32.17)
2362 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
2363 struct WS_sockaddr *from, int *fromlen)
2365 DWORD n, dwFlags = flags;
2371 if ( WSARecvFrom (s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL) == SOCKET_ERROR )
2372 return SOCKET_ERROR;
2377 /***********************************************************************
2378 * recvfrom (WINSOCK.17)
2380 INT16 WINAPI WINSOCK_recvfrom16(SOCKET16 s, char *buf, INT16 len, INT16 flags,
2381 struct WS_sockaddr *from, INT16 *fromlen16)
2384 INT *p = &fromlen32;
2387 if( fromlen16 ) fromlen32 = *fromlen16; else p = NULL;
2388 retVal = WS_recvfrom( s, buf, len, flags, from, p );
2389 if( fromlen16 ) *fromlen16 = fromlen32;
2390 return (INT16)retVal;
2393 /***********************************************************************
2396 static int __ws_select(BOOL b32,
2397 void *ws_readfds, void *ws_writefds, void *ws_exceptfds,
2398 const struct WS_timeval *ws_timeout)
2401 fd_set readfds, writefds, exceptfds;
2402 fd_set *p_read, *p_write, *p_except;
2403 int readfd[FD_SETSIZE], writefd[FD_SETSIZE], exceptfd[FD_SETSIZE];
2404 struct timeval timeout, *timeoutaddr = NULL;
2406 TRACE("read %p, write %p, excp %p timeout %p\n",
2407 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
2409 p_read = fd_set_import(&readfds, ws_readfds, &highfd, readfd, b32);
2410 p_write = fd_set_import(&writefds, ws_writefds, &highfd, writefd, b32);
2411 p_except = fd_set_import(&exceptfds, ws_exceptfds, &highfd, exceptfd, b32);
2414 timeoutaddr = &timeout;
2415 timeout.tv_sec=ws_timeout->tv_sec;
2416 timeout.tv_usec=ws_timeout->tv_usec;
2419 if( (highfd = select(highfd + 1, p_read, p_write, p_except, timeoutaddr)) > 0 )
2421 fd_set_export(&readfds, p_except, ws_readfds, readfd, b32);
2422 fd_set_export(&writefds, p_except, ws_writefds, writefd, b32);
2424 if (p_except && ws_exceptfds)
2426 #define wsfds16 ((ws_fd_set16*)ws_exceptfds)
2427 #define wsfds32 ((WS_fd_set*)ws_exceptfds)
2428 int i, j, count = (b32) ? wsfds32->fd_count : wsfds16->fd_count;
2430 for (i = j = 0; i < count; i++)
2432 int fd = exceptfd[i];
2433 if( fd >= 0 && FD_ISSET(fd, &exceptfds) )
2436 wsfds32->fd_array[j++] = wsfds32->fd_array[i];
2438 wsfds16->fd_array[j++] = wsfds16->fd_array[i];
2440 if( fd >= 0 ) close(fd);
2444 wsfds32->fd_count = j;
2446 wsfds16->fd_count = j;
2452 fd_set_unimport(ws_readfds, readfd, b32);
2453 fd_set_unimport(ws_writefds, writefd, b32);
2454 fd_set_unimport(ws_exceptfds, exceptfd, b32);
2455 if( ws_readfds ) ((WS_fd_set*)ws_readfds)->fd_count = 0;
2456 if( ws_writefds ) ((WS_fd_set*)ws_writefds)->fd_count = 0;
2457 if( ws_exceptfds ) ((WS_fd_set*)ws_exceptfds)->fd_count = 0;
2459 if( highfd == 0 ) return 0;
2460 SetLastError(wsaErrno());
2461 return SOCKET_ERROR;
2464 /***********************************************************************
2465 * select (WINSOCK.18)
2467 INT16 WINAPI WINSOCK_select16(INT16 nfds, ws_fd_set16 *ws_readfds,
2468 ws_fd_set16 *ws_writefds, ws_fd_set16 *ws_exceptfds,
2469 struct WS_timeval* timeout)
2471 return (INT16)__ws_select( FALSE, ws_readfds, ws_writefds, ws_exceptfds, timeout );
2474 /***********************************************************************
2475 * select (WS2_32.18)
2477 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
2478 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
2479 const struct WS_timeval* timeout)
2481 /* struct timeval is the same for both 32- and 16-bit code */
2482 return (INT)__ws_select( TRUE, ws_readfds, ws_writefds, ws_exceptfds, timeout );
2486 /***********************************************************************
2489 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
2495 wsabuf.buf = (char*) buf;
2497 if ( WSASendTo ( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
2498 return SOCKET_ERROR;
2503 /***********************************************************************
2504 * WSASend (WS2_32.72)
2506 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2507 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2508 LPWSAOVERLAPPED lpOverlapped,
2509 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2511 return WSASendTo ( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
2512 NULL, 0, lpOverlapped, lpCompletionRoutine );
2515 /***********************************************************************
2516 * WSASendDisconnect (WS2_32.73)
2518 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
2520 return WS_shutdown ( s, SD_SEND );
2524 /***********************************************************************
2525 * WSASendTo (WS2_32.74)
2527 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2528 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2529 const struct WS_sockaddr *to, int tolen,
2530 LPWSAOVERLAPPED lpOverlapped,
2531 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2533 int i, n, fd, err = WSAENOTSOCK, flags, ret;
2534 struct iovec* iovec;
2535 struct ws2_async *wsa;
2538 TRACE ("socket %04x, wsabuf %p, nbufs %ld, flags %ld, to %p, tolen %d, ovl %p, func %p\n",
2539 s, lpBuffers, dwBufferCount, dwFlags,
2540 to, tolen, lpOverlapped, lpCompletionRoutine);
2542 fd = _get_sock_fd_type( s, GENERIC_WRITE, &type, &flags );
2543 TRACE ( "fd=%d, type=%d, flags=%x\n", fd, type, flags );
2547 err = WSAGetLastError ();
2551 iovec = HeapAlloc (GetProcessHeap(), 0, dwBufferCount * sizeof (struct iovec) );
2559 for ( i = 0; i < dwBufferCount; i++ )
2561 iovec[i].iov_base = lpBuffers[i].buf;
2562 iovec[i].iov_len = lpBuffers[i].len;
2565 if ( (lpOverlapped || lpCompletionRoutine) && flags & FD_FLAG_OVERLAPPED )
2567 wsa = WS2_make_async ( s, fd, ASYNC_TYPE_WRITE, iovec, dwBufferCount,
2568 &dwFlags, (struct WS_sockaddr*) to, &tolen,
2569 lpOverlapped, lpCompletionRoutine );
2576 if ( ( ret = register_new_async ( &wsa->async )) )
2578 err = NtStatusToWSAError ( ret );
2580 if ( !lpOverlapped )
2581 HeapFree ( GetProcessHeap(), 0, wsa->overlapped );
2582 HeapFree ( GetProcessHeap(), 0, wsa );
2586 /* Try immediate completion */
2587 if ( lpOverlapped && !NtResetEvent( lpOverlapped->hEvent, NULL ) )
2589 if ( WSAGetOverlappedResult ( s, lpOverlapped,
2590 lpNumberOfBytesSent, FALSE, &dwFlags) )
2593 if ( (err = WSAGetLastError ()) != WSA_IO_INCOMPLETE )
2597 WSASetLastError ( WSA_IO_PENDING );
2598 return SOCKET_ERROR;
2601 if (_is_blocking(s))
2603 /* FIXME: exceptfds? */
2607 n = WS2_send ( fd, iovec, dwBufferCount, to, tolen, dwFlags );
2611 if ( err == WSAEWOULDBLOCK )
2612 _enable_event (SOCKET2HANDLE(s), FD_WRITE, 0, 0);
2616 TRACE(" -> %i bytes\n", n);
2617 *lpNumberOfBytesSent = n;
2619 HeapFree ( GetProcessHeap(), 0, iovec );
2624 HeapFree ( GetProcessHeap(), 0, iovec );
2630 WARN (" -> ERROR %d\n", err);
2631 WSASetLastError (err);
2632 return SOCKET_ERROR;
2635 /***********************************************************************
2638 INT16 WINAPI WINSOCK_send16(SOCKET16 s, char *buf, INT16 len, INT16 flags)
2640 return WS_send( s, buf, len, flags );
2643 /***********************************************************************
2644 * sendto (WS2_32.20)
2646 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
2647 const struct WS_sockaddr *to, int tolen)
2653 wsabuf.buf = (char*) buf;
2655 if ( WSASendTo (s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
2656 return SOCKET_ERROR;
2661 /***********************************************************************
2662 * sendto (WINSOCK.20)
2664 INT16 WINAPI WINSOCK_sendto16(SOCKET16 s, char *buf, INT16 len, INT16 flags,
2665 struct WS_sockaddr *to, INT16 tolen)
2667 return (INT16)WS_sendto( s, buf, len, flags, to, tolen );
2670 /***********************************************************************
2671 * setsockopt (WS2_32.21)
2673 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
2674 const char *optval, int optlen)
2678 TRACE("socket: %04x, level 0x%x, name 0x%x, ptr %8x, len %d\n", s, level,
2679 (int) optname, (int) optval, optlen);
2680 /* SO_OPENTYPE does not require a valid socket handle. */
2681 if (level == WS_SOL_SOCKET && optname == WS_SO_OPENTYPE)
2683 if (optlen < sizeof(int) || !optval)
2685 SetLastError(WSAEFAULT);
2686 return SOCKET_ERROR;
2688 TlsSetValue( opentype_tls_index, (LPVOID)*(int *)optval );
2689 TRACE("setting global SO_OPENTYPE to 0x%x\n", *(int *)optval );
2693 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
2694 * socket. This will either not happen under windows or it is ignored in
2695 * windows (but it works in linux and therefor prevents the game to find
2696 * games outsite the current network) */
2697 if ( level==WS_SOL_SOCKET && optname==WS_SO_DONTROUTE )
2699 FIXME("Does windows ignore SO_DONTROUTE?\n");
2704 fd = _get_sock_fd(s);
2707 struct linger linger;
2709 struct timeval tval;
2711 /* Is a privileged and useless operation, so we don't. */
2712 if ((optname == WS_SO_DEBUG) && (level == WS_SOL_SOCKET)) {
2713 FIXME("(%d,SOL_SOCKET,SO_DEBUG,%p(%ld)) attempted (is privileged). Ignoring.\n",s,optval,*(DWORD*)optval);
2717 if(optname == WS_SO_DONTLINGER && level == WS_SOL_SOCKET) {
2718 /* This is unique to WinSock and takes special conversion */
2719 linger.l_onoff = *((int*)optval) ? 0: 1;
2720 linger.l_linger = 0;
2722 optval = (char*)&linger;
2723 optlen = sizeof(struct linger);
2726 if (!convert_sockopt(&level, &optname)) {
2727 SetLastError(WSAENOPROTOOPT);
2729 return SOCKET_ERROR;
2731 if (optname == SO_LINGER && optval) {
2732 /* yes, uses unsigned short in both win16/win32 */
2733 linger.l_onoff = ((UINT16*)optval)[0];
2734 linger.l_linger = ((UINT16*)optval)[1];
2735 /* FIXME: what is documented behavior if SO_LINGER optval
2737 optval = (char*)&linger;
2738 optlen = sizeof(struct linger);
2739 } else if (optlen < sizeof(int)){
2740 woptval= *((INT16 *) optval);
2741 optval= (char*) &woptval;
2745 if (level == SOL_SOCKET && optname == SO_RCVTIMEO) {
2746 if (optlen == sizeof(UINT32)) {
2747 /* WinSock passes miliseconds instead of struct timeval */
2748 tval.tv_usec = *(PUINT32)optval % 1000;
2749 tval.tv_sec = *(PUINT32)optval / 1000;
2750 /* min of 500 milisec */
2751 if (tval.tv_sec == 0 && tval.tv_usec < 500) tval.tv_usec = 500;
2752 optlen = sizeof(struct timeval);
2753 optval = (char*)&tval;
2754 } else if (optlen == sizeof(struct timeval)) {
2755 WARN("SO_RCVTIMEO for %d bytes: assuming unixism\n", optlen);
2757 WARN("SO_RCVTIMEO for %d bytes is weird: ignored\n", optlen);
2764 if (level == SOL_SOCKET && optname == SO_SNDTIMEO) {
2765 if (optlen == sizeof(UINT32)) {
2766 /* WinSock passes miliseconds instead of struct timeval */
2767 tval.tv_usec = *(PUINT32)optval % 1000;
2768 tval.tv_sec = *(PUINT32)optval / 1000;
2769 /* min of 500 milisec */
2770 if (tval.tv_sec == 0 && tval.tv_usec < 500) tval.tv_usec = 500;
2771 optlen = sizeof(struct timeval);
2772 optval = (char*)&tval;
2773 } else if (optlen == sizeof(struct timeval)) {
2774 WARN("SO_SNDTIMEO for %d bytes: assuming unixism\n", optlen);
2776 WARN("SO_SNDTIMEO for %d bytes is weird: ignored\n", optlen);
2783 if(optname == SO_RCVBUF && *(int*)optval < 2048) {
2784 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(int*)optval );
2789 if (setsockopt(fd, level, optname, optval, optlen) == 0)
2794 SetLastError(wsaErrno());
2797 else SetLastError(WSAENOTSOCK);
2798 return SOCKET_ERROR;
2801 /***********************************************************************
2802 * setsockopt (WINSOCK.21)
2804 INT16 WINAPI WINSOCK_setsockopt16(SOCKET16 s, INT16 level, INT16 optname,
2805 char *optval, INT16 optlen)
2807 if( !optval ) return SOCKET_ERROR;
2808 return (INT16)WS_setsockopt( s, (UINT16)level, optname, optval, optlen );
2812 /***********************************************************************
2813 * shutdown (WS2_32.22)
2815 int WINAPI WS_shutdown(SOCKET s, int how)
2817 int fd, fd0 = -1, fd1 = -1, flags, err = WSAENOTSOCK;
2819 unsigned int clear_flags = 0;
2821 fd = _get_sock_fd_type ( s, 0, &type, &flags );
2822 TRACE("socket %04x, how %i %d %d \n", s, how, type, flags );
2825 return SOCKET_ERROR;
2829 case 0: /* drop receives */
2830 clear_flags |= FD_READ;
2832 case 1: /* drop sends */
2833 clear_flags |= FD_WRITE;
2835 case 2: /* drop all */
2836 clear_flags |= FD_READ|FD_WRITE;
2838 clear_flags |= FD_WINE_LISTENING;
2841 if ( flags & FD_FLAG_OVERLAPPED ) {
2854 fd1 = _get_sock_fd ( s );
2859 err = WS2_register_async_shutdown ( s, fd0, ASYNC_TYPE_READ );
2868 err = WS2_register_async_shutdown ( s, fd1, ASYNC_TYPE_WRITE );
2876 else /* non-overlapped mode */
2878 if ( shutdown( fd, how ) )
2887 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
2888 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
2892 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
2893 WSASetLastError ( err );
2894 return SOCKET_ERROR;
2897 /***********************************************************************
2898 * shutdown (WINSOCK.22)
2900 INT16 WINAPI WINSOCK_shutdown16(SOCKET16 s, INT16 how)
2902 return (INT16)WS_shutdown( s, how );
2906 /***********************************************************************
2907 * socket (WS2_32.23)
2909 SOCKET WINAPI WS_socket(int af, int type, int protocol)
2911 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
2913 return WSASocketA ( af, type, protocol, NULL, 0,
2914 (TlsGetValue(opentype_tls_index) ? 0 : WSA_FLAG_OVERLAPPED) );
2917 /***********************************************************************
2918 * socket (WINSOCK.23)
2920 SOCKET16 WINAPI WINSOCK_socket16(INT16 af, INT16 type, INT16 protocol)
2922 return (SOCKET16)WS_socket( af, type, protocol );
2926 /* ----------------------------------- DNS services
2928 * IMPORTANT: 16-bit API structures have SEGPTR pointers inside them.
2929 * Also, we have to use wsock32 stubs to convert structures and
2930 * error codes from Unix to WSA, hence there is no direct mapping in
2931 * the relay32/wsock32.spec.
2935 /***********************************************************************
2936 * __ws_gethostbyaddr
2938 static WIN_hostent* __ws_gethostbyaddr(const char *addr, int len, int type, int dup_flag)
2940 WIN_hostent *retval = NULL;
2942 struct hostent* host;
2943 #if HAVE_LINUX_GETHOSTBYNAME_R_6
2946 struct hostent hostentry;
2949 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
2951 int res = gethostbyaddr_r(addr, len, type,
2952 &hostentry, extrabuf, ebufsize, &host, &locerr);
2953 if( res != ERANGE) break;
2955 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
2957 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
2959 EnterCriticalSection( &csWSgetXXXbyYYY );
2960 host = gethostbyaddr(addr, len, type);
2961 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
2965 if( WS_dup_he(host, dup_flag) )
2968 SetLastError(WSAENOBUFS);
2970 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
2971 HeapFree(GetProcessHeap(),0,extrabuf);
2973 LeaveCriticalSection( &csWSgetXXXbyYYY );
2978 /***********************************************************************
2979 * gethostbyaddr (WINSOCK.51)
2981 SEGPTR WINAPI WINSOCK_gethostbyaddr16(const char *addr, INT16 len, INT16 type)
2983 TRACE("ptr %p, len %d, type %d\n", addr, len, type);
2984 if (!__ws_gethostbyaddr( addr, len, type, WS_DUP_SEGPTR )) return 0;
2985 return he_buffer_seg;
2988 /***********************************************************************
2989 * gethostbyaddr (WS2_32.51)
2991 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len,
2994 TRACE("ptr %08x, len %d, type %d\n",
2995 (unsigned) addr, len, type);
2996 return __ws_gethostbyaddr(addr, len, type, WS_DUP_LINEAR);
2999 /***********************************************************************
3000 * __ws_gethostbyname
3002 static WIN_hostent * __ws_gethostbyname(const char *name, int dup_flag)
3004 WIN_hostent *retval = NULL;
3005 struct hostent* host;
3006 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3009 struct hostent hostentry;
3010 int locerr = ENOBUFS;
3012 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3014 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
3015 if( res != ERANGE) break;
3017 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3019 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3021 EnterCriticalSection( &csWSgetXXXbyYYY );
3022 host = gethostbyname(name);
3023 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3027 if( WS_dup_he(host, dup_flag) )
3029 else SetLastError(WSAENOBUFS);
3031 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3032 HeapFree(GetProcessHeap(),0,extrabuf);
3034 LeaveCriticalSection( &csWSgetXXXbyYYY );
3039 /***********************************************************************
3040 * gethostbyname (WINSOCK.52)
3042 SEGPTR WINAPI WINSOCK_gethostbyname16(const char *name)
3044 TRACE( "%s\n", debugstr_a(name) );
3045 if (!__ws_gethostbyname( name, WS_DUP_SEGPTR )) return 0;
3046 return he_buffer_seg;
3049 /***********************************************************************
3050 * gethostbyname (WS2_32.52)
3052 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
3054 TRACE( "%s\n", debugstr_a(name) );
3055 return __ws_gethostbyname( name, WS_DUP_LINEAR );
3059 /***********************************************************************
3060 * __ws_getprotobyname
3062 static WIN_protoent* __ws_getprotobyname(const char *name, int dup_flag)
3064 WIN_protoent* retval = NULL;
3065 #ifdef HAVE_GETPROTOBYNAME
3066 struct protoent* proto;
3067 EnterCriticalSection( &csWSgetXXXbyYYY );
3068 if( (proto = getprotobyname(name)) != NULL )
3070 if( WS_dup_pe(proto, dup_flag) )
3072 else SetLastError(WSAENOBUFS);
3075 MESSAGE("protocol %s not found; You might want to add "
3076 "this to /etc/protocols\n", debugstr_a(name) );
3077 SetLastError(WSANO_DATA);
3079 LeaveCriticalSection( &csWSgetXXXbyYYY );
3084 /***********************************************************************
3085 * getprotobyname (WINSOCK.53)
3087 SEGPTR WINAPI WINSOCK_getprotobyname16(const char *name)
3089 TRACE( "%s\n", debugstr_a(name) );
3090 if (!__ws_getprotobyname(name, WS_DUP_SEGPTR)) return 0;
3091 return pe_buffer_seg;
3094 /***********************************************************************
3095 * getprotobyname (WS2_32.53)
3097 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
3099 TRACE( "%s\n", debugstr_a(name) );
3100 return __ws_getprotobyname(name, WS_DUP_LINEAR);
3104 /***********************************************************************
3105 * __ws_getprotobynumber
3107 static WIN_protoent* __ws_getprotobynumber(int number, int dup_flag)
3109 WIN_protoent* retval = NULL;
3110 #ifdef HAVE_GETPROTOBYNUMBER
3111 struct protoent* proto;
3112 EnterCriticalSection( &csWSgetXXXbyYYY );
3113 if( (proto = getprotobynumber(number)) != NULL )
3115 if( WS_dup_pe(proto, dup_flag) )
3117 else SetLastError(WSAENOBUFS);
3120 MESSAGE("protocol number %d not found; You might want to add "
3121 "this to /etc/protocols\n", number );
3122 SetLastError(WSANO_DATA);
3124 LeaveCriticalSection( &csWSgetXXXbyYYY );
3129 /***********************************************************************
3130 * getprotobynumber (WINSOCK.54)
3132 SEGPTR WINAPI WINSOCK_getprotobynumber16(INT16 number)
3134 TRACE("%i\n", number);
3135 if (!__ws_getprotobynumber(number, WS_DUP_SEGPTR)) return 0;
3136 return pe_buffer_seg;
3139 /***********************************************************************
3140 * getprotobynumber (WS2_32.54)
3142 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
3144 TRACE("%i\n", number);
3145 return __ws_getprotobynumber(number, WS_DUP_LINEAR);
3149 /***********************************************************************
3150 * __ws_getservbyname
3152 static WIN_servent* __ws_getservbyname(const char *name, const char *proto, int dup_flag)
3154 WIN_servent* retval = NULL;
3155 struct servent* serv;
3156 int i = wsi_strtolo( name, proto );
3159 EnterCriticalSection( &csWSgetXXXbyYYY );
3160 serv = getservbyname(local_buffer,
3161 proto ? (local_buffer + i) : NULL);
3164 if( WS_dup_se(serv, dup_flag) )
3166 else SetLastError(WSAENOBUFS);
3169 MESSAGE("service %s protocol %s not found; You might want to add "
3170 "this to /etc/services\n", debugstr_a(local_buffer),
3171 proto ? debugstr_a(local_buffer+i):"*");
3172 SetLastError(WSANO_DATA);
3174 LeaveCriticalSection( &csWSgetXXXbyYYY );
3176 else SetLastError(WSAENOBUFS);
3180 /***********************************************************************
3181 * getservbyname (WINSOCK.55)
3183 SEGPTR WINAPI WINSOCK_getservbyname16(const char *name, const char *proto)
3185 TRACE( "%s, %s\n", debugstr_a(name), debugstr_a(proto) );
3186 if (!__ws_getservbyname(name, proto, WS_DUP_SEGPTR)) return 0;
3187 return se_buffer_seg;
3190 /***********************************************************************
3191 * getservbyname (WS2_32.55)
3193 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
3195 TRACE( "%s, %s\n", debugstr_a(name), debugstr_a(proto) );
3196 return __ws_getservbyname(name, proto, WS_DUP_LINEAR);
3200 /***********************************************************************
3201 * __ws_getservbyport
3203 static WIN_servent* __ws_getservbyport(int port, const char* proto, int dup_flag)
3205 WIN_servent* retval = NULL;
3206 #ifdef HAVE_GETSERVBYPORT
3207 struct servent* serv;
3208 if (!proto || wsi_strtolo( proto, NULL )) {
3209 EnterCriticalSection( &csWSgetXXXbyYYY );
3210 if( (serv = getservbyport(port, (proto) ? local_buffer : NULL)) != NULL ) {
3211 if( WS_dup_se(serv, dup_flag) )
3213 else SetLastError(WSAENOBUFS);
3216 MESSAGE("service on port %lu protocol %s not found; You might want to add "
3217 "this to /etc/services\n", (unsigned long)ntohl(port),
3218 proto ? debugstr_a(local_buffer) : "*");
3219 SetLastError(WSANO_DATA);
3221 LeaveCriticalSection( &csWSgetXXXbyYYY );
3223 else SetLastError(WSAENOBUFS);
3228 /***********************************************************************
3229 * getservbyport (WINSOCK.56)
3231 SEGPTR WINAPI WINSOCK_getservbyport16(INT16 port, const char *proto)
3233 TRACE("%d (i.e. port %d), %s\n", (int)port, (int)ntohl(port), debugstr_a(proto));
3234 if (!__ws_getservbyport(port, proto, WS_DUP_SEGPTR)) return 0;
3235 return se_buffer_seg;
3238 /***********************************************************************
3239 * getservbyport (WS2_32.56)
3241 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
3243 TRACE("%d (i.e. port %d), %s\n", (int)port, (int)ntohl(port), debugstr_a(proto));
3244 return __ws_getservbyport(port, proto, WS_DUP_LINEAR);
3248 /***********************************************************************
3249 * gethostname (WS2_32.57)
3251 int WINAPI WS_gethostname(char *name, int namelen)
3253 TRACE("name %p, len %d\n", name, namelen);
3255 if (gethostname(name, namelen) == 0)
3257 TRACE("<- '%s'\n", name);
3260 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
3261 TRACE("<- ERROR !\n");
3262 return SOCKET_ERROR;
3265 /***********************************************************************
3266 * gethostname (WINSOCK.57)
3268 INT16 WINAPI WINSOCK_gethostname16(char *name, INT16 namelen)
3270 return (INT16)WS_gethostname(name, namelen);
3274 /* ------------------------------------- Windows sockets extensions -- *
3276 * ------------------------------------------------------------------- */
3278 /***********************************************************************
3279 * WSAEnumNetworkEvents (WS2_32.36)
3281 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
3285 TRACE("%08x, hEvent %p, lpEvent %08x\n", s, hEvent, (unsigned)lpEvent );
3287 SERVER_START_REQ( get_socket_event )
3289 req->handle = SOCKET2HANDLE(s);
3290 req->service = TRUE;
3291 req->c_event = hEvent;
3292 wine_server_set_reply( req, lpEvent->iErrorCode, sizeof(lpEvent->iErrorCode) );
3293 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
3297 SetLastError(WSAEINVAL);
3298 return SOCKET_ERROR;
3301 /***********************************************************************
3302 * WSAEventSelect (WS2_32.39)
3304 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
3308 TRACE("%08x, hEvent %p, event %08x\n", s, hEvent, (unsigned)lEvent );
3310 SERVER_START_REQ( set_socket_event )
3312 req->handle = SOCKET2HANDLE(s);
3314 req->event = hEvent;
3317 ret = wine_server_call( req );
3321 SetLastError(WSAEINVAL);
3322 return SOCKET_ERROR;
3325 /**********************************************************************
3326 * WSAGetOverlappedResult (WS2_32.40)
3328 BOOL WINAPI WSAGetOverlappedResult ( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
3329 LPDWORD lpcbTransfer, BOOL fWait,
3334 TRACE ( "socket %d ovl %p trans %p, wait %d flags %p\n",
3335 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
3337 if ( !(lpOverlapped && lpOverlapped->hEvent) )
3339 ERR ( "Invalid pointer\n" );
3340 WSASetLastError (WSA_INVALID_PARAMETER);
3346 while ( WaitForSingleObjectEx (lpOverlapped->hEvent, INFINITE, TRUE) == STATUS_USER_APC );
3348 else if ( lpOverlapped->Internal == STATUS_PENDING )
3350 /* Wait in order to give APCs a chance to run. */
3351 /* This is cheating, so we must set the event again in case of success -
3352 it may be a non-manual reset event. */
3353 while ( (r = WaitForSingleObjectEx (lpOverlapped->hEvent, 0, TRUE)) == STATUS_USER_APC );
3354 if ( r == WAIT_OBJECT_0 )
3355 NtSetEvent ( lpOverlapped->hEvent, NULL );
3359 *lpcbTransfer = lpOverlapped->InternalHigh;
3362 *lpdwFlags = lpOverlapped->Offset;
3364 switch ( lpOverlapped->Internal )
3366 case STATUS_SUCCESS:
3368 case STATUS_PENDING:
3369 WSASetLastError ( WSA_IO_INCOMPLETE );
3370 if (fWait) ERR ("PENDING status after waiting!\n");
3373 WSASetLastError ( NtStatusToWSAError ( lpOverlapped->Internal ));
3379 /***********************************************************************
3380 * WSAAsyncSelect (WS2_32.101)
3382 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
3386 TRACE("%x, hWnd %p, uMsg %08x, event %08lx\n", s, hWnd, uMsg, lEvent );
3388 SERVER_START_REQ( set_socket_event )
3390 req->handle = SOCKET2HANDLE(s);
3395 ret = wine_server_call( req );
3399 SetLastError(WSAEINVAL);
3400 return SOCKET_ERROR;
3403 /***********************************************************************
3404 * WSAAsyncSelect (WINSOCK.101)
3406 INT16 WINAPI WSAAsyncSelect16(SOCKET16 s, HWND16 hWnd, UINT16 wMsg, LONG lEvent)
3408 return (INT16)WSAAsyncSelect( s, HWND_32(hWnd), wMsg, lEvent );
3411 /***********************************************************************
3412 * WSARecvEx (WINSOCK.1107)
3414 * See description for WSARecvEx()
3416 INT16 WINAPI WSARecvEx16(SOCKET16 s, char *buf, INT16 len, INT16 *flags)
3418 FIXME("(WSARecvEx16) partial packet return value not set \n");
3420 return WINSOCK_recv16(s, buf, len, *flags);
3424 /***********************************************************************
3425 * WSACreateEvent (WS2_32.31)
3428 WSAEVENT WINAPI WSACreateEvent(void)
3430 /* Create a manual-reset event, with initial state: unsignealed */
3433 return CreateEventA(NULL, TRUE, FALSE, NULL);
3436 /***********************************************************************
3437 * WSACloseEvent (WS2_32.29)
3440 BOOL WINAPI WSACloseEvent(WSAEVENT event)
3442 TRACE ("event=%p\n", event);
3444 return CloseHandle(event);
3447 /***********************************************************************
3448 * WSASocketA (WS2_32.78)
3451 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
3452 LPWSAPROTOCOL_INFOA lpProtocolInfo,
3453 GROUP g, DWORD dwFlags)
3458 FIXME: The "advanced" parameters of WSASocketA (lpProtocolInfo,
3459 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
3462 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%lx\n",
3463 af, type, protocol, lpProtocolInfo, g, dwFlags );
3465 /* hack for WSADuplicateSocket */
3466 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
3467 ret = lpProtocolInfo->dwCatalogEntryId;
3468 TRACE("\tgot duplicate %04x\n", ret);
3472 /* check the socket family */
3476 case WS_AF_IPX: af = AF_IPX;
3482 SetLastError(WSAEAFNOSUPPORT);
3483 return INVALID_SOCKET;
3486 /* check the socket type */
3489 case WS_SOCK_STREAM:
3499 SetLastError(WSAESOCKTNOSUPPORT);
3500 return INVALID_SOCKET;
3503 /* check the protocol type */
3504 if ( protocol < 0 ) /* don't support negative values */
3506 SetLastError(WSAEPROTONOSUPPORT);
3507 return INVALID_SOCKET;
3510 if ( af == AF_UNSPEC) /* did they not specify the address family? */
3514 if (type == SOCK_STREAM) { af = AF_INET; break; }
3516 if (type == SOCK_DGRAM) { af = AF_INET; break; }
3517 default: SetLastError(WSAEPROTOTYPE); return INVALID_SOCKET;
3520 SERVER_START_REQ( create_socket )
3524 req->protocol = protocol;
3525 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
3526 req->flags = dwFlags;
3527 req->inherit = TRUE;
3528 set_error( wine_server_call( req ) );
3529 ret = HANDLE2SOCKET( reply->handle );
3534 TRACE("\tcreated %04x\n", ret );
3538 if (GetLastError() == WSAEACCES) /* raw socket denied */
3540 if (type == SOCK_RAW)
3541 MESSAGE("WARNING: Trying to create a socket of type SOCK_RAW, will fail unless running as root\n");
3543 MESSAGE("WS_SOCKET: not enough privileges to create socket, try running as root\n");
3544 SetLastError(WSAESOCKTNOSUPPORT);
3547 WARN("\t\tfailed!\n");
3548 return INVALID_SOCKET;
3552 /***********************************************************************
3553 * __WSAFDIsSet (WINSOCK.151)
3555 INT16 WINAPI __WSAFDIsSet16(SOCKET16 s, ws_fd_set16 *set)
3557 int i = set->fd_count;
3559 TRACE("(%d,%8lx(%i))\n", s,(unsigned long)set, i);
3562 if (set->fd_array[i] == s) return 1;
3566 /***********************************************************************
3567 * __WSAFDIsSet (WS2_32.151)
3569 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
3571 int i = set->fd_count;
3573 TRACE("(%d,%8lx(%i))\n", s,(unsigned long)set, i);
3576 if (set->fd_array[i] == s) return 1;
3580 /***********************************************************************
3581 * WSAIsBlocking (WINSOCK.114)
3582 * WSAIsBlocking (WS2_32.114)
3584 BOOL WINAPI WSAIsBlocking(void)
3586 /* By default WinSock should set all its sockets to non-blocking mode
3587 * and poll in PeekMessage loop when processing "blocking" ones. This
3588 * function is supposed to tell if the program is in this loop. Our
3589 * blocking calls are truly blocking so we always return FALSE.
3591 * Note: It is allowed to call this function without prior WSAStartup().
3598 /***********************************************************************
3599 * WSACancelBlockingCall (WINSOCK.113)
3600 * WSACancelBlockingCall (WS2_32.113)
3602 INT WINAPI WSACancelBlockingCall(void)
3609 /***********************************************************************
3610 * WSASetBlockingHook (WINSOCK.109)
3612 FARPROC16 WINAPI WSASetBlockingHook16(FARPROC16 lpBlockFunc)
3614 FARPROC16 prev = (FARPROC16)blocking_hook;
3615 blocking_hook = (FARPROC)lpBlockFunc;
3616 TRACE("hook %p\n", lpBlockFunc);
3621 /***********************************************************************
3622 * WSASetBlockingHook (WS2_32.109)
3624 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
3626 FARPROC prev = blocking_hook;
3627 blocking_hook = lpBlockFunc;
3628 TRACE("hook %p\n", lpBlockFunc);
3633 /***********************************************************************
3634 * WSAUnhookBlockingHook (WINSOCK.110)
3636 INT16 WINAPI WSAUnhookBlockingHook16(void)
3638 blocking_hook = NULL;
3643 /***********************************************************************
3644 * WSAUnhookBlockingHook (WS2_32.110)
3646 INT WINAPI WSAUnhookBlockingHook(void)
3648 blocking_hook = NULL;
3653 /* ----------------------------------- end of API stuff */
3655 /* ----------------------------------- helper functions -
3657 * TODO: Merge WS_dup_..() stuff into one function that
3658 * would operate with a generic structure containing internal
3659 * pointers (via a template of some kind).
3662 static int list_size(char** l, int item_size)
3667 j += (item_size) ? item_size : strlen(l[i]) + 1;
3668 j += (i + 1) * sizeof(char*); }
3672 static int list_dup(char** l_src, char* ref, char* base, int item_size)
3674 /* base is either either equal to ref or 0 or SEGPTR */
3677 char** l_to = (char**)ref;
3680 for(j=0;l_src[j];j++) ;
3681 p += (j + 1) * sizeof(char*);
3683 { l_to[i] = base + (p - ref);
3684 k = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
3685 memcpy(p, l_src[i], k); p += k; }
3692 static int hostent_size(struct hostent* p_he)
3696 { size = sizeof(struct hostent);
3697 size += strlen(p_he->h_name) + 1;
3698 size += list_size(p_he->h_aliases, 0);
3699 size += list_size(p_he->h_addr_list, p_he->h_length ); }
3703 /* duplicate hostent entry
3704 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
3705 * Dito for protoent and servent.
3707 static int WS_dup_he(struct hostent* p_he, int flag)
3709 /* Convert hostent structure into ws_hostent so that the data fits
3710 * into local_buffer. Internal pointers can be linear, SEGPTR, or
3711 * relative to local_buffer depending on "flag" value. Returns size
3712 * of the data copied.
3715 int size = hostent_size(p_he);
3718 char *p_name,*p_aliases,*p_addr,*p_base,*p;
3720 struct ws_hostent16 *p_to16;
3721 struct WS_hostent *p_to32;
3723 check_buffer_he(size);
3729 p_base = (flag & WS_DUP_SEGPTR) ? (char*)he_buffer_seg : he_buffer;
3730 p += (flag & WS_DUP_SEGPTR) ?
3731 sizeof(struct ws_hostent16) : sizeof(struct WS_hostent);
3733 strcpy(p, p_he->h_name); p += strlen(p) + 1;
3735 p += list_dup(p_he->h_aliases, p, p_base + (p - p_to), 0);
3737 list_dup(p_he->h_addr_list, p, p_base + (p - p_to), p_he->h_length);
3739 if (flag & WS_DUP_SEGPTR) /* Win16 */
3741 p_to16->h_addrtype = (INT16)p_he->h_addrtype;
3742 p_to16->h_length = (INT16)p_he->h_length;
3743 p_to16->h_name = (SEGPTR)(p_base + (p_name - p_to));
3744 p_to16->h_aliases = (SEGPTR)(p_base + (p_aliases - p_to));
3745 p_to16->h_addr_list = (SEGPTR)(p_base + (p_addr - p_to));
3746 size += (sizeof(struct ws_hostent16) - sizeof(struct hostent));
3750 p_to32->h_addrtype = p_he->h_addrtype;
3751 p_to32->h_length = p_he->h_length;
3752 p_to32->h_name = (p_base + (p_name - p_to));
3753 p_to32->h_aliases = (char **)(p_base + (p_aliases - p_to));
3754 p_to32->h_addr_list = (char **)(p_base + (p_addr - p_to));
3755 size += (sizeof(struct WS_hostent) - sizeof(struct hostent));
3761 /* ----- protoent */
3763 static int protoent_size(struct protoent* p_pe)
3767 { size = sizeof(struct protoent);
3768 size += strlen(p_pe->p_name) + 1;
3769 size += list_size(p_pe->p_aliases, 0); }
3773 static int WS_dup_pe(struct protoent* p_pe, int flag)
3775 int size = protoent_size(p_pe);
3779 struct ws_protoent16 *p_to16;
3780 struct WS_protoent *p_to32;
3781 char *p_name,*p_aliases,*p_base,*p;
3783 check_buffer_pe(size);
3788 p_base = (flag & WS_DUP_SEGPTR) ? (char*)pe_buffer_seg : pe_buffer;
3789 p += (flag & WS_DUP_SEGPTR) ?
3790 sizeof(struct ws_protoent16) : sizeof(struct WS_protoent);
3792 strcpy(p, p_pe->p_name); p += strlen(p) + 1;
3794 list_dup(p_pe->p_aliases, p, p_base + (p - p_to), 0);
3796 if (flag & WS_DUP_SEGPTR) /* Win16 */
3798 p_to16->p_proto = (INT16)p_pe->p_proto;
3799 p_to16->p_name = (SEGPTR)(p_base) + (p_name - p_to);
3800 p_to16->p_aliases = (SEGPTR)((p_base) + (p_aliases - p_to));
3801 size += (sizeof(struct ws_protoent16) - sizeof(struct protoent));
3805 p_to32->p_proto = p_pe->p_proto;
3806 p_to32->p_name = (p_base) + (p_name - p_to);
3807 p_to32->p_aliases = (char **)((p_base) + (p_aliases - p_to));
3808 size += (sizeof(struct WS_protoent) - sizeof(struct protoent));
3816 static int servent_size(struct servent* p_se)
3820 { size += sizeof(struct servent);
3821 size += strlen(p_se->s_proto) + strlen(p_se->s_name) + 2;
3822 size += list_size(p_se->s_aliases, 0); }
3826 static int WS_dup_se(struct servent* p_se, int flag)
3828 int size = servent_size(p_se);
3831 char *p_name,*p_aliases,*p_proto,*p_base,*p;
3833 struct ws_servent16 *p_to16;
3834 struct WS_servent *p_to32;
3836 check_buffer_se(size);
3841 p_base = (flag & WS_DUP_SEGPTR) ? (char*)se_buffer_seg : se_buffer;
3842 p += (flag & WS_DUP_SEGPTR) ?
3843 sizeof(struct ws_servent16) : sizeof(struct WS_servent);
3845 strcpy(p, p_se->s_name); p += strlen(p) + 1;
3847 strcpy(p, p_se->s_proto); p += strlen(p) + 1;
3849 list_dup(p_se->s_aliases, p, p_base + (p - p_to), 0);
3851 if (flag & WS_DUP_SEGPTR) /* Win16 */
3853 p_to16->s_port = (INT16)p_se->s_port;
3854 p_to16->s_name = (SEGPTR)(p_base + (p_name - p_to));
3855 p_to16->s_proto = (SEGPTR)(p_base + (p_proto - p_to));
3856 p_to16->s_aliases = (SEGPTR)(p_base + (p_aliases - p_to));
3857 size += (sizeof(struct ws_servent16) - sizeof(struct servent));
3861 p_to32->s_port = p_se->s_port;
3862 p_to32->s_name = (p_base + (p_name - p_to));
3863 p_to32->s_proto = (p_base + (p_proto - p_to));
3864 p_to32->s_aliases = (char **)(p_base + (p_aliases - p_to));
3865 size += (sizeof(struct WS_servent) - sizeof(struct servent));
3871 /* ----------------------------------- error handling */
3873 UINT16 wsaErrno(void)
3875 int loc_errno = errno;
3876 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
3880 case EINTR: return WSAEINTR;
3881 case EBADF: return WSAEBADF;
3883 case EACCES: return WSAEACCES;
3884 case EFAULT: return WSAEFAULT;
3885 case EINVAL: return WSAEINVAL;
3886 case EMFILE: return WSAEMFILE;
3887 case EWOULDBLOCK: return WSAEWOULDBLOCK;
3888 case EINPROGRESS: return WSAEINPROGRESS;
3889 case EALREADY: return WSAEALREADY;
3890 case ENOTSOCK: return WSAENOTSOCK;
3891 case EDESTADDRREQ: return WSAEDESTADDRREQ;
3892 case EMSGSIZE: return WSAEMSGSIZE;
3893 case EPROTOTYPE: return WSAEPROTOTYPE;
3894 case ENOPROTOOPT: return WSAENOPROTOOPT;
3895 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
3896 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
3897 case EOPNOTSUPP: return WSAEOPNOTSUPP;
3898 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
3899 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
3900 case EADDRINUSE: return WSAEADDRINUSE;
3901 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
3902 case ENETDOWN: return WSAENETDOWN;
3903 case ENETUNREACH: return WSAENETUNREACH;
3904 case ENETRESET: return WSAENETRESET;
3905 case ECONNABORTED: return WSAECONNABORTED;
3907 case ECONNRESET: return WSAECONNRESET;
3908 case ENOBUFS: return WSAENOBUFS;
3909 case EISCONN: return WSAEISCONN;
3910 case ENOTCONN: return WSAENOTCONN;
3911 case ESHUTDOWN: return WSAESHUTDOWN;
3912 case ETOOMANYREFS: return WSAETOOMANYREFS;
3913 case ETIMEDOUT: return WSAETIMEDOUT;
3914 case ECONNREFUSED: return WSAECONNREFUSED;
3915 case ELOOP: return WSAELOOP;
3916 case ENAMETOOLONG: return WSAENAMETOOLONG;
3917 case EHOSTDOWN: return WSAEHOSTDOWN;
3918 case EHOSTUNREACH: return WSAEHOSTUNREACH;
3919 case ENOTEMPTY: return WSAENOTEMPTY;
3921 case EPROCLIM: return WSAEPROCLIM;
3924 case EUSERS: return WSAEUSERS;
3927 case EDQUOT: return WSAEDQUOT;
3930 case ESTALE: return WSAESTALE;
3933 case EREMOTE: return WSAEREMOTE;
3936 /* just in case we ever get here and there are no problems */
3939 WARN("Unknown errno %d!\n", loc_errno);
3940 return WSAEOPNOTSUPP;
3944 UINT16 wsaHerrno(int loc_errno)
3947 WARN("h_errno %d.\n", loc_errno);
3951 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
3952 case TRY_AGAIN: return WSATRY_AGAIN;
3953 case NO_RECOVERY: return WSANO_RECOVERY;
3954 case NO_DATA: return WSANO_DATA;
3955 case ENOBUFS: return WSAENOBUFS;
3959 WARN("Unknown h_errno %d!\n", loc_errno);
3960 return WSAEOPNOTSUPP;
3965 /***********************************************************************
3966 * WSARecv (WS2_32.67)
3968 int WINAPI WSARecv (SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3969 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
3970 LPWSAOVERLAPPED lpOverlapped,
3971 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
3973 return WSARecvFrom (s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
3974 NULL, NULL, lpOverlapped, lpCompletionRoutine);
3977 /***********************************************************************
3978 * WSARecvFrom (WS2_32.69)
3980 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3981 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
3982 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
3983 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3986 int i, n, fd, err = WSAENOTSOCK, flags, ret;
3987 struct iovec* iovec;
3988 struct ws2_async *wsa;
3991 TRACE("socket %04x, wsabuf %p, nbufs %ld, flags %ld, from %p, fromlen %ld, ovl %p, func %p\n",
3992 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
3993 (lpFromlen ? *lpFromlen : -1L),
3994 lpOverlapped, lpCompletionRoutine);
3996 fd = _get_sock_fd_type( s, GENERIC_READ, &type, &flags );
3997 TRACE ( "fd=%d, type=%d, flags=%x\n", fd, type, flags );
4001 err = WSAGetLastError ();
4005 iovec = HeapAlloc ( GetProcessHeap(), 0, dwBufferCount * sizeof (struct iovec) );
4012 for (i = 0; i < dwBufferCount; i++)
4014 iovec[i].iov_base = lpBuffers[i].buf;
4015 iovec[i].iov_len = lpBuffers[i].len;
4018 if ( (lpOverlapped || lpCompletionRoutine) && flags & FD_FLAG_OVERLAPPED )
4020 wsa = WS2_make_async ( s, fd, ASYNC_TYPE_READ, iovec, dwBufferCount,
4021 lpFlags, lpFrom, lpFromlen,
4022 lpOverlapped, lpCompletionRoutine );
4030 if ( ( ret = register_new_async ( &wsa->async )) )
4032 err = NtStatusToWSAError ( ret );
4034 if ( !lpOverlapped )
4035 HeapFree ( GetProcessHeap(), 0, wsa->overlapped );
4036 HeapFree ( GetProcessHeap(), 0, wsa );
4040 /* Try immediate completion */
4041 if ( lpOverlapped && !NtResetEvent( lpOverlapped->hEvent, NULL ) )
4043 if ( WSAGetOverlappedResult ( s, lpOverlapped,
4044 lpNumberOfBytesRecvd, FALSE, lpFlags) )
4047 if ( (err = WSAGetLastError ()) != WSA_IO_INCOMPLETE )
4051 WSASetLastError ( WSA_IO_PENDING );
4052 return SOCKET_ERROR;
4055 if ( _is_blocking(s) )
4058 /* FIXME: OOB and exceptfds? */
4062 n = WS2_recv ( fd, iovec, dwBufferCount, lpFrom, lpFromlen, lpFlags );
4069 TRACE(" -> %i bytes\n", n);
4070 *lpNumberOfBytesRecvd = n;
4072 HeapFree (GetProcessHeap(), 0, iovec);
4074 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4079 HeapFree (GetProcessHeap(), 0, iovec);
4085 WARN(" -> ERROR %d\n", err);
4086 WSASetLastError ( err );
4087 return SOCKET_ERROR;
4090 /***********************************************************************
4091 * WSCInstallProvider (WS2_32.88)
4093 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
4094 LPCWSTR lpszProviderDllPath,
4095 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
4096 DWORD dwNumberOfEntries,
4099 FIXME("(%s, %s, %p, %ld, %p): stub !\n", debugstr_guid(lpProviderId),
4100 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
4101 dwNumberOfEntries, lpErrno);
4107 /***********************************************************************
4108 * WSCDeinstallProvider (WS2_32.83)
4110 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
4112 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
4118 /***********************************************************************
4119 * WSAAccept (WS2_32.26)
4121 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
4122 LPCONDITIONPROC lpfnCondition, DWORD dwCallbackData)
4125 int ret = 0, size = 0;
4126 WSABUF CallerId, CallerData, CalleeId, CalleeData;
4127 /* QOS SQOS, GQOS; */
4130 SOCKADDR src_addr, dst_addr;
4132 TRACE("Socket %u, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
4133 s, addr, addrlen, lpfnCondition, dwCallbackData);
4136 size = sizeof(src_addr);
4137 cs = WS_accept(s, &src_addr, &size);
4139 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
4141 CallerId.buf = (char *)&src_addr;
4142 CallerId.len = sizeof(src_addr);
4144 CallerData.buf = NULL;
4145 CallerData.len = (ULONG)NULL;
4147 WS_getsockname(cs, &dst_addr, &size);
4149 CalleeId.buf = (char *)&dst_addr;
4150 CalleeId.len = sizeof(dst_addr);
4153 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
4154 &CalleeId, &CalleeData, &g, dwCallbackData);
4159 if (addr && addrlen)
4160 addr = memcpy(addr, &src_addr, (*addrlen > size) ? size : *addrlen );
4163 SERVER_START_REQ ( set_socket_deferred )
4165 req->handle = SOCKET2HANDLE (s);
4166 req->deferred = SOCKET2HANDLE (cs);
4167 if ( !wine_server_call_err ( req ) )
4169 SetLastError ( WSATRY_AGAIN );
4170 WS_closesocket ( cs );
4174 return SOCKET_ERROR;
4177 SetLastError(WSAECONNREFUSED);
4178 return SOCKET_ERROR;
4180 FIXME("Unknown return type from Condition function\n");
4181 SetLastError(WSAENOTSOCK);
4182 return SOCKET_ERROR;
4185 SetLastError(WSAENOTSOCK);
4186 return SOCKET_ERROR;
4189 /***********************************************************************
4190 * WSAEnumProtocolsA (WS2_32.37)
4192 int WINAPI WSAEnumProtocolsA(LPINT lpiProtocols, LPWSAPROTOCOL_INFOA lpProtocolBuffer, LPDWORD lpdwBufferLength)
4194 FIXME("(%p,%p,%p): stub\n", lpiProtocols,lpProtocolBuffer, lpdwBufferLength);
4198 /***********************************************************************
4199 * WSAEnumProtocolsW (WS2_32.38)
4201 int WINAPI WSAEnumProtocolsW(LPINT lpiProtocols, LPWSAPROTOCOL_INFOW lpProtocolBuffer, LPDWORD lpdwBufferLength)
4203 FIXME("(%p,%p,%p): stub\n", lpiProtocols,lpProtocolBuffer, lpdwBufferLength);
4207 /***********************************************************************
4208 * WSADuplicateSocketA (WS2_32.32)
4210 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
4214 TRACE("(%d,%lx,%p)\n", s, dwProcessId, lpProtocolInfo);
4215 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
4216 /* FIXME: WS_getsockopt(s, WS_SOL_SOCKET, SO_PROTOCOL_INFO, lpProtocolInfo, sizeof(*lpProtocolInfo)); */
4217 /* I don't know what the real Windoze does next, this is a hack */
4218 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
4219 * the target use the global duplicate, or we could copy a reference to us to the structure
4220 * and let the target duplicate it from us, but let's do it as simple as possible */
4221 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
4222 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
4223 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
4224 0, FALSE, DUPLICATE_SAME_ACCESS);
4225 CloseHandle(hProcess);
4226 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
4230 /***********************************************************************
4231 * WSAInstallServiceClassA (WS2_32.48)
4233 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
4235 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
4239 /***********************************************************************
4240 * WSAInstallServiceClassW (WS2_32.49)
4242 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
4244 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));