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 #define MAP_OPTION(opt) { WS_##opt, opt }
248 static const int ws_sock_map[][2] =
250 MAP_OPTION( SO_DEBUG ),
251 MAP_OPTION( SO_REUSEADDR ),
252 MAP_OPTION( SO_KEEPALIVE ),
253 MAP_OPTION( SO_DONTROUTE ),
254 MAP_OPTION( SO_BROADCAST ),
255 MAP_OPTION( SO_LINGER ),
256 MAP_OPTION( SO_OOBINLINE ),
257 MAP_OPTION( SO_SNDBUF ),
258 MAP_OPTION( SO_RCVBUF ),
259 MAP_OPTION( SO_ERROR ),
260 MAP_OPTION( SO_TYPE ),
262 MAP_OPTION( SO_RCVTIMEO ),
265 MAP_OPTION( SO_SNDTIMEO ),
270 static const int ws_tcp_map[][2] =
273 MAP_OPTION( TCP_NODELAY ),
278 static const int ws_ip_map[][2] =
280 MAP_OPTION( IP_MULTICAST_IF ),
281 MAP_OPTION( IP_MULTICAST_TTL ),
282 MAP_OPTION( IP_MULTICAST_LOOP ),
283 MAP_OPTION( IP_ADD_MEMBERSHIP ),
284 MAP_OPTION( IP_DROP_MEMBERSHIP ),
285 MAP_OPTION( IP_OPTIONS ),
286 MAP_OPTION( IP_HDRINCL ),
287 MAP_OPTION( IP_TOS ),
288 MAP_OPTION( IP_TTL ),
292 static DWORD opentype_tls_index = -1; /* TLS index for SO_OPENTYPE flag */
294 inline static DWORD NtStatusToWSAError ( const DWORD status )
296 /* We only need to cover the status codes set by server async request handling */
300 case STATUS_SUCCESS: wserr = 0; break;
301 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
302 case STATUS_INVALID_HANDLE: wserr = WSAENOTSOCK; break; /* WSAEBADF ? */
303 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
304 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
305 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
306 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
307 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
309 if ( status >= WSABASEERR && status <= WSABASEERR+1004 )
310 /* It is not a NT status code but a winsock error */
314 wserr = RtlNtStatusToDosError( status );
315 FIXME ( "Status code %08lx converted to DOS error code %lx\n", status, wserr );
321 /* set last error code from NT status without mapping WSA errors */
322 inline static unsigned int set_error( unsigned int err )
326 err = NtStatusToWSAError ( err );
332 static char* check_buffer(int size);
334 inline static int _get_sock_fd(SOCKET s)
338 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), GENERIC_READ, &fd, NULL, NULL ) ))
343 inline static int _get_sock_fd_type( SOCKET s, DWORD access, enum fd_type *type, int *flags )
346 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, type, flags ) )) return -1;
347 if ( ( (access & GENERIC_READ) && (*flags & FD_FLAG_RECV_SHUTDOWN ) ) ||
348 ( (access & GENERIC_WRITE) && (*flags & FD_FLAG_SEND_SHUTDOWN ) ) )
351 WSASetLastError ( WSAESHUTDOWN );
357 static void _enable_event( HANDLE s, unsigned int event,
358 unsigned int sstate, unsigned int cstate )
360 SERVER_START_REQ( enable_socket_event )
364 req->sstate = sstate;
365 req->cstate = cstate;
366 wine_server_call( req );
371 static int _is_blocking(SOCKET s)
374 SERVER_START_REQ( get_socket_event )
376 req->handle = SOCKET2HANDLE(s);
377 req->service = FALSE;
379 wine_server_call( req );
380 ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
386 static unsigned int _get_sock_mask(SOCKET s)
389 SERVER_START_REQ( get_socket_event )
391 req->handle = SOCKET2HANDLE(s);
392 req->service = FALSE;
394 wine_server_call( req );
401 static void _sync_sock_state(SOCKET s)
403 /* do a dummy wineserver request in order to let
404 the wineserver run through its select loop once */
405 (void)_is_blocking(s);
408 static int _get_sock_error(SOCKET s, unsigned int bit)
410 int events[FD_MAX_EVENTS];
412 SERVER_START_REQ( get_socket_event )
414 req->handle = SOCKET2HANDLE(s);
415 req->service = FALSE;
417 wine_server_set_reply( req, events, sizeof(events) );
418 wine_server_call( req );
424 static void WINSOCK_DeleteIData(void)
426 /* delete scratch buffers */
428 UnMapLS( he_buffer_seg );
429 UnMapLS( se_buffer_seg );
430 UnMapLS( pe_buffer_seg );
431 UnMapLS( dbuffer_seg );
432 if (he_buffer) HeapFree( GetProcessHeap(), 0, he_buffer );
433 if (se_buffer) HeapFree( GetProcessHeap(), 0, se_buffer );
434 if (pe_buffer) HeapFree( GetProcessHeap(), 0, pe_buffer );
435 if (local_buffer) HeapFree( GetProcessHeap(), 0, local_buffer );
447 /***********************************************************************
448 * DllMain (WS2_32.init)
450 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
452 TRACE("%p 0x%lx %p\n", hInstDLL, fdwReason, fImpLoad);
454 case DLL_PROCESS_ATTACH:
455 opentype_tls_index = TlsAlloc();
457 case DLL_PROCESS_DETACH:
458 TlsFree( opentype_tls_index );
459 WINSOCK_DeleteIData();
465 /***********************************************************************
468 * Converts socket flags from Windows format.
469 * Return 1 if converted, 0 if not (error).
471 static int convert_sockopt(INT *level, INT *optname)
478 for(i=0; ws_sock_map[i][0]; i++)
480 if( ws_sock_map[i][0] == *optname )
482 *optname = ws_sock_map[i][1];
486 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
489 *level = IPPROTO_TCP;
490 for(i=0; ws_tcp_map[i][0]; i++)
492 if ( ws_tcp_map[i][0] == *optname )
494 *optname = ws_tcp_map[i][1];
498 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
502 for(i=0; ws_ip_map[i][0]; i++)
504 if (ws_ip_map[i][0] == *optname )
506 *optname = ws_ip_map[i][1];
510 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
512 default: FIXME("Unimplemented or unknown socket level\n");
517 /* ----------------------------------- Per-thread info (or per-process?) */
519 static int wsi_strtolo(const char* name, const char* opt)
521 /* Stuff a lowercase copy of the string into the local buffer */
523 int i = strlen(name) + 2;
524 char* p = check_buffer(i + ((opt)?strlen(opt):0));
528 do *p++ = tolower(*name); while(*name++);
529 i = (p - local_buffer);
530 if( opt ) do *p++ = tolower(*opt); while(*opt++);
536 static fd_set* fd_set_import( fd_set* fds, void* wsfds, int* highfd, int lfd[], BOOL b32 )
538 /* translate Winsock fd set into local fd set */
542 #define wsfds16 ((ws_fd_set16*)wsfds)
543 #define wsfds32 ((WS_fd_set*)wsfds)
547 count = b32 ? wsfds32->fd_count : wsfds16->fd_count;
549 for( i = 0; i < count; i++ )
551 int s = (b32) ? wsfds32->fd_array[i]
552 : wsfds16->fd_array[i];
553 int fd = _get_sock_fd(s);
557 if( fd > *highfd ) *highfd = fd;
569 inline static int sock_error_p(int s)
571 unsigned int optval, optlen;
573 optlen = sizeof(optval);
574 getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
575 if (optval) WARN("\t[%i] error: %d\n", s, optval);
579 static int fd_set_export( fd_set* fds, fd_set* exceptfds, void* wsfds, int lfd[], BOOL b32 )
583 /* translate local fd set into Winsock fd set, adding
584 * errors to exceptfds (only if app requested it) */
588 #define wsfds16 ((ws_fd_set16*)wsfds)
589 #define wsfds32 ((WS_fd_set*)wsfds)
590 int i, j, count = (b32) ? wsfds32->fd_count : wsfds16->fd_count;
592 for( i = 0, j = 0; i < count; i++ )
597 if( FD_ISSET(fd, fds) )
599 if ( exceptfds && sock_error_p(fd) )
601 FD_SET(fd, exceptfds);
605 wsfds32->fd_array[j++] = wsfds32->fd_array[i];
607 wsfds16->fd_array[j++] = wsfds16->fd_array[i];
614 if( b32 ) wsfds32->fd_count = j;
615 else wsfds16->fd_count = j;
624 static void fd_set_unimport( void* wsfds, int lfd[], BOOL b32 )
628 #define wsfds16 ((ws_fd_set16*)wsfds)
629 #define wsfds32 ((WS_fd_set*)wsfds)
630 int i, count = (b32) ? wsfds32->fd_count : wsfds16->fd_count;
632 for( i = 0; i < count; i++ )
642 static int do_block( int fd, int mask )
653 i = select( fd+1, &fds[0], &fds[1], &fds[2], NULL );
654 if (i <= 0) return -1;
657 if (FD_ISSET(fd, &fds[i]))
662 void* __ws_memalloc( int size )
664 return WS_ALLOC(size);
667 void __ws_memfree(void* ptr)
673 /* ----------------------------------- API -----
675 * Init / cleanup / error checking.
678 /***********************************************************************
679 * WSAStartup (WINSOCK.115)
681 * Create socket control struct, attach it to the global list and
682 * update a pointer in the task struct.
684 INT16 WINAPI WSAStartup16(UINT16 wVersionRequested, LPWSADATA16 lpWSAData)
686 static const WSADATA16 data =
692 #elif defined(__NetBSD__)
696 #elif defined(__FreeBSD__)
698 #elif defined(__OpenBSD__)
703 WS_MAX_SOCKETS_PER_PROCESS,
708 TRACE("verReq=%x\n", wVersionRequested);
710 if (LOBYTE(wVersionRequested) < 1 || (LOBYTE(wVersionRequested) == 1 &&
711 HIBYTE(wVersionRequested) < 1)) return WSAVERNOTSUPPORTED;
713 if (!lpWSAData) return WSAEINVAL;
715 /* initialize socket heap */
719 _WSHeap = HeapCreate(HEAP_ZERO_MEMORY, 8120, 32768);
722 ERR("Fatal: failed to create WinSock heap\n");
726 if( _WSHeap == 0 ) return WSASYSNOTREADY;
730 /* return winsock information */
732 memcpy(lpWSAData, &data, sizeof(data));
734 TRACE("succeeded\n");
738 /***********************************************************************
739 * WSAStartup (WS2_32.115)
741 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
743 TRACE("verReq=%x\n", wVersionRequested);
745 if (LOBYTE(wVersionRequested) < 1)
746 return WSAVERNOTSUPPORTED;
748 if (!lpWSAData) return WSAEINVAL;
750 /* initialize socket heap */
754 _WSHeap = HeapCreate(HEAP_ZERO_MEMORY, 8120, 32768);
757 ERR("Fatal: failed to create WinSock heap\n");
761 if( _WSHeap == 0 ) return WSASYSNOTREADY;
765 /* that's the whole of the negotiation for now */
766 lpWSAData->wVersion = wVersionRequested;
767 /* return winsock information */
768 lpWSAData->wHighVersion = 0x0202;
769 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
770 strcpy(lpWSAData->szSystemStatus, "Running" );
771 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
772 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
773 /* don't do anything with lpWSAData->lpVendorInfo */
774 /* (some apps don't allocate the space for this field) */
776 TRACE("succeeded\n");
781 /***********************************************************************
782 * WSACleanup (WINSOCK.116)
783 * WSACleanup (WS2_32.116)
785 INT WINAPI WSACleanup(void)
789 if (--num_startup > 0) return 0;
790 WINSOCK_DeleteIData();
793 SetLastError(WSANOTINITIALISED);
798 /***********************************************************************
799 * WSAGetLastError (WINSOCK.111)
800 * WSAGetLastError (WS2_32.111)
802 INT WINAPI WSAGetLastError(void)
804 return GetLastError();
807 /***********************************************************************
808 * WSASetLastError (WS2_32.112)
810 void WINAPI WSASetLastError(INT iError) {
811 SetLastError(iError);
814 /***********************************************************************
815 * WSASetLastError (WINSOCK.112)
817 void WINAPI WSASetLastError16(INT16 iError)
819 WSASetLastError(iError);
822 static char* check_buffer(int size)
824 static int local_buflen;
828 if (local_buflen >= size ) return local_buffer;
829 HeapFree( GetProcessHeap(), 0, local_buffer );
831 local_buffer = HeapAlloc( GetProcessHeap(), 0, (local_buflen = size) );
835 static struct ws_hostent* check_buffer_he(int size)
840 if (he_len >= size ) return he_buffer;
841 UnMapLS( he_buffer_seg );
842 HeapFree( GetProcessHeap(), 0, he_buffer );
844 he_buffer = HeapAlloc( GetProcessHeap(), 0, (he_len = size) );
845 he_buffer_seg = MapLS( he_buffer );
849 static void* check_buffer_se(int size)
854 if (se_len >= size ) return se_buffer;
855 UnMapLS( se_buffer_seg );
856 HeapFree( GetProcessHeap(), 0, se_buffer );
858 se_buffer = HeapAlloc( GetProcessHeap(), 0, (se_len = size) );
859 se_buffer_seg = MapLS( se_buffer );
863 static struct ws_protoent* check_buffer_pe(int size)
868 if (pe_len >= size ) return pe_buffer;
869 UnMapLS( pe_buffer_seg );
870 HeapFree( GetProcessHeap(), 0, pe_buffer );
872 pe_buffer = HeapAlloc( GetProcessHeap(), 0, (pe_len = size) );
873 pe_buffer_seg = MapLS( he_buffer );
877 /* ----------------------------------- i/o APIs */
880 #define SUPPORTED_PF(pf) ((pf)==WS_AF_INET || (pf)== WS_AF_IPX)
882 #define SUPPORTED_PF(pf) ((pf)==WS_AF_INET)
886 /**********************************************************************/
888 /* Returns the converted address if successful, NULL if it was too small to
889 * start with. Note that the returned pointer may be the original pointer
890 * if no conversion is necessary.
892 static const struct sockaddr* ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen, int *uaddrlen)
894 switch (wsaddr->sa_family)
899 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
900 struct sockaddr_ipx* uipx;
902 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
905 *uaddrlen=sizeof(struct sockaddr_ipx);
906 uipx=malloc(*uaddrlen);
907 uipx->sipx_family=AF_IPX;
908 uipx->sipx_port=wsipx->sa_socket;
909 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
912 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
913 #ifdef IPX_FRAME_NONE
914 uipx->sipx_type=IPX_FRAME_NONE;
916 memset(&uipx->sipx_zero,0,sizeof uipx->sipx_zero);
917 return (const struct sockaddr*)uipx;
922 if (wsaddrlen<sizeof(struct WS_sockaddr))
925 /* No conversion needed, just return the original address */
927 return (const struct sockaddr*)wsaddr;
932 /* Allocates a Unix sockaddr structure to receive the data */
933 inline struct sockaddr* ws_sockaddr_alloc(const struct WS_sockaddr* wsaddr, int* wsaddrlen, int* uaddrlen)
937 ERR( "WINE shouldn't pass a NULL wsaddr! Attempting to continue\n" );
939 /* This is not strictly the right thing to do. Hope it works however */
948 *uaddrlen=max(sizeof(struct sockaddr),*wsaddrlen);
950 return malloc(*uaddrlen);
953 /* Returns 0 if successful, -1 if the buffer is too small */
954 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, int uaddrlen, struct WS_sockaddr* wsaddr, int* wsaddrlen)
958 switch(uaddr->sa_family)
963 struct sockaddr_ipx* uipx=(struct sockaddr_ipx*)uaddr;
964 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
967 switch (*wsaddrlen) /* how much can we copy? */
972 wsipx->sa_socket=uipx->sipx_port;
976 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
984 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
990 wsipx->sa_family=WS_AF_IPX;
1002 /* No conversion needed */
1003 memcpy(wsaddr,uaddr,*wsaddrlen);
1004 if (*wsaddrlen<uaddrlen) {
1007 *wsaddrlen=uaddrlen;
1014 /* to be called to free the memory allocated by ws_sockaddr_ws2u or
1017 inline void ws_sockaddr_free(const struct sockaddr* uaddr, const struct WS_sockaddr* wsaddr)
1019 if (uaddr!=NULL && uaddr!=(const struct sockaddr*)wsaddr)
1023 /**************************************************************************
1024 * Functions for handling overlapped I/O
1025 **************************************************************************/
1027 static DWORD ws2_async_get_status (const struct async_private *ovp)
1029 return ((ws2_async*) ovp)->overlapped->Internal;
1032 static VOID ws2_async_set_status (struct async_private *ovp, const DWORD status)
1034 ((ws2_async*) ovp)->overlapped->Internal = status;
1037 static DWORD ws2_async_get_count (const struct async_private *ovp)
1039 return ((ws2_async*) ovp)->overlapped->InternalHigh;
1042 static void ws2_async_cleanup ( struct async_private *ap )
1044 struct ws2_async *as = (struct ws2_async*) ap;
1046 TRACE ( "as: %p uovl %p ovl %p\n", as, as->user_overlapped, as->overlapped );
1047 if ( !as->user_overlapped )
1049 if ( as->overlapped->hEvent != INVALID_HANDLE_VALUE )
1050 WSACloseEvent ( as->overlapped->hEvent );
1051 HeapFree ( GetProcessHeap(), 0, as->overlapped );
1055 HeapFree ( GetProcessHeap(), 0, as->iovec );
1057 HeapFree ( GetProcessHeap(), 0, as );
1060 static void CALLBACK ws2_async_call_completion (ULONG_PTR data)
1062 ws2_async* as = (ws2_async*) data;
1064 TRACE ("data: %p\n", as);
1066 as->completion_func ( NtStatusToWSAError (as->overlapped->Internal),
1067 as->overlapped->InternalHigh,
1068 as->user_overlapped,
1070 ws2_async_cleanup ( &as->async );
1073 /***********************************************************************
1074 * WS2_make_async (INTERNAL)
1077 static void WS2_async_recv (async_private *as);
1078 static void WS2_async_send (async_private *as);
1080 inline static struct ws2_async*
1081 WS2_make_async (SOCKET s, int fd, int type, struct iovec *iovec, DWORD dwBufferCount,
1082 LPDWORD lpFlags, struct WS_sockaddr *addr,
1083 LPINT addrlen, LPWSAOVERLAPPED lpOverlapped,
1084 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
1086 struct ws2_async *wsa = HeapAlloc ( GetProcessHeap(), 0, sizeof ( ws2_async ) );
1088 TRACE ( "wsa %p\n", wsa );
1093 wsa->async.ops = ( lpCompletionRoutine ? &ws2_async_ops : &ws2_nocomp_async_ops );
1094 wsa->async.handle = (HANDLE) s;
1096 wsa->async.type = type;
1099 case ASYNC_TYPE_READ:
1100 wsa->flags = *lpFlags;
1101 wsa->async.func = WS2_async_recv;
1102 wsa->addrlen.ptr = addrlen;
1104 case ASYNC_TYPE_WRITE:
1106 wsa->async.func = WS2_async_send;
1107 wsa->addrlen.val = *addrlen;
1110 ERR ("Invalid async type: %d\n", type);
1112 wsa->user_overlapped = lpOverlapped;
1113 wsa->completion_func = lpCompletionRoutine;
1115 wsa->n_iovecs = dwBufferCount;
1120 wsa->overlapped = lpOverlapped;
1121 wsa->async.event = ( lpCompletionRoutine ? INVALID_HANDLE_VALUE : lpOverlapped->hEvent );
1125 wsa->overlapped = HeapAlloc ( GetProcessHeap(), 0,
1126 sizeof (WSAOVERLAPPED) );
1127 if ( !wsa->overlapped )
1129 wsa->async.event = wsa->overlapped->hEvent = INVALID_HANDLE_VALUE;
1132 wsa->overlapped->InternalHigh = 0;
1133 TRACE ( "wsa %p, ops %p, h %p, ev %p, fd %d, func %p, ov %p, uov %p, cfunc %p\n",
1134 wsa, wsa->async.ops, wsa->async.handle, wsa->async.event, wsa->async.fd, wsa->async.func,
1135 wsa->overlapped, wsa->user_overlapped, wsa->completion_func );
1141 HeapFree ( GetProcessHeap(), 0, wsa );
1145 /***********************************************************************
1146 * WS2_recv (INTERNAL)
1148 * Work horse for both synchronous and asynchronous recv() operations.
1150 static int WS2_recv ( int fd, struct iovec* iov, int count,
1151 struct WS_sockaddr *lpFrom, LPINT lpFromlen,
1156 TRACE ( "fd %d, iovec %p, count %d addr %p, len %p, flags %lx\n",
1157 fd, iov, count, lpFrom, lpFromlen, *lpFlags);
1159 hdr.msg_name = NULL;
1164 dump_sockaddr (lpFrom);
1167 hdr.msg_namelen = *lpFromlen;
1168 hdr.msg_name = ws_sockaddr_alloc ( lpFrom, lpFromlen, &hdr.msg_namelen );
1169 if ( !hdr.msg_name )
1171 WSASetLastError ( WSAEFAULT );
1177 hdr.msg_namelen = 0;
1180 hdr.msg_iovlen = count;
1181 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1182 hdr.msg_accrights = NULL;
1183 hdr.msg_accrightslen = 0;
1185 hdr.msg_control = NULL;
1186 hdr.msg_controllen = 0;
1190 if ( (n = recvmsg (fd, &hdr, *lpFlags)) == -1 )
1192 TRACE ( "recvmsg error %d\n", errno);
1197 ws_sockaddr_u2ws ( hdr.msg_name, hdr.msg_namelen,
1198 lpFrom, lpFromlen ) != 0 )
1200 /* The from buffer was too small, but we read the data
1201 * anyway. Is that really bad?
1203 WSASetLastError ( WSAEFAULT );
1204 WARN ( "Address buffer too small\n" );
1209 ws_sockaddr_free ( hdr.msg_name, lpFrom );
1210 TRACE ("-> %d\n", n);
1214 /***********************************************************************
1215 * WS2_async_recv (INTERNAL)
1217 * Handler for overlapped recv() operations.
1219 static void WS2_async_recv ( async_private *as )
1221 ws2_async* wsa = (ws2_async*) as;
1224 TRACE ( "async %p\n", wsa );
1226 if ( wsa->overlapped->Internal != STATUS_PENDING )
1228 TRACE ( "status: %ld\n", wsa->overlapped->Internal );
1232 result = WS2_recv ( wsa->async.fd, wsa->iovec, wsa->n_iovecs,
1233 wsa->addr, wsa->addrlen.ptr, &wsa->flags );
1237 wsa->overlapped->Internal = STATUS_SUCCESS;
1238 wsa->overlapped->InternalHigh = result;
1239 TRACE ( "received %d bytes\n", result );
1240 _enable_event ( wsa->async.handle, FD_READ, 0, 0 );
1245 if ( err == WSAEINTR || err == WSAEWOULDBLOCK ) /* errno: EINTR / EAGAIN */
1247 wsa->overlapped->Internal = STATUS_PENDING;
1248 _enable_event ( wsa->async.handle, FD_READ, 0, 0 );
1249 TRACE ( "still pending\n" );
1253 wsa->overlapped->Internal = err;
1254 TRACE ( "Error: %x\n", err );
1258 /***********************************************************************
1259 * WS2_send (INTERNAL)
1261 * Work horse for both synchronous and asynchronous send() operations.
1263 static int WS2_send ( int fd, struct iovec* iov, int count,
1264 const struct WS_sockaddr *to, INT tolen, DWORD dwFlags )
1268 TRACE ( "fd %d, iovec %p, count %d addr %p, len %d, flags %lx\n",
1269 fd, iov, count, to, tolen, dwFlags);
1271 hdr.msg_name = NULL;
1278 hdr.msg_name = (struct sockaddr*) ws_sockaddr_ws2u ( to, tolen, &hdr.msg_namelen );
1279 if ( !hdr.msg_name )
1281 WSASetLastError ( WSAEFAULT );
1286 hdr.msg_namelen = 0;
1289 hdr.msg_iovlen = count;
1290 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1291 hdr.msg_accrights = NULL;
1292 hdr.msg_accrightslen = 0;
1294 hdr.msg_control = NULL;
1295 hdr.msg_controllen = 0;
1299 n = sendmsg (fd, &hdr, dwFlags);
1302 ws_sockaddr_free ( hdr.msg_name, to );
1306 /***********************************************************************
1307 * WS2_async_send (INTERNAL)
1309 * Handler for overlapped send() operations.
1311 static void WS2_async_send ( async_private *as )
1313 ws2_async* wsa = (ws2_async*) as;
1316 TRACE ( "async %p\n", wsa );
1318 if ( wsa->overlapped->Internal != STATUS_PENDING )
1320 TRACE ( "status: %ld\n", wsa->overlapped->Internal );
1324 result = WS2_send ( wsa->async.fd, wsa->iovec, wsa->n_iovecs,
1325 wsa->addr, wsa->addrlen.val, wsa->flags );
1329 wsa->overlapped->Internal = STATUS_SUCCESS;
1330 wsa->overlapped->InternalHigh = result;
1331 TRACE ( "sent %d bytes\n", result );
1332 _enable_event ( wsa->async.handle, FD_WRITE, 0, 0 );
1337 if ( err == WSAEINTR )
1339 wsa->overlapped->Internal = STATUS_PENDING;
1340 _enable_event ( wsa->async.handle, FD_WRITE, 0, 0 );
1341 TRACE ( "still pending\n" );
1345 /* We set the status to a winsock error code and check for that
1346 later in NtStatusToWSAError () */
1347 wsa->overlapped->Internal = err;
1348 TRACE ( "Error: %x\n", err );
1352 /***********************************************************************
1353 * WS2_async_shutdown (INTERNAL)
1355 * Handler for shutdown() operations on overlapped sockets.
1357 static void WS2_async_shutdown ( async_private *as )
1359 ws2_async* wsa = (ws2_async*) as;
1362 TRACE ( "async %p %d\n", wsa, wsa->async.type );
1363 switch ( wsa->async.type )
1365 case ASYNC_TYPE_READ:
1366 err = shutdown ( wsa->async.fd, 0 );
1368 case ASYNC_TYPE_WRITE:
1369 err = shutdown ( wsa->async.fd, 1 );
1372 ERR ("invalid type: %d\n", wsa->async.type );
1376 wsa->overlapped->Internal = wsaErrno ();
1378 wsa->overlapped->Internal = STATUS_SUCCESS;
1381 /***********************************************************************
1382 * WS2_register_async_shutdown (INTERNAL)
1384 * Helper function for WS_shutdown() on overlapped sockets.
1386 static int WS2_register_async_shutdown ( SOCKET s, int fd, int type )
1388 struct ws2_async *wsa;
1389 int ret, err = WSAEFAULT;
1392 LPWSAOVERLAPPED ovl = HeapAlloc (GetProcessHeap(), 0, sizeof ( WSAOVERLAPPED ));
1394 TRACE ("s %d fd %d type %d\n", s, fd, type);
1398 ovl->hEvent = WSACreateEvent ();
1399 if ( ovl->hEvent == WSA_INVALID_EVENT )
1402 wsa = WS2_make_async ( s, fd, type, NULL, 0,
1403 &dwflags, NULL, &len, ovl, NULL );
1407 /* Hack: this will cause ws2_async_cleanup() to free the overlapped structure */
1408 wsa->user_overlapped = NULL;
1409 wsa->async.func = WS2_async_shutdown;
1410 if ( (ret = register_new_async ( &wsa->async )) )
1412 err = NtStatusToWSAError ( ret );
1415 /* Try immediate completion */
1416 while ( WaitForSingleObjectEx ( ovl->hEvent, 0, TRUE ) == STATUS_USER_APC );
1420 WSACloseEvent ( ovl->hEvent );
1422 HeapFree ( GetProcessHeap(), 0, ovl );
1427 /***********************************************************************
1430 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr,
1433 int fd = _get_sock_fd(s);
1435 TRACE("socket %04x\n", (UINT16)s );
1439 if (_is_blocking(s))
1443 _sync_sock_state(s); /* let wineserver notice connection */
1444 /* retrieve any error codes from it */
1445 SetLastError(_get_sock_error(s, FD_ACCEPT_BIT));
1446 /* FIXME: care about the error? */
1449 SERVER_START_REQ( accept_socket )
1451 req->lhandle = SOCKET2HANDLE(s);
1452 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
1453 req->inherit = TRUE;
1454 set_error( wine_server_call( req ) );
1455 as = HANDLE2SOCKET( reply->handle );
1461 WS_getpeername(as, addr, addrlen32);
1467 SetLastError(WSAENOTSOCK);
1469 return INVALID_SOCKET;
1472 /***********************************************************************
1473 * accept (WINSOCK.1)
1475 SOCKET16 WINAPI WINSOCK_accept16(SOCKET16 s, struct WS_sockaddr* addr,
1478 INT addrlen32 = addrlen16 ? *addrlen16 : 0;
1479 SOCKET retSocket = WS_accept( s, addr, &addrlen32 );
1480 if( addrlen16 ) *addrlen16 = (INT16)addrlen32;
1481 return (SOCKET16)retSocket;
1484 /***********************************************************************
1487 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
1489 int fd = _get_sock_fd(s);
1492 TRACE("socket %04x, ptr %p, length %d\n", s, name, namelen);
1494 dump_sockaddr(name);
1500 if (!name || !SUPPORTED_PF(name->sa_family))
1502 SetLastError(WSAEAFNOSUPPORT);
1506 const struct sockaddr* uaddr;
1509 uaddr=ws_sockaddr_ws2u(name,namelen,&uaddrlen);
1512 SetLastError(WSAEFAULT);
1517 /* The game GrandPrixLegends binds more than one time, but does
1518 * not do a SO_REUSEADDR - Stevens says this is ok */
1519 TRACE( "Setting WS_SO_REUSEADDR on socket before we bind it\n");
1520 WS_setsockopt( s, WS_SOL_SOCKET, WS_SO_REUSEADDR, (char*)&on, sizeof(on) );
1522 if (bind(fd, uaddr, uaddrlen) < 0)
1524 int loc_errno = errno;
1525 WARN("\tfailure - errno = %i\n", errno);
1530 SetLastError(WSAENOTSOCK);
1533 SetLastError(WSAEINVAL);
1536 SetLastError(wsaErrno());
1542 res=0; /* success */
1544 ws_sockaddr_free(uaddr,name);
1551 SetLastError(WSAENOTSOCK);
1556 /***********************************************************************
1559 INT16 WINAPI WINSOCK_bind16(SOCKET16 s, struct WS_sockaddr *name, INT16 namelen)
1561 return (INT16)WS_bind( s, name, namelen );
1564 /***********************************************************************
1565 * closesocket (WS2_32.3)
1567 int WINAPI WS_closesocket(SOCKET s)
1569 TRACE("socket %08x\n", s);
1570 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
1571 return SOCKET_ERROR;
1574 /***********************************************************************
1575 * closesocket (WINSOCK.3)
1577 INT16 WINAPI WINSOCK_closesocket16(SOCKET16 s)
1579 return (INT16)WS_closesocket(s);
1582 /***********************************************************************
1583 * connect (WS2_32.4)
1585 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
1587 int fd = _get_sock_fd(s);
1589 TRACE("socket %04x, ptr %p, length %d\n", s, name, namelen);
1591 dump_sockaddr(name);
1596 const struct sockaddr* uaddr;
1599 uaddr=ws_sockaddr_ws2u(name,namelen,&uaddrlen);
1602 SetLastError(WSAEFAULT);
1608 rc=connect(fd, uaddr, uaddrlen);
1609 ws_sockaddr_free(uaddr,name);
1611 goto connect_success;
1614 if (errno == EINPROGRESS)
1616 /* tell wineserver that a connection is in progress */
1617 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1618 FD_CONNECT|FD_READ|FD_WRITE,
1619 FD_WINE_CONNECTED|FD_WINE_LISTENING);
1620 if (_is_blocking(s))
1625 _sync_sock_state(s); /* let wineserver notice connection */
1626 /* retrieve any error codes from it */
1627 result = _get_sock_error(s, FD_CONNECT_BIT);
1629 SetLastError(result);
1632 goto connect_success;
1637 SetLastError(WSAEWOULDBLOCK);
1642 SetLastError(wsaErrno());
1648 SetLastError(WSAENOTSOCK);
1650 return SOCKET_ERROR;
1654 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1655 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
1656 FD_CONNECT|FD_WINE_LISTENING);
1660 /***********************************************************************
1661 * connect (WINSOCK.4)
1663 INT16 WINAPI WINSOCK_connect16(SOCKET16 s, struct WS_sockaddr *name, INT16 namelen)
1665 return (INT16)WS_connect( s, name, namelen );
1668 /***********************************************************************
1669 * WSAConnect (WS2_32.30)
1671 int WINAPI WSAConnect ( SOCKET s, const struct WS_sockaddr* name, int namelen,
1672 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
1673 LPQOS lpSQOS, LPQOS lpGQOS )
1675 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
1676 FIXME ("unsupported parameters!\n");
1677 return WS_connect ( s, name, namelen );
1681 /***********************************************************************
1682 * getpeername (WS2_32.5)
1684 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
1689 TRACE("socket: %04x, ptr %p, len %8x\n", s, name, *namelen);
1691 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1692 if( (name == NULL) || (namelen == NULL) )
1694 SetLastError( WSAEFAULT );
1695 return SOCKET_ERROR;
1698 fd = _get_sock_fd(s);
1703 struct sockaddr* uaddr;
1706 uaddr=ws_sockaddr_alloc(name,namelen,&uaddrlen);
1707 if (getpeername(fd, uaddr, &uaddrlen) != 0)
1709 SetLastError(wsaErrno());
1711 else if (ws_sockaddr_u2ws(uaddr,uaddrlen,name,namelen) != 0)
1713 /* The buffer was too small */
1714 SetLastError(WSAEFAULT);
1720 ws_sockaddr_free(uaddr,name);
1725 SetLastError(WSAENOTSOCK);
1730 /***********************************************************************
1731 * getpeername (WINSOCK.5)
1733 INT16 WINAPI WINSOCK_getpeername16(SOCKET16 s, struct WS_sockaddr *name,
1736 INT namelen32 = *namelen16;
1737 INT retVal = WS_getpeername( s, name, &namelen32 );
1740 dump_sockaddr(name);
1743 *namelen16 = namelen32;
1744 return (INT16)retVal;
1747 /***********************************************************************
1748 * getsockname (WS2_32.6)
1750 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
1755 TRACE("socket: %04x, ptr %p, len %8x\n", s, name, *namelen);
1757 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1758 if( (name == NULL) || (namelen == NULL) )
1760 SetLastError( WSAEFAULT );
1761 return SOCKET_ERROR;
1764 fd = _get_sock_fd(s);
1769 struct sockaddr* uaddr;
1772 uaddr=ws_sockaddr_alloc(name,namelen,&uaddrlen);
1773 if (getsockname(fd, uaddr, &uaddrlen) != 0)
1775 SetLastError(wsaErrno());
1777 else if (ws_sockaddr_u2ws(uaddr,uaddrlen,name,namelen) != 0)
1779 /* The buffer was too small */
1780 SetLastError(WSAEFAULT);
1790 SetLastError(WSAENOTSOCK);
1795 /***********************************************************************
1796 * getsockname (WINSOCK.6)
1798 INT16 WINAPI WINSOCK_getsockname16(SOCKET16 s, struct WS_sockaddr *name,
1805 INT namelen32 = *namelen16;
1806 retVal = WS_getsockname( s, name, &namelen32 );
1807 *namelen16 = namelen32;
1810 dump_sockaddr(name);
1814 else retVal = SOCKET_ERROR;
1815 return (INT16)retVal;
1819 /***********************************************************************
1820 * getsockopt (WS2_32.7)
1822 INT WINAPI WS_getsockopt(SOCKET s, INT level,
1823 INT optname, char *optval, INT *optlen)
1827 TRACE("socket: %04x, level 0x%x, name 0x%x, ptr %8x, len %d\n", s, level,
1828 (int) optname, (int) optval, (int) *optlen);
1829 /* SO_OPENTYPE does not require a valid socket handle. */
1830 if (level == WS_SOL_SOCKET && optname == WS_SO_OPENTYPE)
1832 if (!optlen || *optlen < sizeof(int) || !optval)
1834 SetLastError(WSAEFAULT);
1835 return SOCKET_ERROR;
1837 *(int *)optval = (int)TlsGetValue( opentype_tls_index );
1838 *optlen = sizeof(int);
1839 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
1843 fd = _get_sock_fd(s);
1846 if (!convert_sockopt(&level, &optname)) {
1847 SetLastError(WSAENOPROTOOPT); /* Unknown option */
1849 if (getsockopt(fd, (int) level, optname, optval, optlen) == 0 )
1854 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1858 return SOCKET_ERROR;
1862 /***********************************************************************
1863 * getsockopt (WINSOCK.7)
1865 INT16 WINAPI WINSOCK_getsockopt16(SOCKET16 s, INT16 level,
1866 INT16 optname, char *optval, INT16 *optlen)
1871 if( optlen ) optlen32 = *optlen; else p = NULL;
1872 retVal = WS_getsockopt( s, (UINT16)level, optname, optval, p );
1873 if( optlen ) *optlen = optlen32;
1874 return (INT16)retVal;
1878 /***********************************************************************
1882 u_long WINAPI WS_htonl(u_long hostlong)
1884 return htonl(hostlong);
1888 /***********************************************************************
1892 u_short WINAPI WS_htons(u_short hostshort)
1894 return htons(hostshort);
1898 /***********************************************************************
1899 * inet_addr (WINSOCK.10)
1900 * inet_addr (WS2_32.11)
1902 u_long WINAPI WS_inet_addr(const char *cp)
1904 return inet_addr(cp);
1908 /***********************************************************************
1909 * ntohl (WINSOCK.14)
1912 u_long WINAPI WS_ntohl(u_long netlong)
1914 return ntohl(netlong);
1918 /***********************************************************************
1919 * ntohs (WINSOCK.15)
1922 u_short WINAPI WS_ntohs(u_short netshort)
1924 return ntohs(netshort);
1928 /***********************************************************************
1929 * inet_ntoa (WS2_32.12)
1931 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
1933 /* use "buffer for dummies" here because some applications have
1934 * propensity to decode addresses in ws_hostent structure without
1935 * saving them first...
1937 static char dbuffer[16]; /* Yes, 16: 4*3 digits + 3 '.' + 1 '\0' */
1939 char* s = inet_ntoa(*((struct in_addr*)&in));
1945 SetLastError(wsaErrno());
1949 /***********************************************************************
1950 * inet_ntoa (WINSOCK.11)
1952 SEGPTR WINAPI WINSOCK_inet_ntoa16(struct in_addr in)
1955 if (!(retVal = WS_inet_ntoa(*((struct WS_in_addr*)&in)))) return 0;
1956 if (!dbuffer_seg) dbuffer_seg = MapLS( retVal );
1961 /**********************************************************************
1962 * WSAIoctl (WS2_32.50)
1965 * FIXME: Only SIO_GET_INTERFACE_LIST option implemented.
1967 INT WINAPI WSAIoctl (SOCKET s,
1968 DWORD dwIoControlCode,
1971 LPVOID lpbOutBuffer,
1973 LPDWORD lpcbBytesReturned,
1974 LPWSAOVERLAPPED lpOverlapped,
1975 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
1977 int fd = _get_sock_fd(s);
1981 switch( dwIoControlCode )
1983 case SIO_GET_INTERFACE_LIST:
1985 INTERFACE_INFO* intArray = (INTERFACE_INFO*)lpbOutBuffer;
1987 struct ifreq ifInfo;
1991 TRACE ("-> SIO_GET_INTERFACE_LIST request\n");
1993 numInt = WSAIOCTL_GetInterfaceCount();
1996 ERR ("Unable to open /proc filesystem to determine number of network interfaces!\n");
1998 WSASetLastError(WSAEINVAL);
1999 return (SOCKET_ERROR);
2002 for (i=0; i<numInt; i++)
2004 if (!WSAIOCTL_GetInterfaceName(i, ifName))
2006 ERR ("Error parsing /proc filesystem!\n");
2008 WSASetLastError(WSAEINVAL);
2009 return (SOCKET_ERROR);
2012 ifInfo.ifr_addr.sa_family = AF_INET;
2015 strcpy (ifInfo.ifr_name, ifName);
2016 if (ioctl(fd, SIOCGIFADDR, &ifInfo) < 0)
2018 ERR ("Error obtaining IP address\n");
2020 WSASetLastError(WSAEINVAL);
2021 return (SOCKET_ERROR);
2025 struct WS_sockaddr_in *ipTemp = (struct WS_sockaddr_in *)&ifInfo.ifr_addr;
2027 intArray->iiAddress.AddressIn.sin_family = AF_INET;
2028 intArray->iiAddress.AddressIn.sin_port = ipTemp->sin_port;
2029 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr = ipTemp->sin_addr.S_un.S_addr;
2032 /* Broadcast Address */
2033 strcpy (ifInfo.ifr_name, ifName);
2034 if (ioctl(fd, SIOCGIFBRDADDR, &ifInfo) < 0)
2036 ERR ("Error obtaining Broadcast IP address\n");
2038 WSASetLastError(WSAEINVAL);
2039 return (SOCKET_ERROR);
2043 struct WS_sockaddr_in *ipTemp = (struct WS_sockaddr_in *)&ifInfo.ifr_broadaddr;
2045 intArray->iiBroadcastAddress.AddressIn.sin_family = AF_INET;
2046 intArray->iiBroadcastAddress.AddressIn.sin_port = ipTemp->sin_port;
2047 intArray->iiBroadcastAddress.AddressIn.sin_addr.WS_s_addr = ipTemp->sin_addr.S_un.S_addr;
2051 strcpy (ifInfo.ifr_name, ifName);
2052 if (ioctl(fd, SIOCGIFNETMASK, &ifInfo) < 0)
2054 ERR ("Error obtaining Subnet IP address\n");
2056 WSASetLastError(WSAEINVAL);
2057 return (SOCKET_ERROR);
2061 /* Trying to avoid some compile problems across platforms.
2062 (Linux, FreeBSD, Solaris...) */
2065 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
2066 intArray->iiNetmask.AddressIn.sin_port = 0;
2067 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr = 0;
2068 ERR ("Unable to determine Netmask on your platform!\n");
2070 struct WS_sockaddr_in *ipTemp = (struct WS_sockaddr_in *)&ifInfo.ifr_addr;
2072 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
2073 intArray->iiNetmask.AddressIn.sin_port = ipTemp->sin_port;
2074 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr = ipTemp->sin_addr.S_un.S_addr;
2077 struct WS_sockaddr_in *ipTemp = (struct WS_sockaddr_in *)&ifInfo.ifr_netmask;
2079 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
2080 intArray->iiNetmask.AddressIn.sin_port = ipTemp->sin_port;
2081 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr = ipTemp->sin_addr.S_un.S_addr;
2085 /* Socket Status Flags */
2086 strcpy(ifInfo.ifr_name, ifName);
2087 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
2089 ERR ("Error obtaining status flags for socket!\n");
2091 WSASetLastError(WSAEINVAL);
2092 return (SOCKET_ERROR);
2096 /* FIXME - Is this the right flag to use? */
2097 intArray->iiFlags = ifInfo.ifr_flags;
2099 intArray++; /* Prepare for another interface */
2102 /* Calculate the size of the array being returned */
2103 *lpcbBytesReturned = sizeof(INTERFACE_INFO) * numInt;
2109 WARN("\tunsupported WS_IOCTL cmd (%08lx)\n", dwIoControlCode);
2111 WSASetLastError(WSAEOPNOTSUPP);
2112 return (SOCKET_ERROR);
2116 /* Function executed with no errors */
2122 WSASetLastError(WSAENOTSOCK);
2123 return (SOCKET_ERROR);
2129 Helper function for WSAIoctl - Get count of the number of interfaces
2130 by parsing /proc filesystem.
2132 int WSAIOCTL_GetInterfaceCount(void)
2135 char buf[512]; /* Size doesn't matter, something big */
2139 /* Open /proc filesystem file for network devices */
2140 procfs = fopen(PROCFS_NETDEV_FILE, "r");
2143 /* If we can't open the file, return an error */
2147 /* Omit first two lines, they are only headers */
2148 fgets(buf, sizeof buf, procfs);
2149 fgets(buf, sizeof buf, procfs);
2151 while (fgets(buf, sizeof buf, procfs))
2153 /* Each line in the file represents a network interface */
2163 Helper function for WSAIoctl - Get name of device from interface number
2164 by parsing /proc filesystem.
2166 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName)
2169 char buf[512]; /* Size doesn't matter, something big */
2172 /* Open /proc filesystem file for network devices */
2173 procfs = fopen(PROCFS_NETDEV_FILE, "r");
2176 /* If we can't open the file, return an error */
2180 /* Omit first two lines, they are only headers */
2181 fgets(buf, sizeof(buf), procfs);
2182 fgets(buf, sizeof(buf), procfs);
2184 for (i=0; i<intNumber; i++)
2186 /* Skip the lines that don't interest us. */
2187 fgets(buf, sizeof(buf), procfs);
2189 fgets(buf, sizeof(buf), procfs); /* This is the line we want */
2192 /* Parse out the line, grabbing only the name of the device
2193 to the intName variable
2195 The Line comes in like this: (we only care about the device name)
2196 lo: 21970 377 0 0 0 0 0 0 21970 377 0 0 0 0 0 0
2199 while (isspace(buf[i])) /* Skip initial space(s) */
2206 if (isspace(buf[i]))
2211 if (buf[i] == ':') /* FIXME: Not sure if this block (alias detection) works properly */
2213 /* This interface could be an alias... */
2215 char *dotname = intName;
2216 *intName++ = buf[i++];
2218 while (isdigit(buf[i]))
2220 *intName++ = buf[i++];
2225 /* ... It wasn't, so back up */
2240 *intName++ = buf[i++];
2249 /***********************************************************************
2250 * ioctlsocket (WS2_32.10)
2252 int WINAPI WS_ioctlsocket(SOCKET s, long cmd, u_long *argp)
2254 int fd = _get_sock_fd(s);
2256 TRACE("socket %04x, cmd %08lx, ptr %8x\n", s, cmd, (unsigned) argp);
2269 if( _get_sock_mask(s) )
2271 /* AsyncSelect()'ed sockets are always nonblocking */
2276 SetLastError(WSAEINVAL);
2278 return SOCKET_ERROR;
2282 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
2284 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
2291 case WS__IOW('f',125,u_long):
2292 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
2293 SetLastError(WSAEINVAL);
2294 return SOCKET_ERROR;
2296 case SIOCGIFBRDADDR:
2297 case SIOCGIFNETMASK:
2299 /* These don't need any special handling. They are used by
2300 WsControl, and are here to suppress an unecessary warning. */
2305 /* Netscape tries hard to use bogus ioctl 0x667e */
2306 WARN("\tunknown WS_IOCTL cmd (%08lx)\n", cmd);
2308 if( ioctl(fd, newcmd, (char*)argp ) == 0 )
2313 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2316 return SOCKET_ERROR;
2319 /***********************************************************************
2320 * ioctlsocket (WINSOCK.12)
2322 INT16 WINAPI WINSOCK_ioctlsocket16(SOCKET16 s, LONG cmd, ULONG *argp)
2324 return (INT16)WS_ioctlsocket( s, cmd, argp );
2328 /***********************************************************************
2329 * listen (WS2_32.13)
2331 int WINAPI WS_listen(SOCKET s, int backlog)
2333 int fd = _get_sock_fd(s);
2335 TRACE("socket %04x, backlog %d\n", s, backlog);
2338 if (listen(fd, backlog) == 0)
2341 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
2343 FD_CONNECT|FD_WINE_CONNECTED);
2346 SetLastError(wsaErrno());
2348 else SetLastError(WSAENOTSOCK);
2349 return SOCKET_ERROR;
2352 /***********************************************************************
2353 * listen (WINSOCK.13)
2355 INT16 WINAPI WINSOCK_listen16(SOCKET16 s, INT16 backlog)
2357 return (INT16)WS_listen( s, backlog );
2361 /***********************************************************************
2364 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
2366 DWORD n, dwFlags = flags;
2372 if ( WSARecvFrom (s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
2373 return SOCKET_ERROR;
2378 /***********************************************************************
2381 INT16 WINAPI WINSOCK_recv16(SOCKET16 s, char *buf, INT16 len, INT16 flags)
2383 return (INT16)WS_recv( s, buf, len, flags );
2387 /***********************************************************************
2388 * recvfrom (WS2_32.17)
2390 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
2391 struct WS_sockaddr *from, int *fromlen)
2393 DWORD n, dwFlags = flags;
2399 if ( WSARecvFrom (s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL) == SOCKET_ERROR )
2400 return SOCKET_ERROR;
2405 /***********************************************************************
2406 * recvfrom (WINSOCK.17)
2408 INT16 WINAPI WINSOCK_recvfrom16(SOCKET16 s, char *buf, INT16 len, INT16 flags,
2409 struct WS_sockaddr *from, INT16 *fromlen16)
2412 INT *p = &fromlen32;
2415 if( fromlen16 ) fromlen32 = *fromlen16; else p = NULL;
2416 retVal = WS_recvfrom( s, buf, len, flags, from, p );
2417 if( fromlen16 ) *fromlen16 = fromlen32;
2418 return (INT16)retVal;
2421 /***********************************************************************
2424 static int __ws_select(BOOL b32,
2425 void *ws_readfds, void *ws_writefds, void *ws_exceptfds,
2426 const struct WS_timeval *ws_timeout)
2429 fd_set readfds, writefds, exceptfds;
2430 fd_set *p_read, *p_write, *p_except;
2431 int readfd[FD_SETSIZE], writefd[FD_SETSIZE], exceptfd[FD_SETSIZE];
2432 struct timeval timeout, *timeoutaddr = NULL;
2434 TRACE("read %p, write %p, excp %p timeout %p\n",
2435 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
2437 p_read = fd_set_import(&readfds, ws_readfds, &highfd, readfd, b32);
2438 p_write = fd_set_import(&writefds, ws_writefds, &highfd, writefd, b32);
2439 p_except = fd_set_import(&exceptfds, ws_exceptfds, &highfd, exceptfd, b32);
2442 timeoutaddr = &timeout;
2443 timeout.tv_sec=ws_timeout->tv_sec;
2444 timeout.tv_usec=ws_timeout->tv_usec;
2447 if( (highfd = select(highfd + 1, p_read, p_write, p_except, timeoutaddr)) > 0 )
2449 fd_set_export(&readfds, p_except, ws_readfds, readfd, b32);
2450 fd_set_export(&writefds, p_except, ws_writefds, writefd, b32);
2452 if (p_except && ws_exceptfds)
2454 #define wsfds16 ((ws_fd_set16*)ws_exceptfds)
2455 #define wsfds32 ((WS_fd_set*)ws_exceptfds)
2456 int i, j, count = (b32) ? wsfds32->fd_count : wsfds16->fd_count;
2458 for (i = j = 0; i < count; i++)
2460 int fd = exceptfd[i];
2461 if( fd >= 0 && FD_ISSET(fd, &exceptfds) )
2464 wsfds32->fd_array[j++] = wsfds32->fd_array[i];
2466 wsfds16->fd_array[j++] = wsfds16->fd_array[i];
2468 if( fd >= 0 ) close(fd);
2472 wsfds32->fd_count = j;
2474 wsfds16->fd_count = j;
2480 fd_set_unimport(ws_readfds, readfd, b32);
2481 fd_set_unimport(ws_writefds, writefd, b32);
2482 fd_set_unimport(ws_exceptfds, exceptfd, b32);
2483 if( ws_readfds ) ((WS_fd_set*)ws_readfds)->fd_count = 0;
2484 if( ws_writefds ) ((WS_fd_set*)ws_writefds)->fd_count = 0;
2485 if( ws_exceptfds ) ((WS_fd_set*)ws_exceptfds)->fd_count = 0;
2487 if( highfd == 0 ) return 0;
2488 SetLastError(wsaErrno());
2489 return SOCKET_ERROR;
2492 /***********************************************************************
2493 * select (WINSOCK.18)
2495 INT16 WINAPI WINSOCK_select16(INT16 nfds, ws_fd_set16 *ws_readfds,
2496 ws_fd_set16 *ws_writefds, ws_fd_set16 *ws_exceptfds,
2497 struct WS_timeval* timeout)
2499 return (INT16)__ws_select( FALSE, ws_readfds, ws_writefds, ws_exceptfds, timeout );
2502 /***********************************************************************
2503 * select (WS2_32.18)
2505 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
2506 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
2507 const struct WS_timeval* timeout)
2509 /* struct timeval is the same for both 32- and 16-bit code */
2510 return (INT)__ws_select( TRUE, ws_readfds, ws_writefds, ws_exceptfds, timeout );
2514 /***********************************************************************
2517 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
2523 wsabuf.buf = (char*) buf;
2525 if ( WSASendTo ( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
2526 return SOCKET_ERROR;
2531 /***********************************************************************
2532 * WSASend (WS2_32.72)
2534 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2535 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2536 LPWSAOVERLAPPED lpOverlapped,
2537 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2539 return WSASendTo ( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
2540 NULL, 0, lpOverlapped, lpCompletionRoutine );
2543 /***********************************************************************
2544 * WSASendDisconnect (WS2_32.73)
2546 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
2548 return WS_shutdown ( s, SD_SEND );
2552 /***********************************************************************
2553 * WSASendTo (WS2_32.74)
2555 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2556 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2557 const struct WS_sockaddr *to, int tolen,
2558 LPWSAOVERLAPPED lpOverlapped,
2559 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2561 int i, n, fd, err = WSAENOTSOCK, flags, ret;
2562 struct iovec* iovec;
2563 struct ws2_async *wsa;
2566 TRACE ("socket %04x, wsabuf %p, nbufs %ld, flags %ld, to %p, tolen %d, ovl %p, func %p\n",
2567 s, lpBuffers, dwBufferCount, dwFlags,
2568 to, tolen, lpOverlapped, lpCompletionRoutine);
2570 fd = _get_sock_fd_type( s, GENERIC_WRITE, &type, &flags );
2571 TRACE ( "fd=%d, type=%d, flags=%x\n", fd, type, flags );
2575 err = WSAGetLastError ();
2579 iovec = HeapAlloc (GetProcessHeap(), 0, dwBufferCount * sizeof (struct iovec) );
2587 for ( i = 0; i < dwBufferCount; i++ )
2589 iovec[i].iov_base = lpBuffers[i].buf;
2590 iovec[i].iov_len = lpBuffers[i].len;
2593 if ( (lpOverlapped || lpCompletionRoutine) && flags & FD_FLAG_OVERLAPPED )
2595 wsa = WS2_make_async ( s, fd, ASYNC_TYPE_WRITE, iovec, dwBufferCount,
2596 &dwFlags, (struct WS_sockaddr*) to, &tolen,
2597 lpOverlapped, lpCompletionRoutine );
2604 if ( ( ret = register_new_async ( &wsa->async )) )
2606 err = NtStatusToWSAError ( ret );
2608 if ( !lpOverlapped )
2609 HeapFree ( GetProcessHeap(), 0, wsa->overlapped );
2610 HeapFree ( GetProcessHeap(), 0, wsa );
2614 /* Try immediate completion */
2615 if ( lpOverlapped && !NtResetEvent( lpOverlapped->hEvent, NULL ) )
2617 if ( WSAGetOverlappedResult ( s, lpOverlapped,
2618 lpNumberOfBytesSent, FALSE, &dwFlags) )
2621 if ( (err = WSAGetLastError ()) != WSA_IO_INCOMPLETE )
2625 WSASetLastError ( WSA_IO_PENDING );
2626 return SOCKET_ERROR;
2629 if (_is_blocking(s))
2631 /* FIXME: exceptfds? */
2635 n = WS2_send ( fd, iovec, dwBufferCount, to, tolen, dwFlags );
2639 if ( err == WSAEWOULDBLOCK )
2640 _enable_event (SOCKET2HANDLE(s), FD_WRITE, 0, 0);
2644 TRACE(" -> %i bytes\n", n);
2645 *lpNumberOfBytesSent = n;
2647 HeapFree ( GetProcessHeap(), 0, iovec );
2652 HeapFree ( GetProcessHeap(), 0, iovec );
2658 WARN (" -> ERROR %d\n", err);
2659 WSASetLastError (err);
2660 return SOCKET_ERROR;
2663 /***********************************************************************
2666 INT16 WINAPI WINSOCK_send16(SOCKET16 s, char *buf, INT16 len, INT16 flags)
2668 return WS_send( s, buf, len, flags );
2671 /***********************************************************************
2672 * sendto (WS2_32.20)
2674 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
2675 const struct WS_sockaddr *to, int tolen)
2681 wsabuf.buf = (char*) buf;
2683 if ( WSASendTo (s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
2684 return SOCKET_ERROR;
2689 /***********************************************************************
2690 * sendto (WINSOCK.20)
2692 INT16 WINAPI WINSOCK_sendto16(SOCKET16 s, char *buf, INT16 len, INT16 flags,
2693 struct WS_sockaddr *to, INT16 tolen)
2695 return (INT16)WS_sendto( s, buf, len, flags, to, tolen );
2698 /***********************************************************************
2699 * setsockopt (WS2_32.21)
2701 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
2702 const char *optval, int optlen)
2706 TRACE("socket: %04x, level 0x%x, name 0x%x, ptr %8x, len %d\n", s, level,
2707 (int) optname, (int) optval, optlen);
2708 /* SO_OPENTYPE does not require a valid socket handle. */
2709 if (level == WS_SOL_SOCKET && optname == WS_SO_OPENTYPE)
2711 if (optlen < sizeof(int) || !optval)
2713 SetLastError(WSAEFAULT);
2714 return SOCKET_ERROR;
2716 TlsSetValue( opentype_tls_index, (LPVOID)*(int *)optval );
2717 TRACE("setting global SO_OPENTYPE to 0x%x\n", *(int *)optval );
2721 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
2722 * socket. This will either not happen under windows or it is ignored in
2723 * windows (but it works in linux and therefor prevents the game to find
2724 * games outsite the current network) */
2725 if ( level==WS_SOL_SOCKET && optname==WS_SO_DONTROUTE )
2727 FIXME("Does windows ignore SO_DONTROUTE?\n");
2732 fd = _get_sock_fd(s);
2735 struct linger linger;
2737 struct timeval tval;
2739 /* Is a privileged and useless operation, so we don't. */
2740 if ((optname == WS_SO_DEBUG) && (level == WS_SOL_SOCKET)) {
2741 FIXME("(%d,SOL_SOCKET,SO_DEBUG,%p(%ld)) attempted (is privileged). Ignoring.\n",s,optval,*(DWORD*)optval);
2745 if(optname == WS_SO_DONTLINGER && level == WS_SOL_SOCKET) {
2746 /* This is unique to WinSock and takes special conversion */
2747 linger.l_onoff = *((int*)optval) ? 0: 1;
2748 linger.l_linger = 0;
2750 optval = (char*)&linger;
2751 optlen = sizeof(struct linger);
2754 if (!convert_sockopt(&level, &optname)) {
2755 ERR("Invalid level (%d) or optname (%d)\n", level, optname);
2756 SetLastError(WSAENOPROTOOPT);
2758 return SOCKET_ERROR;
2760 if (optname == SO_LINGER && optval) {
2761 /* yes, uses unsigned short in both win16/win32 */
2762 linger.l_onoff = ((UINT16*)optval)[0];
2763 linger.l_linger = ((UINT16*)optval)[1];
2764 /* FIXME: what is documented behavior if SO_LINGER optval
2766 optval = (char*)&linger;
2767 optlen = sizeof(struct linger);
2768 } else if (optlen < sizeof(int)){
2769 woptval= *((INT16 *) optval);
2770 optval= (char*) &woptval;
2774 if (level == SOL_SOCKET && optname == SO_RCVTIMEO) {
2775 if (optlen == sizeof(UINT32)) {
2776 /* WinSock passes miliseconds instead of struct timeval */
2777 tval.tv_usec = *(PUINT32)optval % 1000;
2778 tval.tv_sec = *(PUINT32)optval / 1000;
2779 /* min of 500 milisec */
2780 if (tval.tv_sec == 0 && tval.tv_usec < 500) tval.tv_usec = 500;
2781 optlen = sizeof(struct timeval);
2782 optval = (char*)&tval;
2783 } else if (optlen == sizeof(struct timeval)) {
2784 WARN("SO_RCVTIMEO for %d bytes: assuming unixism\n", optlen);
2786 WARN("SO_RCVTIMEO for %d bytes is weird: ignored\n", optlen);
2793 if (level == SOL_SOCKET && optname == SO_SNDTIMEO) {
2794 if (optlen == sizeof(UINT32)) {
2795 /* WinSock passes miliseconds instead of struct timeval */
2796 tval.tv_usec = *(PUINT32)optval % 1000;
2797 tval.tv_sec = *(PUINT32)optval / 1000;
2798 /* min of 500 milisec */
2799 if (tval.tv_sec == 0 && tval.tv_usec < 500) tval.tv_usec = 500;
2800 optlen = sizeof(struct timeval);
2801 optval = (char*)&tval;
2802 } else if (optlen == sizeof(struct timeval)) {
2803 WARN("SO_SNDTIMEO for %d bytes: assuming unixism\n", optlen);
2805 WARN("SO_SNDTIMEO for %d bytes is weird: ignored\n", optlen);
2812 if(optname == SO_RCVBUF && *(int*)optval < 2048) {
2813 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(int*)optval );
2818 if (setsockopt(fd, level, optname, optval, optlen) == 0)
2823 TRACE("Setting socket error, %d\n", wsaErrno());
2824 SetLastError(wsaErrno());
2827 else SetLastError(WSAENOTSOCK);
2828 return SOCKET_ERROR;
2831 /***********************************************************************
2832 * setsockopt (WINSOCK.21)
2834 INT16 WINAPI WINSOCK_setsockopt16(SOCKET16 s, INT16 level, INT16 optname,
2835 char *optval, INT16 optlen)
2837 if( !optval ) return SOCKET_ERROR;
2838 return (INT16)WS_setsockopt( s, (UINT16)level, optname, optval, optlen );
2842 /***********************************************************************
2843 * shutdown (WS2_32.22)
2845 int WINAPI WS_shutdown(SOCKET s, int how)
2847 int fd, fd0 = -1, fd1 = -1, flags, err = WSAENOTSOCK;
2849 unsigned int clear_flags = 0;
2851 fd = _get_sock_fd_type ( s, 0, &type, &flags );
2852 TRACE("socket %04x, how %i %d %d \n", s, how, type, flags );
2855 return SOCKET_ERROR;
2859 case 0: /* drop receives */
2860 clear_flags |= FD_READ;
2862 case 1: /* drop sends */
2863 clear_flags |= FD_WRITE;
2865 case 2: /* drop all */
2866 clear_flags |= FD_READ|FD_WRITE;
2868 clear_flags |= FD_WINE_LISTENING;
2871 if ( flags & FD_FLAG_OVERLAPPED ) {
2884 fd1 = _get_sock_fd ( s );
2889 err = WS2_register_async_shutdown ( s, fd0, ASYNC_TYPE_READ );
2898 err = WS2_register_async_shutdown ( s, fd1, ASYNC_TYPE_WRITE );
2906 else /* non-overlapped mode */
2908 if ( shutdown( fd, how ) )
2917 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
2918 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
2922 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
2923 WSASetLastError ( err );
2924 return SOCKET_ERROR;
2927 /***********************************************************************
2928 * shutdown (WINSOCK.22)
2930 INT16 WINAPI WINSOCK_shutdown16(SOCKET16 s, INT16 how)
2932 return (INT16)WS_shutdown( s, how );
2936 /***********************************************************************
2937 * socket (WS2_32.23)
2939 SOCKET WINAPI WS_socket(int af, int type, int protocol)
2941 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
2943 return WSASocketA ( af, type, protocol, NULL, 0,
2944 (TlsGetValue(opentype_tls_index) ? 0 : WSA_FLAG_OVERLAPPED) );
2947 /***********************************************************************
2948 * socket (WINSOCK.23)
2950 SOCKET16 WINAPI WINSOCK_socket16(INT16 af, INT16 type, INT16 protocol)
2952 return (SOCKET16)WS_socket( af, type, protocol );
2956 /* ----------------------------------- DNS services
2958 * IMPORTANT: 16-bit API structures have SEGPTR pointers inside them.
2959 * Also, we have to use wsock32 stubs to convert structures and
2960 * error codes from Unix to WSA, hence there is no direct mapping in
2961 * the relay32/wsock32.spec.
2965 /***********************************************************************
2966 * __ws_gethostbyaddr
2968 static WIN_hostent* __ws_gethostbyaddr(const char *addr, int len, int type, int dup_flag)
2970 WIN_hostent *retval = NULL;
2972 struct hostent* host;
2973 #if HAVE_LINUX_GETHOSTBYNAME_R_6
2976 struct hostent hostentry;
2979 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
2981 int res = gethostbyaddr_r(addr, len, type,
2982 &hostentry, extrabuf, ebufsize, &host, &locerr);
2983 if( res != ERANGE) break;
2985 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
2987 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
2989 EnterCriticalSection( &csWSgetXXXbyYYY );
2990 host = gethostbyaddr(addr, len, type);
2991 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
2995 if( WS_dup_he(host, dup_flag) )
2998 SetLastError(WSAENOBUFS);
3000 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3001 HeapFree(GetProcessHeap(),0,extrabuf);
3003 LeaveCriticalSection( &csWSgetXXXbyYYY );
3008 /***********************************************************************
3009 * gethostbyaddr (WINSOCK.51)
3011 SEGPTR WINAPI WINSOCK_gethostbyaddr16(const char *addr, INT16 len, INT16 type)
3013 TRACE("ptr %p, len %d, type %d\n", addr, len, type);
3014 if (!__ws_gethostbyaddr( addr, len, type, WS_DUP_SEGPTR )) return 0;
3015 return he_buffer_seg;
3018 /***********************************************************************
3019 * gethostbyaddr (WS2_32.51)
3021 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len,
3024 TRACE("ptr %08x, len %d, type %d\n",
3025 (unsigned) addr, len, type);
3026 return __ws_gethostbyaddr(addr, len, type, WS_DUP_LINEAR);
3029 /***********************************************************************
3030 * __ws_gethostbyname
3032 static WIN_hostent * __ws_gethostbyname(const char *name, int dup_flag)
3034 WIN_hostent *retval = NULL;
3035 struct hostent* host;
3036 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3039 struct hostent hostentry;
3040 int locerr = ENOBUFS;
3042 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3044 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
3045 if( res != ERANGE) break;
3047 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3049 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3051 EnterCriticalSection( &csWSgetXXXbyYYY );
3052 host = gethostbyname(name);
3053 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3057 if( WS_dup_he(host, dup_flag) )
3059 else SetLastError(WSAENOBUFS);
3061 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3062 HeapFree(GetProcessHeap(),0,extrabuf);
3064 LeaveCriticalSection( &csWSgetXXXbyYYY );
3069 /***********************************************************************
3070 * gethostbyname (WINSOCK.52)
3072 SEGPTR WINAPI WINSOCK_gethostbyname16(const char *name)
3074 TRACE( "%s\n", debugstr_a(name) );
3075 if (!__ws_gethostbyname( name, WS_DUP_SEGPTR )) return 0;
3076 return he_buffer_seg;
3079 /***********************************************************************
3080 * gethostbyname (WS2_32.52)
3082 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
3084 TRACE( "%s\n", debugstr_a(name) );
3085 return __ws_gethostbyname( name, WS_DUP_LINEAR );
3089 /***********************************************************************
3090 * __ws_getprotobyname
3092 static WIN_protoent* __ws_getprotobyname(const char *name, int dup_flag)
3094 WIN_protoent* retval = NULL;
3095 #ifdef HAVE_GETPROTOBYNAME
3096 struct protoent* proto;
3097 EnterCriticalSection( &csWSgetXXXbyYYY );
3098 if( (proto = getprotobyname(name)) != NULL )
3100 if( WS_dup_pe(proto, dup_flag) )
3102 else SetLastError(WSAENOBUFS);
3105 MESSAGE("protocol %s not found; You might want to add "
3106 "this to /etc/protocols\n", debugstr_a(name) );
3107 SetLastError(WSANO_DATA);
3109 LeaveCriticalSection( &csWSgetXXXbyYYY );
3114 /***********************************************************************
3115 * getprotobyname (WINSOCK.53)
3117 SEGPTR WINAPI WINSOCK_getprotobyname16(const char *name)
3119 TRACE( "%s\n", debugstr_a(name) );
3120 if (!__ws_getprotobyname(name, WS_DUP_SEGPTR)) return 0;
3121 return pe_buffer_seg;
3124 /***********************************************************************
3125 * getprotobyname (WS2_32.53)
3127 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
3129 TRACE( "%s\n", debugstr_a(name) );
3130 return __ws_getprotobyname(name, WS_DUP_LINEAR);
3134 /***********************************************************************
3135 * __ws_getprotobynumber
3137 static WIN_protoent* __ws_getprotobynumber(int number, int dup_flag)
3139 WIN_protoent* retval = NULL;
3140 #ifdef HAVE_GETPROTOBYNUMBER
3141 struct protoent* proto;
3142 EnterCriticalSection( &csWSgetXXXbyYYY );
3143 if( (proto = getprotobynumber(number)) != NULL )
3145 if( WS_dup_pe(proto, dup_flag) )
3147 else SetLastError(WSAENOBUFS);
3150 MESSAGE("protocol number %d not found; You might want to add "
3151 "this to /etc/protocols\n", number );
3152 SetLastError(WSANO_DATA);
3154 LeaveCriticalSection( &csWSgetXXXbyYYY );
3159 /***********************************************************************
3160 * getprotobynumber (WINSOCK.54)
3162 SEGPTR WINAPI WINSOCK_getprotobynumber16(INT16 number)
3164 TRACE("%i\n", number);
3165 if (!__ws_getprotobynumber(number, WS_DUP_SEGPTR)) return 0;
3166 return pe_buffer_seg;
3169 /***********************************************************************
3170 * getprotobynumber (WS2_32.54)
3172 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
3174 TRACE("%i\n", number);
3175 return __ws_getprotobynumber(number, WS_DUP_LINEAR);
3179 /***********************************************************************
3180 * __ws_getservbyname
3182 static WIN_servent* __ws_getservbyname(const char *name, const char *proto, int dup_flag)
3184 WIN_servent* retval = NULL;
3185 struct servent* serv;
3186 int i = wsi_strtolo( name, proto );
3189 EnterCriticalSection( &csWSgetXXXbyYYY );
3190 serv = getservbyname(local_buffer,
3191 proto && *proto ? (local_buffer + i) : NULL);
3194 if( WS_dup_se(serv, dup_flag) )
3196 else SetLastError(WSAENOBUFS);
3199 MESSAGE("service %s protocol %s not found; You might want to add "
3200 "this to /etc/services\n", debugstr_a(local_buffer),
3201 proto ? debugstr_a(local_buffer+i):"*");
3202 SetLastError(WSANO_DATA);
3204 LeaveCriticalSection( &csWSgetXXXbyYYY );
3206 else SetLastError(WSAENOBUFS);
3210 /***********************************************************************
3211 * getservbyname (WINSOCK.55)
3213 SEGPTR WINAPI WINSOCK_getservbyname16(const char *name, const char *proto)
3215 TRACE( "%s, %s\n", debugstr_a(name), debugstr_a(proto) );
3216 if (!__ws_getservbyname(name, proto, WS_DUP_SEGPTR)) return 0;
3217 return se_buffer_seg;
3220 /***********************************************************************
3221 * getservbyname (WS2_32.55)
3223 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
3225 TRACE( "%s, %s\n", debugstr_a(name), debugstr_a(proto) );
3226 return __ws_getservbyname(name, proto, WS_DUP_LINEAR);
3230 /***********************************************************************
3231 * __ws_getservbyport
3233 static WIN_servent* __ws_getservbyport(int port, const char* proto, int dup_flag)
3235 WIN_servent* retval = NULL;
3236 #ifdef HAVE_GETSERVBYPORT
3237 struct servent* serv;
3238 if (!proto || wsi_strtolo( proto, NULL )) {
3239 EnterCriticalSection( &csWSgetXXXbyYYY );
3240 if( (serv = getservbyport(port, proto && *proto ? local_buffer :
3242 if( WS_dup_se(serv, dup_flag) )
3244 else SetLastError(WSAENOBUFS);
3247 MESSAGE("service on port %lu protocol %s not found; You might want to add "
3248 "this to /etc/services\n", (unsigned long)ntohl(port),
3249 proto ? debugstr_a(local_buffer) : "*");
3250 SetLastError(WSANO_DATA);
3252 LeaveCriticalSection( &csWSgetXXXbyYYY );
3254 else SetLastError(WSAENOBUFS);
3259 /***********************************************************************
3260 * getservbyport (WINSOCK.56)
3262 SEGPTR WINAPI WINSOCK_getservbyport16(INT16 port, const char *proto)
3264 TRACE("%d (i.e. port %d), %s\n", (int)port, (int)ntohl(port), debugstr_a(proto));
3265 if (!__ws_getservbyport(port, proto, WS_DUP_SEGPTR)) return 0;
3266 return se_buffer_seg;
3269 /***********************************************************************
3270 * getservbyport (WS2_32.56)
3272 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
3274 TRACE("%d (i.e. port %d), %s\n", (int)port, (int)ntohl(port), debugstr_a(proto));
3275 return __ws_getservbyport(port, proto, WS_DUP_LINEAR);
3279 /***********************************************************************
3280 * gethostname (WS2_32.57)
3282 int WINAPI WS_gethostname(char *name, int namelen)
3284 TRACE("name %p, len %d\n", name, namelen);
3286 if (gethostname(name, namelen) == 0)
3288 TRACE("<- '%s'\n", name);
3291 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
3292 TRACE("<- ERROR !\n");
3293 return SOCKET_ERROR;
3296 /***********************************************************************
3297 * gethostname (WINSOCK.57)
3299 INT16 WINAPI WINSOCK_gethostname16(char *name, INT16 namelen)
3301 return (INT16)WS_gethostname(name, namelen);
3305 /* ------------------------------------- Windows sockets extensions -- *
3307 * ------------------------------------------------------------------- */
3309 /***********************************************************************
3310 * WSAEnumNetworkEvents (WS2_32.36)
3312 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
3316 TRACE("%08x, hEvent %p, lpEvent %08x\n", s, hEvent, (unsigned)lpEvent );
3318 SERVER_START_REQ( get_socket_event )
3320 req->handle = SOCKET2HANDLE(s);
3321 req->service = TRUE;
3322 req->c_event = hEvent;
3323 wine_server_set_reply( req, lpEvent->iErrorCode, sizeof(lpEvent->iErrorCode) );
3324 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
3328 SetLastError(WSAEINVAL);
3329 return SOCKET_ERROR;
3332 /***********************************************************************
3333 * WSAEventSelect (WS2_32.39)
3335 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
3339 TRACE("%08x, hEvent %p, event %08x\n", s, hEvent, (unsigned)lEvent );
3341 SERVER_START_REQ( set_socket_event )
3343 req->handle = SOCKET2HANDLE(s);
3345 req->event = hEvent;
3348 ret = wine_server_call( req );
3352 SetLastError(WSAEINVAL);
3353 return SOCKET_ERROR;
3356 /**********************************************************************
3357 * WSAGetOverlappedResult (WS2_32.40)
3359 BOOL WINAPI WSAGetOverlappedResult ( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
3360 LPDWORD lpcbTransfer, BOOL fWait,
3365 TRACE ( "socket %d ovl %p trans %p, wait %d flags %p\n",
3366 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
3368 if ( !(lpOverlapped && lpOverlapped->hEvent) )
3370 ERR ( "Invalid pointer\n" );
3371 WSASetLastError (WSA_INVALID_PARAMETER);
3377 while ( WaitForSingleObjectEx (lpOverlapped->hEvent, INFINITE, TRUE) == STATUS_USER_APC );
3379 else if ( lpOverlapped->Internal == STATUS_PENDING )
3381 /* Wait in order to give APCs a chance to run. */
3382 /* This is cheating, so we must set the event again in case of success -
3383 it may be a non-manual reset event. */
3384 while ( (r = WaitForSingleObjectEx (lpOverlapped->hEvent, 0, TRUE)) == STATUS_USER_APC );
3385 if ( r == WAIT_OBJECT_0 )
3386 NtSetEvent ( lpOverlapped->hEvent, NULL );
3390 *lpcbTransfer = lpOverlapped->InternalHigh;
3393 *lpdwFlags = lpOverlapped->Offset;
3395 switch ( lpOverlapped->Internal )
3397 case STATUS_SUCCESS:
3399 case STATUS_PENDING:
3400 WSASetLastError ( WSA_IO_INCOMPLETE );
3401 if (fWait) ERR ("PENDING status after waiting!\n");
3404 WSASetLastError ( NtStatusToWSAError ( lpOverlapped->Internal ));
3410 /***********************************************************************
3411 * WSAAsyncSelect (WS2_32.101)
3413 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
3417 TRACE("%x, hWnd %p, uMsg %08x, event %08lx\n", s, hWnd, uMsg, lEvent );
3419 SERVER_START_REQ( set_socket_event )
3421 req->handle = SOCKET2HANDLE(s);
3426 ret = wine_server_call( req );
3430 SetLastError(WSAEINVAL);
3431 return SOCKET_ERROR;
3434 /***********************************************************************
3435 * WSAAsyncSelect (WINSOCK.101)
3437 INT16 WINAPI WSAAsyncSelect16(SOCKET16 s, HWND16 hWnd, UINT16 wMsg, LONG lEvent)
3439 return (INT16)WSAAsyncSelect( s, HWND_32(hWnd), wMsg, lEvent );
3442 /***********************************************************************
3443 * WSARecvEx (WINSOCK.1107)
3445 * See description for WSARecvEx()
3447 INT16 WINAPI WSARecvEx16(SOCKET16 s, char *buf, INT16 len, INT16 *flags)
3449 FIXME("(WSARecvEx16) partial packet return value not set \n");
3451 return WINSOCK_recv16(s, buf, len, *flags);
3455 /***********************************************************************
3456 * WSACreateEvent (WS2_32.31)
3459 WSAEVENT WINAPI WSACreateEvent(void)
3461 /* Create a manual-reset event, with initial state: unsignealed */
3464 return CreateEventA(NULL, TRUE, FALSE, NULL);
3467 /***********************************************************************
3468 * WSACloseEvent (WS2_32.29)
3471 BOOL WINAPI WSACloseEvent(WSAEVENT event)
3473 TRACE ("event=%p\n", event);
3475 return CloseHandle(event);
3478 /***********************************************************************
3479 * WSASocketA (WS2_32.78)
3482 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
3483 LPWSAPROTOCOL_INFOA lpProtocolInfo,
3484 GROUP g, DWORD dwFlags)
3489 FIXME: The "advanced" parameters of WSASocketA (lpProtocolInfo,
3490 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
3493 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%lx\n",
3494 af, type, protocol, lpProtocolInfo, g, dwFlags );
3496 /* hack for WSADuplicateSocket */
3497 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
3498 ret = lpProtocolInfo->dwCatalogEntryId;
3499 TRACE("\tgot duplicate %04x\n", ret);
3503 /* check the socket family */
3507 case WS_AF_IPX: af = AF_IPX;
3513 SetLastError(WSAEAFNOSUPPORT);
3514 return INVALID_SOCKET;
3517 /* check the socket type */
3520 case WS_SOCK_STREAM:
3530 SetLastError(WSAESOCKTNOSUPPORT);
3531 return INVALID_SOCKET;
3534 /* check the protocol type */
3535 if ( protocol < 0 ) /* don't support negative values */
3537 SetLastError(WSAEPROTONOSUPPORT);
3538 return INVALID_SOCKET;
3541 if ( af == AF_UNSPEC) /* did they not specify the address family? */
3545 if (type == SOCK_STREAM) { af = AF_INET; break; }
3547 if (type == SOCK_DGRAM) { af = AF_INET; break; }
3548 default: SetLastError(WSAEPROTOTYPE); return INVALID_SOCKET;
3551 SERVER_START_REQ( create_socket )
3555 req->protocol = protocol;
3556 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
3557 req->flags = dwFlags;
3558 req->inherit = TRUE;
3559 set_error( wine_server_call( req ) );
3560 ret = HANDLE2SOCKET( reply->handle );
3565 TRACE("\tcreated %04x\n", ret );
3569 if (GetLastError() == WSAEACCES) /* raw socket denied */
3571 if (type == SOCK_RAW)
3572 MESSAGE("WARNING: Trying to create a socket of type SOCK_RAW, will fail unless running as root\n");
3574 MESSAGE("WS_SOCKET: not enough privileges to create socket, try running as root\n");
3575 SetLastError(WSAESOCKTNOSUPPORT);
3578 WARN("\t\tfailed!\n");
3579 return INVALID_SOCKET;
3583 /***********************************************************************
3584 * __WSAFDIsSet (WINSOCK.151)
3586 INT16 WINAPI __WSAFDIsSet16(SOCKET16 s, ws_fd_set16 *set)
3588 int i = set->fd_count;
3590 TRACE("(%d,%8lx(%i))\n", s,(unsigned long)set, i);
3593 if (set->fd_array[i] == s) return 1;
3597 /***********************************************************************
3598 * __WSAFDIsSet (WS2_32.151)
3600 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
3602 int i = set->fd_count;
3604 TRACE("(%d,%8lx(%i))\n", s,(unsigned long)set, i);
3607 if (set->fd_array[i] == s) return 1;
3611 /***********************************************************************
3612 * WSAIsBlocking (WINSOCK.114)
3613 * WSAIsBlocking (WS2_32.114)
3615 BOOL WINAPI WSAIsBlocking(void)
3617 /* By default WinSock should set all its sockets to non-blocking mode
3618 * and poll in PeekMessage loop when processing "blocking" ones. This
3619 * function is supposed to tell if the program is in this loop. Our
3620 * blocking calls are truly blocking so we always return FALSE.
3622 * Note: It is allowed to call this function without prior WSAStartup().
3629 /***********************************************************************
3630 * WSACancelBlockingCall (WINSOCK.113)
3631 * WSACancelBlockingCall (WS2_32.113)
3633 INT WINAPI WSACancelBlockingCall(void)
3640 /***********************************************************************
3641 * WSASetBlockingHook (WINSOCK.109)
3643 FARPROC16 WINAPI WSASetBlockingHook16(FARPROC16 lpBlockFunc)
3645 FARPROC16 prev = (FARPROC16)blocking_hook;
3646 blocking_hook = (FARPROC)lpBlockFunc;
3647 TRACE("hook %p\n", lpBlockFunc);
3652 /***********************************************************************
3653 * WSASetBlockingHook (WS2_32.109)
3655 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
3657 FARPROC prev = blocking_hook;
3658 blocking_hook = lpBlockFunc;
3659 TRACE("hook %p\n", lpBlockFunc);
3664 /***********************************************************************
3665 * WSAUnhookBlockingHook (WINSOCK.110)
3667 INT16 WINAPI WSAUnhookBlockingHook16(void)
3669 blocking_hook = NULL;
3674 /***********************************************************************
3675 * WSAUnhookBlockingHook (WS2_32.110)
3677 INT WINAPI WSAUnhookBlockingHook(void)
3679 blocking_hook = NULL;
3684 /* ----------------------------------- end of API stuff */
3686 /* ----------------------------------- helper functions -
3688 * TODO: Merge WS_dup_..() stuff into one function that
3689 * would operate with a generic structure containing internal
3690 * pointers (via a template of some kind).
3693 static int list_size(char** l, int item_size)
3698 j += (item_size) ? item_size : strlen(l[i]) + 1;
3699 j += (i + 1) * sizeof(char*); }
3703 static int list_dup(char** l_src, char* ref, char* base, int item_size)
3705 /* base is either either equal to ref or 0 or SEGPTR */
3708 char** l_to = (char**)ref;
3711 for(j=0;l_src[j];j++) ;
3712 p += (j + 1) * sizeof(char*);
3714 { l_to[i] = base + (p - ref);
3715 k = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
3716 memcpy(p, l_src[i], k); p += k; }
3723 static int hostent_size(struct hostent* p_he)
3727 { size = sizeof(struct hostent);
3728 size += strlen(p_he->h_name) + 1;
3729 size += list_size(p_he->h_aliases, 0);
3730 size += list_size(p_he->h_addr_list, p_he->h_length ); }
3734 /* duplicate hostent entry
3735 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
3736 * Dito for protoent and servent.
3738 static int WS_dup_he(struct hostent* p_he, int flag)
3740 /* Convert hostent structure into ws_hostent so that the data fits
3741 * into local_buffer. Internal pointers can be linear, SEGPTR, or
3742 * relative to local_buffer depending on "flag" value. Returns size
3743 * of the data copied.
3746 int size = hostent_size(p_he);
3749 char *p_name,*p_aliases,*p_addr,*p_base,*p;
3751 struct ws_hostent16 *p_to16;
3752 struct WS_hostent *p_to32;
3754 check_buffer_he(size);
3760 p_base = (flag & WS_DUP_SEGPTR) ? (char*)he_buffer_seg : he_buffer;
3761 p += (flag & WS_DUP_SEGPTR) ?
3762 sizeof(struct ws_hostent16) : sizeof(struct WS_hostent);
3764 strcpy(p, p_he->h_name); p += strlen(p) + 1;
3766 p += list_dup(p_he->h_aliases, p, p_base + (p - p_to), 0);
3768 list_dup(p_he->h_addr_list, p, p_base + (p - p_to), p_he->h_length);
3770 if (flag & WS_DUP_SEGPTR) /* Win16 */
3772 p_to16->h_addrtype = (INT16)p_he->h_addrtype;
3773 p_to16->h_length = (INT16)p_he->h_length;
3774 p_to16->h_name = (SEGPTR)(p_base + (p_name - p_to));
3775 p_to16->h_aliases = (SEGPTR)(p_base + (p_aliases - p_to));
3776 p_to16->h_addr_list = (SEGPTR)(p_base + (p_addr - p_to));
3777 size += (sizeof(struct ws_hostent16) - sizeof(struct hostent));
3781 p_to32->h_addrtype = p_he->h_addrtype;
3782 p_to32->h_length = p_he->h_length;
3783 p_to32->h_name = (p_base + (p_name - p_to));
3784 p_to32->h_aliases = (char **)(p_base + (p_aliases - p_to));
3785 p_to32->h_addr_list = (char **)(p_base + (p_addr - p_to));
3786 size += (sizeof(struct WS_hostent) - sizeof(struct hostent));
3792 /* ----- protoent */
3794 static int protoent_size(struct protoent* p_pe)
3798 { size = sizeof(struct protoent);
3799 size += strlen(p_pe->p_name) + 1;
3800 size += list_size(p_pe->p_aliases, 0); }
3804 static int WS_dup_pe(struct protoent* p_pe, int flag)
3806 int size = protoent_size(p_pe);
3810 struct ws_protoent16 *p_to16;
3811 struct WS_protoent *p_to32;
3812 char *p_name,*p_aliases,*p_base,*p;
3814 check_buffer_pe(size);
3819 p_base = (flag & WS_DUP_SEGPTR) ? (char*)pe_buffer_seg : pe_buffer;
3820 p += (flag & WS_DUP_SEGPTR) ?
3821 sizeof(struct ws_protoent16) : sizeof(struct WS_protoent);
3823 strcpy(p, p_pe->p_name); p += strlen(p) + 1;
3825 list_dup(p_pe->p_aliases, p, p_base + (p - p_to), 0);
3827 if (flag & WS_DUP_SEGPTR) /* Win16 */
3829 p_to16->p_proto = (INT16)p_pe->p_proto;
3830 p_to16->p_name = (SEGPTR)(p_base) + (p_name - p_to);
3831 p_to16->p_aliases = (SEGPTR)((p_base) + (p_aliases - p_to));
3832 size += (sizeof(struct ws_protoent16) - sizeof(struct protoent));
3836 p_to32->p_proto = p_pe->p_proto;
3837 p_to32->p_name = (p_base) + (p_name - p_to);
3838 p_to32->p_aliases = (char **)((p_base) + (p_aliases - p_to));
3839 size += (sizeof(struct WS_protoent) - sizeof(struct protoent));
3847 static int servent_size(struct servent* p_se)
3851 { size += sizeof(struct servent);
3852 size += strlen(p_se->s_proto) + strlen(p_se->s_name) + 2;
3853 size += list_size(p_se->s_aliases, 0); }
3857 static int WS_dup_se(struct servent* p_se, int flag)
3859 int size = servent_size(p_se);
3862 char *p_name,*p_aliases,*p_proto,*p_base,*p;
3864 struct ws_servent16 *p_to16;
3865 struct WS_servent *p_to32;
3867 check_buffer_se(size);
3872 p_base = (flag & WS_DUP_SEGPTR) ? (char*)se_buffer_seg : se_buffer;
3873 p += (flag & WS_DUP_SEGPTR) ?
3874 sizeof(struct ws_servent16) : sizeof(struct WS_servent);
3876 strcpy(p, p_se->s_name); p += strlen(p) + 1;
3878 strcpy(p, p_se->s_proto); p += strlen(p) + 1;
3880 list_dup(p_se->s_aliases, p, p_base + (p - p_to), 0);
3882 if (flag & WS_DUP_SEGPTR) /* Win16 */
3884 p_to16->s_port = (INT16)p_se->s_port;
3885 p_to16->s_name = (SEGPTR)(p_base + (p_name - p_to));
3886 p_to16->s_proto = (SEGPTR)(p_base + (p_proto - p_to));
3887 p_to16->s_aliases = (SEGPTR)(p_base + (p_aliases - p_to));
3888 size += (sizeof(struct ws_servent16) - sizeof(struct servent));
3892 p_to32->s_port = p_se->s_port;
3893 p_to32->s_name = (p_base + (p_name - p_to));
3894 p_to32->s_proto = (p_base + (p_proto - p_to));
3895 p_to32->s_aliases = (char **)(p_base + (p_aliases - p_to));
3896 size += (sizeof(struct WS_servent) - sizeof(struct servent));
3902 /* ----------------------------------- error handling */
3904 UINT16 wsaErrno(void)
3906 int loc_errno = errno;
3907 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
3911 case EINTR: return WSAEINTR;
3912 case EBADF: return WSAEBADF;
3914 case EACCES: return WSAEACCES;
3915 case EFAULT: return WSAEFAULT;
3916 case EINVAL: return WSAEINVAL;
3917 case EMFILE: return WSAEMFILE;
3918 case EWOULDBLOCK: return WSAEWOULDBLOCK;
3919 case EINPROGRESS: return WSAEINPROGRESS;
3920 case EALREADY: return WSAEALREADY;
3921 case ENOTSOCK: return WSAENOTSOCK;
3922 case EDESTADDRREQ: return WSAEDESTADDRREQ;
3923 case EMSGSIZE: return WSAEMSGSIZE;
3924 case EPROTOTYPE: return WSAEPROTOTYPE;
3925 case ENOPROTOOPT: return WSAENOPROTOOPT;
3926 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
3927 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
3928 case EOPNOTSUPP: return WSAEOPNOTSUPP;
3929 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
3930 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
3931 case EADDRINUSE: return WSAEADDRINUSE;
3932 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
3933 case ENETDOWN: return WSAENETDOWN;
3934 case ENETUNREACH: return WSAENETUNREACH;
3935 case ENETRESET: return WSAENETRESET;
3936 case ECONNABORTED: return WSAECONNABORTED;
3938 case ECONNRESET: return WSAECONNRESET;
3939 case ENOBUFS: return WSAENOBUFS;
3940 case EISCONN: return WSAEISCONN;
3941 case ENOTCONN: return WSAENOTCONN;
3942 case ESHUTDOWN: return WSAESHUTDOWN;
3943 case ETOOMANYREFS: return WSAETOOMANYREFS;
3944 case ETIMEDOUT: return WSAETIMEDOUT;
3945 case ECONNREFUSED: return WSAECONNREFUSED;
3946 case ELOOP: return WSAELOOP;
3947 case ENAMETOOLONG: return WSAENAMETOOLONG;
3948 case EHOSTDOWN: return WSAEHOSTDOWN;
3949 case EHOSTUNREACH: return WSAEHOSTUNREACH;
3950 case ENOTEMPTY: return WSAENOTEMPTY;
3952 case EPROCLIM: return WSAEPROCLIM;
3955 case EUSERS: return WSAEUSERS;
3958 case EDQUOT: return WSAEDQUOT;
3961 case ESTALE: return WSAESTALE;
3964 case EREMOTE: return WSAEREMOTE;
3967 /* just in case we ever get here and there are no problems */
3970 WARN("Unknown errno %d!\n", loc_errno);
3971 return WSAEOPNOTSUPP;
3975 UINT16 wsaHerrno(int loc_errno)
3978 WARN("h_errno %d.\n", loc_errno);
3982 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
3983 case TRY_AGAIN: return WSATRY_AGAIN;
3984 case NO_RECOVERY: return WSANO_RECOVERY;
3985 case NO_DATA: return WSANO_DATA;
3986 case ENOBUFS: return WSAENOBUFS;
3990 WARN("Unknown h_errno %d!\n", loc_errno);
3991 return WSAEOPNOTSUPP;
3996 /***********************************************************************
3997 * WSARecv (WS2_32.67)
3999 int WINAPI WSARecv (SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4000 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
4001 LPWSAOVERLAPPED lpOverlapped,
4002 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
4004 return WSARecvFrom (s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
4005 NULL, NULL, lpOverlapped, lpCompletionRoutine);
4008 /***********************************************************************
4009 * WSARecvFrom (WS2_32.69)
4011 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4012 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
4013 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
4014 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4017 int i, n, fd, err = WSAENOTSOCK, flags, ret;
4018 struct iovec* iovec;
4019 struct ws2_async *wsa;
4022 TRACE("socket %04x, wsabuf %p, nbufs %ld, flags %ld, from %p, fromlen %ld, ovl %p, func %p\n",
4023 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
4024 (lpFromlen ? *lpFromlen : -1L),
4025 lpOverlapped, lpCompletionRoutine);
4027 fd = _get_sock_fd_type( s, GENERIC_READ, &type, &flags );
4028 TRACE ( "fd=%d, type=%d, flags=%x\n", fd, type, flags );
4032 err = WSAGetLastError ();
4036 iovec = HeapAlloc ( GetProcessHeap(), 0, dwBufferCount * sizeof (struct iovec) );
4043 for (i = 0; i < dwBufferCount; i++)
4045 iovec[i].iov_base = lpBuffers[i].buf;
4046 iovec[i].iov_len = lpBuffers[i].len;
4049 if ( (lpOverlapped || lpCompletionRoutine) && flags & FD_FLAG_OVERLAPPED )
4051 wsa = WS2_make_async ( s, fd, ASYNC_TYPE_READ, iovec, dwBufferCount,
4052 lpFlags, lpFrom, lpFromlen,
4053 lpOverlapped, lpCompletionRoutine );
4061 if ( ( ret = register_new_async ( &wsa->async )) )
4063 err = NtStatusToWSAError ( ret );
4065 if ( !lpOverlapped )
4066 HeapFree ( GetProcessHeap(), 0, wsa->overlapped );
4067 HeapFree ( GetProcessHeap(), 0, wsa );
4071 /* Try immediate completion */
4072 if ( lpOverlapped && !NtResetEvent( lpOverlapped->hEvent, NULL ) )
4074 if ( WSAGetOverlappedResult ( s, lpOverlapped,
4075 lpNumberOfBytesRecvd, FALSE, lpFlags) )
4078 if ( (err = WSAGetLastError ()) != WSA_IO_INCOMPLETE )
4082 WSASetLastError ( WSA_IO_PENDING );
4083 return SOCKET_ERROR;
4086 if ( _is_blocking(s) )
4089 /* FIXME: OOB and exceptfds? */
4093 n = WS2_recv ( fd, iovec, dwBufferCount, lpFrom, lpFromlen, lpFlags );
4100 TRACE(" -> %i bytes\n", n);
4101 *lpNumberOfBytesRecvd = n;
4103 HeapFree (GetProcessHeap(), 0, iovec);
4105 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4110 HeapFree (GetProcessHeap(), 0, iovec);
4116 WARN(" -> ERROR %d\n", err);
4117 WSASetLastError ( err );
4118 return SOCKET_ERROR;
4121 /***********************************************************************
4122 * WSCInstallProvider (WS2_32.88)
4124 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
4125 LPCWSTR lpszProviderDllPath,
4126 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
4127 DWORD dwNumberOfEntries,
4130 FIXME("(%s, %s, %p, %ld, %p): stub !\n", debugstr_guid(lpProviderId),
4131 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
4132 dwNumberOfEntries, lpErrno);
4138 /***********************************************************************
4139 * WSCDeinstallProvider (WS2_32.83)
4141 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
4143 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
4149 /***********************************************************************
4150 * WSAAccept (WS2_32.26)
4152 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
4153 LPCONDITIONPROC lpfnCondition, DWORD dwCallbackData)
4156 int ret = 0, size = 0;
4157 WSABUF CallerId, CallerData, CalleeId, CalleeData;
4158 /* QOS SQOS, GQOS; */
4161 SOCKADDR src_addr, dst_addr;
4163 TRACE("Socket %u, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
4164 s, addr, addrlen, lpfnCondition, dwCallbackData);
4167 size = sizeof(src_addr);
4168 cs = WS_accept(s, &src_addr, &size);
4170 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
4172 CallerId.buf = (char *)&src_addr;
4173 CallerId.len = sizeof(src_addr);
4175 CallerData.buf = NULL;
4176 CallerData.len = (ULONG)NULL;
4178 WS_getsockname(cs, &dst_addr, &size);
4180 CalleeId.buf = (char *)&dst_addr;
4181 CalleeId.len = sizeof(dst_addr);
4184 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
4185 &CalleeId, &CalleeData, &g, dwCallbackData);
4190 if (addr && addrlen)
4191 addr = memcpy(addr, &src_addr, (*addrlen > size) ? size : *addrlen );
4194 SERVER_START_REQ ( set_socket_deferred )
4196 req->handle = SOCKET2HANDLE (s);
4197 req->deferred = SOCKET2HANDLE (cs);
4198 if ( !wine_server_call_err ( req ) )
4200 SetLastError ( WSATRY_AGAIN );
4201 WS_closesocket ( cs );
4205 return SOCKET_ERROR;
4208 SetLastError(WSAECONNREFUSED);
4209 return SOCKET_ERROR;
4211 FIXME("Unknown return type from Condition function\n");
4212 SetLastError(WSAENOTSOCK);
4213 return SOCKET_ERROR;
4217 /***********************************************************************
4218 * WSAEnumProtocolsA (WS2_32.37)
4220 int WINAPI WSAEnumProtocolsA(LPINT lpiProtocols, LPWSAPROTOCOL_INFOA lpProtocolBuffer, LPDWORD lpdwBufferLength)
4222 FIXME("(%p,%p,%p): stub\n", lpiProtocols,lpProtocolBuffer, lpdwBufferLength);
4226 /***********************************************************************
4227 * WSAEnumProtocolsW (WS2_32.38)
4229 int WINAPI WSAEnumProtocolsW(LPINT lpiProtocols, LPWSAPROTOCOL_INFOW lpProtocolBuffer, LPDWORD lpdwBufferLength)
4231 FIXME("(%p,%p,%p): stub\n", lpiProtocols,lpProtocolBuffer, lpdwBufferLength);
4235 /***********************************************************************
4236 * WSADuplicateSocketA (WS2_32.32)
4238 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
4242 TRACE("(%d,%lx,%p)\n", s, dwProcessId, lpProtocolInfo);
4243 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
4244 /* FIXME: WS_getsockopt(s, WS_SOL_SOCKET, SO_PROTOCOL_INFO, lpProtocolInfo, sizeof(*lpProtocolInfo)); */
4245 /* I don't know what the real Windoze does next, this is a hack */
4246 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
4247 * the target use the global duplicate, or we could copy a reference to us to the structure
4248 * and let the target duplicate it from us, but let's do it as simple as possible */
4249 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
4250 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
4251 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
4252 0, FALSE, DUPLICATE_SAME_ACCESS);
4253 CloseHandle(hProcess);
4254 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
4258 /***********************************************************************
4259 * WSAInstallServiceClassA (WS2_32.48)
4261 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
4263 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
4264 WSASetLastError(WSAEACCES);
4265 return SOCKET_ERROR;
4268 /***********************************************************************
4269 * WSAInstallServiceClassW (WS2_32.49)
4271 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
4273 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
4274 WSASetLastError(WSAEACCES);
4275 return SOCKET_ERROR;
4278 /***********************************************************************
4279 * WSARemoveServiceClass (WS2_32.70)
4281 int WINAPI WSARemoveServiceClass(LPGUID info)
4283 FIXME("Request to remove service %p\n",info);
4284 WSASetLastError(WSATYPE_NOT_FOUND);
4285 return SOCKET_ERROR;