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"
32 #include <sys/types.h>
36 #ifdef HAVE_SYS_IOCTL_H
37 # include <sys/ioctl.h>
39 #ifdef HAVE_SYS_FILIO_H
40 # include <sys/filio.h>
42 #ifdef HAVE_SYS_SOCKIO_H
43 # include <sys/sockio.h>
47 # include <sys/so_ioctl.h>
50 #ifdef HAVE_SYS_PARAM_H
51 # include <sys/param.h>
57 #ifdef HAVE_SYS_WAIT_H
58 # include <sys/wait.h>
63 #ifdef HAVE_SYS_SOCKET_H
64 #include <sys/socket.h>
66 #ifdef HAVE_NETINET_IN_H
67 # include <netinet/in.h>
69 #ifdef HAVE_NETINET_TCP_H
70 # include <netinet/tcp.h>
72 #ifdef HAVE_ARPA_INET_H
73 # include <arpa/inet.h>
78 #ifdef HAVE_SYS_ERRNO_H
79 #include <sys/errno.h>
88 #ifdef HAVE_ARPA_NAMESER_H
89 # include <arpa/nameser.h>
98 # include <netipx/ipx.h>
101 #ifdef HAVE_IPX_LINUX
102 # include <asm/types.h>
103 # include <linux/ipx.h>
107 #ifdef HAVE_SYS_POLL_H
108 # include <sys/poll.h>
110 #ifdef HAVE_SYS_TIME_H
111 # include <sys/time.h>
114 #define NONAMELESSUNION
115 #define NONAMELESSSTRUCT
120 #include "winerror.h"
121 #include "winsock2.h"
122 #include "ws2tcpip.h"
125 #include "iphlpapi.h"
127 #include "wine/server.h"
128 #include "wine/debug.h"
131 # define sipx_network sipx_addr.x_net
132 # define sipx_node sipx_addr.x_host.c_host
133 #endif /* __FreeBSD__ */
135 WINE_DEFAULT_DEBUG_CHANNEL(winsock);
137 /* critical section to protect some non-rentrant net function */
138 extern CRITICAL_SECTION csWSgetXXXbyYYY;
140 inline static const char *debugstr_sockaddr( const struct WS_sockaddr *a )
142 if (!a) return "(nil)";
143 return wine_dbg_sprintf("{ family %d, address %s, port %d }",
144 ((struct sockaddr_in *)a)->sin_family,
145 inet_ntoa(((struct sockaddr_in *)a)->sin_addr),
146 ntohs(((struct sockaddr_in *)a)->sin_port));
149 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
150 #define SOCKET2HANDLE(s) ((HANDLE)(s))
151 #define HANDLE2SOCKET(h) ((SOCKET)(h))
153 /****************************************************************
154 * Async IO declarations
155 ****************************************************************/
158 static DWORD ws2_async_get_count (const struct async_private *ovp);
159 static void CALLBACK ws2_async_call_completion (ULONG_PTR data);
160 static void ws2_async_cleanup ( struct async_private *ovp );
162 static struct async_ops ws2_async_ops =
165 ws2_async_call_completion,
169 static struct async_ops ws2_nocomp_async_ops =
172 NULL, /* call_completion */
176 typedef struct ws2_async
179 LPWSAOVERLAPPED user_overlapped;
180 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
183 struct WS_sockaddr *addr;
185 int val; /* for send operations */
186 int *ptr; /* for recv operations */
191 /****************************************************************/
193 /* ----------------------------------- internal data */
195 /* ws_... struct conversion flags */
197 typedef struct /* WSAAsyncSelect() control struct */
199 HANDLE service, event, sock;
205 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
206 #define WS_MAX_UDP_DATAGRAM 1024
207 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
209 static struct WS_hostent *he_buffer; /* typecast for Win32 ws_hostent */
210 static struct WS_servent *se_buffer; /* typecast for Win32 ws_servent */
211 static struct WS_protoent *pe_buffer; /* typecast for Win32 ws_protoent */
212 static INT num_startup; /* reference counter */
213 static FARPROC blocking_hook = WSA_DefaultBlockingHook;
215 /* function prototypes */
216 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
217 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
218 static struct WS_servent *WS_dup_se(const struct servent* p_se);
220 int WSAIOCTL_GetInterfaceCount(void);
221 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
224 UINT wsaHerrno(int errnr);
226 #define MAP_OPTION(opt) { WS_##opt, opt }
228 static const int ws_sock_map[][2] =
230 MAP_OPTION( SO_DEBUG ),
231 MAP_OPTION( SO_REUSEADDR ),
232 MAP_OPTION( SO_KEEPALIVE ),
233 MAP_OPTION( SO_DONTROUTE ),
234 MAP_OPTION( SO_BROADCAST ),
235 MAP_OPTION( SO_LINGER ),
236 MAP_OPTION( SO_OOBINLINE ),
237 MAP_OPTION( SO_SNDBUF ),
238 MAP_OPTION( SO_RCVBUF ),
239 MAP_OPTION( SO_ERROR ),
240 MAP_OPTION( SO_TYPE ),
242 MAP_OPTION( SO_RCVTIMEO ),
245 MAP_OPTION( SO_SNDTIMEO ),
250 static const int ws_tcp_map[][2] =
253 MAP_OPTION( TCP_NODELAY ),
258 static const int ws_ip_map[][2] =
260 MAP_OPTION( IP_MULTICAST_IF ),
261 MAP_OPTION( IP_MULTICAST_TTL ),
262 MAP_OPTION( IP_MULTICAST_LOOP ),
263 MAP_OPTION( IP_ADD_MEMBERSHIP ),
264 MAP_OPTION( IP_DROP_MEMBERSHIP ),
265 MAP_OPTION( IP_OPTIONS ),
267 MAP_OPTION( IP_HDRINCL ),
269 MAP_OPTION( IP_TOS ),
270 MAP_OPTION( IP_TTL ),
274 static DWORD opentype_tls_index = TLS_OUT_OF_INDEXES; /* TLS index for SO_OPENTYPE flag */
276 inline static DWORD NtStatusToWSAError ( const DWORD status )
278 /* We only need to cover the status codes set by server async request handling */
282 case STATUS_SUCCESS: wserr = 0; break;
283 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
284 case STATUS_INVALID_HANDLE: wserr = WSAENOTSOCK; break; /* WSAEBADF ? */
285 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
286 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
287 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
288 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
289 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
291 if ( status >= WSABASEERR && status <= WSABASEERR+1004 )
292 /* It is not a NT status code but a winsock error */
296 wserr = RtlNtStatusToDosError( status );
297 FIXME ( "Status code %08lx converted to DOS error code %lx\n", status, wserr );
303 /* set last error code from NT status without mapping WSA errors */
304 inline static unsigned int set_error( unsigned int err )
308 err = NtStatusToWSAError ( err );
314 inline static int get_sock_fd( SOCKET s, DWORD access, int *flags )
317 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, NULL, flags ) ))
322 inline static void release_sock_fd( SOCKET s, int fd )
324 wine_server_release_fd( SOCKET2HANDLE(s), fd );
327 static void _enable_event( HANDLE s, unsigned int event,
328 unsigned int sstate, unsigned int cstate )
330 SERVER_START_REQ( enable_socket_event )
334 req->sstate = sstate;
335 req->cstate = cstate;
336 wine_server_call( req );
341 static int _is_blocking(SOCKET s)
344 SERVER_START_REQ( get_socket_event )
346 req->handle = SOCKET2HANDLE(s);
347 req->service = FALSE;
349 wine_server_call( req );
350 ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
356 static unsigned int _get_sock_mask(SOCKET s)
359 SERVER_START_REQ( get_socket_event )
361 req->handle = SOCKET2HANDLE(s);
362 req->service = FALSE;
364 wine_server_call( req );
371 static void _sync_sock_state(SOCKET s)
373 /* do a dummy wineserver request in order to let
374 the wineserver run through its select loop once */
375 (void)_is_blocking(s);
378 static int _get_sock_error(SOCKET s, unsigned int bit)
380 int events[FD_MAX_EVENTS];
382 SERVER_START_REQ( get_socket_event )
384 req->handle = SOCKET2HANDLE(s);
385 req->service = FALSE;
387 wine_server_set_reply( req, events, sizeof(events) );
388 wine_server_call( req );
394 static void WINSOCK_DeleteIData(void)
396 /* delete scratch buffers */
398 if (he_buffer) HeapFree( GetProcessHeap(), 0, he_buffer );
399 if (se_buffer) HeapFree( GetProcessHeap(), 0, se_buffer );
400 if (pe_buffer) HeapFree( GetProcessHeap(), 0, pe_buffer );
407 /***********************************************************************
408 * DllMain (WS2_32.init)
410 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
412 TRACE("%p 0x%lx %p\n", hInstDLL, fdwReason, fImpLoad);
414 case DLL_PROCESS_ATTACH:
415 DisableThreadLibraryCalls(hInstDLL);
416 opentype_tls_index = TlsAlloc();
418 case DLL_PROCESS_DETACH:
419 TlsFree( opentype_tls_index );
420 WINSOCK_DeleteIData();
426 /***********************************************************************
429 * Converts socket flags from Windows format.
430 * Return 1 if converted, 0 if not (error).
432 static int convert_sockopt(INT *level, INT *optname)
439 for(i=0; ws_sock_map[i][0]; i++)
441 if( ws_sock_map[i][0] == *optname )
443 *optname = ws_sock_map[i][1];
447 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
450 *level = IPPROTO_TCP;
451 for(i=0; ws_tcp_map[i][0]; i++)
453 if ( ws_tcp_map[i][0] == *optname )
455 *optname = ws_tcp_map[i][1];
459 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
463 for(i=0; ws_ip_map[i][0]; i++)
465 if (ws_ip_map[i][0] == *optname )
467 *optname = ws_ip_map[i][1];
471 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
473 default: FIXME("Unimplemented or unknown socket level\n");
478 static inline BOOL is_timeout_option( int optname )
481 if (optname == SO_RCVTIMEO) return TRUE;
484 if (optname == SO_SNDTIMEO) return TRUE;
489 /* ----------------------------------- Per-thread info (or per-process?) */
491 static char *strdup_lower(const char *str)
494 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
498 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
501 else SetLastError(WSAENOBUFS);
505 static fd_set* fd_set_import( fd_set* fds, const WS_fd_set* wsfds, int access, int* highfd, int lfd[] )
507 /* translate Winsock fd set into local fd set */
513 for( i = 0; i < wsfds->fd_count; i++ )
515 int s = wsfds->fd_array[i];
516 int fd = get_sock_fd( s, access, NULL );
520 if( fd > *highfd ) *highfd = fd;
530 inline static int sock_error_p(int s)
532 unsigned int optval, optlen;
534 optlen = sizeof(optval);
535 getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
536 if (optval) WARN("\t[%i] error: %d\n", s, optval);
540 static int fd_set_export( const fd_set* fds, fd_set* exceptfds, WS_fd_set* wsfds, int lfd[] )
544 /* translate local fd set into Winsock fd set, adding
545 * errors to exceptfds (only if app requested it) */
549 int i, j, count = wsfds->fd_count;
551 for( i = 0, j = 0; i < count; i++ )
554 SOCKET s = wsfds->fd_array[i];
555 if (fd == -1) continue;
556 if( FD_ISSET(fd, fds) )
558 if ( exceptfds && sock_error_p(fd) )
560 FD_SET(fd, exceptfds);
563 else wsfds->fd_array[j++] = s;
565 release_sock_fd( s, fd );
572 static void fd_set_unimport( WS_fd_set* wsfds, int lfd[] )
578 for( i = 0; i < wsfds->fd_count; i++ )
579 if ( lfd[i] >= 0 ) release_sock_fd( wsfds->fd_array[i], lfd[i] );
584 /* utility: given an fd, will block until one of the events occurs */
585 static inline int do_block( int fd, int events )
596 /* ----------------------------------- API -----
598 * Init / cleanup / error checking.
601 /***********************************************************************
602 * WSAStartup (WS2_32.115)
604 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
606 TRACE("verReq=%x\n", wVersionRequested);
608 if (LOBYTE(wVersionRequested) < 1)
609 return WSAVERNOTSUPPORTED;
611 if (!lpWSAData) return WSAEINVAL;
615 /* that's the whole of the negotiation for now */
616 lpWSAData->wVersion = wVersionRequested;
617 /* return winsock information */
618 lpWSAData->wHighVersion = 0x0202;
619 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
620 strcpy(lpWSAData->szSystemStatus, "Running" );
621 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
622 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
623 /* don't do anything with lpWSAData->lpVendorInfo */
624 /* (some apps don't allocate the space for this field) */
626 TRACE("succeeded\n");
631 /***********************************************************************
632 * WSACleanup (WS2_32.116)
634 INT WINAPI WSACleanup(void)
638 if (--num_startup > 0) return 0;
639 WINSOCK_DeleteIData();
642 SetLastError(WSANOTINITIALISED);
647 /***********************************************************************
648 * WSAGetLastError (WINSOCK.111)
649 * WSAGetLastError (WS2_32.111)
651 INT WINAPI WSAGetLastError(void)
653 return GetLastError();
656 /***********************************************************************
657 * WSASetLastError (WS2_32.112)
659 void WINAPI WSASetLastError(INT iError) {
660 SetLastError(iError);
663 static struct WS_hostent *check_buffer_he(int size)
668 if (he_len >= size ) return he_buffer;
669 HeapFree( GetProcessHeap(), 0, he_buffer );
671 he_buffer = HeapAlloc( GetProcessHeap(), 0, (he_len = size) );
672 if (!he_buffer) SetLastError(WSAENOBUFS);
676 static struct WS_servent *check_buffer_se(int size)
681 if (se_len >= size ) return se_buffer;
682 HeapFree( GetProcessHeap(), 0, se_buffer );
684 se_buffer = HeapAlloc( GetProcessHeap(), 0, (se_len = size) );
685 if (!se_buffer) SetLastError(WSAENOBUFS);
689 static struct WS_protoent *check_buffer_pe(int size)
694 if (pe_len >= size ) return pe_buffer;
695 HeapFree( GetProcessHeap(), 0, pe_buffer );
697 pe_buffer = HeapAlloc( GetProcessHeap(), 0, (pe_len = size) );
698 if (!pe_buffer) SetLastError(WSAENOBUFS);
702 /* ----------------------------------- i/o APIs */
705 #define SUPPORTED_PF(pf) ((pf)==WS_AF_INET || (pf)== WS_AF_IPX)
707 #define SUPPORTED_PF(pf) ((pf)==WS_AF_INET)
711 /**********************************************************************/
713 /* Returns the converted address if successful, NULL if it was too small to
714 * start with. Note that the returned pointer may be the original pointer
715 * if no conversion is necessary.
717 static const struct sockaddr* ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen, int *uaddrlen)
719 switch (wsaddr->sa_family)
724 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
725 struct sockaddr_ipx* uipx;
727 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
730 *uaddrlen=sizeof(struct sockaddr_ipx);
731 uipx=malloc(*uaddrlen);
732 memset(&uipx,0,sizeof(uipx));
733 uipx->sipx_family=AF_IPX;
734 uipx->sipx_port=wsipx->sa_socket;
735 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
738 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
739 #ifdef IPX_FRAME_NONE
740 uipx->sipx_type=IPX_FRAME_NONE;
742 return (const struct sockaddr*)uipx;
747 if (wsaddrlen<sizeof(struct WS_sockaddr))
750 /* No conversion needed, just return the original address */
752 return (const struct sockaddr*)wsaddr;
757 /* Allocates a Unix sockaddr structure to receive the data */
758 inline struct sockaddr* ws_sockaddr_alloc(const struct WS_sockaddr* wsaddr, int* wsaddrlen, int* uaddrlen)
762 ERR( "WINE shouldn't pass a NULL wsaddr! Attempting to continue\n" );
764 /* This is not strictly the right thing to do. Hope it works however */
773 *uaddrlen=max(sizeof(struct sockaddr),*wsaddrlen);
775 return malloc(*uaddrlen);
778 /* Returns 0 if successful, -1 if the buffer is too small */
779 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, int uaddrlen, struct WS_sockaddr* wsaddr, int* wsaddrlen)
783 switch(uaddr->sa_family)
788 struct sockaddr_ipx* uipx=(struct sockaddr_ipx*)uaddr;
789 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
792 switch (*wsaddrlen) /* how much can we copy? */
797 wsipx->sa_socket=uipx->sipx_port;
801 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
809 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
815 wsipx->sa_family=WS_AF_IPX;
827 /* No conversion needed */
828 memcpy(wsaddr,uaddr,*wsaddrlen);
829 if (*wsaddrlen<uaddrlen) {
839 /* to be called to free the memory allocated by ws_sockaddr_ws2u or
842 inline void ws_sockaddr_free(const struct sockaddr* uaddr, const struct WS_sockaddr* wsaddr)
844 if (uaddr!=NULL && uaddr!=(const struct sockaddr*)wsaddr)
848 /**************************************************************************
849 * Functions for handling overlapped I/O
850 **************************************************************************/
852 static DWORD ws2_async_get_count (const struct async_private *ovp)
854 return ovp->iosb->Information;
857 static void ws2_async_cleanup ( struct async_private *ap )
859 struct ws2_async *as = (struct ws2_async*) ap;
861 TRACE ( "as: %p uovl %p ovl %p\n", as, as->user_overlapped, as->async.iosb );
862 if ( !as->user_overlapped )
865 /* FIXME: I don't think this is really used */
866 if ( as->overlapped->hEvent != INVALID_HANDLE_VALUE )
867 WSACloseEvent ( as->overlapped->hEvent );
869 HeapFree ( GetProcessHeap(), 0, as->async.iosb );
873 HeapFree ( GetProcessHeap(), 0, as->iovec );
875 HeapFree ( GetProcessHeap(), 0, as );
878 static void CALLBACK ws2_async_call_completion (ULONG_PTR data)
880 ws2_async* as = (ws2_async*) data;
882 TRACE ("data: %p\n", as);
884 as->completion_func ( NtStatusToWSAError (as->async.iosb->u.Status),
885 as->async.iosb->Information,
888 ws2_async_cleanup ( &as->async );
891 /***********************************************************************
892 * WS2_make_async (INTERNAL)
895 static void WS2_async_recv (async_private *as);
896 static void WS2_async_send (async_private *as);
898 inline static struct ws2_async*
899 WS2_make_async (SOCKET s, int fd, int type, struct iovec *iovec, DWORD dwBufferCount,
900 LPDWORD lpFlags, struct WS_sockaddr *addr,
901 LPINT addrlen, LPWSAOVERLAPPED lpOverlapped,
902 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
904 struct ws2_async *wsa = HeapAlloc ( GetProcessHeap(), 0, sizeof ( ws2_async ) );
906 TRACE ( "wsa %p\n", wsa );
911 wsa->async.ops = ( lpCompletionRoutine ? &ws2_async_ops : &ws2_nocomp_async_ops );
912 wsa->async.handle = (HANDLE) s;
914 wsa->async.type = type;
917 case ASYNC_TYPE_READ:
918 wsa->flags = *lpFlags;
919 wsa->async.func = WS2_async_recv;
920 wsa->addrlen.ptr = addrlen;
922 case ASYNC_TYPE_WRITE:
924 wsa->async.func = WS2_async_send;
925 wsa->addrlen.val = *addrlen;
928 ERR ("Invalid async type: %d\n", type);
930 wsa->user_overlapped = lpOverlapped;
931 wsa->completion_func = lpCompletionRoutine;
933 wsa->n_iovecs = dwBufferCount;
938 wsa->async.iosb = (IO_STATUS_BLOCK*)lpOverlapped;
939 wsa->async.event = ( lpCompletionRoutine ? INVALID_HANDLE_VALUE : lpOverlapped->hEvent );
943 wsa->async.iosb = HeapAlloc ( GetProcessHeap(), 0,
944 sizeof (IO_STATUS_BLOCK) );
945 if ( !wsa->async.iosb )
947 wsa->async.event = INVALID_HANDLE_VALUE;
950 wsa->async.iosb->Information = 0;
951 TRACE ( "wsa %p, ops %p, h %p, ev %p, fd %d, func %p, iosb %p, uov %p, cfunc %p\n",
952 wsa, wsa->async.ops, wsa->async.handle, wsa->async.event, wsa->async.fd, wsa->async.func,
953 wsa->async.iosb, wsa->user_overlapped, wsa->completion_func );
959 HeapFree ( GetProcessHeap(), 0, wsa );
963 /***********************************************************************
964 * WS2_recv (INTERNAL)
966 * Work horse for both synchronous and asynchronous recv() operations.
968 static int WS2_recv ( int fd, struct iovec* iov, int count,
969 struct WS_sockaddr *lpFrom, LPINT lpFromlen,
974 TRACE ( "fd %d, iovec %p, count %d addr %s, len %p, flags %lx\n",
975 fd, iov, count, debugstr_sockaddr(lpFrom), lpFromlen, *lpFlags);
981 hdr.msg_namelen = *lpFromlen;
982 hdr.msg_name = ws_sockaddr_alloc ( lpFrom, lpFromlen, &hdr.msg_namelen );
985 WSASetLastError ( WSAEFAULT );
994 hdr.msg_iovlen = count;
995 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
996 hdr.msg_accrights = NULL;
997 hdr.msg_accrightslen = 0;
999 hdr.msg_control = NULL;
1000 hdr.msg_controllen = 0;
1004 if ( (n = recvmsg (fd, &hdr, *lpFlags)) == -1 )
1006 TRACE ( "recvmsg error %d\n", errno);
1011 ws_sockaddr_u2ws ( hdr.msg_name, hdr.msg_namelen,
1012 lpFrom, lpFromlen ) != 0 )
1014 /* The from buffer was too small, but we read the data
1015 * anyway. Is that really bad?
1017 WSASetLastError ( WSAEFAULT );
1018 WARN ( "Address buffer too small\n" );
1023 ws_sockaddr_free ( hdr.msg_name, lpFrom );
1024 TRACE ("-> %d\n", n);
1028 /***********************************************************************
1029 * WS2_async_recv (INTERNAL)
1031 * Handler for overlapped recv() operations.
1033 static void WS2_async_recv ( async_private *as )
1035 ws2_async* wsa = (ws2_async*) as;
1038 TRACE ( "async %p\n", wsa );
1040 if ( wsa->async.iosb->u.Status != STATUS_PENDING )
1042 TRACE ( "status: %ld\n", wsa->async.iosb->u.Status );
1046 result = WS2_recv ( wsa->async.fd, wsa->iovec, wsa->n_iovecs,
1047 wsa->addr, wsa->addrlen.ptr, &wsa->flags );
1051 wsa->async.iosb->u.Status = STATUS_SUCCESS;
1052 wsa->async.iosb->Information = result;
1053 TRACE ( "received %d bytes\n", result );
1054 _enable_event ( wsa->async.handle, FD_READ, 0, 0 );
1059 if ( err == WSAEINTR || err == WSAEWOULDBLOCK ) /* errno: EINTR / EAGAIN */
1061 wsa->async.iosb->u.Status = STATUS_PENDING;
1062 _enable_event ( wsa->async.handle, FD_READ, 0, 0 );
1063 TRACE ( "still pending\n" );
1067 wsa->async.iosb->u.Status = err;
1068 TRACE ( "Error: %x\n", err );
1072 /***********************************************************************
1073 * WS2_send (INTERNAL)
1075 * Work horse for both synchronous and asynchronous send() operations.
1077 static int WS2_send ( int fd, struct iovec* iov, int count,
1078 const struct WS_sockaddr *to, INT tolen, DWORD dwFlags )
1082 TRACE ( "fd %d, iovec %p, count %d addr %s, len %d, flags %lx\n",
1083 fd, iov, count, debugstr_sockaddr(to), tolen, dwFlags);
1085 hdr.msg_name = NULL;
1089 hdr.msg_name = (struct sockaddr*) ws_sockaddr_ws2u ( to, tolen, &hdr.msg_namelen );
1090 if ( !hdr.msg_name )
1092 WSASetLastError ( WSAEFAULT );
1097 hdr.msg_namelen = 0;
1100 hdr.msg_iovlen = count;
1101 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1102 hdr.msg_accrights = NULL;
1103 hdr.msg_accrightslen = 0;
1105 hdr.msg_control = NULL;
1106 hdr.msg_controllen = 0;
1110 n = sendmsg (fd, &hdr, dwFlags);
1113 ws_sockaddr_free ( hdr.msg_name, to );
1117 /***********************************************************************
1118 * WS2_async_send (INTERNAL)
1120 * Handler for overlapped send() operations.
1122 static void WS2_async_send ( async_private *as )
1124 ws2_async* wsa = (ws2_async*) as;
1127 TRACE ( "async %p\n", wsa );
1129 if ( wsa->async.iosb->u.Status != STATUS_PENDING )
1131 TRACE ( "status: %ld\n", wsa->async.iosb->u.Status );
1135 result = WS2_send ( wsa->async.fd, wsa->iovec, wsa->n_iovecs,
1136 wsa->addr, wsa->addrlen.val, wsa->flags );
1140 wsa->async.iosb->u.Status = STATUS_SUCCESS;
1141 wsa->async.iosb->Information = result;
1142 TRACE ( "sent %d bytes\n", result );
1143 _enable_event ( wsa->async.handle, FD_WRITE, 0, 0 );
1148 if ( err == WSAEINTR )
1150 wsa->async.iosb->u.Status = STATUS_PENDING;
1151 _enable_event ( wsa->async.handle, FD_WRITE, 0, 0 );
1152 TRACE ( "still pending\n" );
1156 /* We set the status to a winsock error code and check for that
1157 later in NtStatusToWSAError () */
1158 wsa->async.iosb->u.Status = err;
1159 TRACE ( "Error: %x\n", err );
1163 /***********************************************************************
1164 * WS2_async_shutdown (INTERNAL)
1166 * Handler for shutdown() operations on overlapped sockets.
1168 static void WS2_async_shutdown ( async_private *as )
1170 ws2_async* wsa = (ws2_async*) as;
1173 TRACE ( "async %p %d\n", wsa, wsa->async.type );
1174 switch ( wsa->async.type )
1176 case ASYNC_TYPE_READ:
1177 err = shutdown ( wsa->async.fd, 0 );
1179 case ASYNC_TYPE_WRITE:
1180 err = shutdown ( wsa->async.fd, 1 );
1183 ERR ("invalid type: %d\n", wsa->async.type );
1187 wsa->async.iosb->u.Status = wsaErrno ();
1189 wsa->async.iosb->u.Status = STATUS_SUCCESS;
1192 /***********************************************************************
1193 * WS2_register_async_shutdown (INTERNAL)
1195 * Helper function for WS_shutdown() on overlapped sockets.
1197 static int WS2_register_async_shutdown ( SOCKET s, int fd, int type )
1199 struct ws2_async *wsa;
1200 int ret, err = WSAEFAULT;
1203 LPWSAOVERLAPPED ovl = HeapAlloc (GetProcessHeap(), 0, sizeof ( WSAOVERLAPPED ));
1205 TRACE ("s %d fd %d type %d\n", s, fd, type);
1209 ovl->hEvent = WSACreateEvent ();
1210 if ( ovl->hEvent == WSA_INVALID_EVENT )
1213 wsa = WS2_make_async ( s, fd, type, NULL, 0,
1214 &dwflags, NULL, &len, ovl, NULL );
1218 /* Hack: this will cause ws2_async_cleanup() to free the overlapped structure */
1219 wsa->user_overlapped = NULL;
1220 wsa->async.func = WS2_async_shutdown;
1221 if ( (ret = register_new_async ( &wsa->async )) )
1223 err = NtStatusToWSAError ( ret );
1226 /* Try immediate completion */
1227 while ( WaitForSingleObjectEx ( ovl->hEvent, 0, TRUE ) == STATUS_USER_APC );
1231 WSACloseEvent ( ovl->hEvent );
1233 HeapFree ( GetProcessHeap(), 0, ovl );
1238 /***********************************************************************
1241 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr,
1246 TRACE("socket %04x\n", s );
1247 if (_is_blocking(s))
1249 int fd = get_sock_fd( s, GENERIC_READ, NULL );
1250 if (fd == -1) return INVALID_SOCKET;
1252 do_block(fd, POLLIN);
1253 _sync_sock_state(s); /* let wineserver notice connection */
1254 release_sock_fd( s, fd );
1255 /* retrieve any error codes from it */
1256 SetLastError(_get_sock_error(s, FD_ACCEPT_BIT));
1257 /* FIXME: care about the error? */
1259 SERVER_START_REQ( accept_socket )
1261 req->lhandle = SOCKET2HANDLE(s);
1262 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
1263 req->inherit = TRUE;
1264 set_error( wine_server_call( req ) );
1265 as = HANDLE2SOCKET( reply->handle );
1270 if (addr) WS_getpeername(as, addr, addrlen32);
1273 return INVALID_SOCKET;
1276 /***********************************************************************
1279 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
1281 int fd = get_sock_fd( s, 0, NULL );
1282 int res = SOCKET_ERROR;
1284 TRACE("socket %04x, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1288 if (!name || !SUPPORTED_PF(name->sa_family))
1290 SetLastError(WSAEAFNOSUPPORT);
1294 const struct sockaddr* uaddr;
1297 uaddr=ws_sockaddr_ws2u(name,namelen,&uaddrlen);
1300 SetLastError(WSAEFAULT);
1305 /* The game GrandPrixLegends binds more than one time, but does
1306 * not do a SO_REUSEADDR - Stevens says this is ok */
1307 TRACE( "Setting WS_SO_REUSEADDR on socket before we bind it\n");
1308 WS_setsockopt( s, WS_SOL_SOCKET, WS_SO_REUSEADDR, (char*)&on, sizeof(on) );
1310 if (bind(fd, uaddr, uaddrlen) < 0)
1312 int loc_errno = errno;
1313 WARN("\tfailure - errno = %i\n", errno);
1318 SetLastError(WSAENOTSOCK);
1321 SetLastError(WSAEINVAL);
1324 SetLastError(wsaErrno());
1330 res=0; /* success */
1332 ws_sockaddr_free(uaddr,name);
1335 release_sock_fd( s, fd );
1340 /***********************************************************************
1341 * closesocket (WS2_32.3)
1343 int WINAPI WS_closesocket(SOCKET s)
1345 TRACE("socket %08x\n", s);
1346 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
1347 return SOCKET_ERROR;
1350 /***********************************************************************
1351 * connect (WS2_32.4)
1353 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
1355 int fd = get_sock_fd( s, GENERIC_READ, NULL );
1357 TRACE("socket %04x, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1361 const struct sockaddr* uaddr;
1364 uaddr=ws_sockaddr_ws2u(name,namelen,&uaddrlen);
1367 SetLastError(WSAEFAULT);
1373 rc=connect(fd, uaddr, uaddrlen);
1374 ws_sockaddr_free(uaddr,name);
1376 goto connect_success;
1379 if (errno == EINPROGRESS)
1381 /* tell wineserver that a connection is in progress */
1382 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1383 FD_CONNECT|FD_READ|FD_WRITE,
1384 FD_WINE_CONNECTED|FD_WINE_LISTENING);
1385 if (_is_blocking(s))
1389 do_block(fd, POLLIN | POLLOUT );
1390 _sync_sock_state(s); /* let wineserver notice connection */
1391 /* retrieve any error codes from it */
1392 result = _get_sock_error(s, FD_CONNECT_BIT);
1394 SetLastError(result);
1397 goto connect_success;
1402 SetLastError(WSAEWOULDBLOCK);
1407 SetLastError(wsaErrno());
1409 release_sock_fd( s, fd );
1411 return SOCKET_ERROR;
1414 release_sock_fd( s, fd );
1415 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1416 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
1417 FD_CONNECT|FD_WINE_LISTENING);
1421 /***********************************************************************
1422 * WSAConnect (WS2_32.30)
1424 int WINAPI WSAConnect ( SOCKET s, const struct WS_sockaddr* name, int namelen,
1425 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
1426 LPQOS lpSQOS, LPQOS lpGQOS )
1428 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
1429 FIXME ("unsupported parameters!\n");
1430 return WS_connect ( s, name, namelen );
1434 /***********************************************************************
1435 * getpeername (WS2_32.5)
1437 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
1442 TRACE("socket: %04x, ptr %p, len %8x\n", s, name, *namelen);
1444 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1445 if( (name == NULL) || (namelen == NULL) )
1447 SetLastError( WSAEFAULT );
1448 return SOCKET_ERROR;
1451 fd = get_sock_fd( s, 0, NULL );
1456 struct sockaddr* uaddr;
1459 uaddr=ws_sockaddr_alloc(name,namelen,&uaddrlen);
1460 if (getpeername(fd, uaddr, &uaddrlen) != 0)
1462 SetLastError(wsaErrno());
1464 else if (ws_sockaddr_u2ws(uaddr,uaddrlen,name,namelen) != 0)
1466 /* The buffer was too small */
1467 SetLastError(WSAEFAULT);
1473 ws_sockaddr_free(uaddr,name);
1474 release_sock_fd( s, fd );
1479 /***********************************************************************
1480 * getsockname (WS2_32.6)
1482 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
1487 TRACE("socket: %04x, ptr %p, len %8x\n", s, name, *namelen);
1489 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1490 if( (name == NULL) || (namelen == NULL) )
1492 SetLastError( WSAEFAULT );
1493 return SOCKET_ERROR;
1496 fd = get_sock_fd( s, 0, NULL );
1501 struct sockaddr* uaddr;
1504 uaddr=ws_sockaddr_alloc(name,namelen,&uaddrlen);
1505 if (getsockname(fd, uaddr, &uaddrlen) != 0)
1507 SetLastError(wsaErrno());
1509 else if (ws_sockaddr_u2ws(uaddr,uaddrlen,name,namelen) != 0)
1511 /* The buffer was too small */
1512 SetLastError(WSAEFAULT);
1518 release_sock_fd( s, fd );
1523 /***********************************************************************
1524 * getsockopt (WS2_32.7)
1526 INT WINAPI WS_getsockopt(SOCKET s, INT level,
1527 INT optname, char *optval, INT *optlen)
1531 TRACE("socket: %04x, level 0x%x, name 0x%x, ptr %8x, len %d\n", s, level,
1532 (int) optname, (int) optval, (int) *optlen);
1533 /* SO_OPENTYPE does not require a valid socket handle. */
1534 if (level == WS_SOL_SOCKET && optname == WS_SO_OPENTYPE)
1536 if (!optlen || *optlen < sizeof(int) || !optval)
1538 SetLastError(WSAEFAULT);
1539 return SOCKET_ERROR;
1541 *(int *)optval = (int)TlsGetValue( opentype_tls_index );
1542 *optlen = sizeof(int);
1543 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
1547 fd = get_sock_fd( s, 0, NULL );
1550 if (!convert_sockopt(&level, &optname)) {
1551 SetLastError(WSAENOPROTOOPT); /* Unknown option */
1553 if (getsockopt(fd, (int) level, optname, optval, optlen) == 0 )
1555 release_sock_fd( s, fd );
1558 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1560 release_sock_fd( s, fd );
1562 return SOCKET_ERROR;
1566 /***********************************************************************
1570 u_long WINAPI WS_htonl(u_long hostlong)
1572 return htonl(hostlong);
1576 /***********************************************************************
1580 u_short WINAPI WS_htons(u_short hostshort)
1582 return htons(hostshort);
1585 /***********************************************************************
1586 * WSAHtonl (WS2_32.46)
1588 int WINAPI WSAHtonl(SOCKET s, u_long hostlong, u_long *lpnetlong)
1591 return INVALID_SOCKET;
1594 /***********************************************************************
1595 * WSAHtons (WS2_32.47)
1597 int WINAPI WSAHtons(SOCKET s, u_short hostshort, u_short *lpnetshort)
1600 return INVALID_SOCKET;
1604 /***********************************************************************
1605 * inet_addr (WINSOCK.10)
1606 * inet_addr (WS2_32.11)
1608 u_long WINAPI WS_inet_addr(const char *cp)
1610 return inet_addr(cp);
1614 /***********************************************************************
1615 * ntohl (WINSOCK.14)
1618 u_long WINAPI WS_ntohl(u_long netlong)
1620 return ntohl(netlong);
1624 /***********************************************************************
1625 * ntohs (WINSOCK.15)
1628 u_short WINAPI WS_ntohs(u_short netshort)
1630 return ntohs(netshort);
1634 /***********************************************************************
1635 * inet_ntoa (WS2_32.12)
1637 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
1639 /* use "buffer for dummies" here because some applications have
1640 * propensity to decode addresses in ws_hostent structure without
1641 * saving them first...
1643 static char dbuffer[16]; /* Yes, 16: 4*3 digits + 3 '.' + 1 '\0' */
1645 char* s = inet_ntoa(*((struct in_addr*)&in));
1651 SetLastError(wsaErrno());
1655 /**********************************************************************
1656 * WSAIoctl (WS2_32.50)
1659 * FIXME: Only SIO_GET_INTERFACE_LIST option implemented.
1661 INT WINAPI WSAIoctl (SOCKET s,
1662 DWORD dwIoControlCode,
1665 LPVOID lpbOutBuffer,
1667 LPDWORD lpcbBytesReturned,
1668 LPWSAOVERLAPPED lpOverlapped,
1669 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
1671 int fd = get_sock_fd( s, 0, NULL );
1673 if (fd == -1) return SOCKET_ERROR;
1675 switch( dwIoControlCode )
1677 case SIO_GET_INTERFACE_LIST:
1679 INTERFACE_INFO* intArray = (INTERFACE_INFO*)lpbOutBuffer;
1680 DWORD size, numInt, apiReturn;
1682 TRACE ("-> SIO_GET_INTERFACE_LIST request\n");
1686 release_sock_fd( s, fd );
1687 WSASetLastError(WSAEFAULT);
1688 return SOCKET_ERROR;
1690 if (!lpcbBytesReturned)
1692 release_sock_fd( s, fd );
1693 WSASetLastError(WSAEFAULT);
1694 return SOCKET_ERROR;
1697 apiReturn = GetAdaptersInfo(NULL, &size);
1698 if (apiReturn == ERROR_NO_DATA)
1702 else if (apiReturn == ERROR_BUFFER_OVERFLOW)
1704 PIP_ADAPTER_INFO table = (PIP_ADAPTER_INFO)HeapAlloc(GetProcessHeap(),0,size);
1708 if (GetAdaptersInfo(table, &size) == NO_ERROR)
1710 PIP_ADAPTER_INFO ptr;
1712 if (size > cbOutBuffer)
1714 HeapFree(GetProcessHeap(),0,table);
1715 release_sock_fd( s, fd );
1716 WSASetLastError(WSAEFAULT);
1717 return (SOCKET_ERROR);
1719 for (ptr = table, numInt = 0; ptr;
1720 ptr = ptr->Next, intArray++, numInt++)
1722 unsigned int addr, mask, bcast;
1723 struct ifreq ifInfo;
1725 /* Socket Status Flags */
1726 strncpy(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
1727 ifInfo.ifr_name[IFNAMSIZ-1] = '\0';
1728 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
1730 ERR ("Error obtaining status flags for socket!\n");
1731 HeapFree(GetProcessHeap(),0,table);
1732 release_sock_fd( s, fd );
1733 WSASetLastError(WSAEINVAL);
1734 return (SOCKET_ERROR);
1738 /* set flags; the values of IFF_* are not the same
1739 under Linux and Windows, therefore must generate
1741 intArray->iiFlags = 0;
1742 if (ifInfo.ifr_flags & IFF_BROADCAST)
1743 intArray->iiFlags |= WS_IFF_BROADCAST;
1744 #ifdef IFF_POINTOPOINT
1745 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
1746 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
1748 if (ifInfo.ifr_flags & IFF_LOOPBACK)
1749 intArray->iiFlags |= WS_IFF_LOOPBACK;
1750 if (ifInfo.ifr_flags & IFF_UP)
1751 intArray->iiFlags |= WS_IFF_UP;
1754 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
1755 mask = inet_addr(ptr->IpAddressList.IpMask.String);
1756 bcast = addr | (addr & !mask);
1757 intArray->iiAddress.AddressIn.sin_family = AF_INET;
1758 intArray->iiAddress.AddressIn.sin_port = 0;
1759 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
1761 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
1762 intArray->iiNetmask.AddressIn.sin_port = 0;
1763 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
1765 intArray->iiBroadcastAddress.AddressIn.sin_family =
1767 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
1768 intArray->iiBroadcastAddress.AddressIn.sin_addr.
1774 ERR ("Unable to get interface table!\n");
1775 release_sock_fd( s, fd );
1776 HeapFree(GetProcessHeap(),0,table);
1777 WSASetLastError(WSAEINVAL);
1778 return (SOCKET_ERROR);
1780 HeapFree(GetProcessHeap(),0,table);
1784 release_sock_fd( s, fd );
1785 WSASetLastError(WSAEINVAL);
1786 return (SOCKET_ERROR);
1791 ERR ("Unable to get interface table!\n");
1792 release_sock_fd( s, fd );
1793 WSASetLastError(WSAEINVAL);
1794 return (SOCKET_ERROR);
1796 /* Calculate the size of the array being returned */
1797 *lpcbBytesReturned = sizeof(INTERFACE_INFO) * numInt;
1802 WARN("\tunsupported WS_IOCTL cmd (%08lx)\n", dwIoControlCode);
1803 release_sock_fd( s, fd );
1804 WSASetLastError(WSAEOPNOTSUPP);
1805 return (SOCKET_ERROR);
1808 /* Function executed with no errors */
1809 release_sock_fd( s, fd );
1814 /***********************************************************************
1815 * ioctlsocket (WS2_32.10)
1817 int WINAPI WS_ioctlsocket(SOCKET s, long cmd, u_long *argp)
1822 TRACE("socket %04x, cmd %08lx, ptr %p\n", s, cmd, argp);
1832 if( _get_sock_mask(s) )
1834 /* AsyncSelect()'ed sockets are always nonblocking */
1835 if (*argp) return 0;
1836 SetLastError(WSAEINVAL);
1837 return SOCKET_ERROR;
1840 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
1842 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
1849 case WS__IOW('f',125,u_long):
1850 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
1851 SetLastError(WSAEINVAL);
1852 return SOCKET_ERROR;
1854 case SIOCGIFBRDADDR:
1855 case SIOCGIFNETMASK:
1857 /* These don't need any special handling. They are used by
1858 WsControl, and are here to suppress an unecessary warning. */
1862 /* Netscape tries hard to use bogus ioctl 0x667e */
1863 WARN("\tunknown WS_IOCTL cmd (%08lx)\n", cmd);
1867 fd = get_sock_fd( s, 0, NULL );
1870 if( ioctl(fd, newcmd, (char*)argp ) == 0 )
1872 release_sock_fd( s, fd );
1875 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1876 release_sock_fd( s, fd );
1878 return SOCKET_ERROR;
1881 /***********************************************************************
1882 * listen (WS2_32.13)
1884 int WINAPI WS_listen(SOCKET s, int backlog)
1886 int fd = get_sock_fd( s, GENERIC_READ, NULL );
1888 TRACE("socket %04x, backlog %d\n", s, backlog);
1891 if (listen(fd, backlog) == 0)
1893 release_sock_fd( s, fd );
1894 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
1896 FD_CONNECT|FD_WINE_CONNECTED);
1899 SetLastError(wsaErrno());
1900 release_sock_fd( s, fd );
1902 return SOCKET_ERROR;
1905 /***********************************************************************
1908 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
1910 DWORD n, dwFlags = flags;
1916 if ( WSARecvFrom (s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
1917 return SOCKET_ERROR;
1922 /***********************************************************************
1923 * recvfrom (WS2_32.17)
1925 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
1926 struct WS_sockaddr *from, int *fromlen)
1928 DWORD n, dwFlags = flags;
1934 if ( WSARecvFrom (s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL) == SOCKET_ERROR )
1935 return SOCKET_ERROR;
1940 /***********************************************************************
1941 * select (WS2_32.18)
1943 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
1944 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
1945 const struct WS_timeval* ws_timeout)
1948 fd_set readfds, writefds, exceptfds;
1949 fd_set *p_read, *p_write, *p_except;
1950 int readfd[FD_SETSIZE], writefd[FD_SETSIZE], exceptfd[FD_SETSIZE];
1951 struct timeval timeout, *timeoutaddr = NULL;
1953 TRACE("read %p, write %p, excp %p timeout %p\n",
1954 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
1956 p_read = fd_set_import(&readfds, ws_readfds, GENERIC_READ, &highfd, readfd);
1957 p_write = fd_set_import(&writefds, ws_writefds, GENERIC_WRITE, &highfd, writefd);
1958 p_except = fd_set_import(&exceptfds, ws_exceptfds, 0, &highfd, exceptfd);
1961 timeoutaddr = &timeout;
1962 timeout.tv_sec=ws_timeout->tv_sec;
1963 timeout.tv_usec=ws_timeout->tv_usec;
1966 if( (highfd = select(highfd + 1, p_read, p_write, p_except, timeoutaddr)) > 0 )
1968 fd_set_export(&readfds, p_except, ws_readfds, readfd);
1969 fd_set_export(&writefds, p_except, ws_writefds, writefd);
1971 if (p_except && ws_exceptfds)
1975 for (i = j = 0; i < ws_exceptfds->fd_count; i++)
1977 int fd = exceptfd[i];
1978 SOCKET s = ws_exceptfds->fd_array[i];
1979 if (fd == -1) continue;
1980 if (FD_ISSET(fd, &exceptfds)) ws_exceptfds->fd_array[j++] = s;
1981 release_sock_fd( s, fd );
1983 ws_exceptfds->fd_count = j;
1987 fd_set_unimport(ws_readfds, readfd);
1988 fd_set_unimport(ws_writefds, writefd);
1989 fd_set_unimport(ws_exceptfds, exceptfd);
1991 if( highfd == 0 ) return 0;
1992 SetLastError(wsaErrno());
1993 return SOCKET_ERROR;
1997 /***********************************************************************
2000 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
2006 wsabuf.buf = (char*) buf;
2008 if ( WSASendTo ( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
2009 return SOCKET_ERROR;
2014 /***********************************************************************
2015 * WSASend (WS2_32.72)
2017 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2018 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2019 LPWSAOVERLAPPED lpOverlapped,
2020 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2022 return WSASendTo ( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
2023 NULL, 0, lpOverlapped, lpCompletionRoutine );
2026 /***********************************************************************
2027 * WSASendDisconnect (WS2_32.73)
2029 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
2031 return WS_shutdown ( s, SD_SEND );
2035 /***********************************************************************
2036 * WSASendTo (WS2_32.74)
2038 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2039 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2040 const struct WS_sockaddr *to, int tolen,
2041 LPWSAOVERLAPPED lpOverlapped,
2042 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2044 int i, n, fd, err = WSAENOTSOCK, flags, ret;
2045 struct iovec* iovec;
2046 struct ws2_async *wsa;
2048 TRACE ("socket %04x, wsabuf %p, nbufs %ld, flags %ld, to %p, tolen %d, ovl %p, func %p\n",
2049 s, lpBuffers, dwBufferCount, dwFlags,
2050 to, tolen, lpOverlapped, lpCompletionRoutine);
2052 fd = get_sock_fd( s, GENERIC_WRITE, &flags );
2053 TRACE ( "fd=%d, flags=%x\n", fd, flags );
2055 if ( fd == -1 ) return SOCKET_ERROR;
2057 if (flags & FD_FLAG_SEND_SHUTDOWN)
2059 WSASetLastError ( WSAESHUTDOWN );
2063 if ( !lpNumberOfBytesSent )
2069 iovec = HeapAlloc (GetProcessHeap(), 0, dwBufferCount * sizeof (struct iovec) );
2077 for ( i = 0; i < dwBufferCount; i++ )
2079 iovec[i].iov_base = lpBuffers[i].buf;
2080 iovec[i].iov_len = lpBuffers[i].len;
2083 if ( (lpOverlapped || lpCompletionRoutine) && flags & FD_FLAG_OVERLAPPED )
2085 wsa = WS2_make_async ( s, fd, ASYNC_TYPE_WRITE, iovec, dwBufferCount,
2086 &dwFlags, (struct WS_sockaddr*) to, &tolen,
2087 lpOverlapped, lpCompletionRoutine );
2094 if ( ( ret = register_new_async ( &wsa->async )) )
2096 err = NtStatusToWSAError ( ret );
2098 if ( !lpOverlapped )
2099 HeapFree ( GetProcessHeap(), 0, wsa->async.iosb );
2100 HeapFree ( GetProcessHeap(), 0, wsa );
2104 /* Try immediate completion */
2105 if ( lpOverlapped && !NtResetEvent( lpOverlapped->hEvent, NULL ) )
2107 if ( WSAGetOverlappedResult ( s, lpOverlapped,
2108 lpNumberOfBytesSent, FALSE, &dwFlags) )
2111 if ( (err = WSAGetLastError ()) != WSA_IO_INCOMPLETE )
2115 WSASetLastError ( WSA_IO_PENDING );
2116 return SOCKET_ERROR;
2119 if (_is_blocking(s))
2121 /* FIXME: exceptfds? */
2122 do_block(fd, POLLOUT);
2125 n = WS2_send ( fd, iovec, dwBufferCount, to, tolen, dwFlags );
2129 if ( err == WSAEWOULDBLOCK )
2130 _enable_event (SOCKET2HANDLE(s), FD_WRITE, 0, 0);
2134 TRACE(" -> %i bytes\n", n);
2135 *lpNumberOfBytesSent = n;
2137 HeapFree ( GetProcessHeap(), 0, iovec );
2138 release_sock_fd( s, fd );
2142 HeapFree ( GetProcessHeap(), 0, iovec );
2145 release_sock_fd( s, fd );
2148 WARN (" -> ERROR %d\n", err);
2149 WSASetLastError (err);
2150 return SOCKET_ERROR;
2153 /***********************************************************************
2154 * sendto (WS2_32.20)
2156 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
2157 const struct WS_sockaddr *to, int tolen)
2163 wsabuf.buf = (char*) buf;
2165 if ( WSASendTo (s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
2166 return SOCKET_ERROR;
2171 /***********************************************************************
2172 * setsockopt (WS2_32.21)
2174 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
2175 const char *optval, int optlen)
2179 struct linger linger;
2180 struct timeval tval;
2182 TRACE("socket: %04x, level %d, name %d, ptr %p, len %d\n",
2183 s, level, optname, optval, optlen);
2185 /* SO_OPENTYPE does not require a valid socket handle. */
2186 if (level == WS_SOL_SOCKET && optname == WS_SO_OPENTYPE)
2188 if (optlen < sizeof(int) || !optval)
2190 SetLastError(WSAEFAULT);
2191 return SOCKET_ERROR;
2193 TlsSetValue( opentype_tls_index, (LPVOID)*(int *)optval );
2194 TRACE("setting global SO_OPENTYPE to 0x%x\n", *(int *)optval );
2198 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
2199 * socket. This will either not happen under windows or it is ignored in
2200 * windows (but it works in linux and therefor prevents the game to find
2201 * games outsite the current network) */
2202 if ( level==WS_SOL_SOCKET && optname==WS_SO_DONTROUTE )
2204 FIXME("Does windows ignore SO_DONTROUTE?\n");
2208 /* Is a privileged and useless operation, so we don't. */
2209 if ((optname == WS_SO_DEBUG) && (level == WS_SOL_SOCKET))
2211 FIXME("(%d,SOL_SOCKET,SO_DEBUG,%p(%ld)) attempted (is privileged). Ignoring.\n",s,optval,*(DWORD*)optval);
2215 if(optname == WS_SO_DONTLINGER && level == WS_SOL_SOCKET) {
2216 /* This is unique to WinSock and takes special conversion */
2217 linger.l_onoff = *((int*)optval) ? 0: 1;
2218 linger.l_linger = 0;
2220 optval = (char*)&linger;
2221 optlen = sizeof(struct linger);
2226 if (!convert_sockopt(&level, &optname)) {
2227 ERR("Invalid level (%d) or optname (%d)\n", level, optname);
2228 SetLastError(WSAENOPROTOOPT);
2229 return SOCKET_ERROR;
2231 if (optname == SO_LINGER && optval) {
2232 /* yes, uses unsigned short in both win16/win32 */
2233 linger.l_onoff = ((UINT16*)optval)[0];
2234 linger.l_linger = ((UINT16*)optval)[1];
2235 /* FIXME: what is documented behavior if SO_LINGER optval
2237 optval = (char*)&linger;
2238 optlen = sizeof(struct linger);
2240 else if (optval && optlen < sizeof(int))
2242 woptval= *((INT16 *) optval);
2243 optval= (char*) &woptval;
2246 if (level == SOL_SOCKET && is_timeout_option(optname))
2248 if (optlen == sizeof(UINT32)) {
2249 /* WinSock passes miliseconds instead of struct timeval */
2250 tval.tv_usec = *(PUINT32)optval % 1000;
2251 tval.tv_sec = *(PUINT32)optval / 1000;
2252 /* min of 500 milisec */
2253 if (tval.tv_sec == 0 && tval.tv_usec < 500) tval.tv_usec = 500;
2254 optlen = sizeof(struct timeval);
2255 optval = (char*)&tval;
2256 } else if (optlen == sizeof(struct timeval)) {
2257 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
2259 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
2263 if (level == SOL_SOCKET && optname == SO_RCVBUF && *(int*)optval < 2048)
2265 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(int*)optval );
2271 fd = get_sock_fd( s, 0, NULL );
2272 if (fd == -1) return SOCKET_ERROR;
2274 if (setsockopt(fd, level, optname, optval, optlen) == 0)
2276 release_sock_fd( s, fd );
2279 TRACE("Setting socket error, %d\n", wsaErrno());
2280 SetLastError(wsaErrno());
2281 release_sock_fd( s, fd );
2282 return SOCKET_ERROR;
2285 /***********************************************************************
2286 * shutdown (WS2_32.22)
2288 int WINAPI WS_shutdown(SOCKET s, int how)
2290 int fd, fd0 = -1, fd1 = -1, flags, err = WSAENOTSOCK;
2291 unsigned int clear_flags = 0;
2293 fd = get_sock_fd( s, 0, &flags );
2294 TRACE("socket %04x, how %i %x\n", s, how, flags );
2297 return SOCKET_ERROR;
2301 case 0: /* drop receives */
2302 clear_flags |= FD_READ;
2304 case 1: /* drop sends */
2305 clear_flags |= FD_WRITE;
2307 case 2: /* drop all */
2308 clear_flags |= FD_READ|FD_WRITE;
2310 clear_flags |= FD_WINE_LISTENING;
2313 if ( flags & FD_FLAG_OVERLAPPED ) {
2326 fd1 = get_sock_fd ( s, 0, NULL );
2332 err = WS2_register_async_shutdown ( s, fd0, ASYNC_TYPE_READ );
2335 release_sock_fd( s, fd0 );
2341 err = WS2_register_async_shutdown ( s, fd1, ASYNC_TYPE_WRITE );
2344 release_sock_fd( s, fd1 );
2349 else /* non-overlapped mode */
2351 if ( shutdown( fd, how ) )
2354 release_sock_fd( s, fd );
2357 release_sock_fd( s, fd );
2360 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
2361 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
2365 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
2366 WSASetLastError ( err );
2367 return SOCKET_ERROR;
2370 /***********************************************************************
2371 * socket (WS2_32.23)
2373 SOCKET WINAPI WS_socket(int af, int type, int protocol)
2375 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
2377 return WSASocketA ( af, type, protocol, NULL, 0,
2378 (TlsGetValue(opentype_tls_index) ? 0 : WSA_FLAG_OVERLAPPED) );
2382 /***********************************************************************
2383 * gethostbyaddr (WS2_32.51)
2385 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
2387 struct WS_hostent *retval = NULL;
2388 struct hostent* host;
2390 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
2393 struct hostent hostentry;
2396 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
2398 int res = gethostbyaddr_r(addr, len, type,
2399 &hostentry, extrabuf, ebufsize, &host, &locerr);
2400 if( res != ERANGE) break;
2402 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
2404 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
2406 EnterCriticalSection( &csWSgetXXXbyYYY );
2407 host = gethostbyaddr(addr, len, type);
2408 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
2410 if( host != NULL ) retval = WS_dup_he(host);
2411 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
2412 HeapFree(GetProcessHeap(),0,extrabuf);
2414 LeaveCriticalSection( &csWSgetXXXbyYYY );
2416 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
2420 /***********************************************************************
2421 * gethostbyname (WS2_32.52)
2423 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
2425 struct WS_hostent *retval = NULL;
2426 struct hostent* host;
2427 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
2430 struct hostent hostentry;
2431 int locerr = ENOBUFS;
2436 if( gethostname( buf, 100) == -1) {
2437 SetLastError( WSAENOBUFS); /* appropriate ? */
2441 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
2443 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
2445 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
2446 if( res != ERANGE) break;
2448 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
2450 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
2452 EnterCriticalSection( &csWSgetXXXbyYYY );
2453 host = gethostbyname(name);
2454 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
2456 if (host) retval = WS_dup_he(host);
2457 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
2458 HeapFree(GetProcessHeap(),0,extrabuf);
2460 LeaveCriticalSection( &csWSgetXXXbyYYY );
2462 TRACE( "%s ret %p\n", debugstr_a(name), retval );
2467 /***********************************************************************
2468 * getprotobyname (WS2_32.53)
2470 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
2472 struct WS_protoent* retval = NULL;
2473 #ifdef HAVE_GETPROTOBYNAME
2474 struct protoent* proto;
2475 EnterCriticalSection( &csWSgetXXXbyYYY );
2476 if( (proto = getprotobyname(name)) != NULL )
2478 retval = WS_dup_pe(proto);
2481 MESSAGE("protocol %s not found; You might want to add "
2482 "this to /etc/protocols\n", debugstr_a(name) );
2483 SetLastError(WSANO_DATA);
2485 LeaveCriticalSection( &csWSgetXXXbyYYY );
2487 TRACE( "%s ret %p\n", debugstr_a(name), retval );
2492 /***********************************************************************
2493 * getprotobynumber (WS2_32.54)
2495 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
2497 struct WS_protoent* retval = NULL;
2498 #ifdef HAVE_GETPROTOBYNUMBER
2499 struct protoent* proto;
2500 EnterCriticalSection( &csWSgetXXXbyYYY );
2501 if( (proto = getprotobynumber(number)) != NULL )
2503 retval = WS_dup_pe(proto);
2506 MESSAGE("protocol number %d not found; You might want to add "
2507 "this to /etc/protocols\n", number );
2508 SetLastError(WSANO_DATA);
2510 LeaveCriticalSection( &csWSgetXXXbyYYY );
2512 TRACE("%i ret %p\n", number, retval);
2517 /***********************************************************************
2518 * getservbyname (WS2_32.55)
2520 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
2522 struct WS_servent* retval = NULL;
2523 struct servent* serv;
2525 char *proto_str = NULL;
2527 if (!(name_str = strdup_lower(name))) return NULL;
2529 if (proto && *proto)
2531 if (!(proto_str = strdup_lower(proto)))
2533 HeapFree( GetProcessHeap(), 0, name_str );
2538 EnterCriticalSection( &csWSgetXXXbyYYY );
2539 serv = getservbyname(name_str, proto_str);
2542 retval = WS_dup_se(serv);
2544 else SetLastError(WSANO_DATA);
2545 LeaveCriticalSection( &csWSgetXXXbyYYY );
2546 if (proto_str) HeapFree( GetProcessHeap(), 0, proto_str );
2547 HeapFree( GetProcessHeap(), 0, name_str );
2548 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
2553 /***********************************************************************
2554 * getservbyport (WS2_32.56)
2556 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
2558 struct WS_servent* retval = NULL;
2559 #ifdef HAVE_GETSERVBYPORT
2560 struct servent* serv;
2561 char *proto_str = NULL;
2563 if (proto && *proto)
2565 if (!(proto_str = strdup_lower(proto))) return NULL;
2567 EnterCriticalSection( &csWSgetXXXbyYYY );
2568 if( (serv = getservbyport(port, proto_str)) != NULL ) {
2569 retval = WS_dup_se(serv);
2571 else SetLastError(WSANO_DATA);
2572 LeaveCriticalSection( &csWSgetXXXbyYYY );
2573 if (proto_str) HeapFree( GetProcessHeap(), 0, proto_str );
2575 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
2580 /***********************************************************************
2581 * gethostname (WS2_32.57)
2583 int WINAPI WS_gethostname(char *name, int namelen)
2585 TRACE("name %p, len %d\n", name, namelen);
2587 if (gethostname(name, namelen) == 0)
2589 TRACE("<- '%s'\n", name);
2592 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
2593 TRACE("<- ERROR !\n");
2594 return SOCKET_ERROR;
2598 /* ------------------------------------- Windows sockets extensions -- *
2600 * ------------------------------------------------------------------- */
2602 /***********************************************************************
2603 * WSAEnumNetworkEvents (WS2_32.36)
2605 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
2609 TRACE("%08x, hEvent %p, lpEvent %08x\n", s, hEvent, (unsigned)lpEvent );
2611 SERVER_START_REQ( get_socket_event )
2613 req->handle = SOCKET2HANDLE(s);
2614 req->service = TRUE;
2615 req->c_event = hEvent;
2616 wine_server_set_reply( req, lpEvent->iErrorCode, sizeof(lpEvent->iErrorCode) );
2617 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
2621 SetLastError(WSAEINVAL);
2622 return SOCKET_ERROR;
2625 /***********************************************************************
2626 * WSAEventSelect (WS2_32.39)
2628 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
2632 TRACE("%08x, hEvent %p, event %08x\n", s, hEvent, (unsigned)lEvent );
2634 SERVER_START_REQ( set_socket_event )
2636 req->handle = SOCKET2HANDLE(s);
2638 req->event = hEvent;
2641 ret = wine_server_call( req );
2645 SetLastError(WSAEINVAL);
2646 return SOCKET_ERROR;
2649 /**********************************************************************
2650 * WSAGetOverlappedResult (WS2_32.40)
2652 BOOL WINAPI WSAGetOverlappedResult ( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
2653 LPDWORD lpcbTransfer, BOOL fWait,
2658 TRACE ( "socket %d ovl %p trans %p, wait %d flags %p\n",
2659 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
2661 if ( !(lpOverlapped && lpOverlapped->hEvent) )
2663 ERR ( "Invalid pointer\n" );
2664 WSASetLastError (WSA_INVALID_PARAMETER);
2670 while ( WaitForSingleObjectEx (lpOverlapped->hEvent, INFINITE, TRUE) == STATUS_USER_APC );
2672 else if ( lpOverlapped->Internal == STATUS_PENDING )
2674 /* Wait in order to give APCs a chance to run. */
2675 /* This is cheating, so we must set the event again in case of success -
2676 it may be a non-manual reset event. */
2677 while ( (r = WaitForSingleObjectEx (lpOverlapped->hEvent, 0, TRUE)) == STATUS_USER_APC );
2678 if ( r == WAIT_OBJECT_0 )
2679 NtSetEvent ( lpOverlapped->hEvent, NULL );
2683 *lpcbTransfer = lpOverlapped->InternalHigh;
2686 *lpdwFlags = lpOverlapped->Offset;
2688 switch ( lpOverlapped->Internal )
2690 case STATUS_SUCCESS:
2692 case STATUS_PENDING:
2693 WSASetLastError ( WSA_IO_INCOMPLETE );
2694 if (fWait) ERR ("PENDING status after waiting!\n");
2697 WSASetLastError ( NtStatusToWSAError ( lpOverlapped->Internal ));
2703 /***********************************************************************
2704 * WSAAsyncSelect (WS2_32.101)
2706 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
2710 TRACE("%x, hWnd %p, uMsg %08x, event %08lx\n", s, hWnd, uMsg, lEvent );
2712 SERVER_START_REQ( set_socket_event )
2714 req->handle = SOCKET2HANDLE(s);
2719 ret = wine_server_call( req );
2723 SetLastError(WSAEINVAL);
2724 return SOCKET_ERROR;
2727 /***********************************************************************
2728 * WSACreateEvent (WS2_32.31)
2731 WSAEVENT WINAPI WSACreateEvent(void)
2733 /* Create a manual-reset event, with initial state: unsignealed */
2736 return CreateEventA(NULL, TRUE, FALSE, NULL);
2739 /***********************************************************************
2740 * WSACloseEvent (WS2_32.29)
2743 BOOL WINAPI WSACloseEvent(WSAEVENT event)
2745 TRACE ("event=%p\n", event);
2747 return CloseHandle(event);
2750 /***********************************************************************
2751 * WSASocketA (WS2_32.78)
2754 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
2755 LPWSAPROTOCOL_INFOA lpProtocolInfo,
2756 GROUP g, DWORD dwFlags)
2761 FIXME: The "advanced" parameters of WSASocketA (lpProtocolInfo,
2762 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
2765 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%lx\n",
2766 af, type, protocol, lpProtocolInfo, g, dwFlags );
2768 /* hack for WSADuplicateSocket */
2769 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
2770 ret = lpProtocolInfo->dwCatalogEntryId;
2771 TRACE("\tgot duplicate %04x\n", ret);
2775 /* check the socket family */
2779 case WS_AF_IPX: af = AF_IPX;
2785 SetLastError(WSAEAFNOSUPPORT);
2786 return INVALID_SOCKET;
2789 /* check the socket type */
2792 case WS_SOCK_STREAM:
2802 SetLastError(WSAESOCKTNOSUPPORT);
2803 return INVALID_SOCKET;
2806 /* check the protocol type */
2807 if ( protocol < 0 ) /* don't support negative values */
2809 SetLastError(WSAEPROTONOSUPPORT);
2810 return INVALID_SOCKET;
2813 if ( af == AF_UNSPEC) /* did they not specify the address family? */
2817 if (type == SOCK_STREAM) { af = AF_INET; break; }
2819 if (type == SOCK_DGRAM) { af = AF_INET; break; }
2820 default: SetLastError(WSAEPROTOTYPE); return INVALID_SOCKET;
2823 SERVER_START_REQ( create_socket )
2827 req->protocol = protocol;
2828 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
2829 req->flags = dwFlags;
2830 req->inherit = TRUE;
2831 set_error( wine_server_call( req ) );
2832 ret = HANDLE2SOCKET( reply->handle );
2837 TRACE("\tcreated %04x\n", ret );
2841 if (GetLastError() == WSAEACCES) /* raw socket denied */
2843 if (type == SOCK_RAW)
2844 MESSAGE("WARNING: Trying to create a socket of type SOCK_RAW, will fail unless running as root\n");
2846 MESSAGE("WS_SOCKET: not enough privileges to create socket, try running as root\n");
2847 SetLastError(WSAESOCKTNOSUPPORT);
2850 WARN("\t\tfailed!\n");
2851 return INVALID_SOCKET;
2854 /***********************************************************************
2855 * WSAJoinLeaf (WS2_32.58)
2858 SOCKET WINAPI WSAJoinLeaf(
2860 const struct WS_sockaddr *addr,
2862 LPWSABUF lpCallerData,
2863 LPWSABUF lpCalleeData,
2869 return INVALID_SOCKET;
2872 /***********************************************************************
2873 * __WSAFDIsSet (WS2_32.151)
2875 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
2877 int i = set->fd_count;
2879 TRACE("(%d,%8lx(%i))\n", s,(unsigned long)set, i);
2882 if (set->fd_array[i] == s) return 1;
2886 /***********************************************************************
2887 * WSAIsBlocking (WINSOCK.114)
2888 * WSAIsBlocking (WS2_32.114)
2890 BOOL WINAPI WSAIsBlocking(void)
2892 /* By default WinSock should set all its sockets to non-blocking mode
2893 * and poll in PeekMessage loop when processing "blocking" ones. This
2894 * function is supposed to tell if the program is in this loop. Our
2895 * blocking calls are truly blocking so we always return FALSE.
2897 * Note: It is allowed to call this function without prior WSAStartup().
2904 /***********************************************************************
2905 * WSACancelBlockingCall (WINSOCK.113)
2906 * WSACancelBlockingCall (WS2_32.113)
2908 INT WINAPI WSACancelBlockingCall(void)
2914 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
2916 FIXME("How was this called?\n");
2921 /***********************************************************************
2922 * WSASetBlockingHook (WS2_32.109)
2924 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
2926 FARPROC prev = blocking_hook;
2927 blocking_hook = lpBlockFunc;
2928 TRACE("hook %p\n", lpBlockFunc);
2933 /***********************************************************************
2934 * WSAUnhookBlockingHook (WS2_32.110)
2936 INT WINAPI WSAUnhookBlockingHook(void)
2938 blocking_hook = WSA_DefaultBlockingHook;
2943 /* ----------------------------------- end of API stuff */
2945 /* ----------------------------------- helper functions -
2947 * TODO: Merge WS_dup_..() stuff into one function that
2948 * would operate with a generic structure containing internal
2949 * pointers (via a template of some kind).
2952 static int list_size(char** l, int item_size)
2957 j += (item_size) ? item_size : strlen(l[i]) + 1;
2958 j += (i + 1) * sizeof(char*); }
2962 static int list_dup(char** l_src, char** l_to, int item_size)
2967 for (i = 0; l_src[i]; i++) ;
2968 p = (char *)(l_to + i + 1);
2969 for (i = 0; l_src[i]; i++)
2971 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
2972 memcpy(p, l_src[i], count);
2977 return (p - (char *)l_to);
2982 /* duplicate hostent entry
2983 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
2984 * Dito for protoent and servent.
2986 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
2989 struct WS_hostent *p_to;
2991 int size = (sizeof(*p_he) +
2992 strlen(p_he->h_name) + 1 +
2993 list_size(p_he->h_aliases, 0) +
2994 list_size(p_he->h_addr_list, p_he->h_length));
2996 if (!(p_to = check_buffer_he(size))) return NULL;
2997 p_to->h_addrtype = p_he->h_addrtype;
2998 p_to->h_length = p_he->h_length;
3000 p = (char *)(p_to + 1);
3002 strcpy(p, p_he->h_name);
3005 p_to->h_aliases = (char **)p;
3006 p += list_dup(p_he->h_aliases, p_to->h_aliases, 0);
3008 p_to->h_addr_list = (char **)p;
3009 list_dup(p_he->h_addr_list, p_to->h_addr_list, p_he->h_length);
3013 /* ----- protoent */
3015 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
3018 struct WS_protoent *p_to;
3020 int size = (sizeof(*p_pe) +
3021 strlen(p_pe->p_name) + 1 +
3022 list_size(p_pe->p_aliases, 0));
3024 if (!(p_to = check_buffer_pe(size))) return NULL;
3025 p_to->p_proto = p_pe->p_proto;
3027 p = (char *)(p_to + 1);
3029 strcpy(p, p_pe->p_name);
3032 p_to->p_aliases = (char **)p;
3033 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
3039 static struct WS_servent *WS_dup_se(const struct servent* p_se)
3042 struct WS_servent *p_to;
3044 int size = (sizeof(*p_se) +
3045 strlen(p_se->s_proto) + 1 +
3046 strlen(p_se->s_name) + 1 +
3047 list_size(p_se->s_aliases, 0));
3049 if (!(p_to = check_buffer_se(size))) return NULL;
3050 p_to->s_port = p_se->s_port;
3052 p = (char *)(p_to + 1);
3054 strcpy(p, p_se->s_name);
3058 strcpy(p, p_se->s_proto);
3061 p_to->s_aliases = (char **)p;
3062 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
3066 /* ----------------------------------- error handling */
3070 int loc_errno = errno;
3071 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
3075 case EINTR: return WSAEINTR;
3076 case EBADF: return WSAEBADF;
3078 case EACCES: return WSAEACCES;
3079 case EFAULT: return WSAEFAULT;
3080 case EINVAL: return WSAEINVAL;
3081 case EMFILE: return WSAEMFILE;
3082 case EWOULDBLOCK: return WSAEWOULDBLOCK;
3083 case EINPROGRESS: return WSAEINPROGRESS;
3084 case EALREADY: return WSAEALREADY;
3085 case ENOTSOCK: return WSAENOTSOCK;
3086 case EDESTADDRREQ: return WSAEDESTADDRREQ;
3087 case EMSGSIZE: return WSAEMSGSIZE;
3088 case EPROTOTYPE: return WSAEPROTOTYPE;
3089 case ENOPROTOOPT: return WSAENOPROTOOPT;
3090 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
3091 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
3092 case EOPNOTSUPP: return WSAEOPNOTSUPP;
3093 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
3094 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
3095 case EADDRINUSE: return WSAEADDRINUSE;
3096 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
3097 case ENETDOWN: return WSAENETDOWN;
3098 case ENETUNREACH: return WSAENETUNREACH;
3099 case ENETRESET: return WSAENETRESET;
3100 case ECONNABORTED: return WSAECONNABORTED;
3102 case ECONNRESET: return WSAECONNRESET;
3103 case ENOBUFS: return WSAENOBUFS;
3104 case EISCONN: return WSAEISCONN;
3105 case ENOTCONN: return WSAENOTCONN;
3106 case ESHUTDOWN: return WSAESHUTDOWN;
3107 case ETOOMANYREFS: return WSAETOOMANYREFS;
3108 case ETIMEDOUT: return WSAETIMEDOUT;
3109 case ECONNREFUSED: return WSAECONNREFUSED;
3110 case ELOOP: return WSAELOOP;
3111 case ENAMETOOLONG: return WSAENAMETOOLONG;
3112 case EHOSTDOWN: return WSAEHOSTDOWN;
3113 case EHOSTUNREACH: return WSAEHOSTUNREACH;
3114 case ENOTEMPTY: return WSAENOTEMPTY;
3116 case EPROCLIM: return WSAEPROCLIM;
3119 case EUSERS: return WSAEUSERS;
3122 case EDQUOT: return WSAEDQUOT;
3125 case ESTALE: return WSAESTALE;
3128 case EREMOTE: return WSAEREMOTE;
3131 /* just in case we ever get here and there are no problems */
3134 WARN("Unknown errno %d!\n", loc_errno);
3135 return WSAEOPNOTSUPP;
3139 UINT wsaHerrno(int loc_errno)
3142 WARN("h_errno %d.\n", loc_errno);
3146 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
3147 case TRY_AGAIN: return WSATRY_AGAIN;
3148 case NO_RECOVERY: return WSANO_RECOVERY;
3149 case NO_DATA: return WSANO_DATA;
3150 case ENOBUFS: return WSAENOBUFS;
3154 WARN("Unknown h_errno %d!\n", loc_errno);
3155 return WSAEOPNOTSUPP;
3160 /***********************************************************************
3161 * WSARecv (WS2_32.67)
3163 int WINAPI WSARecv (SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3164 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
3165 LPWSAOVERLAPPED lpOverlapped,
3166 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
3168 return WSARecvFrom (s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
3169 NULL, NULL, lpOverlapped, lpCompletionRoutine);
3172 /***********************************************************************
3173 * WSARecvFrom (WS2_32.69)
3175 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3176 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
3177 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
3178 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3181 int i, n, fd, err = WSAENOTSOCK, flags, ret;
3182 struct iovec* iovec;
3183 struct ws2_async *wsa;
3185 TRACE("socket %04x, wsabuf %p, nbufs %ld, flags %ld, from %p, fromlen %ld, ovl %p, func %p\n",
3186 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
3187 (lpFromlen ? *lpFromlen : -1L),
3188 lpOverlapped, lpCompletionRoutine);
3190 fd = get_sock_fd( s, GENERIC_READ, &flags );
3191 TRACE ( "fd=%d, flags=%x\n", fd, flags );
3193 if (fd == -1) return SOCKET_ERROR;
3195 if (flags & FD_FLAG_RECV_SHUTDOWN)
3197 WSASetLastError ( WSAESHUTDOWN );
3201 iovec = HeapAlloc ( GetProcessHeap(), 0, dwBufferCount * sizeof (struct iovec) );
3208 for (i = 0; i < dwBufferCount; i++)
3210 iovec[i].iov_base = lpBuffers[i].buf;
3211 iovec[i].iov_len = lpBuffers[i].len;
3214 if ( (lpOverlapped || lpCompletionRoutine) && flags & FD_FLAG_OVERLAPPED )
3216 wsa = WS2_make_async ( s, fd, ASYNC_TYPE_READ, iovec, dwBufferCount,
3217 lpFlags, lpFrom, lpFromlen,
3218 lpOverlapped, lpCompletionRoutine );
3226 if ( ( ret = register_new_async ( &wsa->async )) )
3228 err = NtStatusToWSAError ( ret );
3230 if ( !lpOverlapped )
3231 HeapFree ( GetProcessHeap(), 0, wsa->async.iosb );
3232 HeapFree ( GetProcessHeap(), 0, wsa );
3236 /* Try immediate completion */
3237 if ( lpOverlapped && !NtResetEvent( lpOverlapped->hEvent, NULL ) )
3239 if ( WSAGetOverlappedResult ( s, lpOverlapped,
3240 lpNumberOfBytesRecvd, FALSE, lpFlags) )
3243 if ( (err = WSAGetLastError ()) != WSA_IO_INCOMPLETE )
3247 WSASetLastError ( WSA_IO_PENDING );
3248 return SOCKET_ERROR;
3251 if ( _is_blocking(s) )
3254 /* FIXME: OOB and exceptfds? */
3255 do_block(fd, POLLIN);
3258 n = WS2_recv ( fd, iovec, dwBufferCount, lpFrom, lpFromlen, lpFlags );
3265 TRACE(" -> %i bytes\n", n);
3266 *lpNumberOfBytesRecvd = n;
3268 HeapFree (GetProcessHeap(), 0, iovec);
3269 release_sock_fd( s, fd );
3270 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
3275 HeapFree (GetProcessHeap(), 0, iovec);
3278 release_sock_fd( s, fd );
3281 WARN(" -> ERROR %d\n", err);
3282 WSASetLastError ( err );
3283 return SOCKET_ERROR;
3286 /***********************************************************************
3287 * WSCInstallProvider (WS2_32.88)
3289 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
3290 LPCWSTR lpszProviderDllPath,
3291 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
3292 DWORD dwNumberOfEntries,
3295 FIXME("(%s, %s, %p, %ld, %p): stub !\n", debugstr_guid(lpProviderId),
3296 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
3297 dwNumberOfEntries, lpErrno);
3303 /***********************************************************************
3304 * WSCDeinstallProvider (WS2_32.83)
3306 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
3308 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
3314 /***********************************************************************
3315 * WSAAccept (WS2_32.26)
3317 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
3318 LPCONDITIONPROC lpfnCondition, DWORD dwCallbackData)
3321 int ret = 0, size = 0;
3322 WSABUF CallerId, CallerData, CalleeId, CalleeData;
3323 /* QOS SQOS, GQOS; */
3326 SOCKADDR src_addr, dst_addr;
3328 TRACE("Socket %u, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
3329 s, addr, addrlen, lpfnCondition, dwCallbackData);
3332 size = sizeof(src_addr);
3333 cs = WS_accept(s, &src_addr, &size);
3335 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
3337 CallerId.buf = (char *)&src_addr;
3338 CallerId.len = sizeof(src_addr);
3340 CallerData.buf = NULL;
3341 CallerData.len = (ULONG)NULL;
3343 WS_getsockname(cs, &dst_addr, &size);
3345 CalleeId.buf = (char *)&dst_addr;
3346 CalleeId.len = sizeof(dst_addr);
3349 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
3350 &CalleeId, &CalleeData, &g, dwCallbackData);
3355 if (addr && addrlen)
3356 addr = memcpy(addr, &src_addr, (*addrlen > size) ? size : *addrlen );
3359 SERVER_START_REQ ( set_socket_deferred )
3361 req->handle = SOCKET2HANDLE (s);
3362 req->deferred = SOCKET2HANDLE (cs);
3363 if ( !wine_server_call_err ( req ) )
3365 SetLastError ( WSATRY_AGAIN );
3366 WS_closesocket ( cs );
3370 return SOCKET_ERROR;
3373 SetLastError(WSAECONNREFUSED);
3374 return SOCKET_ERROR;
3376 FIXME("Unknown return type from Condition function\n");
3377 SetLastError(WSAENOTSOCK);
3378 return SOCKET_ERROR;
3382 /***********************************************************************
3383 * WSAEnumProtocolsA (WS2_32.37)
3385 int WINAPI WSAEnumProtocolsA(LPINT lpiProtocols, LPWSAPROTOCOL_INFOA lpProtocolBuffer, LPDWORD lpdwBufferLength)
3387 FIXME("(%p,%p,%p): stub\n", lpiProtocols,lpProtocolBuffer, lpdwBufferLength);
3391 /***********************************************************************
3392 * WSAEnumProtocolsW (WS2_32.38)
3394 int WINAPI WSAEnumProtocolsW(LPINT lpiProtocols, LPWSAPROTOCOL_INFOW lpProtocolBuffer, LPDWORD lpdwBufferLength)
3396 FIXME("(%p,%p,%p): stub\n", lpiProtocols,lpProtocolBuffer, lpdwBufferLength);
3400 /***********************************************************************
3401 * WSADuplicateSocketA (WS2_32.32)
3403 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
3407 TRACE("(%d,%lx,%p)\n", s, dwProcessId, lpProtocolInfo);
3408 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
3409 /* FIXME: WS_getsockopt(s, WS_SOL_SOCKET, SO_PROTOCOL_INFO, lpProtocolInfo, sizeof(*lpProtocolInfo)); */
3410 /* I don't know what the real Windoze does next, this is a hack */
3411 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
3412 * the target use the global duplicate, or we could copy a reference to us to the structure
3413 * and let the target duplicate it from us, but let's do it as simple as possible */
3414 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
3415 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
3416 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
3417 0, FALSE, DUPLICATE_SAME_ACCESS);
3418 CloseHandle(hProcess);
3419 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
3423 /***********************************************************************
3424 * WSAInstallServiceClassA (WS2_32.48)
3426 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
3428 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
3429 WSASetLastError(WSAEACCES);
3430 return SOCKET_ERROR;
3433 /***********************************************************************
3434 * WSAInstallServiceClassW (WS2_32.49)
3436 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
3438 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
3439 WSASetLastError(WSAEACCES);
3440 return SOCKET_ERROR;
3443 /***********************************************************************
3444 * WSARemoveServiceClass (WS2_32.70)
3446 int WINAPI WSARemoveServiceClass(LPGUID info)
3448 FIXME("Request to remove service %p\n",info);
3449 WSASetLastError(WSATYPE_NOT_FOUND);
3450 return SOCKET_ERROR;