wined3d: Use opaque data type for stream output registers.
[wine.git] / dlls / ws2_32 / socket.c
blobd863b3ee48367c9596775513a02443a68f9d0e1b
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) 2001 Stefan Leichter
6 * Copyright (C) 2004 Hans Leidekker
7 * Copyright (C) 2005 Marcus Meissner
8 * Copyright (C) 2006-2008 Kai Blin
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24 * NOTE: If you make any changes to fix a particular app, make sure
25 * they don't break something else like Netscape or telnet and ftp
26 * clients and servers (www.winsite.com got a lot of those).
29 #include "config.h"
30 #include "wine/port.h"
32 #include <stdarg.h>
33 #include <stdio.h>
34 #include <string.h>
35 #include <sys/types.h>
36 #include <limits.h>
37 #ifdef HAVE_SYS_IPC_H
38 # include <sys/ipc.h>
39 #endif
40 #ifdef HAVE_SYS_IOCTL_H
41 # include <sys/ioctl.h>
42 #endif
43 #ifdef HAVE_SYS_FILIO_H
44 # include <sys/filio.h>
45 #endif
46 #ifdef HAVE_SYS_SOCKIO_H
47 # include <sys/sockio.h>
48 #endif
50 #if defined(__EMX__)
51 # include <sys/so_ioctl.h>
52 #endif
54 #ifdef HAVE_SYS_PARAM_H
55 # include <sys/param.h>
56 #endif
58 #ifdef HAVE_SYS_MSG_H
59 # include <sys/msg.h>
60 #endif
61 #ifdef HAVE_SYS_WAIT_H
62 # include <sys/wait.h>
63 #endif
64 #ifdef HAVE_SYS_UIO_H
65 # include <sys/uio.h>
66 #endif
67 #ifdef HAVE_SYS_SOCKET_H
68 #include <sys/socket.h>
69 #endif
70 #ifdef HAVE_NETINET_IN_H
71 # include <netinet/in.h>
72 #endif
73 #ifdef HAVE_NETINET_TCP_H
74 # include <netinet/tcp.h>
75 #endif
76 #ifdef HAVE_ARPA_INET_H
77 # include <arpa/inet.h>
78 #endif
79 #include <ctype.h>
80 #include <fcntl.h>
81 #include <errno.h>
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
98 #ifdef HAVE_LINUX_FILTER_H
99 # include <linux/filter.h>
100 #endif
102 #ifdef HAVE_NETIPX_IPX_H
103 # include <netipx/ipx.h>
104 #elif defined(HAVE_LINUX_IPX_H)
105 # ifdef HAVE_ASM_TYPES_H
106 # include <asm/types.h>
107 # endif
108 # ifdef HAVE_LINUX_TYPES_H
109 # include <linux/types.h>
110 # endif
111 # include <linux/ipx.h>
112 #endif
113 #if defined(SOL_IPX) || defined(SO_DEFAULT_HEADERS)
114 # define HAS_IPX
115 #endif
117 #ifdef HAVE_LINUX_IRDA_H
118 # ifdef HAVE_LINUX_TYPES_H
119 # include <linux/types.h>
120 # endif
121 # include <linux/irda.h>
122 # define HAS_IRDA
123 #endif
125 #ifdef HAVE_POLL_H
126 #include <poll.h>
127 #endif
128 #ifdef HAVE_SYS_POLL_H
129 # include <sys/poll.h>
130 #endif
131 #ifdef HAVE_SYS_TIME_H
132 # include <sys/time.h>
133 #endif
135 #define NONAMELESSUNION
136 #define NONAMELESSSTRUCT
137 #include "ntstatus.h"
138 #define WIN32_NO_STATUS
139 #include "windef.h"
140 #include "winbase.h"
141 #include "wingdi.h"
142 #include "winuser.h"
143 #include "winerror.h"
144 #include "winnls.h"
145 #include "winsock2.h"
146 #include "mswsock.h"
147 #include "ws2tcpip.h"
148 #include "ws2spi.h"
149 #include "wsipx.h"
150 #include "wsnwlink.h"
151 #include "wshisotp.h"
152 #include "mstcpip.h"
153 #include "af_irda.h"
154 #include "winnt.h"
155 #define USE_WC_PREFIX /* For CMSG_DATA */
156 #include "iphlpapi.h"
157 #include "wine/server.h"
158 #include "wine/debug.h"
159 #include "wine/exception.h"
160 #include "wine/unicode.h"
162 #if defined(linux) && !defined(IP_UNICAST_IF)
163 #define IP_UNICAST_IF 50
164 #endif
166 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
167 # define sipx_network sipx_addr.x_net
168 # define sipx_node sipx_addr.x_host.c_host
169 #endif /* __FreeBSD__ */
171 #ifndef INADDR_NONE
172 #define INADDR_NONE ~0UL
173 #endif
175 #if !defined(TCP_KEEPIDLE) && defined(TCP_KEEPALIVE)
176 /* TCP_KEEPALIVE is the Mac OS name for TCP_KEEPIDLE */
177 #define TCP_KEEPIDLE TCP_KEEPALIVE
178 #endif
180 #define FILE_USE_FILE_POINTER_POSITION ((LONGLONG)-2)
182 WINE_DEFAULT_DEBUG_CHANNEL(winsock);
183 WINE_DECLARE_DEBUG_CHANNEL(winediag);
185 /* names of the protocols */
186 static const WCHAR NameIpxW[] = {'I', 'P', 'X', '\0'};
187 static const WCHAR NameSpxW[] = {'S', 'P', 'X', '\0'};
188 static const WCHAR NameSpxIIW[] = {'S', 'P', 'X', ' ', 'I', 'I', '\0'};
189 static const WCHAR NameTcpW[] = {'T', 'C', 'P', '/', 'I', 'P', '\0'};
190 static const WCHAR NameUdpW[] = {'U', 'D', 'P', '/', 'I', 'P', '\0'};
192 /* Taken from Win2k */
193 static const GUID ProviderIdIP = { 0xe70f1aa0, 0xab8b, 0x11cf,
194 { 0x8c, 0xa3, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
195 static const GUID ProviderIdIPX = { 0x11058240, 0xbe47, 0x11cf,
196 { 0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
197 static const GUID ProviderIdSPX = { 0x11058241, 0xbe47, 0x11cf,
198 { 0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
200 static const INT valid_protocols[] =
202 WS_IPPROTO_TCP,
203 WS_IPPROTO_UDP,
204 WS_NSPROTO_IPX,
205 WS_NSPROTO_SPX,
206 WS_NSPROTO_SPXII,
210 #define IS_IPX_PROTO(X) ((X) >= WS_NSPROTO_IPX && (X) <= WS_NSPROTO_IPX + 255)
212 #if defined(IP_UNICAST_IF) && defined(SO_ATTACH_FILTER)
213 # define LINUX_BOUND_IF
214 struct interface_filter {
215 struct sock_filter iface_memaddr;
216 struct sock_filter iface_rule;
217 struct sock_filter ip_memaddr;
218 struct sock_filter ip_rule;
219 struct sock_filter return_keep;
220 struct sock_filter return_dump;
222 # define FILTER_JUMP_DUMP(here) (u_char)(offsetof(struct interface_filter, return_dump) \
223 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
224 /sizeof(struct sock_filter)
225 # define FILTER_JUMP_KEEP(here) (u_char)(offsetof(struct interface_filter, return_keep) \
226 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
227 /sizeof(struct sock_filter)
228 # define FILTER_JUMP_NEXT() (u_char)(0)
229 # define SKF_NET_DESTIP 16 /* offset in the network header to the destination IP */
230 static struct interface_filter generic_interface_filter = {
231 /* This filter rule allows incoming packets on the specified interface, which works for all
232 * remotely generated packets and for locally generated broadcast packets. */
233 BPF_STMT(BPF_LD+BPF_W+BPF_ABS, SKF_AD_OFF+SKF_AD_IFINDEX),
234 BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0xdeadbeef, FILTER_JUMP_KEEP(iface_rule), FILTER_JUMP_NEXT()),
235 /* This rule allows locally generated packets targeted at the specific IP address of the chosen
236 * adapter (local packets not destined for the broadcast address do not have IFINDEX set) */
237 BPF_STMT(BPF_LD+BPF_W+BPF_ABS, SKF_NET_OFF+SKF_NET_DESTIP),
238 BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0xdeadbeef, FILTER_JUMP_KEEP(ip_rule), FILTER_JUMP_DUMP(ip_rule)),
239 BPF_STMT(BPF_RET+BPF_K, (u_int)-1), /* keep packet */
240 BPF_STMT(BPF_RET+BPF_K, 0) /* dump packet */
242 #endif /* LINUX_BOUND_IF */
245 * The actual definition of WSASendTo, wrapped in a different function name
246 * so that internal calls from ws2_32 itself will not trigger programs like
247 * Garena, which hooks WSASendTo/WSARecvFrom calls.
249 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
250 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
251 const struct WS_sockaddr *to, int tolen,
252 LPWSAOVERLAPPED lpOverlapped,
253 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine );
256 * Internal fundamental receive function, essentially WSARecvFrom with an
257 * additional parameter to support message control headers.
259 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
260 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
261 struct WS_sockaddr *lpFrom,
262 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
263 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
264 LPWSABUF lpControlBuffer );
266 /* critical section to protect some non-reentrant net function */
267 static CRITICAL_SECTION csWSgetXXXbyYYY;
268 static CRITICAL_SECTION_DEBUG critsect_debug =
270 0, 0, &csWSgetXXXbyYYY,
271 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
272 0, 0, { (DWORD_PTR)(__FILE__ ": csWSgetXXXbyYYY") }
274 static CRITICAL_SECTION csWSgetXXXbyYYY = { &critsect_debug, -1, 0, 0, 0, 0 };
276 union generic_unix_sockaddr
278 struct sockaddr addr;
279 char data[128]; /* should be big enough for all families */
282 static inline const char *debugstr_sockaddr( const struct WS_sockaddr *a )
284 if (!a) return "(nil)";
285 switch (a->sa_family)
287 case WS_AF_INET:
289 char buf[16];
290 const char *p;
291 struct WS_sockaddr_in *sin = (struct WS_sockaddr_in *)a;
293 p = WS_inet_ntop( WS_AF_INET, &sin->sin_addr, buf, sizeof(buf) );
294 if (!p)
295 p = "(unknown IPv4 address)";
297 return wine_dbg_sprintf("{ family AF_INET, address %s, port %d }",
298 p, ntohs(sin->sin_port));
300 case WS_AF_INET6:
302 char buf[46];
303 const char *p;
304 struct WS_sockaddr_in6 *sin = (struct WS_sockaddr_in6 *)a;
306 p = WS_inet_ntop( WS_AF_INET6, &sin->sin6_addr, buf, sizeof(buf) );
307 if (!p)
308 p = "(unknown IPv6 address)";
309 return wine_dbg_sprintf("{ family AF_INET6, address %s, port %d }",
310 p, ntohs(sin->sin6_port));
312 case WS_AF_IPX:
314 int i;
315 char netnum[16], nodenum[16];
316 struct WS_sockaddr_ipx *sin = (struct WS_sockaddr_ipx *)a;
318 for (i = 0;i < 4; i++) sprintf(netnum + i * 2, "%02X", (unsigned char) sin->sa_netnum[i]);
319 for (i = 0;i < 6; i++) sprintf(nodenum + i * 2, "%02X", (unsigned char) sin->sa_nodenum[i]);
321 return wine_dbg_sprintf("{ family AF_IPX, address %s.%s, ipx socket %d }",
322 netnum, nodenum, sin->sa_socket);
324 case WS_AF_IRDA:
326 DWORD addr;
328 memcpy( &addr, ((const SOCKADDR_IRDA *)a)->irdaDeviceID, sizeof(addr) );
329 addr = ntohl( addr );
330 return wine_dbg_sprintf("{ family AF_IRDA, addr %08x, name %s }",
331 addr,
332 ((const SOCKADDR_IRDA *)a)->irdaServiceName);
334 default:
335 return wine_dbg_sprintf("{ family %d }", a->sa_family);
339 static inline const char *debugstr_sockopt(int level, int optname)
341 const char *stropt = NULL, *strlevel = NULL;
343 #define DEBUG_SOCKLEVEL(x) case (x): strlevel = #x
344 #define DEBUG_SOCKOPT(x) case (x): stropt = #x; break
346 switch(level)
348 DEBUG_SOCKLEVEL(WS_SOL_SOCKET);
349 switch(optname)
351 DEBUG_SOCKOPT(WS_SO_ACCEPTCONN);
352 DEBUG_SOCKOPT(WS_SO_BROADCAST);
353 DEBUG_SOCKOPT(WS_SO_BSP_STATE);
354 DEBUG_SOCKOPT(WS_SO_CONDITIONAL_ACCEPT);
355 DEBUG_SOCKOPT(WS_SO_CONNECT_TIME);
356 DEBUG_SOCKOPT(WS_SO_DEBUG);
357 DEBUG_SOCKOPT(WS_SO_DONTLINGER);
358 DEBUG_SOCKOPT(WS_SO_DONTROUTE);
359 DEBUG_SOCKOPT(WS_SO_ERROR);
360 DEBUG_SOCKOPT(WS_SO_EXCLUSIVEADDRUSE);
361 DEBUG_SOCKOPT(WS_SO_GROUP_ID);
362 DEBUG_SOCKOPT(WS_SO_GROUP_PRIORITY);
363 DEBUG_SOCKOPT(WS_SO_KEEPALIVE);
364 DEBUG_SOCKOPT(WS_SO_LINGER);
365 DEBUG_SOCKOPT(WS_SO_MAX_MSG_SIZE);
366 DEBUG_SOCKOPT(WS_SO_OOBINLINE);
367 DEBUG_SOCKOPT(WS_SO_OPENTYPE);
368 DEBUG_SOCKOPT(WS_SO_PROTOCOL_INFOA);
369 DEBUG_SOCKOPT(WS_SO_PROTOCOL_INFOW);
370 DEBUG_SOCKOPT(WS_SO_RCVBUF);
371 DEBUG_SOCKOPT(WS_SO_RCVTIMEO);
372 DEBUG_SOCKOPT(WS_SO_REUSEADDR);
373 DEBUG_SOCKOPT(WS_SO_SNDBUF);
374 DEBUG_SOCKOPT(WS_SO_SNDTIMEO);
375 DEBUG_SOCKOPT(WS_SO_TYPE);
376 DEBUG_SOCKOPT(WS_SO_UPDATE_CONNECT_CONTEXT);
378 break;
380 DEBUG_SOCKLEVEL(WS_NSPROTO_IPX);
381 switch(optname)
383 DEBUG_SOCKOPT(WS_IPX_PTYPE);
384 DEBUG_SOCKOPT(WS_IPX_FILTERPTYPE);
385 DEBUG_SOCKOPT(WS_IPX_DSTYPE);
386 DEBUG_SOCKOPT(WS_IPX_RECVHDR);
387 DEBUG_SOCKOPT(WS_IPX_MAXSIZE);
388 DEBUG_SOCKOPT(WS_IPX_ADDRESS);
389 DEBUG_SOCKOPT(WS_IPX_MAX_ADAPTER_NUM);
391 break;
393 DEBUG_SOCKLEVEL(WS_SOL_IRLMP);
394 switch(optname)
396 DEBUG_SOCKOPT(WS_IRLMP_ENUMDEVICES);
398 break;
400 DEBUG_SOCKLEVEL(WS_IPPROTO_TCP);
401 switch(optname)
403 DEBUG_SOCKOPT(WS_TCP_BSDURGENT);
404 DEBUG_SOCKOPT(WS_TCP_EXPEDITED_1122);
405 DEBUG_SOCKOPT(WS_TCP_NODELAY);
407 break;
409 DEBUG_SOCKLEVEL(WS_IPPROTO_IP);
410 switch(optname)
412 DEBUG_SOCKOPT(WS_IP_ADD_MEMBERSHIP);
413 DEBUG_SOCKOPT(WS_IP_DONTFRAGMENT);
414 DEBUG_SOCKOPT(WS_IP_DROP_MEMBERSHIP);
415 DEBUG_SOCKOPT(WS_IP_HDRINCL);
416 DEBUG_SOCKOPT(WS_IP_MULTICAST_IF);
417 DEBUG_SOCKOPT(WS_IP_MULTICAST_LOOP);
418 DEBUG_SOCKOPT(WS_IP_MULTICAST_TTL);
419 DEBUG_SOCKOPT(WS_IP_OPTIONS);
420 DEBUG_SOCKOPT(WS_IP_PKTINFO);
421 DEBUG_SOCKOPT(WS_IP_RECEIVE_BROADCAST);
422 DEBUG_SOCKOPT(WS_IP_TOS);
423 DEBUG_SOCKOPT(WS_IP_TTL);
424 DEBUG_SOCKOPT(WS_IP_UNICAST_IF);
426 break;
428 DEBUG_SOCKLEVEL(WS_IPPROTO_IPV6);
429 switch(optname)
431 DEBUG_SOCKOPT(WS_IPV6_ADD_MEMBERSHIP);
432 DEBUG_SOCKOPT(WS_IPV6_DROP_MEMBERSHIP);
433 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_IF);
434 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_HOPS);
435 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_LOOP);
436 DEBUG_SOCKOPT(WS_IPV6_UNICAST_HOPS);
437 DEBUG_SOCKOPT(WS_IPV6_V6ONLY);
438 DEBUG_SOCKOPT(WS_IPV6_UNICAST_IF);
439 DEBUG_SOCKOPT(WS_IPV6_DONTFRAG);
441 break;
443 #undef DEBUG_SOCKLEVEL
444 #undef DEBUG_SOCKOPT
446 if (!strlevel)
447 strlevel = wine_dbg_sprintf("WS_0x%x", level);
448 if (!stropt)
449 stropt = wine_dbg_sprintf("WS_0x%x", optname);
451 return wine_dbg_sprintf("level %s, name %s", strlevel + 3, stropt + 3);
454 static inline const char *debugstr_optval(const char *optval, int optlenval)
456 if (optval && !IS_INTRESOURCE(optval) && optlenval >= 1 && optlenval <= sizeof(DWORD))
458 DWORD value = 0;
459 memcpy(&value, optval, optlenval);
460 return wine_dbg_sprintf("%p (%u)", optval, value);
462 return wine_dbg_sprintf("%p", optval);
465 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
466 #define SOCKET2HANDLE(s) ((HANDLE)(s))
467 #define HANDLE2SOCKET(h) ((SOCKET)(h))
469 /****************************************************************
470 * Async IO declarations
471 ****************************************************************/
473 struct ws2_async_io
475 struct ws2_async_io *next;
478 struct ws2_async_shutdown
480 struct ws2_async_io io;
481 HANDLE hSocket;
482 IO_STATUS_BLOCK iosb;
483 int type;
486 struct ws2_async
488 struct ws2_async_io io;
489 HANDLE hSocket;
490 LPWSAOVERLAPPED user_overlapped;
491 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
492 IO_STATUS_BLOCK local_iosb;
493 struct WS_sockaddr *addr;
494 union
496 int val; /* for send operations */
497 int *ptr; /* for recv operations */
498 } addrlen;
499 DWORD flags;
500 DWORD *lpFlags;
501 WSABUF *control;
502 unsigned int n_iovecs;
503 unsigned int first_iovec;
504 struct iovec iovec[1];
507 struct ws2_accept_async
509 struct ws2_async_io io;
510 HANDLE listen_socket;
511 HANDLE accept_socket;
512 LPOVERLAPPED user_overlapped;
513 ULONG_PTR cvalue;
514 PVOID buf; /* buffer to write data to */
515 int data_len;
516 int local_len;
517 int remote_len;
518 struct ws2_async *read;
521 struct ws2_transmitfile_async
523 struct ws2_async_io io;
524 char *buffer;
525 HANDLE file;
526 DWORD file_read;
527 DWORD file_bytes;
528 DWORD bytes_per_send;
529 TRANSMIT_FILE_BUFFERS buffers;
530 DWORD flags;
531 LARGE_INTEGER offset;
532 struct ws2_async write;
535 static struct ws2_async_io *async_io_freelist;
537 static void release_async_io( struct ws2_async_io *io )
539 for (;;)
541 struct ws2_async_io *next = async_io_freelist;
542 io->next = next;
543 if (InterlockedCompareExchangePointer( (void **)&async_io_freelist, io, next ) == next) return;
547 static struct ws2_async_io *alloc_async_io( DWORD size )
549 /* first free remaining previous fileinfos */
551 struct ws2_async_io *io = InterlockedExchangePointer( (void **)&async_io_freelist, NULL );
553 while (io)
555 struct ws2_async_io *next = io->next;
556 HeapFree( GetProcessHeap(), 0, io );
557 io = next;
560 return HeapAlloc( GetProcessHeap(), 0, size );
563 /****************************************************************/
565 /* ----------------------------------- internal data */
567 /* ws_... struct conversion flags */
569 typedef struct /* WSAAsyncSelect() control struct */
571 HANDLE service, event, sock;
572 HWND hWnd;
573 UINT uMsg;
574 LONG lEvent;
575 } ws_select_info;
577 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
578 #define WS_MAX_UDP_DATAGRAM 1024
579 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
581 /* hostent's, servent's and protent's are stored in one buffer per thread,
582 * as documented on MSDN for the functions that return any of the buffers */
583 struct per_thread_data
585 int opentype;
586 struct WS_hostent *he_buffer;
587 struct WS_servent *se_buffer;
588 struct WS_protoent *pe_buffer;
589 struct pollfd *fd_cache;
590 unsigned int fd_count;
591 int he_len;
592 int se_len;
593 int pe_len;
594 char ntoa_buffer[16]; /* 4*3 digits + 3 '.' + 1 '\0' */
597 /* internal: routing description information */
598 struct route {
599 struct in_addr addr;
600 IF_INDEX interface;
601 DWORD metric, default_route;
604 static INT num_startup; /* reference counter */
605 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
607 /* function prototypes */
608 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length);
609 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
610 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
611 static struct WS_servent *WS_dup_se(const struct servent* p_se);
612 static int ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size);
614 int WSAIOCTL_GetInterfaceCount(void);
615 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
617 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus, ULONG Information );
619 #define MAP_OPTION(opt) { WS_##opt, opt }
621 static const int ws_flags_map[][2] =
623 MAP_OPTION( MSG_OOB ),
624 MAP_OPTION( MSG_PEEK ),
625 MAP_OPTION( MSG_DONTROUTE ),
626 MAP_OPTION( MSG_WAITALL ),
629 static const int ws_sock_map[][2] =
631 MAP_OPTION( SO_DEBUG ),
632 MAP_OPTION( SO_ACCEPTCONN ),
633 MAP_OPTION( SO_REUSEADDR ),
634 MAP_OPTION( SO_KEEPALIVE ),
635 MAP_OPTION( SO_DONTROUTE ),
636 MAP_OPTION( SO_BROADCAST ),
637 MAP_OPTION( SO_LINGER ),
638 MAP_OPTION( SO_OOBINLINE ),
639 MAP_OPTION( SO_SNDBUF ),
640 MAP_OPTION( SO_RCVBUF ),
641 MAP_OPTION( SO_ERROR ),
642 MAP_OPTION( SO_TYPE ),
643 #ifdef SO_RCVTIMEO
644 MAP_OPTION( SO_RCVTIMEO ),
645 #endif
646 #ifdef SO_SNDTIMEO
647 MAP_OPTION( SO_SNDTIMEO ),
648 #endif
651 static const int ws_tcp_map[][2] =
653 #ifdef TCP_NODELAY
654 MAP_OPTION( TCP_NODELAY ),
655 #endif
658 static const int ws_ip_map[][2] =
660 MAP_OPTION( IP_MULTICAST_IF ),
661 MAP_OPTION( IP_MULTICAST_TTL ),
662 MAP_OPTION( IP_MULTICAST_LOOP ),
663 MAP_OPTION( IP_ADD_MEMBERSHIP ),
664 MAP_OPTION( IP_DROP_MEMBERSHIP ),
665 MAP_OPTION( IP_OPTIONS ),
666 #ifdef IP_HDRINCL
667 MAP_OPTION( IP_HDRINCL ),
668 #endif
669 MAP_OPTION( IP_TOS ),
670 MAP_OPTION( IP_TTL ),
671 #ifdef IP_PKTINFO
672 MAP_OPTION( IP_PKTINFO ),
673 #endif
674 #ifdef IP_UNICAST_IF
675 MAP_OPTION( IP_UNICAST_IF ),
676 #endif
679 static const int ws_ipv6_map[][2] =
681 #ifdef IPV6_ADD_MEMBERSHIP
682 MAP_OPTION( IPV6_ADD_MEMBERSHIP ),
683 #endif
684 #ifdef IPV6_DROP_MEMBERSHIP
685 MAP_OPTION( IPV6_DROP_MEMBERSHIP ),
686 #endif
687 MAP_OPTION( IPV6_MULTICAST_IF ),
688 MAP_OPTION( IPV6_MULTICAST_HOPS ),
689 MAP_OPTION( IPV6_MULTICAST_LOOP ),
690 MAP_OPTION( IPV6_UNICAST_HOPS ),
691 MAP_OPTION( IPV6_V6ONLY ),
692 #ifdef IPV6_UNICAST_IF
693 MAP_OPTION( IPV6_UNICAST_IF ),
694 #endif
697 static const int ws_af_map[][2] =
699 MAP_OPTION( AF_UNSPEC ),
700 MAP_OPTION( AF_INET ),
701 MAP_OPTION( AF_INET6 ),
702 #ifdef HAS_IPX
703 MAP_OPTION( AF_IPX ),
704 #endif
705 #ifdef AF_IRDA
706 MAP_OPTION( AF_IRDA ),
707 #endif
708 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
711 static const int ws_socktype_map[][2] =
713 MAP_OPTION( SOCK_DGRAM ),
714 MAP_OPTION( SOCK_STREAM ),
715 MAP_OPTION( SOCK_RAW ),
716 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
719 static const int ws_proto_map[][2] =
721 MAP_OPTION( IPPROTO_IP ),
722 MAP_OPTION( IPPROTO_TCP ),
723 MAP_OPTION( IPPROTO_UDP ),
724 MAP_OPTION( IPPROTO_IPV6 ),
725 MAP_OPTION( IPPROTO_ICMP ),
726 MAP_OPTION( IPPROTO_IGMP ),
727 MAP_OPTION( IPPROTO_RAW ),
728 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
731 static const int ws_aiflag_map[][2] =
733 MAP_OPTION( AI_PASSIVE ),
734 MAP_OPTION( AI_CANONNAME ),
735 MAP_OPTION( AI_NUMERICHOST ),
736 #ifdef AI_NUMERICSERV
737 MAP_OPTION( AI_NUMERICSERV ),
738 #endif
739 #ifdef AI_V4MAPPED
740 MAP_OPTION( AI_V4MAPPED ),
741 #endif
742 MAP_OPTION( AI_ADDRCONFIG ),
745 static const int ws_niflag_map[][2] =
747 MAP_OPTION( NI_NOFQDN ),
748 MAP_OPTION( NI_NUMERICHOST ),
749 MAP_OPTION( NI_NAMEREQD ),
750 MAP_OPTION( NI_NUMERICSERV ),
751 MAP_OPTION( NI_DGRAM ),
754 static const int ws_eai_map[][2] =
756 MAP_OPTION( EAI_AGAIN ),
757 MAP_OPTION( EAI_BADFLAGS ),
758 MAP_OPTION( EAI_FAIL ),
759 MAP_OPTION( EAI_FAMILY ),
760 MAP_OPTION( EAI_MEMORY ),
761 /* Note: EAI_NODATA is deprecated, but still
762 * used by Windows and Linux... We map the newer
763 * EAI_NONAME to EAI_NODATA for now until Windows
764 * changes too.
766 #ifdef EAI_NODATA
767 MAP_OPTION( EAI_NODATA ),
768 #endif
769 #ifdef EAI_NONAME
770 { WS_EAI_NODATA, EAI_NONAME },
771 #endif
773 MAP_OPTION( EAI_SERVICE ),
774 MAP_OPTION( EAI_SOCKTYPE ),
775 { 0, 0 }
778 static const int ws_poll_map[][2] =
780 MAP_OPTION( POLLERR ),
781 MAP_OPTION( POLLHUP ),
782 MAP_OPTION( POLLNVAL ),
783 MAP_OPTION( POLLWRNORM ),
784 MAP_OPTION( POLLWRBAND ),
785 MAP_OPTION( POLLRDNORM ),
786 { WS_POLLRDBAND, POLLPRI }
789 static const char magic_loopback_addr[] = {127, 12, 34, 56};
791 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
792 #ifdef IP_PKTINFO
793 static inline WSACMSGHDR *fill_control_message(int level, int type, WSACMSGHDR *current, ULONG *maxsize, void *data, int len)
795 ULONG msgsize = sizeof(WSACMSGHDR) + WSA_CMSG_ALIGN(len);
796 char *ptr = (char *) current + sizeof(WSACMSGHDR);
798 /* Make sure there is at least enough room for this entry */
799 if (msgsize > *maxsize)
800 return NULL;
801 *maxsize -= msgsize;
802 /* Fill in the entry */
803 current->cmsg_len = sizeof(WSACMSGHDR) + len;
804 current->cmsg_level = level;
805 current->cmsg_type = type;
806 memcpy(ptr, data, len);
807 /* Return the pointer to where next entry should go */
808 return (WSACMSGHDR *) (ptr + WSA_CMSG_ALIGN(len));
810 #endif /* IP_PKTINFO */
812 static inline int convert_control_headers(struct msghdr *hdr, WSABUF *control)
814 #ifdef IP_PKTINFO
815 WSACMSGHDR *cmsg_win = (WSACMSGHDR *) control->buf, *ptr;
816 ULONG ctlsize = control->len;
817 struct cmsghdr *cmsg_unix;
819 ptr = cmsg_win;
820 /* Loop over all the headers, converting as appropriate */
821 for (cmsg_unix = CMSG_FIRSTHDR(hdr); cmsg_unix != NULL; cmsg_unix = CMSG_NXTHDR(hdr, cmsg_unix))
823 switch(cmsg_unix->cmsg_level)
825 case IPPROTO_IP:
826 switch(cmsg_unix->cmsg_type)
828 case IP_PKTINFO:
830 /* Convert the Unix IP_PKTINFO structure to the Windows version */
831 struct in_pktinfo *data_unix = (struct in_pktinfo *) CMSG_DATA(cmsg_unix);
832 struct WS_in_pktinfo data_win;
834 memcpy(&data_win.ipi_addr,&data_unix->ipi_addr.s_addr,4); /* 4 bytes = 32 address bits */
835 data_win.ipi_ifindex = data_unix->ipi_ifindex;
836 ptr = fill_control_message(WS_IPPROTO_IP, WS_IP_PKTINFO, ptr, &ctlsize,
837 (void*)&data_win, sizeof(data_win));
838 if (!ptr) goto error;
839 } break;
840 default:
841 FIXME("Unhandled IPPROTO_IP message header type %d\n", cmsg_unix->cmsg_type);
842 break;
844 break;
845 default:
846 FIXME("Unhandled message header level %d\n", cmsg_unix->cmsg_level);
847 break;
851 error:
852 /* Set the length of the returned control headers */
853 control->len = (ptr == NULL ? 0 : (char*)ptr - (char*)cmsg_win);
854 return (ptr != NULL);
855 #else /* IP_PKTINFO */
856 control->len = 0;
857 return 1;
858 #endif /* IP_PKTINFO */
860 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
862 /* ----------------------------------- error handling */
864 static NTSTATUS sock_get_ntstatus( int err )
866 switch ( err )
868 case EBADF: return STATUS_INVALID_HANDLE;
869 case EBUSY: return STATUS_DEVICE_BUSY;
870 case EPERM:
871 case EACCES: return STATUS_ACCESS_DENIED;
872 case EFAULT: return STATUS_NO_MEMORY;
873 case EINVAL: return STATUS_INVALID_PARAMETER;
874 case ENFILE:
875 case EMFILE: return STATUS_TOO_MANY_OPENED_FILES;
876 case EWOULDBLOCK: return STATUS_CANT_WAIT;
877 case EINPROGRESS: return STATUS_PENDING;
878 case EALREADY: return STATUS_NETWORK_BUSY;
879 case ENOTSOCK: return STATUS_OBJECT_TYPE_MISMATCH;
880 case EDESTADDRREQ: return STATUS_INVALID_PARAMETER;
881 case EMSGSIZE: return STATUS_BUFFER_OVERFLOW;
882 case EPROTONOSUPPORT:
883 case ESOCKTNOSUPPORT:
884 case EPFNOSUPPORT:
885 case EAFNOSUPPORT:
886 case EPROTOTYPE: return STATUS_NOT_SUPPORTED;
887 case ENOPROTOOPT: return STATUS_INVALID_PARAMETER;
888 case EOPNOTSUPP: return STATUS_NOT_SUPPORTED;
889 case EADDRINUSE: return STATUS_ADDRESS_ALREADY_ASSOCIATED;
890 case EADDRNOTAVAIL: return STATUS_INVALID_PARAMETER;
891 case ECONNREFUSED: return STATUS_CONNECTION_REFUSED;
892 case ESHUTDOWN: return STATUS_PIPE_DISCONNECTED;
893 case ENOTCONN: return STATUS_CONNECTION_DISCONNECTED;
894 case ETIMEDOUT: return STATUS_IO_TIMEOUT;
895 case ENETUNREACH: return STATUS_NETWORK_UNREACHABLE;
896 case ENETDOWN: return STATUS_NETWORK_BUSY;
897 case EPIPE:
898 case ECONNRESET: return STATUS_CONNECTION_RESET;
899 case ECONNABORTED: return STATUS_CONNECTION_ABORTED;
901 case 0: return STATUS_SUCCESS;
902 default:
903 WARN("Unknown errno %d!\n", err);
904 return STATUS_UNSUCCESSFUL;
908 static UINT sock_get_error( int err )
910 switch(err)
912 case EINTR: return WSAEINTR;
913 case EPERM:
914 case EACCES: return WSAEACCES;
915 case EFAULT: return WSAEFAULT;
916 case EINVAL: return WSAEINVAL;
917 case EMFILE: return WSAEMFILE;
918 case EWOULDBLOCK: return WSAEWOULDBLOCK;
919 case EINPROGRESS: return WSAEINPROGRESS;
920 case EALREADY: return WSAEALREADY;
921 case EBADF:
922 case ENOTSOCK: return WSAENOTSOCK;
923 case EDESTADDRREQ: return WSAEDESTADDRREQ;
924 case EMSGSIZE: return WSAEMSGSIZE;
925 case EPROTOTYPE: return WSAEPROTOTYPE;
926 case ENOPROTOOPT: return WSAENOPROTOOPT;
927 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
928 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
929 case EOPNOTSUPP: return WSAEOPNOTSUPP;
930 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
931 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
932 case EADDRINUSE: return WSAEADDRINUSE;
933 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
934 case ENETDOWN: return WSAENETDOWN;
935 case ENETUNREACH: return WSAENETUNREACH;
936 case ENETRESET: return WSAENETRESET;
937 case ECONNABORTED: return WSAECONNABORTED;
938 case EPIPE:
939 case ECONNRESET: return WSAECONNRESET;
940 case ENOBUFS: return WSAENOBUFS;
941 case EISCONN: return WSAEISCONN;
942 case ENOTCONN: return WSAENOTCONN;
943 case ESHUTDOWN: return WSAESHUTDOWN;
944 case ETOOMANYREFS: return WSAETOOMANYREFS;
945 case ETIMEDOUT: return WSAETIMEDOUT;
946 case ECONNREFUSED: return WSAECONNREFUSED;
947 case ELOOP: return WSAELOOP;
948 case ENAMETOOLONG: return WSAENAMETOOLONG;
949 case EHOSTDOWN: return WSAEHOSTDOWN;
950 case EHOSTUNREACH: return WSAEHOSTUNREACH;
951 case ENOTEMPTY: return WSAENOTEMPTY;
952 #ifdef EPROCLIM
953 case EPROCLIM: return WSAEPROCLIM;
954 #endif
955 #ifdef EUSERS
956 case EUSERS: return WSAEUSERS;
957 #endif
958 #ifdef EDQUOT
959 case EDQUOT: return WSAEDQUOT;
960 #endif
961 #ifdef ESTALE
962 case ESTALE: return WSAESTALE;
963 #endif
964 #ifdef EREMOTE
965 case EREMOTE: return WSAEREMOTE;
966 #endif
968 /* just in case we ever get here and there are no problems */
969 case 0: return 0;
970 default:
971 WARN("Unknown errno %d!\n", err);
972 return WSAEOPNOTSUPP;
976 static UINT wsaErrno(void)
978 int loc_errno = errno;
979 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
981 return sock_get_error( loc_errno );
984 /* most ws2 overlapped functions return an ntstatus-based error code */
985 static NTSTATUS wsaErrStatus(void)
987 int loc_errno = errno;
988 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
990 return sock_get_ntstatus(loc_errno);
993 static UINT wsaHerrno(int loc_errno)
995 WARN("h_errno %d.\n", loc_errno);
997 switch(loc_errno)
999 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
1000 case TRY_AGAIN: return WSATRY_AGAIN;
1001 case NO_RECOVERY: return WSANO_RECOVERY;
1002 case NO_DATA: return WSANO_DATA;
1003 case ENOBUFS: return WSAENOBUFS;
1005 case 0: return 0;
1006 default:
1007 WARN("Unknown h_errno %d!\n", loc_errno);
1008 return WSAEOPNOTSUPP;
1012 static inline DWORD NtStatusToWSAError( const DWORD status )
1014 /* We only need to cover the status codes set by server async request handling */
1015 DWORD wserr;
1016 switch ( status )
1018 case STATUS_SUCCESS: wserr = 0; break;
1019 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
1020 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
1021 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
1022 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
1023 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
1024 case STATUS_NETWORK_BUSY: wserr = WSAEALREADY; break;
1025 case STATUS_NETWORK_UNREACHABLE: wserr = WSAENETUNREACH; break;
1026 case STATUS_CONNECTION_REFUSED: wserr = WSAECONNREFUSED; break;
1027 case STATUS_CONNECTION_DISCONNECTED: wserr = WSAENOTCONN; break;
1028 case STATUS_CONNECTION_RESET: wserr = WSAECONNRESET; break;
1029 case STATUS_CONNECTION_ABORTED: wserr = WSAECONNABORTED; break;
1030 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
1031 case STATUS_ADDRESS_ALREADY_ASSOCIATED: wserr = WSAEADDRINUSE; break;
1032 case STATUS_IO_TIMEOUT:
1033 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
1034 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
1035 case STATUS_ACCESS_DENIED: wserr = WSAEACCES; break;
1036 case STATUS_TOO_MANY_OPENED_FILES: wserr = WSAEMFILE; break;
1037 case STATUS_CANT_WAIT: wserr = WSAEWOULDBLOCK; break;
1038 case STATUS_BUFFER_OVERFLOW: wserr = WSAEMSGSIZE; break;
1039 case STATUS_NOT_SUPPORTED: wserr = WSAEOPNOTSUPP; break;
1040 case STATUS_HOST_UNREACHABLE: wserr = WSAEHOSTUNREACH; break;
1042 default:
1043 wserr = RtlNtStatusToDosError( status );
1044 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
1046 return wserr;
1049 /* set last error code from NT status without mapping WSA errors */
1050 static inline unsigned int set_error( unsigned int err )
1052 if (err)
1054 err = NtStatusToWSAError( err );
1055 SetLastError( err );
1057 return err;
1060 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
1062 int fd;
1063 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
1064 return -1;
1065 return fd;
1068 static inline void release_sock_fd( SOCKET s, int fd )
1070 wine_server_release_fd( SOCKET2HANDLE(s), fd );
1073 static void _enable_event( HANDLE s, unsigned int event,
1074 unsigned int sstate, unsigned int cstate )
1076 SERVER_START_REQ( enable_socket_event )
1078 req->handle = wine_server_obj_handle( s );
1079 req->mask = event;
1080 req->sstate = sstate;
1081 req->cstate = cstate;
1082 wine_server_call( req );
1084 SERVER_END_REQ;
1087 static NTSTATUS _is_blocking(SOCKET s, BOOL *ret)
1089 NTSTATUS status;
1090 SERVER_START_REQ( get_socket_event )
1092 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1093 req->service = FALSE;
1094 req->c_event = 0;
1095 status = wine_server_call( req );
1096 *ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
1098 SERVER_END_REQ;
1099 return status;
1102 static unsigned int _get_sock_mask(SOCKET s)
1104 unsigned int ret;
1105 SERVER_START_REQ( get_socket_event )
1107 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1108 req->service = FALSE;
1109 req->c_event = 0;
1110 wine_server_call( req );
1111 ret = reply->mask;
1113 SERVER_END_REQ;
1114 return ret;
1117 static void _sync_sock_state(SOCKET s)
1119 BOOL dummy;
1120 /* do a dummy wineserver request in order to let
1121 the wineserver run through its select loop once */
1122 (void)_is_blocking(s, &dummy);
1125 static void _get_sock_errors(SOCKET s, int *events)
1127 SERVER_START_REQ( get_socket_event )
1129 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1130 req->service = FALSE;
1131 req->c_event = 0;
1132 wine_server_set_reply( req, events, sizeof(int) * FD_MAX_EVENTS );
1133 wine_server_call( req );
1135 SERVER_END_REQ;
1138 static int _get_sock_error(SOCKET s, unsigned int bit)
1140 int events[FD_MAX_EVENTS];
1141 _get_sock_errors(s, events);
1142 return events[bit];
1145 static int _get_fd_type(int fd)
1147 int sock_type = -1;
1148 socklen_t optlen = sizeof(sock_type);
1149 getsockopt(fd, SOL_SOCKET, SO_TYPE, (char*) &sock_type, &optlen);
1150 return sock_type;
1153 static struct per_thread_data *get_per_thread_data(void)
1155 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
1156 /* lazy initialization */
1157 if (!ptb)
1159 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
1160 NtCurrentTeb()->WinSockData = ptb;
1162 return ptb;
1165 static void free_per_thread_data(void)
1167 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
1169 if (!ptb) return;
1171 /* delete scratch buffers */
1172 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1173 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1174 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1175 HeapFree( GetProcessHeap(), 0, ptb->fd_cache );
1177 HeapFree( GetProcessHeap(), 0, ptb );
1178 NtCurrentTeb()->WinSockData = NULL;
1181 /***********************************************************************
1182 * DllMain (WS2_32.init)
1184 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
1186 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
1187 switch (fdwReason) {
1188 case DLL_PROCESS_ATTACH:
1189 break;
1190 case DLL_PROCESS_DETACH:
1191 if (fImpLoad) break;
1192 free_per_thread_data();
1193 DeleteCriticalSection(&csWSgetXXXbyYYY);
1194 break;
1195 case DLL_THREAD_DETACH:
1196 free_per_thread_data();
1197 break;
1199 return TRUE;
1202 /***********************************************************************
1203 * convert_flags()
1205 * Converts send/recv flags from Windows format.
1206 * Return the converted flag bits, unsupported flags remain unchanged.
1208 static int convert_flags(int flags)
1210 int i, out;
1211 if (!flags) return 0;
1213 for (out = i = 0; flags && i < sizeof(ws_flags_map) / sizeof(ws_flags_map[0]); i++)
1215 if (ws_flags_map[i][0] & flags)
1217 out |= ws_flags_map[i][1];
1218 flags &= ~ws_flags_map[i][0];
1221 if (flags)
1223 FIXME("Unknown send/recv flags 0x%x, using anyway...\n", flags);
1224 out |= flags;
1226 return out;
1229 /***********************************************************************
1230 * convert_sockopt()
1232 * Converts socket flags from Windows format.
1233 * Return 1 if converted, 0 if not (error).
1235 static int convert_sockopt(INT *level, INT *optname)
1237 unsigned int i;
1238 switch (*level)
1240 case WS_SOL_SOCKET:
1241 *level = SOL_SOCKET;
1242 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
1243 if( ws_sock_map[i][0] == *optname )
1245 *optname = ws_sock_map[i][1];
1246 return 1;
1249 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
1250 break;
1251 case WS_IPPROTO_TCP:
1252 *level = IPPROTO_TCP;
1253 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
1254 if ( ws_tcp_map[i][0] == *optname )
1256 *optname = ws_tcp_map[i][1];
1257 return 1;
1260 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
1261 break;
1262 case WS_IPPROTO_IP:
1263 *level = IPPROTO_IP;
1264 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
1265 if (ws_ip_map[i][0] == *optname )
1267 *optname = ws_ip_map[i][1];
1268 return 1;
1271 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
1272 break;
1273 case WS_IPPROTO_IPV6:
1274 *level = IPPROTO_IPV6;
1275 for(i=0; i<sizeof(ws_ipv6_map)/sizeof(ws_ipv6_map[0]); i++) {
1276 if (ws_ipv6_map[i][0] == *optname )
1278 *optname = ws_ipv6_map[i][1];
1279 return 1;
1282 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname);
1283 break;
1284 default: FIXME("Unimplemented or unknown socket level\n");
1286 return 0;
1289 /* ----------------------------------- Per-thread info (or per-process?) */
1291 static char *strdup_lower(const char *str)
1293 int i;
1294 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
1296 if (ret)
1298 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
1299 ret[i] = 0;
1301 else SetLastError(WSAENOBUFS);
1302 return ret;
1305 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
1306 * from an fd and return the value converted to milli seconds
1307 * or 0 if there is an infinite time out */
1308 static inline INT64 get_rcvsnd_timeo( int fd, BOOL is_recv)
1310 struct timeval tv;
1311 socklen_t len = sizeof(tv);
1312 int optname, res;
1314 if (is_recv)
1315 #ifdef SO_RCVTIMEO
1316 optname = SO_RCVTIMEO;
1317 #else
1318 return 0;
1319 #endif
1320 else
1321 #ifdef SO_SNDTIMEO
1322 optname = SO_SNDTIMEO;
1323 #else
1324 return 0;
1325 #endif
1327 res = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
1328 if (res < 0)
1329 return 0;
1330 return (UINT64)tv.tv_sec * 1000 + tv.tv_usec / 1000;
1333 /* utility: given an fd, will block until one of the events occurs */
1334 static inline int do_block( int fd, int events, int timeout )
1336 struct pollfd pfd;
1337 int ret;
1339 pfd.fd = fd;
1340 pfd.events = events;
1342 while ((ret = poll(&pfd, 1, timeout)) < 0)
1344 if (errno != EINTR)
1345 return -1;
1347 if( ret == 0 )
1348 return 0;
1349 return pfd.revents;
1352 static int
1353 convert_af_w2u(int windowsaf) {
1354 unsigned int i;
1356 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1357 if (ws_af_map[i][0] == windowsaf)
1358 return ws_af_map[i][1];
1359 FIXME("unhandled Windows address family %d\n", windowsaf);
1360 return -1;
1363 static int
1364 convert_af_u2w(int unixaf) {
1365 unsigned int i;
1367 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1368 if (ws_af_map[i][1] == unixaf)
1369 return ws_af_map[i][0];
1370 FIXME("unhandled UNIX address family %d\n", unixaf);
1371 return -1;
1374 static int
1375 convert_proto_w2u(int windowsproto) {
1376 unsigned int i;
1378 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1379 if (ws_proto_map[i][0] == windowsproto)
1380 return ws_proto_map[i][1];
1382 /* check for extended IPX */
1383 if (IS_IPX_PROTO(windowsproto))
1384 return windowsproto;
1386 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
1387 return -1;
1390 static int
1391 convert_proto_u2w(int unixproto) {
1392 unsigned int i;
1394 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1395 if (ws_proto_map[i][1] == unixproto)
1396 return ws_proto_map[i][0];
1398 /* if value is inside IPX range just return it - the kernel simply
1399 * echoes the value used in the socket() function */
1400 if (IS_IPX_PROTO(unixproto))
1401 return unixproto;
1403 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
1404 return -1;
1407 static int
1408 convert_socktype_w2u(int windowssocktype) {
1409 unsigned int i;
1411 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1412 if (ws_socktype_map[i][0] == windowssocktype)
1413 return ws_socktype_map[i][1];
1414 FIXME("unhandled Windows socket type %d\n", windowssocktype);
1415 return -1;
1418 static int
1419 convert_socktype_u2w(int unixsocktype) {
1420 unsigned int i;
1422 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1423 if (ws_socktype_map[i][1] == unixsocktype)
1424 return ws_socktype_map[i][0];
1425 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
1426 return -1;
1429 static int convert_poll_w2u(int events)
1431 int i, ret;
1432 for (i = ret = 0; events && i < sizeof(ws_poll_map) / sizeof(ws_poll_map[0]); i++)
1434 if (ws_poll_map[i][0] & events)
1436 ret |= ws_poll_map[i][1];
1437 events &= ~ws_poll_map[i][0];
1441 if (events)
1442 FIXME("Unsupported WSAPoll() flags 0x%x\n", events);
1443 return ret;
1446 static int convert_poll_u2w(int events)
1448 int i, ret;
1449 for (i = ret = 0; events && i < sizeof(ws_poll_map) / sizeof(ws_poll_map[0]); i++)
1451 if (ws_poll_map[i][1] & events)
1453 ret |= ws_poll_map[i][0];
1454 events &= ~ws_poll_map[i][1];
1458 if (events)
1459 FIXME("Unsupported poll() flags 0x%x\n", events);
1460 return ret;
1463 static int set_ipx_packettype(int sock, int ptype)
1465 #ifdef HAS_IPX
1466 int fd = get_sock_fd( sock, 0, NULL ), ret = 0;
1467 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", ptype, fd);
1469 if (fd == -1) return SOCKET_ERROR;
1471 /* We try to set the ipx type on ipx socket level. */
1472 #ifdef SOL_IPX
1473 if(setsockopt(fd, SOL_IPX, IPX_TYPE, &ptype, sizeof(ptype)) == -1)
1475 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
1476 ret = SOCKET_ERROR;
1478 #else
1480 struct ipx val;
1481 /* Should we retrieve val using a getsockopt call and then
1482 * set the modified one? */
1483 val.ipx_pt = ptype;
1484 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
1486 #endif
1487 release_sock_fd( sock, fd );
1488 return ret;
1489 #else
1490 WARN("IPX support is not enabled, can't set packet type\n");
1491 return SOCKET_ERROR;
1492 #endif
1495 /* ----------------------------------- API -----
1497 * Init / cleanup / error checking.
1500 /***********************************************************************
1501 * WSAStartup (WS2_32.115)
1503 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
1505 TRACE("verReq=%x\n", wVersionRequested);
1507 if (LOBYTE(wVersionRequested) < 1)
1508 return WSAVERNOTSUPPORTED;
1510 if (!lpWSAData) return WSAEINVAL;
1512 num_startup++;
1514 /* that's the whole of the negotiation for now */
1515 lpWSAData->wVersion = wVersionRequested;
1516 /* return winsock information */
1517 lpWSAData->wHighVersion = 0x0202;
1518 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
1519 strcpy(lpWSAData->szSystemStatus, "Running" );
1520 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
1521 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
1522 /* don't do anything with lpWSAData->lpVendorInfo */
1523 /* (some apps don't allocate the space for this field) */
1525 TRACE("succeeded starts: %d\n", num_startup);
1526 return 0;
1530 /***********************************************************************
1531 * WSACleanup (WS2_32.116)
1533 INT WINAPI WSACleanup(void)
1535 if (num_startup) {
1536 num_startup--;
1537 TRACE("pending cleanups: %d\n", num_startup);
1538 return 0;
1540 SetLastError(WSANOTINITIALISED);
1541 return SOCKET_ERROR;
1545 /***********************************************************************
1546 * WSAGetLastError (WS2_32.111)
1548 INT WINAPI WSAGetLastError(void)
1550 return GetLastError();
1553 /***********************************************************************
1554 * WSASetLastError (WS2_32.112)
1556 void WINAPI WSASetLastError(INT iError) {
1557 SetLastError(iError);
1560 static struct WS_hostent *check_buffer_he(int size)
1562 struct per_thread_data * ptb = get_per_thread_data();
1563 if (ptb->he_buffer)
1565 if (ptb->he_len >= size ) return ptb->he_buffer;
1566 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1568 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
1569 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
1570 return ptb->he_buffer;
1573 static struct WS_servent *check_buffer_se(int size)
1575 struct per_thread_data * ptb = get_per_thread_data();
1576 if (ptb->se_buffer)
1578 if (ptb->se_len >= size ) return ptb->se_buffer;
1579 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1581 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
1582 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
1583 return ptb->se_buffer;
1586 static struct WS_protoent *check_buffer_pe(int size)
1588 struct per_thread_data * ptb = get_per_thread_data();
1589 if (ptb->pe_buffer)
1591 if (ptb->pe_len >= size ) return ptb->pe_buffer;
1592 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1594 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
1595 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
1596 return ptb->pe_buffer;
1599 /* ----------------------------------- i/o APIs */
1601 static inline BOOL supported_pf(int pf)
1603 switch (pf)
1605 case WS_AF_INET:
1606 case WS_AF_INET6:
1607 return TRUE;
1608 #ifdef HAS_IPX
1609 case WS_AF_IPX:
1610 return TRUE;
1611 #endif
1612 #ifdef HAS_IRDA
1613 case WS_AF_IRDA:
1614 return TRUE;
1615 #endif
1616 default:
1617 return FALSE;
1621 static inline BOOL supported_protocol(int protocol)
1623 int i;
1624 for (i = 0; i < sizeof(valid_protocols) / sizeof(valid_protocols[0]); i++)
1625 if (protocol == valid_protocols[i])
1626 return TRUE;
1627 return FALSE;
1630 /**********************************************************************/
1632 /* Returns the length of the converted address if successful, 0 if it was too small to
1633 * start with.
1635 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
1636 union generic_unix_sockaddr *uaddr)
1638 unsigned int uaddrlen = 0;
1640 switch (wsaddr->sa_family)
1642 #ifdef HAS_IPX
1643 case WS_AF_IPX:
1645 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
1646 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
1648 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
1649 return 0;
1651 uaddrlen = sizeof(struct sockaddr_ipx);
1652 memset( uaddr, 0, uaddrlen );
1653 uipx->sipx_family=AF_IPX;
1654 uipx->sipx_port=wsipx->sa_socket;
1655 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1656 * in one go
1658 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
1659 #ifdef IPX_FRAME_NONE
1660 uipx->sipx_type=IPX_FRAME_NONE;
1661 #endif
1662 break;
1664 #endif
1665 case WS_AF_INET6: {
1666 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
1667 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
1669 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1670 * scope_id, one without.
1672 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
1673 uaddrlen = sizeof(struct sockaddr_in6);
1674 memset( uaddr, 0, uaddrlen );
1675 uin6->sin6_family = AF_INET6;
1676 uin6->sin6_port = win6->sin6_port;
1677 uin6->sin6_flowinfo = win6->sin6_flowinfo;
1678 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1679 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
1680 #endif
1681 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
1682 break;
1684 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
1685 return 0;
1687 case WS_AF_INET: {
1688 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
1689 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
1691 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
1692 return 0;
1693 uaddrlen = sizeof(struct sockaddr_in);
1694 memset( uaddr, 0, uaddrlen );
1695 uin->sin_family = AF_INET;
1696 uin->sin_port = win->sin_port;
1697 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
1698 break;
1700 #ifdef HAS_IRDA
1701 case WS_AF_IRDA: {
1702 struct sockaddr_irda *uin = (struct sockaddr_irda *)uaddr;
1703 const SOCKADDR_IRDA *win = (const SOCKADDR_IRDA *)wsaddr;
1705 if (wsaddrlen < sizeof(SOCKADDR_IRDA))
1706 return 0;
1707 uaddrlen = sizeof(struct sockaddr_irda);
1708 memset( uaddr, 0, uaddrlen );
1709 uin->sir_family = AF_IRDA;
1710 if (!strncmp( win->irdaServiceName, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1712 unsigned int lsap_sel = 0;
1714 sscanf( win->irdaServiceName, "LSAP-SEL%u", &lsap_sel );
1715 uin->sir_lsap_sel = lsap_sel;
1717 else
1719 uin->sir_lsap_sel = LSAP_ANY;
1720 memcpy( uin->sir_name, win->irdaServiceName, 25 );
1722 memcpy( &uin->sir_addr, win->irdaDeviceID, sizeof(uin->sir_addr) );
1723 break;
1725 #endif
1726 case WS_AF_UNSPEC: {
1727 /* Try to determine the needed space by the passed windows sockaddr space */
1728 switch (wsaddrlen) {
1729 default: /* likely an ipv4 address */
1730 case sizeof(struct WS_sockaddr_in):
1731 uaddrlen = sizeof(struct sockaddr_in);
1732 break;
1733 #ifdef HAS_IPX
1734 case sizeof(struct WS_sockaddr_ipx):
1735 uaddrlen = sizeof(struct sockaddr_ipx);
1736 break;
1737 #endif
1738 #ifdef HAS_IRDA
1739 case sizeof(SOCKADDR_IRDA):
1740 uaddrlen = sizeof(struct sockaddr_irda);
1741 break;
1742 #endif
1743 case sizeof(struct WS_sockaddr_in6):
1744 case sizeof(struct WS_sockaddr_in6_old):
1745 uaddrlen = sizeof(struct sockaddr_in6);
1746 break;
1748 memset( uaddr, 0, uaddrlen );
1749 break;
1751 default:
1752 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
1753 return 0;
1755 return uaddrlen;
1758 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
1760 switch (uaddr->sa_family)
1762 #ifdef HAS_IPX
1763 case AF_IPX:
1765 static const struct sockaddr_ipx emptyAddr;
1766 struct sockaddr_ipx *ipx = (struct sockaddr_ipx*) uaddr;
1767 return ipx->sipx_port
1768 || memcmp(&ipx->sipx_network, &emptyAddr.sipx_network, sizeof(emptyAddr.sipx_network))
1769 || memcmp(&ipx->sipx_node, &emptyAddr.sipx_node, sizeof(emptyAddr.sipx_node));
1771 #endif
1772 case AF_INET6:
1774 static const struct sockaddr_in6 emptyAddr;
1775 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
1776 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
1778 case AF_INET:
1780 static const struct sockaddr_in emptyAddr;
1781 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
1782 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
1784 case AF_UNSPEC:
1785 return FALSE;
1786 default:
1787 FIXME("unknown address family %d\n", uaddr->sa_family);
1788 return TRUE;
1792 /* Returns -1 if getsockname fails, 0 if not bound, 1 otherwise */
1793 static int is_fd_bound(int fd, union generic_unix_sockaddr *uaddr, socklen_t *uaddrlen)
1795 union generic_unix_sockaddr inaddr;
1796 socklen_t inlen;
1797 int res;
1799 if (!uaddr) uaddr = &inaddr;
1800 if (!uaddrlen) uaddrlen = &inlen;
1802 *uaddrlen = sizeof(inaddr);
1803 res = getsockname(fd, &uaddr->addr, uaddrlen);
1804 if (!res) res = is_sockaddr_bound(&uaddr->addr, *uaddrlen);
1805 return res;
1808 /* Returns 0 if successful, -1 if the buffer is too small */
1809 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
1811 int res;
1813 switch(uaddr->sa_family)
1815 #ifdef HAS_IPX
1816 case AF_IPX:
1818 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
1819 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
1821 res=-1;
1822 switch (*wsaddrlen) /* how much can we copy? */
1824 default:
1825 res=0; /* enough */
1826 *wsaddrlen = sizeof(*wsipx);
1827 wsipx->sa_socket=uipx->sipx_port;
1828 /* fall through */
1829 case 13:
1830 case 12:
1831 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
1832 /* fall through */
1833 case 11:
1834 case 10:
1835 case 9:
1836 case 8:
1837 case 7:
1838 case 6:
1839 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1840 /* fall through */
1841 case 5:
1842 case 4:
1843 case 3:
1844 case 2:
1845 wsipx->sa_family=WS_AF_IPX;
1846 /* fall through */
1847 case 1:
1848 case 0:
1849 /* way too small */
1850 break;
1853 break;
1854 #endif
1855 #ifdef HAS_IRDA
1856 case AF_IRDA: {
1857 const struct sockaddr_irda *uin = (const struct sockaddr_irda *)uaddr;
1858 SOCKADDR_IRDA *win = (SOCKADDR_IRDA *)wsaddr;
1860 if (*wsaddrlen < sizeof(SOCKADDR_IRDA))
1861 return -1;
1862 win->irdaAddressFamily = WS_AF_IRDA;
1863 memcpy( win->irdaDeviceID, &uin->sir_addr, sizeof(win->irdaDeviceID) );
1864 if (uin->sir_lsap_sel != LSAP_ANY)
1865 sprintf( win->irdaServiceName, "LSAP-SEL%u", uin->sir_lsap_sel );
1866 else
1867 memcpy( win->irdaServiceName, uin->sir_name,
1868 sizeof(win->irdaServiceName) );
1869 return 0;
1871 #endif
1872 case AF_INET6: {
1873 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1874 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1876 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1877 return -1;
1878 win6old->sin6_family = WS_AF_INET6;
1879 win6old->sin6_port = uin6->sin6_port;
1880 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1881 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1882 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1883 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1884 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1885 win6->sin6_scope_id = uin6->sin6_scope_id;
1886 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1888 else
1889 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1890 #else
1891 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1892 #endif
1893 return 0;
1895 case AF_INET: {
1896 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1897 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1899 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1900 return -1;
1901 win->sin_family = WS_AF_INET;
1902 win->sin_port = uin->sin_port;
1903 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1904 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1905 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1906 return 0;
1908 case AF_UNSPEC: {
1909 memset(wsaddr,0,*wsaddrlen);
1910 return 0;
1912 default:
1913 FIXME("Unknown address family %d\n", uaddr->sa_family);
1914 return -1;
1916 return res;
1919 static INT WS_DuplicateSocket(BOOL unicode, SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo)
1921 HANDLE hProcess;
1922 int size;
1923 WSAPROTOCOL_INFOW infow;
1925 TRACE("(unicode %d, socket %04lx, processid %x, buffer %p)\n",
1926 unicode, s, dwProcessId, lpProtocolInfo);
1928 if (!ws_protocol_info(s, unicode, &infow, &size))
1929 return SOCKET_ERROR;
1931 if (!(hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId)))
1933 SetLastError(WSAEINVAL);
1934 return SOCKET_ERROR;
1937 if (!lpProtocolInfo)
1939 CloseHandle(hProcess);
1940 SetLastError(WSAEFAULT);
1941 return SOCKET_ERROR;
1944 /* I don't know what the real Windoze does next, this is a hack */
1945 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
1946 * the target use the global duplicate, or we could copy a reference to us to the structure
1947 * and let the target duplicate it from us, but let's do it as simple as possible */
1948 memcpy(lpProtocolInfo, &infow, size);
1949 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
1950 hProcess, (LPHANDLE)&lpProtocolInfo->dwServiceFlags3,
1951 0, FALSE, DUPLICATE_SAME_ACCESS);
1952 CloseHandle(hProcess);
1953 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
1954 return 0;
1957 /*****************************************************************************
1958 * WS_EnterSingleProtocolW [internal]
1960 * enters the protocol information of one given protocol into the given
1961 * buffer.
1963 * RETURNS
1964 * TRUE if a protocol was entered into the buffer.
1966 * BUGS
1967 * - only implemented for IPX, SPX, SPXII, TCP, UDP
1968 * - there is no check that the operating system supports the returned
1969 * protocols
1971 static BOOL WS_EnterSingleProtocolW( INT protocol, WSAPROTOCOL_INFOW* info )
1973 memset( info, 0, sizeof(WSAPROTOCOL_INFOW) );
1974 info->iProtocol = protocol;
1976 switch (protocol)
1978 case WS_IPPROTO_TCP:
1979 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_EXPEDITED_DATA |
1980 XP1_GRACEFUL_CLOSE | XP1_GUARANTEED_ORDER |
1981 XP1_GUARANTEED_DELIVERY;
1982 info->ProviderId = ProviderIdIP;
1983 info->dwCatalogEntryId = 0x3e9;
1984 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1985 info->ProtocolChain.ChainLen = 1;
1986 info->iVersion = 2;
1987 info->iAddressFamily = WS_AF_INET;
1988 info->iMaxSockAddr = 0x10;
1989 info->iMinSockAddr = 0x10;
1990 info->iSocketType = WS_SOCK_STREAM;
1991 strcpyW( info->szProtocol, NameTcpW );
1992 break;
1994 case WS_IPPROTO_UDP:
1995 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_SUPPORT_BROADCAST |
1996 XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED |
1997 XP1_CONNECTIONLESS;
1998 info->ProviderId = ProviderIdIP;
1999 info->dwCatalogEntryId = 0x3ea;
2000 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
2001 info->ProtocolChain.ChainLen = 1;
2002 info->iVersion = 2;
2003 info->iAddressFamily = WS_AF_INET;
2004 info->iMaxSockAddr = 0x10;
2005 info->iMinSockAddr = 0x10;
2006 info->iSocketType = WS_SOCK_DGRAM;
2007 info->dwMessageSize = 0xffbb;
2008 strcpyW( info->szProtocol, NameUdpW );
2009 break;
2011 case WS_NSPROTO_IPX:
2012 info->dwServiceFlags1 = XP1_PARTIAL_MESSAGE | XP1_SUPPORT_BROADCAST |
2013 XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED |
2014 XP1_CONNECTIONLESS;
2015 info->ProviderId = ProviderIdIPX;
2016 info->dwCatalogEntryId = 0x406;
2017 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
2018 info->ProtocolChain.ChainLen = 1;
2019 info->iVersion = 2;
2020 info->iAddressFamily = WS_AF_IPX;
2021 info->iMaxSockAddr = 0x10;
2022 info->iMinSockAddr = 0x0e;
2023 info->iSocketType = WS_SOCK_DGRAM;
2024 info->iProtocolMaxOffset = 0xff;
2025 info->dwMessageSize = 0x240;
2026 strcpyW( info->szProtocol, NameIpxW );
2027 break;
2029 case WS_NSPROTO_SPX:
2030 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_PSEUDO_STREAM |
2031 XP1_MESSAGE_ORIENTED | XP1_GUARANTEED_ORDER |
2032 XP1_GUARANTEED_DELIVERY;
2033 info->ProviderId = ProviderIdSPX;
2034 info->dwCatalogEntryId = 0x407;
2035 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
2036 info->ProtocolChain.ChainLen = 1;
2037 info->iVersion = 2;
2038 info->iAddressFamily = WS_AF_IPX;
2039 info->iMaxSockAddr = 0x10;
2040 info->iMinSockAddr = 0x0e;
2041 info->iSocketType = WS_SOCK_SEQPACKET;
2042 info->dwMessageSize = 0xffffffff;
2043 strcpyW( info->szProtocol, NameSpxW );
2044 break;
2046 case WS_NSPROTO_SPXII:
2047 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_GRACEFUL_CLOSE |
2048 XP1_PSEUDO_STREAM | XP1_MESSAGE_ORIENTED |
2049 XP1_GUARANTEED_ORDER | XP1_GUARANTEED_DELIVERY;
2050 info->ProviderId = ProviderIdSPX;
2051 info->dwCatalogEntryId = 0x409;
2052 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
2053 info->ProtocolChain.ChainLen = 1;
2054 info->iVersion = 2;
2055 info->iAddressFamily = WS_AF_IPX;
2056 info->iMaxSockAddr = 0x10;
2057 info->iMinSockAddr = 0x0e;
2058 info->iSocketType = WS_SOCK_SEQPACKET;
2059 info->dwMessageSize = 0xffffffff;
2060 strcpyW( info->szProtocol, NameSpxIIW );
2061 break;
2063 default:
2064 FIXME("unknown Protocol <0x%08x>\n", protocol);
2065 return FALSE;
2067 return TRUE;
2070 /*****************************************************************************
2071 * WS_EnterSingleProtocolA [internal]
2073 * see function WS_EnterSingleProtocolW
2076 static BOOL WS_EnterSingleProtocolA( INT protocol, WSAPROTOCOL_INFOA* info )
2078 WSAPROTOCOL_INFOW infow;
2079 INT ret;
2080 memset( info, 0, sizeof(WSAPROTOCOL_INFOA) );
2082 ret = WS_EnterSingleProtocolW( protocol, &infow );
2083 if (ret)
2085 /* convert the structure from W to A */
2086 memcpy( info, &infow, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
2087 WideCharToMultiByte( CP_ACP, 0, infow.szProtocol, -1,
2088 info->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL );
2091 return ret;
2094 static INT WS_EnumProtocols( BOOL unicode, const INT *protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
2096 INT i = 0, items = 0;
2097 DWORD size = 0;
2098 union _info
2100 LPWSAPROTOCOL_INFOA a;
2101 LPWSAPROTOCOL_INFOW w;
2102 } info;
2103 info.w = buffer;
2105 if (!protocols) protocols = valid_protocols;
2107 while (protocols[i])
2109 if(supported_protocol(protocols[i++]))
2110 items++;
2113 size = items * (unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA));
2115 TRACE("unicode %d, protocols %p, buffer %p, length %p %d, items %d, required %d\n",
2116 unicode, protocols, buffer, len, len ? *len : 0, items, size);
2118 if (*len < size || !buffer)
2120 *len = size;
2121 SetLastError(WSAENOBUFS);
2122 return SOCKET_ERROR;
2125 for (i = items = 0; protocols[i]; i++)
2127 if (!supported_protocol(protocols[i])) continue;
2128 if (unicode)
2130 if (WS_EnterSingleProtocolW( protocols[i], &info.w[items] ))
2131 items++;
2133 else
2135 if (WS_EnterSingleProtocolA( protocols[i], &info.a[items] ))
2136 items++;
2139 return items;
2142 static BOOL ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size)
2144 NTSTATUS status;
2146 *size = unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA);
2147 memset(buffer, 0, *size);
2149 SERVER_START_REQ( get_socket_info )
2151 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
2152 status = wine_server_call( req );
2153 if (!status)
2155 buffer->iAddressFamily = convert_af_u2w(reply->family);
2156 buffer->iSocketType = convert_socktype_u2w(reply->type);
2157 buffer->iProtocol = convert_proto_u2w(reply->protocol);
2160 SERVER_END_REQ;
2162 if (status)
2164 unsigned int err = NtStatusToWSAError( status );
2165 SetLastError( err == WSAEBADF ? WSAENOTSOCK : err );
2166 return FALSE;
2169 if (unicode)
2170 WS_EnterSingleProtocolW( buffer->iProtocol, buffer);
2171 else
2172 WS_EnterSingleProtocolA( buffer->iProtocol, (WSAPROTOCOL_INFOA *)buffer);
2174 return TRUE;
2177 /**************************************************************************
2178 * Functions for handling overlapped I/O
2179 **************************************************************************/
2181 /* user APC called upon async completion */
2182 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
2184 struct ws2_async *wsa = arg;
2186 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
2187 iosb->Information, wsa->user_overlapped,
2188 wsa->flags );
2189 release_async_io( &wsa->io );
2192 /***********************************************************************
2193 * WS2_recv (INTERNAL)
2195 * Workhorse for both synchronous and asynchronous recv() operations.
2197 static int WS2_recv( int fd, struct ws2_async *wsa, int flags )
2199 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2200 char pktbuf[512];
2201 #endif
2202 struct msghdr hdr;
2203 union generic_unix_sockaddr unix_sockaddr;
2204 int n;
2206 hdr.msg_name = NULL;
2208 if (wsa->addr)
2210 hdr.msg_namelen = sizeof(unix_sockaddr);
2211 hdr.msg_name = &unix_sockaddr;
2213 else
2214 hdr.msg_namelen = 0;
2216 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
2217 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
2218 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2219 hdr.msg_accrights = NULL;
2220 hdr.msg_accrightslen = 0;
2221 #else
2222 hdr.msg_control = pktbuf;
2223 hdr.msg_controllen = sizeof(pktbuf);
2224 hdr.msg_flags = 0;
2225 #endif
2227 while ((n = recvmsg(fd, &hdr, flags)) == -1)
2229 if (errno != EINTR)
2230 return -1;
2233 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2234 if (wsa->control)
2236 ERR("Message control headers cannot be properly supported on this system.\n");
2237 wsa->control->len = 0;
2239 #else
2240 if (wsa->control && !convert_control_headers(&hdr, wsa->control))
2242 WARN("Application passed insufficient room for control headers.\n");
2243 *wsa->lpFlags |= WS_MSG_CTRUNC;
2244 errno = EMSGSIZE;
2245 return -1;
2247 #endif
2249 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
2250 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
2252 * quoting linux 2.6 net/ipv4/tcp.c:
2253 * "According to UNIX98, msg_name/msg_namelen are ignored
2254 * on connected socket. I was just happy when found this 8) --ANK"
2256 * likewise MSDN says that lpFrom and lpFromlen are ignored for
2257 * connection-oriented sockets, so don't try to update lpFrom.
2259 if (wsa->addr && hdr.msg_namelen)
2260 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
2262 return n;
2265 /***********************************************************************
2266 * WS2_async_recv (INTERNAL)
2268 * Handler for overlapped recv() operations.
2270 static NTSTATUS WS2_async_recv( void *user, IO_STATUS_BLOCK *iosb,
2271 NTSTATUS status, void **apc, void **arg )
2273 struct ws2_async *wsa = user;
2274 int result = 0, fd;
2276 switch (status)
2278 case STATUS_ALERTED:
2279 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
2280 break;
2282 result = WS2_recv( fd, wsa, convert_flags(wsa->flags) );
2283 wine_server_release_fd( wsa->hSocket, fd );
2284 if (result >= 0)
2286 status = STATUS_SUCCESS;
2287 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
2289 else
2291 if (errno == EAGAIN)
2293 status = STATUS_PENDING;
2294 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
2296 else
2298 result = 0;
2299 status = wsaErrStatus();
2302 break;
2304 if (status != STATUS_PENDING)
2306 iosb->u.Status = status;
2307 iosb->Information = result;
2308 if (wsa->completion_func)
2310 *apc = ws2_async_apc;
2311 *arg = wsa;
2313 else
2314 release_async_io( &wsa->io );
2316 return status;
2319 /***********************************************************************
2320 * WS2_async_accept_recv (INTERNAL)
2322 * This function is used to finish the read part of an accept request. It is
2323 * needed to place the completion on the correct socket (listener).
2325 static NTSTATUS WS2_async_accept_recv( void *user, IO_STATUS_BLOCK *iosb,
2326 NTSTATUS status, void **apc, void **arg )
2328 void *junk;
2329 struct ws2_accept_async *wsa = user;
2331 status = WS2_async_recv( wsa->read, iosb, status, &junk, &junk );
2332 if (status == STATUS_PENDING)
2333 return status;
2335 if (wsa->cvalue)
2336 WS_AddCompletion( HANDLE2SOCKET(wsa->listen_socket), wsa->cvalue, iosb->u.Status, iosb->Information );
2338 release_async_io( &wsa->io );
2339 return status;
2342 /***********************************************************************
2343 * WS2_async_accept (INTERNAL)
2345 * This is the function called to satisfy the AcceptEx callback
2347 static NTSTATUS WS2_async_accept( void *user, IO_STATUS_BLOCK *iosb,
2348 NTSTATUS status, void **apc, void **arg )
2350 struct ws2_accept_async *wsa = user;
2351 int len;
2352 char *addr;
2354 TRACE("status: 0x%x listen: %p, accept: %p\n", status, wsa->listen_socket, wsa->accept_socket);
2356 if (status == STATUS_ALERTED)
2358 SERVER_START_REQ( accept_into_socket )
2360 req->lhandle = wine_server_obj_handle( wsa->listen_socket );
2361 req->ahandle = wine_server_obj_handle( wsa->accept_socket );
2362 status = wine_server_call( req );
2364 SERVER_END_REQ;
2366 if (status == STATUS_CANT_WAIT)
2367 return STATUS_PENDING;
2369 if (status == STATUS_INVALID_HANDLE)
2371 FIXME("AcceptEx accepting socket closed but request was not cancelled\n");
2372 status = STATUS_CANCELLED;
2375 else if (status == STATUS_HANDLES_CLOSED)
2376 status = STATUS_CANCELLED; /* strange windows behavior */
2378 if (status != STATUS_SUCCESS)
2379 goto finish;
2381 /* WS2 Spec says size param is extra 16 bytes long...what do we put in it? */
2382 addr = ((char *)wsa->buf) + wsa->data_len;
2383 len = wsa->local_len - sizeof(int);
2384 WS_getsockname(HANDLE2SOCKET(wsa->accept_socket),
2385 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
2386 *(int *)addr = len;
2388 addr += wsa->local_len;
2389 len = wsa->remote_len - sizeof(int);
2390 WS_getpeername(HANDLE2SOCKET(wsa->accept_socket),
2391 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
2392 *(int *)addr = len;
2394 if (!wsa->read)
2395 goto finish;
2397 SERVER_START_REQ( register_async )
2399 req->type = ASYNC_TYPE_READ;
2400 req->async.handle = wine_server_obj_handle( wsa->accept_socket );
2401 req->async.event = wine_server_obj_handle( wsa->user_overlapped->hEvent );
2402 req->async.callback = wine_server_client_ptr( WS2_async_accept_recv );
2403 req->async.iosb = wine_server_client_ptr( iosb );
2404 req->async.arg = wine_server_client_ptr( wsa );
2405 status = wine_server_call( req );
2407 SERVER_END_REQ;
2409 if (status != STATUS_PENDING)
2410 goto finish;
2412 /* The APC has finished but no completion should be sent for the operation yet, additional processing
2413 * needs to be performed by WS2_async_accept_recv() first. */
2414 return STATUS_MORE_PROCESSING_REQUIRED;
2416 finish:
2417 iosb->u.Status = status;
2418 iosb->Information = 0;
2420 if (wsa->read) release_async_io( &wsa->read->io );
2421 release_async_io( &wsa->io );
2422 return status;
2425 /***********************************************************************
2426 * WS2_send (INTERNAL)
2428 * Workhorse for both synchronous and asynchronous send() operations.
2430 static int WS2_send( int fd, struct ws2_async *wsa, int flags )
2432 struct msghdr hdr;
2433 union generic_unix_sockaddr unix_addr;
2434 int n, ret;
2436 hdr.msg_name = NULL;
2437 hdr.msg_namelen = 0;
2439 if (wsa->addr)
2441 hdr.msg_name = &unix_addr;
2442 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
2443 if ( !hdr.msg_namelen )
2445 errno = EFAULT;
2446 return -1;
2449 #if defined(HAS_IPX) && defined(SOL_IPX)
2450 if(wsa->addr->sa_family == WS_AF_IPX)
2452 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
2453 int val=0;
2454 socklen_t len = sizeof(int);
2456 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
2457 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
2458 * the packet type and then we can retrieve it using getsockopt. After that we can set the
2459 * ipx type in the sockaddr_opx structure with the stored value.
2461 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
2462 uipx->sipx_type = val;
2464 #endif
2467 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
2468 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
2469 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2470 hdr.msg_accrights = NULL;
2471 hdr.msg_accrightslen = 0;
2472 #else
2473 hdr.msg_control = NULL;
2474 hdr.msg_controllen = 0;
2475 hdr.msg_flags = 0;
2476 #endif
2478 while ((ret = sendmsg(fd, &hdr, flags)) == -1)
2480 if (errno != EINTR)
2481 return -1;
2484 n = ret;
2485 while (wsa->first_iovec < wsa->n_iovecs && wsa->iovec[wsa->first_iovec].iov_len <= n)
2486 n -= wsa->iovec[wsa->first_iovec++].iov_len;
2487 if (wsa->first_iovec < wsa->n_iovecs)
2489 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
2490 wsa->iovec[wsa->first_iovec].iov_len -= n;
2492 return ret;
2495 /***********************************************************************
2496 * WS2_async_send (INTERNAL)
2498 * Handler for overlapped send() operations.
2500 static NTSTATUS WS2_async_send( void *user, IO_STATUS_BLOCK *iosb,
2501 NTSTATUS status, void **apc, void **arg )
2503 struct ws2_async *wsa = user;
2504 int result = 0, fd;
2506 switch (status)
2508 case STATUS_ALERTED:
2509 if ( wsa->n_iovecs <= wsa->first_iovec )
2511 /* Nothing to do */
2512 status = STATUS_SUCCESS;
2513 break;
2515 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
2516 break;
2518 /* check to see if the data is ready (non-blocking) */
2519 result = WS2_send( fd, wsa, convert_flags(wsa->flags) );
2520 wine_server_release_fd( wsa->hSocket, fd );
2522 if (result >= 0)
2524 if (wsa->first_iovec < wsa->n_iovecs)
2525 status = STATUS_PENDING;
2526 else
2527 status = STATUS_SUCCESS;
2529 iosb->Information += result;
2531 else if (errno == EAGAIN)
2533 status = STATUS_PENDING;
2535 else
2537 status = wsaErrStatus();
2539 break;
2541 if (status != STATUS_PENDING)
2543 iosb->u.Status = status;
2544 if (wsa->completion_func)
2546 *apc = ws2_async_apc;
2547 *arg = wsa;
2549 else
2550 release_async_io( &wsa->io );
2552 return status;
2555 /***********************************************************************
2556 * WS2_async_shutdown (INTERNAL)
2558 * Handler for shutdown() operations on overlapped sockets.
2560 static NTSTATUS WS2_async_shutdown( void *user, IO_STATUS_BLOCK *iosb,
2561 NTSTATUS status, void **apc, void **arg )
2563 struct ws2_async_shutdown *wsa = user;
2564 int fd, err = 1;
2566 switch (status)
2568 case STATUS_ALERTED:
2569 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
2570 break;
2572 switch ( wsa->type )
2574 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
2575 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
2577 status = err ? wsaErrStatus() : STATUS_SUCCESS;
2578 wine_server_release_fd( wsa->hSocket, fd );
2579 break;
2581 iosb->u.Status = status;
2582 iosb->Information = 0;
2583 release_async_io( &wsa->io );
2584 return status;
2587 /***********************************************************************
2588 * WS2_register_async_shutdown (INTERNAL)
2590 * Helper function for WS_shutdown() on overlapped sockets.
2592 static int WS2_register_async_shutdown( SOCKET s, int type )
2594 struct ws2_async_shutdown *wsa;
2595 NTSTATUS status;
2597 TRACE("socket %04lx type %d\n", s, type);
2599 wsa = (struct ws2_async_shutdown *)alloc_async_io( sizeof(*wsa) );
2600 if ( !wsa )
2601 return WSAEFAULT;
2603 wsa->hSocket = SOCKET2HANDLE(s);
2604 wsa->type = type;
2606 SERVER_START_REQ( register_async )
2608 req->type = type;
2609 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2610 req->async.callback = wine_server_client_ptr( WS2_async_shutdown );
2611 req->async.iosb = wine_server_client_ptr( &wsa->iosb );
2612 req->async.arg = wine_server_client_ptr( wsa );
2613 req->async.cvalue = 0;
2614 status = wine_server_call( req );
2616 SERVER_END_REQ;
2618 if (status != STATUS_PENDING)
2620 HeapFree( GetProcessHeap(), 0, wsa );
2621 return NtStatusToWSAError( status );
2623 return 0;
2626 /***********************************************************************
2627 * accept (WS2_32.1)
2629 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr, int *addrlen32)
2631 NTSTATUS status;
2632 SOCKET as;
2633 BOOL is_blocking;
2635 TRACE("socket %04lx\n", s );
2636 status = _is_blocking(s, &is_blocking);
2637 if (status)
2639 set_error(status);
2640 return INVALID_SOCKET;
2643 do {
2644 /* try accepting first (if there is a deferred connection) */
2645 SERVER_START_REQ( accept_socket )
2647 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
2648 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
2649 req->attributes = OBJ_INHERIT;
2650 status = wine_server_call( req );
2651 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
2653 SERVER_END_REQ;
2654 if (!status)
2656 if (addr && addrlen32 && WS_getpeername(as, addr, addrlen32))
2658 WS_closesocket(as);
2659 return SOCKET_ERROR;
2661 TRACE("\taccepted %04lx\n", as);
2662 return as;
2664 if (is_blocking && status == STATUS_CANT_WAIT)
2666 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2667 /* block here */
2668 do_block(fd, POLLIN, -1);
2669 _sync_sock_state(s); /* let wineserver notice connection */
2670 release_sock_fd( s, fd );
2672 } while (is_blocking && status == STATUS_CANT_WAIT);
2674 set_error(status);
2675 return INVALID_SOCKET;
2678 /***********************************************************************
2679 * AcceptEx
2681 static BOOL WINAPI WS2_AcceptEx(SOCKET listener, SOCKET acceptor, PVOID dest, DWORD dest_len,
2682 DWORD local_addr_len, DWORD rem_addr_len, LPDWORD received,
2683 LPOVERLAPPED overlapped)
2685 DWORD status;
2686 struct ws2_accept_async *wsa;
2687 int fd;
2689 TRACE("(%04lx, %04lx, %p, %d, %d, %d, %p, %p)\n", listener, acceptor, dest, dest_len, local_addr_len,
2690 rem_addr_len, received, overlapped);
2692 if (!dest)
2694 SetLastError(WSAEINVAL);
2695 return FALSE;
2698 if (!overlapped)
2700 SetLastError(WSA_INVALID_PARAMETER);
2701 return FALSE;
2704 if (!rem_addr_len)
2706 SetLastError(WSAEFAULT);
2707 return FALSE;
2710 fd = get_sock_fd( listener, FILE_READ_DATA, NULL );
2711 if (fd == -1)
2713 SetLastError(WSAENOTSOCK);
2714 return FALSE;
2716 release_sock_fd( listener, fd );
2718 fd = get_sock_fd( acceptor, FILE_READ_DATA, NULL );
2719 if (fd == -1)
2721 SetLastError(WSAENOTSOCK);
2722 return FALSE;
2724 release_sock_fd( acceptor, fd );
2726 wsa = (struct ws2_accept_async *)alloc_async_io( sizeof(*wsa) );
2727 if(!wsa)
2729 SetLastError(WSAEFAULT);
2730 return FALSE;
2733 wsa->listen_socket = SOCKET2HANDLE(listener);
2734 wsa->accept_socket = SOCKET2HANDLE(acceptor);
2735 wsa->user_overlapped = overlapped;
2736 wsa->cvalue = !((ULONG_PTR)overlapped->hEvent & 1) ? (ULONG_PTR)overlapped : 0;
2737 wsa->buf = dest;
2738 wsa->data_len = dest_len;
2739 wsa->local_len = local_addr_len;
2740 wsa->remote_len = rem_addr_len;
2741 wsa->read = NULL;
2743 if (wsa->data_len)
2745 /* set up a read request if we need it */
2746 wsa->read = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[1]) );
2747 if (!wsa->read)
2749 HeapFree( GetProcessHeap(), 0, wsa );
2750 SetLastError(WSAEFAULT);
2751 return FALSE;
2754 wsa->read->hSocket = wsa->accept_socket;
2755 wsa->read->flags = 0;
2756 wsa->read->lpFlags = &wsa->read->flags;
2757 wsa->read->addr = NULL;
2758 wsa->read->addrlen.ptr = NULL;
2759 wsa->read->control = NULL;
2760 wsa->read->n_iovecs = 1;
2761 wsa->read->first_iovec = 0;
2762 wsa->read->completion_func = NULL;
2763 wsa->read->iovec[0].iov_base = wsa->buf;
2764 wsa->read->iovec[0].iov_len = wsa->data_len;
2767 SERVER_START_REQ( register_async )
2769 req->type = ASYNC_TYPE_READ;
2770 req->async.handle = wine_server_obj_handle( SOCKET2HANDLE(listener) );
2771 req->async.event = wine_server_obj_handle( overlapped->hEvent );
2772 req->async.callback = wine_server_client_ptr( WS2_async_accept );
2773 req->async.iosb = wine_server_client_ptr( overlapped );
2774 req->async.arg = wine_server_client_ptr( wsa );
2775 req->async.cvalue = wsa->cvalue;
2776 status = wine_server_call( req );
2778 SERVER_END_REQ;
2780 if(status != STATUS_PENDING)
2782 HeapFree( GetProcessHeap(), 0, wsa->read );
2783 HeapFree( GetProcessHeap(), 0, wsa );
2786 SetLastError( NtStatusToWSAError(status) );
2787 return FALSE;
2790 /***********************************************************************
2791 * WS2_ReadFile (INTERNAL)
2793 * Perform an APC-safe ReadFile operation
2795 static NTSTATUS WS2_ReadFile(HANDLE hFile, PIO_STATUS_BLOCK io_status, char* buffer, ULONG length,
2796 PLARGE_INTEGER offset)
2798 int result = -1, unix_handle;
2799 unsigned int options;
2800 NTSTATUS status;
2802 TRACE( "(%p,%p,0x%08x)\n", hFile, buffer,length );
2804 status = wine_server_handle_to_fd( hFile, FILE_READ_DATA, &unix_handle, &options );
2805 if (status) return status;
2807 while (result == -1)
2809 if (offset->QuadPart != FILE_USE_FILE_POINTER_POSITION)
2810 result = pread( unix_handle, buffer, length, offset->QuadPart );
2811 else
2812 result = read( unix_handle, buffer, length );
2813 if (errno != EINTR)
2814 break;
2817 if (!result)
2818 status = (length ? STATUS_END_OF_FILE : STATUS_SUCCESS);
2819 else if (result != -1)
2820 status = STATUS_SUCCESS;
2821 else if (errno != EAGAIN)
2822 status = wsaErrStatus();
2823 else
2824 status = STATUS_PENDING;
2826 wine_server_release_fd( hFile, unix_handle );
2827 TRACE("= 0x%08x (%d)\n", status, result);
2828 if (status == STATUS_SUCCESS || status == STATUS_END_OF_FILE)
2830 io_status->u.Status = status;
2831 io_status->Information = result;
2834 return status;
2837 /***********************************************************************
2838 * WS2_transmitfile_getbuffer (INTERNAL)
2840 * Pick the appropriate buffer for a TransmitFile send operation.
2842 static NTSTATUS WS2_transmitfile_getbuffer( int fd, struct ws2_transmitfile_async *wsa )
2844 /* send any incomplete writes from a previous iteration */
2845 if (wsa->write.first_iovec < wsa->write.n_iovecs)
2846 return STATUS_PENDING;
2848 /* process the header (if applicable) */
2849 if (wsa->buffers.Head)
2851 wsa->write.first_iovec = 0;
2852 wsa->write.n_iovecs = 1;
2853 wsa->write.iovec[0].iov_base = wsa->buffers.Head;
2854 wsa->write.iovec[0].iov_len = wsa->buffers.HeadLength;
2855 wsa->buffers.Head = NULL;
2856 return STATUS_PENDING;
2859 /* process the main file */
2860 if (wsa->file)
2862 DWORD bytes_per_send = wsa->bytes_per_send;
2863 IO_STATUS_BLOCK iosb;
2864 NTSTATUS status;
2866 iosb.Information = 0;
2867 /* when the size of the transfer is limited ensure that we don't go past that limit */
2868 if (wsa->file_bytes != 0)
2869 bytes_per_send = min(bytes_per_send, wsa->file_bytes - wsa->file_read);
2870 status = WS2_ReadFile( wsa->file, &iosb, wsa->buffer, bytes_per_send, &wsa->offset );
2871 if (wsa->offset.QuadPart != FILE_USE_FILE_POINTER_POSITION)
2872 wsa->offset.QuadPart += iosb.Information;
2873 if (status == STATUS_END_OF_FILE)
2874 wsa->file = NULL; /* continue on to the footer */
2875 else if (status != STATUS_SUCCESS)
2876 return status;
2877 else
2879 if (iosb.Information)
2881 wsa->write.first_iovec = 0;
2882 wsa->write.n_iovecs = 1;
2883 wsa->write.iovec[0].iov_base = wsa->buffer;
2884 wsa->write.iovec[0].iov_len = iosb.Information;
2885 wsa->file_read += iosb.Information;
2888 if (wsa->file_bytes != 0 && wsa->file_read >= wsa->file_bytes)
2889 wsa->file = NULL;
2891 return STATUS_PENDING;
2895 /* send the footer (if applicable) */
2896 if (wsa->buffers.Tail)
2898 wsa->write.first_iovec = 0;
2899 wsa->write.n_iovecs = 1;
2900 wsa->write.iovec[0].iov_base = wsa->buffers.Tail;
2901 wsa->write.iovec[0].iov_len = wsa->buffers.TailLength;
2902 wsa->buffers.Tail = NULL;
2903 return STATUS_PENDING;
2906 return STATUS_SUCCESS;
2909 /***********************************************************************
2910 * WS2_transmitfile_base (INTERNAL)
2912 * Shared implementation for both synchronous and asynchronous TransmitFile.
2914 static NTSTATUS WS2_transmitfile_base( int fd, struct ws2_transmitfile_async *wsa )
2916 NTSTATUS status;
2918 status = WS2_transmitfile_getbuffer( fd, wsa );
2919 if (status == STATUS_PENDING)
2921 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)wsa->write.user_overlapped;
2922 int n;
2924 n = WS2_send( fd, &wsa->write, convert_flags(wsa->write.flags) );
2925 if (n >= 0)
2927 if (iosb) iosb->Information += n;
2929 else if (errno != EAGAIN)
2930 return wsaErrStatus();
2933 return status;
2936 /***********************************************************************
2937 * WS2_async_transmitfile (INTERNAL)
2939 * Asynchronous callback for overlapped TransmitFile operations.
2941 static NTSTATUS WS2_async_transmitfile( void *user, IO_STATUS_BLOCK *iosb,
2942 NTSTATUS status, void **apc, void **arg )
2944 struct ws2_transmitfile_async *wsa = user;
2945 int fd;
2947 if (status == STATUS_ALERTED)
2949 if (!(status = wine_server_handle_to_fd( wsa->write.hSocket, FILE_WRITE_DATA, &fd, NULL )))
2951 status = WS2_transmitfile_base( fd, wsa );
2952 wine_server_release_fd( wsa->write.hSocket, fd );
2954 if (status == STATUS_PENDING)
2955 return status;
2958 iosb->u.Status = status;
2959 release_async_io( &wsa->io );
2960 return status;
2963 /***********************************************************************
2964 * TransmitFile
2966 static BOOL WINAPI WS2_TransmitFile( SOCKET s, HANDLE h, DWORD file_bytes, DWORD bytes_per_send,
2967 LPOVERLAPPED overlapped, LPTRANSMIT_FILE_BUFFERS buffers,
2968 DWORD flags )
2970 union generic_unix_sockaddr uaddr;
2971 unsigned int uaddrlen = sizeof(uaddr);
2972 struct ws2_transmitfile_async *wsa;
2973 NTSTATUS status;
2974 int fd;
2976 TRACE("(%lx, %p, %d, %d, %p, %p, %d)\n", s, h, file_bytes, bytes_per_send, overlapped,
2977 buffers, flags );
2979 fd = get_sock_fd( s, FILE_WRITE_DATA, NULL );
2980 if (fd == -1)
2982 WSASetLastError( WSAENOTSOCK );
2983 return FALSE;
2985 if (getpeername( fd, &uaddr.addr, &uaddrlen ) != 0)
2987 release_sock_fd( s, fd );
2988 WSASetLastError( WSAENOTCONN );
2989 return FALSE;
2991 if (flags)
2992 FIXME("Flags are not currently supported (0x%x).\n", flags);
2994 if (h && GetFileType( h ) != FILE_TYPE_DISK)
2996 FIXME("Non-disk file handles are not currently supported.\n");
2997 release_sock_fd( s, fd );
2998 WSASetLastError( WSAEOPNOTSUPP );
2999 return FALSE;
3002 /* set reasonable defaults when requested */
3003 if (!bytes_per_send)
3004 bytes_per_send = (1 << 16); /* Depends on OS version: PAGE_SIZE, 2*PAGE_SIZE, or 2^16 */
3006 if (!(wsa = (struct ws2_transmitfile_async *)alloc_async_io( sizeof(*wsa) + bytes_per_send )))
3008 release_sock_fd( s, fd );
3009 WSASetLastError( WSAEFAULT );
3010 return FALSE;
3012 if (buffers)
3013 wsa->buffers = *buffers;
3014 else
3015 memset(&wsa->buffers, 0x0, sizeof(wsa->buffers));
3016 wsa->buffer = (char *)(wsa + 1);
3017 wsa->file = h;
3018 wsa->file_read = 0;
3019 wsa->file_bytes = file_bytes;
3020 wsa->bytes_per_send = bytes_per_send;
3021 wsa->flags = flags;
3022 wsa->offset.QuadPart = FILE_USE_FILE_POINTER_POSITION;
3023 wsa->write.hSocket = SOCKET2HANDLE(s);
3024 wsa->write.addr = NULL;
3025 wsa->write.addrlen.val = 0;
3026 wsa->write.flags = 0;
3027 wsa->write.lpFlags = &wsa->flags;
3028 wsa->write.control = NULL;
3029 wsa->write.n_iovecs = 0;
3030 wsa->write.first_iovec = 0;
3031 wsa->write.user_overlapped = overlapped;
3032 if (overlapped)
3034 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)overlapped;
3035 int status;
3037 wsa->offset.u.LowPart = overlapped->u.s.Offset;
3038 wsa->offset.u.HighPart = overlapped->u.s.OffsetHigh;
3039 iosb->u.Status = STATUS_PENDING;
3040 iosb->Information = 0;
3041 SERVER_START_REQ( register_async )
3043 req->type = ASYNC_TYPE_WRITE;
3044 req->async.handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
3045 req->async.event = wine_server_obj_handle( overlapped->hEvent );
3046 req->async.callback = wine_server_client_ptr( WS2_async_transmitfile );
3047 req->async.iosb = wine_server_client_ptr( iosb );
3048 req->async.arg = wine_server_client_ptr( wsa );
3049 status = wine_server_call( req );
3051 SERVER_END_REQ;
3053 if(status != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
3054 release_sock_fd( s, fd );
3055 WSASetLastError( NtStatusToWSAError(status) );
3056 return FALSE;
3061 status = WS2_transmitfile_base( fd, wsa );
3062 if (status == STATUS_PENDING)
3064 /* block here */
3065 do_block(fd, POLLOUT, -1);
3066 _sync_sock_state(s); /* let wineserver notice connection */
3069 while (status == STATUS_PENDING);
3070 release_sock_fd( s, fd );
3072 if (status != STATUS_SUCCESS)
3073 WSASetLastError( NtStatusToWSAError(status) );
3074 HeapFree( GetProcessHeap(), 0, wsa );
3075 return (status == STATUS_SUCCESS);
3078 /***********************************************************************
3079 * GetAcceptExSockaddrs
3081 static void WINAPI WS2_GetAcceptExSockaddrs(PVOID buffer, DWORD data_size, DWORD local_size, DWORD remote_size,
3082 struct WS_sockaddr **local_addr, LPINT local_addr_len,
3083 struct WS_sockaddr **remote_addr, LPINT remote_addr_len)
3085 char *cbuf = buffer;
3086 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer, data_size, local_size, remote_size, local_addr,
3087 local_addr_len, remote_addr, remote_addr_len );
3088 cbuf += data_size;
3090 *local_addr_len = *(int *) cbuf;
3091 *local_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
3093 cbuf += local_size;
3095 *remote_addr_len = *(int *) cbuf;
3096 *remote_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
3099 /***********************************************************************
3100 * WSASendMsg
3102 int WINAPI WSASendMsg( SOCKET s, LPWSAMSG msg, DWORD dwFlags, LPDWORD lpNumberOfBytesSent,
3103 LPWSAOVERLAPPED lpOverlapped,
3104 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
3106 if (!msg)
3108 SetLastError( WSAEFAULT );
3109 return SOCKET_ERROR;
3112 return WS2_sendto( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesSent,
3113 dwFlags, msg->name, msg->namelen,
3114 lpOverlapped, lpCompletionRoutine );
3117 /***********************************************************************
3118 * WSARecvMsg
3120 * Perform a receive operation that is capable of returning message
3121 * control headers. It is important to note that the WSAMSG parameter
3122 * must remain valid throughout the operation, even when an overlapped
3123 * receive is performed.
3125 static int WINAPI WS2_WSARecvMsg( SOCKET s, LPWSAMSG msg, LPDWORD lpNumberOfBytesRecvd,
3126 LPWSAOVERLAPPED lpOverlapped,
3127 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3129 if (!msg)
3131 SetLastError( WSAEFAULT );
3132 return SOCKET_ERROR;
3135 return WS2_recv_base( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesRecvd,
3136 &msg->dwFlags, msg->name, &msg->namelen,
3137 lpOverlapped, lpCompletionRoutine, &msg->Control );
3140 /***********************************************************************
3141 * interface_bind (INTERNAL)
3143 * Take bind() calls on any name corresponding to a local network adapter and restrict the given socket to
3144 * operating only on the specified interface. This restriction consists of two components:
3145 * 1) An outgoing packet restriction suggesting the egress interface for all packets.
3146 * 2) An incoming packet restriction dropping packets not meant for the interface.
3147 * If the function succeeds in placing these restrictions (returns TRUE) then the name for the bind() may
3148 * safely be changed to INADDR_ANY, permitting the transmission and receipt of broadcast packets on the
3149 * socket. This behavior is only relevant to UDP sockets and is needed for applications that expect to be able
3150 * to receive broadcast packets on a socket that is bound to a specific network interface.
3152 static BOOL interface_bind( SOCKET s, int fd, struct sockaddr *addr )
3154 struct sockaddr_in *in_sock = (struct sockaddr_in *) addr;
3155 in_addr_t bind_addr = in_sock->sin_addr.s_addr;
3156 PIP_ADAPTER_INFO adapters = NULL, adapter;
3157 BOOL ret = FALSE;
3158 DWORD adap_size;
3159 int enable = 1;
3161 if (bind_addr == htonl(INADDR_ANY) || bind_addr == htonl(INADDR_LOOPBACK))
3162 return FALSE; /* Not binding to a network adapter, special interface binding unnecessary. */
3163 if (_get_fd_type(fd) != SOCK_DGRAM)
3164 return FALSE; /* Special interface binding is only necessary for UDP datagrams. */
3165 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
3166 goto cleanup;
3167 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
3168 if (adapters == NULL || GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
3169 goto cleanup;
3170 /* Search the IPv4 adapter list for the appropriate binding interface */
3171 for (adapter = adapters; adapter != NULL; adapter = adapter->Next)
3173 in_addr_t adapter_addr = (in_addr_t) inet_addr(adapter->IpAddressList.IpAddress.String);
3175 if (bind_addr == adapter_addr)
3177 #if defined(IP_BOUND_IF)
3178 /* IP_BOUND_IF sets both the incoming and outgoing restriction at once */
3179 if (setsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &adapter->Index, sizeof(adapter->Index)) != 0)
3180 goto cleanup;
3181 ret = TRUE;
3182 #elif defined(LINUX_BOUND_IF)
3183 in_addr_t ifindex = (in_addr_t) htonl(adapter->Index);
3184 struct interface_filter specific_interface_filter;
3185 struct sock_fprog filter_prog;
3187 if (setsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex, sizeof(ifindex)) != 0)
3188 goto cleanup; /* Failed to suggest egress interface */
3189 specific_interface_filter = generic_interface_filter;
3190 specific_interface_filter.iface_rule.k = adapter->Index;
3191 specific_interface_filter.ip_rule.k = htonl(adapter_addr);
3192 filter_prog.len = sizeof(generic_interface_filter)/sizeof(struct sock_filter);
3193 filter_prog.filter = (struct sock_filter *) &specific_interface_filter;
3194 if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog, sizeof(filter_prog)) != 0)
3195 goto cleanup; /* Failed to specify incoming packet filter */
3196 ret = TRUE;
3197 #else
3198 FIXME("Broadcast packets on interface-bound sockets are not currently supported on this platform, "
3199 "receiving broadcast packets will not work on socket %04lx.\n", s);
3200 #endif
3201 break;
3204 /* Will soon be switching to INADDR_ANY: permit address reuse */
3205 if (ret && setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) == 0)
3206 TRACE("Socket %04lx bound to interface index %d\n", s, adapter->Index);
3207 else
3208 ret = FALSE;
3210 cleanup:
3211 if(!ret)
3212 ERR("Failed to bind to interface, receiving broadcast packets will not work on socket %04lx.\n", s);
3213 HeapFree(GetProcessHeap(), 0, adapters);
3214 return ret;
3217 /***********************************************************************
3218 * bind (WS2_32.2)
3220 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
3222 int fd = get_sock_fd( s, 0, NULL );
3223 int res = SOCKET_ERROR;
3225 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
3227 if (fd != -1)
3229 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
3231 SetLastError(WSAEAFNOSUPPORT);
3233 else
3235 union generic_unix_sockaddr uaddr;
3236 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
3237 if (!uaddrlen)
3239 SetLastError(WSAEFAULT);
3241 else
3243 if (name->sa_family == WS_AF_INET)
3245 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
3246 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
3248 /* Trying to bind to the default host interface, using
3249 * INADDR_ANY instead*/
3250 WARN("Trying to bind to magic IP address, using "
3251 "INADDR_ANY instead.\n");
3252 in4->sin_addr.s_addr = htonl(INADDR_ANY);
3254 else if (interface_bind(s, fd, &uaddr.addr))
3255 in4->sin_addr.s_addr = htonl(INADDR_ANY);
3257 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
3259 int loc_errno = errno;
3260 WARN("\tfailure - errno = %i\n", errno);
3261 errno = loc_errno;
3262 switch (errno)
3264 case EADDRNOTAVAIL:
3265 SetLastError(WSAEINVAL);
3266 break;
3267 case EADDRINUSE:
3269 int optval = 0;
3270 socklen_t optlen = sizeof(optval);
3271 /* Windows >= 2003 will return different results depending on
3272 * SO_REUSEADDR, WSAEACCES may be returned representing that
3273 * the socket hijacking protection prevented the bind */
3274 if (!getsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&optval, &optlen) && optval)
3276 SetLastError(WSAEACCES);
3277 break;
3279 /* fall through */
3281 default:
3282 SetLastError(wsaErrno());
3283 break;
3286 else
3288 res=0; /* success */
3292 release_sock_fd( s, fd );
3294 return res;
3297 /***********************************************************************
3298 * closesocket (WS2_32.3)
3300 int WINAPI WS_closesocket(SOCKET s)
3302 int res = SOCKET_ERROR, fd;
3303 if (num_startup)
3305 fd = get_sock_fd(s, FILE_READ_DATA, NULL);
3306 if (fd >= 0)
3308 release_sock_fd(s, fd);
3309 if (CloseHandle(SOCKET2HANDLE(s)))
3310 res = 0;
3312 else
3313 SetLastError(WSAENOTSOCK);
3315 else
3316 SetLastError(WSANOTINITIALISED);
3317 TRACE("(socket %04lx) -> %d\n", s, res);
3318 return res;
3321 static int do_connect(int fd, const struct WS_sockaddr* name, int namelen)
3323 union generic_unix_sockaddr uaddr;
3324 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
3326 if (!uaddrlen)
3327 return WSAEFAULT;
3329 if (name->sa_family == WS_AF_INET)
3331 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
3332 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
3334 /* Trying to connect to magic replace-loopback address,
3335 * assuming we really want to connect to localhost */
3336 TRACE("Trying to connect to magic IP address, using "
3337 "INADDR_LOOPBACK instead.\n");
3338 in4->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
3342 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
3343 return 0;
3345 return wsaErrno();
3348 /***********************************************************************
3349 * connect (WS2_32.4)
3351 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
3353 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
3355 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
3357 if (fd != -1)
3359 NTSTATUS status;
3360 BOOL is_blocking;
3361 int ret = do_connect(fd, name, namelen);
3362 if (ret == 0)
3363 goto connect_success;
3365 if (ret == WSAEINPROGRESS)
3367 /* tell wineserver that a connection is in progress */
3368 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3369 FD_CONNECT,
3370 FD_WINE_CONNECTED|FD_WINE_LISTENING);
3371 status = _is_blocking( s, &is_blocking );
3372 if (status)
3374 release_sock_fd( s, fd );
3375 set_error( status );
3376 return SOCKET_ERROR;
3378 if (is_blocking)
3380 int result;
3381 /* block here */
3382 do_block(fd, POLLIN | POLLOUT, -1);
3383 _sync_sock_state(s); /* let wineserver notice connection */
3384 /* retrieve any error codes from it */
3385 result = _get_sock_error(s, FD_CONNECT_BIT);
3386 if (result)
3387 SetLastError(NtStatusToWSAError(result));
3388 else
3390 goto connect_success;
3393 else
3395 SetLastError(WSAEWOULDBLOCK);
3398 else
3400 SetLastError(ret);
3402 release_sock_fd( s, fd );
3404 return SOCKET_ERROR;
3406 connect_success:
3407 release_sock_fd( s, fd );
3408 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3409 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
3410 FD_CONNECT|FD_WINE_LISTENING);
3411 TRACE("\tconnected %04lx\n", s);
3412 return 0;
3415 /***********************************************************************
3416 * WSAConnect (WS2_32.30)
3418 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
3419 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
3420 LPQOS lpSQOS, LPQOS lpGQOS )
3422 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
3423 FIXME("unsupported parameters!\n");
3424 return WS_connect( s, name, namelen );
3427 /***********************************************************************
3428 * ConnectEx
3430 static BOOL WINAPI WS2_ConnectEx(SOCKET s, const struct WS_sockaddr* name, int namelen,
3431 PVOID sendBuf, DWORD sendBufLen, LPDWORD sent, LPOVERLAPPED ov)
3433 int fd, ret, status;
3435 if (!ov)
3437 SetLastError( ERROR_INVALID_PARAMETER );
3438 return FALSE;
3441 fd = get_sock_fd( s, FILE_READ_DATA, NULL );
3442 if (fd == -1)
3444 SetLastError( WSAENOTSOCK );
3445 return FALSE;
3448 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
3449 s, name, debugstr_sockaddr(name), namelen, sendBuf, sendBufLen, ov);
3451 ret = is_fd_bound(fd, NULL, NULL);
3452 if (ret <= 0)
3454 SetLastError(ret == -1 ? wsaErrno() : WSAEINVAL);
3455 release_sock_fd( s, fd );
3456 return FALSE;
3459 ret = do_connect(fd, name, namelen);
3460 if (ret == 0)
3462 WSABUF wsabuf;
3464 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3465 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
3466 FD_CONNECT|FD_WINE_LISTENING);
3468 wsabuf.len = sendBufLen;
3469 wsabuf.buf = (char*) sendBuf;
3471 /* WSASend takes care of completion if need be */
3472 if (WSASend(s, &wsabuf, sendBuf ? 1 : 0, sent, 0, ov, NULL) != SOCKET_ERROR)
3473 goto connection_success;
3475 else if (ret == WSAEINPROGRESS)
3477 struct ws2_async *wsa;
3478 ULONG_PTR cvalue = (((ULONG_PTR)ov->hEvent & 1) == 0) ? (ULONG_PTR)ov : 0;
3480 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3481 FD_CONNECT,
3482 FD_WINE_CONNECTED|FD_WINE_LISTENING);
3484 /* Indirectly call WSASend */
3485 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof( struct ws2_async, iovec[1] ))))
3487 SetLastError(WSAEFAULT);
3489 else
3491 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)ov;
3492 iosb->u.Status = STATUS_PENDING;
3493 iosb->Information = 0;
3495 wsa->hSocket = SOCKET2HANDLE(s);
3496 wsa->addr = NULL;
3497 wsa->addrlen.val = 0;
3498 wsa->flags = 0;
3499 wsa->lpFlags = &wsa->flags;
3500 wsa->control = NULL;
3501 wsa->n_iovecs = sendBuf ? 1 : 0;
3502 wsa->first_iovec = 0;
3503 wsa->completion_func = NULL;
3504 wsa->iovec[0].iov_base = sendBuf;
3505 wsa->iovec[0].iov_len = sendBufLen;
3507 SERVER_START_REQ( register_async )
3509 req->type = ASYNC_TYPE_WRITE;
3510 req->async.handle = wine_server_obj_handle( wsa->hSocket );
3511 req->async.callback = wine_server_client_ptr( WS2_async_send );
3512 req->async.iosb = wine_server_client_ptr( iosb );
3513 req->async.arg = wine_server_client_ptr( wsa );
3514 req->async.event = wine_server_obj_handle( ov->hEvent );
3515 req->async.cvalue = cvalue;
3516 status = wine_server_call( req );
3518 SERVER_END_REQ;
3520 if (status != STATUS_PENDING) HeapFree(GetProcessHeap(), 0, wsa);
3522 /* If the connect already failed */
3523 if (status == STATUS_PIPE_DISCONNECTED)
3524 status = _get_sock_error(s, FD_CONNECT_BIT);
3525 SetLastError( NtStatusToWSAError(status) );
3528 else
3530 SetLastError(ret);
3533 release_sock_fd( s, fd );
3534 return FALSE;
3536 connection_success:
3537 release_sock_fd( s, fd );
3538 return TRUE;
3541 /***********************************************************************
3542 * DisconnectEx
3544 static BOOL WINAPI WS2_DisconnectEx( SOCKET s, LPOVERLAPPED ov, DWORD flags, DWORD reserved )
3546 TRACE( "socket %04lx, ov %p, flags 0x%x, reserved 0x%x\n", s, ov, flags, reserved );
3548 if (flags & TF_REUSE_SOCKET)
3549 FIXME( "Reusing socket not supported yet\n" );
3551 if (ov)
3553 ov->Internal = STATUS_PENDING;
3554 ov->InternalHigh = 0;
3557 return !WS_shutdown( s, SD_BOTH );
3560 /***********************************************************************
3561 * getpeername (WS2_32.5)
3563 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
3565 int fd;
3566 int res;
3568 TRACE("socket %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
3570 fd = get_sock_fd( s, 0, NULL );
3571 res = SOCKET_ERROR;
3573 if (fd != -1)
3575 union generic_unix_sockaddr uaddr;
3576 socklen_t uaddrlen = sizeof(uaddr);
3578 if (getpeername(fd, &uaddr.addr, &uaddrlen) == 0)
3580 if (!name || !namelen)
3581 SetLastError(WSAEFAULT);
3582 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3583 /* The buffer was too small */
3584 SetLastError(WSAEFAULT);
3585 else
3587 res = 0;
3588 TRACE("=> %s\n", debugstr_sockaddr(name));
3591 else
3592 SetLastError(wsaErrno());
3593 release_sock_fd( s, fd );
3595 return res;
3598 /* When binding to an UDP address with filter support the getsockname call on the socket
3599 * will always return 0.0.0.0 instead of the filtered interface address. This function
3600 * checks if the socket is interface-bound on UDP and return the correct address.
3601 * This is required because applications often do a bind() with port zero followed by a
3602 * getsockname() to retrieve the port and address acquired.
3604 static void interface_bind_check(int fd, struct sockaddr_in *addr)
3606 #if !defined(IP_BOUND_IF) && !defined(LINUX_BOUND_IF)
3607 return;
3608 #else
3609 int ifindex;
3610 socklen_t len;
3612 /* Check for IPv4, address 0.0.0.0 and UDP socket */
3613 if (addr->sin_family != AF_INET || addr->sin_addr.s_addr != 0)
3614 return;
3615 if (_get_fd_type(fd) != SOCK_DGRAM)
3616 return;
3618 ifindex = -1;
3619 len = sizeof(ifindex);
3620 #if defined(IP_BOUND_IF)
3621 getsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &ifindex, &len);
3622 #elif defined(LINUX_BOUND_IF)
3623 getsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex, &len);
3624 if (ifindex > 0) ifindex = ntohl(ifindex);
3625 #endif
3626 if (ifindex > 0)
3628 PIP_ADAPTER_INFO adapters, adapter;
3629 DWORD adap_size;
3631 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
3632 return;
3633 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
3634 if (adapters && GetAdaptersInfo(adapters, &adap_size) == NO_ERROR)
3636 /* Search the IPv4 adapter list for the appropriate bound interface */
3637 for (adapter = adapters; adapter != NULL; adapter = adapter->Next)
3639 in_addr_t adapter_addr;
3640 if (adapter->Index != ifindex) continue;
3642 adapter_addr = inet_addr(adapter->IpAddressList.IpAddress.String);
3643 addr->sin_addr.s_addr = adapter_addr;
3644 TRACE("reporting interface address from adapter %d\n", ifindex);
3645 break;
3648 HeapFree(GetProcessHeap(), 0, adapters);
3650 #endif
3653 /***********************************************************************
3654 * getsockname (WS2_32.6)
3656 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
3658 int fd;
3659 int res;
3661 TRACE("socket %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
3663 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
3664 if( (name == NULL) || (namelen == NULL) )
3666 SetLastError( WSAEFAULT );
3667 return SOCKET_ERROR;
3670 fd = get_sock_fd( s, 0, NULL );
3671 res = SOCKET_ERROR;
3673 if (fd != -1)
3675 union generic_unix_sockaddr uaddr;
3676 socklen_t uaddrlen;
3677 int bound = is_fd_bound(fd, &uaddr, &uaddrlen);
3679 if (bound <= 0)
3681 SetLastError(bound == -1 ? wsaErrno() : WSAEINVAL);
3683 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3685 /* The buffer was too small */
3686 SetLastError(WSAEFAULT);
3688 else
3690 interface_bind_check(fd, (struct sockaddr_in*) &uaddr);
3691 if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3693 /* The buffer was too small */
3694 SetLastError(WSAEFAULT);
3696 else
3698 res = 0;
3699 TRACE("=> %s\n", debugstr_sockaddr(name));
3702 release_sock_fd( s, fd );
3704 return res;
3707 /***********************************************************************
3708 * getsockopt (WS2_32.7)
3710 INT WINAPI WS_getsockopt(SOCKET s, INT level,
3711 INT optname, char *optval, INT *optlen)
3713 int fd;
3714 INT ret = 0;
3716 TRACE("(socket %04lx, %s, optval %s, optlen %p (%d))\n", s,
3717 debugstr_sockopt(level, optname), debugstr_optval(optval, 0),
3718 optlen, optlen ? *optlen : 0);
3720 switch(level)
3722 case WS_SOL_SOCKET:
3724 switch(optname)
3726 /* Handle common cases. The special cases are below, sorted
3727 * alphabetically */
3728 case WS_SO_BROADCAST:
3729 case WS_SO_DEBUG:
3730 case WS_SO_KEEPALIVE:
3731 case WS_SO_OOBINLINE:
3732 case WS_SO_RCVBUF:
3733 case WS_SO_REUSEADDR:
3734 case WS_SO_SNDBUF:
3735 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3736 return SOCKET_ERROR;
3737 convert_sockopt(&level, &optname);
3738 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3740 SetLastError(wsaErrno());
3741 ret = SOCKET_ERROR;
3743 release_sock_fd( s, fd );
3744 return ret;
3745 case WS_SO_ACCEPTCONN:
3746 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3747 return SOCKET_ERROR;
3748 if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, optval, (socklen_t *)optlen) != 0 )
3750 SetLastError(wsaErrno());
3751 ret = SOCKET_ERROR;
3753 else
3755 /* BSD returns != 0 while Windows return exact == 1 */
3756 if (*(int *)optval) *(int *)optval = 1;
3758 release_sock_fd( s, fd );
3759 return ret;
3760 case WS_SO_BSP_STATE:
3762 int req_size, addr_size;
3763 WSAPROTOCOL_INFOW infow;
3764 CSADDR_INFO *csinfo;
3766 ret = ws_protocol_info(s, TRUE, &infow, &addr_size);
3767 if (ret)
3769 if (infow.iAddressFamily == WS_AF_INET)
3770 addr_size = sizeof(struct sockaddr_in);
3771 else if (infow.iAddressFamily == WS_AF_INET6)
3772 addr_size = sizeof(struct sockaddr_in6);
3773 else
3775 FIXME("Family %d is unsupported for SO_BSP_STATE\n", infow.iAddressFamily);
3776 SetLastError(WSAEAFNOSUPPORT);
3777 return SOCKET_ERROR;
3780 req_size = sizeof(CSADDR_INFO) + addr_size * 2;
3781 if (*optlen < req_size)
3783 ret = 0;
3784 SetLastError(WSAEFAULT);
3786 else
3788 union generic_unix_sockaddr uaddr;
3789 socklen_t uaddrlen;
3791 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3792 return SOCKET_ERROR;
3794 csinfo = (CSADDR_INFO*) optval;
3796 /* Check if the sock is bound */
3797 if (is_fd_bound(fd, &uaddr, &uaddrlen) == 1)
3799 csinfo->LocalAddr.lpSockaddr =
3800 (LPSOCKADDR) (optval + sizeof(CSADDR_INFO));
3801 ws_sockaddr_u2ws(&uaddr.addr, csinfo->LocalAddr.lpSockaddr, &addr_size);
3802 csinfo->LocalAddr.iSockaddrLength = addr_size;
3804 else
3806 csinfo->LocalAddr.lpSockaddr = NULL;
3807 csinfo->LocalAddr.iSockaddrLength = 0;
3810 /* Check if the sock is connected */
3811 if (!getpeername(fd, &uaddr.addr, &uaddrlen) &&
3812 is_sockaddr_bound(&uaddr.addr, uaddrlen))
3814 csinfo->RemoteAddr.lpSockaddr =
3815 (LPSOCKADDR) (optval + sizeof(CSADDR_INFO) + addr_size);
3816 ws_sockaddr_u2ws(&uaddr.addr, csinfo->RemoteAddr.lpSockaddr, &addr_size);
3817 csinfo->RemoteAddr.iSockaddrLength = addr_size;
3819 else
3821 csinfo->RemoteAddr.lpSockaddr = NULL;
3822 csinfo->RemoteAddr.iSockaddrLength = 0;
3825 csinfo->iSocketType = infow.iSocketType;
3826 csinfo->iProtocol = infow.iProtocol;
3827 release_sock_fd( s, fd );
3830 return ret ? 0 : SOCKET_ERROR;
3832 case WS_SO_DONTLINGER:
3834 struct linger lingval;
3835 socklen_t len = sizeof(struct linger);
3837 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
3839 SetLastError(WSAEFAULT);
3840 return SOCKET_ERROR;
3842 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3843 return SOCKET_ERROR;
3845 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
3847 SetLastError(wsaErrno());
3848 ret = SOCKET_ERROR;
3850 else
3852 *(BOOL *)optval = !lingval.l_onoff;
3853 *optlen = sizeof(BOOL);
3856 release_sock_fd( s, fd );
3857 return ret;
3860 case WS_SO_CONNECT_TIME:
3862 static int pretendtime = 0;
3863 struct WS_sockaddr addr;
3864 int len = sizeof(addr);
3866 if (!optlen || *optlen < sizeof(DWORD) || !optval)
3868 SetLastError(WSAEFAULT);
3869 return SOCKET_ERROR;
3871 if (WS_getpeername(s, &addr, &len) == SOCKET_ERROR)
3872 *(DWORD *)optval = ~0u;
3873 else
3875 if (!pretendtime) FIXME("WS_SO_CONNECT_TIME - faking results\n");
3876 *(DWORD *)optval = pretendtime++;
3878 *optlen = sizeof(DWORD);
3879 return ret;
3881 /* As mentioned in setsockopt, Windows ignores this, so we
3882 * always return true here */
3883 case WS_SO_DONTROUTE:
3884 if (!optlen || *optlen < sizeof(BOOL) || !optval)
3886 SetLastError(WSAEFAULT);
3887 return SOCKET_ERROR;
3889 *(BOOL *)optval = TRUE;
3890 *optlen = sizeof(BOOL);
3891 return 0;
3893 case WS_SO_ERROR:
3895 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3896 return SOCKET_ERROR;
3897 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, optval, (socklen_t *)optlen) != 0 )
3899 SetLastError(wsaErrno());
3900 ret = SOCKET_ERROR;
3902 release_sock_fd( s, fd );
3904 /* The wineserver may have swallowed the error before us */
3905 if (!ret && *(int*) optval == 0)
3907 int i, events[FD_MAX_EVENTS];
3908 _get_sock_errors(s, events);
3909 for (i = 0; i < FD_MAX_EVENTS; i++)
3911 if(events[i])
3913 events[i] = NtStatusToWSAError(events[i]);
3914 TRACE("returning SO_ERROR %d from wine server\n", events[i]);
3915 *(int*) optval = events[i];
3916 break;
3920 return ret;
3923 case WS_SO_LINGER:
3925 struct linger lingval;
3926 socklen_t len = sizeof(struct linger);
3928 /* struct linger and LINGER have different sizes */
3929 if (!optlen || *optlen < sizeof(LINGER) || !optval)
3931 SetLastError(WSAEFAULT);
3932 return SOCKET_ERROR;
3934 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3935 return SOCKET_ERROR;
3937 if (_get_fd_type(fd) == SOCK_DGRAM)
3939 SetLastError(WSAENOPROTOOPT);
3940 ret = SOCKET_ERROR;
3942 else if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0)
3944 SetLastError(wsaErrno());
3945 ret = SOCKET_ERROR;
3947 else
3949 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
3950 ((LINGER *)optval)->l_linger = lingval.l_linger;
3951 *optlen = sizeof(struct linger);
3954 release_sock_fd( s, fd );
3955 return ret;
3958 case WS_SO_MAX_MSG_SIZE:
3959 if (!optlen || *optlen < sizeof(int) || !optval)
3961 SetLastError(WSAEFAULT);
3962 return SOCKET_ERROR;
3964 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
3965 *(int *)optval = 65507;
3966 *optlen = sizeof(int);
3967 return 0;
3969 /* SO_OPENTYPE does not require a valid socket handle. */
3970 case WS_SO_OPENTYPE:
3971 if (!optlen || *optlen < sizeof(int) || !optval)
3973 SetLastError(WSAEFAULT);
3974 return SOCKET_ERROR;
3976 *(int *)optval = get_per_thread_data()->opentype;
3977 *optlen = sizeof(int);
3978 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
3979 return 0;
3980 case WS_SO_PROTOCOL_INFOA:
3981 case WS_SO_PROTOCOL_INFOW:
3983 int size;
3984 WSAPROTOCOL_INFOW infow;
3986 ret = ws_protocol_info(s, optname == WS_SO_PROTOCOL_INFOW, &infow, &size);
3987 if (ret)
3989 if (!optlen || !optval || *optlen < size)
3991 if(optlen) *optlen = size;
3992 ret = 0;
3993 SetLastError(WSAEFAULT);
3995 else
3996 memcpy(optval, &infow, size);
3998 return ret ? 0 : SOCKET_ERROR;
4000 case WS_SO_RCVTIMEO:
4001 case WS_SO_SNDTIMEO:
4003 INT64 timeout;
4005 if (!optlen || *optlen < sizeof(int)|| !optval)
4007 SetLastError(WSAEFAULT);
4008 return SOCKET_ERROR;
4010 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4011 return SOCKET_ERROR;
4013 timeout = get_rcvsnd_timeo(fd, optname == WS_SO_RCVTIMEO);
4014 *(int *)optval = timeout <= UINT_MAX ? timeout : UINT_MAX;
4016 release_sock_fd( s, fd );
4017 return ret;
4019 case WS_SO_TYPE:
4021 int sock_type;
4022 if (!optlen || *optlen < sizeof(int) || !optval)
4024 SetLastError(WSAEFAULT);
4025 return SOCKET_ERROR;
4027 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4028 return SOCKET_ERROR;
4030 sock_type = _get_fd_type(fd);
4031 if (sock_type == -1)
4033 SetLastError(wsaErrno());
4034 ret = SOCKET_ERROR;
4036 else
4037 (*(int *)optval) = convert_socktype_u2w(sock_type);
4039 release_sock_fd( s, fd );
4040 return ret;
4042 default:
4043 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
4044 SetLastError(WSAENOPROTOOPT);
4045 return SOCKET_ERROR;
4046 } /* end switch(optname) */
4047 }/* end case WS_SOL_SOCKET */
4048 #ifdef HAS_IPX
4049 case WS_NSPROTO_IPX:
4051 struct WS_sockaddr_ipx addr;
4052 IPX_ADDRESS_DATA *data;
4053 int namelen;
4054 switch(optname)
4056 case WS_IPX_PTYPE:
4057 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
4058 #ifdef SOL_IPX
4059 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (socklen_t *)optlen) == -1)
4061 ret = SOCKET_ERROR;
4063 #else
4065 struct ipx val;
4066 socklen_t len=sizeof(struct ipx);
4067 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
4068 ret = SOCKET_ERROR;
4069 else
4070 *optval = (int)val.ipx_pt;
4072 #endif
4073 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
4074 release_sock_fd( s, fd );
4075 return ret;
4077 case WS_IPX_ADDRESS:
4079 * On a Win2000 system with one network card there are usually
4080 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
4081 * Using this call you can then retrieve info about this all.
4082 * In case of Linux it is a bit different. Usually you have
4083 * only "one" device active and further it is not possible to
4084 * query things like the linkspeed.
4086 FIXME("IPX_ADDRESS\n");
4087 namelen = sizeof(struct WS_sockaddr_ipx);
4088 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
4089 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
4091 data = (IPX_ADDRESS_DATA*)optval;
4092 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
4093 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
4094 data->adapternum = 0;
4095 data->wan = FALSE; /* We are not on a wan for now .. */
4096 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
4097 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
4098 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
4099 * note 1MB = 1000kB in this case */
4100 return 0;
4102 case WS_IPX_MAX_ADAPTER_NUM:
4103 FIXME("IPX_MAX_ADAPTER_NUM\n");
4104 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
4105 return 0;
4107 default:
4108 FIXME("IPX optname:%x\n", optname);
4109 return SOCKET_ERROR;
4110 }/* end switch(optname) */
4111 } /* end case WS_NSPROTO_IPX */
4112 #endif
4114 #ifdef HAS_IRDA
4115 #define MAX_IRDA_DEVICES 10
4117 case WS_SOL_IRLMP:
4118 switch(optname)
4120 case WS_IRLMP_ENUMDEVICES:
4122 char buf[sizeof(struct irda_device_list) +
4123 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
4124 int res;
4125 socklen_t len = sizeof(buf);
4127 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4128 return SOCKET_ERROR;
4129 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
4130 release_sock_fd( s, fd );
4131 if (res < 0)
4133 SetLastError(wsaErrno());
4134 return SOCKET_ERROR;
4136 else
4138 struct irda_device_list *src = (struct irda_device_list *)buf;
4139 DEVICELIST *dst = (DEVICELIST *)optval;
4140 INT needed = sizeof(DEVICELIST);
4141 unsigned int i;
4143 if (src->len > 0)
4144 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
4145 if (*optlen < needed)
4147 SetLastError(WSAEFAULT);
4148 return SOCKET_ERROR;
4150 *optlen = needed;
4151 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
4152 dst->numDevice = src->len;
4153 for (i = 0; i < src->len; i++)
4155 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
4156 src->dev[i].saddr, src->dev[i].daddr,
4157 src->dev[i].info, src->dev[i].hints[0],
4158 src->dev[i].hints[1]);
4159 memcpy( dst->Device[i].irdaDeviceID,
4160 &src->dev[i].daddr,
4161 sizeof(dst->Device[i].irdaDeviceID) ) ;
4162 memcpy( dst->Device[i].irdaDeviceName,
4163 src->dev[i].info,
4164 sizeof(dst->Device[i].irdaDeviceName) ) ;
4165 memcpy( &dst->Device[i].irdaDeviceHints1,
4166 &src->dev[i].hints[0],
4167 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
4168 memcpy( &dst->Device[i].irdaDeviceHints2,
4169 &src->dev[i].hints[1],
4170 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
4171 dst->Device[i].irdaCharSet = src->dev[i].charset;
4173 return 0;
4176 default:
4177 FIXME("IrDA optname:0x%x\n", optname);
4178 return SOCKET_ERROR;
4180 break; /* case WS_SOL_IRLMP */
4181 #undef MAX_IRDA_DEVICES
4182 #endif
4184 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
4185 case WS_IPPROTO_TCP:
4186 switch(optname)
4188 case WS_TCP_NODELAY:
4189 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4190 return SOCKET_ERROR;
4191 convert_sockopt(&level, &optname);
4192 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
4194 SetLastError(wsaErrno());
4195 ret = SOCKET_ERROR;
4197 release_sock_fd( s, fd );
4198 return ret;
4200 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
4201 return SOCKET_ERROR;
4203 case WS_IPPROTO_IP:
4204 switch(optname)
4206 case WS_IP_ADD_MEMBERSHIP:
4207 case WS_IP_DROP_MEMBERSHIP:
4208 #ifdef IP_HDRINCL
4209 case WS_IP_HDRINCL:
4210 #endif
4211 case WS_IP_MULTICAST_IF:
4212 case WS_IP_MULTICAST_LOOP:
4213 case WS_IP_MULTICAST_TTL:
4214 case WS_IP_OPTIONS:
4215 #ifdef IP_PKTINFO
4216 case WS_IP_PKTINFO:
4217 #endif
4218 case WS_IP_TOS:
4219 case WS_IP_TTL:
4220 #ifdef IP_UNICAST_IF
4221 case WS_IP_UNICAST_IF:
4222 #endif
4223 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4224 return SOCKET_ERROR;
4225 convert_sockopt(&level, &optname);
4226 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
4228 SetLastError(wsaErrno());
4229 ret = SOCKET_ERROR;
4231 release_sock_fd( s, fd );
4232 return ret;
4233 case WS_IP_DONTFRAGMENT:
4234 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
4235 *(BOOL*)optval = FALSE;
4236 return 0;
4238 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
4239 return SOCKET_ERROR;
4241 case WS_IPPROTO_IPV6:
4242 switch(optname)
4244 #ifdef IPV6_ADD_MEMBERSHIP
4245 case WS_IPV6_ADD_MEMBERSHIP:
4246 #endif
4247 #ifdef IPV6_DROP_MEMBERSHIP
4248 case WS_IPV6_DROP_MEMBERSHIP:
4249 #endif
4250 case WS_IPV6_MULTICAST_IF:
4251 case WS_IPV6_MULTICAST_HOPS:
4252 case WS_IPV6_MULTICAST_LOOP:
4253 case WS_IPV6_UNICAST_HOPS:
4254 case WS_IPV6_V6ONLY:
4255 #ifdef IPV6_UNICAST_IF
4256 case WS_IPV6_UNICAST_IF:
4257 #endif
4258 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4259 return SOCKET_ERROR;
4260 convert_sockopt(&level, &optname);
4261 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
4263 SetLastError(wsaErrno());
4264 ret = SOCKET_ERROR;
4266 release_sock_fd( s, fd );
4267 return ret;
4268 case WS_IPV6_DONTFRAG:
4269 FIXME("WS_IPV6_DONTFRAG is always false!\n");
4270 *(BOOL*)optval = FALSE;
4271 return 0;
4273 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
4274 return SOCKET_ERROR;
4276 default:
4277 WARN("Unknown level: 0x%08x\n", level);
4278 SetLastError(WSAEINVAL);
4279 return SOCKET_ERROR;
4280 } /* end switch(level) */
4283 /***********************************************************************
4284 * htonl (WS2_32.8)
4286 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
4288 return htonl(hostlong);
4292 /***********************************************************************
4293 * htons (WS2_32.9)
4295 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
4297 return htons(hostshort);
4300 /***********************************************************************
4301 * WSAHtonl (WS2_32.46)
4302 * From MSDN description of error codes, this function should also
4303 * check if WinSock has been initialized and the socket is a valid
4304 * socket. But why? This function only translates a host byte order
4305 * u_long into a network byte order u_long...
4307 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
4309 if (lpnetlong)
4311 *lpnetlong = htonl(hostlong);
4312 return 0;
4314 SetLastError(WSAEFAULT);
4315 return SOCKET_ERROR;
4318 /***********************************************************************
4319 * WSAHtons (WS2_32.47)
4320 * From MSDN description of error codes, this function should also
4321 * check if WinSock has been initialized and the socket is a valid
4322 * socket. But why? This function only translates a host byte order
4323 * u_short into a network byte order u_short...
4325 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
4328 if (lpnetshort)
4330 *lpnetshort = htons(hostshort);
4331 return 0;
4333 SetLastError(WSAEFAULT);
4334 return SOCKET_ERROR;
4338 /***********************************************************************
4339 * inet_addr (WS2_32.11)
4341 WS_u_long WINAPI WS_inet_addr(const char *cp)
4343 if (!cp) return INADDR_NONE;
4344 return inet_addr(cp);
4348 /***********************************************************************
4349 * ntohl (WS2_32.14)
4351 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
4353 return ntohl(netlong);
4357 /***********************************************************************
4358 * ntohs (WS2_32.15)
4360 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
4362 return ntohs(netshort);
4366 /***********************************************************************
4367 * inet_ntoa (WS2_32.12)
4369 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
4371 unsigned int long_ip = ntohl(in.WS_s_addr);
4372 struct per_thread_data *data = get_per_thread_data();
4374 sprintf( data->ntoa_buffer, "%u.%u.%u.%u",
4375 (long_ip >> 24) & 0xff,
4376 (long_ip >> 16) & 0xff,
4377 (long_ip >> 8) & 0xff,
4378 long_ip & 0xff);
4380 return data->ntoa_buffer;
4383 static const char *debugstr_wsaioctl(DWORD code)
4385 const char *name = NULL, *buf_type, *family;
4387 #define IOCTL_NAME(x) case x: name = #x; break
4388 switch (code)
4390 IOCTL_NAME(WS_FIONBIO);
4391 IOCTL_NAME(WS_FIONREAD);
4392 IOCTL_NAME(WS_SIOCATMARK);
4393 /* IOCTL_NAME(WS_SIO_ACQUIRE_PORT_RESERVATION); */
4394 IOCTL_NAME(WS_SIO_ADDRESS_LIST_CHANGE);
4395 IOCTL_NAME(WS_SIO_ADDRESS_LIST_QUERY);
4396 IOCTL_NAME(WS_SIO_ASSOCIATE_HANDLE);
4397 /* IOCTL_NAME(WS_SIO_ASSOCIATE_PORT_RESERVATION);
4398 IOCTL_NAME(WS_SIO_BASE_HANDLE);
4399 IOCTL_NAME(WS_SIO_BSP_HANDLE);
4400 IOCTL_NAME(WS_SIO_BSP_HANDLE_SELECT);
4401 IOCTL_NAME(WS_SIO_BSP_HANDLE_POLL);
4402 IOCTL_NAME(WS_SIO_CHK_QOS); */
4403 IOCTL_NAME(WS_SIO_ENABLE_CIRCULAR_QUEUEING);
4404 IOCTL_NAME(WS_SIO_FIND_ROUTE);
4405 IOCTL_NAME(WS_SIO_FLUSH);
4406 IOCTL_NAME(WS_SIO_GET_BROADCAST_ADDRESS);
4407 IOCTL_NAME(WS_SIO_GET_EXTENSION_FUNCTION_POINTER);
4408 IOCTL_NAME(WS_SIO_GET_GROUP_QOS);
4409 IOCTL_NAME(WS_SIO_GET_INTERFACE_LIST);
4410 /* IOCTL_NAME(WS_SIO_GET_INTERFACE_LIST_EX); */
4411 IOCTL_NAME(WS_SIO_GET_QOS);
4412 /* IOCTL_NAME(WS_SIO_IDEAL_SEND_BACKLOG_CHANGE);
4413 IOCTL_NAME(WS_SIO_IDEAL_SEND_BACKLOG_QUERY); */
4414 IOCTL_NAME(WS_SIO_KEEPALIVE_VALS);
4415 IOCTL_NAME(WS_SIO_MULTIPOINT_LOOPBACK);
4416 IOCTL_NAME(WS_SIO_MULTICAST_SCOPE);
4417 /* IOCTL_NAME(WS_SIO_QUERY_RSS_SCALABILITY_INFO);
4418 IOCTL_NAME(WS_SIO_QUERY_WFP_ALE_ENDPOINT_HANDLE); */
4419 IOCTL_NAME(WS_SIO_RCVALL);
4420 IOCTL_NAME(WS_SIO_RCVALL_IGMPMCAST);
4421 IOCTL_NAME(WS_SIO_RCVALL_MCAST);
4422 /* IOCTL_NAME(WS_SIO_RELEASE_PORT_RESERVATION); */
4423 IOCTL_NAME(WS_SIO_ROUTING_INTERFACE_CHANGE);
4424 IOCTL_NAME(WS_SIO_ROUTING_INTERFACE_QUERY);
4425 IOCTL_NAME(WS_SIO_SET_COMPATIBILITY_MODE);
4426 IOCTL_NAME(WS_SIO_SET_GROUP_QOS);
4427 IOCTL_NAME(WS_SIO_SET_QOS);
4428 IOCTL_NAME(WS_SIO_TRANSLATE_HANDLE);
4429 IOCTL_NAME(WS_SIO_UDP_CONNRESET);
4431 #undef IOCTL_NAME
4433 if (name)
4434 return name + 3;
4436 /* If this is not a known code split its bits */
4437 switch(code & 0x18000000)
4439 case WS_IOC_WS2:
4440 family = "IOC_WS2";
4441 break;
4442 case WS_IOC_PROTOCOL:
4443 family = "IOC_PROTOCOL";
4444 break;
4445 case WS_IOC_VENDOR:
4446 family = "IOC_VENDOR";
4447 break;
4448 default: /* WS_IOC_UNIX */
4450 BYTE size = (code >> 16) & WS_IOCPARM_MASK;
4451 char x = (code & 0xff00) >> 8;
4452 BYTE y = code & 0xff;
4453 char args[14];
4455 switch (code & (WS_IOC_VOID|WS_IOC_INOUT))
4457 case WS_IOC_VOID:
4458 buf_type = "_IO";
4459 sprintf(args, "%d, %d", x, y);
4460 break;
4461 case WS_IOC_IN:
4462 buf_type = "_IOW";
4463 sprintf(args, "'%c', %d, %d", x, y, size);
4464 break;
4465 case WS_IOC_OUT:
4466 buf_type = "_IOR";
4467 sprintf(args, "'%c', %d, %d", x, y, size);
4468 break;
4469 default:
4470 buf_type = "?";
4471 sprintf(args, "'%c', %d, %d", x, y, size);
4472 break;
4474 return wine_dbg_sprintf("%s(%s)", buf_type, args);
4478 /* We are different from WS_IOC_UNIX. */
4479 switch (code & (WS_IOC_VOID|WS_IOC_INOUT))
4481 case WS_IOC_VOID:
4482 buf_type = "_WSAIO";
4483 break;
4484 case WS_IOC_INOUT:
4485 buf_type = "_WSAIORW";
4486 break;
4487 case WS_IOC_IN:
4488 buf_type = "_WSAIOW";
4489 break;
4490 case WS_IOC_OUT:
4491 buf_type = "_WSAIOR";
4492 break;
4493 default:
4494 buf_type = "?";
4495 break;
4498 return wine_dbg_sprintf("%s(%s, %d)", buf_type, family,
4499 (USHORT)(code & 0xffff));
4502 /* do an ioctl call through the server */
4503 static DWORD server_ioctl_sock( SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size,
4504 LPVOID out_buff, DWORD out_size, LPDWORD ret_size,
4505 LPWSAOVERLAPPED overlapped,
4506 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
4508 HANDLE event = overlapped ? overlapped->hEvent : 0;
4509 HANDLE handle = SOCKET2HANDLE( s );
4510 struct ws2_async *wsa = NULL;
4511 IO_STATUS_BLOCK *io = (PIO_STATUS_BLOCK)overlapped, iosb;
4512 void *cvalue = NULL;
4513 NTSTATUS status;
4515 if (completion)
4517 if (!(wsa = (struct ws2_async *)alloc_async_io( sizeof(*wsa) )))
4518 return WSA_NOT_ENOUGH_MEMORY;
4519 wsa->hSocket = handle;
4520 wsa->user_overlapped = overlapped;
4521 wsa->completion_func = completion;
4522 if (!io) io = &wsa->local_iosb;
4523 cvalue = wsa;
4525 else if (!io)
4526 io = &iosb;
4527 else if (!((ULONG_PTR)overlapped->hEvent & 1))
4528 cvalue = overlapped;
4530 status = NtDeviceIoControlFile( handle, event, wsa ? ws2_async_apc : NULL, cvalue, io, code,
4531 in_buff, in_size, out_buff, out_size );
4532 if (status == STATUS_NOT_SUPPORTED)
4534 FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
4535 code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
4537 else if (status == STATUS_SUCCESS)
4538 *ret_size = io->Information; /* "Information" is the size written to the output buffer */
4540 if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, wsa );
4542 return NtStatusToWSAError( status );
4545 /**********************************************************************
4546 * WSAIoctl (WS2_32.50)
4549 INT WINAPI WSAIoctl(SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size, LPVOID out_buff,
4550 DWORD out_size, LPDWORD ret_size, LPWSAOVERLAPPED overlapped,
4551 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
4553 int fd;
4554 DWORD status = 0, total = 0;
4556 TRACE("%04lx, %s, %p, %d, %p, %d, %p, %p, %p\n",
4557 s, debugstr_wsaioctl(code), in_buff, in_size, out_buff, out_size, ret_size, overlapped, completion);
4559 switch (code)
4561 case WS_FIONBIO:
4562 if (in_size != sizeof(WS_u_long) || IS_INTRESOURCE(in_buff))
4564 SetLastError(WSAEFAULT);
4565 return SOCKET_ERROR;
4567 TRACE("-> FIONBIO (%x)\n", *(WS_u_long*)in_buff);
4568 if (_get_sock_mask(s))
4570 /* AsyncSelect()'ed sockets are always nonblocking */
4571 if (!*(WS_u_long *)in_buff) status = WSAEINVAL;
4572 break;
4574 if (*(WS_u_long *)in_buff)
4575 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
4576 else
4577 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
4578 break;
4580 case WS_FIONREAD:
4582 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
4584 SetLastError(WSAEFAULT);
4585 return SOCKET_ERROR;
4587 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
4588 if (ioctl(fd, FIONREAD, out_buff ) == -1)
4589 status = wsaErrno();
4590 release_sock_fd( s, fd );
4591 break;
4594 case WS_SIOCATMARK:
4596 unsigned int oob = 0, atmark = 0;
4597 socklen_t oobsize = sizeof(int);
4598 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
4600 SetLastError(WSAEFAULT);
4601 return SOCKET_ERROR;
4603 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
4604 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
4605 if ((getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &oob, &oobsize ) == -1)
4606 || (!oob && ioctl(fd, SIOCATMARK, &atmark ) == -1))
4607 status = wsaErrno();
4608 else
4610 /* The SIOCATMARK value read from ioctl() is reversed
4611 * because BSD returns TRUE if it's in the OOB mark
4612 * while Windows returns TRUE if there are NO OOB bytes.
4614 (*(WS_u_long *) out_buff) = oob || !atmark;
4617 release_sock_fd( s, fd );
4618 break;
4621 case WS_FIOASYNC:
4622 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
4623 SetLastError(WSAEINVAL);
4624 return SOCKET_ERROR;
4626 case WS_SIO_GET_INTERFACE_LIST:
4628 INTERFACE_INFO* intArray = out_buff;
4629 DWORD size, numInt = 0, apiReturn;
4631 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
4633 if (!out_buff || !ret_size)
4635 SetLastError(WSAEFAULT);
4636 return SOCKET_ERROR;
4639 fd = get_sock_fd( s, 0, NULL );
4640 if (fd == -1) return SOCKET_ERROR;
4642 apiReturn = GetAdaptersInfo(NULL, &size);
4643 if (apiReturn == ERROR_BUFFER_OVERFLOW)
4645 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
4647 if (table)
4649 if (GetAdaptersInfo(table, &size) == NO_ERROR)
4651 PIP_ADAPTER_INFO ptr;
4653 for (ptr = table, numInt = 0; ptr; ptr = ptr->Next)
4655 unsigned int addr, mask, bcast;
4656 struct ifreq ifInfo;
4658 /* Skip interfaces without an IPv4 address. */
4659 if (ptr->IpAddressList.IpAddress.String[0] == '\0')
4660 continue;
4662 if ((numInt + 1)*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > out_size)
4664 WARN("Buffer too small = %u, out_size = %u\n", numInt + 1, out_size);
4665 status = WSAEFAULT;
4666 break;
4669 /* Socket Status Flags */
4670 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
4671 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
4673 ERR("Error obtaining status flags for socket!\n");
4674 status = WSAEINVAL;
4675 break;
4677 else
4679 /* set flags; the values of IFF_* are not the same
4680 under Linux and Windows, therefore must generate
4681 new flags */
4682 intArray->iiFlags = 0;
4683 if (ifInfo.ifr_flags & IFF_BROADCAST)
4684 intArray->iiFlags |= WS_IFF_BROADCAST;
4685 #ifdef IFF_POINTOPOINT
4686 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
4687 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
4688 #endif
4689 if (ifInfo.ifr_flags & IFF_LOOPBACK)
4690 intArray->iiFlags |= WS_IFF_LOOPBACK;
4691 if (ifInfo.ifr_flags & IFF_UP)
4692 intArray->iiFlags |= WS_IFF_UP;
4693 if (ifInfo.ifr_flags & IFF_MULTICAST)
4694 intArray->iiFlags |= WS_IFF_MULTICAST;
4697 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
4698 mask = inet_addr(ptr->IpAddressList.IpMask.String);
4699 bcast = addr | ~mask;
4700 intArray->iiAddress.AddressIn.sin_family = WS_AF_INET;
4701 intArray->iiAddress.AddressIn.sin_port = 0;
4702 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr = addr;
4704 intArray->iiNetmask.AddressIn.sin_family = WS_AF_INET;
4705 intArray->iiNetmask.AddressIn.sin_port = 0;
4706 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr = mask;
4708 intArray->iiBroadcastAddress.AddressIn.sin_family = WS_AF_INET;
4709 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
4710 intArray->iiBroadcastAddress.AddressIn.sin_addr.WS_s_addr = bcast;
4711 intArray++;
4712 numInt++;
4715 else
4717 ERR("Unable to get interface table!\n");
4718 status = WSAEINVAL;
4720 HeapFree(GetProcessHeap(),0,table);
4722 else status = WSAEINVAL;
4724 else if (apiReturn != ERROR_NO_DATA)
4726 ERR("Unable to get interface table!\n");
4727 status = WSAEINVAL;
4729 /* Calculate the size of the array being returned */
4730 total = sizeof(INTERFACE_INFO) * numInt;
4731 release_sock_fd( s, fd );
4732 break;
4735 case WS_SIO_ADDRESS_LIST_QUERY:
4737 DWORD size;
4739 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
4741 if (!ret_size)
4743 SetLastError(WSAEFAULT);
4744 return SOCKET_ERROR;
4747 if (out_size && out_size < FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[0]))
4749 *ret_size = 0;
4750 SetLastError(WSAEINVAL);
4751 return SOCKET_ERROR;
4754 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
4756 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
4757 SOCKET_ADDRESS_LIST *sa_list;
4758 SOCKADDR_IN *sockaddr;
4759 SOCKET_ADDRESS *sa;
4760 unsigned int i;
4761 DWORD num;
4763 if (!table || GetAdaptersInfo(table, &size))
4765 HeapFree(GetProcessHeap(), 0, table);
4766 status = WSAEINVAL;
4767 break;
4770 for (p = table, num = 0; p; p = p->Next)
4771 if (p->IpAddressList.IpAddress.String[0]) num++;
4773 total = FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[num]) + num * sizeof(*sockaddr);
4774 if (total > out_size || !out_buff)
4776 *ret_size = total;
4777 HeapFree(GetProcessHeap(), 0, table);
4778 status = WSAEFAULT;
4779 break;
4782 sa_list = out_buff;
4783 sa = sa_list->Address;
4784 sockaddr = (SOCKADDR_IN *)&sa[num];
4785 sa_list->iAddressCount = num;
4787 for (p = table, i = 0; p; p = p->Next)
4789 if (!p->IpAddressList.IpAddress.String[0]) continue;
4791 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
4792 sa[i].iSockaddrLength = sizeof(SOCKADDR);
4794 sockaddr[i].sin_family = WS_AF_INET;
4795 sockaddr[i].sin_port = 0;
4796 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
4797 i++;
4800 HeapFree(GetProcessHeap(), 0, table);
4802 else
4804 WARN("unable to get IP address list\n");
4805 status = WSAEINVAL;
4807 break;
4810 case WS_SIO_FLUSH:
4811 FIXME("SIO_FLUSH: stub.\n");
4812 break;
4814 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
4816 static const GUID connectex_guid = WSAID_CONNECTEX;
4817 static const GUID disconnectex_guid = WSAID_DISCONNECTEX;
4818 static const GUID acceptex_guid = WSAID_ACCEPTEX;
4819 static const GUID getaccepexsockaddrs_guid = WSAID_GETACCEPTEXSOCKADDRS;
4820 static const GUID transmitfile_guid = WSAID_TRANSMITFILE;
4821 static const GUID transmitpackets_guid = WSAID_TRANSMITPACKETS;
4822 static const GUID wsarecvmsg_guid = WSAID_WSARECVMSG;
4823 static const GUID wsasendmsg_guid = WSAID_WSASENDMSG;
4825 if ( IsEqualGUID(&connectex_guid, in_buff) )
4827 *(LPFN_CONNECTEX *)out_buff = WS2_ConnectEx;
4828 break;
4830 else if ( IsEqualGUID(&disconnectex_guid, in_buff) )
4832 *(LPFN_DISCONNECTEX *)out_buff = WS2_DisconnectEx;
4833 break;
4835 else if ( IsEqualGUID(&acceptex_guid, in_buff) )
4837 *(LPFN_ACCEPTEX *)out_buff = WS2_AcceptEx;
4838 break;
4840 else if ( IsEqualGUID(&getaccepexsockaddrs_guid, in_buff) )
4842 *(LPFN_GETACCEPTEXSOCKADDRS *)out_buff = WS2_GetAcceptExSockaddrs;
4843 break;
4845 else if ( IsEqualGUID(&transmitfile_guid, in_buff) )
4847 *(LPFN_TRANSMITFILE *)out_buff = WS2_TransmitFile;
4848 break;
4850 else if ( IsEqualGUID(&transmitpackets_guid, in_buff) )
4852 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitPackets\n");
4854 else if ( IsEqualGUID(&wsarecvmsg_guid, in_buff) )
4856 *(LPFN_WSARECVMSG *)out_buff = WS2_WSARecvMsg;
4857 break;
4859 else if ( IsEqualGUID(&wsasendmsg_guid, in_buff) )
4861 *(LPFN_WSASENDMSG *)out_buff = WSASendMsg;
4862 break;
4864 else
4865 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff));
4867 status = WSAEOPNOTSUPP;
4868 break;
4870 case WS_SIO_KEEPALIVE_VALS:
4872 struct tcp_keepalive *k;
4873 int keepalive, keepidle, keepintvl;
4875 if (!in_buff || in_size < sizeof(struct tcp_keepalive))
4877 SetLastError(WSAEFAULT);
4878 return SOCKET_ERROR;
4881 k = in_buff;
4882 keepalive = k->onoff ? 1 : 0;
4883 keepidle = max( 1, (k->keepalivetime + 500) / 1000 );
4884 keepintvl = max( 1, (k->keepaliveinterval + 500) / 1000 );
4886 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
4888 fd = get_sock_fd(s, 0, NULL);
4889 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
4890 status = WSAEINVAL;
4891 #if defined(TCP_KEEPIDLE) || defined(TCP_KEEPINTVL)
4892 /* these values need to be set only if SO_KEEPALIVE is enabled */
4893 else if(keepalive)
4895 #ifndef TCP_KEEPIDLE
4896 FIXME("ignoring keepalive timeout\n");
4897 #else
4898 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
4899 status = WSAEINVAL;
4900 else
4901 #endif
4902 #ifdef TCP_KEEPINTVL
4903 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
4904 status = WSAEINVAL;
4905 #else
4906 FIXME("ignoring keepalive interval\n");
4907 #endif
4909 #else
4910 else
4911 FIXME("ignoring keepalive interval and timeout\n");
4912 #endif
4913 release_sock_fd(s, fd);
4914 break;
4916 case WS_SIO_ROUTING_INTERFACE_QUERY:
4918 struct WS_sockaddr *daddr = (struct WS_sockaddr *)in_buff;
4919 struct WS_sockaddr_in *daddr_in = (struct WS_sockaddr_in *)daddr;
4920 struct WS_sockaddr_in *saddr_in = out_buff;
4921 MIB_IPFORWARDROW row;
4922 PMIB_IPADDRTABLE ipAddrTable = NULL;
4923 DWORD size, i, found_index;
4925 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
4927 if (!in_buff || in_size < sizeof(struct WS_sockaddr) ||
4928 !out_buff || out_size < sizeof(struct WS_sockaddr_in) || !ret_size)
4930 SetLastError(WSAEFAULT);
4931 return SOCKET_ERROR;
4933 if (daddr->sa_family != WS_AF_INET)
4935 FIXME("unsupported address family %d\n", daddr->sa_family);
4936 status = WSAEAFNOSUPPORT;
4937 break;
4939 if (GetBestRoute(daddr_in->sin_addr.S_un.S_addr, 0, &row) != NOERROR ||
4940 GetIpAddrTable(NULL, &size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
4942 status = WSAEFAULT;
4943 break;
4945 ipAddrTable = HeapAlloc(GetProcessHeap(), 0, size);
4946 if (GetIpAddrTable(ipAddrTable, &size, FALSE))
4948 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4949 status = WSAEFAULT;
4950 break;
4952 for (i = 0, found_index = ipAddrTable->dwNumEntries;
4953 i < ipAddrTable->dwNumEntries; i++)
4955 if (ipAddrTable->table[i].dwIndex == row.dwForwardIfIndex)
4956 found_index = i;
4958 if (found_index == ipAddrTable->dwNumEntries)
4960 ERR("no matching IP address for interface %d\n",
4961 row.dwForwardIfIndex);
4962 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4963 status = WSAEFAULT;
4964 break;
4966 saddr_in->sin_family = WS_AF_INET;
4967 saddr_in->sin_addr.S_un.S_addr = ipAddrTable->table[found_index].dwAddr;
4968 saddr_in->sin_port = 0;
4969 total = sizeof(struct WS_sockaddr_in);
4970 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4971 break;
4973 case WS_SIO_SET_COMPATIBILITY_MODE:
4974 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
4975 status = WSAEOPNOTSUPP;
4976 break;
4977 case WS_SIO_UDP_CONNRESET:
4978 FIXME("WS_SIO_UDP_CONNRESET stub\n");
4979 break;
4980 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
4981 SetLastError(WSAEOPNOTSUPP);
4982 return SOCKET_ERROR;
4983 default:
4984 status = WSAEOPNOTSUPP;
4985 break;
4988 if (status == WSAEOPNOTSUPP)
4990 status = server_ioctl_sock(s, code, in_buff, in_size, out_buff, out_size, &total,
4991 overlapped, completion);
4992 if (status != WSAEOPNOTSUPP)
4994 if (status == 0 || status == WSA_IO_PENDING)
4995 TRACE("-> %s request\n", debugstr_wsaioctl(code));
4996 else
4997 ERR("-> %s request failed with status 0x%x\n", debugstr_wsaioctl(code), status);
4999 /* overlapped and completion operations will be handled by the server */
5000 completion = NULL;
5001 overlapped = NULL;
5003 else
5004 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code));
5007 if (completion)
5009 FIXME( "completion routine %p not supported\n", completion );
5011 else if (overlapped)
5013 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
5014 overlapped->Internal = status;
5015 overlapped->InternalHigh = total;
5016 if (overlapped->hEvent) NtSetEvent( overlapped->hEvent, NULL );
5017 if (cvalue) WS_AddCompletion( HANDLE2SOCKET(s), cvalue, status, total );
5020 if (!status)
5022 if (ret_size) *ret_size = total;
5023 return 0;
5025 SetLastError( status );
5026 return SOCKET_ERROR;
5030 /***********************************************************************
5031 * ioctlsocket (WS2_32.10)
5033 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
5035 DWORD ret_size;
5036 return WSAIoctl( s, cmd, argp, sizeof(WS_u_long), argp, sizeof(WS_u_long), &ret_size, NULL, NULL );
5039 /***********************************************************************
5040 * listen (WS2_32.13)
5042 int WINAPI WS_listen(SOCKET s, int backlog)
5044 int fd = get_sock_fd( s, FILE_READ_DATA, NULL ), ret = SOCKET_ERROR;
5046 TRACE("socket %04lx, backlog %d\n", s, backlog);
5047 if (fd != -1)
5049 int bound = is_fd_bound(fd, NULL, NULL);
5051 if (bound <= 0)
5053 SetLastError(bound == -1 ? wsaErrno() : WSAEINVAL);
5055 else if (listen(fd, backlog) == 0)
5057 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
5058 FD_WINE_LISTENING,
5059 FD_CONNECT|FD_WINE_CONNECTED);
5060 ret = 0;
5062 else
5063 SetLastError(wsaErrno());
5064 release_sock_fd( s, fd );
5066 else
5067 SetLastError(WSAENOTSOCK);
5068 return ret;
5071 /***********************************************************************
5072 * recv (WS2_32.16)
5074 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
5076 DWORD n, dwFlags = flags;
5077 WSABUF wsabuf;
5079 wsabuf.len = len;
5080 wsabuf.buf = buf;
5082 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
5083 return SOCKET_ERROR;
5084 else
5085 return n;
5088 /***********************************************************************
5089 * recvfrom (WS2_32.17)
5091 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
5092 struct WS_sockaddr *from, int *fromlen)
5094 DWORD n, dwFlags = flags;
5095 WSABUF wsabuf;
5097 wsabuf.len = len;
5098 wsabuf.buf = buf;
5100 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL, NULL) == SOCKET_ERROR )
5101 return SOCKET_ERROR;
5102 else
5103 return n;
5106 /* allocate a poll array for the corresponding fd sets */
5107 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
5108 const WS_fd_set *exceptfds, int *count_ptr )
5110 unsigned int i, j = 0, count = 0;
5111 struct pollfd *fds;
5112 struct per_thread_data *ptb = get_per_thread_data();
5114 if (readfds) count += readfds->fd_count;
5115 if (writefds) count += writefds->fd_count;
5116 if (exceptfds) count += exceptfds->fd_count;
5117 *count_ptr = count;
5118 if (!count)
5120 SetLastError(WSAEINVAL);
5121 return NULL;
5124 /* check if the cache can hold all descriptors, if not do the resizing */
5125 if (ptb->fd_count < count)
5127 if (!(fds = HeapAlloc(GetProcessHeap(), 0, count * sizeof(fds[0]))))
5129 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
5130 return NULL;
5132 HeapFree(GetProcessHeap(), 0, ptb->fd_cache);
5133 ptb->fd_cache = fds;
5134 ptb->fd_count = count;
5136 else
5137 fds = ptb->fd_cache;
5139 if (readfds)
5140 for (i = 0; i < readfds->fd_count; i++, j++)
5142 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
5143 if (fds[j].fd == -1) goto failed;
5144 fds[j].revents = 0;
5145 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1)
5147 fds[j].events = POLLIN;
5149 else
5151 release_sock_fd( readfds->fd_array[i], fds[j].fd );
5152 fds[j].fd = -1;
5153 fds[j].events = 0;
5156 if (writefds)
5157 for (i = 0; i < writefds->fd_count; i++, j++)
5159 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
5160 if (fds[j].fd == -1) goto failed;
5161 fds[j].revents = 0;
5162 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1 ||
5163 _get_fd_type(fds[j].fd) == SOCK_DGRAM)
5165 fds[j].events = POLLOUT;
5167 else
5169 release_sock_fd( writefds->fd_array[i], fds[j].fd );
5170 fds[j].fd = -1;
5171 fds[j].events = 0;
5174 if (exceptfds)
5175 for (i = 0; i < exceptfds->fd_count; i++, j++)
5177 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
5178 if (fds[j].fd == -1) goto failed;
5179 fds[j].revents = 0;
5180 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1)
5182 int oob_inlined = 0;
5183 socklen_t olen = sizeof(oob_inlined);
5185 fds[j].events = POLLHUP;
5187 /* Check if we need to test for urgent data or not */
5188 getsockopt(fds[j].fd, SOL_SOCKET, SO_OOBINLINE, (char*) &oob_inlined, &olen);
5189 if (!oob_inlined)
5190 fds[j].events |= POLLPRI;
5192 else
5194 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
5195 fds[j].fd = -1;
5196 fds[j].events = 0;
5199 return fds;
5201 failed:
5202 count = j;
5203 j = 0;
5204 if (readfds)
5205 for (i = 0; i < readfds->fd_count && j < count; i++, j++)
5206 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
5207 if (writefds)
5208 for (i = 0; i < writefds->fd_count && j < count; i++, j++)
5209 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
5210 if (exceptfds)
5211 for (i = 0; i < exceptfds->fd_count && j < count; i++, j++)
5212 if (fds[j].fd != -1) release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
5213 return NULL;
5216 /* release the file descriptor obtained in fd_sets_to_poll */
5217 /* must be called with the original fd_set arrays, before calling get_poll_results */
5218 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
5219 const WS_fd_set *exceptfds, struct pollfd *fds )
5221 unsigned int i, j = 0;
5223 if (readfds)
5225 for (i = 0; i < readfds->fd_count; i++, j++)
5226 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
5228 if (writefds)
5230 for (i = 0; i < writefds->fd_count; i++, j++)
5231 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
5233 if (exceptfds)
5235 for (i = 0; i < exceptfds->fd_count; i++, j++)
5237 if (fds[j].fd == -1) continue;
5238 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
5239 if (fds[j].revents & POLLHUP)
5241 int fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
5242 if (fd != -1)
5243 release_sock_fd( exceptfds->fd_array[i], fd );
5244 else
5245 fds[j].revents = 0;
5251 static int do_poll(struct pollfd *pollfds, int count, int timeout)
5253 struct timeval tv1, tv2;
5254 int ret, torig = timeout;
5256 if (timeout > 0) gettimeofday( &tv1, 0 );
5258 while ((ret = poll( pollfds, count, timeout )) < 0)
5260 if (errno != EINTR) break;
5261 if (timeout < 0) continue;
5262 if (timeout == 0) return 0;
5264 gettimeofday( &tv2, 0 );
5266 tv2.tv_sec -= tv1.tv_sec;
5267 tv2.tv_usec -= tv1.tv_usec;
5268 if (tv2.tv_usec < 0)
5270 tv2.tv_usec += 1000000;
5271 tv2.tv_sec -= 1;
5274 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
5275 if (timeout <= 0) return 0;
5277 return ret;
5280 /* map the poll results back into the Windows fd sets */
5281 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
5282 const struct pollfd *fds )
5284 const struct pollfd *poll_writefds = fds + (readfds ? readfds->fd_count : 0);
5285 const struct pollfd *poll_exceptfds = poll_writefds + (writefds ? writefds->fd_count : 0);
5286 unsigned int i, k, total = 0;
5288 if (readfds)
5290 for (i = k = 0; i < readfds->fd_count; i++)
5292 if (fds[i].revents ||
5293 (readfds == writefds && (poll_writefds[i].revents & POLLOUT) && !(poll_writefds[i].revents & POLLHUP)) ||
5294 (readfds == exceptfds && poll_exceptfds[i].revents))
5295 readfds->fd_array[k++] = readfds->fd_array[i];
5297 readfds->fd_count = k;
5298 total += k;
5300 if (writefds && writefds != readfds)
5302 for (i = k = 0; i < writefds->fd_count; i++)
5304 if (((poll_writefds[i].revents & POLLOUT) && !(poll_writefds[i].revents & POLLHUP)) ||
5305 (writefds == exceptfds && poll_exceptfds[i].revents))
5306 writefds->fd_array[k++] = writefds->fd_array[i];
5308 writefds->fd_count = k;
5309 total += k;
5311 if (exceptfds && exceptfds != readfds && exceptfds != writefds)
5313 for (i = k = 0; i < exceptfds->fd_count; i++)
5314 if (poll_exceptfds[i].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
5315 exceptfds->fd_count = k;
5316 total += k;
5318 return total;
5321 /***********************************************************************
5322 * select (WS2_32.18)
5324 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
5325 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
5326 const struct WS_timeval* ws_timeout)
5328 struct pollfd *pollfds;
5329 int count, ret, timeout = -1;
5331 TRACE("read %p, write %p, excp %p timeout %p\n",
5332 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
5334 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )))
5335 return SOCKET_ERROR;
5337 if (ws_timeout)
5338 timeout = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
5340 ret = do_poll(pollfds, count, timeout);
5341 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
5343 if (ret == -1) SetLastError(wsaErrno());
5344 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
5345 return ret;
5348 /***********************************************************************
5349 * WSAPoll
5351 int WINAPI WSAPoll(WSAPOLLFD *wfds, ULONG count, int timeout)
5353 int i, ret;
5354 struct pollfd *ufds;
5356 if (!count)
5358 SetLastError(WSAEINVAL);
5359 return SOCKET_ERROR;
5361 if (!wfds)
5363 SetLastError(WSAEFAULT);
5364 return SOCKET_ERROR;
5367 if (!(ufds = HeapAlloc(GetProcessHeap(), 0, count * sizeof(ufds[0]))))
5369 SetLastError(WSAENOBUFS);
5370 return SOCKET_ERROR;
5373 for (i = 0; i < count; i++)
5375 ufds[i].fd = get_sock_fd(wfds[i].fd, 0, NULL);
5376 ufds[i].events = convert_poll_w2u(wfds[i].events);
5377 ufds[i].revents = 0;
5380 ret = do_poll(ufds, count, timeout);
5382 for (i = 0; i < count; i++)
5384 if (ufds[i].fd != -1)
5386 release_sock_fd(wfds[i].fd, ufds[i].fd);
5387 if (ufds[i].revents & POLLHUP)
5389 /* Check if the socket still exists */
5390 int fd = get_sock_fd(wfds[i].fd, 0, NULL);
5391 if (fd != -1)
5393 wfds[i].revents = WS_POLLHUP;
5394 release_sock_fd(wfds[i].fd, fd);
5396 else
5397 wfds[i].revents = WS_POLLNVAL;
5399 else
5400 wfds[i].revents = convert_poll_u2w(ufds[i].revents);
5402 else
5403 wfds[i].revents = WS_POLLNVAL;
5406 HeapFree(GetProcessHeap(), 0, ufds);
5407 return ret;
5410 /* helper to send completion messages for client-only i/o operation case */
5411 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
5412 ULONG Information )
5414 SERVER_START_REQ( add_fd_completion )
5416 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
5417 req->cvalue = CompletionValue;
5418 req->status = CompletionStatus;
5419 req->information = Information;
5420 wine_server_call( req );
5422 SERVER_END_REQ;
5426 /***********************************************************************
5427 * send (WS2_32.19)
5429 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
5431 DWORD n;
5432 WSABUF wsabuf;
5434 wsabuf.len = len;
5435 wsabuf.buf = (char*) buf;
5437 if ( WS2_sendto( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
5438 return SOCKET_ERROR;
5439 else
5440 return n;
5443 /***********************************************************************
5444 * WSASend (WS2_32.72)
5446 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5447 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
5448 LPWSAOVERLAPPED lpOverlapped,
5449 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5451 return WS2_sendto( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
5452 NULL, 0, lpOverlapped, lpCompletionRoutine );
5455 /***********************************************************************
5456 * WSASendDisconnect (WS2_32.73)
5458 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
5460 return WS_shutdown( s, SD_SEND );
5464 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5465 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
5466 const struct WS_sockaddr *to, int tolen,
5467 LPWSAOVERLAPPED lpOverlapped,
5468 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5470 unsigned int i, options;
5471 int n, fd, err, overlapped, flags;
5472 struct ws2_async *wsa = NULL, localwsa;
5473 int totalLength = 0;
5474 DWORD bytes_sent;
5475 BOOL is_blocking;
5477 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
5478 s, lpBuffers, dwBufferCount, dwFlags,
5479 to, tolen, lpOverlapped, lpCompletionRoutine);
5481 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
5482 TRACE( "fd=%d, options=%x\n", fd, options );
5484 if ( fd == -1 ) return SOCKET_ERROR;
5486 if (!lpOverlapped && !lpNumberOfBytesSent)
5488 err = WSAEFAULT;
5489 goto error;
5492 overlapped = (lpOverlapped || lpCompletionRoutine) &&
5493 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
5494 if (overlapped || dwBufferCount > 1)
5496 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[dwBufferCount]))))
5498 err = WSAEFAULT;
5499 goto error;
5502 else
5503 wsa = &localwsa;
5505 wsa->hSocket = SOCKET2HANDLE(s);
5506 wsa->addr = (struct WS_sockaddr *)to;
5507 wsa->addrlen.val = tolen;
5508 wsa->flags = dwFlags;
5509 wsa->lpFlags = &wsa->flags;
5510 wsa->control = NULL;
5511 wsa->n_iovecs = dwBufferCount;
5512 wsa->first_iovec = 0;
5513 for ( i = 0; i < dwBufferCount; i++ )
5515 wsa->iovec[i].iov_base = lpBuffers[i].buf;
5516 wsa->iovec[i].iov_len = lpBuffers[i].len;
5517 totalLength += lpBuffers[i].len;
5520 flags = convert_flags(dwFlags);
5521 n = WS2_send( fd, wsa, flags );
5522 if (n == -1 && errno != EAGAIN)
5524 err = wsaErrno();
5525 goto error;
5528 if (overlapped)
5530 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
5531 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
5533 wsa->user_overlapped = lpOverlapped;
5534 wsa->completion_func = lpCompletionRoutine;
5535 release_sock_fd( s, fd );
5537 if (n == -1 || n < totalLength)
5539 iosb->u.Status = STATUS_PENDING;
5540 iosb->Information = n == -1 ? 0 : n;
5542 SERVER_START_REQ( register_async )
5544 req->type = ASYNC_TYPE_WRITE;
5545 req->async.handle = wine_server_obj_handle( wsa->hSocket );
5546 req->async.callback = wine_server_client_ptr( WS2_async_send );
5547 req->async.iosb = wine_server_client_ptr( iosb );
5548 req->async.arg = wine_server_client_ptr( wsa );
5549 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
5550 req->async.cvalue = cvalue;
5551 err = wine_server_call( req );
5553 SERVER_END_REQ;
5555 /* Enable the event only after starting the async. The server will deliver it as soon as
5556 the async is done. */
5557 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
5559 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
5560 SetLastError(NtStatusToWSAError( err ));
5561 return SOCKET_ERROR;
5564 iosb->u.Status = STATUS_SUCCESS;
5565 iosb->Information = n;
5566 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = n;
5567 if (!wsa->completion_func)
5569 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
5570 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
5571 HeapFree( GetProcessHeap(), 0, wsa );
5573 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
5574 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
5575 SetLastError(ERROR_SUCCESS);
5576 return 0;
5579 if ((err = _is_blocking( s, &is_blocking )))
5581 err = NtStatusToWSAError( err );
5582 goto error;
5585 if ( is_blocking )
5587 /* On a blocking non-overlapped stream socket,
5588 * sending blocks until the entire buffer is sent. */
5589 DWORD timeout_start = GetTickCount();
5591 bytes_sent = n == -1 ? 0 : n;
5593 while (wsa->first_iovec < wsa->n_iovecs)
5595 struct pollfd pfd;
5596 int poll_timeout = -1;
5597 INT64 timeout = get_rcvsnd_timeo(fd, FALSE);
5599 if (timeout)
5601 timeout -= GetTickCount() - timeout_start;
5602 if (timeout < 0) poll_timeout = 0;
5603 else poll_timeout = timeout <= INT_MAX ? timeout : INT_MAX;
5606 pfd.fd = fd;
5607 pfd.events = POLLOUT;
5609 if (!poll_timeout || !poll( &pfd, 1, poll_timeout ))
5611 err = WSAETIMEDOUT;
5612 goto error; /* msdn says a timeout in send is fatal */
5615 n = WS2_send( fd, wsa, flags );
5616 if (n == -1 && errno != EAGAIN)
5618 err = wsaErrno();
5619 goto error;
5622 if (n >= 0)
5623 bytes_sent += n;
5626 else /* non-blocking */
5628 if (n < totalLength)
5629 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
5630 if (n == -1)
5632 err = WSAEWOULDBLOCK;
5633 goto error;
5635 bytes_sent = n;
5638 TRACE(" -> %i bytes\n", bytes_sent);
5640 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = bytes_sent;
5641 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
5642 release_sock_fd( s, fd );
5643 SetLastError(ERROR_SUCCESS);
5644 return 0;
5646 error:
5647 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
5648 release_sock_fd( s, fd );
5649 WARN(" -> ERROR %d\n", err);
5650 SetLastError(err);
5651 return SOCKET_ERROR;
5654 /***********************************************************************
5655 * WSASendTo (WS2_32.74)
5657 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5658 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
5659 const struct WS_sockaddr *to, int tolen,
5660 LPWSAOVERLAPPED lpOverlapped,
5661 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5663 return WS2_sendto( s, lpBuffers, dwBufferCount,
5664 lpNumberOfBytesSent, dwFlags,
5665 to, tolen,
5666 lpOverlapped, lpCompletionRoutine );
5669 /***********************************************************************
5670 * sendto (WS2_32.20)
5672 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
5673 const struct WS_sockaddr *to, int tolen)
5675 DWORD n;
5676 WSABUF wsabuf;
5678 wsabuf.len = len;
5679 wsabuf.buf = (char*) buf;
5681 if ( WS2_sendto(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
5682 return SOCKET_ERROR;
5683 else
5684 return n;
5687 /***********************************************************************
5688 * setsockopt (WS2_32.21)
5690 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
5691 const char *optval, int optlen)
5693 int fd;
5694 int woptval;
5695 struct linger linger;
5696 struct timeval tval;
5698 TRACE("(socket %04lx, %s, optval %s, optlen %d)\n", s,
5699 debugstr_sockopt(level, optname), debugstr_optval(optval, optlen),
5700 optlen);
5702 /* some broken apps pass the value directly instead of a pointer to it */
5703 if(optlen && IS_INTRESOURCE(optval))
5705 SetLastError(WSAEFAULT);
5706 return SOCKET_ERROR;
5709 switch(level)
5711 case WS_SOL_SOCKET:
5712 switch(optname)
5714 /* Some options need some conversion before they can be sent to
5715 * setsockopt. The conversions are done here, then they will fall through
5716 * to the general case. Special options that are not passed to
5717 * setsockopt follow below that.*/
5719 case WS_SO_DONTLINGER:
5720 if (!optval)
5722 SetLastError(WSAEFAULT);
5723 return SOCKET_ERROR;
5725 linger.l_onoff = *(const int*)optval == 0;
5726 linger.l_linger = 0;
5727 level = SOL_SOCKET;
5728 optname = SO_LINGER;
5729 optval = (char*)&linger;
5730 optlen = sizeof(struct linger);
5731 break;
5733 case WS_SO_LINGER:
5734 if (!optval)
5736 SetLastError(WSAEFAULT);
5737 return SOCKET_ERROR;
5739 linger.l_onoff = ((LINGER*)optval)->l_onoff;
5740 linger.l_linger = ((LINGER*)optval)->l_linger;
5741 level = SOL_SOCKET;
5742 optname = SO_LINGER;
5743 optval = (char*)&linger;
5744 optlen = sizeof(struct linger);
5745 break;
5747 case WS_SO_RCVBUF:
5748 if (*(const int*)optval < 2048)
5750 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
5751 return 0;
5753 /* Fall through */
5755 /* The options listed here don't need any special handling. Thanks to
5756 * the conversion happening above, options from there will fall through
5757 * to this, too.*/
5758 case WS_SO_ACCEPTCONN:
5759 case WS_SO_BROADCAST:
5760 case WS_SO_ERROR:
5761 case WS_SO_KEEPALIVE:
5762 case WS_SO_OOBINLINE:
5763 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
5764 * however, using it the BSD way fixes bug 8513 and seems to be what
5765 * most programmers assume, anyway */
5766 case WS_SO_REUSEADDR:
5767 case WS_SO_SNDBUF:
5768 case WS_SO_TYPE:
5769 convert_sockopt(&level, &optname);
5770 break;
5772 /* SO_DEBUG is a privileged operation, ignore it. */
5773 case WS_SO_DEBUG:
5774 TRACE("Ignoring SO_DEBUG\n");
5775 return 0;
5777 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
5778 * socket. According to MSDN, this option is silently ignored.*/
5779 case WS_SO_DONTROUTE:
5780 TRACE("Ignoring SO_DONTROUTE\n");
5781 return 0;
5783 /* Stops two sockets from being bound to the same port. Always happens
5784 * on unix systems, so just drop it. */
5785 case WS_SO_EXCLUSIVEADDRUSE:
5786 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
5787 return 0;
5789 /* After a ConnectEx call succeeds, the socket can't be used with half of the
5790 * normal winsock functions on windows. We don't have that problem. */
5791 case WS_SO_UPDATE_CONNECT_CONTEXT:
5792 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
5793 return 0;
5795 /* After a AcceptEx call succeeds, the socket can't be used with half of the
5796 * normal winsock functions on windows. We don't have that problem. */
5797 case WS_SO_UPDATE_ACCEPT_CONTEXT:
5798 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
5799 return 0;
5801 /* SO_OPENTYPE does not require a valid socket handle. */
5802 case WS_SO_OPENTYPE:
5803 if (!optlen || optlen < sizeof(int) || !optval)
5805 SetLastError(WSAEFAULT);
5806 return SOCKET_ERROR;
5808 get_per_thread_data()->opentype = *(const int *)optval;
5809 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
5810 return 0;
5812 #ifdef SO_RCVTIMEO
5813 case WS_SO_RCVTIMEO:
5814 #endif
5815 #ifdef SO_SNDTIMEO
5816 case WS_SO_SNDTIMEO:
5817 #endif
5818 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
5819 if (optval && optlen == sizeof(UINT32)) {
5820 /* WinSock passes milliseconds instead of struct timeval */
5821 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
5822 tval.tv_sec = *(const UINT32*)optval / 1000;
5823 /* min of 500 milliseconds */
5824 if (tval.tv_sec == 0 && tval.tv_usec && tval.tv_usec < 500000)
5825 tval.tv_usec = 500000;
5826 optlen = sizeof(struct timeval);
5827 optval = (char*)&tval;
5828 } else if (optlen == sizeof(struct timeval)) {
5829 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
5830 } else {
5831 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
5832 return 0;
5834 convert_sockopt(&level, &optname);
5835 break;
5836 #endif
5838 default:
5839 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
5840 SetLastError(WSAENOPROTOOPT);
5841 return SOCKET_ERROR;
5843 break; /* case WS_SOL_SOCKET */
5845 #ifdef HAS_IPX
5846 case WS_NSPROTO_IPX:
5847 switch(optname)
5849 case WS_IPX_PTYPE:
5850 return set_ipx_packettype(s, *(int*)optval);
5852 case WS_IPX_FILTERPTYPE:
5853 /* Sets the receive filter packet type, at the moment we don't support it */
5854 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
5855 /* Returning 0 is better for now than returning a SOCKET_ERROR */
5856 return 0;
5858 default:
5859 FIXME("opt_name:%x\n", optname);
5860 return SOCKET_ERROR;
5862 break; /* case WS_NSPROTO_IPX */
5863 #endif
5865 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
5866 case WS_IPPROTO_TCP:
5867 switch(optname)
5869 case WS_TCP_NODELAY:
5870 convert_sockopt(&level, &optname);
5871 break;
5872 default:
5873 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
5874 return SOCKET_ERROR;
5876 break;
5878 case WS_IPPROTO_IP:
5879 switch(optname)
5881 case WS_IP_ADD_MEMBERSHIP:
5882 case WS_IP_DROP_MEMBERSHIP:
5883 #ifdef IP_HDRINCL
5884 case WS_IP_HDRINCL:
5885 #endif
5886 case WS_IP_MULTICAST_IF:
5887 case WS_IP_MULTICAST_LOOP:
5888 case WS_IP_MULTICAST_TTL:
5889 case WS_IP_OPTIONS:
5890 #ifdef IP_PKTINFO
5891 case WS_IP_PKTINFO:
5892 #endif
5893 case WS_IP_TOS:
5894 case WS_IP_TTL:
5895 #ifdef IP_UNICAST_IF
5896 case WS_IP_UNICAST_IF:
5897 #endif
5898 convert_sockopt(&level, &optname);
5899 break;
5900 case WS_IP_DONTFRAGMENT:
5901 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
5902 return 0;
5903 default:
5904 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
5905 return SOCKET_ERROR;
5907 break;
5909 case WS_IPPROTO_IPV6:
5910 switch(optname)
5912 #ifdef IPV6_ADD_MEMBERSHIP
5913 case WS_IPV6_ADD_MEMBERSHIP:
5914 #endif
5915 #ifdef IPV6_DROP_MEMBERSHIP
5916 case WS_IPV6_DROP_MEMBERSHIP:
5917 #endif
5918 case WS_IPV6_MULTICAST_IF:
5919 case WS_IPV6_MULTICAST_HOPS:
5920 case WS_IPV6_MULTICAST_LOOP:
5921 case WS_IPV6_UNICAST_HOPS:
5922 case WS_IPV6_V6ONLY:
5923 #ifdef IPV6_UNICAST_IF
5924 case WS_IPV6_UNICAST_IF:
5925 #endif
5926 convert_sockopt(&level, &optname);
5927 break;
5928 case WS_IPV6_DONTFRAG:
5929 FIXME("IPV6_DONTFRAG is silently ignored!\n");
5930 return 0;
5931 case WS_IPV6_PROTECTION_LEVEL:
5932 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
5933 return 0;
5934 default:
5935 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
5936 return SOCKET_ERROR;
5938 break;
5940 default:
5941 WARN("Unknown level: 0x%08x\n", level);
5942 SetLastError(WSAEINVAL);
5943 return SOCKET_ERROR;
5944 } /* end switch(level) */
5946 /* avoid endianness issues if argument is a 16-bit int */
5947 if (optval && optlen < sizeof(int))
5949 woptval= *((const INT16 *) optval);
5950 optval= (char*) &woptval;
5951 woptval&= (1 << optlen * 8) - 1;
5952 optlen=sizeof(int);
5954 fd = get_sock_fd( s, 0, NULL );
5955 if (fd == -1) return SOCKET_ERROR;
5957 if (setsockopt(fd, level, optname, optval, optlen) == 0)
5959 #ifdef __APPLE__
5960 if (level == SOL_SOCKET && optname == SO_REUSEADDR &&
5961 setsockopt(fd, level, SO_REUSEPORT, optval, optlen) != 0)
5963 SetLastError(wsaErrno());
5964 release_sock_fd( s, fd );
5965 return SOCKET_ERROR;
5967 #endif
5968 release_sock_fd( s, fd );
5969 return 0;
5971 TRACE("Setting socket error, %d\n", wsaErrno());
5972 SetLastError(wsaErrno());
5973 release_sock_fd( s, fd );
5975 return SOCKET_ERROR;
5978 /***********************************************************************
5979 * shutdown (WS2_32.22)
5981 int WINAPI WS_shutdown(SOCKET s, int how)
5983 int fd, err = WSAENOTSOCK;
5984 unsigned int options = 0, clear_flags = 0;
5986 fd = get_sock_fd( s, 0, &options );
5987 TRACE("socket %04lx, how 0x%x, options 0x%x\n", s, how, options );
5989 if (fd == -1)
5990 return SOCKET_ERROR;
5992 switch( how )
5994 case SD_RECEIVE: /* drop receives */
5995 clear_flags |= FD_READ;
5996 break;
5997 case SD_SEND: /* drop sends */
5998 clear_flags |= FD_WRITE;
5999 break;
6000 case SD_BOTH: /* drop all */
6001 clear_flags |= FD_READ|FD_WRITE;
6002 /*fall through */
6003 default:
6004 clear_flags |= FD_WINE_LISTENING;
6007 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
6009 switch ( how )
6011 case SD_RECEIVE:
6012 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
6013 break;
6014 case SD_SEND:
6015 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
6016 break;
6017 case SD_BOTH:
6018 default:
6019 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
6020 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
6021 break;
6023 if (err) goto error;
6025 else /* non-overlapped mode */
6027 if ( shutdown( fd, how ) )
6029 err = wsaErrno();
6030 goto error;
6034 release_sock_fd( s, fd );
6035 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
6036 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
6037 return 0;
6039 error:
6040 release_sock_fd( s, fd );
6041 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
6042 SetLastError( err );
6043 return SOCKET_ERROR;
6046 /***********************************************************************
6047 * socket (WS2_32.23)
6049 SOCKET WINAPI WS_socket(int af, int type, int protocol)
6051 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
6053 return WSASocketW( af, type, protocol, NULL, 0,
6054 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
6058 /***********************************************************************
6059 * gethostbyaddr (WS2_32.51)
6061 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
6063 struct WS_hostent *retval = NULL;
6064 struct hostent* host;
6065 int unixtype = convert_af_w2u(type);
6066 const char *paddr = addr;
6067 unsigned long loopback;
6068 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6069 char *extrabuf;
6070 int ebufsize = 1024;
6071 struct hostent hostentry;
6072 int locerr = ENOBUFS;
6073 #endif
6075 /* convert back the magic loopback address if necessary */
6076 if (unixtype == AF_INET && len == 4 && !memcmp(addr, magic_loopback_addr, 4))
6078 loopback = htonl(INADDR_LOOPBACK);
6079 paddr = (char*) &loopback;
6082 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6083 host = NULL;
6084 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
6085 while(extrabuf) {
6086 int res = gethostbyaddr_r(paddr, len, unixtype,
6087 &hostentry, extrabuf, ebufsize, &host, &locerr);
6088 if (res != ERANGE) break;
6089 ebufsize *=2;
6090 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
6092 if (host) retval = WS_dup_he(host);
6093 else SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
6094 HeapFree(GetProcessHeap(),0,extrabuf);
6095 #else
6096 EnterCriticalSection( &csWSgetXXXbyYYY );
6097 host = gethostbyaddr(paddr, len, unixtype);
6098 if (host) retval = WS_dup_he(host);
6099 else SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
6100 LeaveCriticalSection( &csWSgetXXXbyYYY );
6101 #endif
6102 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
6103 return retval;
6106 /***********************************************************************
6107 * WS_compare_routes_by_metric_asc (INTERNAL)
6109 * Comparison function for qsort(), for sorting two routes (struct route)
6110 * by metric in ascending order.
6112 static int WS_compare_routes_by_metric_asc(const void *left, const void *right)
6114 const struct route *a = left, *b = right;
6115 if (a->default_route && b->default_route)
6116 return a->default_route - b->default_route;
6117 if (a->default_route && !b->default_route)
6118 return -1;
6119 if (b->default_route && !a->default_route)
6120 return 1;
6121 return a->metric - b->metric;
6124 /***********************************************************************
6125 * WS_get_local_ips (INTERNAL)
6127 * Returns the list of local IP addresses by going through the network
6128 * adapters and using the local routing table to sort the addresses
6129 * from highest routing priority to lowest routing priority. This
6130 * functionality is inferred from the description for obtaining local
6131 * IP addresses given in the Knowledge Base Article Q160215.
6133 * Please note that the returned hostent is only freed when the thread
6134 * closes and is replaced if another hostent is requested.
6136 static struct WS_hostent* WS_get_local_ips( char *hostname )
6138 int numroutes = 0, i, j, default_routes = 0;
6139 DWORD n;
6140 PIP_ADAPTER_INFO adapters = NULL, k;
6141 struct WS_hostent *hostlist = NULL;
6142 PMIB_IPFORWARDTABLE routes = NULL;
6143 struct route *route_addrs = NULL;
6144 DWORD adap_size, route_size;
6146 /* Obtain the size of the adapter list and routing table, also allocate memory */
6147 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
6148 return NULL;
6149 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
6150 return NULL;
6151 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
6152 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
6153 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
6154 if (adapters == NULL || routes == NULL || route_addrs == NULL)
6155 goto cleanup;
6156 /* Obtain the adapter list and the full routing table */
6157 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
6158 goto cleanup;
6159 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
6160 goto cleanup;
6161 /* Store the interface associated with each route */
6162 for (n = 0; n < routes->dwNumEntries; n++)
6164 IF_INDEX ifindex;
6165 DWORD ifmetric, ifdefault = 0;
6166 BOOL exists = FALSE;
6168 /* Check if this is a default route (there may be more than one) */
6169 if (!routes->table[n].dwForwardDest)
6170 ifdefault = ++default_routes;
6171 else if (routes->table[n].u1.ForwardType != MIB_IPROUTE_TYPE_DIRECT)
6172 continue;
6173 ifindex = routes->table[n].dwForwardIfIndex;
6174 ifmetric = routes->table[n].dwForwardMetric1;
6175 /* Only store the lowest valued metric for an interface */
6176 for (j = 0; j < numroutes; j++)
6178 if (route_addrs[j].interface == ifindex)
6180 if (route_addrs[j].metric > ifmetric)
6181 route_addrs[j].metric = ifmetric;
6182 exists = TRUE;
6185 if (exists)
6186 continue;
6187 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
6188 if (route_addrs == NULL)
6189 goto cleanup; /* Memory allocation error, fail gracefully */
6190 route_addrs[numroutes].interface = ifindex;
6191 route_addrs[numroutes].metric = ifmetric;
6192 route_addrs[numroutes].default_route = ifdefault;
6193 /* If no IP is found in the next step (for whatever reason)
6194 * then fall back to the magic loopback address.
6196 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
6197 numroutes++;
6199 if (numroutes == 0)
6200 goto cleanup; /* No routes, fall back to the Magic IP */
6201 /* Find the IP address associated with each found interface */
6202 for (i = 0; i < numroutes; i++)
6204 for (k = adapters; k != NULL; k = k->Next)
6206 char *ip = k->IpAddressList.IpAddress.String;
6208 if (route_addrs[i].interface == k->Index)
6209 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
6212 /* Allocate a hostent and enough memory for all the IPs,
6213 * including the NULL at the end of the list.
6215 hostlist = WS_create_he(hostname, 1, 0, numroutes+1, sizeof(struct in_addr));
6216 if (hostlist == NULL)
6217 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
6218 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
6219 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
6220 hostlist->h_addrtype = AF_INET;
6221 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
6222 /* Reorder the entries before placing them in the host list. Windows expects
6223 * the IP list in order from highest priority to lowest (the critical thing
6224 * is that most applications expect the first IP to be the default route).
6226 if (numroutes > 1)
6227 qsort(route_addrs, numroutes, sizeof(struct route), WS_compare_routes_by_metric_asc);
6229 for (i = 0; i < numroutes; i++)
6230 (*(struct in_addr *) hostlist->h_addr_list[i]) = route_addrs[i].addr;
6232 /* Cleanup all allocated memory except the address list,
6233 * the address list is used by the calling app.
6235 cleanup:
6236 HeapFree(GetProcessHeap(), 0, route_addrs);
6237 HeapFree(GetProcessHeap(), 0, adapters);
6238 HeapFree(GetProcessHeap(), 0, routes);
6239 return hostlist;
6242 /***********************************************************************
6243 * gethostbyname (WS2_32.52)
6245 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
6247 struct WS_hostent *retval = NULL;
6248 struct hostent* host;
6249 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6250 char *extrabuf;
6251 int ebufsize=1024;
6252 struct hostent hostentry;
6253 int locerr = ENOBUFS;
6254 #endif
6255 char hostname[100];
6256 if(!num_startup) {
6257 SetLastError(WSANOTINITIALISED);
6258 return NULL;
6260 if( gethostname( hostname, 100) == -1) {
6261 SetLastError(WSAENOBUFS); /* appropriate ? */
6262 return retval;
6264 if( !name || !name[0]) {
6265 name = hostname;
6267 /* If the hostname of the local machine is requested then return the
6268 * complete list of local IP addresses */
6269 if(strcmp(name, hostname) == 0)
6270 retval = WS_get_local_ips(hostname);
6271 /* If any other hostname was requested (or the routing table lookup failed)
6272 * then return the IP found by the host OS */
6273 if(retval == NULL)
6275 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6276 host = NULL;
6277 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
6278 while(extrabuf) {
6279 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
6280 if( res != ERANGE) break;
6281 ebufsize *=2;
6282 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
6284 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
6285 #else
6286 EnterCriticalSection( &csWSgetXXXbyYYY );
6287 host = gethostbyname(name);
6288 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
6289 #endif
6290 if (host) retval = WS_dup_he(host);
6291 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6292 HeapFree(GetProcessHeap(),0,extrabuf);
6293 #else
6294 LeaveCriticalSection( &csWSgetXXXbyYYY );
6295 #endif
6297 if (retval && retval->h_addr_list[0][0] == 127 &&
6298 strcmp(name, "localhost") != 0)
6300 /* hostname != "localhost" but has loopback address. replace by our
6301 * special address.*/
6302 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
6304 TRACE( "%s ret %p\n", debugstr_a(name), retval );
6305 return retval;
6309 /***********************************************************************
6310 * getprotobyname (WS2_32.53)
6312 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
6314 struct WS_protoent* retval = NULL;
6315 #ifdef HAVE_GETPROTOBYNAME
6316 struct protoent* proto;
6317 EnterCriticalSection( &csWSgetXXXbyYYY );
6318 if( (proto = getprotobyname(name)) != NULL )
6320 retval = WS_dup_pe(proto);
6322 else {
6323 MESSAGE("protocol %s not found; You might want to add "
6324 "this to /etc/protocols\n", debugstr_a(name) );
6325 SetLastError(WSANO_DATA);
6327 LeaveCriticalSection( &csWSgetXXXbyYYY );
6328 #endif
6329 TRACE( "%s ret %p\n", debugstr_a(name), retval );
6330 return retval;
6334 /***********************************************************************
6335 * getprotobynumber (WS2_32.54)
6337 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
6339 struct WS_protoent* retval = NULL;
6340 #ifdef HAVE_GETPROTOBYNUMBER
6341 struct protoent* proto;
6342 EnterCriticalSection( &csWSgetXXXbyYYY );
6343 if( (proto = getprotobynumber(number)) != NULL )
6345 retval = WS_dup_pe(proto);
6347 else {
6348 MESSAGE("protocol number %d not found; You might want to add "
6349 "this to /etc/protocols\n", number );
6350 SetLastError(WSANO_DATA);
6352 LeaveCriticalSection( &csWSgetXXXbyYYY );
6353 #endif
6354 TRACE("%i ret %p\n", number, retval);
6355 return retval;
6359 /***********************************************************************
6360 * getservbyname (WS2_32.55)
6362 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
6364 struct WS_servent* retval = NULL;
6365 struct servent* serv;
6366 char *name_str;
6367 char *proto_str = NULL;
6369 if (!(name_str = strdup_lower(name))) return NULL;
6371 if (proto && *proto)
6373 if (!(proto_str = strdup_lower(proto)))
6375 HeapFree( GetProcessHeap(), 0, name_str );
6376 return NULL;
6380 EnterCriticalSection( &csWSgetXXXbyYYY );
6381 serv = getservbyname(name_str, proto_str);
6382 if( serv != NULL )
6384 retval = WS_dup_se(serv);
6386 else SetLastError(WSANO_DATA);
6387 LeaveCriticalSection( &csWSgetXXXbyYYY );
6388 HeapFree( GetProcessHeap(), 0, proto_str );
6389 HeapFree( GetProcessHeap(), 0, name_str );
6390 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
6391 return retval;
6394 /***********************************************************************
6395 * freeaddrinfo (WS2_32.@)
6397 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
6399 while (res) {
6400 struct WS_addrinfo *next;
6402 HeapFree(GetProcessHeap(),0,res->ai_canonname);
6403 HeapFree(GetProcessHeap(),0,res->ai_addr);
6404 next = res->ai_next;
6405 HeapFree(GetProcessHeap(),0,res);
6406 res = next;
6410 /* helper functions for getaddrinfo()/getnameinfo() */
6411 static int convert_aiflag_w2u(int winflags) {
6412 unsigned int i;
6413 int unixflags = 0;
6415 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
6416 if (ws_aiflag_map[i][0] & winflags) {
6417 unixflags |= ws_aiflag_map[i][1];
6418 winflags &= ~ws_aiflag_map[i][0];
6420 if (winflags)
6421 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
6422 return unixflags;
6425 static int convert_niflag_w2u(int winflags) {
6426 unsigned int i;
6427 int unixflags = 0;
6429 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
6430 if (ws_niflag_map[i][0] & winflags) {
6431 unixflags |= ws_niflag_map[i][1];
6432 winflags &= ~ws_niflag_map[i][0];
6434 if (winflags)
6435 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
6436 return unixflags;
6439 static int convert_aiflag_u2w(int unixflags) {
6440 unsigned int i;
6441 int winflags = 0;
6443 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
6444 if (ws_aiflag_map[i][1] & unixflags) {
6445 winflags |= ws_aiflag_map[i][0];
6446 unixflags &= ~ws_aiflag_map[i][1];
6448 if (unixflags) /* will warn usually */
6449 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
6450 return winflags;
6453 static int convert_eai_u2w(int unixret) {
6454 int i;
6456 if (!unixret) return 0;
6458 for (i=0;ws_eai_map[i][0];i++)
6459 if (ws_eai_map[i][1] == unixret)
6460 return ws_eai_map[i][0];
6462 if (unixret == EAI_SYSTEM)
6463 /* There are broken versions of glibc which return EAI_SYSTEM
6464 * and set errno to 0 instead of returning EAI_NONAME.
6466 return errno ? sock_get_error( errno ) : WS_EAI_NONAME;
6468 FIXME("Unhandled unix EAI_xxx ret %d\n", unixret);
6469 return unixret;
6472 static char *get_hostname(void)
6474 char *ret;
6475 DWORD size = 0;
6477 GetComputerNameExA( ComputerNamePhysicalDnsHostname, NULL, &size );
6478 if (GetLastError() != ERROR_MORE_DATA) return NULL;
6479 if (!(ret = HeapAlloc( GetProcessHeap(), 0, size ))) return NULL;
6480 if (!GetComputerNameExA( ComputerNamePhysicalDnsHostname, ret, &size ))
6482 HeapFree( GetProcessHeap(), 0, ret );
6483 return NULL;
6485 return ret;
6488 /***********************************************************************
6489 * getaddrinfo (WS2_32.@)
6491 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
6493 #ifdef HAVE_GETADDRINFO
6494 struct addrinfo *unixaires = NULL;
6495 int result;
6496 struct addrinfo unixhints, *punixhints = NULL;
6497 char *hostname;
6498 const char *node;
6500 *res = NULL;
6501 if (!nodename && !servname)
6503 SetLastError(WSAHOST_NOT_FOUND);
6504 return WSAHOST_NOT_FOUND;
6507 hostname = get_hostname();
6508 if (!hostname) return WSA_NOT_ENOUGH_MEMORY;
6510 if (!nodename)
6511 node = NULL;
6512 else if (!nodename[0])
6513 node = hostname;
6514 else
6515 node = nodename;
6517 /* servname tweak required by OSX and BSD kernels */
6518 if (servname && !servname[0]) servname = "0";
6520 if (hints) {
6521 punixhints = &unixhints;
6523 memset(&unixhints, 0, sizeof(unixhints));
6524 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
6526 /* zero is a wildcard, no need to convert */
6527 if (hints->ai_family)
6528 punixhints->ai_family = convert_af_w2u(hints->ai_family);
6529 if (hints->ai_socktype)
6530 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
6531 if (hints->ai_protocol)
6532 punixhints->ai_protocol = max(convert_proto_w2u(hints->ai_protocol), 0);
6534 if (punixhints->ai_socktype < 0)
6536 SetLastError(WSAESOCKTNOSUPPORT);
6537 HeapFree(GetProcessHeap(), 0, hostname);
6538 return SOCKET_ERROR;
6541 /* windows allows invalid combinations of socket type and protocol, unix does not.
6542 * fix the parameters here to make getaddrinfo call always work */
6543 if (punixhints->ai_protocol == IPPROTO_TCP &&
6544 punixhints->ai_socktype != SOCK_STREAM && punixhints->ai_socktype != SOCK_SEQPACKET)
6545 punixhints->ai_socktype = 0;
6547 else if (punixhints->ai_protocol == IPPROTO_UDP && punixhints->ai_socktype != SOCK_DGRAM)
6548 punixhints->ai_socktype = 0;
6550 else if (IS_IPX_PROTO(punixhints->ai_protocol) && punixhints->ai_socktype != SOCK_DGRAM)
6551 punixhints->ai_socktype = 0;
6553 else if (punixhints->ai_protocol == IPPROTO_IPV6)
6554 punixhints->ai_protocol = 0;
6557 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
6558 result = getaddrinfo(node, servname, punixhints, &unixaires);
6560 if (result && !strcmp(hostname, node))
6562 /* If it didn't work it means the host name IP is not in /etc/hosts, try again
6563 * by sending a NULL host and avoid sending a NULL servname too because that
6564 * is invalid */
6565 ERR_(winediag)("Failed to resolve your host name IP\n");
6566 result = getaddrinfo(NULL, servname ? servname : "0", punixhints, &unixaires);
6568 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
6569 HeapFree(GetProcessHeap(), 0, hostname);
6571 if (!result) {
6572 struct addrinfo *xuai = unixaires;
6573 struct WS_addrinfo **xai = res;
6575 *xai = NULL;
6576 while (xuai) {
6577 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
6578 SIZE_T len;
6580 if (!ai)
6581 goto outofmem;
6583 *xai = ai;xai = &ai->ai_next;
6584 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
6585 ai->ai_family = convert_af_u2w(xuai->ai_family);
6586 /* copy whatever was sent in the hints */
6587 if(hints) {
6588 ai->ai_socktype = hints->ai_socktype;
6589 ai->ai_protocol = hints->ai_protocol;
6590 } else {
6591 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
6592 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
6594 if (xuai->ai_canonname) {
6595 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
6596 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
6597 if (!ai->ai_canonname)
6598 goto outofmem;
6599 strcpy(ai->ai_canonname,xuai->ai_canonname);
6601 len = xuai->ai_addrlen;
6602 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
6603 if (!ai->ai_addr)
6604 goto outofmem;
6605 ai->ai_addrlen = len;
6606 do {
6607 int winlen = ai->ai_addrlen;
6609 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
6610 ai->ai_addrlen = winlen;
6611 break;
6613 len = 2*len;
6614 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
6615 if (!ai->ai_addr)
6616 goto outofmem;
6617 ai->ai_addrlen = len;
6618 } while (1);
6619 xuai = xuai->ai_next;
6621 freeaddrinfo(unixaires);
6623 if (TRACE_ON(winsock))
6625 struct WS_addrinfo *ai = *res;
6626 while (ai)
6628 TRACE("=> %p, flags %#x, family %d, type %d, protocol %d, len %ld, name %s, addr %s\n",
6629 ai, ai->ai_flags, ai->ai_family, ai->ai_socktype, ai->ai_protocol, ai->ai_addrlen,
6630 ai->ai_canonname, debugstr_sockaddr(ai->ai_addr));
6631 ai = ai->ai_next;
6634 } else
6635 result = convert_eai_u2w(result);
6637 SetLastError(result);
6638 return result;
6640 outofmem:
6641 if (*res) WS_freeaddrinfo(*res);
6642 if (unixaires) freeaddrinfo(unixaires);
6643 return WSA_NOT_ENOUGH_MEMORY;
6644 #else
6645 FIXME("getaddrinfo() failed, not found during buildtime.\n");
6646 return EAI_FAIL;
6647 #endif
6650 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
6652 struct WS_addrinfoW *ret;
6654 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
6655 ret->ai_flags = ai->ai_flags;
6656 ret->ai_family = ai->ai_family;
6657 ret->ai_socktype = ai->ai_socktype;
6658 ret->ai_protocol = ai->ai_protocol;
6659 ret->ai_addrlen = ai->ai_addrlen;
6660 ret->ai_canonname = NULL;
6661 ret->ai_addr = NULL;
6662 ret->ai_next = NULL;
6663 if (ai->ai_canonname)
6665 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
6666 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR))))
6668 HeapFree(GetProcessHeap(), 0, ret);
6669 return NULL;
6671 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
6673 if (ai->ai_addr)
6675 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, ai->ai_addrlen)))
6677 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
6678 HeapFree(GetProcessHeap(), 0, ret);
6679 return NULL;
6681 memcpy(ret->ai_addr, ai->ai_addr, ai->ai_addrlen);
6683 return ret;
6686 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
6688 struct WS_addrinfoW *ret, *infoW;
6690 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
6691 while (info->ai_next)
6693 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
6695 FreeAddrInfoW(ret);
6696 return NULL;
6698 infoW = infoW->ai_next;
6699 info = info->ai_next;
6701 return ret;
6704 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
6706 struct WS_addrinfo *ret;
6708 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
6709 ret->ai_flags = ai->ai_flags;
6710 ret->ai_family = ai->ai_family;
6711 ret->ai_socktype = ai->ai_socktype;
6712 ret->ai_protocol = ai->ai_protocol;
6713 ret->ai_addrlen = ai->ai_addrlen;
6714 ret->ai_canonname = NULL;
6715 ret->ai_addr = NULL;
6716 ret->ai_next = NULL;
6717 if (ai->ai_canonname)
6719 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
6720 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
6722 HeapFree(GetProcessHeap(), 0, ret);
6723 return NULL;
6725 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
6727 if (ai->ai_addr)
6729 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
6731 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
6732 HeapFree(GetProcessHeap(), 0, ret);
6733 return NULL;
6735 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
6737 return ret;
6740 /***********************************************************************
6741 * GetAddrInfoExW (WS2_32.@)
6743 int WINAPI GetAddrInfoExW(const WCHAR *name, const WCHAR *servname, DWORD namespace, GUID *namespace_id,
6744 const ADDRINFOEXW *hints, ADDRINFOEXW **result, struct timeval *timeout, OVERLAPPED *overlapped,
6745 LPLOOKUPSERVICE_COMPLETION_ROUTINE completion_routine, HANDLE *handle)
6747 FIXME("(%s %s %x %s %p %p %p %p %p %p)\n", debugstr_w(name), debugstr_w(servname), namespace,
6748 debugstr_guid(namespace_id), hints, result, timeout, overlapped, completion_routine, handle);
6749 return WSAHOST_NOT_FOUND;
6752 /***********************************************************************
6753 * GetAddrInfoW (WS2_32.@)
6755 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
6757 int ret = EAI_MEMORY, len, i;
6758 char *nodenameA = NULL, *servnameA = NULL;
6759 struct WS_addrinfo *resA, *hintsA = NULL;
6760 WCHAR *local_nodenameW = (WCHAR *)nodename;
6762 TRACE("nodename %s, servname %s, hints %p, result %p\n",
6763 debugstr_w(nodename), debugstr_w(servname), hints, res);
6765 *res = NULL;
6766 if (nodename)
6768 /* Is this an IDN? Most likely if any char is above the Ascii table, this
6769 * is the simplest validation possible, further validation will be done by
6770 * the native getaddrinfo() */
6771 for (i = 0; nodename[i]; i++)
6773 if (nodename[i] > 'z')
6774 break;
6776 if (nodename[i])
6778 if (hints && (hints->ai_flags & WS_AI_DISABLE_IDN_ENCODING))
6780 /* Name requires conversion but it was disabled */
6781 ret = WSAHOST_NOT_FOUND;
6782 WSASetLastError(ret);
6783 goto end;
6786 len = IdnToAscii(0, nodename, -1, NULL, 0);
6787 if (!len)
6789 ERR("Failed to convert %s to punycode\n", debugstr_w(nodename));
6790 ret = EAI_FAIL;
6791 goto end;
6793 if (!(local_nodenameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) goto end;
6794 IdnToAscii(0, nodename, -1, local_nodenameW, len);
6797 if (local_nodenameW)
6799 len = WideCharToMultiByte(CP_ACP, 0, local_nodenameW, -1, NULL, 0, NULL, NULL);
6800 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) goto end;
6801 WideCharToMultiByte(CP_ACP, 0, local_nodenameW, -1, nodenameA, len, NULL, NULL);
6803 if (servname)
6805 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
6806 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len))) goto end;
6807 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
6810 if (hints) hintsA = addrinfo_WtoA(hints);
6811 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
6812 WS_freeaddrinfo(hintsA);
6814 if (!ret)
6816 *res = addrinfo_list_AtoW(resA);
6817 WS_freeaddrinfo(resA);
6820 end:
6821 if (local_nodenameW != nodename)
6822 HeapFree(GetProcessHeap(), 0, local_nodenameW);
6823 HeapFree(GetProcessHeap(), 0, nodenameA);
6824 HeapFree(GetProcessHeap(), 0, servnameA);
6825 return ret;
6828 /***********************************************************************
6829 * FreeAddrInfoW (WS2_32.@)
6831 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
6833 while (ai)
6835 ADDRINFOW *next;
6836 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
6837 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
6838 next = ai->ai_next;
6839 HeapFree(GetProcessHeap(), 0, ai);
6840 ai = next;
6844 /***********************************************************************
6845 * FreeAddrInfoExW (WS2_32.@)
6847 void WINAPI FreeAddrInfoExW(ADDRINFOEXW *ai)
6849 FIXME("%p\n", ai);
6852 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
6853 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
6855 #ifdef HAVE_GETNAMEINFO
6856 int ret;
6857 union generic_unix_sockaddr sa_u;
6858 unsigned int size;
6860 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
6861 serv, servlen, flags);
6863 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
6864 if (!size)
6866 SetLastError(WSAEFAULT);
6867 return WSA_NOT_ENOUGH_MEMORY;
6869 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
6870 return convert_eai_u2w(ret);
6871 #else
6872 FIXME("getnameinfo() failed, not found during buildtime.\n");
6873 return EAI_FAIL;
6874 #endif
6877 int WINAPI GetNameInfoW(const SOCKADDR *sa, WS_socklen_t salen, PWCHAR host,
6878 DWORD hostlen, PWCHAR serv, DWORD servlen, INT flags)
6880 int ret;
6881 char *hostA = NULL, *servA = NULL;
6883 if (host && (!(hostA = HeapAlloc(GetProcessHeap(), 0, hostlen)))) return EAI_MEMORY;
6884 if (serv && (!(servA = HeapAlloc(GetProcessHeap(), 0, servlen))))
6886 HeapFree(GetProcessHeap(), 0, hostA);
6887 return EAI_MEMORY;
6890 ret = WS_getnameinfo(sa, salen, hostA, hostlen, servA, servlen, flags);
6891 if (!ret)
6893 if (host) MultiByteToWideChar(CP_ACP, 0, hostA, -1, host, hostlen);
6894 if (serv) MultiByteToWideChar(CP_ACP, 0, servA, -1, serv, servlen);
6897 HeapFree(GetProcessHeap(), 0, hostA);
6898 HeapFree(GetProcessHeap(), 0, servA);
6899 return ret;
6902 /***********************************************************************
6903 * getservbyport (WS2_32.56)
6905 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
6907 struct WS_servent* retval = NULL;
6908 #ifdef HAVE_GETSERVBYPORT
6909 struct servent* serv;
6910 char *proto_str = NULL;
6912 if (proto && *proto)
6914 if (!(proto_str = strdup_lower(proto))) return NULL;
6916 EnterCriticalSection( &csWSgetXXXbyYYY );
6917 if( (serv = getservbyport(port, proto_str)) != NULL ) {
6918 retval = WS_dup_se(serv);
6920 else SetLastError(WSANO_DATA);
6921 LeaveCriticalSection( &csWSgetXXXbyYYY );
6922 HeapFree( GetProcessHeap(), 0, proto_str );
6923 #endif
6924 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
6925 return retval;
6929 /***********************************************************************
6930 * gethostname (WS2_32.57)
6932 int WINAPI WS_gethostname(char *name, int namelen)
6934 char buf[256];
6935 int len;
6937 TRACE("name %p, len %d\n", name, namelen);
6939 if (!name)
6941 SetLastError(WSAEFAULT);
6942 return SOCKET_ERROR;
6945 if (gethostname(buf, sizeof(buf)) != 0)
6947 SetLastError(wsaErrno());
6948 return SOCKET_ERROR;
6951 TRACE("<- '%s'\n", buf);
6952 len = strlen(buf);
6953 if (len > 15)
6954 WARN("Windows supports NetBIOS name length up to 15 bytes!\n");
6955 if (namelen <= len)
6957 SetLastError(WSAEFAULT);
6958 WARN("<- not enough space for hostname, required %d, got %d!\n", len + 1, namelen);
6959 return SOCKET_ERROR;
6961 strcpy(name, buf);
6962 return 0;
6966 /* ------------------------------------- Windows sockets extensions -- *
6968 * ------------------------------------------------------------------- */
6970 /***********************************************************************
6971 * WSAEnumNetworkEvents (WS2_32.36)
6973 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
6975 int ret;
6976 int i;
6977 int errors[FD_MAX_EVENTS];
6979 TRACE("%04lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
6981 SERVER_START_REQ( get_socket_event )
6983 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6984 req->service = TRUE;
6985 req->c_event = wine_server_obj_handle( hEvent );
6986 wine_server_set_reply( req, errors, sizeof(errors) );
6987 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
6989 SERVER_END_REQ;
6990 if (!ret)
6992 for (i = 0; i < FD_MAX_EVENTS; i++)
6993 lpEvent->iErrorCode[i] = NtStatusToWSAError(errors[i]);
6994 return 0;
6996 SetLastError(WSAEINVAL);
6997 return SOCKET_ERROR;
7000 /***********************************************************************
7001 * WSAEventSelect (WS2_32.39)
7003 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
7005 int ret;
7007 TRACE("%04lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
7009 SERVER_START_REQ( set_socket_event )
7011 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
7012 req->mask = lEvent;
7013 req->event = wine_server_obj_handle( hEvent );
7014 req->window = 0;
7015 req->msg = 0;
7016 ret = wine_server_call( req );
7018 SERVER_END_REQ;
7019 if (!ret) return 0;
7020 SetLastError(WSAEINVAL);
7021 return SOCKET_ERROR;
7024 /**********************************************************************
7025 * WSAGetOverlappedResult (WS2_32.40)
7027 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
7028 LPDWORD lpcbTransfer, BOOL fWait,
7029 LPDWORD lpdwFlags )
7031 NTSTATUS status;
7033 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
7034 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
7036 if ( lpOverlapped == NULL )
7038 ERR( "Invalid pointer\n" );
7039 SetLastError(WSA_INVALID_PARAMETER);
7040 return FALSE;
7043 status = lpOverlapped->Internal;
7044 if (status == STATUS_PENDING)
7046 if (!fWait)
7048 SetLastError( WSA_IO_INCOMPLETE );
7049 return FALSE;
7052 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
7053 INFINITE ) == WAIT_FAILED)
7054 return FALSE;
7055 status = lpOverlapped->Internal;
7058 if ( lpcbTransfer )
7059 *lpcbTransfer = lpOverlapped->InternalHigh;
7061 if ( lpdwFlags )
7062 *lpdwFlags = lpOverlapped->u.s.Offset;
7064 if (status) SetLastError( RtlNtStatusToDosError(status) );
7065 return !status;
7069 /***********************************************************************
7070 * WSAAsyncSelect (WS2_32.101)
7072 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
7074 int ret;
7076 TRACE("%04lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
7078 SERVER_START_REQ( set_socket_event )
7080 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
7081 req->mask = lEvent;
7082 req->event = 0;
7083 req->window = wine_server_user_handle( hWnd );
7084 req->msg = uMsg;
7085 ret = wine_server_call( req );
7087 SERVER_END_REQ;
7088 if (!ret) return 0;
7089 SetLastError(WSAEINVAL);
7090 return SOCKET_ERROR;
7093 /***********************************************************************
7094 * WSACreateEvent (WS2_32.31)
7097 WSAEVENT WINAPI WSACreateEvent(void)
7099 /* Create a manual-reset event, with initial state: unsignaled */
7100 TRACE("\n");
7102 return CreateEventW(NULL, TRUE, FALSE, NULL);
7105 /***********************************************************************
7106 * WSACloseEvent (WS2_32.29)
7109 BOOL WINAPI WSACloseEvent(WSAEVENT event)
7111 TRACE ("event=%p\n", event);
7113 return CloseHandle(event);
7116 /***********************************************************************
7117 * WSASocketA (WS2_32.78)
7120 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
7121 LPWSAPROTOCOL_INFOA lpProtocolInfo,
7122 GROUP g, DWORD dwFlags)
7124 INT len;
7125 WSAPROTOCOL_INFOW info;
7127 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
7128 af, type, protocol, lpProtocolInfo, g, dwFlags);
7130 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
7132 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
7133 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
7134 info.szProtocol, WSAPROTOCOL_LEN + 1);
7136 if (!len)
7138 SetLastError(WSAEINVAL);
7139 return SOCKET_ERROR;
7142 return WSASocketW(af, type, protocol, &info, g, dwFlags);
7145 /***********************************************************************
7146 * WSASocketW (WS2_32.79)
7149 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
7150 LPWSAPROTOCOL_INFOW lpProtocolInfo,
7151 GROUP g, DWORD dwFlags)
7153 SOCKET ret;
7154 DWORD err;
7155 int unixaf, unixtype, ipxptype = -1;
7158 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
7159 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
7162 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
7163 af, type, protocol, lpProtocolInfo, g, dwFlags );
7165 if (!num_startup)
7167 err = WSANOTINITIALISED;
7168 goto done;
7171 /* hack for WSADuplicateSocket */
7172 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
7173 ret = lpProtocolInfo->dwServiceFlags3;
7174 TRACE("\tgot duplicate %04lx\n", ret);
7175 return ret;
7178 if (lpProtocolInfo)
7180 if (af == FROM_PROTOCOL_INFO || !af)
7181 af = lpProtocolInfo->iAddressFamily;
7182 if (type == FROM_PROTOCOL_INFO || !type)
7183 type = lpProtocolInfo->iSocketType;
7184 if (protocol == FROM_PROTOCOL_INFO || !protocol)
7185 protocol = lpProtocolInfo->iProtocol;
7188 if (!type && (af || protocol))
7190 int autoproto = protocol;
7191 WSAPROTOCOL_INFOW infow;
7193 /* default to the first valid protocol */
7194 if (!autoproto)
7195 autoproto = valid_protocols[0];
7196 else if(IS_IPX_PROTO(autoproto))
7197 autoproto = WS_NSPROTO_IPX;
7199 if (WS_EnterSingleProtocolW(autoproto, &infow))
7201 type = infow.iSocketType;
7203 /* after win2003 it's no longer possible to pass AF_UNSPEC
7204 using the protocol info struct */
7205 if (!lpProtocolInfo && af == WS_AF_UNSPEC)
7206 af = infow.iAddressFamily;
7211 Windows has an extension to the IPX protocol that allows one to create sockets
7212 and set the IPX packet type at the same time, to do that a caller will use
7213 a protocol like NSPROTO_IPX + <PACKET TYPE>
7215 if (IS_IPX_PROTO(protocol))
7216 ipxptype = protocol - WS_NSPROTO_IPX;
7218 /* convert the socket family, type and protocol */
7219 unixaf = convert_af_w2u(af);
7220 unixtype = convert_socktype_w2u(type);
7221 protocol = convert_proto_w2u(protocol);
7222 if (unixaf == AF_UNSPEC) unixaf = -1;
7224 /* filter invalid parameters */
7225 if (protocol < 0)
7227 /* the type could not be converted */
7228 if (type && unixtype < 0)
7230 err = WSAESOCKTNOSUPPORT;
7231 goto done;
7234 err = WSAEPROTONOSUPPORT;
7235 goto done;
7237 if (unixaf < 0)
7239 /* both family and protocol can't be invalid */
7240 if (protocol <= 0)
7242 err = WSAEINVAL;
7243 goto done;
7246 /* family could not be converted and neither socket type */
7247 if (unixtype < 0 && af >= 0)
7250 err = WSAESOCKTNOSUPPORT;
7251 goto done;
7254 err = WSAEAFNOSUPPORT;
7255 goto done;
7258 SERVER_START_REQ( create_socket )
7260 req->family = unixaf;
7261 req->type = unixtype;
7262 req->protocol = protocol;
7263 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
7264 req->attributes = (dwFlags & WSA_FLAG_NO_HANDLE_INHERIT) ? 0 : OBJ_INHERIT;
7265 req->flags = dwFlags & ~WSA_FLAG_NO_HANDLE_INHERIT;
7266 set_error( wine_server_call( req ) );
7267 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
7269 SERVER_END_REQ;
7270 if (ret)
7272 TRACE("\tcreated %04lx\n", ret );
7273 if (ipxptype > 0)
7274 set_ipx_packettype(ret, ipxptype);
7276 #ifdef IPV6_V6ONLY
7277 if (unixaf == AF_INET6)
7279 int fd = get_sock_fd(ret, 0, NULL);
7280 if (fd != -1)
7282 /* IPV6_V6ONLY is set by default on Windows */
7283 int enable = 1;
7284 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)))
7285 WARN("\tsetting IPV6_V6ONLY failed - errno = %i\n", errno);
7286 release_sock_fd(ret, fd);
7289 #endif
7290 return ret;
7293 err = GetLastError();
7294 if (err == WSAEACCES) /* raw socket denied */
7296 if (type == SOCK_RAW)
7297 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
7298 else
7299 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
7301 else
7303 /* invalid combination of valid parameters, like SOCK_STREAM + IPPROTO_UDP */
7304 if (err == WSAEINVAL)
7305 err = WSAESOCKTNOSUPPORT;
7306 else if (err == WSAEOPNOTSUPP)
7307 err = WSAEPROTONOSUPPORT;
7310 done:
7311 WARN("\t\tfailed, error %d!\n", err);
7312 SetLastError(err);
7313 return INVALID_SOCKET;
7316 /***********************************************************************
7317 * WSAJoinLeaf (WS2_32.58)
7320 SOCKET WINAPI WSAJoinLeaf(
7321 SOCKET s,
7322 const struct WS_sockaddr *addr,
7323 int addrlen,
7324 LPWSABUF lpCallerData,
7325 LPWSABUF lpCalleeData,
7326 LPQOS lpSQOS,
7327 LPQOS lpGQOS,
7328 DWORD dwFlags)
7330 FIXME("stub.\n");
7331 return INVALID_SOCKET;
7334 /***********************************************************************
7335 * __WSAFDIsSet (WS2_32.151)
7337 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
7339 int i = set->fd_count, ret = 0;
7341 while (i--)
7342 if (set->fd_array[i] == s)
7344 ret = 1;
7345 break;
7348 TRACE("(socket %04lx, fd_set %p, count %i) <- %d\n", s, set, set->fd_count, ret);
7349 return ret;
7352 /***********************************************************************
7353 * WSAIsBlocking (WS2_32.114)
7355 BOOL WINAPI WSAIsBlocking(void)
7357 /* By default WinSock should set all its sockets to non-blocking mode
7358 * and poll in PeekMessage loop when processing "blocking" ones. This
7359 * function is supposed to tell if the program is in this loop. Our
7360 * blocking calls are truly blocking so we always return FALSE.
7362 * Note: It is allowed to call this function without prior WSAStartup().
7365 TRACE("\n");
7366 return FALSE;
7369 /***********************************************************************
7370 * WSACancelBlockingCall (WS2_32.113)
7372 INT WINAPI WSACancelBlockingCall(void)
7374 TRACE("\n");
7375 return 0;
7378 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
7380 FIXME("How was this called?\n");
7381 return x();
7385 /***********************************************************************
7386 * WSASetBlockingHook (WS2_32.109)
7388 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
7390 FARPROC prev = blocking_hook;
7391 blocking_hook = lpBlockFunc;
7392 TRACE("hook %p\n", lpBlockFunc);
7393 return prev;
7397 /***********************************************************************
7398 * WSAUnhookBlockingHook (WS2_32.110)
7400 INT WINAPI WSAUnhookBlockingHook(void)
7402 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
7403 return 0;
7407 /* ----------------------------------- end of API stuff */
7409 /* ----------------------------------- helper functions -
7411 * TODO: Merge WS_dup_..() stuff into one function that
7412 * would operate with a generic structure containing internal
7413 * pointers (via a template of some kind).
7416 static int list_size(char** l, int item_size)
7418 int i,j = 0;
7419 if(l)
7420 { for(i=0;l[i];i++)
7421 j += (item_size) ? item_size : strlen(l[i]) + 1;
7422 j += (i + 1) * sizeof(char*); }
7423 return j;
7426 static int list_dup(char** l_src, char** l_to, int item_size)
7428 char *p;
7429 int i;
7431 for (i = 0; l_src[i]; i++) ;
7432 p = (char *)(l_to + i + 1);
7433 for (i = 0; l_src[i]; i++)
7435 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
7436 memcpy(p, l_src[i], count);
7437 l_to[i] = p;
7438 p += count;
7440 l_to[i] = NULL;
7441 return p - (char *)l_to;
7444 /* ----- hostent */
7446 /* create a hostent entry
7448 * Creates the entry with enough memory for the name, aliases
7449 * addresses, and the address pointers. Also copies the name
7450 * and sets up all the pointers.
7452 * NOTE: The alias and address lists must be allocated with room
7453 * for the NULL item terminating the list. This is true even if
7454 * the list has no items ("aliases" and "addresses" must be
7455 * at least "1", a truly empty list is invalid).
7457 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length)
7459 struct WS_hostent *p_to;
7460 char *p;
7461 int size = (sizeof(struct WS_hostent) +
7462 strlen(name) + 1 +
7463 sizeof(char *) * aliases +
7464 aliases_size +
7465 sizeof(char *) * addresses +
7466 address_length * (addresses - 1)), i;
7468 if (!(p_to = check_buffer_he(size))) return NULL;
7469 memset(p_to, 0, size);
7471 /* Use the memory in the same way winsock does.
7472 * First set the pointer for aliases, second set the pointers for addresses.
7473 * Third fill the addresses indexes, fourth jump aliases names size.
7474 * Fifth fill the hostname.
7475 * NOTE: This method is valid for OS version's >= XP.
7477 p = (char *)(p_to + 1);
7478 p_to->h_aliases = (char **)p;
7479 p += sizeof(char *)*aliases;
7481 p_to->h_addr_list = (char **)p;
7482 p += sizeof(char *)*addresses;
7484 for (i = 0, addresses--; i < addresses; i++, p += address_length)
7485 p_to->h_addr_list[i] = p;
7487 /* NOTE: h_aliases must be filled in manually because we don't know each string
7488 * size, leave these pointers NULL (already set to NULL by memset earlier).
7490 p += aliases_size;
7492 p_to->h_name = p;
7493 strcpy(p, name);
7495 return p_to;
7498 /* duplicate hostent entry
7499 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
7500 * Ditto for protoent and servent.
7502 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
7504 int i, addresses = 0, alias_size = 0;
7505 struct WS_hostent *p_to;
7506 char *p;
7508 for( i = 0; p_he->h_aliases[i]; i++) alias_size += strlen(p_he->h_aliases[i]) + 1;
7509 while (p_he->h_addr_list[addresses]) addresses++;
7511 p_to = WS_create_he(p_he->h_name, i + 1, alias_size, addresses + 1, p_he->h_length);
7513 if (!p_to) return NULL;
7514 p_to->h_addrtype = convert_af_u2w(p_he->h_addrtype);
7515 p_to->h_length = p_he->h_length;
7517 for(i = 0, p = p_to->h_addr_list[0]; p_he->h_addr_list[i]; i++, p += p_to->h_length)
7518 memcpy(p, p_he->h_addr_list[i], p_to->h_length);
7520 /* Fill the aliases after the IP data */
7521 for(i = 0; p_he->h_aliases[i]; i++)
7523 p_to->h_aliases[i] = p;
7524 strcpy(p, p_he->h_aliases[i]);
7525 p += strlen(p) + 1;
7528 return p_to;
7531 /* ----- protoent */
7533 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
7535 char *p;
7536 struct WS_protoent *p_to;
7538 int size = (sizeof(*p_pe) +
7539 strlen(p_pe->p_name) + 1 +
7540 list_size(p_pe->p_aliases, 0));
7542 if (!(p_to = check_buffer_pe(size))) return NULL;
7543 p_to->p_proto = p_pe->p_proto;
7545 p = (char *)(p_to + 1);
7546 p_to->p_name = p;
7547 strcpy(p, p_pe->p_name);
7548 p += strlen(p) + 1;
7550 p_to->p_aliases = (char **)p;
7551 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
7552 return p_to;
7555 /* ----- servent */
7557 static struct WS_servent *WS_dup_se(const struct servent* p_se)
7559 char *p;
7560 struct WS_servent *p_to;
7562 int size = (sizeof(*p_se) +
7563 strlen(p_se->s_proto) + 1 +
7564 strlen(p_se->s_name) + 1 +
7565 list_size(p_se->s_aliases, 0));
7567 if (!(p_to = check_buffer_se(size))) return NULL;
7568 p_to->s_port = p_se->s_port;
7570 p = (char *)(p_to + 1);
7571 p_to->s_name = p;
7572 strcpy(p, p_se->s_name);
7573 p += strlen(p) + 1;
7575 p_to->s_proto = p;
7576 strcpy(p, p_se->s_proto);
7577 p += strlen(p) + 1;
7579 p_to->s_aliases = (char **)p;
7580 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
7581 return p_to;
7585 /***********************************************************************
7586 * WSARecv (WS2_32.67)
7588 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
7589 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
7590 LPWSAOVERLAPPED lpOverlapped,
7591 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
7593 return WS2_recv_base(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
7594 NULL, NULL, lpOverlapped, lpCompletionRoutine, NULL);
7597 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
7598 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
7599 struct WS_sockaddr *lpFrom,
7600 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
7601 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
7602 LPWSABUF lpControlBuffer )
7604 unsigned int i, options;
7605 int n, fd, err, overlapped, flags;
7606 struct ws2_async *wsa = NULL, localwsa;
7607 BOOL is_blocking;
7608 DWORD timeout_start = GetTickCount();
7609 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
7611 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
7612 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
7613 (lpFromlen ? *lpFromlen : -1),
7614 lpOverlapped, lpCompletionRoutine);
7616 fd = get_sock_fd( s, FILE_READ_DATA, &options );
7617 TRACE( "fd=%d, options=%x\n", fd, options );
7619 if (fd == -1) return SOCKET_ERROR;
7621 if (*lpFlags & WS_MSG_OOB)
7623 /* It's invalid to receive OOB data from an OOBINLINED socket
7624 * as OOB data is turned into normal data. */
7625 i = sizeof(n);
7626 if (!getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, (char*) &n, &i) && n)
7628 err = WSAEINVAL;
7629 goto error;
7633 overlapped = (lpOverlapped || lpCompletionRoutine) &&
7634 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
7635 if (overlapped || dwBufferCount > 1)
7637 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[dwBufferCount]))))
7639 err = WSAEFAULT;
7640 goto error;
7643 else
7644 wsa = &localwsa;
7646 wsa->hSocket = SOCKET2HANDLE(s);
7647 wsa->flags = *lpFlags;
7648 wsa->lpFlags = lpFlags;
7649 wsa->addr = lpFrom;
7650 wsa->addrlen.ptr = lpFromlen;
7651 wsa->control = lpControlBuffer;
7652 wsa->n_iovecs = dwBufferCount;
7653 wsa->first_iovec = 0;
7654 for (i = 0; i < dwBufferCount; i++)
7656 /* check buffer first to trigger write watches */
7657 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
7659 err = WSAEFAULT;
7660 goto error;
7662 wsa->iovec[i].iov_base = lpBuffers[i].buf;
7663 wsa->iovec[i].iov_len = lpBuffers[i].len;
7666 flags = convert_flags(wsa->flags);
7667 for (;;)
7669 n = WS2_recv( fd, wsa, flags );
7670 if (n == -1)
7672 /* Unix-like systems return EINVAL when attempting to read OOB data from
7673 * an empty socket buffer, convert that to a Windows expected return. */
7674 if ((flags & MSG_OOB) && errno == EINVAL)
7675 errno = EWOULDBLOCK;
7677 if (errno != EAGAIN)
7679 int loc_errno = errno;
7680 err = wsaErrno();
7681 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
7682 goto error;
7685 else if (lpNumberOfBytesRecvd) *lpNumberOfBytesRecvd = n;
7687 if (overlapped)
7689 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
7691 wsa->user_overlapped = lpOverlapped;
7692 wsa->completion_func = lpCompletionRoutine;
7693 release_sock_fd( s, fd );
7695 if (n == -1)
7697 iosb->u.Status = STATUS_PENDING;
7698 iosb->Information = 0;
7700 SERVER_START_REQ( register_async )
7702 req->type = ASYNC_TYPE_READ;
7703 req->async.handle = wine_server_obj_handle( wsa->hSocket );
7704 req->async.callback = wine_server_client_ptr( WS2_async_recv );
7705 req->async.iosb = wine_server_client_ptr( iosb );
7706 req->async.arg = wine_server_client_ptr( wsa );
7707 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
7708 req->async.cvalue = cvalue;
7709 err = wine_server_call( req );
7711 SERVER_END_REQ;
7713 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
7714 SetLastError(NtStatusToWSAError( err ));
7715 return SOCKET_ERROR;
7718 iosb->u.Status = STATUS_SUCCESS;
7719 iosb->Information = n;
7720 if (!wsa->completion_func)
7722 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
7723 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
7724 HeapFree( GetProcessHeap(), 0, wsa );
7726 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
7727 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
7728 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7729 return 0;
7732 if (n != -1) break;
7734 if ((err = _is_blocking( s, &is_blocking )))
7736 err = NtStatusToWSAError( err );
7737 goto error;
7740 if ( is_blocking )
7742 struct pollfd pfd;
7743 int poll_timeout = -1;
7744 INT64 timeout = get_rcvsnd_timeo(fd, TRUE);
7746 if (timeout)
7748 timeout -= GetTickCount() - timeout_start;
7749 if (timeout < 0) poll_timeout = 0;
7750 else poll_timeout = timeout <= INT_MAX ? timeout : INT_MAX;
7753 pfd.fd = fd;
7754 pfd.events = POLLIN;
7755 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
7757 if (!poll_timeout || !poll( &pfd, 1, poll_timeout ))
7759 err = WSAETIMEDOUT;
7760 /* a timeout is not fatal */
7761 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7762 goto error;
7765 else
7767 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7768 err = WSAEWOULDBLOCK;
7769 goto error;
7773 TRACE(" -> %i bytes\n", n);
7774 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
7775 release_sock_fd( s, fd );
7776 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7777 SetLastError(ERROR_SUCCESS);
7779 return 0;
7781 error:
7782 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
7783 release_sock_fd( s, fd );
7784 WARN(" -> ERROR %d\n", err);
7785 SetLastError( err );
7786 return SOCKET_ERROR;
7789 /***********************************************************************
7790 * WSARecvFrom (WS2_32.69)
7792 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
7793 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
7794 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
7795 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
7798 return WS2_recv_base( s, lpBuffers, dwBufferCount,
7799 lpNumberOfBytesRecvd, lpFlags,
7800 lpFrom, lpFromlen,
7801 lpOverlapped, lpCompletionRoutine, NULL );
7804 /***********************************************************************
7805 * WSCInstallProvider (WS2_32.88)
7807 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
7808 LPCWSTR lpszProviderDllPath,
7809 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
7810 DWORD dwNumberOfEntries,
7811 LPINT lpErrno )
7813 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
7814 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
7815 dwNumberOfEntries, lpErrno);
7816 *lpErrno = 0;
7817 return 0;
7821 /***********************************************************************
7822 * WSCDeinstallProvider (WS2_32.83)
7824 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
7826 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
7827 *lpErrno = 0;
7828 return 0;
7832 /***********************************************************************
7833 * WSAAccept (WS2_32.26)
7835 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
7836 LPCONDITIONPROC lpfnCondition, DWORD_PTR dwCallbackData)
7839 int ret = 0, size;
7840 WSABUF CallerId, CallerData, CalleeId, CalleeData;
7841 /* QOS SQOS, GQOS; */
7842 GROUP g;
7843 SOCKET cs;
7844 SOCKADDR src_addr, dst_addr;
7846 TRACE("socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
7847 s, addr, addrlen, lpfnCondition, dwCallbackData);
7849 cs = WS_accept(s, addr, addrlen);
7850 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
7851 if (!lpfnCondition) return cs;
7853 if (addr && addrlen)
7855 CallerId.buf = (char *)addr;
7856 CallerId.len = *addrlen;
7858 else
7860 size = sizeof(src_addr);
7861 WS_getpeername(cs, &src_addr, &size);
7862 CallerId.buf = (char *)&src_addr;
7863 CallerId.len = size;
7865 CallerData.buf = NULL;
7866 CallerData.len = 0;
7868 size = sizeof(dst_addr);
7869 WS_getsockname(cs, &dst_addr, &size);
7871 CalleeId.buf = (char *)&dst_addr;
7872 CalleeId.len = sizeof(dst_addr);
7874 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
7875 &CalleeId, &CalleeData, &g, dwCallbackData);
7877 switch (ret)
7879 case CF_ACCEPT:
7880 return cs;
7881 case CF_DEFER:
7882 SERVER_START_REQ( set_socket_deferred )
7884 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
7885 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
7886 if ( !wine_server_call_err ( req ) )
7888 SetLastError( WSATRY_AGAIN );
7889 WS_closesocket( cs );
7892 SERVER_END_REQ;
7893 return SOCKET_ERROR;
7894 case CF_REJECT:
7895 WS_closesocket(cs);
7896 SetLastError(WSAECONNREFUSED);
7897 return SOCKET_ERROR;
7898 default:
7899 FIXME("Unknown return type from Condition function\n");
7900 SetLastError(WSAENOTSOCK);
7901 return SOCKET_ERROR;
7905 /***********************************************************************
7906 * WSADuplicateSocketA (WS2_32.32)
7908 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
7910 return WS_DuplicateSocket(FALSE, s, dwProcessId, (LPWSAPROTOCOL_INFOW) lpProtocolInfo);
7913 /***********************************************************************
7914 * WSADuplicateSocketW (WS2_32.33)
7916 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
7918 return WS_DuplicateSocket(TRUE, s, dwProcessId, lpProtocolInfo);
7921 /***********************************************************************
7922 * WSAInstallServiceClassA (WS2_32.48)
7924 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
7926 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
7927 SetLastError(WSAEACCES);
7928 return SOCKET_ERROR;
7931 /***********************************************************************
7932 * WSAInstallServiceClassW (WS2_32.49)
7934 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
7936 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
7937 SetLastError(WSAEACCES);
7938 return SOCKET_ERROR;
7941 /***********************************************************************
7942 * WSARemoveServiceClass (WS2_32.70)
7944 int WINAPI WSARemoveServiceClass(LPGUID info)
7946 FIXME("Request to remove service %s\n", debugstr_guid(info));
7947 SetLastError(WSATYPE_NOT_FOUND);
7948 return SOCKET_ERROR;
7951 /***********************************************************************
7952 * inet_ntop (WS2_32.@)
7954 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
7956 #ifdef HAVE_INET_NTOP
7957 struct WS_in6_addr *in6;
7958 struct WS_in_addr *in;
7959 PCSTR pdst;
7961 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
7962 if (!buffer)
7964 SetLastError( STATUS_INVALID_PARAMETER );
7965 return NULL;
7968 switch (family)
7970 case WS_AF_INET:
7972 in = addr;
7973 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
7974 break;
7976 case WS_AF_INET6:
7978 in6 = addr;
7979 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
7980 break;
7982 default:
7983 SetLastError( WSAEAFNOSUPPORT );
7984 return NULL;
7987 if (!pdst) SetLastError( STATUS_INVALID_PARAMETER );
7988 return pdst;
7989 #else
7990 FIXME( "not supported on this platform\n" );
7991 SetLastError( WSAEAFNOSUPPORT );
7992 return NULL;
7993 #endif
7996 /***********************************************************************
7997 * inet_pton (WS2_32.@)
7999 INT WINAPI WS_inet_pton( INT family, PCSTR addr, PVOID buffer)
8001 #ifdef HAVE_INET_PTON
8002 int unixaf, ret;
8004 TRACE("family %d, addr %s, buffer (%p)\n", family, debugstr_a(addr), buffer);
8006 if (!addr || !buffer)
8008 SetLastError(WSAEFAULT);
8009 return SOCKET_ERROR;
8012 unixaf = convert_af_w2u(family);
8013 if (unixaf != AF_INET && unixaf != AF_INET6)
8015 SetLastError(WSAEAFNOSUPPORT);
8016 return SOCKET_ERROR;
8019 ret = inet_pton(unixaf, addr, buffer);
8020 if (ret == -1) SetLastError(wsaErrno());
8021 return ret;
8022 #else
8023 FIXME( "not supported on this platform\n" );
8024 SetLastError( WSAEAFNOSUPPORT );
8025 return SOCKET_ERROR;
8026 #endif
8029 /***********************************************************************
8030 * InetPtonW (WS2_32.@)
8032 INT WINAPI InetPtonW(INT family, PCWSTR addr, PVOID buffer)
8034 char *addrA;
8035 int len;
8036 INT ret;
8038 TRACE("family %d, addr %s, buffer (%p)\n", family, debugstr_w(addr), buffer);
8040 if (!addr)
8042 SetLastError(WSAEFAULT);
8043 return SOCKET_ERROR;
8046 len = WideCharToMultiByte(CP_ACP, 0, addr, -1, NULL, 0, NULL, NULL);
8047 if (!(addrA = HeapAlloc(GetProcessHeap(), 0, len)))
8049 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8050 return SOCKET_ERROR;
8052 WideCharToMultiByte(CP_ACP, 0, addr, -1, addrA, len, NULL, NULL);
8054 ret = WS_inet_pton(family, addrA, buffer);
8056 HeapFree(GetProcessHeap(), 0, addrA);
8057 return ret;
8060 /***********************************************************************
8061 * InetNtopW (WS2_32.@)
8063 PCWSTR WINAPI InetNtopW(INT family, PVOID addr, PWSTR buffer, SIZE_T len)
8065 char bufferA[WS_INET6_ADDRSTRLEN];
8066 PWSTR ret = NULL;
8068 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
8070 if (WS_inet_ntop(family, addr, bufferA, sizeof(bufferA)))
8072 if (MultiByteToWideChar(CP_ACP, 0, bufferA, -1, buffer, len))
8073 ret = buffer;
8074 else
8075 SetLastError(ERROR_INVALID_PARAMETER);
8077 return ret;
8080 /***********************************************************************
8081 * WSAStringToAddressA (WS2_32.80)
8083 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
8084 INT AddressFamily,
8085 LPWSAPROTOCOL_INFOA lpProtocolInfo,
8086 LPSOCKADDR lpAddress,
8087 LPINT lpAddressLength)
8089 INT res=0;
8090 LPSTR workBuffer=NULL,ptrPort;
8092 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
8093 lpProtocolInfo, lpAddress, lpAddressLength );
8095 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
8097 if (!AddressString)
8099 SetLastError(WSAEINVAL);
8100 return SOCKET_ERROR;
8103 if (lpProtocolInfo)
8104 FIXME("ProtocolInfo not implemented.\n");
8106 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
8107 strlen(AddressString) + 1);
8108 if (!workBuffer)
8110 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8111 return SOCKET_ERROR;
8114 strcpy(workBuffer, AddressString);
8116 switch(AddressFamily)
8118 case WS_AF_INET:
8120 struct in_addr inetaddr;
8122 /* If lpAddressLength is too small, tell caller the size we need */
8123 if (*lpAddressLength < sizeof(SOCKADDR_IN))
8125 *lpAddressLength = sizeof(SOCKADDR_IN);
8126 res = WSAEFAULT;
8127 break;
8129 *lpAddressLength = sizeof(SOCKADDR_IN);
8130 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
8132 ((LPSOCKADDR_IN)lpAddress)->sin_family = WS_AF_INET;
8134 ptrPort = strchr(workBuffer, ':');
8135 if(ptrPort)
8137 /* User may have entered an IPv6 and asked to parse as IPv4 */
8138 if(strchr(ptrPort + 1, ':'))
8140 res = WSAEINVAL;
8141 break;
8143 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
8144 *ptrPort = '\0';
8146 else
8148 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
8151 if(inet_aton(workBuffer, &inetaddr) > 0)
8153 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
8154 res = 0;
8156 else
8157 res = WSAEINVAL;
8159 break;
8162 case WS_AF_INET6:
8164 struct in6_addr inetaddr;
8165 /* If lpAddressLength is too small, tell caller the size we need */
8166 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
8168 *lpAddressLength = sizeof(SOCKADDR_IN6);
8169 res = WSAEFAULT;
8170 break;
8172 #ifdef HAVE_INET_PTON
8173 *lpAddressLength = sizeof(SOCKADDR_IN6);
8174 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
8176 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
8178 /* This one is a bit tricky. An IPv6 address contains colons, so the
8179 * check from IPv4 doesn't work like that. However, IPv6 addresses that
8180 * contain a port are written with braces like [fd12:3456:7890::1]:12345
8181 * so what we will do is to look for ']', check if the next char is a
8182 * colon, and if it is, parse the port as in IPv4. */
8184 ptrPort = strchr(workBuffer, ']');
8185 if(ptrPort && *(++ptrPort) == ':')
8187 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort+1));
8188 *ptrPort = '\0';
8190 else
8192 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
8195 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
8197 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
8198 sizeof(struct in6_addr));
8199 res = 0;
8201 else
8202 #endif /* HAVE_INET_PTON */
8203 res = WSAEINVAL;
8205 break;
8207 default:
8208 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
8209 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
8210 res = WSAEINVAL;
8213 HeapFree(GetProcessHeap(), 0, workBuffer);
8215 if (!res) return 0;
8216 SetLastError(res);
8217 return SOCKET_ERROR;
8220 /***********************************************************************
8221 * WSAStringToAddressW (WS2_32.81)
8223 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
8224 * If this should be the case, it would be required to map these digits
8225 * to Unicode digits (0-9) using FoldString first.
8227 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
8228 INT AddressFamily,
8229 LPWSAPROTOCOL_INFOW lpProtocolInfo,
8230 LPSOCKADDR lpAddress,
8231 LPINT lpAddressLength)
8233 INT sBuffer,res=0;
8234 LPSTR workBuffer=NULL;
8235 WSAPROTOCOL_INFOA infoA;
8236 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
8238 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
8239 lpAddress, lpAddressLength );
8241 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
8243 /* if ProtocolInfo is available - convert to ANSI variant */
8244 if (lpProtocolInfo)
8246 lpProtoInfoA = &infoA;
8247 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
8249 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
8250 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
8252 SetLastError(WSAEINVAL);
8253 return SOCKET_ERROR;
8257 if (AddressString)
8259 /* Translate AddressString to ANSI code page - assumes that only
8260 standard digits 0-9 are used with this API call */
8261 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
8262 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
8264 if (workBuffer)
8266 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
8267 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
8268 lpAddress,lpAddressLength);
8269 HeapFree( GetProcessHeap(), 0, workBuffer );
8270 return res;
8272 else
8273 res = WSA_NOT_ENOUGH_MEMORY;
8275 else
8276 res = WSAEINVAL;
8278 SetLastError(res);
8279 return SOCKET_ERROR;
8282 /***********************************************************************
8283 * WSAAddressToStringA (WS2_32.27)
8285 * See WSAAddressToStringW
8287 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
8288 LPWSAPROTOCOL_INFOA info, LPSTR string,
8289 LPDWORD lenstr )
8291 DWORD size;
8292 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
8293 CHAR *p;
8295 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
8297 if (!sockaddr) return SOCKET_ERROR;
8298 if (!string || !lenstr) return SOCKET_ERROR;
8300 switch(sockaddr->sa_family)
8302 case WS_AF_INET:
8304 unsigned int long_ip = ntohl(((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr);
8305 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
8306 sprintf( buffer, "%u.%u.%u.%u:%u",
8307 (long_ip >> 24) & 0xff,
8308 (long_ip >> 16) & 0xff,
8309 (long_ip >> 8) & 0xff,
8310 long_ip & 0xff,
8311 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
8313 p = strchr( buffer, ':' );
8314 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
8315 break;
8317 case WS_AF_INET6:
8319 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
8320 size_t slen;
8322 buffer[0] = 0;
8323 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
8324 if ((sockaddr6->sin6_port))
8325 strcpy(buffer, "[");
8326 slen = strlen(buffer);
8327 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, &buffer[slen], sizeof(buffer) - slen))
8329 SetLastError(WSAEINVAL);
8330 return SOCKET_ERROR;
8332 if ((sockaddr6->sin6_scope_id))
8333 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
8334 if ((sockaddr6->sin6_port))
8335 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
8336 break;
8339 default:
8340 SetLastError(WSAEINVAL);
8341 return SOCKET_ERROR;
8344 size = strlen( buffer ) + 1;
8346 if (*lenstr < size)
8348 *lenstr = size;
8349 SetLastError(WSAEFAULT);
8350 return SOCKET_ERROR;
8353 TRACE("=> %s,%u bytes\n", debugstr_a(buffer), size);
8354 *lenstr = size;
8355 strcpy( string, buffer );
8356 return 0;
8359 /***********************************************************************
8360 * WSAAddressToStringW (WS2_32.28)
8362 * Convert a sockaddr address into a readable address string.
8364 * PARAMS
8365 * sockaddr [I] Pointer to a sockaddr structure.
8366 * len [I] Size of the sockaddr structure.
8367 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
8368 * string [I/O] Pointer to a buffer to receive the address string.
8369 * lenstr [I/O] Size of the receive buffer in WCHARs.
8371 * RETURNS
8372 * Success: 0
8373 * Failure: SOCKET_ERROR
8375 * NOTES
8376 * The 'info' parameter is ignored.
8378 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
8379 LPWSAPROTOCOL_INFOW info, LPWSTR string,
8380 LPDWORD lenstr )
8382 INT ret;
8383 DWORD size;
8384 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
8385 CHAR bufAddr[54];
8387 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
8389 size = *lenstr;
8390 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
8392 if (ret) return ret;
8394 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
8396 if (*lenstr < size)
8398 *lenstr = size;
8399 SetLastError(WSAEFAULT);
8400 return SOCKET_ERROR;
8403 TRACE("=> %s,%u bytes\n", debugstr_w(buffer), size);
8404 *lenstr = size;
8405 lstrcpyW( string, buffer );
8406 return 0;
8409 /***********************************************************************
8410 * WSAEnumNameSpaceProvidersA (WS2_32.34)
8412 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
8414 FIXME( "(%p %p) Stub!\n", len, buffer );
8415 return 0;
8418 /***********************************************************************
8419 * WSAEnumNameSpaceProvidersW (WS2_32.35)
8421 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
8423 FIXME( "(%p %p) Stub!\n", len, buffer );
8424 return 0;
8427 /***********************************************************************
8428 * WSAGetQOSByName (WS2_32.41)
8430 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
8432 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
8433 return FALSE;
8436 /***********************************************************************
8437 * WSAGetServiceClassInfoA (WS2_32.42)
8439 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
8440 LPWSASERVICECLASSINFOA info )
8442 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
8443 len, info );
8444 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8445 return SOCKET_ERROR;
8448 /***********************************************************************
8449 * WSAGetServiceClassInfoW (WS2_32.43)
8451 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
8452 LPWSASERVICECLASSINFOW info )
8454 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
8455 len, info );
8456 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8457 return SOCKET_ERROR;
8460 /***********************************************************************
8461 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
8463 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
8465 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
8466 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8467 return SOCKET_ERROR;
8470 /***********************************************************************
8471 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
8473 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
8475 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
8476 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8477 return SOCKET_ERROR;
8480 /***********************************************************************
8481 * WSALookupServiceBeginA (WS2_32.59)
8483 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
8484 DWORD dwControlFlags,
8485 LPHANDLE lphLookup)
8487 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
8488 lphLookup);
8489 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8490 return SOCKET_ERROR;
8493 /***********************************************************************
8494 * WSALookupServiceBeginW (WS2_32.60)
8496 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
8497 DWORD dwControlFlags,
8498 LPHANDLE lphLookup)
8500 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
8501 lphLookup);
8502 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8503 return SOCKET_ERROR;
8506 /***********************************************************************
8507 * WSALookupServiceEnd (WS2_32.61)
8509 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
8511 FIXME("(%p) Stub!\n", lookup );
8512 return 0;
8515 /***********************************************************************
8516 * WSALookupServiceNextA (WS2_32.62)
8518 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
8520 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
8521 SetLastError(WSA_E_NO_MORE);
8522 return SOCKET_ERROR;
8525 /***********************************************************************
8526 * WSALookupServiceNextW (WS2_32.63)
8528 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
8530 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
8531 SetLastError(WSA_E_NO_MORE);
8532 return SOCKET_ERROR;
8535 /***********************************************************************
8536 * WSANtohl (WS2_32.64)
8538 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
8540 TRACE( "(%04lx 0x%08x %p)\n", s, netlong, lphostlong );
8542 if (!lphostlong) return WSAEFAULT;
8544 *lphostlong = ntohl( netlong );
8545 return 0;
8548 /***********************************************************************
8549 * WSANtohs (WS2_32.65)
8551 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
8553 TRACE( "(%04lx 0x%08x %p)\n", s, netshort, lphostshort );
8555 if (!lphostshort) return WSAEFAULT;
8557 *lphostshort = ntohs( netshort );
8558 return 0;
8561 /***********************************************************************
8562 * WSAProviderConfigChange (WS2_32.66)
8564 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
8565 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
8567 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
8568 return SOCKET_ERROR;
8571 /***********************************************************************
8572 * WSARecvDisconnect (WS2_32.68)
8574 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
8576 TRACE( "(%04lx %p)\n", s, disconnectdata );
8578 return WS_shutdown( s, SD_RECEIVE );
8581 /***********************************************************************
8582 * WSASetServiceA (WS2_32.76)
8584 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
8586 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
8587 return 0;
8590 /***********************************************************************
8591 * WSASetServiceW (WS2_32.77)
8593 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
8595 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
8596 return 0;
8599 /***********************************************************************
8600 * WSCEnableNSProvider (WS2_32.84)
8602 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
8604 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
8605 return 0;
8608 /***********************************************************************
8609 * WSCGetProviderPath (WS2_32.86)
8611 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
8613 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
8615 if (!errcode || !provider || !len) return WSAEFAULT;
8617 *errcode = WSAEINVAL;
8618 return SOCKET_ERROR;
8621 /***********************************************************************
8622 * WSCInstallNameSpace (WS2_32.87)
8624 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
8625 DWORD version, LPGUID provider )
8627 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
8628 namespace, version, debugstr_guid(provider) );
8629 return 0;
8632 /***********************************************************************
8633 * WSCUnInstallNameSpace (WS2_32.89)
8635 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
8637 FIXME("(%s) Stub!\n", debugstr_guid(lpProviderId));
8638 return NO_ERROR;
8641 /***********************************************************************
8642 * WSCWriteProviderOrder (WS2_32.91)
8644 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
8646 FIXME("(%p 0x%08x) Stub!\n", entry, number);
8647 return 0;
8650 /***********************************************************************
8651 * WSANSPIoctl (WS2_32.91)
8653 INT WINAPI WSANSPIoctl( HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer,
8654 DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer,
8655 LPDWORD lpcbBytesReturned, LPWSACOMPLETION lpCompletion )
8657 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup, dwControlCode,
8658 lpvInBuffer, cbInBuffer, lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpCompletion);
8659 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8660 return SOCKET_ERROR;
8663 /*****************************************************************************
8664 * WSAEnumProtocolsA [WS2_32.@]
8666 * see function WSAEnumProtocolsW
8668 INT WINAPI WSAEnumProtocolsA( LPINT protocols, LPWSAPROTOCOL_INFOA buffer, LPDWORD len )
8670 return WS_EnumProtocols( FALSE, protocols, (LPWSAPROTOCOL_INFOW) buffer, len);
8673 /*****************************************************************************
8674 * WSAEnumProtocolsW [WS2_32.@]
8676 * Retrieves information about specified set of active network protocols.
8678 * PARAMS
8679 * protocols [I] Pointer to null-terminated array of protocol id's. NULL
8680 * retrieves information on all available protocols.
8681 * buffer [I] Pointer to a buffer to be filled with WSAPROTOCOL_INFO
8682 * structures.
8683 * len [I/O] Pointer to a variable specifying buffer size. On output
8684 * the variable holds the number of bytes needed when the
8685 * specified size is too small.
8687 * RETURNS
8688 * Success: number of WSAPROTOCOL_INFO structures in buffer.
8689 * Failure: SOCKET_ERROR
8691 * NOTES
8692 * NT4SP5 does not return SPX if protocols == NULL
8694 * BUGS
8695 * - NT4SP5 returns in addition these list of NETBIOS protocols
8696 * (address family 17), each entry two times one for socket type 2 and 5
8698 * iProtocol szProtocol
8699 * 0x80000000 \Device\NwlnkNb
8700 * 0xfffffffa \Device\NetBT_CBENT7
8701 * 0xfffffffb \Device\Nbf_CBENT7
8702 * 0xfffffffc \Device\NetBT_NdisWan5
8703 * 0xfffffffd \Device\NetBT_El9202
8704 * 0xfffffffe \Device\Nbf_El9202
8705 * 0xffffffff \Device\Nbf_NdisWan4
8707 * - there is no check that the operating system supports the returned
8708 * protocols
8710 INT WINAPI WSAEnumProtocolsW( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
8712 return WS_EnumProtocols( TRUE, protocols, buffer, len);
8715 /*****************************************************************************
8716 * WSCEnumProtocols [WS2_32.@]
8718 * PARAMS
8719 * protocols [I] Null-terminated array of iProtocol values.
8720 * buffer [O] Buffer of WSAPROTOCOL_INFOW structures.
8721 * len [I/O] Size of buffer on input/output.
8722 * errno [O] Error code.
8724 * RETURNS
8725 * Success: number of protocols to be reported on.
8726 * Failure: SOCKET_ERROR. error is in errno.
8728 * BUGS
8729 * Doesn't supply info on layered protocols.
8732 INT WINAPI WSCEnumProtocols( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len, LPINT err )
8734 INT ret = WSAEnumProtocolsW( protocols, buffer, len );
8736 if (ret == SOCKET_ERROR) *err = WSAENOBUFS;
8738 return ret;