winemac: Fix the logic for checking if a view is already in the intended z-order.
[wine.git] / dlls / ws2_32 / socket.c
bloba2e69128302ca507c7b0fa03ac0f597185910d17
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 int he_len;
590 int se_len;
591 int pe_len;
592 char ntoa_buffer[16]; /* 4*3 digits + 3 '.' + 1 '\0' */
595 /* internal: routing description information */
596 struct route {
597 struct in_addr addr;
598 IF_INDEX interface;
599 DWORD metric;
602 static INT num_startup; /* reference counter */
603 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
605 /* function prototypes */
606 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length);
607 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
608 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
609 static struct WS_servent *WS_dup_se(const struct servent* p_se);
610 static int ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size);
612 int WSAIOCTL_GetInterfaceCount(void);
613 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
615 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus, ULONG Information );
617 #define MAP_OPTION(opt) { WS_##opt, opt }
619 static const int ws_flags_map[][2] =
621 MAP_OPTION( MSG_OOB ),
622 MAP_OPTION( MSG_PEEK ),
623 MAP_OPTION( MSG_DONTROUTE ),
624 MAP_OPTION( MSG_WAITALL ),
627 static const int ws_sock_map[][2] =
629 MAP_OPTION( SO_DEBUG ),
630 MAP_OPTION( SO_ACCEPTCONN ),
631 MAP_OPTION( SO_REUSEADDR ),
632 MAP_OPTION( SO_KEEPALIVE ),
633 MAP_OPTION( SO_DONTROUTE ),
634 MAP_OPTION( SO_BROADCAST ),
635 MAP_OPTION( SO_LINGER ),
636 MAP_OPTION( SO_OOBINLINE ),
637 MAP_OPTION( SO_SNDBUF ),
638 MAP_OPTION( SO_RCVBUF ),
639 MAP_OPTION( SO_ERROR ),
640 MAP_OPTION( SO_TYPE ),
641 #ifdef SO_RCVTIMEO
642 MAP_OPTION( SO_RCVTIMEO ),
643 #endif
644 #ifdef SO_SNDTIMEO
645 MAP_OPTION( SO_SNDTIMEO ),
646 #endif
649 static const int ws_tcp_map[][2] =
651 #ifdef TCP_NODELAY
652 MAP_OPTION( TCP_NODELAY ),
653 #endif
656 static const int ws_ip_map[][2] =
658 MAP_OPTION( IP_MULTICAST_IF ),
659 MAP_OPTION( IP_MULTICAST_TTL ),
660 MAP_OPTION( IP_MULTICAST_LOOP ),
661 MAP_OPTION( IP_ADD_MEMBERSHIP ),
662 MAP_OPTION( IP_DROP_MEMBERSHIP ),
663 MAP_OPTION( IP_OPTIONS ),
664 #ifdef IP_HDRINCL
665 MAP_OPTION( IP_HDRINCL ),
666 #endif
667 MAP_OPTION( IP_TOS ),
668 MAP_OPTION( IP_TTL ),
669 #ifdef IP_PKTINFO
670 MAP_OPTION( IP_PKTINFO ),
671 #endif
672 #ifdef IP_UNICAST_IF
673 MAP_OPTION( IP_UNICAST_IF ),
674 #endif
677 static const int ws_ipv6_map[][2] =
679 #ifdef IPV6_ADD_MEMBERSHIP
680 MAP_OPTION( IPV6_ADD_MEMBERSHIP ),
681 #endif
682 #ifdef IPV6_DROP_MEMBERSHIP
683 MAP_OPTION( IPV6_DROP_MEMBERSHIP ),
684 #endif
685 MAP_OPTION( IPV6_MULTICAST_IF ),
686 MAP_OPTION( IPV6_MULTICAST_HOPS ),
687 MAP_OPTION( IPV6_MULTICAST_LOOP ),
688 MAP_OPTION( IPV6_UNICAST_HOPS ),
689 MAP_OPTION( IPV6_V6ONLY ),
690 #ifdef IPV6_UNICAST_IF
691 MAP_OPTION( IPV6_UNICAST_IF ),
692 #endif
695 static const int ws_af_map[][2] =
697 MAP_OPTION( AF_UNSPEC ),
698 MAP_OPTION( AF_INET ),
699 MAP_OPTION( AF_INET6 ),
700 #ifdef HAS_IPX
701 MAP_OPTION( AF_IPX ),
702 #endif
703 #ifdef AF_IRDA
704 MAP_OPTION( AF_IRDA ),
705 #endif
706 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
709 static const int ws_socktype_map[][2] =
711 MAP_OPTION( SOCK_DGRAM ),
712 MAP_OPTION( SOCK_STREAM ),
713 MAP_OPTION( SOCK_RAW ),
714 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
717 static const int ws_proto_map[][2] =
719 MAP_OPTION( IPPROTO_IP ),
720 MAP_OPTION( IPPROTO_TCP ),
721 MAP_OPTION( IPPROTO_UDP ),
722 MAP_OPTION( IPPROTO_IPV6 ),
723 MAP_OPTION( IPPROTO_ICMP ),
724 MAP_OPTION( IPPROTO_IGMP ),
725 MAP_OPTION( IPPROTO_RAW ),
726 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
729 static const int ws_aiflag_map[][2] =
731 MAP_OPTION( AI_PASSIVE ),
732 MAP_OPTION( AI_CANONNAME ),
733 MAP_OPTION( AI_NUMERICHOST ),
734 #ifdef AI_NUMERICSERV
735 MAP_OPTION( AI_NUMERICSERV ),
736 #endif
737 #ifdef AI_V4MAPPED
738 MAP_OPTION( AI_V4MAPPED ),
739 #endif
740 MAP_OPTION( AI_ADDRCONFIG ),
743 static const int ws_niflag_map[][2] =
745 MAP_OPTION( NI_NOFQDN ),
746 MAP_OPTION( NI_NUMERICHOST ),
747 MAP_OPTION( NI_NAMEREQD ),
748 MAP_OPTION( NI_NUMERICSERV ),
749 MAP_OPTION( NI_DGRAM ),
752 static const int ws_eai_map[][2] =
754 MAP_OPTION( EAI_AGAIN ),
755 MAP_OPTION( EAI_BADFLAGS ),
756 MAP_OPTION( EAI_FAIL ),
757 MAP_OPTION( EAI_FAMILY ),
758 MAP_OPTION( EAI_MEMORY ),
759 /* Note: EAI_NODATA is deprecated, but still
760 * used by Windows and Linux... We map the newer
761 * EAI_NONAME to EAI_NODATA for now until Windows
762 * changes too.
764 #ifdef EAI_NODATA
765 MAP_OPTION( EAI_NODATA ),
766 #endif
767 #ifdef EAI_NONAME
768 { WS_EAI_NODATA, EAI_NONAME },
769 #endif
771 MAP_OPTION( EAI_SERVICE ),
772 MAP_OPTION( EAI_SOCKTYPE ),
773 { 0, 0 }
776 static const int ws_poll_map[][2] =
778 MAP_OPTION( POLLERR ),
779 MAP_OPTION( POLLHUP ),
780 MAP_OPTION( POLLNVAL ),
781 MAP_OPTION( POLLWRNORM ),
782 MAP_OPTION( POLLWRBAND ),
783 MAP_OPTION( POLLRDNORM ),
784 { WS_POLLRDBAND, POLLPRI }
787 static const char magic_loopback_addr[] = {127, 12, 34, 56};
789 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
790 #ifdef IP_PKTINFO
791 static inline WSACMSGHDR *fill_control_message(int level, int type, WSACMSGHDR *current, ULONG *maxsize, void *data, int len)
793 ULONG msgsize = sizeof(WSACMSGHDR) + WSA_CMSG_ALIGN(len);
794 char *ptr = (char *) current + sizeof(WSACMSGHDR);
796 /* Make sure there is at least enough room for this entry */
797 if (msgsize > *maxsize)
798 return NULL;
799 *maxsize -= msgsize;
800 /* Fill in the entry */
801 current->cmsg_len = sizeof(WSACMSGHDR) + len;
802 current->cmsg_level = level;
803 current->cmsg_type = type;
804 memcpy(ptr, data, len);
805 /* Return the pointer to where next entry should go */
806 return (WSACMSGHDR *) (ptr + WSA_CMSG_ALIGN(len));
808 #endif /* IP_PKTINFO */
810 static inline int convert_control_headers(struct msghdr *hdr, WSABUF *control)
812 #ifdef IP_PKTINFO
813 WSACMSGHDR *cmsg_win = (WSACMSGHDR *) control->buf, *ptr;
814 ULONG ctlsize = control->len;
815 struct cmsghdr *cmsg_unix;
817 ptr = cmsg_win;
818 /* Loop over all the headers, converting as appropriate */
819 for (cmsg_unix = CMSG_FIRSTHDR(hdr); cmsg_unix != NULL; cmsg_unix = CMSG_NXTHDR(hdr, cmsg_unix))
821 switch(cmsg_unix->cmsg_level)
823 case IPPROTO_IP:
824 switch(cmsg_unix->cmsg_type)
826 case IP_PKTINFO:
828 /* Convert the Unix IP_PKTINFO structure to the Windows version */
829 struct in_pktinfo *data_unix = (struct in_pktinfo *) CMSG_DATA(cmsg_unix);
830 struct WS_in_pktinfo data_win;
832 memcpy(&data_win.ipi_addr,&data_unix->ipi_addr.s_addr,4); /* 4 bytes = 32 address bits */
833 data_win.ipi_ifindex = data_unix->ipi_ifindex;
834 ptr = fill_control_message(WS_IPPROTO_IP, WS_IP_PKTINFO, ptr, &ctlsize,
835 (void*)&data_win, sizeof(data_win));
836 if (!ptr) goto error;
837 } break;
838 default:
839 FIXME("Unhandled IPPROTO_IP message header type %d\n", cmsg_unix->cmsg_type);
840 break;
842 break;
843 default:
844 FIXME("Unhandled message header level %d\n", cmsg_unix->cmsg_level);
845 break;
849 error:
850 /* Set the length of the returned control headers */
851 control->len = (ptr == NULL ? 0 : (char*)ptr - (char*)cmsg_win);
852 return (ptr != NULL);
853 #else /* IP_PKTINFO */
854 control->len = 0;
855 return 1;
856 #endif /* IP_PKTINFO */
858 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
860 /* ----------------------------------- error handling */
862 static NTSTATUS sock_get_ntstatus( int err )
864 switch ( err )
866 case EBADF: return STATUS_INVALID_HANDLE;
867 case EBUSY: return STATUS_DEVICE_BUSY;
868 case EPERM:
869 case EACCES: return STATUS_ACCESS_DENIED;
870 case EFAULT: return STATUS_NO_MEMORY;
871 case EINVAL: return STATUS_INVALID_PARAMETER;
872 case ENFILE:
873 case EMFILE: return STATUS_TOO_MANY_OPENED_FILES;
874 case EWOULDBLOCK: return STATUS_CANT_WAIT;
875 case EINPROGRESS: return STATUS_PENDING;
876 case EALREADY: return STATUS_NETWORK_BUSY;
877 case ENOTSOCK: return STATUS_OBJECT_TYPE_MISMATCH;
878 case EDESTADDRREQ: return STATUS_INVALID_PARAMETER;
879 case EMSGSIZE: return STATUS_BUFFER_OVERFLOW;
880 case EPROTONOSUPPORT:
881 case ESOCKTNOSUPPORT:
882 case EPFNOSUPPORT:
883 case EAFNOSUPPORT:
884 case EPROTOTYPE: return STATUS_NOT_SUPPORTED;
885 case ENOPROTOOPT: return STATUS_INVALID_PARAMETER;
886 case EOPNOTSUPP: return STATUS_NOT_SUPPORTED;
887 case EADDRINUSE: return STATUS_ADDRESS_ALREADY_ASSOCIATED;
888 case EADDRNOTAVAIL: return STATUS_INVALID_PARAMETER;
889 case ECONNREFUSED: return STATUS_CONNECTION_REFUSED;
890 case ESHUTDOWN: return STATUS_PIPE_DISCONNECTED;
891 case ENOTCONN: return STATUS_CONNECTION_DISCONNECTED;
892 case ETIMEDOUT: return STATUS_IO_TIMEOUT;
893 case ENETUNREACH: return STATUS_NETWORK_UNREACHABLE;
894 case ENETDOWN: return STATUS_NETWORK_BUSY;
895 case EPIPE:
896 case ECONNRESET: return STATUS_CONNECTION_RESET;
897 case ECONNABORTED: return STATUS_CONNECTION_ABORTED;
899 case 0: return STATUS_SUCCESS;
900 default:
901 WARN("Unknown errno %d!\n", err);
902 return STATUS_UNSUCCESSFUL;
906 static UINT sock_get_error( int err )
908 switch(err)
910 case EINTR: return WSAEINTR;
911 case EPERM:
912 case EACCES: return WSAEACCES;
913 case EFAULT: return WSAEFAULT;
914 case EINVAL: return WSAEINVAL;
915 case EMFILE: return WSAEMFILE;
916 case EWOULDBLOCK: return WSAEWOULDBLOCK;
917 case EINPROGRESS: return WSAEINPROGRESS;
918 case EALREADY: return WSAEALREADY;
919 case EBADF:
920 case ENOTSOCK: return WSAENOTSOCK;
921 case EDESTADDRREQ: return WSAEDESTADDRREQ;
922 case EMSGSIZE: return WSAEMSGSIZE;
923 case EPROTOTYPE: return WSAEPROTOTYPE;
924 case ENOPROTOOPT: return WSAENOPROTOOPT;
925 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
926 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
927 case EOPNOTSUPP: return WSAEOPNOTSUPP;
928 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
929 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
930 case EADDRINUSE: return WSAEADDRINUSE;
931 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
932 case ENETDOWN: return WSAENETDOWN;
933 case ENETUNREACH: return WSAENETUNREACH;
934 case ENETRESET: return WSAENETRESET;
935 case ECONNABORTED: return WSAECONNABORTED;
936 case EPIPE:
937 case ECONNRESET: return WSAECONNRESET;
938 case ENOBUFS: return WSAENOBUFS;
939 case EISCONN: return WSAEISCONN;
940 case ENOTCONN: return WSAENOTCONN;
941 case ESHUTDOWN: return WSAESHUTDOWN;
942 case ETOOMANYREFS: return WSAETOOMANYREFS;
943 case ETIMEDOUT: return WSAETIMEDOUT;
944 case ECONNREFUSED: return WSAECONNREFUSED;
945 case ELOOP: return WSAELOOP;
946 case ENAMETOOLONG: return WSAENAMETOOLONG;
947 case EHOSTDOWN: return WSAEHOSTDOWN;
948 case EHOSTUNREACH: return WSAEHOSTUNREACH;
949 case ENOTEMPTY: return WSAENOTEMPTY;
950 #ifdef EPROCLIM
951 case EPROCLIM: return WSAEPROCLIM;
952 #endif
953 #ifdef EUSERS
954 case EUSERS: return WSAEUSERS;
955 #endif
956 #ifdef EDQUOT
957 case EDQUOT: return WSAEDQUOT;
958 #endif
959 #ifdef ESTALE
960 case ESTALE: return WSAESTALE;
961 #endif
962 #ifdef EREMOTE
963 case EREMOTE: return WSAEREMOTE;
964 #endif
966 /* just in case we ever get here and there are no problems */
967 case 0: return 0;
968 default:
969 WARN("Unknown errno %d!\n", err);
970 return WSAEOPNOTSUPP;
974 static UINT wsaErrno(void)
976 int loc_errno = errno;
977 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
979 return sock_get_error( loc_errno );
982 /* most ws2 overlapped functions return an ntstatus-based error code */
983 static NTSTATUS wsaErrStatus(void)
985 int loc_errno = errno;
986 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
988 return sock_get_ntstatus(loc_errno);
991 static UINT wsaHerrno(int loc_errno)
993 WARN("h_errno %d.\n", loc_errno);
995 switch(loc_errno)
997 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
998 case TRY_AGAIN: return WSATRY_AGAIN;
999 case NO_RECOVERY: return WSANO_RECOVERY;
1000 case NO_DATA: return WSANO_DATA;
1001 case ENOBUFS: return WSAENOBUFS;
1003 case 0: return 0;
1004 default:
1005 WARN("Unknown h_errno %d!\n", loc_errno);
1006 return WSAEOPNOTSUPP;
1010 static inline DWORD NtStatusToWSAError( const DWORD status )
1012 /* We only need to cover the status codes set by server async request handling */
1013 DWORD wserr;
1014 switch ( status )
1016 case STATUS_SUCCESS: wserr = 0; break;
1017 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
1018 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
1019 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
1020 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
1021 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
1022 case STATUS_NETWORK_BUSY: wserr = WSAEALREADY; break;
1023 case STATUS_NETWORK_UNREACHABLE: wserr = WSAENETUNREACH; break;
1024 case STATUS_CONNECTION_REFUSED: wserr = WSAECONNREFUSED; break;
1025 case STATUS_CONNECTION_DISCONNECTED: wserr = WSAENOTCONN; break;
1026 case STATUS_CONNECTION_RESET: wserr = WSAECONNRESET; break;
1027 case STATUS_CONNECTION_ABORTED: wserr = WSAECONNABORTED; break;
1028 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
1029 case STATUS_ADDRESS_ALREADY_ASSOCIATED: wserr = WSAEADDRINUSE; break;
1030 case STATUS_IO_TIMEOUT:
1031 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
1032 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
1033 case STATUS_ACCESS_DENIED: wserr = WSAEACCES; break;
1034 case STATUS_TOO_MANY_OPENED_FILES: wserr = WSAEMFILE; break;
1035 case STATUS_CANT_WAIT: wserr = WSAEWOULDBLOCK; break;
1036 case STATUS_BUFFER_OVERFLOW: wserr = WSAEMSGSIZE; break;
1037 case STATUS_NOT_SUPPORTED: wserr = WSAEOPNOTSUPP; break;
1038 case STATUS_HOST_UNREACHABLE: wserr = WSAEHOSTUNREACH; break;
1040 default:
1041 wserr = RtlNtStatusToDosError( status );
1042 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
1044 return wserr;
1047 /* set last error code from NT status without mapping WSA errors */
1048 static inline unsigned int set_error( unsigned int err )
1050 if (err)
1052 err = NtStatusToWSAError( err );
1053 SetLastError( err );
1055 return err;
1058 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
1060 int fd;
1061 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
1062 return -1;
1063 return fd;
1066 static inline void release_sock_fd( SOCKET s, int fd )
1068 wine_server_release_fd( SOCKET2HANDLE(s), fd );
1071 static void _enable_event( HANDLE s, unsigned int event,
1072 unsigned int sstate, unsigned int cstate )
1074 SERVER_START_REQ( enable_socket_event )
1076 req->handle = wine_server_obj_handle( s );
1077 req->mask = event;
1078 req->sstate = sstate;
1079 req->cstate = cstate;
1080 wine_server_call( req );
1082 SERVER_END_REQ;
1085 static NTSTATUS _is_blocking(SOCKET s, BOOL *ret)
1087 NTSTATUS status;
1088 SERVER_START_REQ( get_socket_event )
1090 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1091 req->service = FALSE;
1092 req->c_event = 0;
1093 status = wine_server_call( req );
1094 *ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
1096 SERVER_END_REQ;
1097 return status;
1100 static unsigned int _get_sock_mask(SOCKET s)
1102 unsigned int ret;
1103 SERVER_START_REQ( get_socket_event )
1105 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1106 req->service = FALSE;
1107 req->c_event = 0;
1108 wine_server_call( req );
1109 ret = reply->mask;
1111 SERVER_END_REQ;
1112 return ret;
1115 static void _sync_sock_state(SOCKET s)
1117 BOOL dummy;
1118 /* do a dummy wineserver request in order to let
1119 the wineserver run through its select loop once */
1120 (void)_is_blocking(s, &dummy);
1123 static void _get_sock_errors(SOCKET s, int *events)
1125 SERVER_START_REQ( get_socket_event )
1127 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1128 req->service = FALSE;
1129 req->c_event = 0;
1130 wine_server_set_reply( req, events, sizeof(int) * FD_MAX_EVENTS );
1131 wine_server_call( req );
1133 SERVER_END_REQ;
1136 static int _get_sock_error(SOCKET s, unsigned int bit)
1138 int events[FD_MAX_EVENTS];
1139 _get_sock_errors(s, events);
1140 return events[bit];
1143 static int _get_fd_type(int fd)
1145 int sock_type = -1;
1146 socklen_t optlen = sizeof(sock_type);
1147 getsockopt(fd, SOL_SOCKET, SO_TYPE, (char*) &sock_type, &optlen);
1148 return sock_type;
1151 static struct per_thread_data *get_per_thread_data(void)
1153 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
1154 /* lazy initialization */
1155 if (!ptb)
1157 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
1158 NtCurrentTeb()->WinSockData = ptb;
1160 return ptb;
1163 static void free_per_thread_data(void)
1165 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
1167 if (!ptb) return;
1169 /* delete scratch buffers */
1170 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1171 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1172 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1173 ptb->he_buffer = NULL;
1174 ptb->se_buffer = NULL;
1175 ptb->pe_buffer = NULL;
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 && 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 #ifdef IPV6_V6ONLY
3244 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
3245 if (name->sa_family == WS_AF_INET6 &&
3246 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
3248 int enable = 1;
3249 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
3251 release_sock_fd( s, fd );
3252 SetLastError(WSAEAFNOSUPPORT);
3253 return SOCKET_ERROR;
3256 #endif
3257 if (name->sa_family == WS_AF_INET)
3259 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
3260 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
3262 /* Trying to bind to the default host interface, using
3263 * INADDR_ANY instead*/
3264 WARN("Trying to bind to magic IP address, using "
3265 "INADDR_ANY instead.\n");
3266 in4->sin_addr.s_addr = htonl(INADDR_ANY);
3268 else if (interface_bind(s, fd, &uaddr.addr))
3269 in4->sin_addr.s_addr = htonl(INADDR_ANY);
3271 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
3273 int loc_errno = errno;
3274 WARN("\tfailure - errno = %i\n", errno);
3275 errno = loc_errno;
3276 switch (errno)
3278 case EADDRNOTAVAIL:
3279 SetLastError(WSAEINVAL);
3280 break;
3281 case EADDRINUSE:
3283 int optval = 0;
3284 socklen_t optlen = sizeof(optval);
3285 /* Windows >= 2003 will return different results depending on
3286 * SO_REUSEADDR, WSAEACCES may be returned representing that
3287 * the socket hijacking protection prevented the bind */
3288 if (!getsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&optval, &optlen) && optval)
3290 SetLastError(WSAEACCES);
3291 break;
3293 /* fall through */
3295 default:
3296 SetLastError(wsaErrno());
3297 break;
3300 else
3302 res=0; /* success */
3306 release_sock_fd( s, fd );
3308 return res;
3311 /***********************************************************************
3312 * closesocket (WS2_32.3)
3314 int WINAPI WS_closesocket(SOCKET s)
3316 int res = SOCKET_ERROR, fd;
3317 if (num_startup)
3319 fd = get_sock_fd(s, FILE_READ_DATA, NULL);
3320 if (fd >= 0)
3322 release_sock_fd(s, fd);
3323 if (CloseHandle(SOCKET2HANDLE(s)))
3324 res = 0;
3326 else
3327 SetLastError(WSAENOTSOCK);
3329 else
3330 SetLastError(WSANOTINITIALISED);
3331 TRACE("(socket %04lx) -> %d\n", s, res);
3332 return res;
3335 static int do_connect(int fd, const struct WS_sockaddr* name, int namelen)
3337 union generic_unix_sockaddr uaddr;
3338 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
3340 if (!uaddrlen)
3341 return WSAEFAULT;
3343 if (name->sa_family == WS_AF_INET)
3345 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
3346 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
3348 /* Trying to connect to magic replace-loopback address,
3349 * assuming we really want to connect to localhost */
3350 TRACE("Trying to connect to magic IP address, using "
3351 "INADDR_LOOPBACK instead.\n");
3352 in4->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
3356 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
3357 return 0;
3359 return wsaErrno();
3362 /***********************************************************************
3363 * connect (WS2_32.4)
3365 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
3367 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
3369 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
3371 if (fd != -1)
3373 NTSTATUS status;
3374 BOOL is_blocking;
3375 int ret = do_connect(fd, name, namelen);
3376 if (ret == 0)
3377 goto connect_success;
3379 if (ret == WSAEINPROGRESS)
3381 /* tell wineserver that a connection is in progress */
3382 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3383 FD_CONNECT,
3384 FD_WINE_CONNECTED|FD_WINE_LISTENING);
3385 status = _is_blocking( s, &is_blocking );
3386 if (status)
3388 release_sock_fd( s, fd );
3389 set_error( status );
3390 return SOCKET_ERROR;
3392 if (is_blocking)
3394 int result;
3395 /* block here */
3396 do_block(fd, POLLIN | POLLOUT, -1);
3397 _sync_sock_state(s); /* let wineserver notice connection */
3398 /* retrieve any error codes from it */
3399 result = _get_sock_error(s, FD_CONNECT_BIT);
3400 if (result)
3401 SetLastError(NtStatusToWSAError(result));
3402 else
3404 goto connect_success;
3407 else
3409 SetLastError(WSAEWOULDBLOCK);
3412 else
3414 SetLastError(ret);
3416 release_sock_fd( s, fd );
3418 return SOCKET_ERROR;
3420 connect_success:
3421 release_sock_fd( s, fd );
3422 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3423 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
3424 FD_CONNECT|FD_WINE_LISTENING);
3425 TRACE("\tconnected %04lx\n", s);
3426 return 0;
3429 /***********************************************************************
3430 * WSAConnect (WS2_32.30)
3432 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
3433 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
3434 LPQOS lpSQOS, LPQOS lpGQOS )
3436 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
3437 FIXME("unsupported parameters!\n");
3438 return WS_connect( s, name, namelen );
3441 /***********************************************************************
3442 * ConnectEx
3444 static BOOL WINAPI WS2_ConnectEx(SOCKET s, const struct WS_sockaddr* name, int namelen,
3445 PVOID sendBuf, DWORD sendBufLen, LPDWORD sent, LPOVERLAPPED ov)
3447 int fd, ret, status;
3449 if (!ov)
3451 SetLastError( ERROR_INVALID_PARAMETER );
3452 return FALSE;
3455 fd = get_sock_fd( s, FILE_READ_DATA, NULL );
3456 if (fd == -1)
3458 SetLastError( WSAENOTSOCK );
3459 return FALSE;
3462 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
3463 s, name, debugstr_sockaddr(name), namelen, sendBuf, sendBufLen, ov);
3465 ret = is_fd_bound(fd, NULL, NULL);
3466 if (ret <= 0)
3468 SetLastError(ret == -1 ? wsaErrno() : WSAEINVAL);
3469 release_sock_fd( s, fd );
3470 return FALSE;
3473 ret = do_connect(fd, name, namelen);
3474 if (ret == 0)
3476 WSABUF wsabuf;
3478 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3479 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
3480 FD_CONNECT|FD_WINE_LISTENING);
3482 wsabuf.len = sendBufLen;
3483 wsabuf.buf = (char*) sendBuf;
3485 /* WSASend takes care of completion if need be */
3486 if (WSASend(s, &wsabuf, sendBuf ? 1 : 0, sent, 0, ov, NULL) != SOCKET_ERROR)
3487 goto connection_success;
3489 else if (ret == WSAEINPROGRESS)
3491 struct ws2_async *wsa;
3492 ULONG_PTR cvalue = (((ULONG_PTR)ov->hEvent & 1) == 0) ? (ULONG_PTR)ov : 0;
3494 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3495 FD_CONNECT,
3496 FD_WINE_CONNECTED|FD_WINE_LISTENING);
3498 /* Indirectly call WSASend */
3499 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof( struct ws2_async, iovec[1] ))))
3501 SetLastError(WSAEFAULT);
3503 else
3505 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)ov;
3506 iosb->u.Status = STATUS_PENDING;
3507 iosb->Information = 0;
3509 wsa->hSocket = SOCKET2HANDLE(s);
3510 wsa->addr = NULL;
3511 wsa->addrlen.val = 0;
3512 wsa->flags = 0;
3513 wsa->lpFlags = &wsa->flags;
3514 wsa->control = NULL;
3515 wsa->n_iovecs = sendBuf ? 1 : 0;
3516 wsa->first_iovec = 0;
3517 wsa->completion_func = NULL;
3518 wsa->iovec[0].iov_base = sendBuf;
3519 wsa->iovec[0].iov_len = sendBufLen;
3521 SERVER_START_REQ( register_async )
3523 req->type = ASYNC_TYPE_WRITE;
3524 req->async.handle = wine_server_obj_handle( wsa->hSocket );
3525 req->async.callback = wine_server_client_ptr( WS2_async_send );
3526 req->async.iosb = wine_server_client_ptr( iosb );
3527 req->async.arg = wine_server_client_ptr( wsa );
3528 req->async.event = wine_server_obj_handle( ov->hEvent );
3529 req->async.cvalue = cvalue;
3530 status = wine_server_call( req );
3532 SERVER_END_REQ;
3534 if (status != STATUS_PENDING) HeapFree(GetProcessHeap(), 0, wsa);
3536 /* If the connect already failed */
3537 if (status == STATUS_PIPE_DISCONNECTED)
3538 status = _get_sock_error(s, FD_CONNECT_BIT);
3539 SetLastError( NtStatusToWSAError(status) );
3542 else
3544 SetLastError(ret);
3547 release_sock_fd( s, fd );
3548 return FALSE;
3550 connection_success:
3551 release_sock_fd( s, fd );
3552 return TRUE;
3555 /***********************************************************************
3556 * DisconnectEx
3558 static BOOL WINAPI WS2_DisconnectEx( SOCKET s, LPOVERLAPPED ov, DWORD flags, DWORD reserved )
3560 TRACE( "socket %04lx, ov %p, flags 0x%x, reserved 0x%x\n", s, ov, flags, reserved );
3562 if (flags & TF_REUSE_SOCKET)
3563 FIXME( "Reusing socket not supported yet\n" );
3565 if (ov)
3567 ov->Internal = STATUS_PENDING;
3568 ov->InternalHigh = 0;
3571 return !WS_shutdown( s, SD_BOTH );
3574 /***********************************************************************
3575 * getpeername (WS2_32.5)
3577 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
3579 int fd;
3580 int res;
3582 TRACE("socket %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
3584 fd = get_sock_fd( s, 0, NULL );
3585 res = SOCKET_ERROR;
3587 if (fd != -1)
3589 union generic_unix_sockaddr uaddr;
3590 socklen_t uaddrlen = sizeof(uaddr);
3592 if (getpeername(fd, &uaddr.addr, &uaddrlen) == 0)
3594 if (!name || !namelen)
3595 SetLastError(WSAEFAULT);
3596 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3597 /* The buffer was too small */
3598 SetLastError(WSAEFAULT);
3599 else
3601 res = 0;
3602 TRACE("=> %s\n", debugstr_sockaddr(name));
3605 else
3606 SetLastError(wsaErrno());
3607 release_sock_fd( s, fd );
3609 return res;
3612 /* When binding to an UDP address with filter support the getsockname call on the socket
3613 * will always return 0.0.0.0 instead of the filtered interface address. This function
3614 * checks if the socket is interface-bound on UDP and return the correct address.
3615 * This is required because applications often do a bind() with port zero followed by a
3616 * getsockname() to retrieve the port and address acquired.
3618 static void interface_bind_check(int fd, struct sockaddr_in *addr)
3620 #if !defined(IP_BOUND_IF) && !defined(LINUX_BOUND_IF)
3621 return;
3622 #else
3623 int ifindex;
3624 socklen_t len;
3626 /* Check for IPv4, address 0.0.0.0 and UDP socket */
3627 if (addr->sin_family != AF_INET || addr->sin_addr.s_addr != 0)
3628 return;
3629 if (_get_fd_type(fd) != SOCK_DGRAM)
3630 return;
3632 ifindex = -1;
3633 len = sizeof(ifindex);
3634 #if defined(IP_BOUND_IF)
3635 getsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &ifindex, &len);
3636 #elif defined(LINUX_BOUND_IF)
3637 getsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex, &len);
3638 if (ifindex > 0) ifindex = ntohl(ifindex);
3639 #endif
3640 if (ifindex > 0)
3642 PIP_ADAPTER_INFO adapters, adapter;
3643 DWORD adap_size;
3645 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
3646 return;
3647 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
3648 if (adapters && GetAdaptersInfo(adapters, &adap_size) == NO_ERROR)
3650 /* Search the IPv4 adapter list for the appropriate bound interface */
3651 for (adapter = adapters; adapter != NULL; adapter = adapter->Next)
3653 in_addr_t adapter_addr;
3654 if (adapter->Index != ifindex) continue;
3656 adapter_addr = inet_addr(adapter->IpAddressList.IpAddress.String);
3657 addr->sin_addr.s_addr = adapter_addr;
3658 TRACE("reporting interface address from adapter %d\n", ifindex);
3659 break;
3662 HeapFree(GetProcessHeap(), 0, adapters);
3664 #endif
3667 /***********************************************************************
3668 * getsockname (WS2_32.6)
3670 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
3672 int fd;
3673 int res;
3675 TRACE("socket %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
3677 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
3678 if( (name == NULL) || (namelen == NULL) )
3680 SetLastError( WSAEFAULT );
3681 return SOCKET_ERROR;
3684 fd = get_sock_fd( s, 0, NULL );
3685 res = SOCKET_ERROR;
3687 if (fd != -1)
3689 union generic_unix_sockaddr uaddr;
3690 socklen_t uaddrlen;
3691 int bound = is_fd_bound(fd, &uaddr, &uaddrlen);
3693 if (bound <= 0)
3695 SetLastError(bound == -1 ? wsaErrno() : WSAEINVAL);
3697 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3699 /* The buffer was too small */
3700 SetLastError(WSAEFAULT);
3702 else
3704 interface_bind_check(fd, (struct sockaddr_in*) &uaddr);
3705 if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3707 /* The buffer was too small */
3708 SetLastError(WSAEFAULT);
3710 else
3712 res = 0;
3713 TRACE("=> %s\n", debugstr_sockaddr(name));
3716 release_sock_fd( s, fd );
3718 return res;
3721 /***********************************************************************
3722 * getsockopt (WS2_32.7)
3724 INT WINAPI WS_getsockopt(SOCKET s, INT level,
3725 INT optname, char *optval, INT *optlen)
3727 int fd;
3728 INT ret = 0;
3730 TRACE("(socket %04lx, %s, optval %s, optlen %p (%d))\n", s,
3731 debugstr_sockopt(level, optname), debugstr_optval(optval, 0),
3732 optlen, optlen ? *optlen : 0);
3734 switch(level)
3736 case WS_SOL_SOCKET:
3738 switch(optname)
3740 /* Handle common cases. The special cases are below, sorted
3741 * alphabetically */
3742 case WS_SO_BROADCAST:
3743 case WS_SO_DEBUG:
3744 case WS_SO_KEEPALIVE:
3745 case WS_SO_OOBINLINE:
3746 case WS_SO_RCVBUF:
3747 case WS_SO_REUSEADDR:
3748 case WS_SO_SNDBUF:
3749 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3750 return SOCKET_ERROR;
3751 convert_sockopt(&level, &optname);
3752 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3754 SetLastError(wsaErrno());
3755 ret = SOCKET_ERROR;
3757 release_sock_fd( s, fd );
3758 return ret;
3759 case WS_SO_ACCEPTCONN:
3760 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3761 return SOCKET_ERROR;
3762 if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, optval, (socklen_t *)optlen) != 0 )
3764 SetLastError(wsaErrno());
3765 ret = SOCKET_ERROR;
3767 else
3769 /* BSD returns != 0 while Windows return exact == 1 */
3770 if (*(int *)optval) *(int *)optval = 1;
3772 release_sock_fd( s, fd );
3773 return ret;
3774 case WS_SO_BSP_STATE:
3776 int req_size, addr_size;
3777 WSAPROTOCOL_INFOW infow;
3778 CSADDR_INFO *csinfo;
3780 ret = ws_protocol_info(s, TRUE, &infow, &addr_size);
3781 if (ret)
3783 if (infow.iAddressFamily == WS_AF_INET)
3784 addr_size = sizeof(struct sockaddr_in);
3785 else if (infow.iAddressFamily == WS_AF_INET6)
3786 addr_size = sizeof(struct sockaddr_in6);
3787 else
3789 FIXME("Family %d is unsupported for SO_BSP_STATE\n", infow.iAddressFamily);
3790 SetLastError(WSAEAFNOSUPPORT);
3791 return SOCKET_ERROR;
3794 req_size = sizeof(CSADDR_INFO) + addr_size * 2;
3795 if (*optlen < req_size)
3797 ret = 0;
3798 SetLastError(WSAEFAULT);
3800 else
3802 union generic_unix_sockaddr uaddr;
3803 socklen_t uaddrlen;
3805 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3806 return SOCKET_ERROR;
3808 csinfo = (CSADDR_INFO*) optval;
3810 /* Check if the sock is bound */
3811 if (is_fd_bound(fd, &uaddr, &uaddrlen) == 1)
3813 csinfo->LocalAddr.lpSockaddr =
3814 (LPSOCKADDR) (optval + sizeof(CSADDR_INFO));
3815 ws_sockaddr_u2ws(&uaddr.addr, csinfo->LocalAddr.lpSockaddr, &addr_size);
3816 csinfo->LocalAddr.iSockaddrLength = addr_size;
3818 else
3820 csinfo->LocalAddr.lpSockaddr = NULL;
3821 csinfo->LocalAddr.iSockaddrLength = 0;
3824 /* Check if the sock is connected */
3825 if (!getpeername(fd, &uaddr.addr, &uaddrlen) &&
3826 is_sockaddr_bound(&uaddr.addr, uaddrlen))
3828 csinfo->RemoteAddr.lpSockaddr =
3829 (LPSOCKADDR) (optval + sizeof(CSADDR_INFO) + addr_size);
3830 ws_sockaddr_u2ws(&uaddr.addr, csinfo->RemoteAddr.lpSockaddr, &addr_size);
3831 csinfo->RemoteAddr.iSockaddrLength = addr_size;
3833 else
3835 csinfo->RemoteAddr.lpSockaddr = NULL;
3836 csinfo->RemoteAddr.iSockaddrLength = 0;
3839 csinfo->iSocketType = infow.iSocketType;
3840 csinfo->iProtocol = infow.iProtocol;
3841 release_sock_fd( s, fd );
3844 return ret ? 0 : SOCKET_ERROR;
3846 case WS_SO_DONTLINGER:
3848 struct linger lingval;
3849 socklen_t len = sizeof(struct linger);
3851 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
3853 SetLastError(WSAEFAULT);
3854 return SOCKET_ERROR;
3856 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3857 return SOCKET_ERROR;
3859 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
3861 SetLastError(wsaErrno());
3862 ret = SOCKET_ERROR;
3864 else
3866 *(BOOL *)optval = !lingval.l_onoff;
3867 *optlen = sizeof(BOOL);
3870 release_sock_fd( s, fd );
3871 return ret;
3874 case WS_SO_CONNECT_TIME:
3876 static int pretendtime = 0;
3877 struct WS_sockaddr addr;
3878 int len = sizeof(addr);
3880 if (!optlen || *optlen < sizeof(DWORD) || !optval)
3882 SetLastError(WSAEFAULT);
3883 return SOCKET_ERROR;
3885 if (WS_getpeername(s, &addr, &len) == SOCKET_ERROR)
3886 *(DWORD *)optval = ~0u;
3887 else
3889 if (!pretendtime) FIXME("WS_SO_CONNECT_TIME - faking results\n");
3890 *(DWORD *)optval = pretendtime++;
3892 *optlen = sizeof(DWORD);
3893 return ret;
3895 /* As mentioned in setsockopt, Windows ignores this, so we
3896 * always return true here */
3897 case WS_SO_DONTROUTE:
3898 if (!optlen || *optlen < sizeof(BOOL) || !optval)
3900 SetLastError(WSAEFAULT);
3901 return SOCKET_ERROR;
3903 *(BOOL *)optval = TRUE;
3904 *optlen = sizeof(BOOL);
3905 return 0;
3907 case WS_SO_ERROR:
3909 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3910 return SOCKET_ERROR;
3911 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, optval, (socklen_t *)optlen) != 0 )
3913 SetLastError(wsaErrno());
3914 ret = SOCKET_ERROR;
3916 release_sock_fd( s, fd );
3918 /* The wineserver may have swallowed the error before us */
3919 if (!ret && *(int*) optval == 0)
3921 int i, events[FD_MAX_EVENTS];
3922 _get_sock_errors(s, events);
3923 for (i = 0; i < FD_MAX_EVENTS; i++)
3925 if(events[i])
3927 events[i] = NtStatusToWSAError(events[i]);
3928 TRACE("returning SO_ERROR %d from wine server\n", events[i]);
3929 *(int*) optval = events[i];
3930 break;
3934 return ret;
3937 case WS_SO_LINGER:
3939 struct linger lingval;
3940 socklen_t len = sizeof(struct linger);
3942 /* struct linger and LINGER have different sizes */
3943 if (!optlen || *optlen < sizeof(LINGER) || !optval)
3945 SetLastError(WSAEFAULT);
3946 return SOCKET_ERROR;
3948 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3949 return SOCKET_ERROR;
3951 if (_get_fd_type(fd) == SOCK_DGRAM)
3953 SetLastError(WSAENOPROTOOPT);
3954 ret = SOCKET_ERROR;
3956 else if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0)
3958 SetLastError(wsaErrno());
3959 ret = SOCKET_ERROR;
3961 else
3963 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
3964 ((LINGER *)optval)->l_linger = lingval.l_linger;
3965 *optlen = sizeof(struct linger);
3968 release_sock_fd( s, fd );
3969 return ret;
3972 case WS_SO_MAX_MSG_SIZE:
3973 if (!optlen || *optlen < sizeof(int) || !optval)
3975 SetLastError(WSAEFAULT);
3976 return SOCKET_ERROR;
3978 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
3979 *(int *)optval = 65507;
3980 *optlen = sizeof(int);
3981 return 0;
3983 /* SO_OPENTYPE does not require a valid socket handle. */
3984 case WS_SO_OPENTYPE:
3985 if (!optlen || *optlen < sizeof(int) || !optval)
3987 SetLastError(WSAEFAULT);
3988 return SOCKET_ERROR;
3990 *(int *)optval = get_per_thread_data()->opentype;
3991 *optlen = sizeof(int);
3992 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
3993 return 0;
3994 case WS_SO_PROTOCOL_INFOA:
3995 case WS_SO_PROTOCOL_INFOW:
3997 int size;
3998 WSAPROTOCOL_INFOW infow;
4000 ret = ws_protocol_info(s, optname == WS_SO_PROTOCOL_INFOW, &infow, &size);
4001 if (ret)
4003 if (!optlen || !optval || *optlen < size)
4005 if(optlen) *optlen = size;
4006 ret = 0;
4007 SetLastError(WSAEFAULT);
4009 else
4010 memcpy(optval, &infow, size);
4012 return ret ? 0 : SOCKET_ERROR;
4014 case WS_SO_RCVTIMEO:
4015 case WS_SO_SNDTIMEO:
4017 INT64 timeout;
4019 if (!optlen || *optlen < sizeof(int)|| !optval)
4021 SetLastError(WSAEFAULT);
4022 return SOCKET_ERROR;
4024 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4025 return SOCKET_ERROR;
4027 timeout = get_rcvsnd_timeo(fd, optname == WS_SO_RCVTIMEO);
4028 *(int *)optval = timeout <= UINT_MAX ? timeout : UINT_MAX;
4030 release_sock_fd( s, fd );
4031 return ret;
4033 case WS_SO_TYPE:
4035 int sock_type;
4036 if (!optlen || *optlen < sizeof(int) || !optval)
4038 SetLastError(WSAEFAULT);
4039 return SOCKET_ERROR;
4041 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4042 return SOCKET_ERROR;
4044 sock_type = _get_fd_type(fd);
4045 if (sock_type == -1)
4047 SetLastError(wsaErrno());
4048 ret = SOCKET_ERROR;
4050 else
4051 (*(int *)optval) = convert_socktype_u2w(sock_type);
4053 release_sock_fd( s, fd );
4054 return ret;
4056 default:
4057 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
4058 SetLastError(WSAENOPROTOOPT);
4059 return SOCKET_ERROR;
4060 } /* end switch(optname) */
4061 }/* end case WS_SOL_SOCKET */
4062 #ifdef HAS_IPX
4063 case WS_NSPROTO_IPX:
4065 struct WS_sockaddr_ipx addr;
4066 IPX_ADDRESS_DATA *data;
4067 int namelen;
4068 switch(optname)
4070 case WS_IPX_PTYPE:
4071 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
4072 #ifdef SOL_IPX
4073 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (socklen_t *)optlen) == -1)
4075 ret = SOCKET_ERROR;
4077 #else
4079 struct ipx val;
4080 socklen_t len=sizeof(struct ipx);
4081 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
4082 ret = SOCKET_ERROR;
4083 else
4084 *optval = (int)val.ipx_pt;
4086 #endif
4087 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
4088 release_sock_fd( s, fd );
4089 return ret;
4091 case WS_IPX_ADDRESS:
4093 * On a Win2000 system with one network card there are usually
4094 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
4095 * Using this call you can then retrieve info about this all.
4096 * In case of Linux it is a bit different. Usually you have
4097 * only "one" device active and further it is not possible to
4098 * query things like the linkspeed.
4100 FIXME("IPX_ADDRESS\n");
4101 namelen = sizeof(struct WS_sockaddr_ipx);
4102 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
4103 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
4105 data = (IPX_ADDRESS_DATA*)optval;
4106 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
4107 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
4108 data->adapternum = 0;
4109 data->wan = FALSE; /* We are not on a wan for now .. */
4110 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
4111 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
4112 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
4113 * note 1MB = 1000kB in this case */
4114 return 0;
4116 case WS_IPX_MAX_ADAPTER_NUM:
4117 FIXME("IPX_MAX_ADAPTER_NUM\n");
4118 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
4119 return 0;
4121 default:
4122 FIXME("IPX optname:%x\n", optname);
4123 return SOCKET_ERROR;
4124 }/* end switch(optname) */
4125 } /* end case WS_NSPROTO_IPX */
4126 #endif
4128 #ifdef HAS_IRDA
4129 #define MAX_IRDA_DEVICES 10
4131 case WS_SOL_IRLMP:
4132 switch(optname)
4134 case WS_IRLMP_ENUMDEVICES:
4136 char buf[sizeof(struct irda_device_list) +
4137 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
4138 int res;
4139 socklen_t len = sizeof(buf);
4141 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4142 return SOCKET_ERROR;
4143 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
4144 release_sock_fd( s, fd );
4145 if (res < 0)
4147 SetLastError(wsaErrno());
4148 return SOCKET_ERROR;
4150 else
4152 struct irda_device_list *src = (struct irda_device_list *)buf;
4153 DEVICELIST *dst = (DEVICELIST *)optval;
4154 INT needed = sizeof(DEVICELIST);
4155 unsigned int i;
4157 if (src->len > 0)
4158 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
4159 if (*optlen < needed)
4161 SetLastError(WSAEFAULT);
4162 return SOCKET_ERROR;
4164 *optlen = needed;
4165 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
4166 dst->numDevice = src->len;
4167 for (i = 0; i < src->len; i++)
4169 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
4170 src->dev[i].saddr, src->dev[i].daddr,
4171 src->dev[i].info, src->dev[i].hints[0],
4172 src->dev[i].hints[1]);
4173 memcpy( dst->Device[i].irdaDeviceID,
4174 &src->dev[i].daddr,
4175 sizeof(dst->Device[i].irdaDeviceID) ) ;
4176 memcpy( dst->Device[i].irdaDeviceName,
4177 src->dev[i].info,
4178 sizeof(dst->Device[i].irdaDeviceName) ) ;
4179 memcpy( &dst->Device[i].irdaDeviceHints1,
4180 &src->dev[i].hints[0],
4181 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
4182 memcpy( &dst->Device[i].irdaDeviceHints2,
4183 &src->dev[i].hints[1],
4184 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
4185 dst->Device[i].irdaCharSet = src->dev[i].charset;
4187 return 0;
4190 default:
4191 FIXME("IrDA optname:0x%x\n", optname);
4192 return SOCKET_ERROR;
4194 break; /* case WS_SOL_IRLMP */
4195 #undef MAX_IRDA_DEVICES
4196 #endif
4198 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
4199 case WS_IPPROTO_TCP:
4200 switch(optname)
4202 case WS_TCP_NODELAY:
4203 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4204 return SOCKET_ERROR;
4205 convert_sockopt(&level, &optname);
4206 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
4208 SetLastError(wsaErrno());
4209 ret = SOCKET_ERROR;
4211 release_sock_fd( s, fd );
4212 return ret;
4214 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
4215 return SOCKET_ERROR;
4217 case WS_IPPROTO_IP:
4218 switch(optname)
4220 case WS_IP_ADD_MEMBERSHIP:
4221 case WS_IP_DROP_MEMBERSHIP:
4222 #ifdef IP_HDRINCL
4223 case WS_IP_HDRINCL:
4224 #endif
4225 case WS_IP_MULTICAST_IF:
4226 case WS_IP_MULTICAST_LOOP:
4227 case WS_IP_MULTICAST_TTL:
4228 case WS_IP_OPTIONS:
4229 #ifdef IP_PKTINFO
4230 case WS_IP_PKTINFO:
4231 #endif
4232 case WS_IP_TOS:
4233 case WS_IP_TTL:
4234 #ifdef IP_UNICAST_IF
4235 case WS_IP_UNICAST_IF:
4236 #endif
4237 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4238 return SOCKET_ERROR;
4239 convert_sockopt(&level, &optname);
4240 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
4242 SetLastError(wsaErrno());
4243 ret = SOCKET_ERROR;
4245 release_sock_fd( s, fd );
4246 return ret;
4247 case WS_IP_DONTFRAGMENT:
4248 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
4249 *(BOOL*)optval = FALSE;
4250 return 0;
4252 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
4253 return SOCKET_ERROR;
4255 case WS_IPPROTO_IPV6:
4256 switch(optname)
4258 #ifdef IPV6_ADD_MEMBERSHIP
4259 case WS_IPV6_ADD_MEMBERSHIP:
4260 #endif
4261 #ifdef IPV6_DROP_MEMBERSHIP
4262 case WS_IPV6_DROP_MEMBERSHIP:
4263 #endif
4264 case WS_IPV6_MULTICAST_IF:
4265 case WS_IPV6_MULTICAST_HOPS:
4266 case WS_IPV6_MULTICAST_LOOP:
4267 case WS_IPV6_UNICAST_HOPS:
4268 case WS_IPV6_V6ONLY:
4269 #ifdef IPV6_UNICAST_IF
4270 case WS_IPV6_UNICAST_IF:
4271 #endif
4272 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4273 return SOCKET_ERROR;
4274 convert_sockopt(&level, &optname);
4275 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
4277 SetLastError(wsaErrno());
4278 ret = SOCKET_ERROR;
4280 release_sock_fd( s, fd );
4281 return ret;
4282 case WS_IPV6_DONTFRAG:
4283 FIXME("WS_IPV6_DONTFRAG is always false!\n");
4284 *(BOOL*)optval = FALSE;
4285 return 0;
4287 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
4288 return SOCKET_ERROR;
4290 default:
4291 WARN("Unknown level: 0x%08x\n", level);
4292 SetLastError(WSAEINVAL);
4293 return SOCKET_ERROR;
4294 } /* end switch(level) */
4297 /***********************************************************************
4298 * htonl (WS2_32.8)
4300 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
4302 return htonl(hostlong);
4306 /***********************************************************************
4307 * htons (WS2_32.9)
4309 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
4311 return htons(hostshort);
4314 /***********************************************************************
4315 * WSAHtonl (WS2_32.46)
4316 * From MSDN description of error codes, this function should also
4317 * check if WinSock has been initialized and the socket is a valid
4318 * socket. But why? This function only translates a host byte order
4319 * u_long into a network byte order u_long...
4321 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
4323 if (lpnetlong)
4325 *lpnetlong = htonl(hostlong);
4326 return 0;
4328 SetLastError(WSAEFAULT);
4329 return SOCKET_ERROR;
4332 /***********************************************************************
4333 * WSAHtons (WS2_32.47)
4334 * From MSDN description of error codes, this function should also
4335 * check if WinSock has been initialized and the socket is a valid
4336 * socket. But why? This function only translates a host byte order
4337 * u_short into a network byte order u_short...
4339 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
4342 if (lpnetshort)
4344 *lpnetshort = htons(hostshort);
4345 return 0;
4347 SetLastError(WSAEFAULT);
4348 return SOCKET_ERROR;
4352 /***********************************************************************
4353 * inet_addr (WS2_32.11)
4355 WS_u_long WINAPI WS_inet_addr(const char *cp)
4357 if (!cp) return INADDR_NONE;
4358 return inet_addr(cp);
4362 /***********************************************************************
4363 * ntohl (WS2_32.14)
4365 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
4367 return ntohl(netlong);
4371 /***********************************************************************
4372 * ntohs (WS2_32.15)
4374 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
4376 return ntohs(netshort);
4380 /***********************************************************************
4381 * inet_ntoa (WS2_32.12)
4383 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
4385 struct per_thread_data *data = get_per_thread_data();
4387 sprintf( data->ntoa_buffer, "%u.%u.%u.%u",
4388 (unsigned int)(ntohl( in.WS_s_addr ) >> 24 & 0xff),
4389 (unsigned int)(ntohl( in.WS_s_addr ) >> 16 & 0xff),
4390 (unsigned int)(ntohl( in.WS_s_addr ) >> 8 & 0xff),
4391 (unsigned int)(ntohl( in.WS_s_addr ) & 0xff) );
4393 return data->ntoa_buffer;
4396 static const char *debugstr_wsaioctl(DWORD ioctl)
4398 const char *buf_type, *family;
4400 switch(ioctl & 0x18000000)
4402 case WS_IOC_WS2:
4403 family = "IOC_WS2";
4404 break;
4405 case WS_IOC_PROTOCOL:
4406 family = "IOC_PROTOCOL";
4407 break;
4408 case WS_IOC_VENDOR:
4409 family = "IOC_VENDOR";
4410 break;
4411 default: /* WS_IOC_UNIX */
4413 BYTE size = (ioctl >> 16) & WS_IOCPARM_MASK;
4414 char x = (ioctl & 0xff00) >> 8;
4415 BYTE y = ioctl & 0xff;
4416 char args[14];
4418 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
4420 case WS_IOC_VOID:
4421 buf_type = "_IO";
4422 sprintf(args, "%d, %d", x, y);
4423 break;
4424 case WS_IOC_IN:
4425 buf_type = "_IOW";
4426 sprintf(args, "'%c', %d, %d", x, y, size);
4427 break;
4428 case WS_IOC_OUT:
4429 buf_type = "_IOR";
4430 sprintf(args, "'%c', %d, %d", x, y, size);
4431 break;
4432 default:
4433 buf_type = "?";
4434 sprintf(args, "'%c', %d, %d", x, y, size);
4435 break;
4437 return wine_dbg_sprintf("%s(%s)", buf_type, args);
4441 /* We are different from WS_IOC_UNIX. */
4442 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
4444 case WS_IOC_VOID:
4445 buf_type = "_WSAIO";
4446 break;
4447 case WS_IOC_INOUT:
4448 buf_type = "_WSAIORW";
4449 break;
4450 case WS_IOC_IN:
4451 buf_type = "_WSAIOW";
4452 break;
4453 case WS_IOC_OUT:
4454 buf_type = "_WSAIOR";
4455 break;
4456 default:
4457 buf_type = "?";
4458 break;
4461 return wine_dbg_sprintf("%s(%s, %d)", buf_type, family,
4462 (USHORT)(ioctl & 0xffff));
4465 /* do an ioctl call through the server */
4466 static DWORD server_ioctl_sock( SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size,
4467 LPVOID out_buff, DWORD out_size, LPDWORD ret_size,
4468 LPWSAOVERLAPPED overlapped,
4469 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
4471 HANDLE event = overlapped ? overlapped->hEvent : 0;
4472 HANDLE handle = SOCKET2HANDLE( s );
4473 struct ws2_async *wsa;
4474 NTSTATUS status;
4475 PIO_STATUS_BLOCK io;
4477 if (!(wsa = (struct ws2_async *)alloc_async_io( sizeof(*wsa) )))
4478 return WSA_NOT_ENOUGH_MEMORY;
4479 wsa->hSocket = handle;
4480 wsa->user_overlapped = overlapped;
4481 wsa->completion_func = completion;
4482 io = (overlapped ? (PIO_STATUS_BLOCK)overlapped : &wsa->local_iosb);
4484 status = NtDeviceIoControlFile( handle, event, ws2_async_apc, wsa, io, code,
4485 in_buff, in_size, out_buff, out_size );
4486 if (status == STATUS_NOT_SUPPORTED)
4488 FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
4489 code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
4491 else if (status == STATUS_SUCCESS)
4492 *ret_size = io->Information; /* "Information" is the size written to the output buffer */
4494 if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, wsa );
4496 return NtStatusToWSAError( status );
4499 /**********************************************************************
4500 * WSAIoctl (WS2_32.50)
4503 INT WINAPI WSAIoctl(SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size, LPVOID out_buff,
4504 DWORD out_size, LPDWORD ret_size, LPWSAOVERLAPPED overlapped,
4505 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
4507 int fd;
4508 DWORD status = 0, total = 0;
4510 TRACE("%04lx, %s, %p, %d, %p, %d, %p, %p, %p\n",
4511 s, debugstr_wsaioctl(code), in_buff, in_size, out_buff, out_size, ret_size, overlapped, completion);
4513 switch (code)
4515 case WS_FIONBIO:
4516 if (in_size != sizeof(WS_u_long) || IS_INTRESOURCE(in_buff))
4518 SetLastError(WSAEFAULT);
4519 return SOCKET_ERROR;
4521 TRACE("-> FIONBIO (%x)\n", *(WS_u_long*)in_buff);
4522 if (_get_sock_mask(s))
4524 /* AsyncSelect()'ed sockets are always nonblocking */
4525 if (!*(WS_u_long *)in_buff) status = WSAEINVAL;
4526 break;
4528 if (*(WS_u_long *)in_buff)
4529 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
4530 else
4531 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
4532 break;
4534 case WS_FIONREAD:
4536 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
4538 SetLastError(WSAEFAULT);
4539 return SOCKET_ERROR;
4541 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
4542 if (ioctl(fd, FIONREAD, out_buff ) == -1)
4543 status = wsaErrno();
4544 release_sock_fd( s, fd );
4545 break;
4548 case WS_SIOCATMARK:
4550 unsigned int oob = 0, atmark = 0;
4551 socklen_t oobsize = sizeof(int);
4552 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
4554 SetLastError(WSAEFAULT);
4555 return SOCKET_ERROR;
4557 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
4558 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
4559 if ((getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &oob, &oobsize ) == -1)
4560 || (!oob && ioctl(fd, SIOCATMARK, &atmark ) == -1))
4561 status = wsaErrno();
4562 else
4564 /* The SIOCATMARK value read from ioctl() is reversed
4565 * because BSD returns TRUE if it's in the OOB mark
4566 * while Windows returns TRUE if there are NO OOB bytes.
4568 (*(WS_u_long *) out_buff) = oob || !atmark;
4571 release_sock_fd( s, fd );
4572 break;
4575 case WS_FIOASYNC:
4576 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
4577 SetLastError(WSAEINVAL);
4578 return SOCKET_ERROR;
4580 case WS_SIO_GET_INTERFACE_LIST:
4582 INTERFACE_INFO* intArray = out_buff;
4583 DWORD size, numInt = 0, apiReturn;
4585 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
4587 if (!out_buff || !ret_size)
4589 SetLastError(WSAEFAULT);
4590 return SOCKET_ERROR;
4593 fd = get_sock_fd( s, 0, NULL );
4594 if (fd == -1) return SOCKET_ERROR;
4596 apiReturn = GetAdaptersInfo(NULL, &size);
4597 if (apiReturn == ERROR_BUFFER_OVERFLOW)
4599 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
4601 if (table)
4603 if (GetAdaptersInfo(table, &size) == NO_ERROR)
4605 PIP_ADAPTER_INFO ptr;
4607 for (ptr = table, numInt = 0; ptr; ptr = ptr->Next)
4609 unsigned int addr, mask, bcast;
4610 struct ifreq ifInfo;
4612 /* Skip interfaces without an IPv4 address. */
4613 if (ptr->IpAddressList.IpAddress.String[0] == '\0')
4614 continue;
4616 if ((numInt + 1)*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > out_size)
4618 WARN("Buffer too small = %u, out_size = %u\n", numInt + 1, out_size);
4619 status = WSAEFAULT;
4620 break;
4623 /* Socket Status Flags */
4624 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
4625 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
4627 ERR("Error obtaining status flags for socket!\n");
4628 status = WSAEINVAL;
4629 break;
4631 else
4633 /* set flags; the values of IFF_* are not the same
4634 under Linux and Windows, therefore must generate
4635 new flags */
4636 intArray->iiFlags = 0;
4637 if (ifInfo.ifr_flags & IFF_BROADCAST)
4638 intArray->iiFlags |= WS_IFF_BROADCAST;
4639 #ifdef IFF_POINTOPOINT
4640 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
4641 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
4642 #endif
4643 if (ifInfo.ifr_flags & IFF_LOOPBACK)
4644 intArray->iiFlags |= WS_IFF_LOOPBACK;
4645 if (ifInfo.ifr_flags & IFF_UP)
4646 intArray->iiFlags |= WS_IFF_UP;
4647 if (ifInfo.ifr_flags & IFF_MULTICAST)
4648 intArray->iiFlags |= WS_IFF_MULTICAST;
4651 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
4652 mask = inet_addr(ptr->IpAddressList.IpMask.String);
4653 bcast = addr | ~mask;
4654 intArray->iiAddress.AddressIn.sin_family = AF_INET;
4655 intArray->iiAddress.AddressIn.sin_port = 0;
4656 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
4657 addr;
4658 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
4659 intArray->iiNetmask.AddressIn.sin_port = 0;
4660 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
4661 mask;
4662 intArray->iiBroadcastAddress.AddressIn.sin_family =
4663 AF_INET;
4664 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
4665 intArray->iiBroadcastAddress.AddressIn.sin_addr.
4666 WS_s_addr = bcast;
4667 intArray++;
4668 numInt++;
4671 else
4673 ERR("Unable to get interface table!\n");
4674 status = WSAEINVAL;
4676 HeapFree(GetProcessHeap(),0,table);
4678 else status = WSAEINVAL;
4680 else if (apiReturn != ERROR_NO_DATA)
4682 ERR("Unable to get interface table!\n");
4683 status = WSAEINVAL;
4685 /* Calculate the size of the array being returned */
4686 total = sizeof(INTERFACE_INFO) * numInt;
4687 release_sock_fd( s, fd );
4688 break;
4691 case WS_SIO_ADDRESS_LIST_QUERY:
4693 DWORD size;
4695 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
4697 if (!ret_size)
4699 SetLastError(WSAEFAULT);
4700 return SOCKET_ERROR;
4703 if (out_size && out_size < FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[0]))
4705 *ret_size = 0;
4706 SetLastError(WSAEINVAL);
4707 return SOCKET_ERROR;
4710 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
4712 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
4713 SOCKET_ADDRESS_LIST *sa_list;
4714 SOCKADDR_IN *sockaddr;
4715 SOCKET_ADDRESS *sa;
4716 unsigned int i;
4717 DWORD num;
4719 if (!table || GetAdaptersInfo(table, &size))
4721 HeapFree(GetProcessHeap(), 0, table);
4722 status = WSAEINVAL;
4723 break;
4726 for (p = table, num = 0; p; p = p->Next)
4727 if (p->IpAddressList.IpAddress.String[0]) num++;
4729 total = FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[num]) + num * sizeof(*sockaddr);
4730 if (total > out_size || !out_buff)
4732 *ret_size = total;
4733 HeapFree(GetProcessHeap(), 0, table);
4734 status = WSAEFAULT;
4735 break;
4738 sa_list = out_buff;
4739 sa = sa_list->Address;
4740 sockaddr = (SOCKADDR_IN *)&sa[num];
4741 sa_list->iAddressCount = num;
4743 for (p = table, i = 0; p; p = p->Next)
4745 if (!p->IpAddressList.IpAddress.String[0]) continue;
4747 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
4748 sa[i].iSockaddrLength = sizeof(SOCKADDR);
4750 sockaddr[i].sin_family = AF_INET;
4751 sockaddr[i].sin_port = 0;
4752 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
4753 i++;
4756 HeapFree(GetProcessHeap(), 0, table);
4758 else
4760 WARN("unable to get IP address list\n");
4761 status = WSAEINVAL;
4763 break;
4766 case WS_SIO_FLUSH:
4767 FIXME("SIO_FLUSH: stub.\n");
4768 break;
4770 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
4772 static const GUID connectex_guid = WSAID_CONNECTEX;
4773 static const GUID disconnectex_guid = WSAID_DISCONNECTEX;
4774 static const GUID acceptex_guid = WSAID_ACCEPTEX;
4775 static const GUID getaccepexsockaddrs_guid = WSAID_GETACCEPTEXSOCKADDRS;
4776 static const GUID transmitfile_guid = WSAID_TRANSMITFILE;
4777 static const GUID transmitpackets_guid = WSAID_TRANSMITPACKETS;
4778 static const GUID wsarecvmsg_guid = WSAID_WSARECVMSG;
4779 static const GUID wsasendmsg_guid = WSAID_WSASENDMSG;
4781 if ( IsEqualGUID(&connectex_guid, in_buff) )
4783 *(LPFN_CONNECTEX *)out_buff = WS2_ConnectEx;
4784 break;
4786 else if ( IsEqualGUID(&disconnectex_guid, in_buff) )
4788 *(LPFN_DISCONNECTEX *)out_buff = WS2_DisconnectEx;
4789 break;
4791 else if ( IsEqualGUID(&acceptex_guid, in_buff) )
4793 *(LPFN_ACCEPTEX *)out_buff = WS2_AcceptEx;
4794 break;
4796 else if ( IsEqualGUID(&getaccepexsockaddrs_guid, in_buff) )
4798 *(LPFN_GETACCEPTEXSOCKADDRS *)out_buff = WS2_GetAcceptExSockaddrs;
4799 break;
4801 else if ( IsEqualGUID(&transmitfile_guid, in_buff) )
4803 *(LPFN_TRANSMITFILE *)out_buff = WS2_TransmitFile;
4804 break;
4806 else if ( IsEqualGUID(&transmitpackets_guid, in_buff) )
4808 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitPackets\n");
4810 else if ( IsEqualGUID(&wsarecvmsg_guid, in_buff) )
4812 *(LPFN_WSARECVMSG *)out_buff = WS2_WSARecvMsg;
4813 break;
4815 else if ( IsEqualGUID(&wsasendmsg_guid, in_buff) )
4817 *(LPFN_WSASENDMSG *)out_buff = WSASendMsg;
4818 break;
4820 else
4821 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff));
4823 status = WSAEOPNOTSUPP;
4824 break;
4826 case WS_SIO_KEEPALIVE_VALS:
4828 struct tcp_keepalive *k;
4829 int keepalive, keepidle, keepintvl;
4831 if (!in_buff || in_size < sizeof(struct tcp_keepalive))
4833 SetLastError(WSAEFAULT);
4834 return SOCKET_ERROR;
4837 k = in_buff;
4838 keepalive = k->onoff ? 1 : 0;
4839 keepidle = max( 1, (k->keepalivetime + 500) / 1000 );
4840 keepintvl = max( 1, (k->keepaliveinterval + 500) / 1000 );
4842 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
4844 fd = get_sock_fd(s, 0, NULL);
4845 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
4846 status = WSAEINVAL;
4847 #if defined(TCP_KEEPIDLE) || defined(TCP_KEEPINTVL)
4848 /* these values need to be set only if SO_KEEPALIVE is enabled */
4849 else if(keepalive)
4851 #ifndef TCP_KEEPIDLE
4852 FIXME("ignoring keepalive timeout\n");
4853 #else
4854 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
4855 status = WSAEINVAL;
4856 else
4857 #endif
4858 #ifdef TCP_KEEPINTVL
4859 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
4860 status = WSAEINVAL;
4861 #else
4862 FIXME("ignoring keepalive interval\n");
4863 #endif
4865 #else
4866 else
4867 FIXME("ignoring keepalive interval and timeout\n");
4868 #endif
4869 release_sock_fd(s, fd);
4870 break;
4872 case WS_SIO_ROUTING_INTERFACE_QUERY:
4874 struct WS_sockaddr *daddr = (struct WS_sockaddr *)in_buff;
4875 struct WS_sockaddr_in *daddr_in = (struct WS_sockaddr_in *)daddr;
4876 struct WS_sockaddr_in *saddr_in = out_buff;
4877 MIB_IPFORWARDROW row;
4878 PMIB_IPADDRTABLE ipAddrTable = NULL;
4879 DWORD size, i, found_index;
4881 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
4883 if (!in_buff || in_size < sizeof(struct WS_sockaddr) ||
4884 !out_buff || out_size < sizeof(struct WS_sockaddr_in) || !ret_size)
4886 SetLastError(WSAEFAULT);
4887 return SOCKET_ERROR;
4889 if (daddr->sa_family != AF_INET)
4891 FIXME("unsupported address family %d\n", daddr->sa_family);
4892 status = WSAEAFNOSUPPORT;
4893 break;
4895 if (GetBestRoute(daddr_in->sin_addr.S_un.S_addr, 0, &row) != NOERROR ||
4896 GetIpAddrTable(NULL, &size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
4898 status = WSAEFAULT;
4899 break;
4901 ipAddrTable = HeapAlloc(GetProcessHeap(), 0, size);
4902 if (GetIpAddrTable(ipAddrTable, &size, FALSE))
4904 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4905 status = WSAEFAULT;
4906 break;
4908 for (i = 0, found_index = ipAddrTable->dwNumEntries;
4909 i < ipAddrTable->dwNumEntries; i++)
4911 if (ipAddrTable->table[i].dwIndex == row.dwForwardIfIndex)
4912 found_index = i;
4914 if (found_index == ipAddrTable->dwNumEntries)
4916 ERR("no matching IP address for interface %d\n",
4917 row.dwForwardIfIndex);
4918 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4919 status = WSAEFAULT;
4920 break;
4922 saddr_in->sin_family = AF_INET;
4923 saddr_in->sin_addr.S_un.S_addr = ipAddrTable->table[found_index].dwAddr;
4924 saddr_in->sin_port = 0;
4925 total = sizeof(struct WS_sockaddr_in);
4926 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4927 break;
4929 case WS_SIO_SET_COMPATIBILITY_MODE:
4930 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
4931 status = WSAEOPNOTSUPP;
4932 break;
4933 case WS_SIO_UDP_CONNRESET:
4934 FIXME("WS_SIO_UDP_CONNRESET stub\n");
4935 break;
4936 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
4937 SetLastError(WSAEOPNOTSUPP);
4938 return SOCKET_ERROR;
4939 default:
4940 status = WSAEOPNOTSUPP;
4941 break;
4944 if (status == WSAEOPNOTSUPP)
4946 status = server_ioctl_sock(s, code, in_buff, in_size, out_buff, out_size, &total,
4947 overlapped, completion);
4948 if (status != WSAEOPNOTSUPP)
4950 if (status == 0 || status == WSA_IO_PENDING)
4951 TRACE("-> %s request\n", debugstr_wsaioctl(code));
4952 else
4953 ERR("-> %s request failed with status 0x%x\n", debugstr_wsaioctl(code), status);
4955 /* overlapped and completion operations will be handled by the server */
4956 completion = NULL;
4957 overlapped = NULL;
4959 else
4960 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code));
4963 if (completion)
4965 FIXME( "completion routine %p not supported\n", completion );
4967 else if (overlapped)
4969 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
4970 overlapped->Internal = status;
4971 overlapped->InternalHigh = total;
4972 if (overlapped->hEvent) NtSetEvent( overlapped->hEvent, NULL );
4973 if (cvalue) WS_AddCompletion( HANDLE2SOCKET(s), cvalue, status, total );
4976 if (!status)
4978 if (ret_size) *ret_size = total;
4979 return 0;
4981 SetLastError( status );
4982 return SOCKET_ERROR;
4986 /***********************************************************************
4987 * ioctlsocket (WS2_32.10)
4989 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
4991 DWORD ret_size;
4992 return WSAIoctl( s, cmd, argp, sizeof(WS_u_long), argp, sizeof(WS_u_long), &ret_size, NULL, NULL );
4995 /***********************************************************************
4996 * listen (WS2_32.13)
4998 int WINAPI WS_listen(SOCKET s, int backlog)
5000 int fd = get_sock_fd( s, FILE_READ_DATA, NULL ), ret = SOCKET_ERROR;
5002 TRACE("socket %04lx, backlog %d\n", s, backlog);
5003 if (fd != -1)
5005 int bound = is_fd_bound(fd, NULL, NULL);
5007 if (bound <= 0)
5009 SetLastError(bound == -1 ? wsaErrno() : WSAEINVAL);
5011 else if (listen(fd, backlog) == 0)
5013 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
5014 FD_WINE_LISTENING,
5015 FD_CONNECT|FD_WINE_CONNECTED);
5016 ret = 0;
5018 else
5019 SetLastError(wsaErrno());
5020 release_sock_fd( s, fd );
5022 else
5023 SetLastError(WSAENOTSOCK);
5024 return ret;
5027 /***********************************************************************
5028 * recv (WS2_32.16)
5030 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
5032 DWORD n, dwFlags = flags;
5033 WSABUF wsabuf;
5035 wsabuf.len = len;
5036 wsabuf.buf = buf;
5038 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
5039 return SOCKET_ERROR;
5040 else
5041 return n;
5044 /***********************************************************************
5045 * recvfrom (WS2_32.17)
5047 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
5048 struct WS_sockaddr *from, int *fromlen)
5050 DWORD n, dwFlags = flags;
5051 WSABUF wsabuf;
5053 wsabuf.len = len;
5054 wsabuf.buf = buf;
5056 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL, NULL) == SOCKET_ERROR )
5057 return SOCKET_ERROR;
5058 else
5059 return n;
5062 /* allocate a poll array for the corresponding fd sets */
5063 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
5064 const WS_fd_set *exceptfds, int *count_ptr )
5066 unsigned int i, j = 0, count = 0;
5067 struct pollfd *fds;
5069 if (readfds) count += readfds->fd_count;
5070 if (writefds) count += writefds->fd_count;
5071 if (exceptfds) count += exceptfds->fd_count;
5072 *count_ptr = count;
5073 if (!count)
5075 SetLastError(WSAEINVAL);
5076 return NULL;
5078 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0]))))
5080 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
5081 return NULL;
5083 if (readfds)
5084 for (i = 0; i < readfds->fd_count; i++, j++)
5086 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
5087 if (fds[j].fd == -1) goto failed;
5088 fds[j].revents = 0;
5089 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1)
5091 fds[j].events = POLLIN;
5093 else
5095 release_sock_fd( readfds->fd_array[i], fds[j].fd );
5096 fds[j].fd = -1;
5097 fds[j].events = 0;
5100 if (writefds)
5101 for (i = 0; i < writefds->fd_count; i++, j++)
5103 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
5104 if (fds[j].fd == -1) goto failed;
5105 fds[j].revents = 0;
5106 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1 ||
5107 _get_fd_type(fds[j].fd) == SOCK_DGRAM)
5109 fds[j].events = POLLOUT;
5111 else
5113 release_sock_fd( writefds->fd_array[i], fds[j].fd );
5114 fds[j].fd = -1;
5115 fds[j].events = 0;
5118 if (exceptfds)
5119 for (i = 0; i < exceptfds->fd_count; i++, j++)
5121 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
5122 if (fds[j].fd == -1) goto failed;
5123 fds[j].revents = 0;
5124 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1)
5126 int oob_inlined = 0;
5127 socklen_t olen = sizeof(oob_inlined);
5129 fds[j].events = POLLHUP;
5131 /* Check if we need to test for urgent data or not */
5132 getsockopt(fds[j].fd, SOL_SOCKET, SO_OOBINLINE, (char*) &oob_inlined, &olen);
5133 if (!oob_inlined)
5134 fds[j].events |= POLLPRI;
5136 else
5138 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
5139 fds[j].fd = -1;
5140 fds[j].events = 0;
5143 return fds;
5145 failed:
5146 count = j;
5147 j = 0;
5148 if (readfds)
5149 for (i = 0; i < readfds->fd_count && j < count; i++, j++)
5150 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
5151 if (writefds)
5152 for (i = 0; i < writefds->fd_count && j < count; i++, j++)
5153 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
5154 if (exceptfds)
5155 for (i = 0; i < exceptfds->fd_count && j < count; i++, j++)
5156 if (fds[j].fd != -1) release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
5157 HeapFree( GetProcessHeap(), 0, fds );
5158 return NULL;
5161 /* release the file descriptor obtained in fd_sets_to_poll */
5162 /* must be called with the original fd_set arrays, before calling get_poll_results */
5163 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
5164 const WS_fd_set *exceptfds, struct pollfd *fds )
5166 unsigned int i, j = 0;
5168 if (readfds)
5170 for (i = 0; i < readfds->fd_count; i++, j++)
5171 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
5173 if (writefds)
5175 for (i = 0; i < writefds->fd_count; i++, j++)
5176 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
5178 if (exceptfds)
5180 for (i = 0; i < exceptfds->fd_count; i++, j++)
5182 if (fds[j].fd == -1) continue;
5183 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
5184 if (fds[j].revents & POLLHUP)
5186 int fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
5187 if (fd != -1)
5188 release_sock_fd( exceptfds->fd_array[i], fd );
5189 else
5190 fds[j].revents = 0;
5196 static int do_poll(struct pollfd *pollfds, int count, int timeout)
5198 struct timeval tv1, tv2;
5199 int ret, torig = timeout;
5201 if (timeout > 0) gettimeofday( &tv1, 0 );
5203 while ((ret = poll( pollfds, count, timeout )) < 0)
5205 if (errno != EINTR) break;
5206 if (timeout < 0) continue;
5207 if (timeout == 0) return 0;
5209 gettimeofday( &tv2, 0 );
5211 tv2.tv_sec -= tv1.tv_sec;
5212 tv2.tv_usec -= tv1.tv_usec;
5213 if (tv2.tv_usec < 0)
5215 tv2.tv_usec += 1000000;
5216 tv2.tv_sec -= 1;
5219 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
5220 if (timeout <= 0) return 0;
5222 return ret;
5225 /* map the poll results back into the Windows fd sets */
5226 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
5227 const struct pollfd *fds )
5229 const struct pollfd *poll_writefds = fds + (readfds ? readfds->fd_count : 0);
5230 const struct pollfd *poll_exceptfds = poll_writefds + (writefds ? writefds->fd_count : 0);
5231 unsigned int i, k, total = 0;
5233 if (readfds)
5235 for (i = k = 0; i < readfds->fd_count; i++)
5237 if (fds[i].revents ||
5238 (readfds == writefds && (poll_writefds[i].revents & POLLOUT) && !(poll_writefds[i].revents & POLLHUP)) ||
5239 (readfds == exceptfds && poll_exceptfds[i].revents))
5240 readfds->fd_array[k++] = readfds->fd_array[i];
5242 readfds->fd_count = k;
5243 total += k;
5245 if (writefds && writefds != readfds)
5247 for (i = k = 0; i < writefds->fd_count; i++)
5249 if (((poll_writefds[i].revents & POLLOUT) && !(poll_writefds[i].revents & POLLHUP)) ||
5250 (writefds == exceptfds && poll_exceptfds[i].revents))
5251 writefds->fd_array[k++] = writefds->fd_array[i];
5253 writefds->fd_count = k;
5254 total += k;
5256 if (exceptfds && exceptfds != readfds && exceptfds != writefds)
5258 for (i = k = 0; i < exceptfds->fd_count; i++)
5259 if (poll_exceptfds[i].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
5260 exceptfds->fd_count = k;
5261 total += k;
5263 return total;
5266 /***********************************************************************
5267 * select (WS2_32.18)
5269 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
5270 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
5271 const struct WS_timeval* ws_timeout)
5273 struct pollfd *pollfds;
5274 int count, ret, timeout = -1;
5276 TRACE("read %p, write %p, excp %p timeout %p\n",
5277 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
5279 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )))
5280 return SOCKET_ERROR;
5282 if (ws_timeout)
5283 timeout = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
5285 ret = do_poll(pollfds, count, timeout);
5286 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
5288 if (ret == -1) SetLastError(wsaErrno());
5289 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
5290 HeapFree( GetProcessHeap(), 0, pollfds );
5291 return ret;
5294 /***********************************************************************
5295 * WSAPoll
5297 int WINAPI WSAPoll(WSAPOLLFD *wfds, ULONG count, int timeout)
5299 int i, ret;
5300 struct pollfd *ufds;
5302 if (!count)
5304 SetLastError(WSAEINVAL);
5305 return SOCKET_ERROR;
5307 if (!wfds)
5309 SetLastError(WSAEFAULT);
5310 return SOCKET_ERROR;
5313 if (!(ufds = HeapAlloc(GetProcessHeap(), 0, count * sizeof(ufds[0]))))
5315 SetLastError(WSAENOBUFS);
5316 return SOCKET_ERROR;
5319 for (i = 0; i < count; i++)
5321 ufds[i].fd = get_sock_fd(wfds[i].fd, 0, NULL);
5322 ufds[i].events = convert_poll_w2u(wfds[i].events);
5323 ufds[i].revents = 0;
5326 ret = do_poll(ufds, count, timeout);
5328 for (i = 0; i < count; i++)
5330 if (ufds[i].fd != -1)
5332 release_sock_fd(wfds[i].fd, ufds[i].fd);
5333 wfds[i].revents = convert_poll_u2w(ufds[i].revents);
5335 else
5336 wfds[i].revents = WS_POLLNVAL;
5339 HeapFree(GetProcessHeap(), 0, ufds);
5340 return ret;
5343 /* helper to send completion messages for client-only i/o operation case */
5344 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
5345 ULONG Information )
5347 SERVER_START_REQ( add_fd_completion )
5349 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
5350 req->cvalue = CompletionValue;
5351 req->status = CompletionStatus;
5352 req->information = Information;
5353 wine_server_call( req );
5355 SERVER_END_REQ;
5359 /***********************************************************************
5360 * send (WS2_32.19)
5362 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
5364 DWORD n;
5365 WSABUF wsabuf;
5367 wsabuf.len = len;
5368 wsabuf.buf = (char*) buf;
5370 if ( WS2_sendto( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
5371 return SOCKET_ERROR;
5372 else
5373 return n;
5376 /***********************************************************************
5377 * WSASend (WS2_32.72)
5379 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5380 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
5381 LPWSAOVERLAPPED lpOverlapped,
5382 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5384 return WS2_sendto( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
5385 NULL, 0, lpOverlapped, lpCompletionRoutine );
5388 /***********************************************************************
5389 * WSASendDisconnect (WS2_32.73)
5391 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
5393 return WS_shutdown( s, SD_SEND );
5397 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5398 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
5399 const struct WS_sockaddr *to, int tolen,
5400 LPWSAOVERLAPPED lpOverlapped,
5401 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5403 unsigned int i, options;
5404 int n, fd, err, overlapped, flags;
5405 struct ws2_async *wsa = NULL, localwsa;
5406 int totalLength = 0;
5407 DWORD bytes_sent;
5408 BOOL is_blocking;
5410 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
5411 s, lpBuffers, dwBufferCount, dwFlags,
5412 to, tolen, lpOverlapped, lpCompletionRoutine);
5414 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
5415 TRACE( "fd=%d, options=%x\n", fd, options );
5417 if ( fd == -1 ) return SOCKET_ERROR;
5419 if (!lpOverlapped && !lpNumberOfBytesSent)
5421 err = WSAEFAULT;
5422 goto error;
5425 overlapped = (lpOverlapped || lpCompletionRoutine) &&
5426 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
5427 if (overlapped || dwBufferCount > 1)
5429 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[dwBufferCount]))))
5431 err = WSAEFAULT;
5432 goto error;
5435 else
5436 wsa = &localwsa;
5438 wsa->hSocket = SOCKET2HANDLE(s);
5439 wsa->addr = (struct WS_sockaddr *)to;
5440 wsa->addrlen.val = tolen;
5441 wsa->flags = dwFlags;
5442 wsa->lpFlags = &wsa->flags;
5443 wsa->control = NULL;
5444 wsa->n_iovecs = dwBufferCount;
5445 wsa->first_iovec = 0;
5446 for ( i = 0; i < dwBufferCount; i++ )
5448 wsa->iovec[i].iov_base = lpBuffers[i].buf;
5449 wsa->iovec[i].iov_len = lpBuffers[i].len;
5450 totalLength += lpBuffers[i].len;
5453 flags = convert_flags(dwFlags);
5454 n = WS2_send( fd, wsa, flags );
5455 if (n == -1 && errno != EAGAIN)
5457 err = wsaErrno();
5458 goto error;
5461 if (overlapped)
5463 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
5464 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
5466 wsa->user_overlapped = lpOverlapped;
5467 wsa->completion_func = lpCompletionRoutine;
5468 release_sock_fd( s, fd );
5470 if (n == -1 || n < totalLength)
5472 iosb->u.Status = STATUS_PENDING;
5473 iosb->Information = n == -1 ? 0 : n;
5475 SERVER_START_REQ( register_async )
5477 req->type = ASYNC_TYPE_WRITE;
5478 req->async.handle = wine_server_obj_handle( wsa->hSocket );
5479 req->async.callback = wine_server_client_ptr( WS2_async_send );
5480 req->async.iosb = wine_server_client_ptr( iosb );
5481 req->async.arg = wine_server_client_ptr( wsa );
5482 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
5483 req->async.cvalue = cvalue;
5484 err = wine_server_call( req );
5486 SERVER_END_REQ;
5488 /* Enable the event only after starting the async. The server will deliver it as soon as
5489 the async is done. */
5490 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
5492 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
5493 SetLastError(NtStatusToWSAError( err ));
5494 return SOCKET_ERROR;
5497 iosb->u.Status = STATUS_SUCCESS;
5498 iosb->Information = n;
5499 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = n;
5500 if (!wsa->completion_func)
5502 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
5503 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
5504 HeapFree( GetProcessHeap(), 0, wsa );
5506 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
5507 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
5508 SetLastError(ERROR_SUCCESS);
5509 return 0;
5512 if ((err = _is_blocking( s, &is_blocking )))
5514 err = NtStatusToWSAError( err );
5515 goto error;
5518 if ( is_blocking )
5520 /* On a blocking non-overlapped stream socket,
5521 * sending blocks until the entire buffer is sent. */
5522 DWORD timeout_start = GetTickCount();
5524 bytes_sent = n == -1 ? 0 : n;
5526 while (wsa->first_iovec < wsa->n_iovecs)
5528 struct pollfd pfd;
5529 int poll_timeout = -1;
5530 INT64 timeout = get_rcvsnd_timeo(fd, FALSE);
5532 if (timeout)
5534 timeout -= GetTickCount() - timeout_start;
5535 if (timeout < 0) poll_timeout = 0;
5536 else poll_timeout = timeout <= INT_MAX ? timeout : INT_MAX;
5539 pfd.fd = fd;
5540 pfd.events = POLLOUT;
5542 if (!poll_timeout || !poll( &pfd, 1, poll_timeout ))
5544 err = WSAETIMEDOUT;
5545 goto error; /* msdn says a timeout in send is fatal */
5548 n = WS2_send( fd, wsa, flags );
5549 if (n == -1 && errno != EAGAIN)
5551 err = wsaErrno();
5552 goto error;
5555 if (n >= 0)
5556 bytes_sent += n;
5559 else /* non-blocking */
5561 if (n < totalLength)
5562 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
5563 if (n == -1)
5565 err = WSAEWOULDBLOCK;
5566 goto error;
5568 bytes_sent = n;
5571 TRACE(" -> %i bytes\n", bytes_sent);
5573 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = bytes_sent;
5574 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
5575 release_sock_fd( s, fd );
5576 SetLastError(ERROR_SUCCESS);
5577 return 0;
5579 error:
5580 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
5581 release_sock_fd( s, fd );
5582 WARN(" -> ERROR %d\n", err);
5583 SetLastError(err);
5584 return SOCKET_ERROR;
5587 /***********************************************************************
5588 * WSASendTo (WS2_32.74)
5590 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5591 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
5592 const struct WS_sockaddr *to, int tolen,
5593 LPWSAOVERLAPPED lpOverlapped,
5594 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5596 return WS2_sendto( s, lpBuffers, dwBufferCount,
5597 lpNumberOfBytesSent, dwFlags,
5598 to, tolen,
5599 lpOverlapped, lpCompletionRoutine );
5602 /***********************************************************************
5603 * sendto (WS2_32.20)
5605 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
5606 const struct WS_sockaddr *to, int tolen)
5608 DWORD n;
5609 WSABUF wsabuf;
5611 wsabuf.len = len;
5612 wsabuf.buf = (char*) buf;
5614 if ( WS2_sendto(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
5615 return SOCKET_ERROR;
5616 else
5617 return n;
5620 /***********************************************************************
5621 * setsockopt (WS2_32.21)
5623 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
5624 const char *optval, int optlen)
5626 int fd;
5627 int woptval;
5628 struct linger linger;
5629 struct timeval tval;
5631 TRACE("(socket %04lx, %s, optval %s, optlen %d)\n", s,
5632 debugstr_sockopt(level, optname), debugstr_optval(optval, optlen),
5633 optlen);
5635 /* some broken apps pass the value directly instead of a pointer to it */
5636 if(optlen && IS_INTRESOURCE(optval))
5638 SetLastError(WSAEFAULT);
5639 return SOCKET_ERROR;
5642 switch(level)
5644 case WS_SOL_SOCKET:
5645 switch(optname)
5647 /* Some options need some conversion before they can be sent to
5648 * setsockopt. The conversions are done here, then they will fall through
5649 * to the general case. Special options that are not passed to
5650 * setsockopt follow below that.*/
5652 case WS_SO_DONTLINGER:
5653 if (!optval)
5655 SetLastError(WSAEFAULT);
5656 return SOCKET_ERROR;
5658 linger.l_onoff = *(const int*)optval == 0;
5659 linger.l_linger = 0;
5660 level = SOL_SOCKET;
5661 optname = SO_LINGER;
5662 optval = (char*)&linger;
5663 optlen = sizeof(struct linger);
5664 break;
5666 case WS_SO_LINGER:
5667 if (!optval)
5669 SetLastError(WSAEFAULT);
5670 return SOCKET_ERROR;
5672 linger.l_onoff = ((LINGER*)optval)->l_onoff;
5673 linger.l_linger = ((LINGER*)optval)->l_linger;
5674 level = SOL_SOCKET;
5675 optname = SO_LINGER;
5676 optval = (char*)&linger;
5677 optlen = sizeof(struct linger);
5678 break;
5680 case WS_SO_RCVBUF:
5681 if (*(const int*)optval < 2048)
5683 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
5684 return 0;
5686 /* Fall through */
5688 /* The options listed here don't need any special handling. Thanks to
5689 * the conversion happening above, options from there will fall through
5690 * to this, too.*/
5691 case WS_SO_ACCEPTCONN:
5692 case WS_SO_BROADCAST:
5693 case WS_SO_ERROR:
5694 case WS_SO_KEEPALIVE:
5695 case WS_SO_OOBINLINE:
5696 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
5697 * however, using it the BSD way fixes bug 8513 and seems to be what
5698 * most programmers assume, anyway */
5699 case WS_SO_REUSEADDR:
5700 case WS_SO_SNDBUF:
5701 case WS_SO_TYPE:
5702 convert_sockopt(&level, &optname);
5703 break;
5705 /* SO_DEBUG is a privileged operation, ignore it. */
5706 case WS_SO_DEBUG:
5707 TRACE("Ignoring SO_DEBUG\n");
5708 return 0;
5710 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
5711 * socket. According to MSDN, this option is silently ignored.*/
5712 case WS_SO_DONTROUTE:
5713 TRACE("Ignoring SO_DONTROUTE\n");
5714 return 0;
5716 /* Stops two sockets from being bound to the same port. Always happens
5717 * on unix systems, so just drop it. */
5718 case WS_SO_EXCLUSIVEADDRUSE:
5719 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
5720 return 0;
5722 /* After a ConnectEx call succeeds, the socket can't be used with half of the
5723 * normal winsock functions on windows. We don't have that problem. */
5724 case WS_SO_UPDATE_CONNECT_CONTEXT:
5725 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
5726 return 0;
5728 /* After a AcceptEx call succeeds, the socket can't be used with half of the
5729 * normal winsock functions on windows. We don't have that problem. */
5730 case WS_SO_UPDATE_ACCEPT_CONTEXT:
5731 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
5732 return 0;
5734 /* SO_OPENTYPE does not require a valid socket handle. */
5735 case WS_SO_OPENTYPE:
5736 if (!optlen || optlen < sizeof(int) || !optval)
5738 SetLastError(WSAEFAULT);
5739 return SOCKET_ERROR;
5741 get_per_thread_data()->opentype = *(const int *)optval;
5742 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
5743 return 0;
5745 #ifdef SO_RCVTIMEO
5746 case WS_SO_RCVTIMEO:
5747 #endif
5748 #ifdef SO_SNDTIMEO
5749 case WS_SO_SNDTIMEO:
5750 #endif
5751 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
5752 if (optval && optlen == sizeof(UINT32)) {
5753 /* WinSock passes milliseconds instead of struct timeval */
5754 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
5755 tval.tv_sec = *(const UINT32*)optval / 1000;
5756 /* min of 500 milliseconds */
5757 if (tval.tv_sec == 0 && tval.tv_usec && tval.tv_usec < 500000)
5758 tval.tv_usec = 500000;
5759 optlen = sizeof(struct timeval);
5760 optval = (char*)&tval;
5761 } else if (optlen == sizeof(struct timeval)) {
5762 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
5763 } else {
5764 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
5765 return 0;
5767 convert_sockopt(&level, &optname);
5768 break;
5769 #endif
5771 default:
5772 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
5773 SetLastError(WSAENOPROTOOPT);
5774 return SOCKET_ERROR;
5776 break; /* case WS_SOL_SOCKET */
5778 #ifdef HAS_IPX
5779 case WS_NSPROTO_IPX:
5780 switch(optname)
5782 case WS_IPX_PTYPE:
5783 return set_ipx_packettype(s, *(int*)optval);
5785 case WS_IPX_FILTERPTYPE:
5786 /* Sets the receive filter packet type, at the moment we don't support it */
5787 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
5788 /* Returning 0 is better for now than returning a SOCKET_ERROR */
5789 return 0;
5791 default:
5792 FIXME("opt_name:%x\n", optname);
5793 return SOCKET_ERROR;
5795 break; /* case WS_NSPROTO_IPX */
5796 #endif
5798 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
5799 case WS_IPPROTO_TCP:
5800 switch(optname)
5802 case WS_TCP_NODELAY:
5803 convert_sockopt(&level, &optname);
5804 break;
5805 default:
5806 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
5807 return SOCKET_ERROR;
5809 break;
5811 case WS_IPPROTO_IP:
5812 switch(optname)
5814 case WS_IP_ADD_MEMBERSHIP:
5815 case WS_IP_DROP_MEMBERSHIP:
5816 #ifdef IP_HDRINCL
5817 case WS_IP_HDRINCL:
5818 #endif
5819 case WS_IP_MULTICAST_IF:
5820 case WS_IP_MULTICAST_LOOP:
5821 case WS_IP_MULTICAST_TTL:
5822 case WS_IP_OPTIONS:
5823 #ifdef IP_PKTINFO
5824 case WS_IP_PKTINFO:
5825 #endif
5826 case WS_IP_TOS:
5827 case WS_IP_TTL:
5828 #ifdef IP_UNICAST_IF
5829 case WS_IP_UNICAST_IF:
5830 #endif
5831 convert_sockopt(&level, &optname);
5832 break;
5833 case WS_IP_DONTFRAGMENT:
5834 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
5835 return 0;
5836 default:
5837 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
5838 return SOCKET_ERROR;
5840 break;
5842 case WS_IPPROTO_IPV6:
5843 switch(optname)
5845 #ifdef IPV6_ADD_MEMBERSHIP
5846 case WS_IPV6_ADD_MEMBERSHIP:
5847 #endif
5848 #ifdef IPV6_DROP_MEMBERSHIP
5849 case WS_IPV6_DROP_MEMBERSHIP:
5850 #endif
5851 case WS_IPV6_MULTICAST_IF:
5852 case WS_IPV6_MULTICAST_HOPS:
5853 case WS_IPV6_MULTICAST_LOOP:
5854 case WS_IPV6_UNICAST_HOPS:
5855 case WS_IPV6_V6ONLY:
5856 #ifdef IPV6_UNICAST_IF
5857 case WS_IPV6_UNICAST_IF:
5858 #endif
5859 convert_sockopt(&level, &optname);
5860 break;
5861 case WS_IPV6_DONTFRAG:
5862 FIXME("IPV6_DONTFRAG is silently ignored!\n");
5863 return 0;
5864 case WS_IPV6_PROTECTION_LEVEL:
5865 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
5866 return 0;
5867 default:
5868 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
5869 return SOCKET_ERROR;
5871 break;
5873 default:
5874 WARN("Unknown level: 0x%08x\n", level);
5875 SetLastError(WSAEINVAL);
5876 return SOCKET_ERROR;
5877 } /* end switch(level) */
5879 /* avoid endianness issues if argument is a 16-bit int */
5880 if (optval && optlen < sizeof(int))
5882 woptval= *((const INT16 *) optval);
5883 optval= (char*) &woptval;
5884 woptval&= (1 << optlen * 8) - 1;
5885 optlen=sizeof(int);
5887 fd = get_sock_fd( s, 0, NULL );
5888 if (fd == -1) return SOCKET_ERROR;
5890 if (setsockopt(fd, level, optname, optval, optlen) == 0)
5892 #ifdef __APPLE__
5893 if (level == SOL_SOCKET && optname == SO_REUSEADDR &&
5894 setsockopt(fd, level, SO_REUSEPORT, optval, optlen) != 0)
5896 SetLastError(wsaErrno());
5897 release_sock_fd( s, fd );
5898 return SOCKET_ERROR;
5900 #endif
5901 release_sock_fd( s, fd );
5902 return 0;
5904 TRACE("Setting socket error, %d\n", wsaErrno());
5905 SetLastError(wsaErrno());
5906 release_sock_fd( s, fd );
5908 return SOCKET_ERROR;
5911 /***********************************************************************
5912 * shutdown (WS2_32.22)
5914 int WINAPI WS_shutdown(SOCKET s, int how)
5916 int fd, err = WSAENOTSOCK;
5917 unsigned int options = 0, clear_flags = 0;
5919 fd = get_sock_fd( s, 0, &options );
5920 TRACE("socket %04lx, how 0x%x, options 0x%x\n", s, how, options );
5922 if (fd == -1)
5923 return SOCKET_ERROR;
5925 switch( how )
5927 case SD_RECEIVE: /* drop receives */
5928 clear_flags |= FD_READ;
5929 break;
5930 case SD_SEND: /* drop sends */
5931 clear_flags |= FD_WRITE;
5932 break;
5933 case SD_BOTH: /* drop all */
5934 clear_flags |= FD_READ|FD_WRITE;
5935 /*fall through */
5936 default:
5937 clear_flags |= FD_WINE_LISTENING;
5940 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
5942 switch ( how )
5944 case SD_RECEIVE:
5945 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
5946 break;
5947 case SD_SEND:
5948 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
5949 break;
5950 case SD_BOTH:
5951 default:
5952 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
5953 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
5954 break;
5956 if (err) goto error;
5958 else /* non-overlapped mode */
5960 if ( shutdown( fd, how ) )
5962 err = wsaErrno();
5963 goto error;
5967 release_sock_fd( s, fd );
5968 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
5969 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
5970 return 0;
5972 error:
5973 release_sock_fd( s, fd );
5974 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
5975 SetLastError( err );
5976 return SOCKET_ERROR;
5979 /***********************************************************************
5980 * socket (WS2_32.23)
5982 SOCKET WINAPI WS_socket(int af, int type, int protocol)
5984 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
5986 return WSASocketW( af, type, protocol, NULL, 0,
5987 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
5991 /***********************************************************************
5992 * gethostbyaddr (WS2_32.51)
5994 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
5996 struct WS_hostent *retval = NULL;
5997 struct hostent* host;
5998 int unixtype = convert_af_w2u(type);
5999 const char *paddr = addr;
6000 unsigned long loopback;
6001 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6002 char *extrabuf;
6003 int ebufsize = 1024;
6004 struct hostent hostentry;
6005 int locerr = ENOBUFS;
6006 #endif
6008 /* convert back the magic loopback address if necessary */
6009 if (unixtype == AF_INET && len == 4 && !memcmp(addr, magic_loopback_addr, 4))
6011 loopback = htonl(INADDR_LOOPBACK);
6012 paddr = (char*) &loopback;
6015 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6016 host = NULL;
6017 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
6018 while(extrabuf) {
6019 int res = gethostbyaddr_r(paddr, len, unixtype,
6020 &hostentry, extrabuf, ebufsize, &host, &locerr);
6021 if (res != ERANGE) break;
6022 ebufsize *=2;
6023 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
6025 if (host) retval = WS_dup_he(host);
6026 else SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
6027 HeapFree(GetProcessHeap(),0,extrabuf);
6028 #else
6029 EnterCriticalSection( &csWSgetXXXbyYYY );
6030 host = gethostbyaddr(paddr, len, unixtype);
6031 if (host) retval = WS_dup_he(host);
6032 else SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
6033 LeaveCriticalSection( &csWSgetXXXbyYYY );
6034 #endif
6035 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
6036 return retval;
6039 /***********************************************************************
6040 * WS_compare_routes_by_metric_asc (INTERNAL)
6042 * Comparison function for qsort(), for sorting two routes (struct route)
6043 * by metric in ascending order.
6045 static int WS_compare_routes_by_metric_asc(const void *left, const void *right)
6047 return ((const struct route*)left)->metric - ((const struct route*)right)->metric;
6050 /***********************************************************************
6051 * WS_get_local_ips (INTERNAL)
6053 * Returns the list of local IP addresses by going through the network
6054 * adapters and using the local routing table to sort the addresses
6055 * from highest routing priority to lowest routing priority. This
6056 * functionality is inferred from the description for obtaining local
6057 * IP addresses given in the Knowledge Base Article Q160215.
6059 * Please note that the returned hostent is only freed when the thread
6060 * closes and is replaced if another hostent is requested.
6062 static struct WS_hostent* WS_get_local_ips( char *hostname )
6064 int numroutes = 0, i, j;
6065 DWORD n;
6066 PIP_ADAPTER_INFO adapters = NULL, k;
6067 struct WS_hostent *hostlist = NULL;
6068 PMIB_IPFORWARDTABLE routes = NULL;
6069 struct route *route_addrs = NULL;
6070 DWORD adap_size, route_size;
6072 /* Obtain the size of the adapter list and routing table, also allocate memory */
6073 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
6074 return NULL;
6075 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
6076 return NULL;
6077 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
6078 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
6079 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
6080 if (adapters == NULL || routes == NULL || route_addrs == NULL)
6081 goto cleanup;
6082 /* Obtain the adapter list and the full routing table */
6083 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
6084 goto cleanup;
6085 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
6086 goto cleanup;
6087 /* Store the interface associated with each route */
6088 for (n = 0; n < routes->dwNumEntries; n++)
6090 IF_INDEX ifindex;
6091 DWORD ifmetric;
6092 BOOL exists = FALSE;
6094 if (routes->table[n].u1.ForwardType != MIB_IPROUTE_TYPE_DIRECT)
6095 continue;
6096 ifindex = routes->table[n].dwForwardIfIndex;
6097 ifmetric = routes->table[n].dwForwardMetric1;
6098 /* Only store the lowest valued metric for an interface */
6099 for (j = 0; j < numroutes; j++)
6101 if (route_addrs[j].interface == ifindex)
6103 if (route_addrs[j].metric > ifmetric)
6104 route_addrs[j].metric = ifmetric;
6105 exists = TRUE;
6108 if (exists)
6109 continue;
6110 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
6111 if (route_addrs == NULL)
6112 goto cleanup; /* Memory allocation error, fail gracefully */
6113 route_addrs[numroutes].interface = ifindex;
6114 route_addrs[numroutes].metric = ifmetric;
6115 /* If no IP is found in the next step (for whatever reason)
6116 * then fall back to the magic loopback address.
6118 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
6119 numroutes++;
6121 if (numroutes == 0)
6122 goto cleanup; /* No routes, fall back to the Magic IP */
6123 /* Find the IP address associated with each found interface */
6124 for (i = 0; i < numroutes; i++)
6126 for (k = adapters; k != NULL; k = k->Next)
6128 char *ip = k->IpAddressList.IpAddress.String;
6130 if (route_addrs[i].interface == k->Index)
6131 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
6134 /* Allocate a hostent and enough memory for all the IPs,
6135 * including the NULL at the end of the list.
6137 hostlist = WS_create_he(hostname, 1, 0, numroutes+1, sizeof(struct in_addr));
6138 if (hostlist == NULL)
6139 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
6140 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
6141 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
6142 hostlist->h_addrtype = AF_INET;
6143 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
6144 /* Reorder the entries before placing them in the host list. Windows expects
6145 * the IP list in order from highest priority to lowest (the critical thing
6146 * is that most applications expect the first IP to be the default route).
6148 if (numroutes > 1)
6149 qsort(route_addrs, numroutes, sizeof(struct route), WS_compare_routes_by_metric_asc);
6151 for (i = 0; i < numroutes; i++)
6152 (*(struct in_addr *) hostlist->h_addr_list[i]) = route_addrs[i].addr;
6154 /* Cleanup all allocated memory except the address list,
6155 * the address list is used by the calling app.
6157 cleanup:
6158 HeapFree(GetProcessHeap(), 0, route_addrs);
6159 HeapFree(GetProcessHeap(), 0, adapters);
6160 HeapFree(GetProcessHeap(), 0, routes);
6161 return hostlist;
6164 /***********************************************************************
6165 * gethostbyname (WS2_32.52)
6167 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
6169 struct WS_hostent *retval = NULL;
6170 struct hostent* host;
6171 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6172 char *extrabuf;
6173 int ebufsize=1024;
6174 struct hostent hostentry;
6175 int locerr = ENOBUFS;
6176 #endif
6177 char hostname[100];
6178 if(!num_startup) {
6179 SetLastError(WSANOTINITIALISED);
6180 return NULL;
6182 if( gethostname( hostname, 100) == -1) {
6183 SetLastError(WSAENOBUFS); /* appropriate ? */
6184 return retval;
6186 if( !name || !name[0]) {
6187 name = hostname;
6189 /* If the hostname of the local machine is requested then return the
6190 * complete list of local IP addresses */
6191 if(strcmp(name, hostname) == 0)
6192 retval = WS_get_local_ips(hostname);
6193 /* If any other hostname was requested (or the routing table lookup failed)
6194 * then return the IP found by the host OS */
6195 if(retval == NULL)
6197 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6198 host = NULL;
6199 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
6200 while(extrabuf) {
6201 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
6202 if( res != ERANGE) break;
6203 ebufsize *=2;
6204 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
6206 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
6207 #else
6208 EnterCriticalSection( &csWSgetXXXbyYYY );
6209 host = gethostbyname(name);
6210 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
6211 #endif
6212 if (host) retval = WS_dup_he(host);
6213 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6214 HeapFree(GetProcessHeap(),0,extrabuf);
6215 #else
6216 LeaveCriticalSection( &csWSgetXXXbyYYY );
6217 #endif
6219 if (retval && retval->h_addr_list[0][0] == 127 &&
6220 strcmp(name, "localhost") != 0)
6222 /* hostname != "localhost" but has loopback address. replace by our
6223 * special address.*/
6224 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
6226 TRACE( "%s ret %p\n", debugstr_a(name), retval );
6227 return retval;
6231 /***********************************************************************
6232 * getprotobyname (WS2_32.53)
6234 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
6236 struct WS_protoent* retval = NULL;
6237 #ifdef HAVE_GETPROTOBYNAME
6238 struct protoent* proto;
6239 EnterCriticalSection( &csWSgetXXXbyYYY );
6240 if( (proto = getprotobyname(name)) != NULL )
6242 retval = WS_dup_pe(proto);
6244 else {
6245 MESSAGE("protocol %s not found; You might want to add "
6246 "this to /etc/protocols\n", debugstr_a(name) );
6247 SetLastError(WSANO_DATA);
6249 LeaveCriticalSection( &csWSgetXXXbyYYY );
6250 #endif
6251 TRACE( "%s ret %p\n", debugstr_a(name), retval );
6252 return retval;
6256 /***********************************************************************
6257 * getprotobynumber (WS2_32.54)
6259 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
6261 struct WS_protoent* retval = NULL;
6262 #ifdef HAVE_GETPROTOBYNUMBER
6263 struct protoent* proto;
6264 EnterCriticalSection( &csWSgetXXXbyYYY );
6265 if( (proto = getprotobynumber(number)) != NULL )
6267 retval = WS_dup_pe(proto);
6269 else {
6270 MESSAGE("protocol number %d not found; You might want to add "
6271 "this to /etc/protocols\n", number );
6272 SetLastError(WSANO_DATA);
6274 LeaveCriticalSection( &csWSgetXXXbyYYY );
6275 #endif
6276 TRACE("%i ret %p\n", number, retval);
6277 return retval;
6281 /***********************************************************************
6282 * getservbyname (WS2_32.55)
6284 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
6286 struct WS_servent* retval = NULL;
6287 struct servent* serv;
6288 char *name_str;
6289 char *proto_str = NULL;
6291 if (!(name_str = strdup_lower(name))) return NULL;
6293 if (proto && *proto)
6295 if (!(proto_str = strdup_lower(proto)))
6297 HeapFree( GetProcessHeap(), 0, name_str );
6298 return NULL;
6302 EnterCriticalSection( &csWSgetXXXbyYYY );
6303 serv = getservbyname(name_str, proto_str);
6304 if( serv != NULL )
6306 retval = WS_dup_se(serv);
6308 else SetLastError(WSANO_DATA);
6309 LeaveCriticalSection( &csWSgetXXXbyYYY );
6310 HeapFree( GetProcessHeap(), 0, proto_str );
6311 HeapFree( GetProcessHeap(), 0, name_str );
6312 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
6313 return retval;
6316 /***********************************************************************
6317 * freeaddrinfo (WS2_32.@)
6319 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
6321 while (res) {
6322 struct WS_addrinfo *next;
6324 HeapFree(GetProcessHeap(),0,res->ai_canonname);
6325 HeapFree(GetProcessHeap(),0,res->ai_addr);
6326 next = res->ai_next;
6327 HeapFree(GetProcessHeap(),0,res);
6328 res = next;
6332 /* helper functions for getaddrinfo()/getnameinfo() */
6333 static int convert_aiflag_w2u(int winflags) {
6334 unsigned int i;
6335 int unixflags = 0;
6337 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
6338 if (ws_aiflag_map[i][0] & winflags) {
6339 unixflags |= ws_aiflag_map[i][1];
6340 winflags &= ~ws_aiflag_map[i][0];
6342 if (winflags)
6343 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
6344 return unixflags;
6347 static int convert_niflag_w2u(int winflags) {
6348 unsigned int i;
6349 int unixflags = 0;
6351 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
6352 if (ws_niflag_map[i][0] & winflags) {
6353 unixflags |= ws_niflag_map[i][1];
6354 winflags &= ~ws_niflag_map[i][0];
6356 if (winflags)
6357 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
6358 return unixflags;
6361 static int convert_aiflag_u2w(int unixflags) {
6362 unsigned int i;
6363 int winflags = 0;
6365 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
6366 if (ws_aiflag_map[i][1] & unixflags) {
6367 winflags |= ws_aiflag_map[i][0];
6368 unixflags &= ~ws_aiflag_map[i][1];
6370 if (unixflags) /* will warn usually */
6371 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
6372 return winflags;
6375 static int convert_eai_u2w(int unixret) {
6376 int i;
6378 if (!unixret) return 0;
6380 for (i=0;ws_eai_map[i][0];i++)
6381 if (ws_eai_map[i][1] == unixret)
6382 return ws_eai_map[i][0];
6384 if (unixret == EAI_SYSTEM)
6385 /* There are broken versions of glibc which return EAI_SYSTEM
6386 * and set errno to 0 instead of returning EAI_NONAME.
6388 return errno ? sock_get_error( errno ) : WS_EAI_NONAME;
6390 FIXME("Unhandled unix EAI_xxx ret %d\n", unixret);
6391 return unixret;
6394 static char *get_hostname(void)
6396 char *ret;
6397 DWORD size = 0;
6399 GetComputerNameExA( ComputerNamePhysicalDnsHostname, NULL, &size );
6400 if (GetLastError() != ERROR_MORE_DATA) return NULL;
6401 if (!(ret = HeapAlloc( GetProcessHeap(), 0, size ))) return NULL;
6402 if (!GetComputerNameExA( ComputerNamePhysicalDnsHostname, ret, &size ))
6404 HeapFree( GetProcessHeap(), 0, ret );
6405 return NULL;
6407 return ret;
6410 /***********************************************************************
6411 * getaddrinfo (WS2_32.@)
6413 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
6415 #ifdef HAVE_GETADDRINFO
6416 struct addrinfo *unixaires = NULL;
6417 int result;
6418 struct addrinfo unixhints, *punixhints = NULL;
6419 char *hostname;
6420 const char *node;
6422 *res = NULL;
6423 if (!nodename && !servname)
6425 SetLastError(WSAHOST_NOT_FOUND);
6426 return WSAHOST_NOT_FOUND;
6429 hostname = get_hostname();
6430 if (!hostname) return WSA_NOT_ENOUGH_MEMORY;
6432 if (!nodename)
6433 node = NULL;
6434 else if (!nodename[0])
6435 node = hostname;
6436 else
6437 node = nodename;
6439 /* servname tweak required by OSX and BSD kernels */
6440 if (servname && !servname[0]) servname = "0";
6442 if (hints) {
6443 punixhints = &unixhints;
6445 memset(&unixhints, 0, sizeof(unixhints));
6446 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
6448 /* zero is a wildcard, no need to convert */
6449 if (hints->ai_family)
6450 punixhints->ai_family = convert_af_w2u(hints->ai_family);
6451 if (hints->ai_socktype)
6452 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
6453 if (hints->ai_protocol)
6454 punixhints->ai_protocol = max(convert_proto_w2u(hints->ai_protocol), 0);
6456 if (punixhints->ai_socktype < 0)
6458 SetLastError(WSAESOCKTNOSUPPORT);
6459 HeapFree(GetProcessHeap(), 0, hostname);
6460 return SOCKET_ERROR;
6463 /* windows allows invalid combinations of socket type and protocol, unix does not.
6464 * fix the parameters here to make getaddrinfo call always work */
6465 if (punixhints->ai_protocol == IPPROTO_TCP &&
6466 punixhints->ai_socktype != SOCK_STREAM && punixhints->ai_socktype != SOCK_SEQPACKET)
6467 punixhints->ai_socktype = 0;
6469 else if (punixhints->ai_protocol == IPPROTO_UDP && punixhints->ai_socktype != SOCK_DGRAM)
6470 punixhints->ai_socktype = 0;
6472 else if (IS_IPX_PROTO(punixhints->ai_protocol) && punixhints->ai_socktype != SOCK_DGRAM)
6473 punixhints->ai_socktype = 0;
6475 else if (punixhints->ai_protocol == IPPROTO_IPV6)
6476 punixhints->ai_protocol = 0;
6479 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
6480 result = getaddrinfo(node, servname, punixhints, &unixaires);
6482 if (result && !strcmp(hostname, node))
6484 /* If it didn't work it means the host name IP is not in /etc/hosts, try again
6485 * by sending a NULL host and avoid sending a NULL servname too because that
6486 * is invalid */
6487 ERR_(winediag)("Failed to resolve your host name IP\n");
6488 result = getaddrinfo(NULL, servname ? servname : "0", punixhints, &unixaires);
6490 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
6491 HeapFree(GetProcessHeap(), 0, hostname);
6493 if (!result) {
6494 struct addrinfo *xuai = unixaires;
6495 struct WS_addrinfo **xai = res;
6497 *xai = NULL;
6498 while (xuai) {
6499 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
6500 SIZE_T len;
6502 if (!ai)
6503 goto outofmem;
6505 *xai = ai;xai = &ai->ai_next;
6506 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
6507 ai->ai_family = convert_af_u2w(xuai->ai_family);
6508 /* copy whatever was sent in the hints */
6509 if(hints) {
6510 ai->ai_socktype = hints->ai_socktype;
6511 ai->ai_protocol = hints->ai_protocol;
6512 } else {
6513 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
6514 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
6516 if (xuai->ai_canonname) {
6517 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
6518 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
6519 if (!ai->ai_canonname)
6520 goto outofmem;
6521 strcpy(ai->ai_canonname,xuai->ai_canonname);
6523 len = xuai->ai_addrlen;
6524 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
6525 if (!ai->ai_addr)
6526 goto outofmem;
6527 ai->ai_addrlen = len;
6528 do {
6529 int winlen = ai->ai_addrlen;
6531 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
6532 ai->ai_addrlen = winlen;
6533 break;
6535 len = 2*len;
6536 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
6537 if (!ai->ai_addr)
6538 goto outofmem;
6539 ai->ai_addrlen = len;
6540 } while (1);
6541 xuai = xuai->ai_next;
6543 freeaddrinfo(unixaires);
6545 if (TRACE_ON(winsock))
6547 struct WS_addrinfo *ai = *res;
6548 while (ai)
6550 TRACE("=> %p, flags %#x, family %d, type %d, protocol %d, len %ld, name %s, addr %s\n",
6551 ai, ai->ai_flags, ai->ai_family, ai->ai_socktype, ai->ai_protocol, ai->ai_addrlen,
6552 ai->ai_canonname, debugstr_sockaddr(ai->ai_addr));
6553 ai = ai->ai_next;
6556 } else
6557 result = convert_eai_u2w(result);
6559 SetLastError(result);
6560 return result;
6562 outofmem:
6563 if (*res) WS_freeaddrinfo(*res);
6564 if (unixaires) freeaddrinfo(unixaires);
6565 return WSA_NOT_ENOUGH_MEMORY;
6566 #else
6567 FIXME("getaddrinfo() failed, not found during buildtime.\n");
6568 return EAI_FAIL;
6569 #endif
6572 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
6574 struct WS_addrinfoW *ret;
6576 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
6577 ret->ai_flags = ai->ai_flags;
6578 ret->ai_family = ai->ai_family;
6579 ret->ai_socktype = ai->ai_socktype;
6580 ret->ai_protocol = ai->ai_protocol;
6581 ret->ai_addrlen = ai->ai_addrlen;
6582 ret->ai_canonname = NULL;
6583 ret->ai_addr = NULL;
6584 ret->ai_next = NULL;
6585 if (ai->ai_canonname)
6587 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
6588 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR))))
6590 HeapFree(GetProcessHeap(), 0, ret);
6591 return NULL;
6593 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
6595 if (ai->ai_addr)
6597 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, ai->ai_addrlen)))
6599 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
6600 HeapFree(GetProcessHeap(), 0, ret);
6601 return NULL;
6603 memcpy(ret->ai_addr, ai->ai_addr, ai->ai_addrlen);
6605 return ret;
6608 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
6610 struct WS_addrinfoW *ret, *infoW;
6612 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
6613 while (info->ai_next)
6615 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
6617 FreeAddrInfoW(ret);
6618 return NULL;
6620 infoW = infoW->ai_next;
6621 info = info->ai_next;
6623 return ret;
6626 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
6628 struct WS_addrinfo *ret;
6630 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
6631 ret->ai_flags = ai->ai_flags;
6632 ret->ai_family = ai->ai_family;
6633 ret->ai_socktype = ai->ai_socktype;
6634 ret->ai_protocol = ai->ai_protocol;
6635 ret->ai_addrlen = ai->ai_addrlen;
6636 ret->ai_canonname = NULL;
6637 ret->ai_addr = NULL;
6638 ret->ai_next = NULL;
6639 if (ai->ai_canonname)
6641 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
6642 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
6644 HeapFree(GetProcessHeap(), 0, ret);
6645 return NULL;
6647 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
6649 if (ai->ai_addr)
6651 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
6653 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
6654 HeapFree(GetProcessHeap(), 0, ret);
6655 return NULL;
6657 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
6659 return ret;
6662 /***********************************************************************
6663 * GetAddrInfoExW (WS2_32.@)
6665 int WINAPI GetAddrInfoExW(const WCHAR *name, const WCHAR *servname, DWORD namespace, GUID *namespace_id,
6666 const ADDRINFOEXW *hints, ADDRINFOEXW **result, struct timeval *timeout, OVERLAPPED *overlapped,
6667 LPLOOKUPSERVICE_COMPLETION_ROUTINE completion_routine, HANDLE *handle)
6669 FIXME("(%s %s %x %s %p %p %p %p %p %p)\n", debugstr_w(name), debugstr_w(servname), namespace,
6670 debugstr_guid(namespace_id), hints, result, timeout, overlapped, completion_routine, handle);
6671 return WSAHOST_NOT_FOUND;
6674 /***********************************************************************
6675 * GetAddrInfoW (WS2_32.@)
6677 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
6679 int ret, len;
6680 char *nodenameA = NULL, *servnameA = NULL;
6681 struct WS_addrinfo *resA, *hintsA = NULL;
6683 *res = NULL;
6684 if (nodename)
6686 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
6687 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
6688 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
6690 if (servname)
6692 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
6693 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
6695 HeapFree(GetProcessHeap(), 0, nodenameA);
6696 return EAI_MEMORY;
6698 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
6701 if (hints) hintsA = addrinfo_WtoA(hints);
6702 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
6703 WS_freeaddrinfo(hintsA);
6705 if (!ret)
6707 *res = addrinfo_list_AtoW(resA);
6708 WS_freeaddrinfo(resA);
6711 HeapFree(GetProcessHeap(), 0, nodenameA);
6712 HeapFree(GetProcessHeap(), 0, servnameA);
6713 return ret;
6716 /***********************************************************************
6717 * FreeAddrInfoW (WS2_32.@)
6719 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
6721 while (ai)
6723 ADDRINFOW *next;
6724 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
6725 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
6726 next = ai->ai_next;
6727 HeapFree(GetProcessHeap(), 0, ai);
6728 ai = next;
6732 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
6733 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
6735 #ifdef HAVE_GETNAMEINFO
6736 int ret;
6737 union generic_unix_sockaddr sa_u;
6738 unsigned int size;
6740 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
6741 serv, servlen, flags);
6743 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
6744 if (!size)
6746 SetLastError(WSAEFAULT);
6747 return WSA_NOT_ENOUGH_MEMORY;
6749 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
6750 return convert_eai_u2w(ret);
6751 #else
6752 FIXME("getnameinfo() failed, not found during buildtime.\n");
6753 return EAI_FAIL;
6754 #endif
6757 int WINAPI GetNameInfoW(const SOCKADDR *sa, WS_socklen_t salen, PWCHAR host,
6758 DWORD hostlen, PWCHAR serv, DWORD servlen, INT flags)
6760 int ret;
6761 char *hostA = NULL, *servA = NULL;
6763 if (host && (!(hostA = HeapAlloc(GetProcessHeap(), 0, hostlen)))) return EAI_MEMORY;
6764 if (serv && (!(servA = HeapAlloc(GetProcessHeap(), 0, servlen))))
6766 HeapFree(GetProcessHeap(), 0, hostA);
6767 return EAI_MEMORY;
6770 ret = WS_getnameinfo(sa, salen, hostA, hostlen, servA, servlen, flags);
6771 if (!ret)
6773 if (host) MultiByteToWideChar(CP_ACP, 0, hostA, -1, host, hostlen);
6774 if (serv) MultiByteToWideChar(CP_ACP, 0, servA, -1, serv, servlen);
6777 HeapFree(GetProcessHeap(), 0, hostA);
6778 HeapFree(GetProcessHeap(), 0, servA);
6779 return ret;
6782 /***********************************************************************
6783 * getservbyport (WS2_32.56)
6785 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
6787 struct WS_servent* retval = NULL;
6788 #ifdef HAVE_GETSERVBYPORT
6789 struct servent* serv;
6790 char *proto_str = NULL;
6792 if (proto && *proto)
6794 if (!(proto_str = strdup_lower(proto))) return NULL;
6796 EnterCriticalSection( &csWSgetXXXbyYYY );
6797 if( (serv = getservbyport(port, proto_str)) != NULL ) {
6798 retval = WS_dup_se(serv);
6800 else SetLastError(WSANO_DATA);
6801 LeaveCriticalSection( &csWSgetXXXbyYYY );
6802 HeapFree( GetProcessHeap(), 0, proto_str );
6803 #endif
6804 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
6805 return retval;
6809 /***********************************************************************
6810 * gethostname (WS2_32.57)
6812 int WINAPI WS_gethostname(char *name, int namelen)
6814 char buf[256];
6815 int len;
6817 TRACE("name %p, len %d\n", name, namelen);
6819 if (!name)
6821 SetLastError(WSAEFAULT);
6822 return SOCKET_ERROR;
6825 if (gethostname(buf, sizeof(buf)) != 0)
6827 SetLastError(wsaErrno());
6828 return SOCKET_ERROR;
6831 TRACE("<- '%s'\n", buf);
6832 len = strlen(buf);
6833 if (len > 15)
6834 WARN("Windows supports NetBIOS name length up to 15 bytes!\n");
6835 if (namelen <= len)
6837 SetLastError(WSAEFAULT);
6838 WARN("<- not enough space for hostname, required %d, got %d!\n", len + 1, namelen);
6839 return SOCKET_ERROR;
6841 strcpy(name, buf);
6842 return 0;
6846 /* ------------------------------------- Windows sockets extensions -- *
6848 * ------------------------------------------------------------------- */
6850 /***********************************************************************
6851 * WSAEnumNetworkEvents (WS2_32.36)
6853 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
6855 int ret;
6856 int i;
6857 int errors[FD_MAX_EVENTS];
6859 TRACE("%04lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
6861 SERVER_START_REQ( get_socket_event )
6863 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6864 req->service = TRUE;
6865 req->c_event = wine_server_obj_handle( hEvent );
6866 wine_server_set_reply( req, errors, sizeof(errors) );
6867 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
6869 SERVER_END_REQ;
6870 if (!ret)
6872 for (i = 0; i < FD_MAX_EVENTS; i++)
6873 lpEvent->iErrorCode[i] = NtStatusToWSAError(errors[i]);
6874 return 0;
6876 SetLastError(WSAEINVAL);
6877 return SOCKET_ERROR;
6880 /***********************************************************************
6881 * WSAEventSelect (WS2_32.39)
6883 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
6885 int ret;
6887 TRACE("%04lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
6889 SERVER_START_REQ( set_socket_event )
6891 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6892 req->mask = lEvent;
6893 req->event = wine_server_obj_handle( hEvent );
6894 req->window = 0;
6895 req->msg = 0;
6896 ret = wine_server_call( req );
6898 SERVER_END_REQ;
6899 if (!ret) return 0;
6900 SetLastError(WSAEINVAL);
6901 return SOCKET_ERROR;
6904 /**********************************************************************
6905 * WSAGetOverlappedResult (WS2_32.40)
6907 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
6908 LPDWORD lpcbTransfer, BOOL fWait,
6909 LPDWORD lpdwFlags )
6911 NTSTATUS status;
6913 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
6914 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
6916 if ( lpOverlapped == NULL )
6918 ERR( "Invalid pointer\n" );
6919 SetLastError(WSA_INVALID_PARAMETER);
6920 return FALSE;
6923 status = lpOverlapped->Internal;
6924 if (status == STATUS_PENDING)
6926 if (!fWait)
6928 SetLastError( WSA_IO_INCOMPLETE );
6929 return FALSE;
6932 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
6933 INFINITE ) == WAIT_FAILED)
6934 return FALSE;
6935 status = lpOverlapped->Internal;
6938 if ( lpcbTransfer )
6939 *lpcbTransfer = lpOverlapped->InternalHigh;
6941 if ( lpdwFlags )
6942 *lpdwFlags = lpOverlapped->u.s.Offset;
6944 if (status) SetLastError( RtlNtStatusToDosError(status) );
6945 return !status;
6949 /***********************************************************************
6950 * WSAAsyncSelect (WS2_32.101)
6952 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
6954 int ret;
6956 TRACE("%04lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
6958 SERVER_START_REQ( set_socket_event )
6960 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6961 req->mask = lEvent;
6962 req->event = 0;
6963 req->window = wine_server_user_handle( hWnd );
6964 req->msg = uMsg;
6965 ret = wine_server_call( req );
6967 SERVER_END_REQ;
6968 if (!ret) return 0;
6969 SetLastError(WSAEINVAL);
6970 return SOCKET_ERROR;
6973 /***********************************************************************
6974 * WSACreateEvent (WS2_32.31)
6977 WSAEVENT WINAPI WSACreateEvent(void)
6979 /* Create a manual-reset event, with initial state: unsignaled */
6980 TRACE("\n");
6982 return CreateEventW(NULL, TRUE, FALSE, NULL);
6985 /***********************************************************************
6986 * WSACloseEvent (WS2_32.29)
6989 BOOL WINAPI WSACloseEvent(WSAEVENT event)
6991 TRACE ("event=%p\n", event);
6993 return CloseHandle(event);
6996 /***********************************************************************
6997 * WSASocketA (WS2_32.78)
7000 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
7001 LPWSAPROTOCOL_INFOA lpProtocolInfo,
7002 GROUP g, DWORD dwFlags)
7004 INT len;
7005 WSAPROTOCOL_INFOW info;
7007 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
7008 af, type, protocol, lpProtocolInfo, g, dwFlags);
7010 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
7012 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
7013 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
7014 info.szProtocol, WSAPROTOCOL_LEN + 1);
7016 if (!len)
7018 SetLastError(WSAEINVAL);
7019 return SOCKET_ERROR;
7022 return WSASocketW(af, type, protocol, &info, g, dwFlags);
7025 /***********************************************************************
7026 * WSASocketW (WS2_32.79)
7029 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
7030 LPWSAPROTOCOL_INFOW lpProtocolInfo,
7031 GROUP g, DWORD dwFlags)
7033 SOCKET ret;
7034 DWORD err;
7035 int unixaf, unixtype, ipxptype = -1;
7038 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
7039 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
7042 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
7043 af, type, protocol, lpProtocolInfo, g, dwFlags );
7045 if (!num_startup)
7047 err = WSANOTINITIALISED;
7048 goto done;
7051 /* hack for WSADuplicateSocket */
7052 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
7053 ret = lpProtocolInfo->dwServiceFlags3;
7054 TRACE("\tgot duplicate %04lx\n", ret);
7055 return ret;
7058 if (lpProtocolInfo)
7060 if (af == FROM_PROTOCOL_INFO || !af)
7061 af = lpProtocolInfo->iAddressFamily;
7062 if (type == FROM_PROTOCOL_INFO || !type)
7063 type = lpProtocolInfo->iSocketType;
7064 if (protocol == FROM_PROTOCOL_INFO || !protocol)
7065 protocol = lpProtocolInfo->iProtocol;
7068 if (!type && (af || protocol))
7070 int autoproto = protocol;
7071 WSAPROTOCOL_INFOW infow;
7073 /* default to the first valid protocol */
7074 if (!autoproto)
7075 autoproto = valid_protocols[0];
7076 else if(IS_IPX_PROTO(autoproto))
7077 autoproto = WS_NSPROTO_IPX;
7079 if (WS_EnterSingleProtocolW(autoproto, &infow))
7081 type = infow.iSocketType;
7083 /* after win2003 it's no longer possible to pass AF_UNSPEC
7084 using the protocol info struct */
7085 if (!lpProtocolInfo && af == WS_AF_UNSPEC)
7086 af = infow.iAddressFamily;
7091 Windows has an extension to the IPX protocol that allows one to create sockets
7092 and set the IPX packet type at the same time, to do that a caller will use
7093 a protocol like NSPROTO_IPX + <PACKET TYPE>
7095 if (IS_IPX_PROTO(protocol))
7096 ipxptype = protocol - WS_NSPROTO_IPX;
7098 /* convert the socket family, type and protocol */
7099 unixaf = convert_af_w2u(af);
7100 unixtype = convert_socktype_w2u(type);
7101 protocol = convert_proto_w2u(protocol);
7102 if (unixaf == AF_UNSPEC) unixaf = -1;
7104 /* filter invalid parameters */
7105 if (protocol < 0)
7107 /* the type could not be converted */
7108 if (type && unixtype < 0)
7110 err = WSAESOCKTNOSUPPORT;
7111 goto done;
7114 err = WSAEPROTONOSUPPORT;
7115 goto done;
7117 if (unixaf < 0)
7119 /* both family and protocol can't be invalid */
7120 if (protocol <= 0)
7122 err = WSAEINVAL;
7123 goto done;
7126 /* family could not be converted and neither socket type */
7127 if (unixtype < 0 && af >= 0)
7130 err = WSAESOCKTNOSUPPORT;
7131 goto done;
7134 err = WSAEAFNOSUPPORT;
7135 goto done;
7138 SERVER_START_REQ( create_socket )
7140 req->family = unixaf;
7141 req->type = unixtype;
7142 req->protocol = protocol;
7143 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
7144 req->attributes = (dwFlags & WSA_FLAG_NO_HANDLE_INHERIT) ? 0 : OBJ_INHERIT;
7145 req->flags = dwFlags & ~WSA_FLAG_NO_HANDLE_INHERIT;
7146 set_error( wine_server_call( req ) );
7147 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
7149 SERVER_END_REQ;
7150 if (ret)
7152 TRACE("\tcreated %04lx\n", ret );
7153 if (ipxptype > 0)
7154 set_ipx_packettype(ret, ipxptype);
7155 return ret;
7158 err = GetLastError();
7159 if (err == WSAEACCES) /* raw socket denied */
7161 if (type == SOCK_RAW)
7162 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
7163 else
7164 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
7166 else
7168 /* invalid combination of valid parameters, like SOCK_STREAM + IPPROTO_UDP */
7169 if (err == WSAEINVAL)
7170 err = WSAESOCKTNOSUPPORT;
7171 else if (err == WSAEOPNOTSUPP)
7172 err = WSAEPROTONOSUPPORT;
7175 done:
7176 WARN("\t\tfailed, error %d!\n", err);
7177 SetLastError(err);
7178 return INVALID_SOCKET;
7181 /***********************************************************************
7182 * WSAJoinLeaf (WS2_32.58)
7185 SOCKET WINAPI WSAJoinLeaf(
7186 SOCKET s,
7187 const struct WS_sockaddr *addr,
7188 int addrlen,
7189 LPWSABUF lpCallerData,
7190 LPWSABUF lpCalleeData,
7191 LPQOS lpSQOS,
7192 LPQOS lpGQOS,
7193 DWORD dwFlags)
7195 FIXME("stub.\n");
7196 return INVALID_SOCKET;
7199 /***********************************************************************
7200 * __WSAFDIsSet (WS2_32.151)
7202 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
7204 int i = set->fd_count, ret = 0;
7206 while (i--)
7207 if (set->fd_array[i] == s)
7209 ret = 1;
7210 break;
7213 TRACE("(socket %04lx, fd_set %p, count %i) <- %d\n", s, set, set->fd_count, ret);
7214 return ret;
7217 /***********************************************************************
7218 * WSAIsBlocking (WS2_32.114)
7220 BOOL WINAPI WSAIsBlocking(void)
7222 /* By default WinSock should set all its sockets to non-blocking mode
7223 * and poll in PeekMessage loop when processing "blocking" ones. This
7224 * function is supposed to tell if the program is in this loop. Our
7225 * blocking calls are truly blocking so we always return FALSE.
7227 * Note: It is allowed to call this function without prior WSAStartup().
7230 TRACE("\n");
7231 return FALSE;
7234 /***********************************************************************
7235 * WSACancelBlockingCall (WS2_32.113)
7237 INT WINAPI WSACancelBlockingCall(void)
7239 TRACE("\n");
7240 return 0;
7243 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
7245 FIXME("How was this called?\n");
7246 return x();
7250 /***********************************************************************
7251 * WSASetBlockingHook (WS2_32.109)
7253 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
7255 FARPROC prev = blocking_hook;
7256 blocking_hook = lpBlockFunc;
7257 TRACE("hook %p\n", lpBlockFunc);
7258 return prev;
7262 /***********************************************************************
7263 * WSAUnhookBlockingHook (WS2_32.110)
7265 INT WINAPI WSAUnhookBlockingHook(void)
7267 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
7268 return 0;
7272 /* ----------------------------------- end of API stuff */
7274 /* ----------------------------------- helper functions -
7276 * TODO: Merge WS_dup_..() stuff into one function that
7277 * would operate with a generic structure containing internal
7278 * pointers (via a template of some kind).
7281 static int list_size(char** l, int item_size)
7283 int i,j = 0;
7284 if(l)
7285 { for(i=0;l[i];i++)
7286 j += (item_size) ? item_size : strlen(l[i]) + 1;
7287 j += (i + 1) * sizeof(char*); }
7288 return j;
7291 static int list_dup(char** l_src, char** l_to, int item_size)
7293 char *p;
7294 int i;
7296 for (i = 0; l_src[i]; i++) ;
7297 p = (char *)(l_to + i + 1);
7298 for (i = 0; l_src[i]; i++)
7300 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
7301 memcpy(p, l_src[i], count);
7302 l_to[i] = p;
7303 p += count;
7305 l_to[i] = NULL;
7306 return p - (char *)l_to;
7309 /* ----- hostent */
7311 /* create a hostent entry
7313 * Creates the entry with enough memory for the name, aliases
7314 * addresses, and the address pointers. Also copies the name
7315 * and sets up all the pointers.
7317 * NOTE: The alias and address lists must be allocated with room
7318 * for the NULL item terminating the list. This is true even if
7319 * the list has no items ("aliases" and "addresses" must be
7320 * at least "1", a truly empty list is invalid).
7322 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length)
7324 struct WS_hostent *p_to;
7325 char *p;
7326 int size = (sizeof(struct WS_hostent) +
7327 strlen(name) + 1 +
7328 sizeof(char *) * aliases +
7329 aliases_size +
7330 sizeof(char *) * addresses +
7331 address_length * (addresses - 1)), i;
7333 if (!(p_to = check_buffer_he(size))) return NULL;
7334 memset(p_to, 0, size);
7336 /* Use the memory in the same way winsock does.
7337 * First set the pointer for aliases, second set the pointers for addresses.
7338 * Third fill the addresses indexes, fourth jump aliases names size.
7339 * Fifth fill the hostname.
7340 * NOTE: This method is valid for OS version's >= XP.
7342 p = (char *)(p_to + 1);
7343 p_to->h_aliases = (char **)p;
7344 p += sizeof(char *)*aliases;
7346 p_to->h_addr_list = (char **)p;
7347 p += sizeof(char *)*addresses;
7349 for (i = 0, addresses--; i < addresses; i++, p += address_length)
7350 p_to->h_addr_list[i] = p;
7352 /* NOTE: h_aliases must be filled in manually because we don't know each string
7353 * size, leave these pointers NULL (already set to NULL by memset earlier).
7355 p += aliases_size;
7357 p_to->h_name = p;
7358 strcpy(p, name);
7360 return p_to;
7363 /* duplicate hostent entry
7364 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
7365 * Ditto for protoent and servent.
7367 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
7369 int i, addresses = 0, alias_size = 0;
7370 struct WS_hostent *p_to;
7371 char *p;
7373 for( i = 0; p_he->h_aliases[i]; i++) alias_size += strlen(p_he->h_aliases[i]) + 1;
7374 while (p_he->h_addr_list[addresses]) addresses++;
7376 p_to = WS_create_he(p_he->h_name, i + 1, alias_size, addresses + 1, p_he->h_length);
7378 if (!p_to) return NULL;
7379 p_to->h_addrtype = convert_af_u2w(p_he->h_addrtype);
7380 p_to->h_length = p_he->h_length;
7382 for(i = 0, p = p_to->h_addr_list[0]; p_he->h_addr_list[i]; i++, p += p_to->h_length)
7383 memcpy(p, p_he->h_addr_list[i], p_to->h_length);
7385 /* Fill the aliases after the IP data */
7386 for(i = 0; p_he->h_aliases[i]; i++)
7388 p_to->h_aliases[i] = p;
7389 strcpy(p, p_he->h_aliases[i]);
7390 p += strlen(p) + 1;
7393 return p_to;
7396 /* ----- protoent */
7398 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
7400 char *p;
7401 struct WS_protoent *p_to;
7403 int size = (sizeof(*p_pe) +
7404 strlen(p_pe->p_name) + 1 +
7405 list_size(p_pe->p_aliases, 0));
7407 if (!(p_to = check_buffer_pe(size))) return NULL;
7408 p_to->p_proto = p_pe->p_proto;
7410 p = (char *)(p_to + 1);
7411 p_to->p_name = p;
7412 strcpy(p, p_pe->p_name);
7413 p += strlen(p) + 1;
7415 p_to->p_aliases = (char **)p;
7416 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
7417 return p_to;
7420 /* ----- servent */
7422 static struct WS_servent *WS_dup_se(const struct servent* p_se)
7424 char *p;
7425 struct WS_servent *p_to;
7427 int size = (sizeof(*p_se) +
7428 strlen(p_se->s_proto) + 1 +
7429 strlen(p_se->s_name) + 1 +
7430 list_size(p_se->s_aliases, 0));
7432 if (!(p_to = check_buffer_se(size))) return NULL;
7433 p_to->s_port = p_se->s_port;
7435 p = (char *)(p_to + 1);
7436 p_to->s_name = p;
7437 strcpy(p, p_se->s_name);
7438 p += strlen(p) + 1;
7440 p_to->s_proto = p;
7441 strcpy(p, p_se->s_proto);
7442 p += strlen(p) + 1;
7444 p_to->s_aliases = (char **)p;
7445 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
7446 return p_to;
7450 /***********************************************************************
7451 * WSARecv (WS2_32.67)
7453 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
7454 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
7455 LPWSAOVERLAPPED lpOverlapped,
7456 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
7458 return WS2_recv_base(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
7459 NULL, NULL, lpOverlapped, lpCompletionRoutine, NULL);
7462 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
7463 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
7464 struct WS_sockaddr *lpFrom,
7465 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
7466 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
7467 LPWSABUF lpControlBuffer )
7469 unsigned int i, options;
7470 int n, fd, err, overlapped, flags;
7471 struct ws2_async *wsa = NULL, localwsa;
7472 BOOL is_blocking;
7473 DWORD timeout_start = GetTickCount();
7474 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
7476 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
7477 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
7478 (lpFromlen ? *lpFromlen : -1),
7479 lpOverlapped, lpCompletionRoutine);
7481 fd = get_sock_fd( s, FILE_READ_DATA, &options );
7482 TRACE( "fd=%d, options=%x\n", fd, options );
7484 if (fd == -1) return SOCKET_ERROR;
7486 if (*lpFlags & WS_MSG_OOB)
7488 /* It's invalid to receive OOB data from an OOBINLINED socket
7489 * as OOB data is turned into normal data. */
7490 i = sizeof(n);
7491 if (!getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, (char*) &n, &i) && n)
7493 err = WSAEINVAL;
7494 goto error;
7498 overlapped = (lpOverlapped || lpCompletionRoutine) &&
7499 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
7500 if (overlapped || dwBufferCount > 1)
7502 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[dwBufferCount]))))
7504 err = WSAEFAULT;
7505 goto error;
7508 else
7509 wsa = &localwsa;
7511 wsa->hSocket = SOCKET2HANDLE(s);
7512 wsa->flags = *lpFlags;
7513 wsa->lpFlags = lpFlags;
7514 wsa->addr = lpFrom;
7515 wsa->addrlen.ptr = lpFromlen;
7516 wsa->control = lpControlBuffer;
7517 wsa->n_iovecs = dwBufferCount;
7518 wsa->first_iovec = 0;
7519 for (i = 0; i < dwBufferCount; i++)
7521 /* check buffer first to trigger write watches */
7522 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
7524 err = WSAEFAULT;
7525 goto error;
7527 wsa->iovec[i].iov_base = lpBuffers[i].buf;
7528 wsa->iovec[i].iov_len = lpBuffers[i].len;
7531 flags = convert_flags(wsa->flags);
7532 for (;;)
7534 n = WS2_recv( fd, wsa, flags );
7535 if (n == -1)
7537 /* Unix-like systems return EINVAL when attempting to read OOB data from
7538 * an empty socket buffer, convert that to a Windows expected return. */
7539 if ((flags & MSG_OOB) && errno == EINVAL)
7540 errno = EWOULDBLOCK;
7542 if (errno != EAGAIN)
7544 int loc_errno = errno;
7545 err = wsaErrno();
7546 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
7547 goto error;
7550 else if (lpNumberOfBytesRecvd) *lpNumberOfBytesRecvd = n;
7552 if (overlapped)
7554 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
7556 wsa->user_overlapped = lpOverlapped;
7557 wsa->completion_func = lpCompletionRoutine;
7558 release_sock_fd( s, fd );
7560 if (n == -1)
7562 iosb->u.Status = STATUS_PENDING;
7563 iosb->Information = 0;
7565 SERVER_START_REQ( register_async )
7567 req->type = ASYNC_TYPE_READ;
7568 req->async.handle = wine_server_obj_handle( wsa->hSocket );
7569 req->async.callback = wine_server_client_ptr( WS2_async_recv );
7570 req->async.iosb = wine_server_client_ptr( iosb );
7571 req->async.arg = wine_server_client_ptr( wsa );
7572 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
7573 req->async.cvalue = cvalue;
7574 err = wine_server_call( req );
7576 SERVER_END_REQ;
7578 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
7579 SetLastError(NtStatusToWSAError( err ));
7580 return SOCKET_ERROR;
7583 iosb->u.Status = STATUS_SUCCESS;
7584 iosb->Information = n;
7585 if (!wsa->completion_func)
7587 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
7588 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
7589 HeapFree( GetProcessHeap(), 0, wsa );
7591 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
7592 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
7593 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7594 return 0;
7597 if (n != -1) break;
7599 if ((err = _is_blocking( s, &is_blocking )))
7601 err = NtStatusToWSAError( err );
7602 goto error;
7605 if ( is_blocking )
7607 struct pollfd pfd;
7608 int poll_timeout = -1;
7609 INT64 timeout = get_rcvsnd_timeo(fd, TRUE);
7611 if (timeout)
7613 timeout -= GetTickCount() - timeout_start;
7614 if (timeout < 0) poll_timeout = 0;
7615 else poll_timeout = timeout <= INT_MAX ? timeout : INT_MAX;
7618 pfd.fd = fd;
7619 pfd.events = POLLIN;
7620 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
7622 if (!poll_timeout || !poll( &pfd, 1, poll_timeout ))
7624 err = WSAETIMEDOUT;
7625 /* a timeout is not fatal */
7626 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7627 goto error;
7630 else
7632 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7633 err = WSAEWOULDBLOCK;
7634 goto error;
7638 TRACE(" -> %i bytes\n", n);
7639 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
7640 release_sock_fd( s, fd );
7641 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7642 SetLastError(ERROR_SUCCESS);
7644 return 0;
7646 error:
7647 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
7648 release_sock_fd( s, fd );
7649 WARN(" -> ERROR %d\n", err);
7650 SetLastError( err );
7651 return SOCKET_ERROR;
7654 /***********************************************************************
7655 * WSARecvFrom (WS2_32.69)
7657 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
7658 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
7659 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
7660 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
7663 return WS2_recv_base( s, lpBuffers, dwBufferCount,
7664 lpNumberOfBytesRecvd, lpFlags,
7665 lpFrom, lpFromlen,
7666 lpOverlapped, lpCompletionRoutine, NULL );
7669 /***********************************************************************
7670 * WSCInstallProvider (WS2_32.88)
7672 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
7673 LPCWSTR lpszProviderDllPath,
7674 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
7675 DWORD dwNumberOfEntries,
7676 LPINT lpErrno )
7678 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
7679 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
7680 dwNumberOfEntries, lpErrno);
7681 *lpErrno = 0;
7682 return 0;
7686 /***********************************************************************
7687 * WSCDeinstallProvider (WS2_32.83)
7689 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
7691 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
7692 *lpErrno = 0;
7693 return 0;
7697 /***********************************************************************
7698 * WSAAccept (WS2_32.26)
7700 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
7701 LPCONDITIONPROC lpfnCondition, DWORD_PTR dwCallbackData)
7704 int ret = 0, size;
7705 WSABUF CallerId, CallerData, CalleeId, CalleeData;
7706 /* QOS SQOS, GQOS; */
7707 GROUP g;
7708 SOCKET cs;
7709 SOCKADDR src_addr, dst_addr;
7711 TRACE("socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
7712 s, addr, addrlen, lpfnCondition, dwCallbackData);
7714 cs = WS_accept(s, addr, addrlen);
7715 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
7716 if (!lpfnCondition) return cs;
7718 if (addr && addrlen)
7720 CallerId.buf = (char *)addr;
7721 CallerId.len = *addrlen;
7723 else
7725 size = sizeof(src_addr);
7726 WS_getpeername(cs, &src_addr, &size);
7727 CallerId.buf = (char *)&src_addr;
7728 CallerId.len = size;
7730 CallerData.buf = NULL;
7731 CallerData.len = 0;
7733 size = sizeof(dst_addr);
7734 WS_getsockname(cs, &dst_addr, &size);
7736 CalleeId.buf = (char *)&dst_addr;
7737 CalleeId.len = sizeof(dst_addr);
7739 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
7740 &CalleeId, &CalleeData, &g, dwCallbackData);
7742 switch (ret)
7744 case CF_ACCEPT:
7745 return cs;
7746 case CF_DEFER:
7747 SERVER_START_REQ( set_socket_deferred )
7749 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
7750 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
7751 if ( !wine_server_call_err ( req ) )
7753 SetLastError( WSATRY_AGAIN );
7754 WS_closesocket( cs );
7757 SERVER_END_REQ;
7758 return SOCKET_ERROR;
7759 case CF_REJECT:
7760 WS_closesocket(cs);
7761 SetLastError(WSAECONNREFUSED);
7762 return SOCKET_ERROR;
7763 default:
7764 FIXME("Unknown return type from Condition function\n");
7765 SetLastError(WSAENOTSOCK);
7766 return SOCKET_ERROR;
7770 /***********************************************************************
7771 * WSADuplicateSocketA (WS2_32.32)
7773 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
7775 return WS_DuplicateSocket(FALSE, s, dwProcessId, (LPWSAPROTOCOL_INFOW) lpProtocolInfo);
7778 /***********************************************************************
7779 * WSADuplicateSocketW (WS2_32.33)
7781 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
7783 return WS_DuplicateSocket(TRUE, s, dwProcessId, lpProtocolInfo);
7786 /***********************************************************************
7787 * WSAInstallServiceClassA (WS2_32.48)
7789 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
7791 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
7792 SetLastError(WSAEACCES);
7793 return SOCKET_ERROR;
7796 /***********************************************************************
7797 * WSAInstallServiceClassW (WS2_32.49)
7799 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
7801 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
7802 SetLastError(WSAEACCES);
7803 return SOCKET_ERROR;
7806 /***********************************************************************
7807 * WSARemoveServiceClass (WS2_32.70)
7809 int WINAPI WSARemoveServiceClass(LPGUID info)
7811 FIXME("Request to remove service %p\n",info);
7812 SetLastError(WSATYPE_NOT_FOUND);
7813 return SOCKET_ERROR;
7816 /***********************************************************************
7817 * inet_ntop (WS2_32.@)
7819 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
7821 #ifdef HAVE_INET_NTOP
7822 struct WS_in6_addr *in6;
7823 struct WS_in_addr *in;
7824 PCSTR pdst;
7826 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
7827 if (!buffer)
7829 SetLastError( STATUS_INVALID_PARAMETER );
7830 return NULL;
7833 switch (family)
7835 case WS_AF_INET:
7837 in = addr;
7838 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
7839 break;
7841 case WS_AF_INET6:
7843 in6 = addr;
7844 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
7845 break;
7847 default:
7848 SetLastError( WSAEAFNOSUPPORT );
7849 return NULL;
7852 if (!pdst) SetLastError( STATUS_INVALID_PARAMETER );
7853 return pdst;
7854 #else
7855 FIXME( "not supported on this platform\n" );
7856 SetLastError( WSAEAFNOSUPPORT );
7857 return NULL;
7858 #endif
7861 /***********************************************************************
7862 * inet_pton (WS2_32.@)
7864 INT WINAPI WS_inet_pton( INT family, PCSTR addr, PVOID buffer)
7866 #ifdef HAVE_INET_PTON
7867 int unixaf, ret;
7869 TRACE("family %d, addr %s, buffer (%p)\n", family, debugstr_a(addr), buffer);
7871 if (!addr || !buffer)
7873 SetLastError(WSAEFAULT);
7874 return SOCKET_ERROR;
7877 unixaf = convert_af_w2u(family);
7878 if (unixaf != AF_INET && unixaf != AF_INET6)
7880 SetLastError(WSAEAFNOSUPPORT);
7881 return SOCKET_ERROR;
7884 ret = inet_pton(unixaf, addr, buffer);
7885 if (ret == -1) SetLastError(wsaErrno());
7886 return ret;
7887 #else
7888 FIXME( "not supported on this platform\n" );
7889 SetLastError( WSAEAFNOSUPPORT );
7890 return SOCKET_ERROR;
7891 #endif
7894 /***********************************************************************
7895 * InetPtonW (WS2_32.@)
7897 INT WINAPI InetPtonW(INT family, PCWSTR addr, PVOID buffer)
7899 char *addrA;
7900 int len;
7901 INT ret;
7903 TRACE("family %d, addr %s, buffer (%p)\n", family, debugstr_w(addr), buffer);
7905 if (!addr)
7907 SetLastError(WSAEFAULT);
7908 return SOCKET_ERROR;
7911 len = WideCharToMultiByte(CP_ACP, 0, addr, -1, NULL, 0, NULL, NULL);
7912 if (!(addrA = HeapAlloc(GetProcessHeap(), 0, len)))
7914 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7915 return SOCKET_ERROR;
7917 WideCharToMultiByte(CP_ACP, 0, addr, -1, addrA, len, NULL, NULL);
7919 ret = WS_inet_pton(family, addrA, buffer);
7921 HeapFree(GetProcessHeap(), 0, addrA);
7922 return ret;
7925 /***********************************************************************
7926 * WSAStringToAddressA (WS2_32.80)
7928 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
7929 INT AddressFamily,
7930 LPWSAPROTOCOL_INFOA lpProtocolInfo,
7931 LPSOCKADDR lpAddress,
7932 LPINT lpAddressLength)
7934 INT res=0;
7935 LPSTR workBuffer=NULL,ptrPort;
7937 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
7938 lpProtocolInfo, lpAddress, lpAddressLength );
7940 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
7942 if (!AddressString)
7944 SetLastError(WSAEINVAL);
7945 return SOCKET_ERROR;
7948 if (lpProtocolInfo)
7949 FIXME("ProtocolInfo not implemented.\n");
7951 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
7952 strlen(AddressString) + 1);
7953 if (!workBuffer)
7955 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7956 return SOCKET_ERROR;
7959 strcpy(workBuffer, AddressString);
7961 switch(AddressFamily)
7963 case WS_AF_INET:
7965 struct in_addr inetaddr;
7967 /* If lpAddressLength is too small, tell caller the size we need */
7968 if (*lpAddressLength < sizeof(SOCKADDR_IN))
7970 *lpAddressLength = sizeof(SOCKADDR_IN);
7971 res = WSAEFAULT;
7972 break;
7974 *lpAddressLength = sizeof(SOCKADDR_IN);
7975 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
7977 ((LPSOCKADDR_IN)lpAddress)->sin_family = WS_AF_INET;
7979 ptrPort = strchr(workBuffer, ':');
7980 if(ptrPort)
7982 /* User may have entered an IPv6 and asked to parse as IPv4 */
7983 if(strchr(ptrPort + 1, ':'))
7985 res = WSAEINVAL;
7986 break;
7988 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
7989 *ptrPort = '\0';
7991 else
7993 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
7996 if(inet_aton(workBuffer, &inetaddr) > 0)
7998 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
7999 res = 0;
8001 else
8002 res = WSAEINVAL;
8004 break;
8007 case WS_AF_INET6:
8009 struct in6_addr inetaddr;
8010 /* If lpAddressLength is too small, tell caller the size we need */
8011 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
8013 *lpAddressLength = sizeof(SOCKADDR_IN6);
8014 res = WSAEFAULT;
8015 break;
8017 #ifdef HAVE_INET_PTON
8018 *lpAddressLength = sizeof(SOCKADDR_IN6);
8019 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
8021 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
8023 /* This one is a bit tricky. An IPv6 address contains colons, so the
8024 * check from IPv4 doesn't work like that. However, IPv6 addresses that
8025 * contain a port are written with braces like [fd12:3456:7890::1]:12345
8026 * so what we will do is to look for ']', check if the next char is a
8027 * colon, and if it is, parse the port as in IPv4. */
8029 ptrPort = strchr(workBuffer, ']');
8030 if(ptrPort && *(++ptrPort) == ':')
8032 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort+1));
8033 *ptrPort = '\0';
8035 else
8037 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
8040 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
8042 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
8043 sizeof(struct in6_addr));
8044 res = 0;
8046 else
8047 #endif /* HAVE_INET_PTON */
8048 res = WSAEINVAL;
8050 break;
8052 default:
8053 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
8054 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
8055 res = WSAEINVAL;
8058 HeapFree(GetProcessHeap(), 0, workBuffer);
8060 if (!res) return 0;
8061 SetLastError(res);
8062 return SOCKET_ERROR;
8065 /***********************************************************************
8066 * WSAStringToAddressW (WS2_32.81)
8068 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
8069 * If this should be the case, it would be required to map these digits
8070 * to Unicode digits (0-9) using FoldString first.
8072 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
8073 INT AddressFamily,
8074 LPWSAPROTOCOL_INFOW lpProtocolInfo,
8075 LPSOCKADDR lpAddress,
8076 LPINT lpAddressLength)
8078 INT sBuffer,res=0;
8079 LPSTR workBuffer=NULL;
8080 WSAPROTOCOL_INFOA infoA;
8081 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
8083 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
8084 lpAddress, lpAddressLength );
8086 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
8088 /* if ProtocolInfo is available - convert to ANSI variant */
8089 if (lpProtocolInfo)
8091 lpProtoInfoA = &infoA;
8092 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
8094 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
8095 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
8097 SetLastError(WSAEINVAL);
8098 return SOCKET_ERROR;
8102 if (AddressString)
8104 /* Translate AddressString to ANSI code page - assumes that only
8105 standard digits 0-9 are used with this API call */
8106 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
8107 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
8109 if (workBuffer)
8111 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
8112 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
8113 lpAddress,lpAddressLength);
8114 HeapFree( GetProcessHeap(), 0, workBuffer );
8115 return res;
8117 else
8118 res = WSA_NOT_ENOUGH_MEMORY;
8120 else
8121 res = WSAEINVAL;
8123 SetLastError(res);
8124 return SOCKET_ERROR;
8127 /***********************************************************************
8128 * WSAAddressToStringA (WS2_32.27)
8130 * See WSAAddressToStringW
8132 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
8133 LPWSAPROTOCOL_INFOA info, LPSTR string,
8134 LPDWORD lenstr )
8136 DWORD size;
8137 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
8138 CHAR *p;
8140 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
8142 if (!sockaddr) return SOCKET_ERROR;
8143 if (!string || !lenstr) return SOCKET_ERROR;
8145 switch(sockaddr->sa_family)
8147 case WS_AF_INET:
8148 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
8149 sprintf( buffer, "%u.%u.%u.%u:%u",
8150 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
8151 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
8152 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
8153 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
8154 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
8156 p = strchr( buffer, ':' );
8157 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
8158 break;
8160 case WS_AF_INET6:
8162 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
8163 size_t slen;
8165 buffer[0] = 0;
8166 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
8167 if ((sockaddr6->sin6_port))
8168 strcpy(buffer, "[");
8169 slen = strlen(buffer);
8170 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, &buffer[slen], sizeof(buffer) - slen))
8172 SetLastError(WSAEINVAL);
8173 return SOCKET_ERROR;
8175 if ((sockaddr6->sin6_scope_id))
8176 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
8177 if ((sockaddr6->sin6_port))
8178 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
8179 break;
8182 default:
8183 SetLastError(WSAEINVAL);
8184 return SOCKET_ERROR;
8187 size = strlen( buffer ) + 1;
8189 if (*lenstr < size)
8191 *lenstr = size;
8192 SetLastError(WSAEFAULT);
8193 return SOCKET_ERROR;
8196 TRACE("=> %s,%u bytes\n", debugstr_a(buffer), size);
8197 *lenstr = size;
8198 strcpy( string, buffer );
8199 return 0;
8202 /***********************************************************************
8203 * WSAAddressToStringW (WS2_32.28)
8205 * Convert a sockaddr address into a readable address string.
8207 * PARAMS
8208 * sockaddr [I] Pointer to a sockaddr structure.
8209 * len [I] Size of the sockaddr structure.
8210 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
8211 * string [I/O] Pointer to a buffer to receive the address string.
8212 * lenstr [I/O] Size of the receive buffer in WCHARs.
8214 * RETURNS
8215 * Success: 0
8216 * Failure: SOCKET_ERROR
8218 * NOTES
8219 * The 'info' parameter is ignored.
8221 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
8222 LPWSAPROTOCOL_INFOW info, LPWSTR string,
8223 LPDWORD lenstr )
8225 INT ret;
8226 DWORD size;
8227 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
8228 CHAR bufAddr[54];
8230 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
8232 size = *lenstr;
8233 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
8235 if (ret) return ret;
8237 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
8239 if (*lenstr < size)
8241 *lenstr = size;
8242 SetLastError(WSAEFAULT);
8243 return SOCKET_ERROR;
8246 TRACE("=> %s,%u bytes\n", debugstr_w(buffer), size);
8247 *lenstr = size;
8248 lstrcpyW( string, buffer );
8249 return 0;
8252 /***********************************************************************
8253 * WSAEnumNameSpaceProvidersA (WS2_32.34)
8255 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
8257 FIXME( "(%p %p) Stub!\n", len, buffer );
8258 return 0;
8261 /***********************************************************************
8262 * WSAEnumNameSpaceProvidersW (WS2_32.35)
8264 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
8266 FIXME( "(%p %p) Stub!\n", len, buffer );
8267 return 0;
8270 /***********************************************************************
8271 * WSAGetQOSByName (WS2_32.41)
8273 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
8275 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
8276 return FALSE;
8279 /***********************************************************************
8280 * WSAGetServiceClassInfoA (WS2_32.42)
8282 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
8283 LPWSASERVICECLASSINFOA info )
8285 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
8286 len, info );
8287 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8288 return SOCKET_ERROR;
8291 /***********************************************************************
8292 * WSAGetServiceClassInfoW (WS2_32.43)
8294 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
8295 LPWSASERVICECLASSINFOW info )
8297 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
8298 len, info );
8299 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8300 return SOCKET_ERROR;
8303 /***********************************************************************
8304 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
8306 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
8308 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
8309 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8310 return SOCKET_ERROR;
8313 /***********************************************************************
8314 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
8316 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
8318 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
8319 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8320 return SOCKET_ERROR;
8323 /***********************************************************************
8324 * WSALookupServiceBeginA (WS2_32.59)
8326 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
8327 DWORD dwControlFlags,
8328 LPHANDLE lphLookup)
8330 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
8331 lphLookup);
8332 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8333 return SOCKET_ERROR;
8336 /***********************************************************************
8337 * WSALookupServiceBeginW (WS2_32.60)
8339 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
8340 DWORD dwControlFlags,
8341 LPHANDLE lphLookup)
8343 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
8344 lphLookup);
8345 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8346 return SOCKET_ERROR;
8349 /***********************************************************************
8350 * WSALookupServiceEnd (WS2_32.61)
8352 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
8354 FIXME("(%p) Stub!\n", lookup );
8355 return 0;
8358 /***********************************************************************
8359 * WSALookupServiceNextA (WS2_32.62)
8361 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
8363 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
8364 SetLastError(WSA_E_NO_MORE);
8365 return SOCKET_ERROR;
8368 /***********************************************************************
8369 * WSALookupServiceNextW (WS2_32.63)
8371 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
8373 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
8374 SetLastError(WSA_E_NO_MORE);
8375 return SOCKET_ERROR;
8378 /***********************************************************************
8379 * WSANtohl (WS2_32.64)
8381 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
8383 TRACE( "(%04lx 0x%08x %p)\n", s, netlong, lphostlong );
8385 if (!lphostlong) return WSAEFAULT;
8387 *lphostlong = ntohl( netlong );
8388 return 0;
8391 /***********************************************************************
8392 * WSANtohs (WS2_32.65)
8394 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
8396 TRACE( "(%04lx 0x%08x %p)\n", s, netshort, lphostshort );
8398 if (!lphostshort) return WSAEFAULT;
8400 *lphostshort = ntohs( netshort );
8401 return 0;
8404 /***********************************************************************
8405 * WSAProviderConfigChange (WS2_32.66)
8407 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
8408 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
8410 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
8411 return SOCKET_ERROR;
8414 /***********************************************************************
8415 * WSARecvDisconnect (WS2_32.68)
8417 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
8419 TRACE( "(%04lx %p)\n", s, disconnectdata );
8421 return WS_shutdown( s, SD_RECEIVE );
8424 /***********************************************************************
8425 * WSASetServiceA (WS2_32.76)
8427 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
8429 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
8430 return 0;
8433 /***********************************************************************
8434 * WSASetServiceW (WS2_32.77)
8436 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
8438 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
8439 return 0;
8442 /***********************************************************************
8443 * WSCEnableNSProvider (WS2_32.84)
8445 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
8447 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
8448 return 0;
8451 /***********************************************************************
8452 * WSCGetProviderPath (WS2_32.86)
8454 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
8456 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
8458 if (!errcode || !provider || !len) return WSAEFAULT;
8460 *errcode = WSAEINVAL;
8461 return SOCKET_ERROR;
8464 /***********************************************************************
8465 * WSCInstallNameSpace (WS2_32.87)
8467 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
8468 DWORD version, LPGUID provider )
8470 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
8471 namespace, version, debugstr_guid(provider) );
8472 return 0;
8475 /***********************************************************************
8476 * WSCUnInstallNameSpace (WS2_32.89)
8478 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
8480 FIXME("(%p) Stub!\n", lpProviderId);
8481 return NO_ERROR;
8484 /***********************************************************************
8485 * WSCWriteProviderOrder (WS2_32.91)
8487 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
8489 FIXME("(%p 0x%08x) Stub!\n", entry, number);
8490 return 0;
8493 /***********************************************************************
8494 * WSANSPIoctl (WS2_32.91)
8496 INT WINAPI WSANSPIoctl( HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer,
8497 DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer,
8498 LPDWORD lpcbBytesReturned, LPWSACOMPLETION lpCompletion )
8500 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup, dwControlCode,
8501 lpvInBuffer, cbInBuffer, lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpCompletion);
8502 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8503 return SOCKET_ERROR;
8506 /*****************************************************************************
8507 * WSAEnumProtocolsA [WS2_32.@]
8509 * see function WSAEnumProtocolsW
8511 INT WINAPI WSAEnumProtocolsA( LPINT protocols, LPWSAPROTOCOL_INFOA buffer, LPDWORD len )
8513 return WS_EnumProtocols( FALSE, protocols, (LPWSAPROTOCOL_INFOW) buffer, len);
8516 /*****************************************************************************
8517 * WSAEnumProtocolsW [WS2_32.@]
8519 * Retrieves information about specified set of active network protocols.
8521 * PARAMS
8522 * protocols [I] Pointer to null-terminated array of protocol id's. NULL
8523 * retrieves information on all available protocols.
8524 * buffer [I] Pointer to a buffer to be filled with WSAPROTOCOL_INFO
8525 * structures.
8526 * len [I/O] Pointer to a variable specifying buffer size. On output
8527 * the variable holds the number of bytes needed when the
8528 * specified size is too small.
8530 * RETURNS
8531 * Success: number of WSAPROTOCOL_INFO structures in buffer.
8532 * Failure: SOCKET_ERROR
8534 * NOTES
8535 * NT4SP5 does not return SPX if protocols == NULL
8537 * BUGS
8538 * - NT4SP5 returns in addition these list of NETBIOS protocols
8539 * (address family 17), each entry two times one for socket type 2 and 5
8541 * iProtocol szProtocol
8542 * 0x80000000 \Device\NwlnkNb
8543 * 0xfffffffa \Device\NetBT_CBENT7
8544 * 0xfffffffb \Device\Nbf_CBENT7
8545 * 0xfffffffc \Device\NetBT_NdisWan5
8546 * 0xfffffffd \Device\NetBT_El9202
8547 * 0xfffffffe \Device\Nbf_El9202
8548 * 0xffffffff \Device\Nbf_NdisWan4
8550 * - there is no check that the operating system supports the returned
8551 * protocols
8553 INT WINAPI WSAEnumProtocolsW( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
8555 return WS_EnumProtocols( TRUE, protocols, buffer, len);
8558 /*****************************************************************************
8559 * WSCEnumProtocols [WS2_32.@]
8561 * PARAMS
8562 * protocols [I] Null-terminated array of iProtocol values.
8563 * buffer [O] Buffer of WSAPROTOCOL_INFOW structures.
8564 * len [I/O] Size of buffer on input/output.
8565 * errno [O] Error code.
8567 * RETURNS
8568 * Success: number of protocols to be reported on.
8569 * Failure: SOCKET_ERROR. error is in errno.
8571 * BUGS
8572 * Doesn't supply info on layered protocols.
8575 INT WINAPI WSCEnumProtocols( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len, LPINT err )
8577 INT ret = WSAEnumProtocolsW( protocols, buffer, len );
8579 if (ret == SOCKET_ERROR) *err = WSAENOBUFS;
8581 return ret;