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>
60 #ifdef HAVE_SYS_SOCKET_H
61 #include <sys/socket.h>
63 #ifdef HAVE_NETINET_IN_H
64 # include <netinet/in.h>
66 #ifdef HAVE_NETINET_TCP_H
67 # include <netinet/tcp.h>
69 #ifdef HAVE_ARPA_INET_H
70 # include <arpa/inet.h>
75 #ifdef HAVE_SYS_ERRNO_H
76 #include <sys/errno.h>
83 #ifdef HAVE_ARPA_NAMESER_H
84 # include <arpa/nameser.h>
93 # include <netipx/ipx.h>
97 # include <asm/types.h>
98 # include <linux/ipx.h>
102 #ifdef HAVE_SYS_TIME_H
103 # include <sys/time.h>
106 #include "wine/winbase16.h"
109 #include "winerror.h"
110 #include "winsock2.h"
111 #include "ws2tcpip.h"
113 #include "wine/winsock16.h"
115 #include "wine/server.h"
116 #include "wine/debug.h"
119 WINE_DEFAULT_DEBUG_CHANNEL(winsock);
121 /* critical section to protect some non-rentrant net function */
122 extern CRITICAL_SECTION csWSgetXXXbyYYY;
124 #define DEBUG_SOCKADDR 0
125 #define dump_sockaddr(a) \
126 DPRINTF("sockaddr_in: family %d, address %s, port %d\n", \
127 ((struct sockaddr_in *)a)->sin_family, \
128 inet_ntoa(((struct sockaddr_in *)a)->sin_addr), \
129 ntohs(((struct sockaddr_in *)a)->sin_port))
131 /****************************************************************
132 * Async IO declarations
133 ****************************************************************/
136 static DWORD ws2_async_get_status (const struct async_private *ovp);
137 static DWORD ws2_async_get_count (const struct async_private *ovp);
138 static void ws2_async_set_status (struct async_private *ovp, const DWORD status);
139 static void CALLBACK ws2_async_call_completion (ULONG_PTR data);
140 static void ws2_async_cleanup ( struct async_private *ovp );
142 static struct async_ops ws2_async_ops =
144 ws2_async_get_status,
145 ws2_async_set_status,
147 ws2_async_call_completion,
151 static struct async_ops ws2_nocomp_async_ops =
153 ws2_async_get_status,
154 ws2_async_set_status,
156 NULL, /* call_completion */
160 typedef struct ws2_async
163 LPWSAOVERLAPPED overlapped;
164 LPWSAOVERLAPPED user_overlapped;
165 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
168 struct WS_sockaddr *addr;
170 int val; /* for send operations */
171 int *ptr; /* for recv operations */
176 /****************************************************************/
178 /* ----------------------------------- internal data */
180 /* ws_... struct conversion flags */
182 #define WS_DUP_LINEAR 0x0001
183 #define WS_DUP_SEGPTR 0x0002 /* internal pointers are SEGPTRs */
184 /* by default, internal pointers are linear */
185 typedef struct /* WSAAsyncSelect() control struct */
187 HANDLE service, event, sock;
193 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
194 #define WS_MAX_UDP_DATAGRAM 1024
196 #define PROCFS_NETDEV_FILE "/proc/net/dev" /* Points to the file in the /proc fs
197 that lists the network devices.
198 Do we need an #ifdef LINUX for this? */
200 static void *he_buffer; /* typecast for Win16/32 ws_hostent */
201 static SEGPTR he_buffer_seg;
202 static void *se_buffer; /* typecast for Win16/32 ws_servent */
203 static SEGPTR se_buffer_seg;
204 static void *pe_buffer; /* typecast for Win16/32 ws_protoent */
205 static SEGPTR pe_buffer_seg;
206 static char* local_buffer;
207 static SEGPTR dbuffer_seg;
208 static INT num_startup; /* reference counter */
209 static FARPROC blocking_hook;
211 /* function prototypes */
212 static int WS_dup_he(struct hostent* p_he, int flag);
213 static int WS_dup_pe(struct protoent* p_pe, int flag);
214 static int WS_dup_se(struct servent* p_se, int flag);
216 typedef void WIN_hostent;
217 typedef void WIN_protoent;
218 typedef void WIN_servent;
220 int WSAIOCTL_GetInterfaceCount(void);
221 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
223 UINT16 wsaErrno(void);
224 UINT16 wsaHerrno(int errnr);
226 static HANDLE _WSHeap = 0;
228 #define WS_ALLOC(size) \
229 HeapAlloc(_WSHeap, HEAP_ZERO_MEMORY, (size) )
230 #define WS_FREE(ptr) \
231 HeapFree(_WSHeap, 0, (ptr) )
233 static INT _ws_sock_ops[] =
234 { WS_SO_DEBUG, WS_SO_REUSEADDR, WS_SO_KEEPALIVE, WS_SO_DONTROUTE,
235 WS_SO_BROADCAST, WS_SO_LINGER, WS_SO_OOBINLINE, WS_SO_SNDBUF,
236 WS_SO_RCVBUF, WS_SO_ERROR, WS_SO_TYPE,
244 static int _px_sock_ops[] =
245 { SO_DEBUG, SO_REUSEADDR, SO_KEEPALIVE, SO_DONTROUTE, SO_BROADCAST,
246 SO_LINGER, SO_OOBINLINE, SO_SNDBUF, SO_RCVBUF, SO_ERROR, SO_TYPE,
255 static INT _ws_tcp_ops[] = {
261 static int _px_tcp_ops[] = {
268 static DWORD opentype_tls_index = -1; /* TLS index for SO_OPENTYPE flag */
270 inline static DWORD NtStatusToWSAError ( const DWORD status )
272 /* We only need to cover the status codes set by server async request handling */
276 case STATUS_SUCCESS: wserr = 0; break;
277 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
278 case STATUS_INVALID_HANDLE: wserr = WSAENOTSOCK; break; /* WSAEBADF ? */
279 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
280 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
281 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
282 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
283 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
285 if ( status >= WSABASEERR && status <= WSABASEERR+1004 )
286 /* It is not a NT status code but a winsock error */
290 wserr = RtlNtStatusToDosError( status );
291 FIXME ( "Status code %08lx converted to DOS error code %lx\n", status, wserr );
297 /* set last error code from NT status without mapping WSA errors */
298 inline static unsigned int set_error( unsigned int err )
302 err = NtStatusToWSAError ( err );
308 static char* check_buffer(int size);
310 inline static int _get_sock_fd(SOCKET s)
314 if (set_error( wine_server_handle_to_fd( s, GENERIC_READ, &fd, NULL, NULL ) )) return -1;
318 inline static int _get_sock_fd_type( SOCKET s, DWORD access, enum fd_type *type, int *flags )
321 if (set_error( wine_server_handle_to_fd( s, access, &fd, type, flags ) )) return -1;
322 if ( ( (access & GENERIC_READ) && (*flags & FD_FLAG_RECV_SHUTDOWN ) ) ||
323 ( (access & GENERIC_WRITE) && (*flags & FD_FLAG_SEND_SHUTDOWN ) ) )
326 WSASetLastError ( WSAESHUTDOWN );
332 static void _enable_event(SOCKET s, unsigned int event,
333 unsigned int sstate, unsigned int cstate)
335 SERVER_START_REQ( enable_socket_event )
339 req->sstate = sstate;
340 req->cstate = cstate;
341 wine_server_call( req );
346 static int _is_blocking(SOCKET s)
349 SERVER_START_REQ( get_socket_event )
352 req->service = FALSE;
354 wine_server_call( req );
355 ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
361 static unsigned int _get_sock_mask(SOCKET s)
364 SERVER_START_REQ( get_socket_event )
367 req->service = FALSE;
369 wine_server_call( req );
376 static void _sync_sock_state(SOCKET s)
378 /* do a dummy wineserver request in order to let
379 the wineserver run through its select loop once */
380 (void)_is_blocking(s);
383 static int _get_sock_error(SOCKET s, unsigned int bit)
385 int events[FD_MAX_EVENTS];
387 SERVER_START_REQ( get_socket_event )
390 req->service = FALSE;
392 wine_server_set_reply( req, events, sizeof(events) );
393 wine_server_call( req );
399 static void WINSOCK_DeleteIData(void)
401 /* delete scratch buffers */
403 UnMapLS( he_buffer_seg );
404 UnMapLS( se_buffer_seg );
405 UnMapLS( pe_buffer_seg );
406 UnMapLS( dbuffer_seg );
407 if (he_buffer) HeapFree( GetProcessHeap(), 0, he_buffer );
408 if (se_buffer) HeapFree( GetProcessHeap(), 0, se_buffer );
409 if (pe_buffer) HeapFree( GetProcessHeap(), 0, pe_buffer );
410 if (local_buffer) HeapFree( GetProcessHeap(), 0, local_buffer );
422 /***********************************************************************
423 * WS_LibMain (WS2_32.init)
425 BOOL WINAPI WS_LibMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
427 TRACE("0x%x 0x%lx %p\n", hInstDLL, fdwReason, fImpLoad);
429 case DLL_PROCESS_ATTACH:
430 opentype_tls_index = TlsAlloc();
432 case DLL_PROCESS_DETACH:
433 TlsFree( opentype_tls_index );
434 WINSOCK_DeleteIData();
440 /***********************************************************************
443 * Converts socket flags from Windows format.
444 * Return 1 if converted, 0 if not (error).
446 static int convert_sockopt(INT *level, INT *optname)
453 for(i=0; _ws_sock_ops[i]; i++)
454 if( _ws_sock_ops[i] == *optname ) break;
455 if( _ws_sock_ops[i] ) {
456 *optname = _px_sock_ops[i];
459 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
462 *level = IPPROTO_TCP;
463 for(i=0; _ws_tcp_ops[i]; i++)
464 if ( _ws_tcp_ops[i] == *optname ) break;
465 if( _ws_tcp_ops[i] ) {
466 *optname = _px_tcp_ops[i];
469 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
475 /* ----------------------------------- Per-thread info (or per-process?) */
477 static int wsi_strtolo(const char* name, const char* opt)
479 /* Stuff a lowercase copy of the string into the local buffer */
481 int i = strlen(name) + 2;
482 char* p = check_buffer(i + ((opt)?strlen(opt):0));
486 do *p++ = tolower(*name); while(*name++);
487 i = (p - local_buffer);
488 if( opt ) do *p++ = tolower(*opt); while(*opt++);
494 static fd_set* fd_set_import( fd_set* fds, void* wsfds, int* highfd, int lfd[], BOOL b32 )
496 /* translate Winsock fd set into local fd set */
500 #define wsfds16 ((ws_fd_set16*)wsfds)
501 #define wsfds32 ((WS_fd_set*)wsfds)
505 count = b32 ? wsfds32->fd_count : wsfds16->fd_count;
507 for( i = 0; i < count; i++ )
509 int s = (b32) ? wsfds32->fd_array[i]
510 : wsfds16->fd_array[i];
511 int fd = _get_sock_fd(s);
515 if( fd > *highfd ) *highfd = fd;
527 inline static int sock_error_p(int s)
529 unsigned int optval, optlen;
531 optlen = sizeof(optval);
532 getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
533 if (optval) WARN("\t[%i] error: %d\n", s, optval);
537 static int fd_set_export( fd_set* fds, fd_set* exceptfds, void* wsfds, int lfd[], BOOL b32 )
541 /* translate local fd set into Winsock fd set, adding
542 * errors to exceptfds (only if app requested it) */
546 #define wsfds16 ((ws_fd_set16*)wsfds)
547 #define wsfds32 ((WS_fd_set*)wsfds)
548 int i, j, count = (b32) ? wsfds32->fd_count : wsfds16->fd_count;
550 for( i = 0, j = 0; i < count; i++ )
555 if( FD_ISSET(fd, fds) )
557 if ( exceptfds && sock_error_p(fd) )
559 FD_SET(fd, exceptfds);
563 wsfds32->fd_array[j++] = wsfds32->fd_array[i];
565 wsfds16->fd_array[j++] = wsfds16->fd_array[i];
572 if( b32 ) wsfds32->fd_count = j;
573 else wsfds16->fd_count = j;
582 static void fd_set_unimport( void* wsfds, int lfd[], BOOL b32 )
586 #define wsfds16 ((ws_fd_set16*)wsfds)
587 #define wsfds32 ((WS_fd_set*)wsfds)
588 int i, count = (b32) ? wsfds32->fd_count : wsfds16->fd_count;
590 for( i = 0; i < count; i++ )
600 static int do_block( int fd, int mask )
611 i = select( fd+1, &fds[0], &fds[1], &fds[2], NULL );
612 if (i <= 0) return -1;
615 if (FD_ISSET(fd, &fds[i]))
620 void* __ws_memalloc( int size )
622 return WS_ALLOC(size);
625 void __ws_memfree(void* ptr)
631 /* ----------------------------------- API -----
633 * Init / cleanup / error checking.
636 /***********************************************************************
637 * WSAStartup (WINSOCK.115)
639 * Create socket control struct, attach it to the global list and
640 * update a pointer in the task struct.
642 INT16 WINAPI WSAStartup16(UINT16 wVersionRequested, LPWSADATA16 lpWSAData)
644 static const WSADATA16 data =
650 #elif defined(__NetBSD__)
654 #elif defined(__FreeBSD__)
656 #elif defined(__OpenBSD__)
661 WS_MAX_SOCKETS_PER_PROCESS,
666 TRACE("verReq=%x\n", wVersionRequested);
668 if (LOBYTE(wVersionRequested) < 1 || (LOBYTE(wVersionRequested) == 1 &&
669 HIBYTE(wVersionRequested) < 1)) return WSAVERNOTSUPPORTED;
671 if (!lpWSAData) return WSAEINVAL;
673 /* initialize socket heap */
677 _WSHeap = HeapCreate(HEAP_ZERO_MEMORY, 8120, 32768);
680 ERR("Fatal: failed to create WinSock heap\n");
684 if( _WSHeap == 0 ) return WSASYSNOTREADY;
688 /* return winsock information */
690 memcpy(lpWSAData, &data, sizeof(data));
692 TRACE("succeeded\n");
696 /***********************************************************************
697 * WSAStartup (WS2_32.115)
699 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
701 static const WSADATA data =
707 #elif defined(__NetBSD__)
711 #elif defined(__FreeBSD__)
713 #elif defined(__OpenBSD__)
718 WS_MAX_SOCKETS_PER_PROCESS,
723 TRACE("verReq=%x\n", wVersionRequested);
725 if (LOBYTE(wVersionRequested) < 1)
726 return WSAVERNOTSUPPORTED;
728 if (!lpWSAData) return WSAEINVAL;
730 /* initialize socket heap */
734 _WSHeap = HeapCreate(HEAP_ZERO_MEMORY, 8120, 32768);
737 ERR("Fatal: failed to create WinSock heap\n");
741 if( _WSHeap == 0 ) return WSASYSNOTREADY;
745 /* return winsock information */
746 memcpy(lpWSAData, &data, sizeof(data));
748 /* that's the whole of the negotiation for now */
749 lpWSAData->wVersion = wVersionRequested;
751 TRACE("succeeded\n");
756 /***********************************************************************
757 * WSACleanup (WINSOCK.116)
758 * WSACleanup (WS2_32.116)
760 INT WINAPI WSACleanup(void)
764 if (--num_startup > 0) return 0;
765 WINSOCK_DeleteIData();
768 SetLastError(WSANOTINITIALISED);
773 /***********************************************************************
774 * WSAGetLastError (WINSOCK.111)
775 * WSAGetLastError (WS2_32.111)
777 INT WINAPI WSAGetLastError(void)
779 return GetLastError();
782 /***********************************************************************
783 * WSASetLastError (WS2_32.112)
785 void WINAPI WSASetLastError(INT iError) {
786 SetLastError(iError);
789 /***********************************************************************
790 * WSASetLastError (WINSOCK.112)
792 void WINAPI WSASetLastError16(INT16 iError)
794 WSASetLastError(iError);
797 static char* check_buffer(int size)
799 static int local_buflen;
803 if (local_buflen >= size ) return local_buffer;
804 HeapFree( GetProcessHeap(), 0, local_buffer );
806 local_buffer = HeapAlloc( GetProcessHeap(), 0, (local_buflen = size) );
810 static struct ws_hostent* check_buffer_he(int size)
815 if (he_len >= size ) return he_buffer;
816 UnMapLS( he_buffer_seg );
817 HeapFree( GetProcessHeap(), 0, he_buffer );
819 he_buffer = HeapAlloc( GetProcessHeap(), 0, (he_len = size) );
820 he_buffer_seg = MapLS( he_buffer );
824 static void* check_buffer_se(int size)
829 if (se_len >= size ) return se_buffer;
830 UnMapLS( se_buffer_seg );
831 HeapFree( GetProcessHeap(), 0, se_buffer );
833 se_buffer = HeapAlloc( GetProcessHeap(), 0, (se_len = size) );
834 se_buffer_seg = MapLS( he_buffer );
838 static struct ws_protoent* check_buffer_pe(int size)
843 if (pe_len >= size ) return pe_buffer;
844 UnMapLS( pe_buffer_seg );
845 HeapFree( GetProcessHeap(), 0, pe_buffer );
847 pe_buffer = HeapAlloc( GetProcessHeap(), 0, (pe_len = size) );
848 pe_buffer_seg = MapLS( he_buffer );
852 /* ----------------------------------- i/o APIs */
855 #define SUPPORTED_PF(pf) ((pf)==WS_AF_INET || (pf)== WS_AF_IPX)
857 #define SUPPORTED_PF(pf) ((pf)==WS_AF_INET)
861 /**********************************************************************/
863 /* Returns the converted address if successful, NULL if it was too small to
864 * start with. Note that the returned pointer may be the original pointer
865 * if no conversion is necessary.
867 static const struct sockaddr* ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen, int *uaddrlen)
869 switch (wsaddr->sa_family)
874 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
875 struct sockaddr_ipx* uipx;
877 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
880 *uaddrlen=sizeof(struct sockaddr_ipx);
881 uipx=malloc(*uaddrlen);
882 uipx->sipx_family=AF_IPX;
883 uipx->sipx_port=wsipx->sa_socket;
884 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
887 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
888 uipx->sipx_type=IPX_FRAME_NONE;
890 return (const struct sockaddr*)uipx;
895 if (wsaddrlen<sizeof(struct WS_sockaddr))
898 /* No conversion needed, just return the original address */
900 return (const struct sockaddr*)wsaddr;
905 /* Allocates a Unix sockaddr structure to receive the data */
906 inline struct sockaddr* ws_sockaddr_alloc(const struct WS_sockaddr* wsaddr, int* wsaddrlen, int* uaddrlen)
910 ERR( "WINE shouldn't pass a NULL wsaddr! Attempting to continue\n" );
912 /* This is not strictly the right thing to do. Hope it works however */
921 *uaddrlen=max(sizeof(struct sockaddr),*wsaddrlen);
923 return malloc(*uaddrlen);
926 /* Returns 0 if successful, -1 if the buffer is too small */
927 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, int uaddrlen, struct WS_sockaddr* wsaddr, int* wsaddrlen)
931 switch(uaddr->sa_family)
936 struct sockaddr_ipx* uipx=(struct sockaddr_ipx*)uaddr;
937 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
940 switch (*wsaddrlen) /* how much can we copy? */
945 wsipx->sa_socket=uipx->sipx_port;
949 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
957 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
963 wsipx->sa_family=WS_AF_IPX;
975 /* No conversion needed */
976 memcpy(wsaddr,uaddr,*wsaddrlen);
977 if (*wsaddrlen<uaddrlen) {
987 /* to be called to free the memory allocated by ws_sockaddr_ws2u or
990 inline void ws_sockaddr_free(const struct sockaddr* uaddr, const struct WS_sockaddr* wsaddr)
992 if (uaddr!=NULL && uaddr!=(const struct sockaddr*)wsaddr)
996 /**************************************************************************
997 * Functions for handling overlapped I/O
998 **************************************************************************/
1000 static DWORD ws2_async_get_status (const struct async_private *ovp)
1002 return ((ws2_async*) ovp)->overlapped->Internal;
1005 static VOID ws2_async_set_status (struct async_private *ovp, const DWORD status)
1007 ((ws2_async*) ovp)->overlapped->Internal = status;
1010 static DWORD ws2_async_get_count (const struct async_private *ovp)
1012 return ((ws2_async*) ovp)->overlapped->InternalHigh;
1015 static void ws2_async_cleanup ( struct async_private *ap )
1017 struct ws2_async *as = (struct ws2_async*) ap;
1019 TRACE ( "as: %p uovl %p ovl %p\n", as, as->user_overlapped, as->overlapped );
1020 if ( !as->user_overlapped )
1022 if ( as->overlapped->hEvent != INVALID_HANDLE_VALUE )
1023 WSACloseEvent ( as->overlapped->hEvent );
1024 HeapFree ( GetProcessHeap(), 0, as->overlapped );
1028 HeapFree ( GetProcessHeap(), 0, as->iovec );
1030 HeapFree ( GetProcessHeap(), 0, as );
1033 static void CALLBACK ws2_async_call_completion (ULONG_PTR data)
1035 ws2_async* as = (ws2_async*) data;
1037 TRACE ("data: %p\n", as);
1039 as->completion_func ( NtStatusToWSAError (as->overlapped->Internal),
1040 as->overlapped->InternalHigh,
1041 as->user_overlapped,
1043 ws2_async_cleanup ( &as->async );
1046 /***********************************************************************
1047 * WS2_make_async (INTERNAL)
1050 static void WS2_async_recv (async_private *as);
1051 static void WS2_async_send (async_private *as);
1053 inline static struct ws2_async*
1054 WS2_make_async (SOCKET s, int fd, int type, struct iovec *iovec, DWORD dwBufferCount,
1055 LPDWORD lpFlags, struct WS_sockaddr *addr,
1056 LPINT addrlen, LPWSAOVERLAPPED lpOverlapped,
1057 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
1059 struct ws2_async *wsa = HeapAlloc ( GetProcessHeap(), 0, sizeof ( ws2_async ) );
1061 TRACE ( "wsa %p\n", wsa );
1066 wsa->async.ops = ( lpCompletionRoutine ? &ws2_async_ops : &ws2_nocomp_async_ops );
1067 wsa->async.handle = (HANDLE) s;
1069 wsa->async.type = type;
1072 case ASYNC_TYPE_READ:
1073 wsa->flags = *lpFlags;
1074 wsa->async.func = WS2_async_recv;
1075 wsa->addrlen.ptr = addrlen;
1077 case ASYNC_TYPE_WRITE:
1079 wsa->async.func = WS2_async_send;
1080 wsa->addrlen.val = *addrlen;
1083 ERR ("Invalid async type: %d\n", type);
1085 wsa->user_overlapped = lpOverlapped;
1086 wsa->completion_func = lpCompletionRoutine;
1088 wsa->n_iovecs = dwBufferCount;
1093 wsa->overlapped = lpOverlapped;
1094 wsa->async.event = ( lpCompletionRoutine ? INVALID_HANDLE_VALUE : lpOverlapped->hEvent );
1098 wsa->overlapped = HeapAlloc ( GetProcessHeap(), 0,
1099 sizeof (WSAOVERLAPPED) );
1100 if ( !wsa->overlapped )
1102 wsa->async.event = wsa->overlapped->hEvent = INVALID_HANDLE_VALUE;
1105 wsa->overlapped->InternalHigh = 0;
1106 TRACE ( "wsa %p, ops %p, h %d, ev %d, fd %d, func %p, ov %p, uov %p, cfunc %p\n",
1107 wsa, wsa->async.ops, wsa->async.handle, wsa->async.event, wsa->async.fd, wsa->async.func,
1108 wsa->overlapped, wsa->user_overlapped, wsa->completion_func );
1114 HeapFree ( GetProcessHeap(), 0, wsa );
1118 /***********************************************************************
1119 * WS2_recv (INTERNAL)
1121 * Work horse for both synchronous and asynchronous recv() operations.
1123 static int WS2_recv ( int fd, struct iovec* iov, int count,
1124 struct WS_sockaddr *lpFrom, LPINT lpFromlen,
1129 TRACE ( "fd %d, iovec %p, count %d addr %p, len %p, flags %lx\n",
1130 fd, iov, count, lpFrom, lpFromlen, *lpFlags);
1132 hdr.msg_name = NULL;
1137 dump_sockaddr (lpFrom);
1140 hdr.msg_namelen = *lpFromlen;
1141 hdr.msg_name = ws_sockaddr_alloc ( lpFrom, lpFromlen, &hdr.msg_namelen );
1142 if ( !hdr.msg_name )
1144 WSASetLastError ( WSAEFAULT );
1150 hdr.msg_namelen = 0;
1153 hdr.msg_iovlen = count;
1154 #ifdef HAVE_MSGHDR_ACCRIGHTS
1155 hdr.msg_accrights = NULL;
1156 hdr.msg_accrightslen = 0;
1158 hdr.msg_control = NULL;
1159 hdr.msg_controllen = 0;
1163 if ( (n = recvmsg (fd, &hdr, *lpFlags)) == -1 )
1165 TRACE ( "recvmsg error %d\n", errno);
1170 ws_sockaddr_u2ws ( hdr.msg_name, hdr.msg_namelen,
1171 lpFrom, lpFromlen ) != 0 )
1173 /* The from buffer was too small, but we read the data
1174 * anyway. Is that really bad?
1176 WSASetLastError ( WSAEFAULT );
1177 WARN ( "Address buffer too small\n" );
1182 ws_sockaddr_free ( hdr.msg_name, lpFrom );
1183 TRACE ("-> %d\n", n);
1187 /***********************************************************************
1188 * WS2_async_recv (INTERNAL)
1190 * Handler for overlapped recv() operations.
1192 static void WS2_async_recv ( async_private *as )
1194 ws2_async* wsa = (ws2_async*) as;
1197 TRACE ( "async %p\n", wsa );
1199 if ( wsa->overlapped->Internal != STATUS_PENDING )
1201 TRACE ( "status: %ld\n", wsa->overlapped->Internal );
1205 result = WS2_recv ( wsa->async.fd, wsa->iovec, wsa->n_iovecs,
1206 wsa->addr, wsa->addrlen.ptr, &wsa->flags );
1210 wsa->overlapped->Internal = STATUS_SUCCESS;
1211 wsa->overlapped->InternalHigh = result;
1212 TRACE ( "received %d bytes\n", result );
1213 _enable_event ( (SOCKET) wsa->async.handle, FD_READ, 0, 0 );
1218 if ( err == WSAEINTR || err == WSAEWOULDBLOCK ) /* errno: EINTR / EAGAIN */
1220 wsa->overlapped->Internal = STATUS_PENDING;
1221 _enable_event ( (SOCKET) wsa->async.handle, FD_READ, 0, 0 );
1222 TRACE ( "still pending\n" );
1226 wsa->overlapped->Internal = err;
1227 TRACE ( "Error: %x\n", err );
1231 /***********************************************************************
1232 * WS2_send (INTERNAL)
1234 * Work horse for both synchronous and asynchronous send() operations.
1236 static int WS2_send ( int fd, struct iovec* iov, int count,
1237 const struct WS_sockaddr *to, INT tolen, DWORD dwFlags )
1241 TRACE ( "fd %d, iovec %p, count %d addr %p, len %d, flags %lx\n",
1242 fd, iov, count, to, tolen, dwFlags);
1244 hdr.msg_name = NULL;
1251 hdr.msg_name = (struct sockaddr*) ws_sockaddr_ws2u ( to, tolen, &hdr.msg_namelen );
1252 if ( !hdr.msg_name )
1254 WSASetLastError ( WSAEFAULT );
1259 hdr.msg_namelen = 0;
1262 hdr.msg_iovlen = count;
1263 #ifdef HAVE_MSGHDR_ACCRIGHTS
1264 hdr.msg_accrights = NULL;
1265 hdr.msg_accrightslen = 0;
1267 hdr.msg_control = NULL;
1268 hdr.msg_controllen = 0;
1272 n = sendmsg (fd, &hdr, dwFlags);
1275 ws_sockaddr_free ( hdr.msg_name, to );
1279 /***********************************************************************
1280 * WS2_async_send (INTERNAL)
1282 * Handler for overlapped send() operations.
1284 static void WS2_async_send ( async_private *as )
1286 ws2_async* wsa = (ws2_async*) as;
1289 TRACE ( "async %p\n", wsa );
1291 if ( wsa->overlapped->Internal != STATUS_PENDING )
1293 TRACE ( "status: %ld\n", wsa->overlapped->Internal );
1297 result = WS2_send ( wsa->async.fd, wsa->iovec, wsa->n_iovecs,
1298 wsa->addr, wsa->addrlen.val, wsa->flags );
1302 wsa->overlapped->Internal = STATUS_SUCCESS;
1303 wsa->overlapped->InternalHigh = result;
1304 TRACE ( "sent %d bytes\n", result );
1305 _enable_event ( (SOCKET) wsa->async.handle, FD_WRITE, 0, 0 );
1310 if ( err == WSAEINTR )
1312 wsa->overlapped->Internal = STATUS_PENDING;
1313 _enable_event ( (SOCKET) wsa->async.handle, FD_WRITE, 0, 0 );
1314 TRACE ( "still pending\n" );
1318 /* We set the status to a winsock error code and check for that
1319 later in NtStatusToWSAError () */
1320 wsa->overlapped->Internal = err;
1321 TRACE ( "Error: %x\n", err );
1325 /***********************************************************************
1326 * WS2_async_shutdown (INTERNAL)
1328 * Handler for shutdown() operations on overlapped sockets.
1330 static void WS2_async_shutdown ( async_private *as )
1332 ws2_async* wsa = (ws2_async*) as;
1335 TRACE ( "async %p %d\n", wsa, wsa->async.type );
1336 switch ( wsa->async.type )
1338 case ASYNC_TYPE_READ:
1339 err = shutdown ( wsa->async.fd, 0 );
1341 case ASYNC_TYPE_WRITE:
1342 err = shutdown ( wsa->async.fd, 1 );
1345 ERR ("invalid type: %d\n", wsa->async.type );
1349 wsa->overlapped->Internal = wsaErrno ();
1351 wsa->overlapped->Internal = STATUS_SUCCESS;
1354 /***********************************************************************
1355 * WS2_register_async_shutdown (INTERNAL)
1357 * Helper function for WS_shutdown() on overlapped sockets.
1359 static int WS2_register_async_shutdown ( SOCKET s, int fd, int type )
1361 struct ws2_async *wsa;
1362 int ret, err = WSAEFAULT;
1365 LPWSAOVERLAPPED ovl = HeapAlloc (GetProcessHeap(), 0, sizeof ( WSAOVERLAPPED ));
1367 TRACE ("s %d fd %d type %d\n", s, fd, type);
1371 ovl->hEvent = WSACreateEvent ();
1372 if ( ovl->hEvent == WSA_INVALID_EVENT )
1375 wsa = WS2_make_async ( s, fd, type, NULL, 0,
1376 &dwflags, NULL, &len, ovl, NULL );
1380 /* Hack: this will cause ws2_async_cleanup() to free the overlapped structure */
1381 wsa->user_overlapped = NULL;
1382 wsa->async.func = WS2_async_shutdown;
1383 if ( (ret = register_new_async ( &wsa->async )) )
1385 err = NtStatusToWSAError ( ret );
1386 ws2_async_cleanup ( &wsa->async );
1392 WSACloseEvent ( ovl->hEvent );
1394 HeapFree ( GetProcessHeap(), 0, ovl );
1399 /***********************************************************************
1402 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr,
1405 int fd = _get_sock_fd(s);
1407 TRACE("socket %04x\n", (UINT16)s );
1411 if (_is_blocking(s))
1415 _sync_sock_state(s); /* let wineserver notice connection */
1416 /* retrieve any error codes from it */
1417 SetLastError(_get_sock_error(s, FD_ACCEPT_BIT));
1418 /* FIXME: care about the error? */
1421 SERVER_START_REQ( accept_socket )
1424 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
1425 req->inherit = TRUE;
1426 set_error( wine_server_call( req ) );
1427 as = (SOCKET)reply->handle;
1432 WS_getpeername(as, addr, addrlen32);
1438 SetLastError(WSAENOTSOCK);
1440 return INVALID_SOCKET;
1443 /***********************************************************************
1444 * accept (WINSOCK.1)
1446 SOCKET16 WINAPI WINSOCK_accept16(SOCKET16 s, struct WS_sockaddr* addr,
1449 INT addrlen32 = addrlen16 ? *addrlen16 : 0;
1450 SOCKET retSocket = WS_accept( s, addr, &addrlen32 );
1451 if( addrlen16 ) *addrlen16 = (INT16)addrlen32;
1452 return (SOCKET16)retSocket;
1455 /***********************************************************************
1458 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
1460 int fd = _get_sock_fd(s);
1463 TRACE("socket %04x, ptr %p, length %d\n", s, name, namelen);
1465 dump_sockaddr(name);
1471 if (!name || !SUPPORTED_PF(name->sa_family))
1473 SetLastError(WSAEAFNOSUPPORT);
1477 const struct sockaddr* uaddr;
1480 uaddr=ws_sockaddr_ws2u(name,namelen,&uaddrlen);
1483 SetLastError(WSAEFAULT);
1487 if (bind(fd, uaddr, uaddrlen) < 0)
1489 int loc_errno = errno;
1490 WARN("\tfailure - errno = %i\n", errno);
1495 SetLastError(WSAENOTSOCK);
1498 SetLastError(WSAEINVAL);
1501 SetLastError(wsaErrno());
1507 res=0; /* success */
1509 ws_sockaddr_free(uaddr,name);
1516 SetLastError(WSAENOTSOCK);
1521 /***********************************************************************
1524 INT16 WINAPI WINSOCK_bind16(SOCKET16 s, struct WS_sockaddr *name, INT16 namelen)
1526 return (INT16)WS_bind( s, name, namelen );
1529 /***********************************************************************
1530 * closesocket (WS2_32.3)
1532 int WINAPI WS_closesocket(SOCKET s)
1534 TRACE("socket %08x\n", s);
1535 if (CloseHandle(s)) return 0;
1536 return SOCKET_ERROR;
1539 /***********************************************************************
1540 * closesocket (WINSOCK.3)
1542 INT16 WINAPI WINSOCK_closesocket16(SOCKET16 s)
1544 return (INT16)WS_closesocket(s);
1547 /***********************************************************************
1548 * connect (WS2_32.4)
1550 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
1552 int fd = _get_sock_fd(s);
1554 TRACE("socket %04x, ptr %p, length %d\n", s, name, namelen);
1556 dump_sockaddr(name);
1561 const struct sockaddr* uaddr;
1564 uaddr=ws_sockaddr_ws2u(name,namelen,&uaddrlen);
1567 SetLastError(WSAEFAULT);
1573 rc=connect(fd, uaddr, uaddrlen);
1574 ws_sockaddr_free(uaddr,name);
1576 goto connect_success;
1579 if (errno == EINPROGRESS)
1581 /* tell wineserver that a connection is in progress */
1582 _enable_event(s, FD_CONNECT|FD_READ|FD_WRITE,
1583 FD_CONNECT|FD_READ|FD_WRITE,
1584 FD_WINE_CONNECTED|FD_WINE_LISTENING);
1585 if (_is_blocking(s))
1590 _sync_sock_state(s); /* let wineserver notice connection */
1591 /* retrieve any error codes from it */
1592 result = _get_sock_error(s, FD_CONNECT_BIT);
1594 SetLastError(result);
1597 goto connect_success;
1602 SetLastError(WSAEWOULDBLOCK);
1607 SetLastError(wsaErrno());
1613 SetLastError(WSAENOTSOCK);
1615 return SOCKET_ERROR;
1619 _enable_event(s, FD_CONNECT|FD_READ|FD_WRITE,
1620 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
1621 FD_CONNECT|FD_WINE_LISTENING);
1625 /***********************************************************************
1626 * connect (WINSOCK.4)
1628 INT16 WINAPI WINSOCK_connect16(SOCKET16 s, struct WS_sockaddr *name, INT16 namelen)
1630 return (INT16)WS_connect( s, name, namelen );
1633 /***********************************************************************
1634 * WSAConnect (WS2_32.30)
1636 int WINAPI WSAConnect ( SOCKET s, const struct WS_sockaddr* name, int namelen,
1637 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
1638 LPQOS lpSQOS, LPQOS lpGQOS )
1640 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
1641 FIXME ("unsupported parameters!\n");
1642 return WS_connect ( s, name, namelen );
1646 /***********************************************************************
1647 * getpeername (WS2_32.5)
1649 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
1654 TRACE("socket: %04x, ptr %p, len %8x\n", s, name, *namelen);
1656 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1657 if( (name == NULL) || (namelen == NULL) )
1659 SetLastError( WSAEFAULT );
1660 return SOCKET_ERROR;
1663 fd = _get_sock_fd(s);
1668 struct sockaddr* uaddr;
1671 uaddr=ws_sockaddr_alloc(name,namelen,&uaddrlen);
1672 if (getpeername(fd, uaddr, &uaddrlen) != 0)
1674 SetLastError(wsaErrno());
1676 else if (ws_sockaddr_u2ws(uaddr,uaddrlen,name,namelen) != 0)
1678 /* The buffer was too small */
1679 SetLastError(WSAEFAULT);
1685 ws_sockaddr_free(uaddr,name);
1690 SetLastError(WSAENOTSOCK);
1695 /***********************************************************************
1696 * getpeername (WINSOCK.5)
1698 INT16 WINAPI WINSOCK_getpeername16(SOCKET16 s, struct WS_sockaddr *name,
1701 INT namelen32 = *namelen16;
1702 INT retVal = WS_getpeername( s, name, &namelen32 );
1705 dump_sockaddr(name);
1708 *namelen16 = namelen32;
1709 return (INT16)retVal;
1712 /***********************************************************************
1713 * getsockname (WS2_32.6)
1715 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
1720 TRACE("socket: %04x, ptr %p, len %8x\n", s, name, *namelen);
1722 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1723 if( (name == NULL) || (namelen == NULL) )
1725 SetLastError( WSAEFAULT );
1726 return SOCKET_ERROR;
1729 fd = _get_sock_fd(s);
1734 struct sockaddr* uaddr;
1737 uaddr=ws_sockaddr_alloc(name,namelen,&uaddrlen);
1738 if (getsockname(fd, uaddr, &uaddrlen) != 0)
1740 SetLastError(wsaErrno());
1742 else if (ws_sockaddr_u2ws(uaddr,uaddrlen,name,namelen) != 0)
1744 /* The buffer was too small */
1745 SetLastError(WSAEFAULT);
1755 SetLastError(WSAENOTSOCK);
1760 /***********************************************************************
1761 * getsockname (WINSOCK.6)
1763 INT16 WINAPI WINSOCK_getsockname16(SOCKET16 s, struct WS_sockaddr *name,
1770 INT namelen32 = *namelen16;
1771 retVal = WS_getsockname( s, name, &namelen32 );
1772 *namelen16 = namelen32;
1775 dump_sockaddr(name);
1779 else retVal = SOCKET_ERROR;
1780 return (INT16)retVal;
1784 /***********************************************************************
1785 * getsockopt (WS2_32.7)
1787 INT WINAPI WS_getsockopt(SOCKET s, INT level,
1788 INT optname, char *optval, INT *optlen)
1792 TRACE("socket: %04x, level 0x%x, name 0x%x, ptr %8x, len %d\n", s, level,
1793 (int) optname, (int) optval, (int) *optlen);
1794 /* SO_OPENTYPE does not require a valid socket handle. */
1795 if (level == WS_SOL_SOCKET && optname == WS_SO_OPENTYPE)
1797 if (!optlen || *optlen < sizeof(int) || !optval)
1799 SetLastError(WSAEFAULT);
1800 return SOCKET_ERROR;
1802 *(int *)optval = (int)TlsGetValue( opentype_tls_index );
1803 *optlen = sizeof(int);
1804 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
1808 fd = _get_sock_fd(s);
1811 if (!convert_sockopt(&level, &optname)) {
1812 SetLastError(WSAENOPROTOOPT); /* Unknown option */
1814 if (getsockopt(fd, (int) level, optname, optval, optlen) == 0 )
1819 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1823 return SOCKET_ERROR;
1827 /***********************************************************************
1828 * getsockopt (WINSOCK.7)
1830 INT16 WINAPI WINSOCK_getsockopt16(SOCKET16 s, INT16 level,
1831 INT16 optname, char *optval, INT16 *optlen)
1836 if( optlen ) optlen32 = *optlen; else p = NULL;
1837 retVal = WS_getsockopt( s, (UINT16)level, optname, optval, p );
1838 if( optlen ) *optlen = optlen32;
1839 return (INT16)retVal;
1843 /***********************************************************************
1847 u_long WINAPI WS_htonl(u_long hostlong)
1849 return htonl(hostlong);
1853 /***********************************************************************
1857 u_short WINAPI WS_htons(u_short hostshort)
1859 return htons(hostshort);
1863 /***********************************************************************
1864 * inet_addr (WINSOCK.10)
1865 * inet_addr (WS2_32.11)
1867 u_long WINAPI WS_inet_addr(const char *cp)
1869 return inet_addr(cp);
1873 /***********************************************************************
1874 * ntohl (WINSOCK.14)
1877 u_long WINAPI WS_ntohl(u_long netlong)
1879 return ntohl(netlong);
1883 /***********************************************************************
1884 * ntohs (WINSOCK.15)
1887 u_short WINAPI WS_ntohs(u_short netshort)
1889 return ntohs(netshort);
1893 /***********************************************************************
1894 * inet_ntoa (WS2_32.12)
1896 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
1898 /* use "buffer for dummies" here because some applications have
1899 * propensity to decode addresses in ws_hostent structure without
1900 * saving them first...
1902 static char dbuffer[16]; /* Yes, 16: 4*3 digits + 3 '.' + 1 '\0' */
1904 char* s = inet_ntoa(*((struct in_addr*)&in));
1910 SetLastError(wsaErrno());
1914 /***********************************************************************
1915 * inet_ntoa (WINSOCK.11)
1917 SEGPTR WINAPI WINSOCK_inet_ntoa16(struct in_addr in)
1920 if (!(retVal = WS_inet_ntoa(*((struct WS_in_addr*)&in)))) return 0;
1921 if (!dbuffer_seg) dbuffer_seg = MapLS( retVal );
1926 /**********************************************************************
1927 * WSAIoctl (WS2_32.50)
1930 * FIXME: Only SIO_GET_INTERFACE_LIST option implemented.
1932 INT WINAPI WSAIoctl (SOCKET s,
1933 DWORD dwIoControlCode,
1936 LPVOID lpbOutBuffer,
1938 LPDWORD lpcbBytesReturned,
1939 LPWSAOVERLAPPED lpOverlapped,
1940 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
1942 int fd = _get_sock_fd(s);
1946 switch( dwIoControlCode )
1948 case SIO_GET_INTERFACE_LIST:
1950 INTERFACE_INFO* intArray = (INTERFACE_INFO*)lpbOutBuffer;
1952 struct ifreq ifInfo;
1956 TRACE ("-> SIO_GET_INTERFACE_LIST request\n");
1958 numInt = WSAIOCTL_GetInterfaceCount();
1961 ERR ("Unable to open /proc filesystem to determine number of network interfaces!\n");
1963 WSASetLastError(WSAEINVAL);
1964 return (SOCKET_ERROR);
1967 for (i=0; i<numInt; i++)
1969 if (!WSAIOCTL_GetInterfaceName(i, ifName))
1971 ERR ("Error parsing /proc filesystem!\n");
1973 WSASetLastError(WSAEINVAL);
1974 return (SOCKET_ERROR);
1977 ifInfo.ifr_addr.sa_family = AF_INET;
1980 strcpy (ifInfo.ifr_name, ifName);
1981 if (ioctl(fd, SIOCGIFADDR, &ifInfo) < 0)
1983 ERR ("Error obtaining IP address\n");
1985 WSASetLastError(WSAEINVAL);
1986 return (SOCKET_ERROR);
1990 struct WS_sockaddr_in *ipTemp = (struct WS_sockaddr_in *)&ifInfo.ifr_addr;
1992 intArray->iiAddress.AddressIn.sin_family = AF_INET;
1993 intArray->iiAddress.AddressIn.sin_port = ipTemp->sin_port;
1994 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr = ipTemp->sin_addr.S_un.S_addr;
1997 /* Broadcast Address */
1998 strcpy (ifInfo.ifr_name, ifName);
1999 if (ioctl(fd, SIOCGIFBRDADDR, &ifInfo) < 0)
2001 ERR ("Error obtaining Broadcast IP address\n");
2003 WSASetLastError(WSAEINVAL);
2004 return (SOCKET_ERROR);
2008 struct WS_sockaddr_in *ipTemp = (struct WS_sockaddr_in *)&ifInfo.ifr_broadaddr;
2010 intArray->iiBroadcastAddress.AddressIn.sin_family = AF_INET;
2011 intArray->iiBroadcastAddress.AddressIn.sin_port = ipTemp->sin_port;
2012 intArray->iiBroadcastAddress.AddressIn.sin_addr.WS_s_addr = ipTemp->sin_addr.S_un.S_addr;
2016 strcpy (ifInfo.ifr_name, ifName);
2017 if (ioctl(fd, SIOCGIFNETMASK, &ifInfo) < 0)
2019 ERR ("Error obtaining Subnet IP address\n");
2021 WSASetLastError(WSAEINVAL);
2022 return (SOCKET_ERROR);
2026 /* Trying to avoid some compile problems across platforms.
2027 (Linux, FreeBSD, Solaris...) */
2030 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
2031 intArray->iiNetmask.AddressIn.sin_port = 0;
2032 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr = 0;
2033 ERR ("Unable to determine Netmask on your platform!\n");
2035 struct WS_sockaddr_in *ipTemp = (struct WS_sockaddr_in *)&ifInfo.ifr_addr;
2037 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
2038 intArray->iiNetmask.AddressIn.sin_port = ipTemp->sin_port;
2039 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr = ipTemp->sin_addr.S_un.S_addr;
2042 struct WS_sockaddr_in *ipTemp = (struct WS_sockaddr_in *)&ifInfo.ifr_netmask;
2044 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
2045 intArray->iiNetmask.AddressIn.sin_port = ipTemp->sin_port;
2046 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr = ipTemp->sin_addr.S_un.S_addr;
2050 /* Socket Status Flags */
2051 strcpy(ifInfo.ifr_name, ifName);
2052 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
2054 ERR ("Error obtaining status flags for socket!\n");
2056 WSASetLastError(WSAEINVAL);
2057 return (SOCKET_ERROR);
2061 /* FIXME - Is this the right flag to use? */
2062 intArray->iiFlags = ifInfo.ifr_flags;
2064 intArray++; /* Prepare for another interface */
2067 /* Calculate the size of the array being returned */
2068 *lpcbBytesReturned = sizeof(INTERFACE_INFO) * numInt;
2074 WARN("\tunsupported WS_IOCTL cmd (%08lx)\n", dwIoControlCode);
2076 WSASetLastError(WSAEOPNOTSUPP);
2077 return (SOCKET_ERROR);
2081 /* Function executed with no errors */
2087 WSASetLastError(WSAENOTSOCK);
2088 return (SOCKET_ERROR);
2094 Helper function for WSAIoctl - Get count of the number of interfaces
2095 by parsing /proc filesystem.
2097 int WSAIOCTL_GetInterfaceCount(void)
2100 char buf[512]; /* Size doesn't matter, something big */
2104 /* Open /proc filesystem file for network devices */
2105 procfs = fopen(PROCFS_NETDEV_FILE, "r");
2108 /* If we can't open the file, return an error */
2112 /* Omit first two lines, they are only headers */
2113 fgets(buf, sizeof buf, procfs);
2114 fgets(buf, sizeof buf, procfs);
2116 while (fgets(buf, sizeof buf, procfs))
2118 /* Each line in the file represents a network interface */
2128 Helper function for WSAIoctl - Get name of device from interface number
2129 by parsing /proc filesystem.
2131 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName)
2134 char buf[512]; /* Size doesn't matter, something big */
2137 /* Open /proc filesystem file for network devices */
2138 procfs = fopen(PROCFS_NETDEV_FILE, "r");
2141 /* If we can't open the file, return an error */
2145 /* Omit first two lines, they are only headers */
2146 fgets(buf, sizeof(buf), procfs);
2147 fgets(buf, sizeof(buf), procfs);
2149 for (i=0; i<intNumber; i++)
2151 /* Skip the lines that don't interest us. */
2152 fgets(buf, sizeof(buf), procfs);
2154 fgets(buf, sizeof(buf), procfs); /* This is the line we want */
2157 /* Parse out the line, grabbing only the name of the device
2158 to the intName variable
2160 The Line comes in like this: (we only care about the device name)
2161 lo: 21970 377 0 0 0 0 0 0 21970 377 0 0 0 0 0 0
2164 while (isspace(buf[i])) /* Skip initial space(s) */
2171 if (isspace(buf[i]))
2176 if (buf[i] == ':') /* FIXME: Not sure if this block (alias detection) works properly */
2178 /* This interface could be an alias... */
2180 char *dotname = intName;
2181 *intName++ = buf[i++];
2183 while (isdigit(buf[i]))
2185 *intName++ = buf[i++];
2190 /* ... It wasn't, so back up */
2205 *intName++ = buf[i++];
2214 /***********************************************************************
2215 * ioctlsocket (WS2_32.10)
2217 int WINAPI WS_ioctlsocket(SOCKET s, long cmd, u_long *argp)
2219 int fd = _get_sock_fd(s);
2221 TRACE("socket %04x, cmd %08lx, ptr %8x\n", s, cmd, (unsigned) argp);
2234 if( _get_sock_mask(s) )
2236 /* AsyncSelect()'ed sockets are always nonblocking */
2241 SetLastError(WSAEINVAL);
2243 return SOCKET_ERROR;
2247 _enable_event(s, 0, FD_WINE_NONBLOCKING, 0);
2249 _enable_event(s, 0, 0, FD_WINE_NONBLOCKING);
2256 case WS__IOW('f',125,u_long):
2257 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
2258 SetLastError(WSAEINVAL);
2259 return SOCKET_ERROR;
2261 case SIOCGIFBRDADDR:
2262 case SIOCGIFNETMASK:
2264 /* These don't need any special handling. They are used by
2265 WsControl, and are here to suppress an unecessary warning. */
2270 /* Netscape tries hard to use bogus ioctl 0x667e */
2271 WARN("\tunknown WS_IOCTL cmd (%08lx)\n", cmd);
2273 if( ioctl(fd, newcmd, (char*)argp ) == 0 )
2278 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2281 return SOCKET_ERROR;
2284 /***********************************************************************
2285 * ioctlsocket (WINSOCK.12)
2287 INT16 WINAPI WINSOCK_ioctlsocket16(SOCKET16 s, LONG cmd, ULONG *argp)
2289 return (INT16)WS_ioctlsocket( s, cmd, argp );
2293 /***********************************************************************
2294 * listen (WS2_32.13)
2296 int WINAPI WS_listen(SOCKET s, int backlog)
2298 int fd = _get_sock_fd(s);
2300 TRACE("socket %04x, backlog %d\n", s, backlog);
2303 if (listen(fd, backlog) == 0)
2306 _enable_event(s, FD_ACCEPT,
2308 FD_CONNECT|FD_WINE_CONNECTED);
2311 SetLastError(wsaErrno());
2313 else SetLastError(WSAENOTSOCK);
2314 return SOCKET_ERROR;
2317 /***********************************************************************
2318 * listen (WINSOCK.13)
2320 INT16 WINAPI WINSOCK_listen16(SOCKET16 s, INT16 backlog)
2322 return (INT16)WS_listen( s, backlog );
2326 /***********************************************************************
2329 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
2331 DWORD n, dwFlags = flags;
2337 if ( WSARecvFrom (s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
2338 return SOCKET_ERROR;
2343 /***********************************************************************
2346 INT16 WINAPI WINSOCK_recv16(SOCKET16 s, char *buf, INT16 len, INT16 flags)
2348 return (INT16)WS_recv( s, buf, len, flags );
2352 /***********************************************************************
2353 * recvfrom (WS2_32.17)
2355 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
2356 struct WS_sockaddr *from, int *fromlen)
2358 DWORD n, dwFlags = flags;
2364 if ( WSARecvFrom (s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL) == SOCKET_ERROR )
2365 return SOCKET_ERROR;
2370 /***********************************************************************
2371 * recvfrom (WINSOCK.17)
2373 INT16 WINAPI WINSOCK_recvfrom16(SOCKET16 s, char *buf, INT16 len, INT16 flags,
2374 struct WS_sockaddr *from, INT16 *fromlen16)
2377 INT *p = &fromlen32;
2380 if( fromlen16 ) fromlen32 = *fromlen16; else p = NULL;
2381 retVal = WS_recvfrom( s, buf, len, flags, from, p );
2382 if( fromlen16 ) *fromlen16 = fromlen32;
2383 return (INT16)retVal;
2386 /***********************************************************************
2389 static int __ws_select(BOOL b32,
2390 void *ws_readfds, void *ws_writefds, void *ws_exceptfds,
2391 const struct WS_timeval *ws_timeout)
2394 fd_set readfds, writefds, exceptfds;
2395 fd_set *p_read, *p_write, *p_except;
2396 int readfd[FD_SETSIZE], writefd[FD_SETSIZE], exceptfd[FD_SETSIZE];
2397 struct timeval timeout, *timeoutaddr = NULL;
2399 TRACE("read %p, write %p, excp %p timeout %p\n",
2400 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
2402 p_read = fd_set_import(&readfds, ws_readfds, &highfd, readfd, b32);
2403 p_write = fd_set_import(&writefds, ws_writefds, &highfd, writefd, b32);
2404 p_except = fd_set_import(&exceptfds, ws_exceptfds, &highfd, exceptfd, b32);
2407 timeoutaddr = &timeout;
2408 timeout.tv_sec=ws_timeout->tv_sec;
2409 timeout.tv_usec=ws_timeout->tv_usec;
2412 if( (highfd = select(highfd + 1, p_read, p_write, p_except, timeoutaddr)) > 0 )
2414 fd_set_export(&readfds, p_except, ws_readfds, readfd, b32);
2415 fd_set_export(&writefds, p_except, ws_writefds, writefd, b32);
2417 if (p_except && ws_exceptfds)
2419 #define wsfds16 ((ws_fd_set16*)ws_exceptfds)
2420 #define wsfds32 ((WS_fd_set*)ws_exceptfds)
2421 int i, j, count = (b32) ? wsfds32->fd_count : wsfds16->fd_count;
2423 for (i = j = 0; i < count; i++)
2425 int fd = exceptfd[i];
2426 if( fd >= 0 && FD_ISSET(fd, &exceptfds) )
2429 wsfds32->fd_array[j++] = wsfds32->fd_array[i];
2431 wsfds16->fd_array[j++] = wsfds16->fd_array[i];
2433 if( fd >= 0 ) close(fd);
2437 wsfds32->fd_count = j;
2439 wsfds16->fd_count = j;
2445 fd_set_unimport(ws_readfds, readfd, b32);
2446 fd_set_unimport(ws_writefds, writefd, b32);
2447 fd_set_unimport(ws_exceptfds, exceptfd, b32);
2448 if( ws_readfds ) ((WS_fd_set*)ws_readfds)->fd_count = 0;
2449 if( ws_writefds ) ((WS_fd_set*)ws_writefds)->fd_count = 0;
2450 if( ws_exceptfds ) ((WS_fd_set*)ws_exceptfds)->fd_count = 0;
2452 if( highfd == 0 ) return 0;
2453 SetLastError(wsaErrno());
2454 return SOCKET_ERROR;
2457 /***********************************************************************
2458 * select (WINSOCK.18)
2460 INT16 WINAPI WINSOCK_select16(INT16 nfds, ws_fd_set16 *ws_readfds,
2461 ws_fd_set16 *ws_writefds, ws_fd_set16 *ws_exceptfds,
2462 struct WS_timeval* timeout)
2464 return (INT16)__ws_select( FALSE, ws_readfds, ws_writefds, ws_exceptfds, timeout );
2467 /***********************************************************************
2468 * select (WS2_32.18)
2470 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
2471 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
2472 const struct WS_timeval* timeout)
2474 /* struct timeval is the same for both 32- and 16-bit code */
2475 return (INT)__ws_select( TRUE, ws_readfds, ws_writefds, ws_exceptfds, timeout );
2479 /***********************************************************************
2482 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
2488 wsabuf.buf = (char*) buf;
2490 if ( WSASendTo ( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
2491 return SOCKET_ERROR;
2496 /***********************************************************************
2497 * WSASend (WS2_32.72)
2499 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2500 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2501 LPWSAOVERLAPPED lpOverlapped,
2502 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2504 return WSASendTo ( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
2505 NULL, 0, lpOverlapped, lpCompletionRoutine );
2508 /***********************************************************************
2509 * WSASendTo (WS2_32.74)
2511 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2512 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2513 const struct WS_sockaddr *to, int tolen,
2514 LPWSAOVERLAPPED lpOverlapped,
2515 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2517 int i, n, fd, err = WSAENOTSOCK, flags, ret;
2518 struct iovec* iovec;
2519 struct ws2_async *wsa;
2522 TRACE ("socket %04x, wsabuf %p, nbufs %ld, flags %ld, to %p, tolen %d, ovl %p, func %p\n",
2523 s, lpBuffers, dwBufferCount, dwFlags,
2524 to, tolen, lpOverlapped, lpCompletionRoutine);
2526 fd = _get_sock_fd_type( s, GENERIC_WRITE, &type, &flags );
2527 TRACE ( "fd=%d, type=%d, flags=%x\n", fd, type, flags );
2531 err = WSAGetLastError ();
2535 iovec = HeapAlloc (GetProcessHeap(), 0, dwBufferCount * sizeof (struct iovec) );
2543 for ( i = 0; i < dwBufferCount; i++ )
2545 iovec[i].iov_base = lpBuffers[i].buf;
2546 iovec[i].iov_len = lpBuffers[i].len;
2549 if ( (lpOverlapped || lpCompletionRoutine) && flags & FD_FLAG_OVERLAPPED )
2551 wsa = WS2_make_async ( s, fd, ASYNC_TYPE_WRITE, iovec, dwBufferCount,
2552 &dwFlags, (struct WS_sockaddr*) to, &tolen,
2553 lpOverlapped, lpCompletionRoutine );
2560 if ( ( ret = register_new_async ( &wsa->async )) )
2562 err = NtStatusToWSAError ( ret );
2564 if ( !lpOverlapped )
2565 HeapFree ( GetProcessHeap(), 0, wsa->overlapped );
2566 HeapFree ( GetProcessHeap(), 0, wsa );
2570 /* Try immediate completion */
2571 if ( lpOverlapped && !NtResetEvent( lpOverlapped->hEvent, NULL ) )
2573 if ( WSAGetOverlappedResult ( (HANDLE) s, lpOverlapped,
2574 lpNumberOfBytesSent, FALSE, &dwFlags) )
2577 if ( (err = WSAGetLastError ()) != WSA_IO_INCOMPLETE )
2581 WSASetLastError ( WSA_IO_PENDING );
2582 return SOCKET_ERROR;
2585 if (_is_blocking(s))
2587 /* FIXME: exceptfds? */
2591 n = WS2_send ( fd, iovec, dwBufferCount, to, tolen, dwFlags );
2595 if ( err == WSAEWOULDBLOCK )
2596 _enable_event (s, FD_WRITE, 0, 0);
2600 TRACE(" -> %i bytes\n", n);
2601 *lpNumberOfBytesSent = n;
2603 HeapFree ( GetProcessHeap(), 0, iovec );
2608 HeapFree ( GetProcessHeap(), 0, iovec );
2614 WARN (" -> ERROR %d\n", err);
2615 WSASetLastError (err);
2616 return SOCKET_ERROR;
2619 /***********************************************************************
2622 INT16 WINAPI WINSOCK_send16(SOCKET16 s, char *buf, INT16 len, INT16 flags)
2624 return WS_send( s, buf, len, flags );
2627 /***********************************************************************
2628 * sendto (WS2_32.20)
2630 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
2631 const struct WS_sockaddr *to, int tolen)
2637 wsabuf.buf = (char*) buf;
2639 if ( WSASendTo (s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
2640 return SOCKET_ERROR;
2645 /***********************************************************************
2646 * sendto (WINSOCK.20)
2648 INT16 WINAPI WINSOCK_sendto16(SOCKET16 s, char *buf, INT16 len, INT16 flags,
2649 struct WS_sockaddr *to, INT16 tolen)
2651 return (INT16)WS_sendto( s, buf, len, flags, to, tolen );
2654 /***********************************************************************
2655 * setsockopt (WS2_32.21)
2657 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
2658 const char *optval, int optlen)
2662 TRACE("socket: %04x, level 0x%x, name 0x%x, ptr %8x, len %d\n", s, level,
2663 (int) optname, (int) optval, optlen);
2664 /* SO_OPENTYPE does not require a valid socket handle. */
2665 if (level == WS_SOL_SOCKET && optname == WS_SO_OPENTYPE)
2667 if (optlen < sizeof(int) || !optval)
2669 SetLastError(WSAEFAULT);
2670 return SOCKET_ERROR;
2672 TlsSetValue( opentype_tls_index, (LPVOID)*(int *)optval );
2673 TRACE("setting global SO_OPENTYPE to 0x%x\n", *(int *)optval );
2677 fd = _get_sock_fd(s);
2680 struct linger linger;
2683 /* Is a privileged and useless operation, so we don't. */
2684 if ((optname == WS_SO_DEBUG) && (level == WS_SOL_SOCKET)) {
2685 FIXME("(%d,SOL_SOCKET,SO_DEBUG,%p(%ld)) attempted (is privileged). Ignoring.\n",s,optval,*(DWORD*)optval);
2689 if(optname == WS_SO_DONTLINGER && level == WS_SOL_SOCKET) {
2690 /* This is unique to WinSock and takes special conversion */
2691 linger.l_onoff = *((int*)optval) ? 0: 1;
2692 linger.l_linger = 0;
2694 optval = (char*)&linger;
2695 optlen = sizeof(struct linger);
2698 if (!convert_sockopt(&level, &optname)) {
2699 SetLastError(WSAENOPROTOOPT);
2701 return SOCKET_ERROR;
2703 if (optname == SO_LINGER && optval) {
2704 /* yes, uses unsigned short in both win16/win32 */
2705 linger.l_onoff = ((UINT16*)optval)[0];
2706 linger.l_linger = ((UINT16*)optval)[1];
2707 /* FIXME: what is documented behavior if SO_LINGER optval
2709 optval = (char*)&linger;
2710 optlen = sizeof(struct linger);
2711 } else if (optlen < sizeof(int)){
2712 woptval= *((INT16 *) optval);
2713 optval= (char*) &woptval;
2717 if(optname == SO_RCVBUF && *(int*)optval < 2048) {
2718 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(int*)optval );
2723 if (setsockopt(fd, level, optname, optval, optlen) == 0)
2728 SetLastError(wsaErrno());
2731 else SetLastError(WSAENOTSOCK);
2732 return SOCKET_ERROR;
2735 /***********************************************************************
2736 * setsockopt (WINSOCK.21)
2738 INT16 WINAPI WINSOCK_setsockopt16(SOCKET16 s, INT16 level, INT16 optname,
2739 char *optval, INT16 optlen)
2741 if( !optval ) return SOCKET_ERROR;
2742 return (INT16)WS_setsockopt( s, (UINT16)level, optname, optval, optlen );
2746 /***********************************************************************
2747 * shutdown (WS2_32.22)
2749 int WINAPI WS_shutdown(SOCKET s, int how)
2751 int fd, fd0 = -1, fd1 = -1, flags, err = WSAENOTSOCK;
2753 unsigned int clear_flags = 0;
2755 fd = _get_sock_fd_type ( s, 0, &type, &flags );
2756 TRACE("socket %04x, how %i %d %d \n", s, how, type, flags );
2759 return SOCKET_ERROR;
2763 case 0: /* drop receives */
2764 clear_flags |= FD_READ;
2766 case 1: /* drop sends */
2767 clear_flags |= FD_WRITE;
2769 case 2: /* drop all */
2770 clear_flags |= FD_READ|FD_WRITE;
2772 clear_flags |= FD_WINE_CONNECTED|FD_WINE_LISTENING;
2775 if ( flags & FD_FLAG_OVERLAPPED ) {
2788 fd1 = _get_sock_fd ( s );
2793 err = WS2_register_async_shutdown ( s, fd0, ASYNC_TYPE_READ );
2802 err = WS2_register_async_shutdown ( s, fd1, ASYNC_TYPE_WRITE );
2810 else /* non-overlapped mode */
2812 if ( shutdown( fd, how ) )
2821 _enable_event( s, 0, 0, clear_flags );
2822 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
2826 _enable_event( s, 0, 0, clear_flags );
2827 WSASetLastError ( err );
2828 return SOCKET_ERROR;
2831 /***********************************************************************
2832 * shutdown (WINSOCK.22)
2834 INT16 WINAPI WINSOCK_shutdown16(SOCKET16 s, INT16 how)
2836 return (INT16)WS_shutdown( s, how );
2840 /***********************************************************************
2841 * socket (WS2_32.23)
2843 SOCKET WINAPI WS_socket(int af, int type, int protocol)
2845 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
2847 return WSASocketA ( af, type, protocol, NULL, 0,
2848 (TlsGetValue(opentype_tls_index) ? 0 : WSA_FLAG_OVERLAPPED) );
2851 /***********************************************************************
2852 * socket (WINSOCK.23)
2854 SOCKET16 WINAPI WINSOCK_socket16(INT16 af, INT16 type, INT16 protocol)
2856 return (SOCKET16)WS_socket( af, type, protocol );
2860 /* ----------------------------------- DNS services
2862 * IMPORTANT: 16-bit API structures have SEGPTR pointers inside them.
2863 * Also, we have to use wsock32 stubs to convert structures and
2864 * error codes from Unix to WSA, hence there is no direct mapping in
2865 * the relay32/wsock32.spec.
2869 /***********************************************************************
2870 * __ws_gethostbyaddr
2872 static WIN_hostent* __ws_gethostbyaddr(const char *addr, int len, int type, int dup_flag)
2874 WIN_hostent *retval = NULL;
2876 struct hostent* host;
2877 #if HAVE_LINUX_GETHOSTBYNAME_R_6
2880 struct hostent hostentry;
2883 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
2885 int res = gethostbyaddr_r(addr, len, type,
2886 &hostentry, extrabuf, ebufsize, &host, &locerr);
2887 if( res != ERANGE) break;
2889 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
2891 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
2893 EnterCriticalSection( &csWSgetXXXbyYYY );
2894 host = gethostbyaddr(addr, len, type);
2895 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
2899 if( WS_dup_he(host, dup_flag) )
2902 SetLastError(WSAENOBUFS);
2904 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
2905 HeapFree(GetProcessHeap(),0,extrabuf);
2907 LeaveCriticalSection( &csWSgetXXXbyYYY );
2912 /***********************************************************************
2913 * gethostbyaddr (WINSOCK.51)
2915 SEGPTR WINAPI WINSOCK_gethostbyaddr16(const char *addr, INT16 len, INT16 type)
2917 TRACE("ptr %p, len %d, type %d\n", addr, len, type);
2918 if (!__ws_gethostbyaddr( addr, len, type, WS_DUP_SEGPTR )) return 0;
2919 return he_buffer_seg;
2922 /***********************************************************************
2923 * gethostbyaddr (WS2_32.51)
2925 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len,
2928 TRACE("ptr %08x, len %d, type %d\n",
2929 (unsigned) addr, len, type);
2930 return __ws_gethostbyaddr(addr, len, type, WS_DUP_LINEAR);
2933 /***********************************************************************
2934 * __ws_gethostbyname
2936 static WIN_hostent * __ws_gethostbyname(const char *name, int dup_flag)
2938 WIN_hostent *retval = NULL;
2939 struct hostent* host;
2940 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
2943 struct hostent hostentry;
2944 int locerr = ENOBUFS;
2946 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
2948 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
2949 if( res != ERANGE) break;
2951 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
2953 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
2955 EnterCriticalSection( &csWSgetXXXbyYYY );
2956 host = gethostbyname(name);
2957 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
2961 if( WS_dup_he(host, dup_flag) )
2963 else SetLastError(WSAENOBUFS);
2965 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
2966 HeapFree(GetProcessHeap(),0,extrabuf);
2968 LeaveCriticalSection( &csWSgetXXXbyYYY );
2973 /***********************************************************************
2974 * gethostbyname (WINSOCK.52)
2976 SEGPTR WINAPI WINSOCK_gethostbyname16(const char *name)
2978 TRACE( "%s\n", debugstr_a(name) );
2979 if (!__ws_gethostbyname( name, WS_DUP_SEGPTR )) return 0;
2980 return he_buffer_seg;
2983 /***********************************************************************
2984 * gethostbyname (WS2_32.52)
2986 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
2988 TRACE( "%s\n", debugstr_a(name) );
2989 return __ws_gethostbyname( name, WS_DUP_LINEAR );
2993 /***********************************************************************
2994 * __ws_getprotobyname
2996 static WIN_protoent* __ws_getprotobyname(const char *name, int dup_flag)
2998 WIN_protoent* retval = NULL;
2999 #ifdef HAVE_GETPROTOBYNAME
3000 struct protoent* proto;
3001 EnterCriticalSection( &csWSgetXXXbyYYY );
3002 if( (proto = getprotobyname(name)) != NULL )
3004 if( WS_dup_pe(proto, dup_flag) )
3006 else SetLastError(WSAENOBUFS);
3009 MESSAGE("protocol %s not found; You might want to add "
3010 "this to /etc/protocols\n", debugstr_a(name) );
3011 SetLastError(WSANO_DATA);
3013 LeaveCriticalSection( &csWSgetXXXbyYYY );
3018 /***********************************************************************
3019 * getprotobyname (WINSOCK.53)
3021 SEGPTR WINAPI WINSOCK_getprotobyname16(const char *name)
3023 TRACE( "%s\n", debugstr_a(name) );
3024 if (!__ws_getprotobyname(name, WS_DUP_SEGPTR)) return 0;
3025 return pe_buffer_seg;
3028 /***********************************************************************
3029 * getprotobyname (WS2_32.53)
3031 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
3033 TRACE( "%s\n", debugstr_a(name) );
3034 return __ws_getprotobyname(name, WS_DUP_LINEAR);
3038 /***********************************************************************
3039 * __ws_getprotobynumber
3041 static WIN_protoent* __ws_getprotobynumber(int number, int dup_flag)
3043 WIN_protoent* retval = NULL;
3044 #ifdef HAVE_GETPROTOBYNUMBER
3045 struct protoent* proto;
3046 EnterCriticalSection( &csWSgetXXXbyYYY );
3047 if( (proto = getprotobynumber(number)) != NULL )
3049 if( WS_dup_pe(proto, dup_flag) )
3051 else SetLastError(WSAENOBUFS);
3054 MESSAGE("protocol number %d not found; You might want to add "
3055 "this to /etc/protocols\n", number );
3056 SetLastError(WSANO_DATA);
3058 LeaveCriticalSection( &csWSgetXXXbyYYY );
3063 /***********************************************************************
3064 * getprotobynumber (WINSOCK.54)
3066 SEGPTR WINAPI WINSOCK_getprotobynumber16(INT16 number)
3068 TRACE("%i\n", number);
3069 if (!__ws_getprotobynumber(number, WS_DUP_SEGPTR)) return 0;
3070 return pe_buffer_seg;
3073 /***********************************************************************
3074 * getprotobynumber (WS2_32.54)
3076 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
3078 TRACE("%i\n", number);
3079 return __ws_getprotobynumber(number, WS_DUP_LINEAR);
3083 /***********************************************************************
3084 * __ws_getservbyname
3086 static WIN_servent* __ws_getservbyname(const char *name, const char *proto, int dup_flag)
3088 WIN_servent* retval = NULL;
3089 struct servent* serv;
3090 int i = wsi_strtolo( name, proto );
3093 EnterCriticalSection( &csWSgetXXXbyYYY );
3094 serv = getservbyname(local_buffer,
3095 proto ? (local_buffer + i) : NULL);
3098 if( WS_dup_se(serv, dup_flag) )
3100 else SetLastError(WSAENOBUFS);
3103 MESSAGE("service %s protocol %s not found; You might want to add "
3104 "this to /etc/services\n", debugstr_a(local_buffer),
3105 proto ? debugstr_a(local_buffer+i):"*");
3106 SetLastError(WSANO_DATA);
3108 LeaveCriticalSection( &csWSgetXXXbyYYY );
3110 else SetLastError(WSAENOBUFS);
3114 /***********************************************************************
3115 * getservbyname (WINSOCK.55)
3117 SEGPTR WINAPI WINSOCK_getservbyname16(const char *name, const char *proto)
3119 TRACE( "%s, %s\n", debugstr_a(name), debugstr_a(proto) );
3120 if (!__ws_getservbyname(name, proto, WS_DUP_SEGPTR)) return 0;
3121 return se_buffer_seg;
3124 /***********************************************************************
3125 * getservbyname (WS2_32.55)
3127 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
3129 TRACE( "%s, %s\n", debugstr_a(name), debugstr_a(proto) );
3130 return __ws_getservbyname(name, proto, WS_DUP_LINEAR);
3134 /***********************************************************************
3135 * __ws_getservbyport
3137 static WIN_servent* __ws_getservbyport(int port, const char* proto, int dup_flag)
3139 WIN_servent* retval = NULL;
3140 #ifdef HAVE_GETSERVBYPORT
3141 struct servent* serv;
3142 if (!proto || wsi_strtolo( proto, NULL )) {
3143 EnterCriticalSection( &csWSgetXXXbyYYY );
3144 if( (serv = getservbyport(port, (proto) ? local_buffer : NULL)) != NULL ) {
3145 if( WS_dup_se(serv, dup_flag) )
3147 else SetLastError(WSAENOBUFS);
3150 MESSAGE("service on port %lu protocol %s not found; You might want to add "
3151 "this to /etc/services\n", (unsigned long)ntohl(port),
3152 proto ? debugstr_a(local_buffer) : "*");
3153 SetLastError(WSANO_DATA);
3155 LeaveCriticalSection( &csWSgetXXXbyYYY );
3157 else SetLastError(WSAENOBUFS);
3162 /***********************************************************************
3163 * getservbyport (WINSOCK.56)
3165 SEGPTR WINAPI WINSOCK_getservbyport16(INT16 port, const char *proto)
3167 TRACE("%d (i.e. port %d), %s\n", (int)port, (int)ntohl(port), debugstr_a(proto));
3168 if (!__ws_getservbyport(port, proto, WS_DUP_SEGPTR)) return 0;
3169 return se_buffer_seg;
3172 /***********************************************************************
3173 * getservbyport (WS2_32.56)
3175 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
3177 TRACE("%d (i.e. port %d), %s\n", (int)port, (int)ntohl(port), debugstr_a(proto));
3178 return __ws_getservbyport(port, proto, WS_DUP_LINEAR);
3182 /***********************************************************************
3183 * gethostname (WS2_32.57)
3185 int WINAPI WS_gethostname(char *name, int namelen)
3187 TRACE("name %p, len %d\n", name, namelen);
3189 if (gethostname(name, namelen) == 0)
3191 TRACE("<- '%s'\n", name);
3194 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
3195 TRACE("<- ERROR !\n");
3196 return SOCKET_ERROR;
3199 /***********************************************************************
3200 * gethostname (WINSOCK.57)
3202 INT16 WINAPI WINSOCK_gethostname16(char *name, INT16 namelen)
3204 return (INT16)WS_gethostname(name, namelen);
3208 /* ------------------------------------- Windows sockets extensions -- *
3210 * ------------------------------------------------------------------- */
3212 /***********************************************************************
3213 * WSAEnumNetworkEvents (WS2_32.36)
3215 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
3219 TRACE("%08x, hEvent %08x, lpEvent %08x\n", s, hEvent, (unsigned)lpEvent );
3221 SERVER_START_REQ( get_socket_event )
3224 req->service = TRUE;
3225 req->c_event = hEvent;
3226 wine_server_set_reply( req, lpEvent->iErrorCode, sizeof(lpEvent->iErrorCode) );
3227 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
3231 SetLastError(WSAEINVAL);
3232 return SOCKET_ERROR;
3235 /***********************************************************************
3236 * WSAEventSelect (WS2_32.39)
3238 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
3242 TRACE("%08x, hEvent %08x, event %08x\n", s, hEvent, (unsigned)lEvent );
3244 SERVER_START_REQ( set_socket_event )
3248 req->event = hEvent;
3251 ret = wine_server_call( req );
3255 SetLastError(WSAEINVAL);
3256 return SOCKET_ERROR;
3259 /**********************************************************************
3260 * WSAGetOverlappedResult (WS2_32.40)
3262 BOOL WINAPI WSAGetOverlappedResult ( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
3263 LPDWORD lpcbTransfer, BOOL fWait,
3268 TRACE ( "socket %d ovl %p trans %p, wait %d flags %p\n",
3269 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
3271 if ( !(lpOverlapped && lpOverlapped->hEvent) )
3273 ERR ( "Invalid pointer\n" );
3274 WSASetLastError (WSA_INVALID_PARAMETER);
3279 r = WaitForSingleObjectEx (lpOverlapped->hEvent, fWait ? INFINITE : 0, TRUE);
3280 } while (r == STATUS_USER_APC);
3283 *lpcbTransfer = lpOverlapped->InternalHigh;
3286 *lpdwFlags = lpOverlapped->Offset;
3288 if ( r == WAIT_OBJECT_0 )
3291 WSASetLastError ( lpOverlapped->Internal == STATUS_PENDING ?
3292 WSA_IO_INCOMPLETE : NtStatusToWSAError ( lpOverlapped->Internal ) );
3297 /***********************************************************************
3298 * WSAAsyncSelect (WS2_32.101)
3300 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
3304 TRACE("%x, hWnd %x, uMsg %08x, event %08lx\n", s, hWnd, uMsg, lEvent );
3306 SERVER_START_REQ( set_socket_event )
3313 ret = wine_server_call( req );
3317 SetLastError(WSAEINVAL);
3318 return SOCKET_ERROR;
3321 /***********************************************************************
3322 * WSAAsyncSelect (WINSOCK.101)
3324 INT16 WINAPI WSAAsyncSelect16(SOCKET16 s, HWND16 hWnd, UINT16 wMsg, LONG lEvent)
3326 return (INT16)WSAAsyncSelect( s, hWnd, wMsg, lEvent );
3329 /***********************************************************************
3330 * WSARecvEx (WINSOCK.1107)
3332 * See description for WSARecvEx()
3334 INT16 WINAPI WSARecvEx16(SOCKET16 s, char *buf, INT16 len, INT16 *flags)
3336 FIXME("(WSARecvEx16) partial packet return value not set \n");
3338 return WINSOCK_recv16(s, buf, len, *flags);
3342 /***********************************************************************
3343 * WSACreateEvent (WS2_32.31)
3346 WSAEVENT WINAPI WSACreateEvent(void)
3348 /* Create a manual-reset event, with initial state: unsignealed */
3351 return CreateEventA(NULL, TRUE, FALSE, NULL);
3354 /***********************************************************************
3355 * WSACloseEvent (WS2_32.29)
3358 BOOL WINAPI WSACloseEvent(WSAEVENT event)
3360 TRACE ("event=0x%x\n", event);
3362 return CloseHandle(event);
3365 /***********************************************************************
3366 * WSASocketA (WS2_32.78)
3369 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
3370 LPWSAPROTOCOL_INFOA lpProtocolInfo,
3371 GROUP g, DWORD dwFlags)
3376 FIXME: The "advanced" parameters of WSASocketA (lpProtocolInfo,
3377 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
3380 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%lx\n",
3381 af, type, protocol, lpProtocolInfo, g, dwFlags );
3383 /* hack for WSADuplicateSocket */
3384 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
3385 ret = lpProtocolInfo->dwCatalogEntryId;
3386 TRACE("\tgot duplicate %04x\n", ret);
3390 /* check the socket family */
3394 case WS_AF_IPX: af = AF_IPX;
3400 SetLastError(WSAEAFNOSUPPORT);
3401 return INVALID_SOCKET;
3404 /* check the socket type */
3407 case WS_SOCK_STREAM:
3417 SetLastError(WSAESOCKTNOSUPPORT);
3418 return INVALID_SOCKET;
3421 /* check the protocol type */
3422 if ( protocol < 0 ) /* don't support negative values */
3424 SetLastError(WSAEPROTONOSUPPORT);
3425 return INVALID_SOCKET;
3428 if ( af == AF_UNSPEC) /* did they not specify the address family? */
3432 if (type == SOCK_STREAM) { af = AF_INET; break; }
3434 if (type == SOCK_DGRAM) { af = AF_INET; break; }
3435 default: SetLastError(WSAEPROTOTYPE); return INVALID_SOCKET;
3438 SERVER_START_REQ( create_socket )
3442 req->protocol = protocol;
3443 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
3444 req->flags = dwFlags;
3445 req->inherit = TRUE;
3446 set_error( wine_server_call( req ) );
3447 ret = (SOCKET)reply->handle;
3452 TRACE("\tcreated %04x\n", ret );
3456 if (GetLastError() == WSAEACCES) /* raw socket denied */
3458 if (type == SOCK_RAW)
3459 MESSAGE("WARNING: Trying to create a socket of type SOCK_RAW, will fail unless running as root\n");
3461 MESSAGE("WS_SOCKET: not enough privileges to create socket, try running as root\n");
3462 SetLastError(WSAESOCKTNOSUPPORT);
3465 WARN("\t\tfailed!\n");
3466 return INVALID_SOCKET;
3470 /***********************************************************************
3471 * __WSAFDIsSet (WINSOCK.151)
3473 INT16 WINAPI __WSAFDIsSet16(SOCKET16 s, ws_fd_set16 *set)
3475 int i = set->fd_count;
3477 TRACE("(%d,%8lx(%i))\n", s,(unsigned long)set, i);
3480 if (set->fd_array[i] == s) return 1;
3484 /***********************************************************************
3485 * __WSAFDIsSet (WS2_32.151)
3487 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
3489 int i = set->fd_count;
3491 TRACE("(%d,%8lx(%i))\n", s,(unsigned long)set, i);
3494 if (set->fd_array[i] == s) return 1;
3498 /***********************************************************************
3499 * WSAIsBlocking (WINSOCK.114)
3500 * WSAIsBlocking (WS2_32.114)
3502 BOOL WINAPI WSAIsBlocking(void)
3504 /* By default WinSock should set all its sockets to non-blocking mode
3505 * and poll in PeekMessage loop when processing "blocking" ones. This
3506 * function is supposed to tell if the program is in this loop. Our
3507 * blocking calls are truly blocking so we always return FALSE.
3509 * Note: It is allowed to call this function without prior WSAStartup().
3516 /***********************************************************************
3517 * WSACancelBlockingCall (WINSOCK.113)
3518 * WSACancelBlockingCall (WS2_32.113)
3520 INT WINAPI WSACancelBlockingCall(void)
3527 /***********************************************************************
3528 * WSASetBlockingHook (WINSOCK.109)
3530 FARPROC16 WINAPI WSASetBlockingHook16(FARPROC16 lpBlockFunc)
3532 FARPROC16 prev = (FARPROC16)blocking_hook;
3533 blocking_hook = (FARPROC)lpBlockFunc;
3534 TRACE("hook %p\n", lpBlockFunc);
3539 /***********************************************************************
3540 * WSASetBlockingHook (WS2_32.109)
3542 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
3544 FARPROC prev = blocking_hook;
3545 blocking_hook = lpBlockFunc;
3546 TRACE("hook %p\n", lpBlockFunc);
3551 /***********************************************************************
3552 * WSAUnhookBlockingHook (WINSOCK.110)
3554 INT16 WINAPI WSAUnhookBlockingHook16(void)
3556 blocking_hook = NULL;
3561 /***********************************************************************
3562 * WSAUnhookBlockingHook (WS2_32.110)
3564 INT WINAPI WSAUnhookBlockingHook(void)
3566 blocking_hook = NULL;
3571 /* ----------------------------------- end of API stuff */
3573 /* ----------------------------------- helper functions -
3575 * TODO: Merge WS_dup_..() stuff into one function that
3576 * would operate with a generic structure containing internal
3577 * pointers (via a template of some kind).
3580 static int list_size(char** l, int item_size)
3585 j += (item_size) ? item_size : strlen(l[i]) + 1;
3586 j += (i + 1) * sizeof(char*); }
3590 static int list_dup(char** l_src, char* ref, char* base, int item_size)
3592 /* base is either either equal to ref or 0 or SEGPTR */
3595 char** l_to = (char**)ref;
3598 for(j=0;l_src[j];j++) ;
3599 p += (j + 1) * sizeof(char*);
3601 { l_to[i] = base + (p - ref);
3602 k = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
3603 memcpy(p, l_src[i], k); p += k; }
3610 static int hostent_size(struct hostent* p_he)
3614 { size = sizeof(struct hostent);
3615 size += strlen(p_he->h_name) + 1;
3616 size += list_size(p_he->h_aliases, 0);
3617 size += list_size(p_he->h_addr_list, p_he->h_length ); }
3621 /* duplicate hostent entry
3622 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
3623 * Dito for protoent and servent.
3625 static int WS_dup_he(struct hostent* p_he, int flag)
3627 /* Convert hostent structure into ws_hostent so that the data fits
3628 * into local_buffer. Internal pointers can be linear, SEGPTR, or
3629 * relative to local_buffer depending on "flag" value. Returns size
3630 * of the data copied.
3633 int size = hostent_size(p_he);
3636 char *p_name,*p_aliases,*p_addr,*p_base,*p;
3638 struct ws_hostent16 *p_to16;
3639 struct WS_hostent *p_to32;
3641 check_buffer_he(size);
3647 p_base = (flag & WS_DUP_SEGPTR) ? (char*)he_buffer_seg : he_buffer;
3648 p += (flag & WS_DUP_SEGPTR) ?
3649 sizeof(struct ws_hostent16) : sizeof(struct WS_hostent);
3651 strcpy(p, p_he->h_name); p += strlen(p) + 1;
3653 p += list_dup(p_he->h_aliases, p, p_base + (p - p_to), 0);
3655 list_dup(p_he->h_addr_list, p, p_base + (p - p_to), p_he->h_length);
3657 if (flag & WS_DUP_SEGPTR) /* Win16 */
3659 p_to16->h_addrtype = (INT16)p_he->h_addrtype;
3660 p_to16->h_length = (INT16)p_he->h_length;
3661 p_to16->h_name = (SEGPTR)(p_base + (p_name - p_to));
3662 p_to16->h_aliases = (SEGPTR)(p_base + (p_aliases - p_to));
3663 p_to16->h_addr_list = (SEGPTR)(p_base + (p_addr - p_to));
3664 size += (sizeof(struct ws_hostent16) - sizeof(struct hostent));
3668 p_to32->h_addrtype = p_he->h_addrtype;
3669 p_to32->h_length = p_he->h_length;
3670 p_to32->h_name = (p_base + (p_name - p_to));
3671 p_to32->h_aliases = (char **)(p_base + (p_aliases - p_to));
3672 p_to32->h_addr_list = (char **)(p_base + (p_addr - p_to));
3673 size += (sizeof(struct WS_hostent) - sizeof(struct hostent));
3679 /* ----- protoent */
3681 static int protoent_size(struct protoent* p_pe)
3685 { size = sizeof(struct protoent);
3686 size += strlen(p_pe->p_name) + 1;
3687 size += list_size(p_pe->p_aliases, 0); }
3691 static int WS_dup_pe(struct protoent* p_pe, int flag)
3693 int size = protoent_size(p_pe);
3697 struct ws_protoent16 *p_to16;
3698 struct WS_protoent *p_to32;
3699 char *p_name,*p_aliases,*p_base,*p;
3701 check_buffer_pe(size);
3706 p_base = (flag & WS_DUP_SEGPTR) ? (char*)pe_buffer_seg : pe_buffer;
3707 p += (flag & WS_DUP_SEGPTR) ?
3708 sizeof(struct ws_protoent16) : sizeof(struct WS_protoent);
3710 strcpy(p, p_pe->p_name); p += strlen(p) + 1;
3712 list_dup(p_pe->p_aliases, p, p_base + (p - p_to), 0);
3714 if (flag & WS_DUP_SEGPTR) /* Win16 */
3716 p_to16->p_proto = (INT16)p_pe->p_proto;
3717 p_to16->p_name = (SEGPTR)(p_base) + (p_name - p_to);
3718 p_to16->p_aliases = (SEGPTR)((p_base) + (p_aliases - p_to));
3719 size += (sizeof(struct ws_protoent16) - sizeof(struct protoent));
3723 p_to32->p_proto = p_pe->p_proto;
3724 p_to32->p_name = (p_base) + (p_name - p_to);
3725 p_to32->p_aliases = (char **)((p_base) + (p_aliases - p_to));
3726 size += (sizeof(struct WS_protoent) - sizeof(struct protoent));
3734 static int servent_size(struct servent* p_se)
3738 { size += sizeof(struct servent);
3739 size += strlen(p_se->s_proto) + strlen(p_se->s_name) + 2;
3740 size += list_size(p_se->s_aliases, 0); }
3744 static int WS_dup_se(struct servent* p_se, int flag)
3746 int size = servent_size(p_se);
3749 char *p_name,*p_aliases,*p_proto,*p_base,*p;
3751 struct ws_servent16 *p_to16;
3752 struct WS_servent *p_to32;
3754 check_buffer_se(size);
3759 p_base = (flag & WS_DUP_SEGPTR) ? (char*)se_buffer_seg : se_buffer;
3760 p += (flag & WS_DUP_SEGPTR) ?
3761 sizeof(struct ws_servent16) : sizeof(struct WS_servent);
3763 strcpy(p, p_se->s_name); p += strlen(p) + 1;
3765 strcpy(p, p_se->s_proto); p += strlen(p) + 1;
3767 list_dup(p_se->s_aliases, p, p_base + (p - p_to), 0);
3769 if (flag & WS_DUP_SEGPTR) /* Win16 */
3771 p_to16->s_port = (INT16)p_se->s_port;
3772 p_to16->s_name = (SEGPTR)(p_base + (p_name - p_to));
3773 p_to16->s_proto = (SEGPTR)(p_base + (p_proto - p_to));
3774 p_to16->s_aliases = (SEGPTR)(p_base + (p_aliases - p_to));
3775 size += (sizeof(struct ws_servent16) - sizeof(struct servent));
3779 p_to32->s_port = p_se->s_port;
3780 p_to32->s_name = (p_base + (p_name - p_to));
3781 p_to32->s_proto = (p_base + (p_proto - p_to));
3782 p_to32->s_aliases = (char **)(p_base + (p_aliases - p_to));
3783 size += (sizeof(struct WS_servent) - sizeof(struct servent));
3789 /* ----------------------------------- error handling */
3791 UINT16 wsaErrno(void)
3793 int loc_errno = errno;
3794 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
3798 case EINTR: return WSAEINTR;
3799 case EBADF: return WSAEBADF;
3801 case EACCES: return WSAEACCES;
3802 case EFAULT: return WSAEFAULT;
3803 case EINVAL: return WSAEINVAL;
3804 case EMFILE: return WSAEMFILE;
3805 case EWOULDBLOCK: return WSAEWOULDBLOCK;
3806 case EINPROGRESS: return WSAEINPROGRESS;
3807 case EALREADY: return WSAEALREADY;
3808 case ENOTSOCK: return WSAENOTSOCK;
3809 case EDESTADDRREQ: return WSAEDESTADDRREQ;
3810 case EMSGSIZE: return WSAEMSGSIZE;
3811 case EPROTOTYPE: return WSAEPROTOTYPE;
3812 case ENOPROTOOPT: return WSAENOPROTOOPT;
3813 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
3814 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
3815 case EOPNOTSUPP: return WSAEOPNOTSUPP;
3816 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
3817 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
3818 case EADDRINUSE: return WSAEADDRINUSE;
3819 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
3820 case ENETDOWN: return WSAENETDOWN;
3821 case ENETUNREACH: return WSAENETUNREACH;
3822 case ENETRESET: return WSAENETRESET;
3823 case ECONNABORTED: return WSAECONNABORTED;
3825 case ECONNRESET: return WSAECONNRESET;
3826 case ENOBUFS: return WSAENOBUFS;
3827 case EISCONN: return WSAEISCONN;
3828 case ENOTCONN: return WSAENOTCONN;
3829 case ESHUTDOWN: return WSAESHUTDOWN;
3830 case ETOOMANYREFS: return WSAETOOMANYREFS;
3831 case ETIMEDOUT: return WSAETIMEDOUT;
3832 case ECONNREFUSED: return WSAECONNREFUSED;
3833 case ELOOP: return WSAELOOP;
3834 case ENAMETOOLONG: return WSAENAMETOOLONG;
3835 case EHOSTDOWN: return WSAEHOSTDOWN;
3836 case EHOSTUNREACH: return WSAEHOSTUNREACH;
3837 case ENOTEMPTY: return WSAENOTEMPTY;
3839 case EPROCLIM: return WSAEPROCLIM;
3842 case EUSERS: return WSAEUSERS;
3845 case EDQUOT: return WSAEDQUOT;
3848 case ESTALE: return WSAESTALE;
3851 case EREMOTE: return WSAEREMOTE;
3854 /* just in case we ever get here and there are no problems */
3857 WARN("Unknown errno %d!\n", loc_errno);
3858 return WSAEOPNOTSUPP;
3862 UINT16 wsaHerrno(int loc_errno)
3865 WARN("h_errno %d.\n", loc_errno);
3869 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
3870 case TRY_AGAIN: return WSATRY_AGAIN;
3871 case NO_RECOVERY: return WSANO_RECOVERY;
3872 case NO_DATA: return WSANO_DATA;
3873 case ENOBUFS: return WSAENOBUFS;
3877 WARN("Unknown h_errno %d!\n", loc_errno);
3878 return WSAEOPNOTSUPP;
3883 /***********************************************************************
3884 * WSARecv (WS2_32.67)
3886 int WINAPI WSARecv (SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3887 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
3888 LPWSAOVERLAPPED lpOverlapped,
3889 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
3891 return WSARecvFrom (s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
3892 NULL, NULL, lpOverlapped, lpCompletionRoutine);
3895 /***********************************************************************
3896 * WSARecvFrom (WS2_32.69)
3898 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3899 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
3900 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
3901 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3904 int i, n, fd, err = WSAENOTSOCK, flags, ret;
3905 struct iovec* iovec;
3906 struct ws2_async *wsa;
3909 TRACE("socket %04x, wsabuf %p, nbufs %ld, flags %ld, from %p, fromlen %ld, ovl %p, func %p\n",
3910 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
3911 (lpFromlen ? *lpFromlen : -1L),
3912 lpOverlapped, lpCompletionRoutine);
3914 fd = _get_sock_fd_type( s, GENERIC_READ, &type, &flags );
3915 TRACE ( "fd=%d, type=%d, flags=%x\n", fd, type, flags );
3919 err = WSAGetLastError ();
3923 iovec = HeapAlloc ( GetProcessHeap(), 0, dwBufferCount * sizeof (struct iovec) );
3930 for (i = 0; i < dwBufferCount; i++)
3932 iovec[i].iov_base = lpBuffers[i].buf;
3933 iovec[i].iov_len = lpBuffers[i].len;
3936 if ( (lpOverlapped || lpCompletionRoutine) && flags & FD_FLAG_OVERLAPPED )
3938 wsa = WS2_make_async ( s, fd, ASYNC_TYPE_READ, iovec, dwBufferCount,
3939 lpFlags, lpFrom, lpFromlen,
3940 lpOverlapped, lpCompletionRoutine );
3948 if ( ( ret = register_new_async ( &wsa->async )) )
3950 err = NtStatusToWSAError ( ret );
3952 if ( !lpOverlapped )
3953 HeapFree ( GetProcessHeap(), 0, wsa->overlapped );
3954 HeapFree ( GetProcessHeap(), 0, wsa );
3958 /* Try immediate completion */
3959 if ( lpOverlapped && !NtResetEvent( lpOverlapped->hEvent, NULL ) )
3961 if ( WSAGetOverlappedResult ( (HANDLE) s, lpOverlapped,
3962 lpNumberOfBytesRecvd, FALSE, lpFlags) )
3965 if ( (err = WSAGetLastError ()) != WSA_IO_INCOMPLETE )
3969 WSASetLastError ( WSA_IO_PENDING );
3970 return SOCKET_ERROR;
3973 if ( _is_blocking(s) )
3976 /* FIXME: OOB and exceptfds? */
3980 n = WS2_recv ( fd, iovec, dwBufferCount, lpFrom, lpFromlen, lpFlags );
3987 TRACE(" -> %i bytes\n", n);
3988 *lpNumberOfBytesRecvd = n;
3990 HeapFree (GetProcessHeap(), 0, iovec);
3992 _enable_event(s, FD_READ, 0, 0);
3997 HeapFree (GetProcessHeap(), 0, iovec);
4003 WARN(" -> ERROR %d\n", err);
4004 WSASetLastError ( err );
4005 return SOCKET_ERROR;
4008 /***********************************************************************
4009 * WSCInstallProvider (WS2_32.88)
4011 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
4012 LPCWSTR lpszProviderDllPath,
4013 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
4014 DWORD dwNumberOfEntries,
4017 FIXME("(%s, %s, %p, %ld, %p): stub !\n", debugstr_guid(lpProviderId),
4018 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
4019 dwNumberOfEntries, lpErrno);
4025 /***********************************************************************
4026 * WSCDeinstallProvider (WS2_32.83)
4028 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
4030 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
4036 /***********************************************************************
4037 * WSAAccept (WS2_32.26)
4039 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
4040 LPCONDITIONPROC lpfnCondition, DWORD dwCallbackData)
4043 int ret = 0, size = 0;
4044 WSABUF CallerId, CallerData, CalleeId, CalleeData;
4045 /* QOS SQOS, GQOS; */
4048 SOCKADDR src_addr, dst_addr;
4050 TRACE("Socket %u, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
4051 s, addr, addrlen, lpfnCondition, dwCallbackData);
4054 size = sizeof(src_addr);
4055 cs = WS_accept(s, &src_addr, &size);
4057 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
4059 CallerId.buf = (char *)&src_addr;
4060 CallerId.len = sizeof(src_addr);
4062 CallerData.buf = NULL;
4063 CallerData.len = (ULONG)NULL;
4065 WS_getsockname(cs, &dst_addr, &size);
4067 CalleeId.buf = (char *)&dst_addr;
4068 CalleeId.len = sizeof(dst_addr);
4071 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
4072 &CalleeId, &CalleeData, &g, dwCallbackData);
4077 if (addr && addrlen)
4078 addr = memcpy(addr, &src_addr, (*addrlen > size) ? size : *addrlen );
4081 SERVER_START_REQ ( set_socket_deferred )
4085 if ( !wine_server_call_err ( req ) )
4087 SetLastError ( WSATRY_AGAIN );
4092 return SOCKET_ERROR;
4095 SetLastError(WSAECONNREFUSED);
4096 return SOCKET_ERROR;
4098 FIXME("Unknown return type from Condition function\n");
4099 SetLastError(WSAENOTSOCK);
4100 return SOCKET_ERROR;
4103 SetLastError(WSAENOTSOCK);
4104 return SOCKET_ERROR;
4107 /***********************************************************************
4108 * WSAEnumProtocolsA (WS2_32.37)
4110 int WINAPI WSAEnumProtocolsA(LPINT lpiProtocols, LPWSAPROTOCOL_INFOA lpProtocolBuffer, LPDWORD lpdwBufferLength)
4112 FIXME("(%p,%p,%p): stub\n", lpiProtocols,lpProtocolBuffer, lpdwBufferLength);
4116 /***********************************************************************
4117 * WSAEnumProtocolsW (WS2_32.38)
4119 int WINAPI WSAEnumProtocolsW(LPINT lpiProtocols, LPWSAPROTOCOL_INFOW lpProtocolBuffer, LPDWORD lpdwBufferLength)
4121 FIXME("(%p,%p,%p): stub\n", lpiProtocols,lpProtocolBuffer, lpdwBufferLength);
4125 /***********************************************************************
4126 * WSADuplicateSocketA (WS2_32.32)
4128 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
4132 TRACE("(%d,%lx,%p)\n", s, dwProcessId, lpProtocolInfo);
4133 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
4134 /* FIXME: WS_getsockopt(s, WS_SOL_SOCKET, SO_PROTOCOL_INFO, lpProtocolInfo, sizeof(*lpProtocolInfo)); */
4135 /* I don't know what the real Windoze does next, this is a hack */
4136 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
4137 * the target use the global duplicate, or we could copy a reference to us to the structure
4138 * and let the target duplicate it from us, but let's do it as simple as possible */
4139 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
4140 DuplicateHandle(GetCurrentProcess(), s,
4141 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
4142 0, FALSE, DUPLICATE_SAME_ACCESS);
4143 CloseHandle(hProcess);
4144 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */