push 3fbe09a897e9df6e6f0eb06b20d156a830394152
[wine/hacks.git] / dlls / ws2_32 / socket.c
blobcabe191bdde7bba704a7ba760256870a1baca3a4
1 /*
2 * based on Windows Sockets 1.1 specs
4 * Copyright (C) 1993,1994,1996,1997 John Brezak, Erik Bos, Alex Korobka.
5 * Copyright (C) 2005 Marcus Meissner
6 * Copyright (C) 2006-2008 Kai Blin
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 * NOTE: If you make any changes to fix a particular app, make sure
23 * they don't break something else like Netscape or telnet and ftp
24 * clients and servers (www.winsite.com got a lot of those).
27 #include "config.h"
28 #include "wine/port.h"
30 #include <stdarg.h>
31 #include <stdio.h>
32 #include <string.h>
33 #include <sys/types.h>
34 #ifdef HAVE_SYS_IPC_H
35 # include <sys/ipc.h>
36 #endif
37 #ifdef HAVE_SYS_IOCTL_H
38 # include <sys/ioctl.h>
39 #endif
40 #ifdef HAVE_SYS_FILIO_H
41 # include <sys/filio.h>
42 #endif
43 #ifdef HAVE_SYS_SOCKIO_H
44 # include <sys/sockio.h>
45 #endif
47 #if defined(__EMX__)
48 # include <sys/so_ioctl.h>
49 #endif
51 #ifdef HAVE_SYS_PARAM_H
52 # include <sys/param.h>
53 #endif
55 #ifdef HAVE_SYS_MSG_H
56 # include <sys/msg.h>
57 #endif
58 #ifdef HAVE_SYS_WAIT_H
59 # include <sys/wait.h>
60 #endif
61 #ifdef HAVE_SYS_UIO_H
62 # include <sys/uio.h>
63 #endif
64 #ifdef HAVE_SYS_SOCKET_H
65 #include <sys/socket.h>
66 #endif
67 #ifdef HAVE_NETINET_IN_H
68 # include <netinet/in.h>
69 #endif
70 #ifdef HAVE_NETINET_TCP_H
71 # include <netinet/tcp.h>
72 #endif
73 #ifdef HAVE_ARPA_INET_H
74 # include <arpa/inet.h>
75 #endif
76 #include <ctype.h>
77 #include <fcntl.h>
78 #include <errno.h>
79 #ifdef HAVE_SYS_ERRNO_H
80 #include <sys/errno.h>
81 #endif
82 #ifdef HAVE_NETDB_H
83 #include <netdb.h>
84 #endif
85 #ifdef HAVE_UNISTD_H
86 # include <unistd.h>
87 #endif
88 #include <stdlib.h>
89 #ifdef HAVE_ARPA_NAMESER_H
90 # include <arpa/nameser.h>
91 #endif
92 #ifdef HAVE_RESOLV_H
93 # include <resolv.h>
94 #endif
95 #ifdef HAVE_NET_IF_H
96 # include <net/if.h>
97 #endif
99 #ifdef HAVE_NETIPX_IPX_H
100 # include <netipx/ipx.h>
101 # define HAVE_IPX
102 #elif defined(HAVE_LINUX_IPX_H)
103 # ifdef HAVE_ASM_TYPES_H
104 # include <asm/types.h>
105 # endif
106 # ifdef HAVE_LINUX_TYPES_H
107 # include <linux/types.h>
108 # endif
109 # include <linux/ipx.h>
110 # define HAVE_IPX
111 #endif
113 #ifdef HAVE_POLL_H
114 #include <poll.h>
115 #endif
116 #ifdef HAVE_SYS_POLL_H
117 # include <sys/poll.h>
118 #endif
119 #ifdef HAVE_SYS_TIME_H
120 # include <sys/time.h>
121 #endif
123 #define NONAMELESSUNION
124 #define NONAMELESSSTRUCT
125 #include "ntstatus.h"
126 #define WIN32_NO_STATUS
127 #include "windef.h"
128 #include "winbase.h"
129 #include "wingdi.h"
130 #include "winuser.h"
131 #include "winerror.h"
132 #include "winnls.h"
133 #include "winsock2.h"
134 #include "mswsock.h"
135 #include "ws2tcpip.h"
136 #include "ws2spi.h"
137 #include "wsipx.h"
138 #include "mstcpip.h"
139 #include "winnt.h"
140 #include "iphlpapi.h"
141 #include "wine/server.h"
142 #include "wine/debug.h"
143 #include "wine/unicode.h"
145 #ifdef HAVE_IPX
146 # include "wsnwlink.h"
147 #endif
150 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
151 # define sipx_network sipx_addr.x_net
152 # define sipx_node sipx_addr.x_host.c_host
153 #endif /* __FreeBSD__ */
155 #ifndef INADDR_NONE
156 #define INADDR_NONE ~0UL
157 #endif
159 WINE_DEFAULT_DEBUG_CHANNEL(winsock);
161 /* critical section to protect some non-reentrant net function */
162 extern CRITICAL_SECTION csWSgetXXXbyYYY;
164 union generic_unix_sockaddr
166 struct sockaddr addr;
167 char data[128]; /* should be big enough for all families */
170 static inline const char *debugstr_sockaddr( const struct WS_sockaddr *a )
172 if (!a) return "(nil)";
173 return wine_dbg_sprintf("{ family %d, address %s, port %d }",
174 ((const struct sockaddr_in *)a)->sin_family,
175 inet_ntoa(((const struct sockaddr_in *)a)->sin_addr),
176 ntohs(((const struct sockaddr_in *)a)->sin_port));
179 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
180 #define SOCKET2HANDLE(s) ((HANDLE)(s))
181 #define HANDLE2SOCKET(h) ((SOCKET)(h))
183 /****************************************************************
184 * Async IO declarations
185 ****************************************************************/
187 typedef struct ws2_async
189 HANDLE hSocket;
190 int type;
191 LPWSAOVERLAPPED user_overlapped;
192 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
193 IO_STATUS_BLOCK local_iosb;
194 struct WS_sockaddr *addr;
195 union
197 int val; /* for send operations */
198 int *ptr; /* for recv operations */
199 } addrlen;
200 DWORD flags;
201 unsigned int n_iovecs;
202 unsigned int first_iovec;
203 struct iovec iovec[1];
204 } ws2_async;
206 /****************************************************************/
208 /* ----------------------------------- internal data */
210 /* ws_... struct conversion flags */
212 typedef struct /* WSAAsyncSelect() control struct */
214 HANDLE service, event, sock;
215 HWND hWnd;
216 UINT uMsg;
217 LONG lEvent;
218 } ws_select_info;
220 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
221 #define WS_MAX_UDP_DATAGRAM 1024
222 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
224 /* hostent's, servent's and protent's are stored in one buffer per thread,
225 * as documented on MSDN for the functions that return any of the buffers */
226 struct per_thread_data
228 int opentype;
229 struct WS_hostent *he_buffer;
230 struct WS_servent *se_buffer;
231 struct WS_protoent *pe_buffer;
232 int he_len;
233 int se_len;
234 int pe_len;
237 static INT num_startup; /* reference counter */
238 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
240 /* function prototypes */
241 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
242 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
243 static struct WS_servent *WS_dup_se(const struct servent* p_se);
245 int WSAIOCTL_GetInterfaceCount(void);
246 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
248 UINT wsaErrno(void);
249 UINT wsaHerrno(int errnr);
251 #define MAP_OPTION(opt) { WS_##opt, opt }
253 static const int ws_sock_map[][2] =
255 MAP_OPTION( SO_DEBUG ),
256 MAP_OPTION( SO_ACCEPTCONN ),
257 MAP_OPTION( SO_REUSEADDR ),
258 MAP_OPTION( SO_KEEPALIVE ),
259 MAP_OPTION( SO_DONTROUTE ),
260 MAP_OPTION( SO_BROADCAST ),
261 MAP_OPTION( SO_LINGER ),
262 MAP_OPTION( SO_OOBINLINE ),
263 MAP_OPTION( SO_SNDBUF ),
264 MAP_OPTION( SO_RCVBUF ),
265 MAP_OPTION( SO_ERROR ),
266 MAP_OPTION( SO_TYPE ),
267 #ifdef SO_RCVTIMEO
268 MAP_OPTION( SO_RCVTIMEO ),
269 #endif
270 #ifdef SO_SNDTIMEO
271 MAP_OPTION( SO_SNDTIMEO ),
272 #endif
275 static const int ws_tcp_map[][2] =
277 #ifdef TCP_NODELAY
278 MAP_OPTION( TCP_NODELAY ),
279 #endif
282 static const int ws_ip_map[][2] =
284 MAP_OPTION( IP_MULTICAST_IF ),
285 MAP_OPTION( IP_MULTICAST_TTL ),
286 MAP_OPTION( IP_MULTICAST_LOOP ),
287 MAP_OPTION( IP_ADD_MEMBERSHIP ),
288 MAP_OPTION( IP_DROP_MEMBERSHIP ),
289 MAP_OPTION( IP_OPTIONS ),
290 #ifdef IP_HDRINCL
291 MAP_OPTION( IP_HDRINCL ),
292 #endif
293 MAP_OPTION( IP_TOS ),
294 MAP_OPTION( IP_TTL ),
297 static const int ws_af_map[][2] =
299 MAP_OPTION( AF_UNSPEC ),
300 MAP_OPTION( AF_INET ),
301 MAP_OPTION( AF_INET6 ),
302 #ifdef HAVE_IPX
303 MAP_OPTION( AF_IPX ),
304 #endif
305 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
308 static const int ws_socktype_map[][2] =
310 MAP_OPTION( SOCK_DGRAM ),
311 MAP_OPTION( SOCK_STREAM ),
312 MAP_OPTION( SOCK_RAW ),
313 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
316 static const int ws_proto_map[][2] =
318 MAP_OPTION( IPPROTO_IP ),
319 MAP_OPTION( IPPROTO_TCP ),
320 MAP_OPTION( IPPROTO_UDP ),
321 MAP_OPTION( IPPROTO_ICMP ),
322 MAP_OPTION( IPPROTO_IGMP ),
323 MAP_OPTION( IPPROTO_RAW ),
324 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
327 static const int ws_aiflag_map[][2] =
329 MAP_OPTION( AI_PASSIVE ),
330 MAP_OPTION( AI_CANONNAME ),
331 MAP_OPTION( AI_NUMERICHOST ),
332 /* Linux/UNIX knows a lot more. But Windows only
333 * has 3 as far as I could see. -Marcus
337 static const int ws_niflag_map[][2] =
339 MAP_OPTION( NI_NOFQDN ),
340 MAP_OPTION( NI_NUMERICHOST ),
341 MAP_OPTION( NI_NAMEREQD ),
342 MAP_OPTION( NI_NUMERICSERV ),
343 MAP_OPTION( NI_DGRAM ),
346 static const int ws_eai_map[][2] =
348 MAP_OPTION( EAI_AGAIN ),
349 MAP_OPTION( EAI_BADFLAGS ),
350 MAP_OPTION( EAI_FAIL ),
351 MAP_OPTION( EAI_FAMILY ),
352 MAP_OPTION( EAI_MEMORY ),
353 /* Note: EAI_NODATA is deprecated, but still
354 * used by Windows and Linux... We map the newer
355 * EAI_NONAME to EAI_NODATA for now until Windows
356 * changes too.
358 #ifdef EAI_NODATA
359 MAP_OPTION( EAI_NODATA ),
360 #endif
361 #ifdef EAI_NONAME
362 { WS_EAI_NODATA, EAI_NONAME },
363 #endif
365 MAP_OPTION( EAI_SERVICE ),
366 MAP_OPTION( EAI_SOCKTYPE ),
367 { 0, 0 }
370 static const char magic_loopback_addr[] = {127, 12, 34, 56};
372 static inline DWORD NtStatusToWSAError( const DWORD status )
374 /* We only need to cover the status codes set by server async request handling */
375 DWORD wserr;
376 switch ( status )
378 case STATUS_SUCCESS: wserr = 0; break;
379 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
380 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
381 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
382 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
383 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
384 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
385 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
386 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
387 default:
388 if ( status >= WSABASEERR && status <= WSABASEERR+1004 )
389 /* It is not an NT status code but a winsock error */
390 wserr = status;
391 else
393 wserr = RtlNtStatusToDosError( status );
394 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
397 return wserr;
400 /* set last error code from NT status without mapping WSA errors */
401 static inline unsigned int set_error( unsigned int err )
403 if (err)
405 err = NtStatusToWSAError( err );
406 SetLastError( err );
408 return err;
411 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
413 int fd;
414 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
415 return -1;
416 return fd;
419 static inline void release_sock_fd( SOCKET s, int fd )
421 wine_server_release_fd( SOCKET2HANDLE(s), fd );
424 static void _enable_event( HANDLE s, unsigned int event,
425 unsigned int sstate, unsigned int cstate )
427 SERVER_START_REQ( enable_socket_event )
429 req->handle = wine_server_obj_handle( s );
430 req->mask = event;
431 req->sstate = sstate;
432 req->cstate = cstate;
433 wine_server_call( req );
435 SERVER_END_REQ;
438 static int _is_blocking(SOCKET s)
440 int ret;
441 SERVER_START_REQ( get_socket_event )
443 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
444 req->service = FALSE;
445 req->c_event = 0;
446 wine_server_call( req );
447 ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
449 SERVER_END_REQ;
450 return ret;
453 static unsigned int _get_sock_mask(SOCKET s)
455 unsigned int ret;
456 SERVER_START_REQ( get_socket_event )
458 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
459 req->service = FALSE;
460 req->c_event = 0;
461 wine_server_call( req );
462 ret = reply->mask;
464 SERVER_END_REQ;
465 return ret;
468 static void _sync_sock_state(SOCKET s)
470 /* do a dummy wineserver request in order to let
471 the wineserver run through its select loop once */
472 (void)_is_blocking(s);
475 static int _get_sock_error(SOCKET s, unsigned int bit)
477 int events[FD_MAX_EVENTS];
479 SERVER_START_REQ( get_socket_event )
481 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
482 req->service = FALSE;
483 req->c_event = 0;
484 wine_server_set_reply( req, events, sizeof(events) );
485 wine_server_call( req );
487 SERVER_END_REQ;
488 return events[bit];
491 static struct per_thread_data *get_per_thread_data(void)
493 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
494 /* lazy initialization */
495 if (!ptb)
497 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
498 NtCurrentTeb()->WinSockData = ptb;
500 return ptb;
503 static void free_per_thread_data(void)
505 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
507 if (!ptb) return;
509 /* delete scratch buffers */
510 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
511 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
512 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
513 ptb->he_buffer = NULL;
514 ptb->se_buffer = NULL;
515 ptb->pe_buffer = NULL;
517 HeapFree( GetProcessHeap(), 0, ptb );
518 NtCurrentTeb()->WinSockData = NULL;
521 /***********************************************************************
522 * DllMain (WS2_32.init)
524 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
526 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
527 switch (fdwReason) {
528 case DLL_PROCESS_ATTACH:
529 break;
530 case DLL_PROCESS_DETACH:
531 free_per_thread_data();
532 num_startup = 0;
533 break;
534 case DLL_THREAD_DETACH:
535 free_per_thread_data();
536 break;
538 return TRUE;
541 /***********************************************************************
542 * convert_sockopt()
544 * Converts socket flags from Windows format.
545 * Return 1 if converted, 0 if not (error).
547 static int convert_sockopt(INT *level, INT *optname)
549 unsigned int i;
550 switch (*level)
552 case WS_SOL_SOCKET:
553 *level = SOL_SOCKET;
554 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
555 if( ws_sock_map[i][0] == *optname )
557 *optname = ws_sock_map[i][1];
558 return 1;
561 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
562 break;
563 case WS_IPPROTO_TCP:
564 *level = IPPROTO_TCP;
565 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
566 if ( ws_tcp_map[i][0] == *optname )
568 *optname = ws_tcp_map[i][1];
569 return 1;
572 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
573 break;
574 case WS_IPPROTO_IP:
575 *level = IPPROTO_IP;
576 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
577 if (ws_ip_map[i][0] == *optname )
579 *optname = ws_ip_map[i][1];
580 return 1;
583 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
584 break;
585 default: FIXME("Unimplemented or unknown socket level\n");
587 return 0;
590 /* ----------------------------------- Per-thread info (or per-process?) */
592 static char *strdup_lower(const char *str)
594 int i;
595 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
597 if (ret)
599 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
600 ret[i] = 0;
602 else SetLastError(WSAENOBUFS);
603 return ret;
606 static inline int sock_error_p(int s)
608 unsigned int optval, optlen;
610 optlen = sizeof(optval);
611 getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
612 if (optval) WARN("\t[%i] error: %d\n", s, optval);
613 return optval != 0;
616 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
617 * from an fd and return the value converted to milli seconds
618 * or -1 if there is an infinite time out */
619 static inline int get_rcvsnd_timeo( int fd, int optname)
621 struct timeval tv;
622 unsigned int len = sizeof(tv);
623 int ret = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
624 if( ret >= 0)
625 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
626 if( ret <= 0 ) /* tv == {0,0} means infinite time out */
627 return -1;
628 return ret;
631 /* macro wrappers for portability */
632 #ifdef SO_RCVTIMEO
633 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
634 #else
635 #define GET_RCVTIMEO(fd) (-1)
636 #endif
638 #ifdef SO_SNDTIMEO
639 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
640 #else
641 #define GET_SNDTIMEO(fd) (-1)
642 #endif
644 /* utility: given an fd, will block until one of the events occurs */
645 static inline int do_block( int fd, int events, int timeout )
647 struct pollfd pfd;
648 int ret;
650 pfd.fd = fd;
651 pfd.events = events;
653 while ((ret = poll(&pfd, 1, timeout)) < 0)
655 if (errno != EINTR)
656 return -1;
658 if( ret == 0 )
659 return 0;
660 return pfd.revents;
663 static int
664 convert_af_w2u(int windowsaf) {
665 unsigned int i;
667 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
668 if (ws_af_map[i][0] == windowsaf)
669 return ws_af_map[i][1];
670 FIXME("unhandled Windows address family %d\n", windowsaf);
671 return -1;
674 static int
675 convert_af_u2w(int unixaf) {
676 unsigned int i;
678 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
679 if (ws_af_map[i][1] == unixaf)
680 return ws_af_map[i][0];
681 FIXME("unhandled UNIX address family %d\n", unixaf);
682 return -1;
685 static int
686 convert_proto_w2u(int windowsproto) {
687 unsigned int i;
689 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
690 if (ws_proto_map[i][0] == windowsproto)
691 return ws_proto_map[i][1];
692 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
693 return -1;
696 static int
697 convert_proto_u2w(int unixproto) {
698 unsigned int i;
700 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
701 if (ws_proto_map[i][1] == unixproto)
702 return ws_proto_map[i][0];
703 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
704 return -1;
707 static int
708 convert_socktype_w2u(int windowssocktype) {
709 unsigned int i;
711 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
712 if (ws_socktype_map[i][0] == windowssocktype)
713 return ws_socktype_map[i][1];
714 FIXME("unhandled Windows socket type %d\n", windowssocktype);
715 return -1;
718 static int
719 convert_socktype_u2w(int unixsocktype) {
720 unsigned int i;
722 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
723 if (ws_socktype_map[i][1] == unixsocktype)
724 return ws_socktype_map[i][0];
725 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
726 return -1;
729 /* ----------------------------------- API -----
731 * Init / cleanup / error checking.
734 /***********************************************************************
735 * WSAStartup (WS2_32.115)
737 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
739 TRACE("verReq=%x\n", wVersionRequested);
741 if (LOBYTE(wVersionRequested) < 1)
742 return WSAVERNOTSUPPORTED;
744 if (!lpWSAData) return WSAEINVAL;
746 num_startup++;
748 /* that's the whole of the negotiation for now */
749 lpWSAData->wVersion = wVersionRequested;
750 /* return winsock information */
751 lpWSAData->wHighVersion = 0x0202;
752 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
753 strcpy(lpWSAData->szSystemStatus, "Running" );
754 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
755 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
756 /* don't do anything with lpWSAData->lpVendorInfo */
757 /* (some apps don't allocate the space for this field) */
759 TRACE("succeeded\n");
760 return 0;
764 /***********************************************************************
765 * WSACleanup (WS2_32.116)
767 INT WINAPI WSACleanup(void)
769 if (num_startup) {
770 num_startup--;
771 return 0;
773 SetLastError(WSANOTINITIALISED);
774 return SOCKET_ERROR;
778 /***********************************************************************
779 * WSAGetLastError (WINSOCK.111)
780 * WSAGetLastError (WS2_32.111)
782 INT WINAPI WSAGetLastError(void)
784 return GetLastError();
787 /***********************************************************************
788 * WSASetLastError (WS2_32.112)
790 void WINAPI WSASetLastError(INT iError) {
791 SetLastError(iError);
794 static struct WS_hostent *check_buffer_he(int size)
796 struct per_thread_data * ptb = get_per_thread_data();
797 if (ptb->he_buffer)
799 if (ptb->he_len >= size ) return ptb->he_buffer;
800 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
802 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
803 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
804 return ptb->he_buffer;
807 static struct WS_servent *check_buffer_se(int size)
809 struct per_thread_data * ptb = get_per_thread_data();
810 if (ptb->se_buffer)
812 if (ptb->se_len >= size ) return ptb->se_buffer;
813 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
815 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
816 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
817 return ptb->se_buffer;
820 static struct WS_protoent *check_buffer_pe(int size)
822 struct per_thread_data * ptb = get_per_thread_data();
823 if (ptb->pe_buffer)
825 if (ptb->pe_len >= size ) return ptb->pe_buffer;
826 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
828 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
829 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
830 return ptb->pe_buffer;
833 /* ----------------------------------- i/o APIs */
835 #ifdef HAVE_IPX
836 #define SUPPORTED_PF(pf) ((pf)==WS_AF_INET || (pf)== WS_AF_IPX || (pf) == WS_AF_INET6)
837 #else
838 #define SUPPORTED_PF(pf) ((pf)==WS_AF_INET || (pf) == WS_AF_INET6)
839 #endif
842 /**********************************************************************/
844 /* Returns the length of the converted address if successful, 0 if it was too small to
845 * start with.
847 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
848 union generic_unix_sockaddr *uaddr)
850 unsigned int uaddrlen = 0;
852 switch (wsaddr->sa_family)
854 #ifdef HAVE_IPX
855 case WS_AF_IPX:
857 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
858 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
860 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
861 return 0;
863 uaddrlen = sizeof(struct sockaddr_ipx);
864 memset( uaddr, 0, uaddrlen );
865 uipx->sipx_family=AF_IPX;
866 uipx->sipx_port=wsipx->sa_socket;
867 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
868 * in one go
870 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
871 #ifdef IPX_FRAME_NONE
872 uipx->sipx_type=IPX_FRAME_NONE;
873 #endif
874 break;
876 #endif
877 case WS_AF_INET6: {
878 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
879 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
881 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
882 * scope_id, one without.
884 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
885 uaddrlen = sizeof(struct sockaddr_in6);
886 memset( uaddr, 0, uaddrlen );
887 uin6->sin6_family = AF_INET6;
888 uin6->sin6_port = win6->sin6_port;
889 uin6->sin6_flowinfo = win6->sin6_flowinfo;
890 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
891 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
892 #endif
893 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
894 break;
896 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
897 return 0;
899 case WS_AF_INET: {
900 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
901 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
903 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
904 return 0;
905 uaddrlen = sizeof(struct sockaddr_in);
906 memset( uaddr, 0, uaddrlen );
907 uin->sin_family = AF_INET;
908 uin->sin_port = win->sin_port;
909 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
910 break;
912 case WS_AF_UNSPEC: {
913 /* Try to determine the needed space by the passed windows sockaddr space */
914 switch (wsaddrlen) {
915 default: /* likely a ipv4 address */
916 case sizeof(struct WS_sockaddr_in):
917 uaddrlen = sizeof(struct sockaddr_in);
918 break;
919 #ifdef HAVE_IPX
920 case sizeof(struct WS_sockaddr_ipx):
921 uaddrlen = sizeof(struct sockaddr_ipx);
922 break;
923 #endif
924 case sizeof(struct WS_sockaddr_in6):
925 case sizeof(struct WS_sockaddr_in6_old):
926 uaddrlen = sizeof(struct sockaddr_in6);
927 break;
929 memset( uaddr, 0, uaddrlen );
930 break;
932 default:
933 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
934 return 0;
936 return uaddrlen;
939 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
941 switch (uaddr->sa_family)
943 #ifdef HAVE_IPX
944 case AF_IPX:
945 FIXME("don't know how to tell if IPX socket is bound, assuming it is!\n");
946 return TRUE;
947 #endif
948 case AF_INET6:
950 static const struct sockaddr_in6 emptyAddr;
951 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
952 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
954 case AF_INET:
956 static const struct sockaddr_in emptyAddr;
957 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
958 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
960 case AF_UNSPEC:
961 return FALSE;
962 default:
963 FIXME("unknown address family %d\n", uaddr->sa_family);
964 return TRUE;
968 /* Returns 0 if successful, -1 if the buffer is too small */
969 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
971 int res;
973 switch(uaddr->sa_family)
975 #ifdef HAVE_IPX
976 case AF_IPX:
978 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
979 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
981 res=-1;
982 switch (*wsaddrlen) /* how much can we copy? */
984 default:
985 res=0; /* enough */
986 *wsaddrlen = sizeof(*wsipx);
987 wsipx->sa_socket=uipx->sipx_port;
988 /* fall through */
989 case 13:
990 case 12:
991 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
992 /* fall through */
993 case 11:
994 case 10:
995 case 9:
996 case 8:
997 case 7:
998 case 6:
999 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1000 /* fall through */
1001 case 5:
1002 case 4:
1003 case 3:
1004 case 2:
1005 wsipx->sa_family=WS_AF_IPX;
1006 /* fall through */
1007 case 1:
1008 case 0:
1009 /* way too small */
1010 break;
1013 break;
1014 #endif
1015 case AF_INET6: {
1016 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1017 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1019 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1020 return -1;
1021 win6old->sin6_family = WS_AF_INET6;
1022 win6old->sin6_port = uin6->sin6_port;
1023 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1024 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1025 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1026 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1027 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1028 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1029 win6->sin6_scope_id = uin6->sin6_scope_id;
1030 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1032 #endif
1033 return 0;
1035 case AF_INET: {
1036 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1037 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1039 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1040 return -1;
1041 win->sin_family = WS_AF_INET;
1042 win->sin_port = uin->sin_port;
1043 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1044 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1045 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1046 return 0;
1048 case AF_UNSPEC: {
1049 memset(wsaddr,0,*wsaddrlen);
1050 return 0;
1052 default:
1053 FIXME("Unknown address family %d\n", uaddr->sa_family);
1054 return -1;
1056 return res;
1059 /**************************************************************************
1060 * Functions for handling overlapped I/O
1061 **************************************************************************/
1063 /* user APC called upon async completion */
1064 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1066 ws2_async *wsa = arg;
1068 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
1069 iosb->Information, wsa->user_overlapped,
1070 wsa->flags );
1071 HeapFree( GetProcessHeap(), 0, wsa );
1074 /***********************************************************************
1075 * WS2_recv (INTERNAL)
1077 * Workhorse for both synchronous and asynchronous recv() operations.
1079 static int WS2_recv( int fd, struct ws2_async *wsa )
1081 struct msghdr hdr;
1082 union generic_unix_sockaddr unix_sockaddr;
1083 int n;
1085 hdr.msg_name = NULL;
1087 if (wsa->addr)
1089 hdr.msg_namelen = sizeof(unix_sockaddr);
1090 hdr.msg_name = &unix_sockaddr;
1092 else
1093 hdr.msg_namelen = 0;
1095 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1096 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1097 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1098 hdr.msg_accrights = NULL;
1099 hdr.msg_accrightslen = 0;
1100 #else
1101 hdr.msg_control = NULL;
1102 hdr.msg_controllen = 0;
1103 hdr.msg_flags = 0;
1104 #endif
1106 if ( (n = recvmsg(fd, &hdr, wsa->flags)) == -1 )
1107 return -1;
1109 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
1110 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
1112 * quoting linux 2.6 net/ipv4/tcp.c:
1113 * "According to UNIX98, msg_name/msg_namelen are ignored
1114 * on connected socket. I was just happy when found this 8) --ANK"
1116 * likewise MSDN says that lpFrom and lpFromlen are ignored for
1117 * connection-oriented sockets, so don't try to update lpFrom.
1119 if (wsa->addr && hdr.msg_namelen)
1120 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
1122 return n;
1125 /***********************************************************************
1126 * WS2_async_recv (INTERNAL)
1128 * Handler for overlapped recv() operations.
1130 static NTSTATUS WS2_async_recv( void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1132 ws2_async* wsa = user;
1133 int result = 0, fd;
1135 switch (status)
1137 case STATUS_ALERTED:
1138 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
1139 break;
1141 result = WS2_recv( fd, wsa );
1142 wine_server_release_fd( wsa->hSocket, fd );
1143 if (result >= 0)
1145 status = STATUS_SUCCESS;
1146 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1148 else
1150 if (errno == EINTR || errno == EAGAIN)
1152 status = STATUS_PENDING;
1153 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1155 else
1157 result = 0;
1158 status = wsaErrno(); /* FIXME: is this correct ???? */
1161 break;
1163 if (status != STATUS_PENDING)
1165 iosb->u.Status = status;
1166 iosb->Information = result;
1167 *apc = ws2_async_apc;
1169 return status;
1172 /***********************************************************************
1173 * WS2_send (INTERNAL)
1175 * Workhorse for both synchronous and asynchronous send() operations.
1177 static int WS2_send( int fd, struct ws2_async *wsa )
1179 struct msghdr hdr;
1180 union generic_unix_sockaddr unix_addr;
1182 hdr.msg_name = NULL;
1183 hdr.msg_namelen = 0;
1185 if (wsa->addr)
1187 hdr.msg_name = &unix_addr;
1188 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
1189 if ( !hdr.msg_namelen )
1191 errno = EFAULT;
1192 return -1;
1195 #if defined(HAVE_IPX) && defined(SOL_IPX)
1196 if(wsa->addr->sa_family == WS_AF_IPX)
1198 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
1199 int val=0;
1200 unsigned int len=sizeof(int);
1202 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
1203 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
1204 * the packet type and then we can retrieve it using getsockopt. After that we can set the
1205 * ipx type in the sockaddr_opx structure with the stored value.
1207 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
1208 uipx->sipx_type = val;
1210 #endif
1213 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1214 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1215 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1216 hdr.msg_accrights = NULL;
1217 hdr.msg_accrightslen = 0;
1218 #else
1219 hdr.msg_control = NULL;
1220 hdr.msg_controllen = 0;
1221 hdr.msg_flags = 0;
1222 #endif
1224 return sendmsg(fd, &hdr, wsa->flags);
1227 /***********************************************************************
1228 * WS2_async_send (INTERNAL)
1230 * Handler for overlapped send() operations.
1232 static NTSTATUS WS2_async_send(void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1234 ws2_async* wsa = user;
1235 int result = 0, fd;
1237 switch (status)
1239 case STATUS_ALERTED:
1240 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
1241 break;
1243 /* check to see if the data is ready (non-blocking) */
1244 result = WS2_send( fd, wsa );
1245 wine_server_release_fd( wsa->hSocket, fd );
1247 if (result >= 0)
1249 int totalLength = 0;
1250 unsigned int i;
1251 status = STATUS_SUCCESS;
1252 for (i = 0; i < wsa->n_iovecs; i++)
1253 totalLength += wsa->iovec[i].iov_len;
1254 if (result < totalLength)
1255 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1257 else
1259 if (errno == EINTR || errno == EAGAIN)
1261 status = STATUS_PENDING;
1262 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1264 else
1266 /* We set the status to a winsock error code and check for that
1267 later in NtStatusToWSAError () */
1268 status = wsaErrno();
1269 result = 0;
1272 break;
1274 if (status != STATUS_PENDING)
1276 iosb->u.Status = status;
1277 iosb->Information = result;
1278 *apc = ws2_async_apc;
1280 return status;
1283 /***********************************************************************
1284 * WS2_async_shutdown (INTERNAL)
1286 * Handler for shutdown() operations on overlapped sockets.
1288 static NTSTATUS WS2_async_shutdown( void* user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc )
1290 ws2_async* wsa = user;
1291 int fd, err = 1;
1293 switch (status)
1295 case STATUS_ALERTED:
1296 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
1297 break;
1299 switch ( wsa->type )
1301 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
1302 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
1304 wine_server_release_fd( wsa->hSocket, fd );
1305 status = err ? wsaErrno() : STATUS_SUCCESS;
1306 break;
1308 iosb->u.Status = status;
1309 *apc = ws2_async_apc;
1310 return status;
1313 /***********************************************************************
1314 * WS2_register_async_shutdown (INTERNAL)
1316 * Helper function for WS_shutdown() on overlapped sockets.
1318 static int WS2_register_async_shutdown( SOCKET s, int type )
1320 struct ws2_async *wsa;
1321 NTSTATUS status;
1323 TRACE("s %ld type %d\n", s, type);
1325 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
1326 if ( !wsa )
1327 return WSAEFAULT;
1329 wsa->hSocket = SOCKET2HANDLE(s);
1330 wsa->type = type;
1331 wsa->completion_func = NULL;
1333 SERVER_START_REQ( register_async )
1335 req->type = type;
1336 req->async.handle = wine_server_obj_handle( wsa->hSocket );
1337 req->async.callback = wine_server_client_ptr( WS2_async_shutdown );
1338 req->async.iosb = wine_server_client_ptr( &wsa->local_iosb );
1339 req->async.arg = wine_server_client_ptr( wsa );
1340 req->async.cvalue = 0;
1341 status = wine_server_call( req );
1343 SERVER_END_REQ;
1345 if (status != STATUS_PENDING)
1347 HeapFree( GetProcessHeap(), 0, wsa );
1348 return NtStatusToWSAError( status );
1350 return 0;
1353 /***********************************************************************
1354 * accept (WS2_32.1)
1356 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr,
1357 int *addrlen32)
1359 SOCKET as;
1360 BOOL is_blocking;
1362 TRACE("socket %04lx\n", s );
1363 is_blocking = _is_blocking(s);
1365 do {
1366 if (is_blocking)
1368 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1369 if (fd == -1) return INVALID_SOCKET;
1370 /* block here */
1371 do_block(fd, POLLIN, -1);
1372 _sync_sock_state(s); /* let wineserver notice connection */
1373 release_sock_fd( s, fd );
1374 /* retrieve any error codes from it */
1375 SetLastError(_get_sock_error(s, FD_ACCEPT_BIT));
1376 /* FIXME: care about the error? */
1378 SERVER_START_REQ( accept_socket )
1380 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1381 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
1382 req->attributes = OBJ_INHERIT;
1383 set_error( wine_server_call( req ) );
1384 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
1386 SERVER_END_REQ;
1387 if (as)
1389 if (addr) WS_getpeername(as, addr, addrlen32);
1390 return as;
1392 } while (is_blocking);
1393 return INVALID_SOCKET;
1396 /***********************************************************************
1397 * bind (WS2_32.2)
1399 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
1401 int fd = get_sock_fd( s, 0, NULL );
1402 int res = SOCKET_ERROR;
1404 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1406 if (fd != -1)
1408 if (!name || (name->sa_family && !SUPPORTED_PF(name->sa_family)))
1410 SetLastError(WSAEAFNOSUPPORT);
1412 else
1414 union generic_unix_sockaddr uaddr;
1415 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1416 if (!uaddrlen)
1418 SetLastError(WSAEFAULT);
1420 else
1422 #ifdef IPV6_V6ONLY
1423 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
1424 if (name->sa_family == WS_AF_INET6 &&
1425 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
1427 int enable = 1;
1428 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
1430 release_sock_fd( s, fd );
1431 SetLastError(WSAEAFNOSUPPORT);
1432 return SOCKET_ERROR;
1435 #endif
1436 if (name->sa_family == WS_AF_INET)
1438 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
1439 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
1441 /* Trying to bind to the default host interface, using
1442 * INADDR_ANY instead*/
1443 WARN("Trying to bind to magic IP address, using "
1444 "INADDR_ANY instead.\n");
1445 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
1448 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
1450 int loc_errno = errno;
1451 WARN("\tfailure - errno = %i\n", errno);
1452 errno = loc_errno;
1453 switch (errno)
1455 case EBADF:
1456 SetLastError(WSAENOTSOCK);
1457 break;
1458 case EADDRNOTAVAIL:
1459 SetLastError(WSAEINVAL);
1460 break;
1461 default:
1462 SetLastError(wsaErrno());
1463 break;
1466 else
1468 res=0; /* success */
1472 release_sock_fd( s, fd );
1474 return res;
1477 /***********************************************************************
1478 * closesocket (WS2_32.3)
1480 int WINAPI WS_closesocket(SOCKET s)
1482 TRACE("socket %04lx\n", s);
1483 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
1484 return SOCKET_ERROR;
1487 /***********************************************************************
1488 * connect (WS2_32.4)
1490 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
1492 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1494 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1496 if (fd != -1)
1498 union generic_unix_sockaddr uaddr;
1499 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1501 if (!uaddrlen)
1503 SetLastError(WSAEFAULT);
1505 else
1507 if (name->sa_family == WS_AF_INET)
1509 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
1510 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
1512 /* Trying to connect to magic replace-loopback address,
1513 * assuming we really want to connect to localhost */
1514 TRACE("Trying to connect to magic IP address, using "
1515 "INADDR_LOOPBACK instead.\n");
1516 in4->sin_addr.s_addr = htonl(WS_INADDR_LOOPBACK);
1520 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
1521 goto connect_success;
1524 if (errno == EINPROGRESS)
1526 /* tell wineserver that a connection is in progress */
1527 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1528 FD_CONNECT|FD_READ|FD_WRITE,
1529 FD_WINE_CONNECTED|FD_WINE_LISTENING);
1530 if (_is_blocking(s))
1532 int result;
1533 /* block here */
1534 do_block(fd, POLLIN | POLLOUT, -1);
1535 _sync_sock_state(s); /* let wineserver notice connection */
1536 /* retrieve any error codes from it */
1537 result = _get_sock_error(s, FD_CONNECT_BIT);
1538 if (result)
1539 SetLastError(result);
1540 else
1542 goto connect_success;
1545 else
1547 SetLastError(WSAEWOULDBLOCK);
1550 else
1552 SetLastError(wsaErrno());
1554 release_sock_fd( s, fd );
1556 return SOCKET_ERROR;
1558 connect_success:
1559 release_sock_fd( s, fd );
1560 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1561 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
1562 FD_CONNECT|FD_WINE_LISTENING);
1563 return 0;
1566 /***********************************************************************
1567 * WSAConnect (WS2_32.30)
1569 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
1570 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
1571 LPQOS lpSQOS, LPQOS lpGQOS )
1573 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
1574 FIXME("unsupported parameters!\n");
1575 return WS_connect( s, name, namelen );
1579 /***********************************************************************
1580 * getpeername (WS2_32.5)
1582 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
1584 int fd;
1585 int res;
1587 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, *namelen);
1589 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1590 if( (name == NULL) || (namelen == NULL) )
1592 SetLastError( WSAEFAULT );
1593 return SOCKET_ERROR;
1596 fd = get_sock_fd( s, 0, NULL );
1597 res = SOCKET_ERROR;
1599 if (fd != -1)
1601 union generic_unix_sockaddr uaddr;
1602 unsigned int uaddrlen = sizeof(uaddr);
1604 if (getpeername(fd, &uaddr.addr, &uaddrlen) != 0)
1606 SetLastError(wsaErrno());
1608 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
1610 /* The buffer was too small */
1611 SetLastError(WSAEFAULT);
1613 else
1615 res=0;
1617 release_sock_fd( s, fd );
1619 return res;
1622 /***********************************************************************
1623 * getsockname (WS2_32.6)
1625 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
1627 int fd;
1628 int res;
1630 TRACE("socket: %04lx, ptr %p, len %8x\n", s, name, *namelen);
1632 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1633 if( (name == NULL) || (namelen == NULL) )
1635 SetLastError( WSAEFAULT );
1636 return SOCKET_ERROR;
1639 fd = get_sock_fd( s, 0, NULL );
1640 res = SOCKET_ERROR;
1642 if (fd != -1)
1644 union generic_unix_sockaddr uaddr;
1645 unsigned int uaddrlen = sizeof(uaddr);
1647 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
1649 SetLastError(wsaErrno());
1651 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
1653 SetLastError(WSAEINVAL);
1655 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
1657 /* The buffer was too small */
1658 SetLastError(WSAEFAULT);
1660 else
1662 res=0;
1664 release_sock_fd( s, fd );
1666 return res;
1669 /***********************************************************************
1670 * getsockopt (WS2_32.7)
1672 INT WINAPI WS_getsockopt(SOCKET s, INT level,
1673 INT optname, char *optval, INT *optlen)
1675 int fd;
1676 INT ret = 0;
1678 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
1679 s, level, optname, optval, *optlen);
1681 switch(level)
1683 case WS_SOL_SOCKET:
1685 switch(optname)
1687 /* Handle common cases. The special cases are below, sorted
1688 * alphabetically */
1689 case WS_SO_ACCEPTCONN:
1690 case WS_SO_BROADCAST:
1691 case WS_SO_DEBUG:
1692 case WS_SO_ERROR:
1693 case WS_SO_KEEPALIVE:
1694 case WS_SO_OOBINLINE:
1695 case WS_SO_RCVBUF:
1696 case WS_SO_REUSEADDR:
1697 case WS_SO_SNDBUF:
1698 case WS_SO_TYPE:
1699 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1700 return SOCKET_ERROR;
1701 convert_sockopt(&level, &optname);
1702 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
1704 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1705 ret = SOCKET_ERROR;
1707 release_sock_fd( s, fd );
1708 return ret;
1710 case WS_SO_DONTLINGER:
1712 struct linger lingval;
1713 unsigned int len = sizeof(struct linger);
1715 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
1717 SetLastError(WSAEFAULT);
1718 return SOCKET_ERROR;
1720 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1721 return SOCKET_ERROR;
1723 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
1725 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1726 ret = SOCKET_ERROR;
1728 else
1730 *(BOOL *)optval = (lingval.l_onoff) ? FALSE : TRUE;
1731 *optlen = sizeof(BOOL);
1734 release_sock_fd( s, fd );
1735 return ret;
1738 /* As mentioned in setsockopt, Windows ignores this, so we
1739 * always return true here */
1740 case WS_SO_DONTROUTE:
1741 if (!optlen || *optlen < sizeof(BOOL) || !optval)
1743 SetLastError(WSAEFAULT);
1744 return SOCKET_ERROR;
1746 *(BOOL *)optval = TRUE;
1747 *optlen = sizeof(BOOL);
1748 return 0;
1750 case WS_SO_LINGER:
1752 struct linger lingval;
1753 unsigned int len = sizeof(struct linger);
1755 /* struct linger and LINGER have different sizes */
1756 if (!optlen || *optlen < sizeof(LINGER) || !optval)
1758 SetLastError(WSAEFAULT);
1759 return SOCKET_ERROR;
1761 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1762 return SOCKET_ERROR;
1764 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
1766 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1767 ret = SOCKET_ERROR;
1769 else
1771 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
1772 ((LINGER *)optval)->l_linger = lingval.l_linger;
1773 *optlen = sizeof(struct linger);
1776 release_sock_fd( s, fd );
1777 return ret;
1780 case WS_SO_MAX_MSG_SIZE:
1781 if (!optlen || *optlen < sizeof(int) || !optval)
1783 SetLastError(WSAEFAULT);
1784 return SOCKET_ERROR;
1786 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
1787 *(int *)optval = 65507;
1788 *optlen = sizeof(int);
1789 return 0;
1791 /* SO_OPENTYPE does not require a valid socket handle. */
1792 case WS_SO_OPENTYPE:
1793 if (!optlen || *optlen < sizeof(int) || !optval)
1795 SetLastError(WSAEFAULT);
1796 return SOCKET_ERROR;
1798 *(int *)optval = get_per_thread_data()->opentype;
1799 *optlen = sizeof(int);
1800 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
1801 return 0;
1803 #ifdef SO_RCVTIMEO
1804 case WS_SO_RCVTIMEO:
1805 #endif
1806 #ifdef SO_SNDTIMEO
1807 case WS_SO_SNDTIMEO:
1808 #endif
1809 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
1811 struct timeval tv;
1812 unsigned int len = sizeof(struct timeval);
1814 if (!optlen || *optlen < sizeof(int)|| !optval)
1816 SetLastError(WSAEFAULT);
1817 return SOCKET_ERROR;
1819 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1820 return SOCKET_ERROR;
1822 convert_sockopt(&level, &optname);
1823 if (getsockopt(fd, level, optname, &tv, &len) != 0 )
1825 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1826 ret = SOCKET_ERROR;
1828 else
1830 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
1831 *optlen = sizeof(int);
1834 release_sock_fd( s, fd );
1835 return ret;
1837 #endif
1838 default:
1839 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
1840 SetLastError(WSAENOPROTOOPT);
1841 return SOCKET_ERROR;
1842 } /* end switch(optname) */
1843 }/* end case WS_SOL_SOCKET */
1844 #ifdef HAVE_IPX
1845 case NSPROTO_IPX:
1847 struct WS_sockaddr_ipx addr;
1848 IPX_ADDRESS_DATA *data;
1849 int namelen;
1850 switch(optname)
1852 case IPX_PTYPE:
1853 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
1854 #ifdef SOL_IPX
1855 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (unsigned int*)optlen) == -1)
1857 ret = SOCKET_ERROR;
1859 #else
1861 struct ipx val;
1862 socklen_t len=sizeof(struct ipx);
1863 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
1864 ret = SOCKET_ERROR;
1865 else
1866 *optval = (int)val.ipx_pt;
1868 #endif
1869 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
1870 release_sock_fd( s, fd );
1871 return ret;
1873 case IPX_ADDRESS:
1875 * On a Win2000 system with one network card there are usually
1876 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
1877 * Using this call you can then retrieve info about this all.
1878 * In case of Linux it is a bit different. Usually you have
1879 * only "one" device active and further it is not possible to
1880 * query things like the linkspeed.
1882 FIXME("IPX_ADDRESS\n");
1883 namelen = sizeof(struct WS_sockaddr_ipx);
1884 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
1885 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
1887 data = (IPX_ADDRESS_DATA*)optval;
1888 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
1889 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
1890 data->adapternum = 0;
1891 data->wan = FALSE; /* We are not on a wan for now .. */
1892 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
1893 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
1894 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
1895 * note 1MB = 1000kB in this case */
1896 return 0;
1898 case IPX_MAX_ADAPTER_NUM:
1899 FIXME("IPX_MAX_ADAPTER_NUM\n");
1900 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
1901 return 0;
1903 default:
1904 FIXME("IPX optname:%x\n", optname);
1905 return SOCKET_ERROR;
1906 }/* end switch(optname) */
1907 } /* end case NSPROTO_IPX */
1908 #endif
1909 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
1910 case WS_IPPROTO_TCP:
1911 switch(optname)
1913 case WS_TCP_NODELAY:
1914 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1915 return SOCKET_ERROR;
1916 convert_sockopt(&level, &optname);
1917 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
1919 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1920 ret = SOCKET_ERROR;
1922 release_sock_fd( s, fd );
1923 return ret;
1925 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
1926 return SOCKET_ERROR;
1928 case WS_IPPROTO_IP:
1929 switch(optname)
1931 case WS_IP_ADD_MEMBERSHIP:
1932 case WS_IP_DROP_MEMBERSHIP:
1933 #ifdef IP_HDRINCL
1934 case WS_IP_HDRINCL:
1935 #endif
1936 case WS_IP_MULTICAST_IF:
1937 case WS_IP_MULTICAST_LOOP:
1938 case WS_IP_MULTICAST_TTL:
1939 case WS_IP_OPTIONS:
1940 case WS_IP_TOS:
1941 case WS_IP_TTL:
1942 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1943 return SOCKET_ERROR;
1944 convert_sockopt(&level, &optname);
1945 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
1947 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1948 ret = SOCKET_ERROR;
1950 release_sock_fd( s, fd );
1951 return ret;
1952 case WS_IP_DONTFRAGMENT:
1953 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
1954 *(BOOL*)optval = FALSE;
1955 return 0;
1957 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
1958 return SOCKET_ERROR;
1960 default:
1961 FIXME("Unknown level: 0x%08x\n", level);
1962 return SOCKET_ERROR;
1963 } /* end switch(level) */
1966 /***********************************************************************
1967 * htonl (WINSOCK.8)
1968 * htonl (WS2_32.8)
1970 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
1972 return htonl(hostlong);
1976 /***********************************************************************
1977 * htons (WINSOCK.9)
1978 * htons (WS2_32.9)
1980 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
1982 return htons(hostshort);
1985 /***********************************************************************
1986 * WSAHtonl (WS2_32.46)
1987 * From MSDN description of error codes, this function should also
1988 * check if WinSock has been initialized and the socket is a valid
1989 * socket. But why? This function only translates a host byte order
1990 * u_long into a network byte order u_long...
1992 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
1994 if (lpnetlong)
1996 *lpnetlong = htonl(hostlong);
1997 return 0;
1999 WSASetLastError(WSAEFAULT);
2000 return SOCKET_ERROR;
2003 /***********************************************************************
2004 * WSAHtons (WS2_32.47)
2005 * From MSDN description of error codes, this function should also
2006 * check if WinSock has been initialized and the socket is a valid
2007 * socket. But why? This function only translates a host byte order
2008 * u_short into a network byte order u_short...
2010 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
2013 if (lpnetshort)
2015 *lpnetshort = htons(hostshort);
2016 return 0;
2018 WSASetLastError(WSAEFAULT);
2019 return SOCKET_ERROR;
2023 /***********************************************************************
2024 * inet_addr (WINSOCK.10)
2025 * inet_addr (WS2_32.11)
2027 WS_u_long WINAPI WS_inet_addr(const char *cp)
2029 if (!cp) return INADDR_NONE;
2030 return inet_addr(cp);
2034 /***********************************************************************
2035 * ntohl (WINSOCK.14)
2036 * ntohl (WS2_32.14)
2038 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
2040 return ntohl(netlong);
2044 /***********************************************************************
2045 * ntohs (WINSOCK.15)
2046 * ntohs (WS2_32.15)
2048 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
2050 return ntohs(netshort);
2054 /***********************************************************************
2055 * inet_ntoa (WS2_32.12)
2057 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
2059 /* use "buffer for dummies" here because some applications have a
2060 * propensity to decode addresses in ws_hostent structure without
2061 * saving them first...
2063 static char dbuffer[16]; /* Yes, 16: 4*3 digits + 3 '.' + 1 '\0' */
2065 char* s = inet_ntoa(*((struct in_addr*)&in));
2066 if( s )
2068 strcpy(dbuffer, s);
2069 return dbuffer;
2071 SetLastError(wsaErrno());
2072 return NULL;
2075 /**********************************************************************
2076 * WSAIoctl (WS2_32.50)
2079 INT WINAPI WSAIoctl(SOCKET s,
2080 DWORD dwIoControlCode,
2081 LPVOID lpvInBuffer,
2082 DWORD cbInBuffer,
2083 LPVOID lpbOutBuffer,
2084 DWORD cbOutBuffer,
2085 LPDWORD lpcbBytesReturned,
2086 LPWSAOVERLAPPED lpOverlapped,
2087 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
2089 TRACE("%ld, 0x%08x, %p, %d, %p, %d, %p, %p, %p\n",
2090 s, dwIoControlCode, lpvInBuffer, cbInBuffer, lpbOutBuffer,
2091 cbOutBuffer, lpcbBytesReturned, lpOverlapped, lpCompletionRoutine);
2093 switch( dwIoControlCode )
2095 case WS_FIONBIO:
2096 if (cbInBuffer != sizeof(WS_u_long)) {
2097 WSASetLastError(WSAEFAULT);
2098 return SOCKET_ERROR;
2100 return WS_ioctlsocket( s, WS_FIONBIO, lpvInBuffer);
2102 case WS_FIONREAD:
2103 if (cbOutBuffer != sizeof(WS_u_long)) {
2104 WSASetLastError(WSAEFAULT);
2105 return SOCKET_ERROR;
2107 return WS_ioctlsocket( s, WS_FIONREAD, lpbOutBuffer);
2109 case WS_SIO_GET_INTERFACE_LIST:
2111 INTERFACE_INFO* intArray = (INTERFACE_INFO*)lpbOutBuffer;
2112 DWORD size, numInt, apiReturn;
2113 int fd;
2115 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
2117 if (!lpbOutBuffer)
2119 WSASetLastError(WSAEFAULT);
2120 return SOCKET_ERROR;
2122 if (!lpcbBytesReturned)
2124 WSASetLastError(WSAEFAULT);
2125 return SOCKET_ERROR;
2128 fd = get_sock_fd( s, 0, NULL );
2129 if (fd == -1) return SOCKET_ERROR;
2131 apiReturn = GetAdaptersInfo(NULL, &size);
2132 if (apiReturn == ERROR_NO_DATA)
2134 numInt = 0;
2136 else if (apiReturn == ERROR_BUFFER_OVERFLOW)
2138 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
2140 if (table)
2142 if (GetAdaptersInfo(table, &size) == NO_ERROR)
2144 PIP_ADAPTER_INFO ptr;
2146 if (size*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > cbOutBuffer)
2148 WARN("Buffer too small = %u, cbOutBuffer = %u\n", size, cbOutBuffer);
2149 HeapFree(GetProcessHeap(),0,table);
2150 release_sock_fd( s, fd );
2151 WSASetLastError(WSAEFAULT);
2152 return SOCKET_ERROR;
2154 for (ptr = table, numInt = 0; ptr;
2155 ptr = ptr->Next, intArray++, numInt++)
2157 unsigned int addr, mask, bcast;
2158 struct ifreq ifInfo;
2160 /* Socket Status Flags */
2161 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
2162 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
2164 ERR("Error obtaining status flags for socket!\n");
2165 HeapFree(GetProcessHeap(),0,table);
2166 release_sock_fd( s, fd );
2167 WSASetLastError(WSAEINVAL);
2168 return SOCKET_ERROR;
2170 else
2172 /* set flags; the values of IFF_* are not the same
2173 under Linux and Windows, therefore must generate
2174 new flags */
2175 intArray->iiFlags = 0;
2176 if (ifInfo.ifr_flags & IFF_BROADCAST)
2177 intArray->iiFlags |= WS_IFF_BROADCAST;
2178 #ifdef IFF_POINTOPOINT
2179 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
2180 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
2181 #endif
2182 if (ifInfo.ifr_flags & IFF_LOOPBACK)
2183 intArray->iiFlags |= WS_IFF_LOOPBACK;
2184 if (ifInfo.ifr_flags & IFF_UP)
2185 intArray->iiFlags |= WS_IFF_UP;
2186 if (ifInfo.ifr_flags & IFF_MULTICAST)
2187 intArray->iiFlags |= WS_IFF_MULTICAST;
2190 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
2191 mask = inet_addr(ptr->IpAddressList.IpMask.String);
2192 bcast = addr | ~mask;
2193 intArray->iiAddress.AddressIn.sin_family = AF_INET;
2194 intArray->iiAddress.AddressIn.sin_port = 0;
2195 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
2196 addr;
2197 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
2198 intArray->iiNetmask.AddressIn.sin_port = 0;
2199 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
2200 mask;
2201 intArray->iiBroadcastAddress.AddressIn.sin_family =
2202 AF_INET;
2203 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
2204 intArray->iiBroadcastAddress.AddressIn.sin_addr.
2205 WS_s_addr = bcast;
2208 else
2210 ERR("Unable to get interface table!\n");
2211 release_sock_fd( s, fd );
2212 HeapFree(GetProcessHeap(),0,table);
2213 WSASetLastError(WSAEINVAL);
2214 return SOCKET_ERROR;
2216 HeapFree(GetProcessHeap(),0,table);
2218 else
2220 release_sock_fd( s, fd );
2221 WSASetLastError(WSAEINVAL);
2222 return SOCKET_ERROR;
2225 else
2227 ERR("Unable to get interface table!\n");
2228 release_sock_fd( s, fd );
2229 WSASetLastError(WSAEINVAL);
2230 return SOCKET_ERROR;
2232 /* Calculate the size of the array being returned */
2233 *lpcbBytesReturned = sizeof(INTERFACE_INFO) * numInt;
2234 release_sock_fd( s, fd );
2235 break;
2238 case WS_SIO_ADDRESS_LIST_CHANGE:
2239 FIXME("-> SIO_ADDRESS_LIST_CHANGE request: stub\n");
2240 /* FIXME: error and return code depend on whether socket was created
2241 * with WSA_FLAG_OVERLAPPED, but there is no easy way to get this */
2242 break;
2244 case WS_SIO_ADDRESS_LIST_QUERY:
2246 DWORD size;
2248 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
2250 if (!lpcbBytesReturned)
2252 WSASetLastError(WSAEFAULT);
2253 return SOCKET_ERROR;
2256 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
2258 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
2259 DWORD need, num;
2261 if (!table || GetAdaptersInfo(table, &size))
2263 HeapFree(GetProcessHeap(), 0, table);
2264 WSASetLastError(WSAEINVAL);
2265 return SOCKET_ERROR;
2268 for (p = table, num = 0; p; p = p->Next)
2269 if (p->IpAddressList.IpAddress.String[0]) num++;
2271 need = sizeof(SOCKET_ADDRESS_LIST) + sizeof(SOCKET_ADDRESS) * (num - 1);
2272 need += sizeof(SOCKADDR) * num;
2273 *lpcbBytesReturned = need;
2275 if (need > cbOutBuffer)
2277 HeapFree(GetProcessHeap(), 0, table);
2278 WSASetLastError(WSAEFAULT);
2279 return SOCKET_ERROR;
2282 if (lpbOutBuffer)
2284 unsigned int i;
2285 SOCKET_ADDRESS *sa;
2286 SOCKET_ADDRESS_LIST *sa_list = (SOCKET_ADDRESS_LIST *)lpbOutBuffer;
2287 SOCKADDR_IN *sockaddr;
2289 sa = sa_list->Address;
2290 sockaddr = (SOCKADDR_IN *)((char *)sa + num * sizeof(SOCKET_ADDRESS));
2291 sa_list->iAddressCount = num;
2293 for (p = table, i = 0; p; p = p->Next)
2295 if (!p->IpAddressList.IpAddress.String[0]) continue;
2297 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
2298 sa[i].iSockaddrLength = sizeof(SOCKADDR);
2300 sockaddr[i].sin_family = AF_INET;
2301 sockaddr[i].sin_port = 0;
2302 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
2303 i++;
2307 HeapFree(GetProcessHeap(), 0, table);
2308 return 0;
2310 else
2312 WARN("unable to get IP address list\n");
2313 WSASetLastError(WSAEINVAL);
2314 return SOCKET_ERROR;
2317 case WS_SIO_FLUSH:
2318 FIXME("SIO_FLUSH: stub.\n");
2319 break;
2321 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
2322 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(lpvInBuffer));
2323 WSASetLastError(WSAEOPNOTSUPP);
2324 return SOCKET_ERROR;
2326 case WS_SIO_KEEPALIVE_VALS:
2328 int fd;
2329 struct tcp_keepalive *k = lpvInBuffer;
2330 int keepalive = k->onoff ? 1 : 0;
2331 int keepidle = k->keepalivetime / 1000;
2332 int keepintvl = k->keepaliveinterval / 1000;
2334 if (!lpvInBuffer)
2336 WSASetLastError(WSAEINVAL);
2337 return SOCKET_ERROR;
2340 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
2342 fd = get_sock_fd(s, 0, NULL);
2343 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
2345 release_sock_fd(s, fd);
2346 WSASetLastError(WSAEINVAL);
2347 return SOCKET_ERROR;
2349 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
2350 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
2352 release_sock_fd(s, fd);
2353 WSASetLastError(WSAEINVAL);
2354 return SOCKET_ERROR;
2356 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
2358 release_sock_fd(s, fd);
2359 WSASetLastError(WSAEINVAL);
2360 return SOCKET_ERROR;
2362 #else
2363 FIXME("ignoring keepalive interval and timeout\n");
2364 #endif
2366 release_sock_fd(s, fd);
2367 break;
2369 default:
2370 FIXME("unsupported WS_IOCTL cmd (%08x)\n", dwIoControlCode);
2371 WSASetLastError(WSAEOPNOTSUPP);
2372 return SOCKET_ERROR;
2375 return 0;
2379 /***********************************************************************
2380 * ioctlsocket (WS2_32.10)
2382 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
2384 int fd;
2385 long newcmd = cmd;
2387 TRACE("socket %04lx, cmd %08x, ptr %p\n", s, cmd, argp);
2388 /* broken apps like defcon pass the argp value directly instead of a pointer to it */
2389 if(IS_INTRESOURCE(argp))
2391 SetLastError(WSAEFAULT);
2392 return SOCKET_ERROR;
2395 switch( cmd )
2397 case WS_FIONREAD:
2398 newcmd=FIONREAD;
2399 break;
2401 case WS_FIONBIO:
2402 if( _get_sock_mask(s) )
2404 /* AsyncSelect()'ed sockets are always nonblocking */
2405 if (*argp) return 0;
2406 SetLastError(WSAEINVAL);
2407 return SOCKET_ERROR;
2409 fd = get_sock_fd( s, 0, NULL );
2410 if (fd != -1)
2412 int ret;
2413 if (*argp)
2415 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
2416 ret = fcntl( fd, F_SETFL, O_NONBLOCK );
2418 else
2420 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
2421 ret = fcntl( fd, F_SETFL, 0 );
2423 release_sock_fd( s, fd );
2424 if (!ret) return 0;
2425 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2427 return SOCKET_ERROR;
2429 case WS_SIOCATMARK:
2430 newcmd=SIOCATMARK;
2431 break;
2433 case WS_FIOASYNC:
2434 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
2435 SetLastError(WSAEINVAL);
2436 return SOCKET_ERROR;
2438 case SIOCGIFBRDADDR:
2439 case SIOCGIFNETMASK:
2440 case SIOCGIFADDR:
2441 /* These don't need any special handling. They are used by
2442 WsControl, and are here to suppress an unnecessary warning. */
2443 break;
2445 default:
2446 /* Netscape tries hard to use bogus ioctl 0x667e */
2447 /* FIXME: 0x667e above is ('f' << 8) | 126, and is a low word of
2448 * FIONBIO (_IOW('f', 126, u_long)), how that should be handled?
2450 WARN("\tunknown WS_IOCTL cmd (%08x)\n", cmd);
2451 break;
2454 fd = get_sock_fd( s, 0, NULL );
2455 if (fd != -1)
2457 if( ioctl(fd, newcmd, (char*)argp ) == 0 )
2459 release_sock_fd( s, fd );
2460 return 0;
2462 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2463 release_sock_fd( s, fd );
2465 return SOCKET_ERROR;
2468 /***********************************************************************
2469 * listen (WS2_32.13)
2471 int WINAPI WS_listen(SOCKET s, int backlog)
2473 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2475 TRACE("socket %04lx, backlog %d\n", s, backlog);
2476 if (fd != -1)
2478 if (listen(fd, backlog) == 0)
2480 release_sock_fd( s, fd );
2481 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
2482 FD_WINE_LISTENING,
2483 FD_CONNECT|FD_WINE_CONNECTED);
2484 return 0;
2486 SetLastError(wsaErrno());
2487 release_sock_fd( s, fd );
2489 return SOCKET_ERROR;
2492 /***********************************************************************
2493 * recv (WS2_32.16)
2495 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
2497 DWORD n, dwFlags = flags;
2498 WSABUF wsabuf;
2500 wsabuf.len = len;
2501 wsabuf.buf = buf;
2503 if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
2504 return SOCKET_ERROR;
2505 else
2506 return n;
2509 /***********************************************************************
2510 * recvfrom (WS2_32.17)
2512 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
2513 struct WS_sockaddr *from, int *fromlen)
2515 DWORD n, dwFlags = flags;
2516 WSABUF wsabuf;
2518 wsabuf.len = len;
2519 wsabuf.buf = buf;
2521 if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL) == SOCKET_ERROR )
2522 return SOCKET_ERROR;
2523 else
2524 return n;
2527 /* allocate a poll array for the corresponding fd sets */
2528 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
2529 const WS_fd_set *exceptfds, int *count_ptr )
2531 unsigned int i, j = 0, count = 0;
2532 struct pollfd *fds;
2534 if (readfds) count += readfds->fd_count;
2535 if (writefds) count += writefds->fd_count;
2536 if (exceptfds) count += exceptfds->fd_count;
2537 *count_ptr = count;
2538 if (!count) return NULL;
2539 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0])))) return NULL;
2540 if (readfds)
2541 for (i = 0; i < readfds->fd_count; i++, j++)
2543 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
2544 fds[j].events = POLLIN;
2545 fds[j].revents = 0;
2547 if (writefds)
2548 for (i = 0; i < writefds->fd_count; i++, j++)
2550 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
2551 fds[j].events = POLLOUT;
2552 fds[j].revents = 0;
2554 if (exceptfds)
2555 for (i = 0; i < exceptfds->fd_count; i++, j++)
2557 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
2558 fds[j].events = POLLHUP;
2559 fds[j].revents = 0;
2561 return fds;
2564 /* release the file descriptor obtained in fd_sets_to_poll */
2565 /* must be called with the original fd_set arrays, before calling get_poll_results */
2566 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
2567 const WS_fd_set *exceptfds, struct pollfd *fds )
2569 unsigned int i, j = 0;
2571 if (readfds)
2573 for (i = 0; i < readfds->fd_count; i++, j++)
2574 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
2576 if (writefds)
2578 for (i = 0; i < writefds->fd_count; i++, j++)
2579 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
2581 if (exceptfds)
2583 for (i = 0; i < exceptfds->fd_count; i++, j++)
2584 if (fds[j].fd != -1)
2586 /* make sure we have a real error before releasing the fd */
2587 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
2588 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
2593 /* map the poll results back into the Windows fd sets */
2594 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
2595 const struct pollfd *fds )
2597 unsigned int i, j = 0, k, total = 0;
2599 if (readfds)
2601 for (i = k = 0; i < readfds->fd_count; i++, j++)
2602 if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
2603 readfds->fd_count = k;
2604 total += k;
2606 if (writefds)
2608 for (i = k = 0; i < writefds->fd_count; i++, j++)
2609 if (fds[j].revents) writefds->fd_array[k++] = writefds->fd_array[i];
2610 writefds->fd_count = k;
2611 total += k;
2613 if (exceptfds)
2615 for (i = k = 0; i < exceptfds->fd_count; i++, j++)
2616 if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
2617 exceptfds->fd_count = k;
2618 total += k;
2620 return total;
2624 /***********************************************************************
2625 * select (WS2_32.18)
2627 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
2628 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
2629 const struct WS_timeval* ws_timeout)
2631 struct pollfd *pollfds;
2632 int count, ret, timeout = -1;
2634 TRACE("read %p, write %p, excp %p timeout %p\n",
2635 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
2637 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )) && count)
2639 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2640 return SOCKET_ERROR;
2643 if (ws_timeout) timeout = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
2645 ret = poll( pollfds, count, timeout );
2646 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
2648 if (ret == -1) SetLastError(wsaErrno());
2649 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
2650 HeapFree( GetProcessHeap(), 0, pollfds );
2651 return ret;
2654 /* helper to send completion messages for client-only i/o operation case */
2655 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
2656 ULONG Information )
2658 NTSTATUS status;
2660 SERVER_START_REQ( add_fd_completion )
2662 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
2663 req->cvalue = CompletionValue;
2664 req->status = CompletionStatus;
2665 req->information = Information;
2666 status = wine_server_call( req );
2668 SERVER_END_REQ;
2672 /***********************************************************************
2673 * send (WS2_32.19)
2675 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
2677 DWORD n;
2678 WSABUF wsabuf;
2680 wsabuf.len = len;
2681 wsabuf.buf = (char*) buf;
2683 if ( WSASendTo( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
2684 return SOCKET_ERROR;
2685 else
2686 return n;
2689 /***********************************************************************
2690 * WSASend (WS2_32.72)
2692 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2693 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2694 LPWSAOVERLAPPED lpOverlapped,
2695 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2697 return WSASendTo( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
2698 NULL, 0, lpOverlapped, lpCompletionRoutine );
2701 /***********************************************************************
2702 * WSASendDisconnect (WS2_32.73)
2704 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
2706 return WS_shutdown( s, SD_SEND );
2710 /***********************************************************************
2711 * WSASendTo (WS2_32.74)
2713 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2714 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2715 const struct WS_sockaddr *to, int tolen,
2716 LPWSAOVERLAPPED lpOverlapped,
2717 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2719 unsigned int i, options;
2720 int n, fd, err;
2721 struct ws2_async *wsa;
2722 int totalLength = 0;
2723 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
2725 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
2726 s, lpBuffers, dwBufferCount, dwFlags,
2727 to, tolen, lpOverlapped, lpCompletionRoutine);
2729 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
2730 TRACE( "fd=%d, options=%x\n", fd, options );
2732 if ( fd == -1 ) return SOCKET_ERROR;
2734 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
2736 err = WSAEFAULT;
2737 goto error;
2740 wsa->hSocket = SOCKET2HANDLE(s);
2741 wsa->addr = (struct WS_sockaddr *)to;
2742 wsa->addrlen.val = tolen;
2743 wsa->flags = dwFlags;
2744 wsa->n_iovecs = dwBufferCount;
2745 wsa->first_iovec = 0;
2746 for ( i = 0; i < dwBufferCount; i++ )
2748 wsa->iovec[i].iov_base = lpBuffers[i].buf;
2749 wsa->iovec[i].iov_len = lpBuffers[i].len;
2750 totalLength += lpBuffers[i].len;
2753 if (!lpNumberOfBytesSent)
2755 err = WSAEFAULT;
2756 goto error;
2759 for (;;)
2761 n = WS2_send( fd, wsa );
2762 if (n != -1 || errno != EINTR) break;
2764 if (n == -1 && errno != EAGAIN)
2766 err = wsaErrno();
2767 if (cvalue) WS_AddCompletion( s, cvalue, err, 0 );
2768 goto error;
2771 if ((lpOverlapped || lpCompletionRoutine) &&
2772 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
2774 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
2776 wsa->user_overlapped = lpOverlapped;
2777 wsa->completion_func = lpCompletionRoutine;
2778 release_sock_fd( s, fd );
2780 if (n == -1)
2782 iosb->u.Status = STATUS_PENDING;
2783 iosb->Information = 0;
2785 SERVER_START_REQ( register_async )
2787 req->type = ASYNC_TYPE_WRITE;
2788 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2789 req->async.callback = wine_server_client_ptr( WS2_async_send );
2790 req->async.iosb = wine_server_client_ptr( iosb );
2791 req->async.arg = wine_server_client_ptr( wsa );
2792 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
2793 req->async.cvalue = cvalue;
2794 err = wine_server_call( req );
2796 SERVER_END_REQ;
2798 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
2799 WSASetLastError( NtStatusToWSAError( err ));
2800 return SOCKET_ERROR;
2803 iosb->u.Status = STATUS_SUCCESS;
2804 iosb->Information = n;
2805 *lpNumberOfBytesSent = n;
2806 if (!wsa->completion_func)
2808 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
2809 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
2810 HeapFree( GetProcessHeap(), 0, wsa );
2812 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
2813 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
2814 WSASetLastError(0);
2815 return 0;
2818 if ( _is_blocking(s) )
2820 /* On a blocking non-overlapped stream socket,
2821 * sending blocks until the entire buffer is sent. */
2822 DWORD timeout_start = GetTickCount();
2824 *lpNumberOfBytesSent = 0;
2826 while (wsa->first_iovec < dwBufferCount)
2828 struct pollfd pfd;
2829 int timeout = GET_SNDTIMEO(fd);
2831 if (n >= 0)
2833 *lpNumberOfBytesSent += n;
2834 while (wsa->first_iovec < dwBufferCount && wsa->iovec[wsa->first_iovec].iov_len <= n)
2835 n -= wsa->iovec[wsa->first_iovec++].iov_len;
2836 if (wsa->first_iovec >= dwBufferCount) break;
2837 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
2838 wsa->iovec[wsa->first_iovec].iov_len -= n;
2841 if (timeout != -1)
2843 timeout -= GetTickCount() - timeout_start;
2844 if (timeout < 0) timeout = 0;
2847 pfd.fd = fd;
2848 pfd.events = POLLOUT;
2850 if (!timeout || !poll( &pfd, 1, timeout ))
2852 err = WSAETIMEDOUT;
2853 goto error; /* msdn says a timeout in send is fatal */
2856 n = WS2_send( fd, wsa );
2857 if (n == -1 && errno != EAGAIN && errno != EINTR)
2859 err = wsaErrno();
2860 goto error;
2864 else /* non-blocking */
2866 if (n < totalLength)
2867 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
2868 if (n == -1)
2870 err = WSAEWOULDBLOCK;
2871 goto error;
2873 *lpNumberOfBytesSent = n;
2876 TRACE(" -> %i bytes\n", *lpNumberOfBytesSent);
2878 HeapFree( GetProcessHeap(), 0, wsa );
2879 release_sock_fd( s, fd );
2880 WSASetLastError(0);
2881 return 0;
2883 error:
2884 HeapFree( GetProcessHeap(), 0, wsa );
2885 release_sock_fd( s, fd );
2886 WARN(" -> ERROR %d\n", err);
2887 WSASetLastError(err);
2888 return SOCKET_ERROR;
2891 /***********************************************************************
2892 * sendto (WS2_32.20)
2894 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
2895 const struct WS_sockaddr *to, int tolen)
2897 DWORD n;
2898 WSABUF wsabuf;
2900 wsabuf.len = len;
2901 wsabuf.buf = (char*) buf;
2903 if ( WSASendTo(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
2904 return SOCKET_ERROR;
2905 else
2906 return n;
2909 /***********************************************************************
2910 * setsockopt (WS2_32.21)
2912 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
2913 const char *optval, int optlen)
2915 int fd;
2916 int woptval;
2917 struct linger linger;
2918 struct timeval tval;
2920 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
2921 s, level, optname, optval, optlen);
2923 /* some broken apps pass the value directly instead of a pointer to it */
2924 if(IS_INTRESOURCE(optval))
2926 SetLastError(WSAEFAULT);
2927 return SOCKET_ERROR;
2930 switch(level)
2932 case WS_SOL_SOCKET:
2933 switch(optname)
2935 /* Some options need some conversion before they can be sent to
2936 * setsockopt. The conversions are done here, then they will fall though
2937 * to the general case. Special options that are not passed to
2938 * setsockopt follow below that.*/
2940 case WS_SO_DONTLINGER:
2941 linger.l_onoff = *((const int*)optval) ? 0: 1;
2942 linger.l_linger = 0;
2943 level = SOL_SOCKET;
2944 optname = SO_LINGER;
2945 optval = (char*)&linger;
2946 optlen = sizeof(struct linger);
2947 break;
2949 case WS_SO_LINGER:
2950 linger.l_onoff = ((LINGER*)optval)->l_onoff;
2951 linger.l_linger = ((LINGER*)optval)->l_linger;
2952 /* FIXME: what is documented behavior if SO_LINGER optval
2953 is null?? */
2954 level = SOL_SOCKET;
2955 optname = SO_LINGER;
2956 optval = (char*)&linger;
2957 optlen = sizeof(struct linger);
2958 break;
2960 case WS_SO_RCVBUF:
2961 if (*(const int*)optval < 2048)
2963 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
2964 return 0;
2966 /* Fall through */
2968 /* The options listed here don't need any special handling. Thanks to
2969 * the conversion happening above, options from there will fall through
2970 * to this, too.*/
2971 case WS_SO_ACCEPTCONN:
2972 case WS_SO_BROADCAST:
2973 case WS_SO_ERROR:
2974 case WS_SO_KEEPALIVE:
2975 case WS_SO_OOBINLINE:
2976 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
2977 * however, using it the BSD way fixes bug 8513 and seems to be what
2978 * most programmers assume, anyway */
2979 case WS_SO_REUSEADDR:
2980 case WS_SO_SNDBUF:
2981 case WS_SO_TYPE:
2982 convert_sockopt(&level, &optname);
2983 break;
2985 /* SO_DEBUG is a privileged operation, ignore it. */
2986 case WS_SO_DEBUG:
2987 TRACE("Ignoring SO_DEBUG\n");
2988 return 0;
2990 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
2991 * socket. According to MSDN, this option is silently ignored.*/
2992 case WS_SO_DONTROUTE:
2993 TRACE("Ignoring SO_DONTROUTE\n");
2994 return 0;
2996 /* Stops two sockets from being bound to the same port. Always happens
2997 * on unix systems, so just drop it. */
2998 case WS_SO_EXCLUSIVEADDRUSE:
2999 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
3000 return 0;
3002 /* SO_OPENTYPE does not require a valid socket handle. */
3003 case WS_SO_OPENTYPE:
3004 if (!optlen || optlen < sizeof(int) || !optval)
3006 SetLastError(WSAEFAULT);
3007 return SOCKET_ERROR;
3009 get_per_thread_data()->opentype = *(const int *)optval;
3010 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
3011 return 0;
3013 #ifdef SO_RCVTIMEO
3014 case WS_SO_RCVTIMEO:
3015 #endif
3016 #ifdef SO_SNDTIMEO
3017 case WS_SO_SNDTIMEO:
3018 #endif
3019 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
3020 if (optval && optlen == sizeof(UINT32)) {
3021 /* WinSock passes milliseconds instead of struct timeval */
3022 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
3023 tval.tv_sec = *(const UINT32*)optval / 1000;
3024 /* min of 500 milliseconds */
3025 if (tval.tv_sec == 0 && tval.tv_usec < 500000)
3026 tval.tv_usec = 500000;
3027 optlen = sizeof(struct timeval);
3028 optval = (char*)&tval;
3029 } else if (optlen == sizeof(struct timeval)) {
3030 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
3031 } else {
3032 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
3033 return 0;
3035 convert_sockopt(&level, &optname);
3036 break;
3037 #endif
3039 default:
3040 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
3041 SetLastError(WSAENOPROTOOPT);
3042 return SOCKET_ERROR;
3044 break; /* case WS_SOL_SOCKET */
3046 #ifdef HAVE_IPX
3047 case NSPROTO_IPX:
3048 switch(optname)
3050 case IPX_PTYPE:
3051 fd = get_sock_fd( s, 0, NULL );
3052 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", *(const int*)optval, fd);
3054 /* We try to set the ipx type on ipx socket level. */
3055 #ifdef SOL_IPX
3056 if(setsockopt(fd, SOL_IPX, IPX_TYPE, optval, optlen) == -1)
3058 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
3059 release_sock_fd( s, fd );
3060 return SOCKET_ERROR;
3062 #else
3064 struct ipx val;
3065 /* Should we retrieve val using a getsockopt call and then
3066 * set the modified one? */
3067 val.ipx_pt = *optval;
3068 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
3070 #endif
3071 release_sock_fd( s, fd );
3072 return 0;
3074 case IPX_FILTERPTYPE:
3075 /* Sets the receive filter packet type, at the moment we don't support it */
3076 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
3077 /* Returning 0 is better for now than returning a SOCKET_ERROR */
3078 return 0;
3080 default:
3081 FIXME("opt_name:%x\n", optname);
3082 return SOCKET_ERROR;
3084 break; /* case NSPROTO_IPX */
3085 #endif
3087 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3088 case WS_IPPROTO_TCP:
3089 switch(optname)
3091 case WS_TCP_NODELAY:
3092 convert_sockopt(&level, &optname);
3093 break;
3094 default:
3095 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
3096 return SOCKET_ERROR;
3098 break;
3100 case WS_IPPROTO_IP:
3101 switch(optname)
3103 case WS_IP_ADD_MEMBERSHIP:
3104 case WS_IP_DROP_MEMBERSHIP:
3105 #ifdef IP_HDRINCL
3106 case WS_IP_HDRINCL:
3107 #endif
3108 case WS_IP_MULTICAST_IF:
3109 case WS_IP_MULTICAST_LOOP:
3110 case WS_IP_MULTICAST_TTL:
3111 case WS_IP_OPTIONS:
3112 case WS_IP_TOS:
3113 case WS_IP_TTL:
3114 convert_sockopt(&level, &optname);
3115 break;
3116 case WS_IP_DONTFRAGMENT:
3117 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
3118 return 0;
3119 default:
3120 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
3121 return SOCKET_ERROR;
3123 break;
3125 default:
3126 FIXME("Unknown level: 0x%08x\n", level);
3127 return SOCKET_ERROR;
3128 } /* end switch(level) */
3130 /* avoid endianness issues if argument is a 16-bit int */
3131 if (optval && optlen < sizeof(int))
3133 woptval= *((const INT16 *) optval);
3134 optval= (char*) &woptval;
3135 optlen=sizeof(int);
3137 fd = get_sock_fd( s, 0, NULL );
3138 if (fd == -1) return SOCKET_ERROR;
3140 if (setsockopt(fd, level, optname, optval, optlen) == 0)
3142 release_sock_fd( s, fd );
3143 return 0;
3145 TRACE("Setting socket error, %d\n", wsaErrno());
3146 SetLastError(wsaErrno());
3147 release_sock_fd( s, fd );
3149 return SOCKET_ERROR;
3152 /***********************************************************************
3153 * shutdown (WS2_32.22)
3155 int WINAPI WS_shutdown(SOCKET s, int how)
3157 int fd, err = WSAENOTSOCK;
3158 unsigned int options, clear_flags = 0;
3160 fd = get_sock_fd( s, 0, &options );
3161 TRACE("socket %04lx, how %i %x\n", s, how, options );
3163 if (fd == -1)
3164 return SOCKET_ERROR;
3166 switch( how )
3168 case 0: /* drop receives */
3169 clear_flags |= FD_READ;
3170 break;
3171 case 1: /* drop sends */
3172 clear_flags |= FD_WRITE;
3173 break;
3174 case 2: /* drop all */
3175 clear_flags |= FD_READ|FD_WRITE;
3176 default:
3177 clear_flags |= FD_WINE_LISTENING;
3180 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
3182 switch ( how )
3184 case SD_RECEIVE:
3185 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3186 break;
3187 case SD_SEND:
3188 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3189 break;
3190 case SD_BOTH:
3191 default:
3192 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3193 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3194 break;
3196 if (err) goto error;
3198 else /* non-overlapped mode */
3200 if ( shutdown( fd, how ) )
3202 err = wsaErrno();
3203 goto error;
3207 release_sock_fd( s, fd );
3208 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3209 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
3210 return 0;
3212 error:
3213 release_sock_fd( s, fd );
3214 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3215 WSASetLastError( err );
3216 return SOCKET_ERROR;
3219 /***********************************************************************
3220 * socket (WS2_32.23)
3222 SOCKET WINAPI WS_socket(int af, int type, int protocol)
3224 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
3226 return WSASocketA( af, type, protocol, NULL, 0,
3227 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
3231 /***********************************************************************
3232 * gethostbyaddr (WS2_32.51)
3234 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
3236 struct WS_hostent *retval = NULL;
3237 struct hostent* host;
3239 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3240 char *extrabuf;
3241 int ebufsize=1024;
3242 struct hostent hostentry;
3243 int locerr=ENOBUFS;
3244 host = NULL;
3245 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3246 while(extrabuf) {
3247 int res = gethostbyaddr_r(addr, len, type,
3248 &hostentry, extrabuf, ebufsize, &host, &locerr);
3249 if( res != ERANGE) break;
3250 ebufsize *=2;
3251 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3253 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3254 #else
3255 EnterCriticalSection( &csWSgetXXXbyYYY );
3256 host = gethostbyaddr(addr, len, type);
3257 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3258 #endif
3259 if( host != NULL ) retval = WS_dup_he(host);
3260 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3261 HeapFree(GetProcessHeap(),0,extrabuf);
3262 #else
3263 LeaveCriticalSection( &csWSgetXXXbyYYY );
3264 #endif
3265 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
3266 return retval;
3269 /***********************************************************************
3270 * gethostbyname (WS2_32.52)
3272 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
3274 struct WS_hostent *retval = NULL;
3275 struct hostent* host;
3276 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3277 char *extrabuf;
3278 int ebufsize=1024;
3279 struct hostent hostentry;
3280 int locerr = ENOBUFS;
3281 #endif
3282 char buf[100];
3283 if( !name || !name[0]) {
3284 name = buf;
3285 if( gethostname( buf, 100) == -1) {
3286 SetLastError( WSAENOBUFS); /* appropriate ? */
3287 return retval;
3290 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3291 host = NULL;
3292 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3293 while(extrabuf) {
3294 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
3295 if( res != ERANGE) break;
3296 ebufsize *=2;
3297 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3299 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3300 #else
3301 EnterCriticalSection( &csWSgetXXXbyYYY );
3302 host = gethostbyname(name);
3303 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3304 #endif
3305 if (host) retval = WS_dup_he(host);
3306 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3307 HeapFree(GetProcessHeap(),0,extrabuf);
3308 #else
3309 LeaveCriticalSection( &csWSgetXXXbyYYY );
3310 #endif
3311 if (retval && retval->h_addr_list[0][0] == 127 &&
3312 strcmp(name, "localhost") != 0)
3314 /* hostname != "localhost" but has loopback address. replace by our
3315 * special address.*/
3316 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
3318 TRACE( "%s ret %p\n", debugstr_a(name), retval );
3319 return retval;
3323 /***********************************************************************
3324 * getprotobyname (WS2_32.53)
3326 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
3328 struct WS_protoent* retval = NULL;
3329 #ifdef HAVE_GETPROTOBYNAME
3330 struct protoent* proto;
3331 EnterCriticalSection( &csWSgetXXXbyYYY );
3332 if( (proto = getprotobyname(name)) != NULL )
3334 retval = WS_dup_pe(proto);
3336 else {
3337 MESSAGE("protocol %s not found; You might want to add "
3338 "this to /etc/protocols\n", debugstr_a(name) );
3339 SetLastError(WSANO_DATA);
3341 LeaveCriticalSection( &csWSgetXXXbyYYY );
3342 #endif
3343 TRACE( "%s ret %p\n", debugstr_a(name), retval );
3344 return retval;
3348 /***********************************************************************
3349 * getprotobynumber (WS2_32.54)
3351 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
3353 struct WS_protoent* retval = NULL;
3354 #ifdef HAVE_GETPROTOBYNUMBER
3355 struct protoent* proto;
3356 EnterCriticalSection( &csWSgetXXXbyYYY );
3357 if( (proto = getprotobynumber(number)) != NULL )
3359 retval = WS_dup_pe(proto);
3361 else {
3362 MESSAGE("protocol number %d not found; You might want to add "
3363 "this to /etc/protocols\n", number );
3364 SetLastError(WSANO_DATA);
3366 LeaveCriticalSection( &csWSgetXXXbyYYY );
3367 #endif
3368 TRACE("%i ret %p\n", number, retval);
3369 return retval;
3373 /***********************************************************************
3374 * getservbyname (WS2_32.55)
3376 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
3378 struct WS_servent* retval = NULL;
3379 struct servent* serv;
3380 char *name_str;
3381 char *proto_str = NULL;
3383 if (!(name_str = strdup_lower(name))) return NULL;
3385 if (proto && *proto)
3387 if (!(proto_str = strdup_lower(proto)))
3389 HeapFree( GetProcessHeap(), 0, name_str );
3390 return NULL;
3394 EnterCriticalSection( &csWSgetXXXbyYYY );
3395 serv = getservbyname(name_str, proto_str);
3396 if( serv != NULL )
3398 retval = WS_dup_se(serv);
3400 else SetLastError(WSANO_DATA);
3401 LeaveCriticalSection( &csWSgetXXXbyYYY );
3402 HeapFree( GetProcessHeap(), 0, proto_str );
3403 HeapFree( GetProcessHeap(), 0, name_str );
3404 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
3405 return retval;
3408 /***********************************************************************
3409 * freeaddrinfo (WS2_32.@)
3411 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
3413 while (res) {
3414 struct WS_addrinfo *next;
3416 HeapFree(GetProcessHeap(),0,res->ai_canonname);
3417 HeapFree(GetProcessHeap(),0,res->ai_addr);
3418 next = res->ai_next;
3419 HeapFree(GetProcessHeap(),0,res);
3420 res = next;
3424 /* helper functions for getaddrinfo()/getnameinfo() */
3425 static int convert_aiflag_w2u(int winflags) {
3426 unsigned int i;
3427 int unixflags = 0;
3429 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
3430 if (ws_aiflag_map[i][0] & winflags) {
3431 unixflags |= ws_aiflag_map[i][1];
3432 winflags &= ~ws_aiflag_map[i][0];
3434 if (winflags)
3435 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
3436 return unixflags;
3439 static int convert_niflag_w2u(int winflags) {
3440 unsigned int i;
3441 int unixflags = 0;
3443 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
3444 if (ws_niflag_map[i][0] & winflags) {
3445 unixflags |= ws_niflag_map[i][1];
3446 winflags &= ~ws_niflag_map[i][0];
3448 if (winflags)
3449 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
3450 return unixflags;
3453 static int convert_aiflag_u2w(int unixflags) {
3454 unsigned int i;
3455 int winflags = 0;
3457 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
3458 if (ws_aiflag_map[i][1] & unixflags) {
3459 winflags |= ws_aiflag_map[i][0];
3460 unixflags &= ~ws_aiflag_map[i][1];
3462 if (unixflags) /* will warn usually */
3463 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
3464 return winflags;
3467 static int convert_eai_u2w(int unixret) {
3468 int i;
3470 for (i=0;ws_eai_map[i][0];i++)
3471 if (ws_eai_map[i][1] == unixret)
3472 return ws_eai_map[i][0];
3473 return unixret;
3476 /***********************************************************************
3477 * getaddrinfo (WS2_32.@)
3479 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
3481 #ifdef HAVE_GETADDRINFO
3482 struct addrinfo *unixaires = NULL;
3483 int result;
3484 struct addrinfo unixhints, *punixhints = NULL;
3485 CHAR *node = NULL, *serv = NULL;
3487 if (nodename)
3488 if (!(node = strdup_lower(nodename))) return WSA_NOT_ENOUGH_MEMORY;
3490 if (servname) {
3491 if (!(serv = strdup_lower(servname))) {
3492 HeapFree(GetProcessHeap(), 0, node);
3493 return WSA_NOT_ENOUGH_MEMORY;
3497 if (hints) {
3498 punixhints = &unixhints;
3500 memset(&unixhints, 0, sizeof(unixhints));
3501 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
3502 if (hints->ai_family == 0) /* wildcard, specific to getaddrinfo() */
3503 punixhints->ai_family = 0;
3504 else
3505 punixhints->ai_family = convert_af_w2u(hints->ai_family);
3506 if (hints->ai_socktype == 0) /* wildcard, specific to getaddrinfo() */
3507 punixhints->ai_socktype = 0;
3508 else
3509 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
3510 if (hints->ai_protocol == 0) /* wildcard, specific to getaddrinfo() */
3511 punixhints->ai_protocol = 0;
3512 else
3513 punixhints->ai_protocol = convert_proto_w2u(hints->ai_protocol);
3516 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
3517 result = getaddrinfo(nodename, servname, punixhints, &unixaires);
3519 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
3521 HeapFree(GetProcessHeap(), 0, node);
3522 HeapFree(GetProcessHeap(), 0, serv);
3524 if (!result) {
3525 struct addrinfo *xuai = unixaires;
3526 struct WS_addrinfo **xai = res;
3528 *xai = NULL;
3529 while (xuai) {
3530 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
3531 int len;
3533 if (!ai)
3534 goto outofmem;
3536 *xai = ai;xai = &ai->ai_next;
3537 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
3538 ai->ai_family = convert_af_u2w(xuai->ai_family);
3539 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
3540 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
3541 if (xuai->ai_canonname) {
3542 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
3543 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
3544 if (!ai->ai_canonname)
3545 goto outofmem;
3546 strcpy(ai->ai_canonname,xuai->ai_canonname);
3548 len = xuai->ai_addrlen;
3549 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
3550 if (!ai->ai_addr)
3551 goto outofmem;
3552 ai->ai_addrlen = len;
3553 do {
3554 int winlen = ai->ai_addrlen;
3556 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
3557 ai->ai_addrlen = winlen;
3558 break;
3560 len = 2*len;
3561 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
3562 if (!ai->ai_addr)
3563 goto outofmem;
3564 ai->ai_addrlen = len;
3565 } while (1);
3566 xuai = xuai->ai_next;
3568 freeaddrinfo(unixaires);
3569 } else {
3570 result = convert_eai_u2w(result);
3571 *res = NULL;
3573 return result;
3575 outofmem:
3576 if (*res) WS_freeaddrinfo(*res);
3577 if (unixaires) freeaddrinfo(unixaires);
3578 *res = NULL;
3579 return WSA_NOT_ENOUGH_MEMORY;
3580 #else
3581 FIXME("getaddrinfo() failed, not found during buildtime.\n");
3582 return EAI_FAIL;
3583 #endif
3586 /***********************************************************************
3587 * GetAddrInfoW (WS2_32.@)
3589 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
3591 FIXME("empty stub!\n");
3592 return EAI_FAIL;
3595 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
3596 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
3598 #ifdef HAVE_GETNAMEINFO
3599 int ret;
3600 union generic_unix_sockaddr sa_u;
3601 unsigned int size;
3603 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
3604 serv, servlen, flags);
3606 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
3607 if (!size)
3609 WSASetLastError(WSAEFAULT);
3610 return WSA_NOT_ENOUGH_MEMORY;
3612 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
3613 return convert_eai_u2w(ret);
3614 #else
3615 FIXME("getnameinfo() failed, not found during buildtime.\n");
3616 return EAI_FAIL;
3617 #endif
3620 /***********************************************************************
3621 * getservbyport (WS2_32.56)
3623 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
3625 struct WS_servent* retval = NULL;
3626 #ifdef HAVE_GETSERVBYPORT
3627 struct servent* serv;
3628 char *proto_str = NULL;
3630 if (proto && *proto)
3632 if (!(proto_str = strdup_lower(proto))) return NULL;
3634 EnterCriticalSection( &csWSgetXXXbyYYY );
3635 if( (serv = getservbyport(port, proto_str)) != NULL ) {
3636 retval = WS_dup_se(serv);
3638 else SetLastError(WSANO_DATA);
3639 LeaveCriticalSection( &csWSgetXXXbyYYY );
3640 HeapFree( GetProcessHeap(), 0, proto_str );
3641 #endif
3642 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
3643 return retval;
3647 /***********************************************************************
3648 * gethostname (WS2_32.57)
3650 int WINAPI WS_gethostname(char *name, int namelen)
3652 TRACE("name %p, len %d\n", name, namelen);
3654 if (gethostname(name, namelen) == 0)
3656 TRACE("<- '%s'\n", name);
3657 return 0;
3659 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
3660 TRACE("<- ERROR !\n");
3661 return SOCKET_ERROR;
3665 /* ------------------------------------- Windows sockets extensions -- *
3667 * ------------------------------------------------------------------- */
3669 /***********************************************************************
3670 * WSAEnumNetworkEvents (WS2_32.36)
3672 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
3674 int ret;
3676 TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
3678 SERVER_START_REQ( get_socket_event )
3680 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
3681 req->service = TRUE;
3682 req->c_event = wine_server_obj_handle( hEvent );
3683 wine_server_set_reply( req, lpEvent->iErrorCode, sizeof(lpEvent->iErrorCode) );
3684 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
3686 SERVER_END_REQ;
3687 if (!ret) return 0;
3688 SetLastError(WSAEINVAL);
3689 return SOCKET_ERROR;
3692 /***********************************************************************
3693 * WSAEventSelect (WS2_32.39)
3695 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
3697 int ret;
3699 TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
3701 SERVER_START_REQ( set_socket_event )
3703 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
3704 req->mask = lEvent;
3705 req->event = wine_server_obj_handle( hEvent );
3706 req->window = 0;
3707 req->msg = 0;
3708 ret = wine_server_call( req );
3710 SERVER_END_REQ;
3711 if (!ret) return 0;
3712 SetLastError(WSAEINVAL);
3713 return SOCKET_ERROR;
3716 /**********************************************************************
3717 * WSAGetOverlappedResult (WS2_32.40)
3719 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
3720 LPDWORD lpcbTransfer, BOOL fWait,
3721 LPDWORD lpdwFlags )
3723 NTSTATUS status;
3725 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
3726 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
3728 if ( lpOverlapped == NULL )
3730 ERR( "Invalid pointer\n" );
3731 WSASetLastError(WSA_INVALID_PARAMETER);
3732 return FALSE;
3735 status = lpOverlapped->Internal;
3736 if (status == STATUS_PENDING)
3738 if (!fWait)
3740 SetLastError( WSA_IO_INCOMPLETE );
3741 return FALSE;
3744 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
3745 INFINITE ) == WAIT_FAILED)
3746 return FALSE;
3747 status = lpOverlapped->Internal;
3750 if ( lpcbTransfer )
3751 *lpcbTransfer = lpOverlapped->InternalHigh;
3753 if ( lpdwFlags )
3754 *lpdwFlags = lpOverlapped->u.s.Offset;
3756 if (status) SetLastError( RtlNtStatusToDosError(status) );
3757 return !status;
3761 /***********************************************************************
3762 * WSAAsyncSelect (WS2_32.101)
3764 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
3766 int ret;
3768 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
3770 SERVER_START_REQ( set_socket_event )
3772 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
3773 req->mask = lEvent;
3774 req->event = 0;
3775 req->window = wine_server_user_handle( hWnd );
3776 req->msg = uMsg;
3777 ret = wine_server_call( req );
3779 SERVER_END_REQ;
3780 if (!ret) return 0;
3781 SetLastError(WSAEINVAL);
3782 return SOCKET_ERROR;
3785 /***********************************************************************
3786 * WSACreateEvent (WS2_32.31)
3789 WSAEVENT WINAPI WSACreateEvent(void)
3791 /* Create a manual-reset event, with initial state: unsignaled */
3792 TRACE("\n");
3794 return CreateEventW(NULL, TRUE, FALSE, NULL);
3797 /***********************************************************************
3798 * WSACloseEvent (WS2_32.29)
3801 BOOL WINAPI WSACloseEvent(WSAEVENT event)
3803 TRACE ("event=%p\n", event);
3805 return CloseHandle(event);
3808 /***********************************************************************
3809 * WSASocketA (WS2_32.78)
3812 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
3813 LPWSAPROTOCOL_INFOA lpProtocolInfo,
3814 GROUP g, DWORD dwFlags)
3816 INT len;
3817 WSAPROTOCOL_INFOW info;
3819 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
3820 af, type, protocol, lpProtocolInfo, g, dwFlags);
3822 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
3824 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
3825 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
3826 info.szProtocol, WSAPROTOCOL_LEN + 1);
3828 if (!len)
3830 WSASetLastError( WSAEINVAL);
3831 return SOCKET_ERROR;
3834 return WSASocketW(af, type, protocol, &info, g, dwFlags);
3837 /***********************************************************************
3838 * WSASocketW (WS2_32.79)
3841 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
3842 LPWSAPROTOCOL_INFOW lpProtocolInfo,
3843 GROUP g, DWORD dwFlags)
3845 SOCKET ret;
3848 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
3849 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
3852 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
3853 af, type, protocol, lpProtocolInfo, g, dwFlags );
3855 /* hack for WSADuplicateSocket */
3856 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
3857 ret = lpProtocolInfo->dwCatalogEntryId;
3858 TRACE("\tgot duplicate %04lx\n", ret);
3859 return ret;
3862 /* convert the socket family and type */
3863 af = convert_af_w2u(af);
3864 type = convert_socktype_w2u(type);
3866 if (lpProtocolInfo)
3868 if (af == FROM_PROTOCOL_INFO)
3869 af = lpProtocolInfo->iAddressFamily;
3870 if (type == FROM_PROTOCOL_INFO)
3871 type = lpProtocolInfo->iSocketType;
3872 if (protocol == FROM_PROTOCOL_INFO)
3873 protocol = lpProtocolInfo->iProtocol;
3876 if ( af == AF_UNSPEC) /* did they not specify the address family? */
3877 switch(protocol)
3879 case IPPROTO_TCP:
3880 if (type == SOCK_STREAM) { af = AF_INET; break; }
3881 case IPPROTO_UDP:
3882 if (type == SOCK_DGRAM) { af = AF_INET; break; }
3883 default: SetLastError(WSAEPROTOTYPE); return INVALID_SOCKET;
3886 SERVER_START_REQ( create_socket )
3888 req->family = af;
3889 req->type = type;
3890 req->protocol = protocol;
3891 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
3892 req->attributes = OBJ_INHERIT;
3893 req->flags = dwFlags;
3894 set_error( wine_server_call( req ) );
3895 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
3897 SERVER_END_REQ;
3898 if (ret)
3900 TRACE("\tcreated %04lx\n", ret );
3901 return ret;
3904 if (GetLastError() == WSAEACCES) /* raw socket denied */
3906 if (type == SOCK_RAW)
3907 MESSAGE("WARNING: Trying to create a socket of type SOCK_RAW, this"
3908 " will fail unless you have special permissions.\n");
3909 else
3910 MESSAGE("WS_SOCKET: Failed to create socket, this requires"
3911 " special permissions.\n");
3912 SetLastError(WSAESOCKTNOSUPPORT);
3915 WARN("\t\tfailed!\n");
3916 return INVALID_SOCKET;
3919 /***********************************************************************
3920 * WSAJoinLeaf (WS2_32.58)
3923 SOCKET WINAPI WSAJoinLeaf(
3924 SOCKET s,
3925 const struct WS_sockaddr *addr,
3926 int addrlen,
3927 LPWSABUF lpCallerData,
3928 LPWSABUF lpCalleeData,
3929 LPQOS lpSQOS,
3930 LPQOS lpGQOS,
3931 DWORD dwFlags)
3933 FIXME("stub.\n");
3934 return INVALID_SOCKET;
3937 /***********************************************************************
3938 * __WSAFDIsSet (WS2_32.151)
3940 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
3942 int i = set->fd_count;
3944 TRACE("(%ld,%p(%i))\n", s, set, i);
3946 while (i--)
3947 if (set->fd_array[i] == s) return 1;
3948 return 0;
3951 /***********************************************************************
3952 * WSAIsBlocking (WINSOCK.114)
3953 * WSAIsBlocking (WS2_32.114)
3955 BOOL WINAPI WSAIsBlocking(void)
3957 /* By default WinSock should set all its sockets to non-blocking mode
3958 * and poll in PeekMessage loop when processing "blocking" ones. This
3959 * function is supposed to tell if the program is in this loop. Our
3960 * blocking calls are truly blocking so we always return FALSE.
3962 * Note: It is allowed to call this function without prior WSAStartup().
3965 TRACE("\n");
3966 return FALSE;
3969 /***********************************************************************
3970 * WSACancelBlockingCall (WINSOCK.113)
3971 * WSACancelBlockingCall (WS2_32.113)
3973 INT WINAPI WSACancelBlockingCall(void)
3975 TRACE("\n");
3976 return 0;
3979 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
3981 FIXME("How was this called?\n");
3982 return x();
3986 /***********************************************************************
3987 * WSASetBlockingHook (WS2_32.109)
3989 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
3991 FARPROC prev = blocking_hook;
3992 blocking_hook = lpBlockFunc;
3993 TRACE("hook %p\n", lpBlockFunc);
3994 return prev;
3998 /***********************************************************************
3999 * WSAUnhookBlockingHook (WS2_32.110)
4001 INT WINAPI WSAUnhookBlockingHook(void)
4003 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
4004 return 0;
4008 /* ----------------------------------- end of API stuff */
4010 /* ----------------------------------- helper functions -
4012 * TODO: Merge WS_dup_..() stuff into one function that
4013 * would operate with a generic structure containing internal
4014 * pointers (via a template of some kind).
4017 static int list_size(char** l, int item_size)
4019 int i,j = 0;
4020 if(l)
4021 { for(i=0;l[i];i++)
4022 j += (item_size) ? item_size : strlen(l[i]) + 1;
4023 j += (i + 1) * sizeof(char*); }
4024 return j;
4027 static int list_dup(char** l_src, char** l_to, int item_size)
4029 char *p;
4030 int i;
4032 for (i = 0; l_src[i]; i++) ;
4033 p = (char *)(l_to + i + 1);
4034 for (i = 0; l_src[i]; i++)
4036 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
4037 memcpy(p, l_src[i], count);
4038 l_to[i] = p;
4039 p += count;
4041 l_to[i] = NULL;
4042 return p - (char *)l_to;
4045 /* ----- hostent */
4047 /* duplicate hostent entry
4048 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
4049 * Ditto for protoent and servent.
4051 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
4053 char *p;
4054 struct WS_hostent *p_to;
4056 int size = (sizeof(*p_he) +
4057 strlen(p_he->h_name) + 1 +
4058 list_size(p_he->h_aliases, 0) +
4059 list_size(p_he->h_addr_list, p_he->h_length));
4061 if (!(p_to = check_buffer_he(size))) return NULL;
4062 p_to->h_addrtype = p_he->h_addrtype;
4063 p_to->h_length = p_he->h_length;
4065 p = (char *)(p_to + 1);
4066 p_to->h_name = p;
4067 strcpy(p, p_he->h_name);
4068 p += strlen(p) + 1;
4070 p_to->h_aliases = (char **)p;
4071 p += list_dup(p_he->h_aliases, p_to->h_aliases, 0);
4073 p_to->h_addr_list = (char **)p;
4074 list_dup(p_he->h_addr_list, p_to->h_addr_list, p_he->h_length);
4075 return p_to;
4078 /* ----- protoent */
4080 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
4082 char *p;
4083 struct WS_protoent *p_to;
4085 int size = (sizeof(*p_pe) +
4086 strlen(p_pe->p_name) + 1 +
4087 list_size(p_pe->p_aliases, 0));
4089 if (!(p_to = check_buffer_pe(size))) return NULL;
4090 p_to->p_proto = p_pe->p_proto;
4092 p = (char *)(p_to + 1);
4093 p_to->p_name = p;
4094 strcpy(p, p_pe->p_name);
4095 p += strlen(p) + 1;
4097 p_to->p_aliases = (char **)p;
4098 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
4099 return p_to;
4102 /* ----- servent */
4104 static struct WS_servent *WS_dup_se(const struct servent* p_se)
4106 char *p;
4107 struct WS_servent *p_to;
4109 int size = (sizeof(*p_se) +
4110 strlen(p_se->s_proto) + 1 +
4111 strlen(p_se->s_name) + 1 +
4112 list_size(p_se->s_aliases, 0));
4114 if (!(p_to = check_buffer_se(size))) return NULL;
4115 p_to->s_port = p_se->s_port;
4117 p = (char *)(p_to + 1);
4118 p_to->s_name = p;
4119 strcpy(p, p_se->s_name);
4120 p += strlen(p) + 1;
4122 p_to->s_proto = p;
4123 strcpy(p, p_se->s_proto);
4124 p += strlen(p) + 1;
4126 p_to->s_aliases = (char **)p;
4127 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
4128 return p_to;
4131 /* ----------------------------------- error handling */
4133 UINT wsaErrno(void)
4135 int loc_errno = errno;
4136 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
4138 switch(loc_errno)
4140 case EINTR: return WSAEINTR;
4141 case EBADF: return WSAEBADF;
4142 case EPERM:
4143 case EACCES: return WSAEACCES;
4144 case EFAULT: return WSAEFAULT;
4145 case EINVAL: return WSAEINVAL;
4146 case EMFILE: return WSAEMFILE;
4147 case EWOULDBLOCK: return WSAEWOULDBLOCK;
4148 case EINPROGRESS: return WSAEINPROGRESS;
4149 case EALREADY: return WSAEALREADY;
4150 case ENOTSOCK: return WSAENOTSOCK;
4151 case EDESTADDRREQ: return WSAEDESTADDRREQ;
4152 case EMSGSIZE: return WSAEMSGSIZE;
4153 case EPROTOTYPE: return WSAEPROTOTYPE;
4154 case ENOPROTOOPT: return WSAENOPROTOOPT;
4155 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
4156 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
4157 case EOPNOTSUPP: return WSAEOPNOTSUPP;
4158 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
4159 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
4160 case EADDRINUSE: return WSAEADDRINUSE;
4161 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
4162 case ENETDOWN: return WSAENETDOWN;
4163 case ENETUNREACH: return WSAENETUNREACH;
4164 case ENETRESET: return WSAENETRESET;
4165 case ECONNABORTED: return WSAECONNABORTED;
4166 case EPIPE:
4167 case ECONNRESET: return WSAECONNRESET;
4168 case ENOBUFS: return WSAENOBUFS;
4169 case EISCONN: return WSAEISCONN;
4170 case ENOTCONN: return WSAENOTCONN;
4171 case ESHUTDOWN: return WSAESHUTDOWN;
4172 case ETOOMANYREFS: return WSAETOOMANYREFS;
4173 case ETIMEDOUT: return WSAETIMEDOUT;
4174 case ECONNREFUSED: return WSAECONNREFUSED;
4175 case ELOOP: return WSAELOOP;
4176 case ENAMETOOLONG: return WSAENAMETOOLONG;
4177 case EHOSTDOWN: return WSAEHOSTDOWN;
4178 case EHOSTUNREACH: return WSAEHOSTUNREACH;
4179 case ENOTEMPTY: return WSAENOTEMPTY;
4180 #ifdef EPROCLIM
4181 case EPROCLIM: return WSAEPROCLIM;
4182 #endif
4183 #ifdef EUSERS
4184 case EUSERS: return WSAEUSERS;
4185 #endif
4186 #ifdef EDQUOT
4187 case EDQUOT: return WSAEDQUOT;
4188 #endif
4189 #ifdef ESTALE
4190 case ESTALE: return WSAESTALE;
4191 #endif
4192 #ifdef EREMOTE
4193 case EREMOTE: return WSAEREMOTE;
4194 #endif
4196 /* just in case we ever get here and there are no problems */
4197 case 0: return 0;
4198 default:
4199 WARN("Unknown errno %d!\n", loc_errno);
4200 return WSAEOPNOTSUPP;
4204 UINT wsaHerrno(int loc_errno)
4207 WARN("h_errno %d.\n", loc_errno);
4209 switch(loc_errno)
4211 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
4212 case TRY_AGAIN: return WSATRY_AGAIN;
4213 case NO_RECOVERY: return WSANO_RECOVERY;
4214 case NO_DATA: return WSANO_DATA;
4215 case ENOBUFS: return WSAENOBUFS;
4217 case 0: return 0;
4218 default:
4219 WARN("Unknown h_errno %d!\n", loc_errno);
4220 return WSAEOPNOTSUPP;
4225 /***********************************************************************
4226 * WSARecv (WS2_32.67)
4228 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4229 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
4230 LPWSAOVERLAPPED lpOverlapped,
4231 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
4233 return WSARecvFrom(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
4234 NULL, NULL, lpOverlapped, lpCompletionRoutine);
4237 /***********************************************************************
4238 * WSARecvFrom (WS2_32.69)
4240 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4241 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
4242 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
4243 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4246 unsigned int i, options;
4247 int n, fd, err;
4248 struct ws2_async *wsa;
4249 DWORD timeout_start = GetTickCount();
4250 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
4252 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
4253 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
4254 (lpFromlen ? *lpFromlen : -1),
4255 lpOverlapped, lpCompletionRoutine);
4257 fd = get_sock_fd( s, FILE_READ_DATA, &options );
4258 TRACE( "fd=%d, options=%x\n", fd, options );
4260 if (fd == -1) return SOCKET_ERROR;
4262 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
4264 err = WSAEFAULT;
4265 goto error;
4268 wsa->hSocket = SOCKET2HANDLE(s);
4269 wsa->flags = *lpFlags;
4270 wsa->addr = lpFrom;
4271 wsa->addrlen.ptr = lpFromlen;
4272 wsa->n_iovecs = dwBufferCount;
4273 wsa->first_iovec = 0;
4274 for (i = 0; i < dwBufferCount; i++)
4276 wsa->iovec[i].iov_base = lpBuffers[i].buf;
4277 wsa->iovec[i].iov_len = lpBuffers[i].len;
4280 for (;;)
4282 n = WS2_recv( fd, wsa );
4283 if (n == -1)
4285 if (errno == EINTR) continue;
4286 if (errno != EAGAIN)
4288 err = wsaErrno();
4289 if (cvalue) WS_AddCompletion( s, cvalue, err, 0 );
4290 goto error;
4293 else
4294 *lpNumberOfBytesRecvd = n;
4296 if ((lpOverlapped || lpCompletionRoutine) &&
4297 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
4299 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
4301 wsa->user_overlapped = lpOverlapped;
4302 wsa->completion_func = lpCompletionRoutine;
4303 release_sock_fd( s, fd );
4305 if (n == -1)
4307 iosb->u.Status = STATUS_PENDING;
4308 iosb->Information = 0;
4310 SERVER_START_REQ( register_async )
4312 req->type = ASYNC_TYPE_READ;
4313 req->async.handle = wine_server_obj_handle( wsa->hSocket );
4314 req->async.callback = wine_server_client_ptr( WS2_async_recv );
4315 req->async.iosb = wine_server_client_ptr( iosb );
4316 req->async.arg = wine_server_client_ptr( wsa );
4317 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
4318 req->async.cvalue = cvalue;
4319 err = wine_server_call( req );
4321 SERVER_END_REQ;
4323 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
4324 WSASetLastError( NtStatusToWSAError( err ));
4325 return SOCKET_ERROR;
4328 iosb->u.Status = STATUS_SUCCESS;
4329 iosb->Information = n;
4330 if (!wsa->completion_func)
4332 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
4333 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
4334 HeapFree( GetProcessHeap(), 0, wsa );
4336 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
4337 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
4338 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4339 return 0;
4342 if (n != -1) break;
4344 if ( _is_blocking(s) )
4346 struct pollfd pfd;
4347 int timeout = GET_RCVTIMEO(fd);
4348 if (timeout != -1)
4350 timeout -= GetTickCount() - timeout_start;
4351 if (timeout < 0) timeout = 0;
4354 pfd.fd = fd;
4355 pfd.events = POLLIN;
4356 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
4358 if (!timeout || !poll( &pfd, 1, timeout ))
4360 err = WSAETIMEDOUT;
4361 /* a timeout is not fatal */
4362 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4363 goto error;
4366 else
4368 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4369 err = WSAEWOULDBLOCK;
4370 goto error;
4374 TRACE(" -> %i bytes\n", n);
4375 HeapFree( GetProcessHeap(), 0, wsa );
4376 release_sock_fd( s, fd );
4377 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4379 return 0;
4381 error:
4382 HeapFree( GetProcessHeap(), 0, wsa );
4383 release_sock_fd( s, fd );
4384 WARN(" -> ERROR %d\n", err);
4385 WSASetLastError( err );
4386 return SOCKET_ERROR;
4389 /***********************************************************************
4390 * WSCInstallProvider (WS2_32.88)
4392 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
4393 LPCWSTR lpszProviderDllPath,
4394 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
4395 DWORD dwNumberOfEntries,
4396 LPINT lpErrno )
4398 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
4399 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
4400 dwNumberOfEntries, lpErrno);
4401 *lpErrno = 0;
4402 return 0;
4406 /***********************************************************************
4407 * WSCDeinstallProvider (WS2_32.83)
4409 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
4411 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
4412 *lpErrno = 0;
4413 return 0;
4417 /***********************************************************************
4418 * WSAAccept (WS2_32.26)
4420 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
4421 LPCONDITIONPROC lpfnCondition, DWORD dwCallbackData)
4424 int ret = 0, size = 0;
4425 WSABUF CallerId, CallerData, CalleeId, CalleeData;
4426 /* QOS SQOS, GQOS; */
4427 GROUP g;
4428 SOCKET cs;
4429 SOCKADDR src_addr, dst_addr;
4431 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %d\n",
4432 s, addr, addrlen, lpfnCondition, dwCallbackData);
4435 size = sizeof(src_addr);
4436 cs = WS_accept(s, &src_addr, &size);
4438 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
4440 if (!lpfnCondition) return cs;
4442 CallerId.buf = (char *)&src_addr;
4443 CallerId.len = sizeof(src_addr);
4445 CallerData.buf = NULL;
4446 CallerData.len = 0;
4448 WS_getsockname(cs, &dst_addr, &size);
4450 CalleeId.buf = (char *)&dst_addr;
4451 CalleeId.len = sizeof(dst_addr);
4454 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
4455 &CalleeId, &CalleeData, &g, dwCallbackData);
4457 switch (ret)
4459 case CF_ACCEPT:
4460 if (addr && addrlen)
4461 addr = memcpy(addr, &src_addr, (*addrlen > size) ? size : *addrlen );
4462 return cs;
4463 case CF_DEFER:
4464 SERVER_START_REQ( set_socket_deferred )
4466 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
4467 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
4468 if ( !wine_server_call_err ( req ) )
4470 SetLastError( WSATRY_AGAIN );
4471 WS_closesocket( cs );
4474 SERVER_END_REQ;
4475 return SOCKET_ERROR;
4476 case CF_REJECT:
4477 WS_closesocket(cs);
4478 SetLastError(WSAECONNREFUSED);
4479 return SOCKET_ERROR;
4480 default:
4481 FIXME("Unknown return type from Condition function\n");
4482 SetLastError(WSAENOTSOCK);
4483 return SOCKET_ERROR;
4487 /***********************************************************************
4488 * WSADuplicateSocketA (WS2_32.32)
4490 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
4492 HANDLE hProcess;
4494 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
4495 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
4496 /* FIXME: WS_getsockopt(s, WS_SOL_SOCKET, SO_PROTOCOL_INFO, lpProtocolInfo, sizeof(*lpProtocolInfo)); */
4497 /* I don't know what the real Windoze does next, this is a hack */
4498 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
4499 * the target use the global duplicate, or we could copy a reference to us to the structure
4500 * and let the target duplicate it from us, but let's do it as simple as possible */
4501 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
4502 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
4503 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
4504 0, FALSE, DUPLICATE_SAME_ACCESS);
4505 CloseHandle(hProcess);
4506 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
4507 return 0;
4510 /***********************************************************************
4511 * WSADuplicateSocketW (WS2_32.33)
4513 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
4515 HANDLE hProcess;
4517 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
4519 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
4520 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
4521 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
4522 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
4523 0, FALSE, DUPLICATE_SAME_ACCESS);
4524 CloseHandle(hProcess);
4525 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
4526 return 0;
4529 /***********************************************************************
4530 * WSAInstallServiceClassA (WS2_32.48)
4532 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
4534 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
4535 WSASetLastError(WSAEACCES);
4536 return SOCKET_ERROR;
4539 /***********************************************************************
4540 * WSAInstallServiceClassW (WS2_32.49)
4542 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
4544 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
4545 WSASetLastError(WSAEACCES);
4546 return SOCKET_ERROR;
4549 /***********************************************************************
4550 * WSARemoveServiceClass (WS2_32.70)
4552 int WINAPI WSARemoveServiceClass(LPGUID info)
4554 FIXME("Request to remove service %p\n",info);
4555 WSASetLastError(WSATYPE_NOT_FOUND);
4556 return SOCKET_ERROR;
4559 /***********************************************************************
4560 * inet_ntop (WS2_32.@)
4562 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, size_t len )
4564 #ifdef HAVE_INET_NTOP
4565 union generic_unix_sockaddr unix_addr;
4567 switch (family)
4569 case WS_AF_INET:
4570 ws_sockaddr_ws2u( addr, sizeof(struct WS_sockaddr_in), &unix_addr );
4571 return inet_ntop( AF_INET, &unix_addr, buffer, len );
4572 case WS_AF_INET6:
4573 ws_sockaddr_ws2u( addr, sizeof(struct WS_sockaddr_in6), &unix_addr );
4574 return inet_ntop( AF_INET6, &unix_addr, buffer, len );
4576 #else
4577 FIXME( "not supported on this platform\n" );
4578 #endif
4579 WSASetLastError( WSAEAFNOSUPPORT );
4580 return NULL;
4583 /***********************************************************************
4584 * WSAStringToAddressA (WS2_32.80)
4586 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
4587 INT AddressFamily,
4588 LPWSAPROTOCOL_INFOA lpProtocolInfo,
4589 LPSOCKADDR lpAddress,
4590 LPINT lpAddressLength)
4592 INT res=0;
4593 LPSTR workBuffer=NULL,ptrPort;
4595 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
4596 lpProtocolInfo, lpAddress, lpAddressLength );
4598 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
4600 if (!AddressString)
4602 WSASetLastError(WSAEINVAL);
4603 return SOCKET_ERROR;
4606 if (lpProtocolInfo)
4607 FIXME("ProtocolInfo not implemented.\n");
4609 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
4610 strlen(AddressString) + 1);
4611 if (!workBuffer)
4613 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4614 return SOCKET_ERROR;
4617 strcpy(workBuffer, AddressString);
4619 switch(AddressFamily)
4621 case WS_AF_INET:
4623 struct in_addr inetaddr;
4625 /* If lpAddressLength is too small, tell caller the size we need */
4626 if (*lpAddressLength < sizeof(SOCKADDR_IN))
4628 *lpAddressLength = sizeof(SOCKADDR_IN);
4629 res = WSAEFAULT;
4630 break;
4632 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
4634 ((LPSOCKADDR_IN)lpAddress)->sin_family = AF_INET;
4636 ptrPort = strchr(workBuffer, ':');
4637 if(ptrPort)
4639 ((LPSOCKADDR_IN)lpAddress)->sin_port = (WS_u_short)atoi(ptrPort+1);
4640 *ptrPort = '\0';
4642 else
4644 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
4647 if(inet_aton(workBuffer, &inetaddr) > 0)
4649 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
4650 res = 0;
4652 else
4653 res = WSAEINVAL;
4655 break;
4658 case WS_AF_INET6:
4660 struct in6_addr inetaddr;
4661 /* If lpAddressLength is too small, tell caller the size we need */
4662 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
4664 *lpAddressLength = sizeof(SOCKADDR_IN6);
4665 res = WSAEFAULT;
4666 break;
4668 #ifdef HAVE_INET_PTON
4669 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
4671 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
4673 /* This one is a bit tricky. An IPv6 address contains colons, so the
4674 * check from IPv4 doesn't work like that. However, IPv6 addresses that
4675 * contain a port are written with braces like [fd12:3456:7890::1]:12345
4676 * so what we will do is to look for ']', check if the next char is a
4677 * colon, and if it is, parse the port as in IPv4. */
4679 ptrPort = strchr(workBuffer, ']');
4680 if(ptrPort && *(++ptrPort) == ':')
4682 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = (WS_u_short)atoi(ptrPort+1);
4683 *ptrPort = '\0';
4685 else
4687 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
4690 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
4692 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
4693 sizeof(struct in6_addr));
4694 res = 0;
4696 else
4697 #endif /* HAVE_INET_PTON */
4698 res = WSAEINVAL;
4700 break;
4702 default:
4703 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
4704 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
4705 res = WSAEINVAL;
4708 HeapFree(GetProcessHeap(), 0, workBuffer);
4710 if (!res) return 0;
4711 WSASetLastError(res);
4712 return SOCKET_ERROR;
4715 /***********************************************************************
4716 * WSAStringToAddressW (WS2_32.81)
4718 * Does anybody know if this functions allows to use hebrew/arabic/chinese... digits?
4719 * If this should be the case, it would be required to map these digits
4720 * to Unicode digits (0-9) using FoldString first.
4722 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
4723 INT AddressFamily,
4724 LPWSAPROTOCOL_INFOW lpProtocolInfo,
4725 LPSOCKADDR lpAddress,
4726 LPINT lpAddressLength)
4728 INT sBuffer,res=0;
4729 LPSTR workBuffer=NULL;
4730 WSAPROTOCOL_INFOA infoA;
4731 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
4733 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
4734 lpAddress, lpAddressLength );
4736 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
4738 /* if ProtocolInfo is available - convert to ANSI variant */
4739 if (lpProtocolInfo)
4741 lpProtoInfoA = &infoA;
4742 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
4744 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
4745 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
4747 WSASetLastError( WSAEINVAL);
4748 return SOCKET_ERROR;
4752 if (AddressString)
4754 /* Translate AddressString to ANSI code page - assumes that only
4755 standard digits 0-9 are used with this API call */
4756 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
4757 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
4759 if (workBuffer)
4761 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
4762 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
4763 lpAddress,lpAddressLength);
4764 HeapFree( GetProcessHeap(), 0, workBuffer );
4765 return res;
4767 else
4768 res = WSA_NOT_ENOUGH_MEMORY;
4770 else
4771 res = WSAEINVAL;
4773 WSASetLastError(res);
4774 return SOCKET_ERROR;
4777 /***********************************************************************
4778 * WSAAddressToStringA (WS2_32.27)
4780 * See WSAAddressToStringW
4782 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
4783 LPWSAPROTOCOL_INFOA info, LPSTR string,
4784 LPDWORD lenstr )
4786 DWORD size;
4787 CHAR buffer[22]; /* 12 digits + 3 dots + ':' + 5 digits + '\0' */
4788 CHAR *p;
4790 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
4792 if (!sockaddr || len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
4793 if (!string || !lenstr) return SOCKET_ERROR;
4795 /* sin_family is guaranteed to be the first u_short */
4796 if (((SOCKADDR_IN *)sockaddr)->sin_family != AF_INET) return SOCKET_ERROR;
4798 sprintf( buffer, "%u.%u.%u.%u:%u",
4799 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
4800 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
4801 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
4802 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
4803 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
4805 p = strchr( buffer, ':' );
4806 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
4808 size = strlen( buffer );
4810 if (*lenstr < size)
4812 *lenstr = size;
4813 WSASetLastError(WSAEFAULT);
4814 return SOCKET_ERROR;
4817 strcpy( string, buffer );
4818 return 0;
4821 /***********************************************************************
4822 * WSAAddressToStringW (WS2_32.28)
4824 * Convert a sockaddr address into a readable address string.
4826 * PARAMS
4827 * sockaddr [I] Pointer to a sockaddr structure.
4828 * len [I] Size of the sockaddr structure.
4829 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
4830 * string [I/O] Pointer to a buffer to receive the address string.
4831 * lenstr [I/O] Size of the receive buffer in WCHARs.
4833 * RETURNS
4834 * Success: 0
4835 * Failure: SOCKET_ERROR
4837 * NOTES
4838 * The 'info' parameter is ignored.
4840 * BUGS
4841 * Only supports AF_INET addresses.
4843 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
4844 LPWSAPROTOCOL_INFOW info, LPWSTR string,
4845 LPDWORD lenstr )
4847 DWORD size;
4848 WCHAR buffer[22]; /* 12 digits + 3 dots + ':' + 5 digits + '\0' */
4849 static const WCHAR format[] = { '%','u','.','%','u','.','%','u','.','%','u',':','%','u',0 };
4850 WCHAR *p;
4852 TRACE( "(%p, %x, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
4854 if (!sockaddr || len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
4855 if (!string || !lenstr) return SOCKET_ERROR;
4857 /* sin_family is guaranteed to be the first u_short */
4858 if (((SOCKADDR_IN *)sockaddr)->sin_family != AF_INET) return SOCKET_ERROR;
4860 sprintfW( buffer, format,
4861 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
4862 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
4863 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
4864 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
4865 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
4867 p = strchrW( buffer, ':' );
4868 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
4870 size = strlenW( buffer );
4872 if (*lenstr < size)
4874 *lenstr = size;
4875 return SOCKET_ERROR;
4878 lstrcpyW( string, buffer );
4879 return 0;
4882 /***********************************************************************
4883 * WSAEnumNameSpaceProvidersA (WS2_32.34)
4885 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
4887 FIXME( "(%p %p) Stub!\n", len, buffer );
4888 return 0;
4891 /***********************************************************************
4892 * WSAEnumNameSpaceProvidersW (WS2_32.35)
4894 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
4896 FIXME( "(%p %p) Stub!\n", len, buffer );
4897 return 0;
4900 /***********************************************************************
4901 * WSAGetQOSByName (WS2_32.41)
4903 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
4905 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
4906 return FALSE;
4909 /***********************************************************************
4910 * WSAGetServiceClassInfoA (WS2_32.42)
4912 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
4913 LPWSASERVICECLASSINFOA info )
4915 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
4916 len, info );
4917 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4918 return SOCKET_ERROR;
4921 /***********************************************************************
4922 * WSAGetServiceClassInfoW (WS2_32.43)
4924 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
4925 LPWSASERVICECLASSINFOW info )
4927 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
4928 len, info );
4929 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4930 return SOCKET_ERROR;
4933 /***********************************************************************
4934 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
4936 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
4938 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
4939 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4940 return SOCKET_ERROR;
4943 /***********************************************************************
4944 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
4946 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
4948 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
4949 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4950 return SOCKET_ERROR;
4953 /***********************************************************************
4954 * WSALookupServiceBeginA (WS2_32.59)
4956 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
4957 DWORD dwControlFlags,
4958 LPHANDLE lphLookup)
4960 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
4961 lphLookup);
4962 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4963 return SOCKET_ERROR;
4966 /***********************************************************************
4967 * WSALookupServiceBeginW (WS2_32.60)
4969 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
4970 DWORD dwControlFlags,
4971 LPHANDLE lphLookup)
4973 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
4974 lphLookup);
4975 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4976 return SOCKET_ERROR;
4979 /***********************************************************************
4980 * WSALookupServiceBeginW (WS2_32.61)
4982 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
4984 FIXME("(%p) Stub!\n", lookup );
4985 return 0;
4988 /***********************************************************************
4989 * WSALookupServiceNextA (WS2_32.62)
4991 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
4993 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
4994 return 0;
4997 /***********************************************************************
4998 * WSALookupServiceNextW (WS2_32.63)
5000 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
5002 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
5003 return 0;
5006 /***********************************************************************
5007 * WSANtohl (WS2_32.64)
5009 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
5011 TRACE( "(0x%04lx 0x%08x %p)\n", s, netlong, lphostlong );
5013 if (!lphostlong) return WSAEFAULT;
5015 *lphostlong = ntohl( netlong );
5016 return 0;
5019 /***********************************************************************
5020 * WSANtohs (WS2_32.65)
5022 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
5024 TRACE( "(0x%04lx 0x%08x %p)\n", s, netshort, lphostshort );
5026 if (!lphostshort) return WSAEFAULT;
5028 *lphostshort = ntohs( netshort );
5029 return 0;
5032 /***********************************************************************
5033 * WSAProviderConfigChange (WS2_32.66)
5035 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
5036 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
5038 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
5039 return SOCKET_ERROR;
5042 /***********************************************************************
5043 * WSARecvDisconnect (WS2_32.68)
5045 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
5047 TRACE( "(0x%04lx %p)\n", s, disconnectdata );
5049 return WS_shutdown( s, 0 );
5052 /***********************************************************************
5053 * WSASetServiceA (WS2_32.76)
5055 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
5057 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
5058 return 0;
5061 /***********************************************************************
5062 * WSASetServiceW (WS2_32.77)
5064 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
5066 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
5067 return 0;
5070 /***********************************************************************
5071 * WSCEnableNSProvider (WS2_32.84)
5073 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
5075 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
5076 return 0;
5079 /***********************************************************************
5080 * WSCGetProviderPath (WS2_32.86)
5082 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
5084 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
5086 if (!errcode || !provider || !len) return WSAEFAULT;
5088 *errcode = WSAEINVAL;
5089 return SOCKET_ERROR;
5092 /***********************************************************************
5093 * WSCInstallNameSpace (WS2_32.87)
5095 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
5096 DWORD version, LPGUID provider )
5098 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
5099 namespace, version, debugstr_guid(provider) );
5100 return 0;
5103 /***********************************************************************
5104 * WSCUnInstallNameSpace (WS2_32.89)
5106 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
5108 FIXME("(%p) Stub!\n", lpProviderId);
5109 return NO_ERROR;
5112 /***********************************************************************
5113 * WSCWriteProviderOrder (WS2_32.91)
5115 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
5117 FIXME("(%p 0x%08x) Stub!\n", entry, number);
5118 return 0;