d3d10core/tests: Remove dead code.
[wine.git] / dlls / ws2_32 / socket.c
blobf62c9cd63eafe946756d733b43e47e2421d63864
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;
3556 /***********************************************************************
3557 * getpeername (WS2_32.5)
3559 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
3561 int fd;
3562 int res;
3564 TRACE("socket %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
3566 fd = get_sock_fd( s, 0, NULL );
3567 res = SOCKET_ERROR;
3569 if (fd != -1)
3571 union generic_unix_sockaddr uaddr;
3572 socklen_t uaddrlen = sizeof(uaddr);
3574 if (getpeername(fd, &uaddr.addr, &uaddrlen) == 0)
3576 if (!name || !namelen)
3577 SetLastError(WSAEFAULT);
3578 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3579 /* The buffer was too small */
3580 SetLastError(WSAEFAULT);
3581 else
3583 res = 0;
3584 TRACE("=> %s\n", debugstr_sockaddr(name));
3587 else
3588 SetLastError(wsaErrno());
3589 release_sock_fd( s, fd );
3591 return res;
3594 /* When binding to an UDP address with filter support the getsockname call on the socket
3595 * will always return 0.0.0.0 instead of the filtered interface address. This function
3596 * checks if the socket is interface-bound on UDP and return the correct address.
3597 * This is required because applications often do a bind() with port zero followed by a
3598 * getsockname() to retrieve the port and address acquired.
3600 static void interface_bind_check(int fd, struct sockaddr_in *addr)
3602 #if !defined(IP_BOUND_IF) && !defined(LINUX_BOUND_IF)
3603 return;
3604 #else
3605 int ifindex;
3606 socklen_t len;
3608 /* Check for IPv4, address 0.0.0.0 and UDP socket */
3609 if (addr->sin_family != AF_INET || addr->sin_addr.s_addr != 0)
3610 return;
3611 if (_get_fd_type(fd) != SOCK_DGRAM)
3612 return;
3614 ifindex = -1;
3615 len = sizeof(ifindex);
3616 #if defined(IP_BOUND_IF)
3617 getsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &ifindex, &len);
3618 #elif defined(LINUX_BOUND_IF)
3619 getsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex, &len);
3620 if (ifindex > 0) ifindex = ntohl(ifindex);
3621 #endif
3622 if (ifindex > 0)
3624 PIP_ADAPTER_INFO adapters, adapter;
3625 DWORD adap_size;
3627 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
3628 return;
3629 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
3630 if (adapters && GetAdaptersInfo(adapters, &adap_size) == NO_ERROR)
3632 /* Search the IPv4 adapter list for the appropriate bound interface */
3633 for (adapter = adapters; adapter != NULL; adapter = adapter->Next)
3635 in_addr_t adapter_addr;
3636 if (adapter->Index != ifindex) continue;
3638 adapter_addr = inet_addr(adapter->IpAddressList.IpAddress.String);
3639 addr->sin_addr.s_addr = adapter_addr;
3640 TRACE("reporting interface address from adapter %d\n", ifindex);
3641 break;
3644 HeapFree(GetProcessHeap(), 0, adapters);
3646 #endif
3649 /***********************************************************************
3650 * getsockname (WS2_32.6)
3652 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
3654 int fd;
3655 int res;
3657 TRACE("socket %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
3659 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
3660 if( (name == NULL) || (namelen == NULL) )
3662 SetLastError( WSAEFAULT );
3663 return SOCKET_ERROR;
3666 fd = get_sock_fd( s, 0, NULL );
3667 res = SOCKET_ERROR;
3669 if (fd != -1)
3671 union generic_unix_sockaddr uaddr;
3672 socklen_t uaddrlen;
3673 int bound = is_fd_bound(fd, &uaddr, &uaddrlen);
3675 if (bound <= 0)
3677 SetLastError(bound == -1 ? wsaErrno() : WSAEINVAL);
3679 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3681 /* The buffer was too small */
3682 SetLastError(WSAEFAULT);
3684 else
3686 interface_bind_check(fd, (struct sockaddr_in*) &uaddr);
3687 if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3689 /* The buffer was too small */
3690 SetLastError(WSAEFAULT);
3692 else
3694 res = 0;
3695 TRACE("=> %s\n", debugstr_sockaddr(name));
3698 release_sock_fd( s, fd );
3700 return res;
3703 /***********************************************************************
3704 * getsockopt (WS2_32.7)
3706 INT WINAPI WS_getsockopt(SOCKET s, INT level,
3707 INT optname, char *optval, INT *optlen)
3709 int fd;
3710 INT ret = 0;
3712 TRACE("(socket %04lx, %s, optval %s, optlen %p (%d))\n", s,
3713 debugstr_sockopt(level, optname), debugstr_optval(optval, 0),
3714 optlen, optlen ? *optlen : 0);
3716 switch(level)
3718 case WS_SOL_SOCKET:
3720 switch(optname)
3722 /* Handle common cases. The special cases are below, sorted
3723 * alphabetically */
3724 case WS_SO_BROADCAST:
3725 case WS_SO_DEBUG:
3726 case WS_SO_KEEPALIVE:
3727 case WS_SO_OOBINLINE:
3728 case WS_SO_RCVBUF:
3729 case WS_SO_REUSEADDR:
3730 case WS_SO_SNDBUF:
3731 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3732 return SOCKET_ERROR;
3733 convert_sockopt(&level, &optname);
3734 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3736 SetLastError(wsaErrno());
3737 ret = SOCKET_ERROR;
3739 release_sock_fd( s, fd );
3740 return ret;
3741 case WS_SO_ACCEPTCONN:
3742 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3743 return SOCKET_ERROR;
3744 if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, optval, (socklen_t *)optlen) != 0 )
3746 SetLastError(wsaErrno());
3747 ret = SOCKET_ERROR;
3749 else
3751 /* BSD returns != 0 while Windows return exact == 1 */
3752 if (*(int *)optval) *(int *)optval = 1;
3754 release_sock_fd( s, fd );
3755 return ret;
3756 case WS_SO_BSP_STATE:
3758 int req_size, addr_size;
3759 WSAPROTOCOL_INFOW infow;
3760 CSADDR_INFO *csinfo;
3762 ret = ws_protocol_info(s, TRUE, &infow, &addr_size);
3763 if (ret)
3765 if (infow.iAddressFamily == WS_AF_INET)
3766 addr_size = sizeof(struct sockaddr_in);
3767 else if (infow.iAddressFamily == WS_AF_INET6)
3768 addr_size = sizeof(struct sockaddr_in6);
3769 else
3771 FIXME("Family %d is unsupported for SO_BSP_STATE\n", infow.iAddressFamily);
3772 SetLastError(WSAEAFNOSUPPORT);
3773 return SOCKET_ERROR;
3776 req_size = sizeof(CSADDR_INFO) + addr_size * 2;
3777 if (*optlen < req_size)
3779 ret = 0;
3780 SetLastError(WSAEFAULT);
3782 else
3784 union generic_unix_sockaddr uaddr;
3785 socklen_t uaddrlen;
3787 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3788 return SOCKET_ERROR;
3790 csinfo = (CSADDR_INFO*) optval;
3792 /* Check if the sock is bound */
3793 if (is_fd_bound(fd, &uaddr, &uaddrlen) == 1)
3795 csinfo->LocalAddr.lpSockaddr =
3796 (LPSOCKADDR) (optval + sizeof(CSADDR_INFO));
3797 ws_sockaddr_u2ws(&uaddr.addr, csinfo->LocalAddr.lpSockaddr, &addr_size);
3798 csinfo->LocalAddr.iSockaddrLength = addr_size;
3800 else
3802 csinfo->LocalAddr.lpSockaddr = NULL;
3803 csinfo->LocalAddr.iSockaddrLength = 0;
3806 /* Check if the sock is connected */
3807 if (!getpeername(fd, &uaddr.addr, &uaddrlen) &&
3808 is_sockaddr_bound(&uaddr.addr, uaddrlen))
3810 csinfo->RemoteAddr.lpSockaddr =
3811 (LPSOCKADDR) (optval + sizeof(CSADDR_INFO) + addr_size);
3812 ws_sockaddr_u2ws(&uaddr.addr, csinfo->RemoteAddr.lpSockaddr, &addr_size);
3813 csinfo->RemoteAddr.iSockaddrLength = addr_size;
3815 else
3817 csinfo->RemoteAddr.lpSockaddr = NULL;
3818 csinfo->RemoteAddr.iSockaddrLength = 0;
3821 csinfo->iSocketType = infow.iSocketType;
3822 csinfo->iProtocol = infow.iProtocol;
3823 release_sock_fd( s, fd );
3826 return ret ? 0 : SOCKET_ERROR;
3828 case WS_SO_DONTLINGER:
3830 struct linger lingval;
3831 socklen_t len = sizeof(struct linger);
3833 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
3835 SetLastError(WSAEFAULT);
3836 return SOCKET_ERROR;
3838 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3839 return SOCKET_ERROR;
3841 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
3843 SetLastError(wsaErrno());
3844 ret = SOCKET_ERROR;
3846 else
3848 *(BOOL *)optval = !lingval.l_onoff;
3849 *optlen = sizeof(BOOL);
3852 release_sock_fd( s, fd );
3853 return ret;
3856 case WS_SO_CONNECT_TIME:
3858 static int pretendtime = 0;
3859 struct WS_sockaddr addr;
3860 int len = sizeof(addr);
3862 if (!optlen || *optlen < sizeof(DWORD) || !optval)
3864 SetLastError(WSAEFAULT);
3865 return SOCKET_ERROR;
3867 if (WS_getpeername(s, &addr, &len) == SOCKET_ERROR)
3868 *(DWORD *)optval = ~0u;
3869 else
3871 if (!pretendtime) FIXME("WS_SO_CONNECT_TIME - faking results\n");
3872 *(DWORD *)optval = pretendtime++;
3874 *optlen = sizeof(DWORD);
3875 return ret;
3877 /* As mentioned in setsockopt, Windows ignores this, so we
3878 * always return true here */
3879 case WS_SO_DONTROUTE:
3880 if (!optlen || *optlen < sizeof(BOOL) || !optval)
3882 SetLastError(WSAEFAULT);
3883 return SOCKET_ERROR;
3885 *(BOOL *)optval = TRUE;
3886 *optlen = sizeof(BOOL);
3887 return 0;
3889 case WS_SO_ERROR:
3891 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3892 return SOCKET_ERROR;
3893 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, optval, (socklen_t *)optlen) != 0 )
3895 SetLastError(wsaErrno());
3896 ret = SOCKET_ERROR;
3898 release_sock_fd( s, fd );
3900 /* The wineserver may have swallowed the error before us */
3901 if (!ret && *(int*) optval == 0)
3903 int i, events[FD_MAX_EVENTS];
3904 _get_sock_errors(s, events);
3905 for (i = 0; i < FD_MAX_EVENTS; i++)
3907 if(events[i])
3909 events[i] = NtStatusToWSAError(events[i]);
3910 TRACE("returning SO_ERROR %d from wine server\n", events[i]);
3911 *(int*) optval = events[i];
3912 break;
3916 return ret;
3919 case WS_SO_LINGER:
3921 struct linger lingval;
3922 socklen_t len = sizeof(struct linger);
3924 /* struct linger and LINGER have different sizes */
3925 if (!optlen || *optlen < sizeof(LINGER) || !optval)
3927 SetLastError(WSAEFAULT);
3928 return SOCKET_ERROR;
3930 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3931 return SOCKET_ERROR;
3933 if (_get_fd_type(fd) == SOCK_DGRAM)
3935 SetLastError(WSAENOPROTOOPT);
3936 ret = SOCKET_ERROR;
3938 else if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0)
3940 SetLastError(wsaErrno());
3941 ret = SOCKET_ERROR;
3943 else
3945 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
3946 ((LINGER *)optval)->l_linger = lingval.l_linger;
3947 *optlen = sizeof(struct linger);
3950 release_sock_fd( s, fd );
3951 return ret;
3954 case WS_SO_MAX_MSG_SIZE:
3955 if (!optlen || *optlen < sizeof(int) || !optval)
3957 SetLastError(WSAEFAULT);
3958 return SOCKET_ERROR;
3960 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
3961 *(int *)optval = 65507;
3962 *optlen = sizeof(int);
3963 return 0;
3965 /* SO_OPENTYPE does not require a valid socket handle. */
3966 case WS_SO_OPENTYPE:
3967 if (!optlen || *optlen < sizeof(int) || !optval)
3969 SetLastError(WSAEFAULT);
3970 return SOCKET_ERROR;
3972 *(int *)optval = get_per_thread_data()->opentype;
3973 *optlen = sizeof(int);
3974 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
3975 return 0;
3976 case WS_SO_PROTOCOL_INFOA:
3977 case WS_SO_PROTOCOL_INFOW:
3979 int size;
3980 WSAPROTOCOL_INFOW infow;
3982 ret = ws_protocol_info(s, optname == WS_SO_PROTOCOL_INFOW, &infow, &size);
3983 if (ret)
3985 if (!optlen || !optval || *optlen < size)
3987 if(optlen) *optlen = size;
3988 ret = 0;
3989 SetLastError(WSAEFAULT);
3991 else
3992 memcpy(optval, &infow, size);
3994 return ret ? 0 : SOCKET_ERROR;
3996 case WS_SO_RCVTIMEO:
3997 case WS_SO_SNDTIMEO:
3999 INT64 timeout;
4001 if (!optlen || *optlen < sizeof(int)|| !optval)
4003 SetLastError(WSAEFAULT);
4004 return SOCKET_ERROR;
4006 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4007 return SOCKET_ERROR;
4009 timeout = get_rcvsnd_timeo(fd, optname == WS_SO_RCVTIMEO);
4010 *(int *)optval = timeout <= UINT_MAX ? timeout : UINT_MAX;
4012 release_sock_fd( s, fd );
4013 return ret;
4015 case WS_SO_TYPE:
4017 int sock_type;
4018 if (!optlen || *optlen < sizeof(int) || !optval)
4020 SetLastError(WSAEFAULT);
4021 return SOCKET_ERROR;
4023 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4024 return SOCKET_ERROR;
4026 sock_type = _get_fd_type(fd);
4027 if (sock_type == -1)
4029 SetLastError(wsaErrno());
4030 ret = SOCKET_ERROR;
4032 else
4033 (*(int *)optval) = convert_socktype_u2w(sock_type);
4035 release_sock_fd( s, fd );
4036 return ret;
4038 default:
4039 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
4040 SetLastError(WSAENOPROTOOPT);
4041 return SOCKET_ERROR;
4042 } /* end switch(optname) */
4043 }/* end case WS_SOL_SOCKET */
4044 #ifdef HAS_IPX
4045 case WS_NSPROTO_IPX:
4047 struct WS_sockaddr_ipx addr;
4048 IPX_ADDRESS_DATA *data;
4049 int namelen;
4050 switch(optname)
4052 case WS_IPX_PTYPE:
4053 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
4054 #ifdef SOL_IPX
4055 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (socklen_t *)optlen) == -1)
4057 ret = SOCKET_ERROR;
4059 #else
4061 struct ipx val;
4062 socklen_t len=sizeof(struct ipx);
4063 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
4064 ret = SOCKET_ERROR;
4065 else
4066 *optval = (int)val.ipx_pt;
4068 #endif
4069 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
4070 release_sock_fd( s, fd );
4071 return ret;
4073 case WS_IPX_ADDRESS:
4075 * On a Win2000 system with one network card there are usually
4076 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
4077 * Using this call you can then retrieve info about this all.
4078 * In case of Linux it is a bit different. Usually you have
4079 * only "one" device active and further it is not possible to
4080 * query things like the linkspeed.
4082 FIXME("IPX_ADDRESS\n");
4083 namelen = sizeof(struct WS_sockaddr_ipx);
4084 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
4085 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
4087 data = (IPX_ADDRESS_DATA*)optval;
4088 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
4089 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
4090 data->adapternum = 0;
4091 data->wan = FALSE; /* We are not on a wan for now .. */
4092 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
4093 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
4094 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
4095 * note 1MB = 1000kB in this case */
4096 return 0;
4098 case WS_IPX_MAX_ADAPTER_NUM:
4099 FIXME("IPX_MAX_ADAPTER_NUM\n");
4100 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
4101 return 0;
4103 default:
4104 FIXME("IPX optname:%x\n", optname);
4105 return SOCKET_ERROR;
4106 }/* end switch(optname) */
4107 } /* end case WS_NSPROTO_IPX */
4108 #endif
4110 #ifdef HAS_IRDA
4111 #define MAX_IRDA_DEVICES 10
4113 case WS_SOL_IRLMP:
4114 switch(optname)
4116 case WS_IRLMP_ENUMDEVICES:
4118 char buf[sizeof(struct irda_device_list) +
4119 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
4120 int res;
4121 socklen_t len = sizeof(buf);
4123 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4124 return SOCKET_ERROR;
4125 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
4126 release_sock_fd( s, fd );
4127 if (res < 0)
4129 SetLastError(wsaErrno());
4130 return SOCKET_ERROR;
4132 else
4134 struct irda_device_list *src = (struct irda_device_list *)buf;
4135 DEVICELIST *dst = (DEVICELIST *)optval;
4136 INT needed = sizeof(DEVICELIST);
4137 unsigned int i;
4139 if (src->len > 0)
4140 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
4141 if (*optlen < needed)
4143 SetLastError(WSAEFAULT);
4144 return SOCKET_ERROR;
4146 *optlen = needed;
4147 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
4148 dst->numDevice = src->len;
4149 for (i = 0; i < src->len; i++)
4151 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
4152 src->dev[i].saddr, src->dev[i].daddr,
4153 src->dev[i].info, src->dev[i].hints[0],
4154 src->dev[i].hints[1]);
4155 memcpy( dst->Device[i].irdaDeviceID,
4156 &src->dev[i].daddr,
4157 sizeof(dst->Device[i].irdaDeviceID) ) ;
4158 memcpy( dst->Device[i].irdaDeviceName,
4159 src->dev[i].info,
4160 sizeof(dst->Device[i].irdaDeviceName) ) ;
4161 memcpy( &dst->Device[i].irdaDeviceHints1,
4162 &src->dev[i].hints[0],
4163 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
4164 memcpy( &dst->Device[i].irdaDeviceHints2,
4165 &src->dev[i].hints[1],
4166 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
4167 dst->Device[i].irdaCharSet = src->dev[i].charset;
4169 return 0;
4172 default:
4173 FIXME("IrDA optname:0x%x\n", optname);
4174 return SOCKET_ERROR;
4176 break; /* case WS_SOL_IRLMP */
4177 #undef MAX_IRDA_DEVICES
4178 #endif
4180 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
4181 case WS_IPPROTO_TCP:
4182 switch(optname)
4184 case WS_TCP_NODELAY:
4185 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4186 return SOCKET_ERROR;
4187 convert_sockopt(&level, &optname);
4188 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
4190 SetLastError(wsaErrno());
4191 ret = SOCKET_ERROR;
4193 release_sock_fd( s, fd );
4194 return ret;
4196 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
4197 return SOCKET_ERROR;
4199 case WS_IPPROTO_IP:
4200 switch(optname)
4202 case WS_IP_ADD_MEMBERSHIP:
4203 case WS_IP_DROP_MEMBERSHIP:
4204 #ifdef IP_HDRINCL
4205 case WS_IP_HDRINCL:
4206 #endif
4207 case WS_IP_MULTICAST_IF:
4208 case WS_IP_MULTICAST_LOOP:
4209 case WS_IP_MULTICAST_TTL:
4210 case WS_IP_OPTIONS:
4211 #ifdef IP_PKTINFO
4212 case WS_IP_PKTINFO:
4213 #endif
4214 case WS_IP_TOS:
4215 case WS_IP_TTL:
4216 #ifdef IP_UNICAST_IF
4217 case WS_IP_UNICAST_IF:
4218 #endif
4219 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4220 return SOCKET_ERROR;
4221 convert_sockopt(&level, &optname);
4222 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
4224 SetLastError(wsaErrno());
4225 ret = SOCKET_ERROR;
4227 release_sock_fd( s, fd );
4228 return ret;
4229 case WS_IP_DONTFRAGMENT:
4230 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
4231 *(BOOL*)optval = FALSE;
4232 return 0;
4234 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
4235 return SOCKET_ERROR;
4237 case WS_IPPROTO_IPV6:
4238 switch(optname)
4240 #ifdef IPV6_ADD_MEMBERSHIP
4241 case WS_IPV6_ADD_MEMBERSHIP:
4242 #endif
4243 #ifdef IPV6_DROP_MEMBERSHIP
4244 case WS_IPV6_DROP_MEMBERSHIP:
4245 #endif
4246 case WS_IPV6_MULTICAST_IF:
4247 case WS_IPV6_MULTICAST_HOPS:
4248 case WS_IPV6_MULTICAST_LOOP:
4249 case WS_IPV6_UNICAST_HOPS:
4250 case WS_IPV6_V6ONLY:
4251 #ifdef IPV6_UNICAST_IF
4252 case WS_IPV6_UNICAST_IF:
4253 #endif
4254 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4255 return SOCKET_ERROR;
4256 convert_sockopt(&level, &optname);
4257 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
4259 SetLastError(wsaErrno());
4260 ret = SOCKET_ERROR;
4262 release_sock_fd( s, fd );
4263 return ret;
4264 case WS_IPV6_DONTFRAG:
4265 FIXME("WS_IPV6_DONTFRAG is always false!\n");
4266 *(BOOL*)optval = FALSE;
4267 return 0;
4269 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
4270 return SOCKET_ERROR;
4272 default:
4273 WARN("Unknown level: 0x%08x\n", level);
4274 SetLastError(WSAEINVAL);
4275 return SOCKET_ERROR;
4276 } /* end switch(level) */
4279 /***********************************************************************
4280 * htonl (WS2_32.8)
4282 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
4284 return htonl(hostlong);
4288 /***********************************************************************
4289 * htons (WS2_32.9)
4291 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
4293 return htons(hostshort);
4296 /***********************************************************************
4297 * WSAHtonl (WS2_32.46)
4298 * From MSDN description of error codes, this function should also
4299 * check if WinSock has been initialized and the socket is a valid
4300 * socket. But why? This function only translates a host byte order
4301 * u_long into a network byte order u_long...
4303 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
4305 if (lpnetlong)
4307 *lpnetlong = htonl(hostlong);
4308 return 0;
4310 SetLastError(WSAEFAULT);
4311 return SOCKET_ERROR;
4314 /***********************************************************************
4315 * WSAHtons (WS2_32.47)
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_short into a network byte order u_short...
4321 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
4324 if (lpnetshort)
4326 *lpnetshort = htons(hostshort);
4327 return 0;
4329 SetLastError(WSAEFAULT);
4330 return SOCKET_ERROR;
4334 /***********************************************************************
4335 * inet_addr (WS2_32.11)
4337 WS_u_long WINAPI WS_inet_addr(const char *cp)
4339 if (!cp) return INADDR_NONE;
4340 return inet_addr(cp);
4344 /***********************************************************************
4345 * ntohl (WS2_32.14)
4347 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
4349 return ntohl(netlong);
4353 /***********************************************************************
4354 * ntohs (WS2_32.15)
4356 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
4358 return ntohs(netshort);
4362 /***********************************************************************
4363 * inet_ntoa (WS2_32.12)
4365 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
4367 struct per_thread_data *data = get_per_thread_data();
4369 sprintf( data->ntoa_buffer, "%u.%u.%u.%u",
4370 (unsigned int)(ntohl( in.WS_s_addr ) >> 24 & 0xff),
4371 (unsigned int)(ntohl( in.WS_s_addr ) >> 16 & 0xff),
4372 (unsigned int)(ntohl( in.WS_s_addr ) >> 8 & 0xff),
4373 (unsigned int)(ntohl( in.WS_s_addr ) & 0xff) );
4375 return data->ntoa_buffer;
4378 static const char *debugstr_wsaioctl(DWORD ioctl)
4380 const char *buf_type, *family;
4382 switch(ioctl & 0x18000000)
4384 case WS_IOC_WS2:
4385 family = "IOC_WS2";
4386 break;
4387 case WS_IOC_PROTOCOL:
4388 family = "IOC_PROTOCOL";
4389 break;
4390 case WS_IOC_VENDOR:
4391 family = "IOC_VENDOR";
4392 break;
4393 default: /* WS_IOC_UNIX */
4395 BYTE size = (ioctl >> 16) & WS_IOCPARM_MASK;
4396 char x = (ioctl & 0xff00) >> 8;
4397 BYTE y = ioctl & 0xff;
4398 char args[14];
4400 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
4402 case WS_IOC_VOID:
4403 buf_type = "_IO";
4404 sprintf(args, "%d, %d", x, y);
4405 break;
4406 case WS_IOC_IN:
4407 buf_type = "_IOW";
4408 sprintf(args, "'%c', %d, %d", x, y, size);
4409 break;
4410 case WS_IOC_OUT:
4411 buf_type = "_IOR";
4412 sprintf(args, "'%c', %d, %d", x, y, size);
4413 break;
4414 default:
4415 buf_type = "?";
4416 sprintf(args, "'%c', %d, %d", x, y, size);
4417 break;
4419 return wine_dbg_sprintf("%s(%s)", buf_type, args);
4423 /* We are different from WS_IOC_UNIX. */
4424 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
4426 case WS_IOC_VOID:
4427 buf_type = "_WSAIO";
4428 break;
4429 case WS_IOC_INOUT:
4430 buf_type = "_WSAIORW";
4431 break;
4432 case WS_IOC_IN:
4433 buf_type = "_WSAIOW";
4434 break;
4435 case WS_IOC_OUT:
4436 buf_type = "_WSAIOR";
4437 break;
4438 default:
4439 buf_type = "?";
4440 break;
4443 return wine_dbg_sprintf("%s(%s, %d)", buf_type, family,
4444 (USHORT)(ioctl & 0xffff));
4447 /* do an ioctl call through the server */
4448 static DWORD server_ioctl_sock( SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size,
4449 LPVOID out_buff, DWORD out_size, LPDWORD ret_size,
4450 LPWSAOVERLAPPED overlapped,
4451 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
4453 HANDLE event = overlapped ? overlapped->hEvent : 0;
4454 HANDLE handle = SOCKET2HANDLE( s );
4455 struct ws2_async *wsa;
4456 NTSTATUS status;
4457 PIO_STATUS_BLOCK io;
4459 if (!(wsa = (struct ws2_async *)alloc_async_io( sizeof(*wsa) )))
4460 return WSA_NOT_ENOUGH_MEMORY;
4461 wsa->hSocket = handle;
4462 wsa->user_overlapped = overlapped;
4463 wsa->completion_func = completion;
4464 io = (overlapped ? (PIO_STATUS_BLOCK)overlapped : &wsa->local_iosb);
4466 status = NtDeviceIoControlFile( handle, event, ws2_async_apc, wsa, io, code,
4467 in_buff, in_size, out_buff, out_size );
4468 if (status == STATUS_NOT_SUPPORTED)
4470 FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
4471 code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
4473 else if (status == STATUS_SUCCESS)
4474 *ret_size = io->Information; /* "Information" is the size written to the output buffer */
4476 if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, wsa );
4478 return NtStatusToWSAError( status );
4481 /**********************************************************************
4482 * WSAIoctl (WS2_32.50)
4485 INT WINAPI WSAIoctl(SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size, LPVOID out_buff,
4486 DWORD out_size, LPDWORD ret_size, LPWSAOVERLAPPED overlapped,
4487 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
4489 int fd;
4490 DWORD status = 0, total = 0;
4492 TRACE("%04lx, %s, %p, %d, %p, %d, %p, %p, %p\n",
4493 s, debugstr_wsaioctl(code), in_buff, in_size, out_buff, out_size, ret_size, overlapped, completion);
4495 switch (code)
4497 case WS_FIONBIO:
4498 if (in_size != sizeof(WS_u_long) || IS_INTRESOURCE(in_buff))
4500 SetLastError(WSAEFAULT);
4501 return SOCKET_ERROR;
4503 TRACE("-> FIONBIO (%x)\n", *(WS_u_long*)in_buff);
4504 if (_get_sock_mask(s))
4506 /* AsyncSelect()'ed sockets are always nonblocking */
4507 if (!*(WS_u_long *)in_buff) status = WSAEINVAL;
4508 break;
4510 if (*(WS_u_long *)in_buff)
4511 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
4512 else
4513 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
4514 break;
4516 case WS_FIONREAD:
4518 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
4520 SetLastError(WSAEFAULT);
4521 return SOCKET_ERROR;
4523 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
4524 if (ioctl(fd, FIONREAD, out_buff ) == -1)
4525 status = wsaErrno();
4526 release_sock_fd( s, fd );
4527 break;
4530 case WS_SIOCATMARK:
4532 unsigned int oob = 0, atmark = 0;
4533 socklen_t oobsize = sizeof(int);
4534 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
4536 SetLastError(WSAEFAULT);
4537 return SOCKET_ERROR;
4539 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
4540 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
4541 if ((getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &oob, &oobsize ) == -1)
4542 || (!oob && ioctl(fd, SIOCATMARK, &atmark ) == -1))
4543 status = wsaErrno();
4544 else
4546 /* The SIOCATMARK value read from ioctl() is reversed
4547 * because BSD returns TRUE if it's in the OOB mark
4548 * while Windows returns TRUE if there are NO OOB bytes.
4550 (*(WS_u_long *) out_buff) = oob || !atmark;
4553 release_sock_fd( s, fd );
4554 break;
4557 case WS_FIOASYNC:
4558 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
4559 SetLastError(WSAEINVAL);
4560 return SOCKET_ERROR;
4562 case WS_SIO_GET_INTERFACE_LIST:
4564 INTERFACE_INFO* intArray = out_buff;
4565 DWORD size, numInt = 0, apiReturn;
4567 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
4569 if (!out_buff || !ret_size)
4571 SetLastError(WSAEFAULT);
4572 return SOCKET_ERROR;
4575 fd = get_sock_fd( s, 0, NULL );
4576 if (fd == -1) return SOCKET_ERROR;
4578 apiReturn = GetAdaptersInfo(NULL, &size);
4579 if (apiReturn == ERROR_BUFFER_OVERFLOW)
4581 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
4583 if (table)
4585 if (GetAdaptersInfo(table, &size) == NO_ERROR)
4587 PIP_ADAPTER_INFO ptr;
4589 for (ptr = table, numInt = 0; ptr; ptr = ptr->Next)
4591 unsigned int addr, mask, bcast;
4592 struct ifreq ifInfo;
4594 /* Skip interfaces without an IPv4 address. */
4595 if (ptr->IpAddressList.IpAddress.String[0] == '\0')
4596 continue;
4598 if ((numInt + 1)*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > out_size)
4600 WARN("Buffer too small = %u, out_size = %u\n", numInt + 1, out_size);
4601 status = WSAEFAULT;
4602 break;
4605 /* Socket Status Flags */
4606 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
4607 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
4609 ERR("Error obtaining status flags for socket!\n");
4610 status = WSAEINVAL;
4611 break;
4613 else
4615 /* set flags; the values of IFF_* are not the same
4616 under Linux and Windows, therefore must generate
4617 new flags */
4618 intArray->iiFlags = 0;
4619 if (ifInfo.ifr_flags & IFF_BROADCAST)
4620 intArray->iiFlags |= WS_IFF_BROADCAST;
4621 #ifdef IFF_POINTOPOINT
4622 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
4623 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
4624 #endif
4625 if (ifInfo.ifr_flags & IFF_LOOPBACK)
4626 intArray->iiFlags |= WS_IFF_LOOPBACK;
4627 if (ifInfo.ifr_flags & IFF_UP)
4628 intArray->iiFlags |= WS_IFF_UP;
4629 if (ifInfo.ifr_flags & IFF_MULTICAST)
4630 intArray->iiFlags |= WS_IFF_MULTICAST;
4633 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
4634 mask = inet_addr(ptr->IpAddressList.IpMask.String);
4635 bcast = addr | ~mask;
4636 intArray->iiAddress.AddressIn.sin_family = AF_INET;
4637 intArray->iiAddress.AddressIn.sin_port = 0;
4638 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
4639 addr;
4640 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
4641 intArray->iiNetmask.AddressIn.sin_port = 0;
4642 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
4643 mask;
4644 intArray->iiBroadcastAddress.AddressIn.sin_family =
4645 AF_INET;
4646 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
4647 intArray->iiBroadcastAddress.AddressIn.sin_addr.
4648 WS_s_addr = bcast;
4649 intArray++;
4650 numInt++;
4653 else
4655 ERR("Unable to get interface table!\n");
4656 status = WSAEINVAL;
4658 HeapFree(GetProcessHeap(),0,table);
4660 else status = WSAEINVAL;
4662 else if (apiReturn != ERROR_NO_DATA)
4664 ERR("Unable to get interface table!\n");
4665 status = WSAEINVAL;
4667 /* Calculate the size of the array being returned */
4668 total = sizeof(INTERFACE_INFO) * numInt;
4669 release_sock_fd( s, fd );
4670 break;
4673 case WS_SIO_ADDRESS_LIST_QUERY:
4675 DWORD size;
4677 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
4679 if (!ret_size)
4681 SetLastError(WSAEFAULT);
4682 return SOCKET_ERROR;
4685 if (out_size && out_size < FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[0]))
4687 *ret_size = 0;
4688 SetLastError(WSAEINVAL);
4689 return SOCKET_ERROR;
4692 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
4694 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
4695 SOCKET_ADDRESS_LIST *sa_list;
4696 SOCKADDR_IN *sockaddr;
4697 SOCKET_ADDRESS *sa;
4698 unsigned int i;
4699 DWORD num;
4701 if (!table || GetAdaptersInfo(table, &size))
4703 HeapFree(GetProcessHeap(), 0, table);
4704 status = WSAEINVAL;
4705 break;
4708 for (p = table, num = 0; p; p = p->Next)
4709 if (p->IpAddressList.IpAddress.String[0]) num++;
4711 total = FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[num]) + num * sizeof(*sockaddr);
4712 if (total > out_size || !out_buff)
4714 *ret_size = total;
4715 HeapFree(GetProcessHeap(), 0, table);
4716 status = WSAEFAULT;
4717 break;
4720 sa_list = out_buff;
4721 sa = sa_list->Address;
4722 sockaddr = (SOCKADDR_IN *)&sa[num];
4723 sa_list->iAddressCount = num;
4725 for (p = table, i = 0; p; p = p->Next)
4727 if (!p->IpAddressList.IpAddress.String[0]) continue;
4729 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
4730 sa[i].iSockaddrLength = sizeof(SOCKADDR);
4732 sockaddr[i].sin_family = AF_INET;
4733 sockaddr[i].sin_port = 0;
4734 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
4735 i++;
4738 HeapFree(GetProcessHeap(), 0, table);
4740 else
4742 WARN("unable to get IP address list\n");
4743 status = WSAEINVAL;
4745 break;
4748 case WS_SIO_FLUSH:
4749 FIXME("SIO_FLUSH: stub.\n");
4750 break;
4752 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
4754 static const GUID connectex_guid = WSAID_CONNECTEX;
4755 static const GUID disconnectex_guid = WSAID_DISCONNECTEX;
4756 static const GUID acceptex_guid = WSAID_ACCEPTEX;
4757 static const GUID getaccepexsockaddrs_guid = WSAID_GETACCEPTEXSOCKADDRS;
4758 static const GUID transmitfile_guid = WSAID_TRANSMITFILE;
4759 static const GUID transmitpackets_guid = WSAID_TRANSMITPACKETS;
4760 static const GUID wsarecvmsg_guid = WSAID_WSARECVMSG;
4761 static const GUID wsasendmsg_guid = WSAID_WSASENDMSG;
4763 if ( IsEqualGUID(&connectex_guid, in_buff) )
4765 *(LPFN_CONNECTEX *)out_buff = WS2_ConnectEx;
4766 break;
4768 else if ( IsEqualGUID(&disconnectex_guid, in_buff) )
4770 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented DisconnectEx\n");
4772 else if ( IsEqualGUID(&acceptex_guid, in_buff) )
4774 *(LPFN_ACCEPTEX *)out_buff = WS2_AcceptEx;
4775 break;
4777 else if ( IsEqualGUID(&getaccepexsockaddrs_guid, in_buff) )
4779 *(LPFN_GETACCEPTEXSOCKADDRS *)out_buff = WS2_GetAcceptExSockaddrs;
4780 break;
4782 else if ( IsEqualGUID(&transmitfile_guid, in_buff) )
4784 *(LPFN_TRANSMITFILE *)out_buff = WS2_TransmitFile;
4785 break;
4787 else if ( IsEqualGUID(&transmitpackets_guid, in_buff) )
4789 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitPackets\n");
4791 else if ( IsEqualGUID(&wsarecvmsg_guid, in_buff) )
4793 *(LPFN_WSARECVMSG *)out_buff = WS2_WSARecvMsg;
4794 break;
4796 else if ( IsEqualGUID(&wsasendmsg_guid, in_buff) )
4798 *(LPFN_WSASENDMSG *)out_buff = WSASendMsg;
4799 break;
4801 else
4802 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff));
4804 status = WSAEOPNOTSUPP;
4805 break;
4807 case WS_SIO_KEEPALIVE_VALS:
4809 struct tcp_keepalive *k;
4810 int keepalive, keepidle, keepintvl;
4812 if (!in_buff || in_size < sizeof(struct tcp_keepalive))
4814 SetLastError(WSAEFAULT);
4815 return SOCKET_ERROR;
4818 k = in_buff;
4819 keepalive = k->onoff ? 1 : 0;
4820 keepidle = max( 1, (k->keepalivetime + 500) / 1000 );
4821 keepintvl = max( 1, (k->keepaliveinterval + 500) / 1000 );
4823 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
4825 fd = get_sock_fd(s, 0, NULL);
4826 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
4827 status = WSAEINVAL;
4828 #if defined(TCP_KEEPIDLE) || defined(TCP_KEEPINTVL)
4829 /* these values need to be set only if SO_KEEPALIVE is enabled */
4830 else if(keepalive)
4832 #ifndef TCP_KEEPIDLE
4833 FIXME("ignoring keepalive timeout\n");
4834 #else
4835 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
4836 status = WSAEINVAL;
4837 else
4838 #endif
4839 #ifdef TCP_KEEPINTVL
4840 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
4841 status = WSAEINVAL;
4842 #else
4843 FIXME("ignoring keepalive interval\n");
4844 #endif
4846 #else
4847 else
4848 FIXME("ignoring keepalive interval and timeout\n");
4849 #endif
4850 release_sock_fd(s, fd);
4851 break;
4853 case WS_SIO_ROUTING_INTERFACE_QUERY:
4855 struct WS_sockaddr *daddr = (struct WS_sockaddr *)in_buff;
4856 struct WS_sockaddr_in *daddr_in = (struct WS_sockaddr_in *)daddr;
4857 struct WS_sockaddr_in *saddr_in = out_buff;
4858 MIB_IPFORWARDROW row;
4859 PMIB_IPADDRTABLE ipAddrTable = NULL;
4860 DWORD size, i, found_index;
4862 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
4864 if (!in_buff || in_size < sizeof(struct WS_sockaddr) ||
4865 !out_buff || out_size < sizeof(struct WS_sockaddr_in) || !ret_size)
4867 SetLastError(WSAEFAULT);
4868 return SOCKET_ERROR;
4870 if (daddr->sa_family != AF_INET)
4872 FIXME("unsupported address family %d\n", daddr->sa_family);
4873 status = WSAEAFNOSUPPORT;
4874 break;
4876 if (GetBestRoute(daddr_in->sin_addr.S_un.S_addr, 0, &row) != NOERROR ||
4877 GetIpAddrTable(NULL, &size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
4879 status = WSAEFAULT;
4880 break;
4882 ipAddrTable = HeapAlloc(GetProcessHeap(), 0, size);
4883 if (GetIpAddrTable(ipAddrTable, &size, FALSE))
4885 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4886 status = WSAEFAULT;
4887 break;
4889 for (i = 0, found_index = ipAddrTable->dwNumEntries;
4890 i < ipAddrTable->dwNumEntries; i++)
4892 if (ipAddrTable->table[i].dwIndex == row.dwForwardIfIndex)
4893 found_index = i;
4895 if (found_index == ipAddrTable->dwNumEntries)
4897 ERR("no matching IP address for interface %d\n",
4898 row.dwForwardIfIndex);
4899 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4900 status = WSAEFAULT;
4901 break;
4903 saddr_in->sin_family = AF_INET;
4904 saddr_in->sin_addr.S_un.S_addr = ipAddrTable->table[found_index].dwAddr;
4905 saddr_in->sin_port = 0;
4906 total = sizeof(struct WS_sockaddr_in);
4907 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4908 break;
4910 case WS_SIO_SET_COMPATIBILITY_MODE:
4911 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
4912 status = WSAEOPNOTSUPP;
4913 break;
4914 case WS_SIO_UDP_CONNRESET:
4915 FIXME("WS_SIO_UDP_CONNRESET stub\n");
4916 break;
4917 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
4918 SetLastError(WSAEOPNOTSUPP);
4919 return SOCKET_ERROR;
4920 default:
4921 status = WSAEOPNOTSUPP;
4922 break;
4925 if (status == WSAEOPNOTSUPP)
4927 status = server_ioctl_sock(s, code, in_buff, in_size, out_buff, out_size, &total,
4928 overlapped, completion);
4929 if (status != WSAEOPNOTSUPP)
4931 if (status == 0 || status == WSA_IO_PENDING)
4932 TRACE("-> %s request\n", debugstr_wsaioctl(code));
4933 else
4934 ERR("-> %s request failed with status 0x%x\n", debugstr_wsaioctl(code), status);
4936 /* overlapped and completion operations will be handled by the server */
4937 completion = NULL;
4938 overlapped = NULL;
4940 else
4941 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code));
4944 if (completion)
4946 FIXME( "completion routine %p not supported\n", completion );
4948 else if (overlapped)
4950 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
4951 overlapped->Internal = status;
4952 overlapped->InternalHigh = total;
4953 if (overlapped->hEvent) NtSetEvent( overlapped->hEvent, NULL );
4954 if (cvalue) WS_AddCompletion( HANDLE2SOCKET(s), cvalue, status, total );
4957 if (!status)
4959 if (ret_size) *ret_size = total;
4960 return 0;
4962 SetLastError( status );
4963 return SOCKET_ERROR;
4967 /***********************************************************************
4968 * ioctlsocket (WS2_32.10)
4970 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
4972 DWORD ret_size;
4973 return WSAIoctl( s, cmd, argp, sizeof(WS_u_long), argp, sizeof(WS_u_long), &ret_size, NULL, NULL );
4976 /***********************************************************************
4977 * listen (WS2_32.13)
4979 int WINAPI WS_listen(SOCKET s, int backlog)
4981 int fd = get_sock_fd( s, FILE_READ_DATA, NULL ), ret = SOCKET_ERROR;
4983 TRACE("socket %04lx, backlog %d\n", s, backlog);
4984 if (fd != -1)
4986 int bound = is_fd_bound(fd, NULL, NULL);
4988 if (bound <= 0)
4990 SetLastError(bound == -1 ? wsaErrno() : WSAEINVAL);
4992 else if (listen(fd, backlog) == 0)
4994 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
4995 FD_WINE_LISTENING,
4996 FD_CONNECT|FD_WINE_CONNECTED);
4997 ret = 0;
4999 else
5000 SetLastError(wsaErrno());
5001 release_sock_fd( s, fd );
5003 else
5004 SetLastError(WSAENOTSOCK);
5005 return ret;
5008 /***********************************************************************
5009 * recv (WS2_32.16)
5011 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
5013 DWORD n, dwFlags = flags;
5014 WSABUF wsabuf;
5016 wsabuf.len = len;
5017 wsabuf.buf = buf;
5019 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
5020 return SOCKET_ERROR;
5021 else
5022 return n;
5025 /***********************************************************************
5026 * recvfrom (WS2_32.17)
5028 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
5029 struct WS_sockaddr *from, int *fromlen)
5031 DWORD n, dwFlags = flags;
5032 WSABUF wsabuf;
5034 wsabuf.len = len;
5035 wsabuf.buf = buf;
5037 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL, NULL) == SOCKET_ERROR )
5038 return SOCKET_ERROR;
5039 else
5040 return n;
5043 /* allocate a poll array for the corresponding fd sets */
5044 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
5045 const WS_fd_set *exceptfds, int *count_ptr )
5047 unsigned int i, j = 0, count = 0;
5048 struct pollfd *fds;
5050 if (readfds) count += readfds->fd_count;
5051 if (writefds) count += writefds->fd_count;
5052 if (exceptfds) count += exceptfds->fd_count;
5053 *count_ptr = count;
5054 if (!count)
5056 SetLastError(WSAEINVAL);
5057 return NULL;
5059 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0]))))
5061 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
5062 return NULL;
5064 if (readfds)
5065 for (i = 0; i < readfds->fd_count; i++, j++)
5067 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
5068 if (fds[j].fd == -1) goto failed;
5069 fds[j].revents = 0;
5070 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1)
5072 fds[j].events = POLLIN;
5074 else
5076 release_sock_fd( readfds->fd_array[i], fds[j].fd );
5077 fds[j].fd = -1;
5078 fds[j].events = 0;
5081 if (writefds)
5082 for (i = 0; i < writefds->fd_count; i++, j++)
5084 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
5085 if (fds[j].fd == -1) goto failed;
5086 fds[j].revents = 0;
5087 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1 ||
5088 _get_fd_type(fds[j].fd) == SOCK_DGRAM)
5090 fds[j].events = POLLOUT;
5092 else
5094 release_sock_fd( writefds->fd_array[i], fds[j].fd );
5095 fds[j].fd = -1;
5096 fds[j].events = 0;
5099 if (exceptfds)
5100 for (i = 0; i < exceptfds->fd_count; i++, j++)
5102 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
5103 if (fds[j].fd == -1) goto failed;
5104 fds[j].revents = 0;
5105 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1)
5107 int oob_inlined = 0;
5108 socklen_t olen = sizeof(oob_inlined);
5110 fds[j].events = POLLHUP;
5112 /* Check if we need to test for urgent data or not */
5113 getsockopt(fds[j].fd, SOL_SOCKET, SO_OOBINLINE, (char*) &oob_inlined, &olen);
5114 if (!oob_inlined)
5115 fds[j].events |= POLLPRI;
5117 else
5119 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
5120 fds[j].fd = -1;
5121 fds[j].events = 0;
5124 return fds;
5126 failed:
5127 count = j;
5128 j = 0;
5129 if (readfds)
5130 for (i = 0; i < readfds->fd_count && j < count; i++, j++)
5131 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
5132 if (writefds)
5133 for (i = 0; i < writefds->fd_count && j < count; i++, j++)
5134 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
5135 if (exceptfds)
5136 for (i = 0; i < exceptfds->fd_count && j < count; i++, j++)
5137 if (fds[j].fd != -1) release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
5138 HeapFree( GetProcessHeap(), 0, fds );
5139 return NULL;
5142 /* release the file descriptor obtained in fd_sets_to_poll */
5143 /* must be called with the original fd_set arrays, before calling get_poll_results */
5144 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
5145 const WS_fd_set *exceptfds, struct pollfd *fds )
5147 unsigned int i, j = 0;
5149 if (readfds)
5151 for (i = 0; i < readfds->fd_count; i++, j++)
5152 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
5154 if (writefds)
5156 for (i = 0; i < writefds->fd_count; i++, j++)
5157 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
5159 if (exceptfds)
5161 for (i = 0; i < exceptfds->fd_count; i++, j++)
5163 if (fds[j].fd == -1) continue;
5164 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
5165 if (fds[j].revents & POLLHUP)
5167 int fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
5168 if (fd != -1)
5169 release_sock_fd( exceptfds->fd_array[i], fd );
5170 else
5171 fds[j].revents = 0;
5177 static int do_poll(struct pollfd *pollfds, int count, int timeout)
5179 struct timeval tv1, tv2;
5180 int ret, torig = timeout;
5182 if (timeout > 0) gettimeofday( &tv1, 0 );
5184 while ((ret = poll( pollfds, count, timeout )) < 0)
5186 if (errno != EINTR) break;
5187 if (timeout < 0) continue;
5188 if (timeout == 0) return 0;
5190 gettimeofday( &tv2, 0 );
5192 tv2.tv_sec -= tv1.tv_sec;
5193 tv2.tv_usec -= tv1.tv_usec;
5194 if (tv2.tv_usec < 0)
5196 tv2.tv_usec += 1000000;
5197 tv2.tv_sec -= 1;
5200 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
5201 if (timeout <= 0) return 0;
5203 return ret;
5206 /* map the poll results back into the Windows fd sets */
5207 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
5208 const struct pollfd *fds )
5210 const struct pollfd *poll_writefds = fds + (readfds ? readfds->fd_count : 0);
5211 const struct pollfd *poll_exceptfds = poll_writefds + (writefds ? writefds->fd_count : 0);
5212 unsigned int i, k, total = 0;
5214 if (readfds)
5216 for (i = k = 0; i < readfds->fd_count; i++)
5218 if (fds[i].revents ||
5219 (readfds == writefds && (poll_writefds[i].revents & POLLOUT) && !(poll_writefds[i].revents & POLLHUP)) ||
5220 (readfds == exceptfds && poll_exceptfds[i].revents))
5221 readfds->fd_array[k++] = readfds->fd_array[i];
5223 readfds->fd_count = k;
5224 total += k;
5226 if (writefds && writefds != readfds)
5228 for (i = k = 0; i < writefds->fd_count; i++)
5230 if (((poll_writefds[i].revents & POLLOUT) && !(poll_writefds[i].revents & POLLHUP)) ||
5231 (writefds == exceptfds && poll_exceptfds[i].revents))
5232 writefds->fd_array[k++] = writefds->fd_array[i];
5234 writefds->fd_count = k;
5235 total += k;
5237 if (exceptfds && exceptfds != readfds && exceptfds != writefds)
5239 for (i = k = 0; i < exceptfds->fd_count; i++)
5240 if (poll_exceptfds[i].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
5241 exceptfds->fd_count = k;
5242 total += k;
5244 return total;
5247 /***********************************************************************
5248 * select (WS2_32.18)
5250 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
5251 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
5252 const struct WS_timeval* ws_timeout)
5254 struct pollfd *pollfds;
5255 int count, ret, timeout = -1;
5257 TRACE("read %p, write %p, excp %p timeout %p\n",
5258 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
5260 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )))
5261 return SOCKET_ERROR;
5263 if (ws_timeout)
5264 timeout = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
5266 ret = do_poll(pollfds, count, timeout);
5267 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
5269 if (ret == -1) SetLastError(wsaErrno());
5270 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
5271 HeapFree( GetProcessHeap(), 0, pollfds );
5272 return ret;
5275 /***********************************************************************
5276 * WSAPoll
5278 int WINAPI WSAPoll(WSAPOLLFD *wfds, ULONG count, int timeout)
5280 int i, ret;
5281 struct pollfd *ufds;
5283 if (!count)
5285 SetLastError(WSAEINVAL);
5286 return SOCKET_ERROR;
5288 if (!wfds)
5290 SetLastError(WSAEFAULT);
5291 return SOCKET_ERROR;
5294 if (!(ufds = HeapAlloc(GetProcessHeap(), 0, count * sizeof(ufds[0]))))
5296 SetLastError(WSAENOBUFS);
5297 return SOCKET_ERROR;
5300 for (i = 0; i < count; i++)
5302 ufds[i].fd = get_sock_fd(wfds[i].fd, 0, NULL);
5303 ufds[i].events = convert_poll_w2u(wfds[i].events);
5304 ufds[i].revents = 0;
5307 ret = do_poll(ufds, count, timeout);
5309 for (i = 0; i < count; i++)
5311 if (ufds[i].fd != -1)
5313 release_sock_fd(wfds[i].fd, ufds[i].fd);
5314 wfds[i].revents = convert_poll_u2w(ufds[i].revents);
5316 else
5317 wfds[i].revents = WS_POLLNVAL;
5320 HeapFree(GetProcessHeap(), 0, ufds);
5321 return ret;
5324 /* helper to send completion messages for client-only i/o operation case */
5325 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
5326 ULONG Information )
5328 SERVER_START_REQ( add_fd_completion )
5330 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
5331 req->cvalue = CompletionValue;
5332 req->status = CompletionStatus;
5333 req->information = Information;
5334 wine_server_call( req );
5336 SERVER_END_REQ;
5340 /***********************************************************************
5341 * send (WS2_32.19)
5343 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
5345 DWORD n;
5346 WSABUF wsabuf;
5348 wsabuf.len = len;
5349 wsabuf.buf = (char*) buf;
5351 if ( WS2_sendto( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
5352 return SOCKET_ERROR;
5353 else
5354 return n;
5357 /***********************************************************************
5358 * WSASend (WS2_32.72)
5360 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5361 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
5362 LPWSAOVERLAPPED lpOverlapped,
5363 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5365 return WS2_sendto( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
5366 NULL, 0, lpOverlapped, lpCompletionRoutine );
5369 /***********************************************************************
5370 * WSASendDisconnect (WS2_32.73)
5372 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
5374 return WS_shutdown( s, SD_SEND );
5378 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5379 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
5380 const struct WS_sockaddr *to, int tolen,
5381 LPWSAOVERLAPPED lpOverlapped,
5382 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5384 unsigned int i, options;
5385 int n, fd, err, overlapped, flags;
5386 struct ws2_async *wsa = NULL, localwsa;
5387 int totalLength = 0;
5388 DWORD bytes_sent;
5389 BOOL is_blocking;
5391 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
5392 s, lpBuffers, dwBufferCount, dwFlags,
5393 to, tolen, lpOverlapped, lpCompletionRoutine);
5395 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
5396 TRACE( "fd=%d, options=%x\n", fd, options );
5398 if ( fd == -1 ) return SOCKET_ERROR;
5400 if (!lpOverlapped && !lpNumberOfBytesSent)
5402 err = WSAEFAULT;
5403 goto error;
5406 overlapped = (lpOverlapped || lpCompletionRoutine) &&
5407 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
5408 if (overlapped || dwBufferCount > 1)
5410 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[dwBufferCount]))))
5412 err = WSAEFAULT;
5413 goto error;
5416 else
5417 wsa = &localwsa;
5419 wsa->hSocket = SOCKET2HANDLE(s);
5420 wsa->addr = (struct WS_sockaddr *)to;
5421 wsa->addrlen.val = tolen;
5422 wsa->flags = dwFlags;
5423 wsa->lpFlags = &wsa->flags;
5424 wsa->control = NULL;
5425 wsa->n_iovecs = dwBufferCount;
5426 wsa->first_iovec = 0;
5427 for ( i = 0; i < dwBufferCount; i++ )
5429 wsa->iovec[i].iov_base = lpBuffers[i].buf;
5430 wsa->iovec[i].iov_len = lpBuffers[i].len;
5431 totalLength += lpBuffers[i].len;
5434 flags = convert_flags(dwFlags);
5435 n = WS2_send( fd, wsa, flags );
5436 if (n == -1 && errno != EAGAIN)
5438 err = wsaErrno();
5439 goto error;
5442 if (overlapped)
5444 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
5445 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
5447 wsa->user_overlapped = lpOverlapped;
5448 wsa->completion_func = lpCompletionRoutine;
5449 release_sock_fd( s, fd );
5451 if (n == -1 || n < totalLength)
5453 iosb->u.Status = STATUS_PENDING;
5454 iosb->Information = n == -1 ? 0 : n;
5456 SERVER_START_REQ( register_async )
5458 req->type = ASYNC_TYPE_WRITE;
5459 req->async.handle = wine_server_obj_handle( wsa->hSocket );
5460 req->async.callback = wine_server_client_ptr( WS2_async_send );
5461 req->async.iosb = wine_server_client_ptr( iosb );
5462 req->async.arg = wine_server_client_ptr( wsa );
5463 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
5464 req->async.cvalue = cvalue;
5465 err = wine_server_call( req );
5467 SERVER_END_REQ;
5469 /* Enable the event only after starting the async. The server will deliver it as soon as
5470 the async is done. */
5471 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
5473 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
5474 SetLastError(NtStatusToWSAError( err ));
5475 return SOCKET_ERROR;
5478 iosb->u.Status = STATUS_SUCCESS;
5479 iosb->Information = n;
5480 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = n;
5481 if (!wsa->completion_func)
5483 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
5484 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
5485 HeapFree( GetProcessHeap(), 0, wsa );
5487 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
5488 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
5489 SetLastError(ERROR_SUCCESS);
5490 return 0;
5493 if ((err = _is_blocking( s, &is_blocking )))
5495 err = NtStatusToWSAError( err );
5496 goto error;
5499 if ( is_blocking )
5501 /* On a blocking non-overlapped stream socket,
5502 * sending blocks until the entire buffer is sent. */
5503 DWORD timeout_start = GetTickCount();
5505 bytes_sent = n == -1 ? 0 : n;
5507 while (wsa->first_iovec < wsa->n_iovecs)
5509 struct pollfd pfd;
5510 int poll_timeout = -1;
5511 INT64 timeout = get_rcvsnd_timeo(fd, FALSE);
5513 if (timeout)
5515 timeout -= GetTickCount() - timeout_start;
5516 if (timeout < 0) poll_timeout = 0;
5517 else poll_timeout = timeout <= INT_MAX ? timeout : INT_MAX;
5520 pfd.fd = fd;
5521 pfd.events = POLLOUT;
5523 if (!poll_timeout || !poll( &pfd, 1, poll_timeout ))
5525 err = WSAETIMEDOUT;
5526 goto error; /* msdn says a timeout in send is fatal */
5529 n = WS2_send( fd, wsa, flags );
5530 if (n == -1 && errno != EAGAIN)
5532 err = wsaErrno();
5533 goto error;
5536 if (n >= 0)
5537 bytes_sent += n;
5540 else /* non-blocking */
5542 if (n < totalLength)
5543 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
5544 if (n == -1)
5546 err = WSAEWOULDBLOCK;
5547 goto error;
5549 bytes_sent = n;
5552 TRACE(" -> %i bytes\n", bytes_sent);
5554 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = bytes_sent;
5555 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
5556 release_sock_fd( s, fd );
5557 SetLastError(ERROR_SUCCESS);
5558 return 0;
5560 error:
5561 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
5562 release_sock_fd( s, fd );
5563 WARN(" -> ERROR %d\n", err);
5564 SetLastError(err);
5565 return SOCKET_ERROR;
5568 /***********************************************************************
5569 * WSASendTo (WS2_32.74)
5571 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5572 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
5573 const struct WS_sockaddr *to, int tolen,
5574 LPWSAOVERLAPPED lpOverlapped,
5575 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5577 return WS2_sendto( s, lpBuffers, dwBufferCount,
5578 lpNumberOfBytesSent, dwFlags,
5579 to, tolen,
5580 lpOverlapped, lpCompletionRoutine );
5583 /***********************************************************************
5584 * sendto (WS2_32.20)
5586 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
5587 const struct WS_sockaddr *to, int tolen)
5589 DWORD n;
5590 WSABUF wsabuf;
5592 wsabuf.len = len;
5593 wsabuf.buf = (char*) buf;
5595 if ( WS2_sendto(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
5596 return SOCKET_ERROR;
5597 else
5598 return n;
5601 /***********************************************************************
5602 * setsockopt (WS2_32.21)
5604 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
5605 const char *optval, int optlen)
5607 int fd;
5608 int woptval;
5609 struct linger linger;
5610 struct timeval tval;
5612 TRACE("(socket %04lx, %s, optval %s, optlen %d)\n", s,
5613 debugstr_sockopt(level, optname), debugstr_optval(optval, optlen),
5614 optlen);
5616 /* some broken apps pass the value directly instead of a pointer to it */
5617 if(optlen && IS_INTRESOURCE(optval))
5619 SetLastError(WSAEFAULT);
5620 return SOCKET_ERROR;
5623 switch(level)
5625 case WS_SOL_SOCKET:
5626 switch(optname)
5628 /* Some options need some conversion before they can be sent to
5629 * setsockopt. The conversions are done here, then they will fall through
5630 * to the general case. Special options that are not passed to
5631 * setsockopt follow below that.*/
5633 case WS_SO_DONTLINGER:
5634 if (!optval)
5636 SetLastError(WSAEFAULT);
5637 return SOCKET_ERROR;
5639 linger.l_onoff = *(const int*)optval == 0;
5640 linger.l_linger = 0;
5641 level = SOL_SOCKET;
5642 optname = SO_LINGER;
5643 optval = (char*)&linger;
5644 optlen = sizeof(struct linger);
5645 break;
5647 case WS_SO_LINGER:
5648 if (!optval)
5650 SetLastError(WSAEFAULT);
5651 return SOCKET_ERROR;
5653 linger.l_onoff = ((LINGER*)optval)->l_onoff;
5654 linger.l_linger = ((LINGER*)optval)->l_linger;
5655 level = SOL_SOCKET;
5656 optname = SO_LINGER;
5657 optval = (char*)&linger;
5658 optlen = sizeof(struct linger);
5659 break;
5661 case WS_SO_RCVBUF:
5662 if (*(const int*)optval < 2048)
5664 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
5665 return 0;
5667 /* Fall through */
5669 /* The options listed here don't need any special handling. Thanks to
5670 * the conversion happening above, options from there will fall through
5671 * to this, too.*/
5672 case WS_SO_ACCEPTCONN:
5673 case WS_SO_BROADCAST:
5674 case WS_SO_ERROR:
5675 case WS_SO_KEEPALIVE:
5676 case WS_SO_OOBINLINE:
5677 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
5678 * however, using it the BSD way fixes bug 8513 and seems to be what
5679 * most programmers assume, anyway */
5680 case WS_SO_REUSEADDR:
5681 case WS_SO_SNDBUF:
5682 case WS_SO_TYPE:
5683 convert_sockopt(&level, &optname);
5684 break;
5686 /* SO_DEBUG is a privileged operation, ignore it. */
5687 case WS_SO_DEBUG:
5688 TRACE("Ignoring SO_DEBUG\n");
5689 return 0;
5691 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
5692 * socket. According to MSDN, this option is silently ignored.*/
5693 case WS_SO_DONTROUTE:
5694 TRACE("Ignoring SO_DONTROUTE\n");
5695 return 0;
5697 /* Stops two sockets from being bound to the same port. Always happens
5698 * on unix systems, so just drop it. */
5699 case WS_SO_EXCLUSIVEADDRUSE:
5700 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
5701 return 0;
5703 /* After a ConnectEx call succeeds, the socket can't be used with half of the
5704 * normal winsock functions on windows. We don't have that problem. */
5705 case WS_SO_UPDATE_CONNECT_CONTEXT:
5706 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
5707 return 0;
5709 /* After a AcceptEx call succeeds, the socket can't be used with half of the
5710 * normal winsock functions on windows. We don't have that problem. */
5711 case WS_SO_UPDATE_ACCEPT_CONTEXT:
5712 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
5713 return 0;
5715 /* SO_OPENTYPE does not require a valid socket handle. */
5716 case WS_SO_OPENTYPE:
5717 if (!optlen || optlen < sizeof(int) || !optval)
5719 SetLastError(WSAEFAULT);
5720 return SOCKET_ERROR;
5722 get_per_thread_data()->opentype = *(const int *)optval;
5723 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
5724 return 0;
5726 #ifdef SO_RCVTIMEO
5727 case WS_SO_RCVTIMEO:
5728 #endif
5729 #ifdef SO_SNDTIMEO
5730 case WS_SO_SNDTIMEO:
5731 #endif
5732 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
5733 if (optval && optlen == sizeof(UINT32)) {
5734 /* WinSock passes milliseconds instead of struct timeval */
5735 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
5736 tval.tv_sec = *(const UINT32*)optval / 1000;
5737 /* min of 500 milliseconds */
5738 if (tval.tv_sec == 0 && tval.tv_usec && tval.tv_usec < 500000)
5739 tval.tv_usec = 500000;
5740 optlen = sizeof(struct timeval);
5741 optval = (char*)&tval;
5742 } else if (optlen == sizeof(struct timeval)) {
5743 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
5744 } else {
5745 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
5746 return 0;
5748 convert_sockopt(&level, &optname);
5749 break;
5750 #endif
5752 default:
5753 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
5754 SetLastError(WSAENOPROTOOPT);
5755 return SOCKET_ERROR;
5757 break; /* case WS_SOL_SOCKET */
5759 #ifdef HAS_IPX
5760 case WS_NSPROTO_IPX:
5761 switch(optname)
5763 case WS_IPX_PTYPE:
5764 return set_ipx_packettype(s, *(int*)optval);
5766 case WS_IPX_FILTERPTYPE:
5767 /* Sets the receive filter packet type, at the moment we don't support it */
5768 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
5769 /* Returning 0 is better for now than returning a SOCKET_ERROR */
5770 return 0;
5772 default:
5773 FIXME("opt_name:%x\n", optname);
5774 return SOCKET_ERROR;
5776 break; /* case WS_NSPROTO_IPX */
5777 #endif
5779 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
5780 case WS_IPPROTO_TCP:
5781 switch(optname)
5783 case WS_TCP_NODELAY:
5784 convert_sockopt(&level, &optname);
5785 break;
5786 default:
5787 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
5788 return SOCKET_ERROR;
5790 break;
5792 case WS_IPPROTO_IP:
5793 switch(optname)
5795 case WS_IP_ADD_MEMBERSHIP:
5796 case WS_IP_DROP_MEMBERSHIP:
5797 #ifdef IP_HDRINCL
5798 case WS_IP_HDRINCL:
5799 #endif
5800 case WS_IP_MULTICAST_IF:
5801 case WS_IP_MULTICAST_LOOP:
5802 case WS_IP_MULTICAST_TTL:
5803 case WS_IP_OPTIONS:
5804 #ifdef IP_PKTINFO
5805 case WS_IP_PKTINFO:
5806 #endif
5807 case WS_IP_TOS:
5808 case WS_IP_TTL:
5809 #ifdef IP_UNICAST_IF
5810 case WS_IP_UNICAST_IF:
5811 #endif
5812 convert_sockopt(&level, &optname);
5813 break;
5814 case WS_IP_DONTFRAGMENT:
5815 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
5816 return 0;
5817 default:
5818 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
5819 return SOCKET_ERROR;
5821 break;
5823 case WS_IPPROTO_IPV6:
5824 switch(optname)
5826 #ifdef IPV6_ADD_MEMBERSHIP
5827 case WS_IPV6_ADD_MEMBERSHIP:
5828 #endif
5829 #ifdef IPV6_DROP_MEMBERSHIP
5830 case WS_IPV6_DROP_MEMBERSHIP:
5831 #endif
5832 case WS_IPV6_MULTICAST_IF:
5833 case WS_IPV6_MULTICAST_HOPS:
5834 case WS_IPV6_MULTICAST_LOOP:
5835 case WS_IPV6_UNICAST_HOPS:
5836 case WS_IPV6_V6ONLY:
5837 #ifdef IPV6_UNICAST_IF
5838 case WS_IPV6_UNICAST_IF:
5839 #endif
5840 convert_sockopt(&level, &optname);
5841 break;
5842 case WS_IPV6_DONTFRAG:
5843 FIXME("IPV6_DONTFRAG is silently ignored!\n");
5844 return 0;
5845 case WS_IPV6_PROTECTION_LEVEL:
5846 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
5847 return 0;
5848 default:
5849 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
5850 return SOCKET_ERROR;
5852 break;
5854 default:
5855 WARN("Unknown level: 0x%08x\n", level);
5856 SetLastError(WSAEINVAL);
5857 return SOCKET_ERROR;
5858 } /* end switch(level) */
5860 /* avoid endianness issues if argument is a 16-bit int */
5861 if (optval && optlen < sizeof(int))
5863 woptval= *((const INT16 *) optval);
5864 optval= (char*) &woptval;
5865 woptval&= (1 << optlen * 8) - 1;
5866 optlen=sizeof(int);
5868 fd = get_sock_fd( s, 0, NULL );
5869 if (fd == -1) return SOCKET_ERROR;
5871 if (setsockopt(fd, level, optname, optval, optlen) == 0)
5873 #ifdef __APPLE__
5874 if (level == SOL_SOCKET && optname == SO_REUSEADDR &&
5875 setsockopt(fd, level, SO_REUSEPORT, optval, optlen) != 0)
5877 SetLastError(wsaErrno());
5878 release_sock_fd( s, fd );
5879 return SOCKET_ERROR;
5881 #endif
5882 release_sock_fd( s, fd );
5883 return 0;
5885 TRACE("Setting socket error, %d\n", wsaErrno());
5886 SetLastError(wsaErrno());
5887 release_sock_fd( s, fd );
5889 return SOCKET_ERROR;
5892 /***********************************************************************
5893 * shutdown (WS2_32.22)
5895 int WINAPI WS_shutdown(SOCKET s, int how)
5897 int fd, err = WSAENOTSOCK;
5898 unsigned int options = 0, clear_flags = 0;
5900 fd = get_sock_fd( s, 0, &options );
5901 TRACE("socket %04lx, how 0x%x, options 0x%x\n", s, how, options );
5903 if (fd == -1)
5904 return SOCKET_ERROR;
5906 switch( how )
5908 case SD_RECEIVE: /* drop receives */
5909 clear_flags |= FD_READ;
5910 break;
5911 case SD_SEND: /* drop sends */
5912 clear_flags |= FD_WRITE;
5913 break;
5914 case SD_BOTH: /* drop all */
5915 clear_flags |= FD_READ|FD_WRITE;
5916 /*fall through */
5917 default:
5918 clear_flags |= FD_WINE_LISTENING;
5921 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
5923 switch ( how )
5925 case SD_RECEIVE:
5926 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
5927 break;
5928 case SD_SEND:
5929 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
5930 break;
5931 case SD_BOTH:
5932 default:
5933 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
5934 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
5935 break;
5937 if (err) goto error;
5939 else /* non-overlapped mode */
5941 if ( shutdown( fd, how ) )
5943 err = wsaErrno();
5944 goto error;
5948 release_sock_fd( s, fd );
5949 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
5950 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
5951 return 0;
5953 error:
5954 release_sock_fd( s, fd );
5955 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
5956 SetLastError( err );
5957 return SOCKET_ERROR;
5960 /***********************************************************************
5961 * socket (WS2_32.23)
5963 SOCKET WINAPI WS_socket(int af, int type, int protocol)
5965 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
5967 return WSASocketW( af, type, protocol, NULL, 0,
5968 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
5972 /***********************************************************************
5973 * gethostbyaddr (WS2_32.51)
5975 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
5977 struct WS_hostent *retval = NULL;
5978 struct hostent* host;
5979 int unixtype = convert_af_w2u(type);
5980 const char *paddr = addr;
5981 unsigned long loopback;
5982 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5983 char *extrabuf;
5984 int ebufsize = 1024;
5985 struct hostent hostentry;
5986 int locerr = ENOBUFS;
5987 #endif
5989 /* convert back the magic loopback address if necessary */
5990 if (unixtype == AF_INET && len == 4 && !memcmp(addr, magic_loopback_addr, 4))
5992 loopback = htonl(INADDR_LOOPBACK);
5993 paddr = (char*) &loopback;
5996 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5997 host = NULL;
5998 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
5999 while(extrabuf) {
6000 int res = gethostbyaddr_r(paddr, len, unixtype,
6001 &hostentry, extrabuf, ebufsize, &host, &locerr);
6002 if (res != ERANGE) break;
6003 ebufsize *=2;
6004 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
6006 if (host) retval = WS_dup_he(host);
6007 else SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
6008 HeapFree(GetProcessHeap(),0,extrabuf);
6009 #else
6010 EnterCriticalSection( &csWSgetXXXbyYYY );
6011 host = gethostbyaddr(paddr, len, unixtype);
6012 if (host) retval = WS_dup_he(host);
6013 else SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
6014 LeaveCriticalSection( &csWSgetXXXbyYYY );
6015 #endif
6016 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
6017 return retval;
6020 /***********************************************************************
6021 * WS_compare_routes_by_metric_asc (INTERNAL)
6023 * Comparison function for qsort(), for sorting two routes (struct route)
6024 * by metric in ascending order.
6026 static int WS_compare_routes_by_metric_asc(const void *left, const void *right)
6028 return ((const struct route*)left)->metric - ((const struct route*)right)->metric;
6031 /***********************************************************************
6032 * WS_get_local_ips (INTERNAL)
6034 * Returns the list of local IP addresses by going through the network
6035 * adapters and using the local routing table to sort the addresses
6036 * from highest routing priority to lowest routing priority. This
6037 * functionality is inferred from the description for obtaining local
6038 * IP addresses given in the Knowledge Base Article Q160215.
6040 * Please note that the returned hostent is only freed when the thread
6041 * closes and is replaced if another hostent is requested.
6043 static struct WS_hostent* WS_get_local_ips( char *hostname )
6045 int numroutes = 0, i, j;
6046 DWORD n;
6047 PIP_ADAPTER_INFO adapters = NULL, k;
6048 struct WS_hostent *hostlist = NULL;
6049 PMIB_IPFORWARDTABLE routes = NULL;
6050 struct route *route_addrs = NULL;
6051 DWORD adap_size, route_size;
6053 /* Obtain the size of the adapter list and routing table, also allocate memory */
6054 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
6055 return NULL;
6056 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
6057 return NULL;
6058 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
6059 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
6060 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
6061 if (adapters == NULL || routes == NULL || route_addrs == NULL)
6062 goto cleanup;
6063 /* Obtain the adapter list and the full routing table */
6064 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
6065 goto cleanup;
6066 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
6067 goto cleanup;
6068 /* Store the interface associated with each route */
6069 for (n = 0; n < routes->dwNumEntries; n++)
6071 IF_INDEX ifindex;
6072 DWORD ifmetric;
6073 BOOL exists = FALSE;
6075 if (routes->table[n].u1.ForwardType != MIB_IPROUTE_TYPE_DIRECT)
6076 continue;
6077 ifindex = routes->table[n].dwForwardIfIndex;
6078 ifmetric = routes->table[n].dwForwardMetric1;
6079 /* Only store the lowest valued metric for an interface */
6080 for (j = 0; j < numroutes; j++)
6082 if (route_addrs[j].interface == ifindex)
6084 if (route_addrs[j].metric > ifmetric)
6085 route_addrs[j].metric = ifmetric;
6086 exists = TRUE;
6089 if (exists)
6090 continue;
6091 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
6092 if (route_addrs == NULL)
6093 goto cleanup; /* Memory allocation error, fail gracefully */
6094 route_addrs[numroutes].interface = ifindex;
6095 route_addrs[numroutes].metric = ifmetric;
6096 /* If no IP is found in the next step (for whatever reason)
6097 * then fall back to the magic loopback address.
6099 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
6100 numroutes++;
6102 if (numroutes == 0)
6103 goto cleanup; /* No routes, fall back to the Magic IP */
6104 /* Find the IP address associated with each found interface */
6105 for (i = 0; i < numroutes; i++)
6107 for (k = adapters; k != NULL; k = k->Next)
6109 char *ip = k->IpAddressList.IpAddress.String;
6111 if (route_addrs[i].interface == k->Index)
6112 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
6115 /* Allocate a hostent and enough memory for all the IPs,
6116 * including the NULL at the end of the list.
6118 hostlist = WS_create_he(hostname, 1, 0, numroutes+1, sizeof(struct in_addr));
6119 if (hostlist == NULL)
6120 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
6121 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
6122 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
6123 hostlist->h_addrtype = AF_INET;
6124 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
6125 /* Reorder the entries before placing them in the host list. Windows expects
6126 * the IP list in order from highest priority to lowest (the critical thing
6127 * is that most applications expect the first IP to be the default route).
6129 if (numroutes > 1)
6130 qsort(route_addrs, numroutes, sizeof(struct route), WS_compare_routes_by_metric_asc);
6132 for (i = 0; i < numroutes; i++)
6133 (*(struct in_addr *) hostlist->h_addr_list[i]) = route_addrs[i].addr;
6135 /* Cleanup all allocated memory except the address list,
6136 * the address list is used by the calling app.
6138 cleanup:
6139 HeapFree(GetProcessHeap(), 0, route_addrs);
6140 HeapFree(GetProcessHeap(), 0, adapters);
6141 HeapFree(GetProcessHeap(), 0, routes);
6142 return hostlist;
6145 /***********************************************************************
6146 * gethostbyname (WS2_32.52)
6148 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
6150 struct WS_hostent *retval = NULL;
6151 struct hostent* host;
6152 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6153 char *extrabuf;
6154 int ebufsize=1024;
6155 struct hostent hostentry;
6156 int locerr = ENOBUFS;
6157 #endif
6158 char hostname[100];
6159 if(!num_startup) {
6160 SetLastError(WSANOTINITIALISED);
6161 return NULL;
6163 if( gethostname( hostname, 100) == -1) {
6164 SetLastError(WSAENOBUFS); /* appropriate ? */
6165 return retval;
6167 if( !name || !name[0]) {
6168 name = hostname;
6170 /* If the hostname of the local machine is requested then return the
6171 * complete list of local IP addresses */
6172 if(strcmp(name, hostname) == 0)
6173 retval = WS_get_local_ips(hostname);
6174 /* If any other hostname was requested (or the routing table lookup failed)
6175 * then return the IP found by the host OS */
6176 if(retval == NULL)
6178 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6179 host = NULL;
6180 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
6181 while(extrabuf) {
6182 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
6183 if( res != ERANGE) break;
6184 ebufsize *=2;
6185 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
6187 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
6188 #else
6189 EnterCriticalSection( &csWSgetXXXbyYYY );
6190 host = gethostbyname(name);
6191 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
6192 #endif
6193 if (host) retval = WS_dup_he(host);
6194 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6195 HeapFree(GetProcessHeap(),0,extrabuf);
6196 #else
6197 LeaveCriticalSection( &csWSgetXXXbyYYY );
6198 #endif
6200 if (retval && retval->h_addr_list[0][0] == 127 &&
6201 strcmp(name, "localhost") != 0)
6203 /* hostname != "localhost" but has loopback address. replace by our
6204 * special address.*/
6205 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
6207 TRACE( "%s ret %p\n", debugstr_a(name), retval );
6208 return retval;
6212 /***********************************************************************
6213 * getprotobyname (WS2_32.53)
6215 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
6217 struct WS_protoent* retval = NULL;
6218 #ifdef HAVE_GETPROTOBYNAME
6219 struct protoent* proto;
6220 EnterCriticalSection( &csWSgetXXXbyYYY );
6221 if( (proto = getprotobyname(name)) != NULL )
6223 retval = WS_dup_pe(proto);
6225 else {
6226 MESSAGE("protocol %s not found; You might want to add "
6227 "this to /etc/protocols\n", debugstr_a(name) );
6228 SetLastError(WSANO_DATA);
6230 LeaveCriticalSection( &csWSgetXXXbyYYY );
6231 #endif
6232 TRACE( "%s ret %p\n", debugstr_a(name), retval );
6233 return retval;
6237 /***********************************************************************
6238 * getprotobynumber (WS2_32.54)
6240 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
6242 struct WS_protoent* retval = NULL;
6243 #ifdef HAVE_GETPROTOBYNUMBER
6244 struct protoent* proto;
6245 EnterCriticalSection( &csWSgetXXXbyYYY );
6246 if( (proto = getprotobynumber(number)) != NULL )
6248 retval = WS_dup_pe(proto);
6250 else {
6251 MESSAGE("protocol number %d not found; You might want to add "
6252 "this to /etc/protocols\n", number );
6253 SetLastError(WSANO_DATA);
6255 LeaveCriticalSection( &csWSgetXXXbyYYY );
6256 #endif
6257 TRACE("%i ret %p\n", number, retval);
6258 return retval;
6262 /***********************************************************************
6263 * getservbyname (WS2_32.55)
6265 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
6267 struct WS_servent* retval = NULL;
6268 struct servent* serv;
6269 char *name_str;
6270 char *proto_str = NULL;
6272 if (!(name_str = strdup_lower(name))) return NULL;
6274 if (proto && *proto)
6276 if (!(proto_str = strdup_lower(proto)))
6278 HeapFree( GetProcessHeap(), 0, name_str );
6279 return NULL;
6283 EnterCriticalSection( &csWSgetXXXbyYYY );
6284 serv = getservbyname(name_str, proto_str);
6285 if( serv != NULL )
6287 retval = WS_dup_se(serv);
6289 else SetLastError(WSANO_DATA);
6290 LeaveCriticalSection( &csWSgetXXXbyYYY );
6291 HeapFree( GetProcessHeap(), 0, proto_str );
6292 HeapFree( GetProcessHeap(), 0, name_str );
6293 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
6294 return retval;
6297 /***********************************************************************
6298 * freeaddrinfo (WS2_32.@)
6300 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
6302 while (res) {
6303 struct WS_addrinfo *next;
6305 HeapFree(GetProcessHeap(),0,res->ai_canonname);
6306 HeapFree(GetProcessHeap(),0,res->ai_addr);
6307 next = res->ai_next;
6308 HeapFree(GetProcessHeap(),0,res);
6309 res = next;
6313 /* helper functions for getaddrinfo()/getnameinfo() */
6314 static int convert_aiflag_w2u(int winflags) {
6315 unsigned int i;
6316 int unixflags = 0;
6318 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
6319 if (ws_aiflag_map[i][0] & winflags) {
6320 unixflags |= ws_aiflag_map[i][1];
6321 winflags &= ~ws_aiflag_map[i][0];
6323 if (winflags)
6324 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
6325 return unixflags;
6328 static int convert_niflag_w2u(int winflags) {
6329 unsigned int i;
6330 int unixflags = 0;
6332 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
6333 if (ws_niflag_map[i][0] & winflags) {
6334 unixflags |= ws_niflag_map[i][1];
6335 winflags &= ~ws_niflag_map[i][0];
6337 if (winflags)
6338 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
6339 return unixflags;
6342 static int convert_aiflag_u2w(int unixflags) {
6343 unsigned int i;
6344 int winflags = 0;
6346 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
6347 if (ws_aiflag_map[i][1] & unixflags) {
6348 winflags |= ws_aiflag_map[i][0];
6349 unixflags &= ~ws_aiflag_map[i][1];
6351 if (unixflags) /* will warn usually */
6352 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
6353 return winflags;
6356 static int convert_eai_u2w(int unixret) {
6357 int i;
6359 if (!unixret) return 0;
6361 for (i=0;ws_eai_map[i][0];i++)
6362 if (ws_eai_map[i][1] == unixret)
6363 return ws_eai_map[i][0];
6365 if (unixret == EAI_SYSTEM)
6366 /* There are broken versions of glibc which return EAI_SYSTEM
6367 * and set errno to 0 instead of returning EAI_NONAME.
6369 return errno ? sock_get_error( errno ) : WS_EAI_NONAME;
6371 FIXME("Unhandled unix EAI_xxx ret %d\n", unixret);
6372 return unixret;
6375 static char *get_hostname(void)
6377 char *ret;
6378 DWORD size = 0;
6380 GetComputerNameExA( ComputerNamePhysicalDnsHostname, NULL, &size );
6381 if (GetLastError() != ERROR_MORE_DATA) return NULL;
6382 if (!(ret = HeapAlloc( GetProcessHeap(), 0, size ))) return NULL;
6383 if (!GetComputerNameExA( ComputerNamePhysicalDnsHostname, ret, &size ))
6385 HeapFree( GetProcessHeap(), 0, ret );
6386 return NULL;
6388 return ret;
6391 /***********************************************************************
6392 * getaddrinfo (WS2_32.@)
6394 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
6396 #ifdef HAVE_GETADDRINFO
6397 struct addrinfo *unixaires = NULL;
6398 int result;
6399 struct addrinfo unixhints, *punixhints = NULL;
6400 char *hostname;
6401 const char *node;
6403 *res = NULL;
6404 if (!nodename && !servname)
6406 SetLastError(WSAHOST_NOT_FOUND);
6407 return WSAHOST_NOT_FOUND;
6410 hostname = get_hostname();
6411 if (!hostname) return WSA_NOT_ENOUGH_MEMORY;
6413 if (!nodename)
6414 node = NULL;
6415 else if (!nodename[0])
6416 node = hostname;
6417 else
6418 node = nodename;
6420 /* servname tweak required by OSX and BSD kernels */
6421 if (servname && !servname[0]) servname = "0";
6423 if (hints) {
6424 punixhints = &unixhints;
6426 memset(&unixhints, 0, sizeof(unixhints));
6427 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
6429 /* zero is a wildcard, no need to convert */
6430 if (hints->ai_family)
6431 punixhints->ai_family = convert_af_w2u(hints->ai_family);
6432 if (hints->ai_socktype)
6433 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
6434 if (hints->ai_protocol)
6435 punixhints->ai_protocol = max(convert_proto_w2u(hints->ai_protocol), 0);
6437 if (punixhints->ai_socktype < 0)
6439 SetLastError(WSAESOCKTNOSUPPORT);
6440 HeapFree(GetProcessHeap(), 0, hostname);
6441 return SOCKET_ERROR;
6444 /* windows allows invalid combinations of socket type and protocol, unix does not.
6445 * fix the parameters here to make getaddrinfo call always work */
6446 if (punixhints->ai_protocol == IPPROTO_TCP &&
6447 punixhints->ai_socktype != SOCK_STREAM && punixhints->ai_socktype != SOCK_SEQPACKET)
6448 punixhints->ai_socktype = 0;
6450 else if (punixhints->ai_protocol == IPPROTO_UDP && punixhints->ai_socktype != SOCK_DGRAM)
6451 punixhints->ai_socktype = 0;
6453 else if (IS_IPX_PROTO(punixhints->ai_protocol) && punixhints->ai_socktype != SOCK_DGRAM)
6454 punixhints->ai_socktype = 0;
6457 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
6458 result = getaddrinfo(node, servname, punixhints, &unixaires);
6460 if (result && !strcmp(hostname, node))
6462 /* If it didn't work it means the host name IP is not in /etc/hosts, try again
6463 * by sending a NULL host and avoid sending a NULL servname too because that
6464 * is invalid */
6465 ERR_(winediag)("Failed to resolve your host name IP\n");
6466 result = getaddrinfo(NULL, servname ? servname : "0", punixhints, &unixaires);
6468 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
6469 HeapFree(GetProcessHeap(), 0, hostname);
6471 if (!result) {
6472 struct addrinfo *xuai = unixaires;
6473 struct WS_addrinfo **xai = res;
6475 *xai = NULL;
6476 while (xuai) {
6477 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
6478 SIZE_T len;
6480 if (!ai)
6481 goto outofmem;
6483 *xai = ai;xai = &ai->ai_next;
6484 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
6485 ai->ai_family = convert_af_u2w(xuai->ai_family);
6486 /* copy whatever was sent in the hints */
6487 if(hints) {
6488 ai->ai_socktype = hints->ai_socktype;
6489 ai->ai_protocol = hints->ai_protocol;
6490 } else {
6491 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
6492 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
6494 if (xuai->ai_canonname) {
6495 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
6496 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
6497 if (!ai->ai_canonname)
6498 goto outofmem;
6499 strcpy(ai->ai_canonname,xuai->ai_canonname);
6501 len = xuai->ai_addrlen;
6502 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
6503 if (!ai->ai_addr)
6504 goto outofmem;
6505 ai->ai_addrlen = len;
6506 do {
6507 int winlen = ai->ai_addrlen;
6509 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
6510 ai->ai_addrlen = winlen;
6511 break;
6513 len = 2*len;
6514 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
6515 if (!ai->ai_addr)
6516 goto outofmem;
6517 ai->ai_addrlen = len;
6518 } while (1);
6519 xuai = xuai->ai_next;
6521 freeaddrinfo(unixaires);
6523 if (TRACE_ON(winsock))
6525 struct WS_addrinfo *ai = *res;
6526 while (ai)
6528 TRACE("=> %p, flags %#x, family %d, type %d, protocol %d, len %ld, name %s, addr %s\n",
6529 ai, ai->ai_flags, ai->ai_family, ai->ai_socktype, ai->ai_protocol, ai->ai_addrlen,
6530 ai->ai_canonname, debugstr_sockaddr(ai->ai_addr));
6531 ai = ai->ai_next;
6534 } else
6535 result = convert_eai_u2w(result);
6537 SetLastError(result);
6538 return result;
6540 outofmem:
6541 if (*res) WS_freeaddrinfo(*res);
6542 if (unixaires) freeaddrinfo(unixaires);
6543 return WSA_NOT_ENOUGH_MEMORY;
6544 #else
6545 FIXME("getaddrinfo() failed, not found during buildtime.\n");
6546 return EAI_FAIL;
6547 #endif
6550 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
6552 struct WS_addrinfoW *ret;
6554 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
6555 ret->ai_flags = ai->ai_flags;
6556 ret->ai_family = ai->ai_family;
6557 ret->ai_socktype = ai->ai_socktype;
6558 ret->ai_protocol = ai->ai_protocol;
6559 ret->ai_addrlen = ai->ai_addrlen;
6560 ret->ai_canonname = NULL;
6561 ret->ai_addr = NULL;
6562 ret->ai_next = NULL;
6563 if (ai->ai_canonname)
6565 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
6566 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR))))
6568 HeapFree(GetProcessHeap(), 0, ret);
6569 return NULL;
6571 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
6573 if (ai->ai_addr)
6575 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, ai->ai_addrlen)))
6577 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
6578 HeapFree(GetProcessHeap(), 0, ret);
6579 return NULL;
6581 memcpy(ret->ai_addr, ai->ai_addr, ai->ai_addrlen);
6583 return ret;
6586 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
6588 struct WS_addrinfoW *ret, *infoW;
6590 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
6591 while (info->ai_next)
6593 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
6595 FreeAddrInfoW(ret);
6596 return NULL;
6598 infoW = infoW->ai_next;
6599 info = info->ai_next;
6601 return ret;
6604 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
6606 struct WS_addrinfo *ret;
6608 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
6609 ret->ai_flags = ai->ai_flags;
6610 ret->ai_family = ai->ai_family;
6611 ret->ai_socktype = ai->ai_socktype;
6612 ret->ai_protocol = ai->ai_protocol;
6613 ret->ai_addrlen = ai->ai_addrlen;
6614 ret->ai_canonname = NULL;
6615 ret->ai_addr = NULL;
6616 ret->ai_next = NULL;
6617 if (ai->ai_canonname)
6619 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
6620 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
6622 HeapFree(GetProcessHeap(), 0, ret);
6623 return NULL;
6625 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
6627 if (ai->ai_addr)
6629 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
6631 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
6632 HeapFree(GetProcessHeap(), 0, ret);
6633 return NULL;
6635 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
6637 return ret;
6640 /***********************************************************************
6641 * GetAddrInfoExW (WS2_32.@)
6643 int WINAPI GetAddrInfoExW(const WCHAR *name, const WCHAR *servname, DWORD namespace, GUID *namespace_id,
6644 const ADDRINFOEXW *hints, ADDRINFOEXW **result, struct timeval *timeout, OVERLAPPED *overlapped,
6645 LPLOOKUPSERVICE_COMPLETION_ROUTINE completion_routine, HANDLE *handle)
6647 FIXME("(%s %s %x %s %p %p %p %p %p %p)\n", debugstr_w(name), debugstr_w(servname), namespace,
6648 debugstr_guid(namespace_id), hints, result, timeout, overlapped, completion_routine, handle);
6649 return WSAHOST_NOT_FOUND;
6652 /***********************************************************************
6653 * GetAddrInfoW (WS2_32.@)
6655 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
6657 int ret, len;
6658 char *nodenameA = NULL, *servnameA = NULL;
6659 struct WS_addrinfo *resA, *hintsA = NULL;
6661 *res = NULL;
6662 if (nodename)
6664 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
6665 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
6666 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
6668 if (servname)
6670 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
6671 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
6673 HeapFree(GetProcessHeap(), 0, nodenameA);
6674 return EAI_MEMORY;
6676 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
6679 if (hints) hintsA = addrinfo_WtoA(hints);
6680 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
6681 WS_freeaddrinfo(hintsA);
6683 if (!ret)
6685 *res = addrinfo_list_AtoW(resA);
6686 WS_freeaddrinfo(resA);
6689 HeapFree(GetProcessHeap(), 0, nodenameA);
6690 HeapFree(GetProcessHeap(), 0, servnameA);
6691 return ret;
6694 /***********************************************************************
6695 * FreeAddrInfoW (WS2_32.@)
6697 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
6699 while (ai)
6701 ADDRINFOW *next;
6702 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
6703 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
6704 next = ai->ai_next;
6705 HeapFree(GetProcessHeap(), 0, ai);
6706 ai = next;
6710 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
6711 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
6713 #ifdef HAVE_GETNAMEINFO
6714 int ret;
6715 union generic_unix_sockaddr sa_u;
6716 unsigned int size;
6718 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
6719 serv, servlen, flags);
6721 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
6722 if (!size)
6724 SetLastError(WSAEFAULT);
6725 return WSA_NOT_ENOUGH_MEMORY;
6727 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
6728 return convert_eai_u2w(ret);
6729 #else
6730 FIXME("getnameinfo() failed, not found during buildtime.\n");
6731 return EAI_FAIL;
6732 #endif
6735 int WINAPI GetNameInfoW(const SOCKADDR *sa, WS_socklen_t salen, PWCHAR host,
6736 DWORD hostlen, PWCHAR serv, DWORD servlen, INT flags)
6738 int ret;
6739 char *hostA = NULL, *servA = NULL;
6741 if (host && (!(hostA = HeapAlloc(GetProcessHeap(), 0, hostlen)))) return EAI_MEMORY;
6742 if (serv && (!(servA = HeapAlloc(GetProcessHeap(), 0, servlen))))
6744 HeapFree(GetProcessHeap(), 0, hostA);
6745 return EAI_MEMORY;
6748 ret = WS_getnameinfo(sa, salen, hostA, hostlen, servA, servlen, flags);
6749 if (!ret)
6751 if (host) MultiByteToWideChar(CP_ACP, 0, hostA, -1, host, hostlen);
6752 if (serv) MultiByteToWideChar(CP_ACP, 0, servA, -1, serv, servlen);
6755 HeapFree(GetProcessHeap(), 0, hostA);
6756 HeapFree(GetProcessHeap(), 0, servA);
6757 return ret;
6760 /***********************************************************************
6761 * getservbyport (WS2_32.56)
6763 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
6765 struct WS_servent* retval = NULL;
6766 #ifdef HAVE_GETSERVBYPORT
6767 struct servent* serv;
6768 char *proto_str = NULL;
6770 if (proto && *proto)
6772 if (!(proto_str = strdup_lower(proto))) return NULL;
6774 EnterCriticalSection( &csWSgetXXXbyYYY );
6775 if( (serv = getservbyport(port, proto_str)) != NULL ) {
6776 retval = WS_dup_se(serv);
6778 else SetLastError(WSANO_DATA);
6779 LeaveCriticalSection( &csWSgetXXXbyYYY );
6780 HeapFree( GetProcessHeap(), 0, proto_str );
6781 #endif
6782 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
6783 return retval;
6787 /***********************************************************************
6788 * gethostname (WS2_32.57)
6790 int WINAPI WS_gethostname(char *name, int namelen)
6792 char buf[256];
6793 int len;
6795 TRACE("name %p, len %d\n", name, namelen);
6797 if (!name)
6799 SetLastError(WSAEFAULT);
6800 return SOCKET_ERROR;
6803 if (gethostname(buf, sizeof(buf)) != 0)
6805 SetLastError(wsaErrno());
6806 return SOCKET_ERROR;
6809 TRACE("<- '%s'\n", buf);
6810 len = strlen(buf);
6811 if (len > 15)
6812 WARN("Windows supports NetBIOS name length up to 15 bytes!\n");
6813 if (namelen <= len)
6815 SetLastError(WSAEFAULT);
6816 WARN("<- not enough space for hostname, required %d, got %d!\n", len + 1, namelen);
6817 return SOCKET_ERROR;
6819 strcpy(name, buf);
6820 return 0;
6824 /* ------------------------------------- Windows sockets extensions -- *
6826 * ------------------------------------------------------------------- */
6828 /***********************************************************************
6829 * WSAEnumNetworkEvents (WS2_32.36)
6831 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
6833 int ret;
6834 int i;
6835 int errors[FD_MAX_EVENTS];
6837 TRACE("%04lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
6839 SERVER_START_REQ( get_socket_event )
6841 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6842 req->service = TRUE;
6843 req->c_event = wine_server_obj_handle( hEvent );
6844 wine_server_set_reply( req, errors, sizeof(errors) );
6845 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
6847 SERVER_END_REQ;
6848 if (!ret)
6850 for (i = 0; i < FD_MAX_EVENTS; i++)
6851 lpEvent->iErrorCode[i] = NtStatusToWSAError(errors[i]);
6852 return 0;
6854 SetLastError(WSAEINVAL);
6855 return SOCKET_ERROR;
6858 /***********************************************************************
6859 * WSAEventSelect (WS2_32.39)
6861 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
6863 int ret;
6865 TRACE("%04lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
6867 SERVER_START_REQ( set_socket_event )
6869 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6870 req->mask = lEvent;
6871 req->event = wine_server_obj_handle( hEvent );
6872 req->window = 0;
6873 req->msg = 0;
6874 ret = wine_server_call( req );
6876 SERVER_END_REQ;
6877 if (!ret) return 0;
6878 SetLastError(WSAEINVAL);
6879 return SOCKET_ERROR;
6882 /**********************************************************************
6883 * WSAGetOverlappedResult (WS2_32.40)
6885 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
6886 LPDWORD lpcbTransfer, BOOL fWait,
6887 LPDWORD lpdwFlags )
6889 NTSTATUS status;
6891 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
6892 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
6894 if ( lpOverlapped == NULL )
6896 ERR( "Invalid pointer\n" );
6897 SetLastError(WSA_INVALID_PARAMETER);
6898 return FALSE;
6901 status = lpOverlapped->Internal;
6902 if (status == STATUS_PENDING)
6904 if (!fWait)
6906 SetLastError( WSA_IO_INCOMPLETE );
6907 return FALSE;
6910 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
6911 INFINITE ) == WAIT_FAILED)
6912 return FALSE;
6913 status = lpOverlapped->Internal;
6916 if ( lpcbTransfer )
6917 *lpcbTransfer = lpOverlapped->InternalHigh;
6919 if ( lpdwFlags )
6920 *lpdwFlags = lpOverlapped->u.s.Offset;
6922 if (status) SetLastError( RtlNtStatusToDosError(status) );
6923 return !status;
6927 /***********************************************************************
6928 * WSAAsyncSelect (WS2_32.101)
6930 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
6932 int ret;
6934 TRACE("%04lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
6936 SERVER_START_REQ( set_socket_event )
6938 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6939 req->mask = lEvent;
6940 req->event = 0;
6941 req->window = wine_server_user_handle( hWnd );
6942 req->msg = uMsg;
6943 ret = wine_server_call( req );
6945 SERVER_END_REQ;
6946 if (!ret) return 0;
6947 SetLastError(WSAEINVAL);
6948 return SOCKET_ERROR;
6951 /***********************************************************************
6952 * WSACreateEvent (WS2_32.31)
6955 WSAEVENT WINAPI WSACreateEvent(void)
6957 /* Create a manual-reset event, with initial state: unsignaled */
6958 TRACE("\n");
6960 return CreateEventW(NULL, TRUE, FALSE, NULL);
6963 /***********************************************************************
6964 * WSACloseEvent (WS2_32.29)
6967 BOOL WINAPI WSACloseEvent(WSAEVENT event)
6969 TRACE ("event=%p\n", event);
6971 return CloseHandle(event);
6974 /***********************************************************************
6975 * WSASocketA (WS2_32.78)
6978 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
6979 LPWSAPROTOCOL_INFOA lpProtocolInfo,
6980 GROUP g, DWORD dwFlags)
6982 INT len;
6983 WSAPROTOCOL_INFOW info;
6985 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
6986 af, type, protocol, lpProtocolInfo, g, dwFlags);
6988 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
6990 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
6991 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
6992 info.szProtocol, WSAPROTOCOL_LEN + 1);
6994 if (!len)
6996 SetLastError(WSAEINVAL);
6997 return SOCKET_ERROR;
7000 return WSASocketW(af, type, protocol, &info, g, dwFlags);
7003 /***********************************************************************
7004 * WSASocketW (WS2_32.79)
7007 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
7008 LPWSAPROTOCOL_INFOW lpProtocolInfo,
7009 GROUP g, DWORD dwFlags)
7011 SOCKET ret;
7012 DWORD err;
7013 int unixaf, unixtype, ipxptype = -1;
7016 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
7017 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
7020 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
7021 af, type, protocol, lpProtocolInfo, g, dwFlags );
7023 if (!num_startup)
7025 err = WSANOTINITIALISED;
7026 goto done;
7029 /* hack for WSADuplicateSocket */
7030 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
7031 ret = lpProtocolInfo->dwServiceFlags3;
7032 TRACE("\tgot duplicate %04lx\n", ret);
7033 return ret;
7036 if (lpProtocolInfo)
7038 if (af == FROM_PROTOCOL_INFO || !af)
7039 af = lpProtocolInfo->iAddressFamily;
7040 if (type == FROM_PROTOCOL_INFO || !type)
7041 type = lpProtocolInfo->iSocketType;
7042 if (protocol == FROM_PROTOCOL_INFO || !protocol)
7043 protocol = lpProtocolInfo->iProtocol;
7046 if (!type && (af || protocol))
7048 int autoproto = protocol;
7049 WSAPROTOCOL_INFOW infow;
7051 /* default to the first valid protocol */
7052 if (!autoproto)
7053 autoproto = valid_protocols[0];
7054 else if(IS_IPX_PROTO(autoproto))
7055 autoproto = WS_NSPROTO_IPX;
7057 if (WS_EnterSingleProtocolW(autoproto, &infow))
7059 type = infow.iSocketType;
7061 /* after win2003 it's no longer possible to pass AF_UNSPEC
7062 using the protocol info struct */
7063 if (!lpProtocolInfo && af == WS_AF_UNSPEC)
7064 af = infow.iAddressFamily;
7069 Windows has an extension to the IPX protocol that allows one to create sockets
7070 and set the IPX packet type at the same time, to do that a caller will use
7071 a protocol like NSPROTO_IPX + <PACKET TYPE>
7073 if (IS_IPX_PROTO(protocol))
7074 ipxptype = protocol - WS_NSPROTO_IPX;
7076 /* convert the socket family, type and protocol */
7077 unixaf = convert_af_w2u(af);
7078 unixtype = convert_socktype_w2u(type);
7079 protocol = convert_proto_w2u(protocol);
7080 if (unixaf == AF_UNSPEC) unixaf = -1;
7082 /* filter invalid parameters */
7083 if (protocol < 0)
7085 /* the type could not be converted */
7086 if (type && unixtype < 0)
7088 err = WSAESOCKTNOSUPPORT;
7089 goto done;
7092 err = WSAEPROTONOSUPPORT;
7093 goto done;
7095 if (unixaf < 0)
7097 /* both family and protocol can't be invalid */
7098 if (protocol <= 0)
7100 err = WSAEINVAL;
7101 goto done;
7104 /* family could not be converted and neither socket type */
7105 if (unixtype < 0 && af >= 0)
7108 err = WSAESOCKTNOSUPPORT;
7109 goto done;
7112 err = WSAEAFNOSUPPORT;
7113 goto done;
7116 SERVER_START_REQ( create_socket )
7118 req->family = unixaf;
7119 req->type = unixtype;
7120 req->protocol = protocol;
7121 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
7122 req->attributes = (dwFlags & WSA_FLAG_NO_HANDLE_INHERIT) ? 0 : OBJ_INHERIT;
7123 req->flags = dwFlags & ~WSA_FLAG_NO_HANDLE_INHERIT;
7124 set_error( wine_server_call( req ) );
7125 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
7127 SERVER_END_REQ;
7128 if (ret)
7130 TRACE("\tcreated %04lx\n", ret );
7131 if (ipxptype > 0)
7132 set_ipx_packettype(ret, ipxptype);
7133 return ret;
7136 err = GetLastError();
7137 if (err == WSAEACCES) /* raw socket denied */
7139 if (type == SOCK_RAW)
7140 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
7141 else
7142 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
7144 else
7146 /* invalid combination of valid parameters, like SOCK_STREAM + IPPROTO_UDP */
7147 if (err == WSAEINVAL)
7148 err = WSAESOCKTNOSUPPORT;
7149 else if (err == WSAEOPNOTSUPP)
7150 err = WSAEPROTONOSUPPORT;
7153 done:
7154 WARN("\t\tfailed, error %d!\n", err);
7155 SetLastError(err);
7156 return INVALID_SOCKET;
7159 /***********************************************************************
7160 * WSAJoinLeaf (WS2_32.58)
7163 SOCKET WINAPI WSAJoinLeaf(
7164 SOCKET s,
7165 const struct WS_sockaddr *addr,
7166 int addrlen,
7167 LPWSABUF lpCallerData,
7168 LPWSABUF lpCalleeData,
7169 LPQOS lpSQOS,
7170 LPQOS lpGQOS,
7171 DWORD dwFlags)
7173 FIXME("stub.\n");
7174 return INVALID_SOCKET;
7177 /***********************************************************************
7178 * __WSAFDIsSet (WS2_32.151)
7180 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
7182 int i = set->fd_count, ret = 0;
7184 while (i--)
7185 if (set->fd_array[i] == s)
7187 ret = 1;
7188 break;
7191 TRACE("(socket %04lx, fd_set %p, count %i) <- %d\n", s, set, set->fd_count, ret);
7192 return ret;
7195 /***********************************************************************
7196 * WSAIsBlocking (WS2_32.114)
7198 BOOL WINAPI WSAIsBlocking(void)
7200 /* By default WinSock should set all its sockets to non-blocking mode
7201 * and poll in PeekMessage loop when processing "blocking" ones. This
7202 * function is supposed to tell if the program is in this loop. Our
7203 * blocking calls are truly blocking so we always return FALSE.
7205 * Note: It is allowed to call this function without prior WSAStartup().
7208 TRACE("\n");
7209 return FALSE;
7212 /***********************************************************************
7213 * WSACancelBlockingCall (WS2_32.113)
7215 INT WINAPI WSACancelBlockingCall(void)
7217 TRACE("\n");
7218 return 0;
7221 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
7223 FIXME("How was this called?\n");
7224 return x();
7228 /***********************************************************************
7229 * WSASetBlockingHook (WS2_32.109)
7231 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
7233 FARPROC prev = blocking_hook;
7234 blocking_hook = lpBlockFunc;
7235 TRACE("hook %p\n", lpBlockFunc);
7236 return prev;
7240 /***********************************************************************
7241 * WSAUnhookBlockingHook (WS2_32.110)
7243 INT WINAPI WSAUnhookBlockingHook(void)
7245 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
7246 return 0;
7250 /* ----------------------------------- end of API stuff */
7252 /* ----------------------------------- helper functions -
7254 * TODO: Merge WS_dup_..() stuff into one function that
7255 * would operate with a generic structure containing internal
7256 * pointers (via a template of some kind).
7259 static int list_size(char** l, int item_size)
7261 int i,j = 0;
7262 if(l)
7263 { for(i=0;l[i];i++)
7264 j += (item_size) ? item_size : strlen(l[i]) + 1;
7265 j += (i + 1) * sizeof(char*); }
7266 return j;
7269 static int list_dup(char** l_src, char** l_to, int item_size)
7271 char *p;
7272 int i;
7274 for (i = 0; l_src[i]; i++) ;
7275 p = (char *)(l_to + i + 1);
7276 for (i = 0; l_src[i]; i++)
7278 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
7279 memcpy(p, l_src[i], count);
7280 l_to[i] = p;
7281 p += count;
7283 l_to[i] = NULL;
7284 return p - (char *)l_to;
7287 /* ----- hostent */
7289 /* create a hostent entry
7291 * Creates the entry with enough memory for the name, aliases
7292 * addresses, and the address pointers. Also copies the name
7293 * and sets up all the pointers.
7295 * NOTE: The alias and address lists must be allocated with room
7296 * for the NULL item terminating the list. This is true even if
7297 * the list has no items ("aliases" and "addresses" must be
7298 * at least "1", a truly empty list is invalid).
7300 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length)
7302 struct WS_hostent *p_to;
7303 char *p;
7304 int size = (sizeof(struct WS_hostent) +
7305 strlen(name) + 1 +
7306 sizeof(char *) * aliases +
7307 aliases_size +
7308 sizeof(char *) * addresses +
7309 address_length * (addresses - 1)), i;
7311 if (!(p_to = check_buffer_he(size))) return NULL;
7312 memset(p_to, 0, size);
7314 /* Use the memory in the same way winsock does.
7315 * First set the pointer for aliases, second set the pointers for addresses.
7316 * Third fill the addresses indexes, fourth jump aliases names size.
7317 * Fifth fill the hostname.
7318 * NOTE: This method is valid for OS version's >= XP.
7320 p = (char *)(p_to + 1);
7321 p_to->h_aliases = (char **)p;
7322 p += sizeof(char *)*aliases;
7324 p_to->h_addr_list = (char **)p;
7325 p += sizeof(char *)*addresses;
7327 for (i = 0, addresses--; i < addresses; i++, p += address_length)
7328 p_to->h_addr_list[i] = p;
7330 /* NOTE: h_aliases must be filled in manually because we don't know each string
7331 * size, leave these pointers NULL (already set to NULL by memset earlier).
7333 p += aliases_size;
7335 p_to->h_name = p;
7336 strcpy(p, name);
7338 return p_to;
7341 /* duplicate hostent entry
7342 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
7343 * Ditto for protoent and servent.
7345 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
7347 int i, addresses = 0, alias_size = 0;
7348 struct WS_hostent *p_to;
7349 char *p;
7351 for( i = 0; p_he->h_aliases[i]; i++) alias_size += strlen(p_he->h_aliases[i]) + 1;
7352 while (p_he->h_addr_list[addresses]) addresses++;
7354 p_to = WS_create_he(p_he->h_name, i + 1, alias_size, addresses + 1, p_he->h_length);
7356 if (!p_to) return NULL;
7357 p_to->h_addrtype = convert_af_u2w(p_he->h_addrtype);
7358 p_to->h_length = p_he->h_length;
7360 for(i = 0, p = p_to->h_addr_list[0]; p_he->h_addr_list[i]; i++, p += p_to->h_length)
7361 memcpy(p, p_he->h_addr_list[i], p_to->h_length);
7363 /* Fill the aliases after the IP data */
7364 for(i = 0; p_he->h_aliases[i]; i++)
7366 p_to->h_aliases[i] = p;
7367 strcpy(p, p_he->h_aliases[i]);
7368 p += strlen(p) + 1;
7371 return p_to;
7374 /* ----- protoent */
7376 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
7378 char *p;
7379 struct WS_protoent *p_to;
7381 int size = (sizeof(*p_pe) +
7382 strlen(p_pe->p_name) + 1 +
7383 list_size(p_pe->p_aliases, 0));
7385 if (!(p_to = check_buffer_pe(size))) return NULL;
7386 p_to->p_proto = p_pe->p_proto;
7388 p = (char *)(p_to + 1);
7389 p_to->p_name = p;
7390 strcpy(p, p_pe->p_name);
7391 p += strlen(p) + 1;
7393 p_to->p_aliases = (char **)p;
7394 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
7395 return p_to;
7398 /* ----- servent */
7400 static struct WS_servent *WS_dup_se(const struct servent* p_se)
7402 char *p;
7403 struct WS_servent *p_to;
7405 int size = (sizeof(*p_se) +
7406 strlen(p_se->s_proto) + 1 +
7407 strlen(p_se->s_name) + 1 +
7408 list_size(p_se->s_aliases, 0));
7410 if (!(p_to = check_buffer_se(size))) return NULL;
7411 p_to->s_port = p_se->s_port;
7413 p = (char *)(p_to + 1);
7414 p_to->s_name = p;
7415 strcpy(p, p_se->s_name);
7416 p += strlen(p) + 1;
7418 p_to->s_proto = p;
7419 strcpy(p, p_se->s_proto);
7420 p += strlen(p) + 1;
7422 p_to->s_aliases = (char **)p;
7423 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
7424 return p_to;
7428 /***********************************************************************
7429 * WSARecv (WS2_32.67)
7431 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
7432 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
7433 LPWSAOVERLAPPED lpOverlapped,
7434 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
7436 return WS2_recv_base(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
7437 NULL, NULL, lpOverlapped, lpCompletionRoutine, NULL);
7440 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
7441 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
7442 struct WS_sockaddr *lpFrom,
7443 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
7444 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
7445 LPWSABUF lpControlBuffer )
7447 unsigned int i, options;
7448 int n, fd, err, overlapped, flags;
7449 struct ws2_async *wsa = NULL, localwsa;
7450 BOOL is_blocking;
7451 DWORD timeout_start = GetTickCount();
7452 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
7454 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
7455 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
7456 (lpFromlen ? *lpFromlen : -1),
7457 lpOverlapped, lpCompletionRoutine);
7459 fd = get_sock_fd( s, FILE_READ_DATA, &options );
7460 TRACE( "fd=%d, options=%x\n", fd, options );
7462 if (fd == -1) return SOCKET_ERROR;
7464 if (*lpFlags & WS_MSG_OOB)
7466 /* It's invalid to receive OOB data from an OOBINLINED socket
7467 * as OOB data is turned into normal data. */
7468 i = sizeof(n);
7469 if (!getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, (char*) &n, &i) && n)
7471 err = WSAEINVAL;
7472 goto error;
7476 overlapped = (lpOverlapped || lpCompletionRoutine) &&
7477 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
7478 if (overlapped || dwBufferCount > 1)
7480 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[dwBufferCount]))))
7482 err = WSAEFAULT;
7483 goto error;
7486 else
7487 wsa = &localwsa;
7489 wsa->hSocket = SOCKET2HANDLE(s);
7490 wsa->flags = *lpFlags;
7491 wsa->lpFlags = lpFlags;
7492 wsa->addr = lpFrom;
7493 wsa->addrlen.ptr = lpFromlen;
7494 wsa->control = lpControlBuffer;
7495 wsa->n_iovecs = dwBufferCount;
7496 wsa->first_iovec = 0;
7497 for (i = 0; i < dwBufferCount; i++)
7499 /* check buffer first to trigger write watches */
7500 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
7502 err = WSAEFAULT;
7503 goto error;
7505 wsa->iovec[i].iov_base = lpBuffers[i].buf;
7506 wsa->iovec[i].iov_len = lpBuffers[i].len;
7509 flags = convert_flags(wsa->flags);
7510 for (;;)
7512 n = WS2_recv( fd, wsa, flags );
7513 if (n == -1)
7515 /* Unix-like systems return EINVAL when attempting to read OOB data from
7516 * an empty socket buffer, convert that to a Windows expected return. */
7517 if ((flags & MSG_OOB) && errno == EINVAL)
7518 errno = EWOULDBLOCK;
7520 if (errno != EAGAIN)
7522 int loc_errno = errno;
7523 err = wsaErrno();
7524 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
7525 goto error;
7528 else if (lpNumberOfBytesRecvd) *lpNumberOfBytesRecvd = n;
7530 if (overlapped)
7532 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
7534 wsa->user_overlapped = lpOverlapped;
7535 wsa->completion_func = lpCompletionRoutine;
7536 release_sock_fd( s, fd );
7538 if (n == -1)
7540 iosb->u.Status = STATUS_PENDING;
7541 iosb->Information = 0;
7543 SERVER_START_REQ( register_async )
7545 req->type = ASYNC_TYPE_READ;
7546 req->async.handle = wine_server_obj_handle( wsa->hSocket );
7547 req->async.callback = wine_server_client_ptr( WS2_async_recv );
7548 req->async.iosb = wine_server_client_ptr( iosb );
7549 req->async.arg = wine_server_client_ptr( wsa );
7550 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
7551 req->async.cvalue = cvalue;
7552 err = wine_server_call( req );
7554 SERVER_END_REQ;
7556 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
7557 SetLastError(NtStatusToWSAError( err ));
7558 return SOCKET_ERROR;
7561 iosb->u.Status = STATUS_SUCCESS;
7562 iosb->Information = n;
7563 if (!wsa->completion_func)
7565 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
7566 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
7567 HeapFree( GetProcessHeap(), 0, wsa );
7569 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
7570 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
7571 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7572 return 0;
7575 if (n != -1) break;
7577 if ((err = _is_blocking( s, &is_blocking )))
7579 err = NtStatusToWSAError( err );
7580 goto error;
7583 if ( is_blocking )
7585 struct pollfd pfd;
7586 int poll_timeout = -1;
7587 INT64 timeout = get_rcvsnd_timeo(fd, TRUE);
7589 if (timeout)
7591 timeout -= GetTickCount() - timeout_start;
7592 if (timeout < 0) poll_timeout = 0;
7593 else poll_timeout = timeout <= INT_MAX ? timeout : INT_MAX;
7596 pfd.fd = fd;
7597 pfd.events = POLLIN;
7598 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
7600 if (!poll_timeout || !poll( &pfd, 1, poll_timeout ))
7602 err = WSAETIMEDOUT;
7603 /* a timeout is not fatal */
7604 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7605 goto error;
7608 else
7610 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7611 err = WSAEWOULDBLOCK;
7612 goto error;
7616 TRACE(" -> %i bytes\n", n);
7617 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
7618 release_sock_fd( s, fd );
7619 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7620 SetLastError(ERROR_SUCCESS);
7622 return 0;
7624 error:
7625 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
7626 release_sock_fd( s, fd );
7627 WARN(" -> ERROR %d\n", err);
7628 SetLastError( err );
7629 return SOCKET_ERROR;
7632 /***********************************************************************
7633 * WSARecvFrom (WS2_32.69)
7635 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
7636 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
7637 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
7638 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
7641 return WS2_recv_base( s, lpBuffers, dwBufferCount,
7642 lpNumberOfBytesRecvd, lpFlags,
7643 lpFrom, lpFromlen,
7644 lpOverlapped, lpCompletionRoutine, NULL );
7647 /***********************************************************************
7648 * WSCInstallProvider (WS2_32.88)
7650 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
7651 LPCWSTR lpszProviderDllPath,
7652 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
7653 DWORD dwNumberOfEntries,
7654 LPINT lpErrno )
7656 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
7657 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
7658 dwNumberOfEntries, lpErrno);
7659 *lpErrno = 0;
7660 return 0;
7664 /***********************************************************************
7665 * WSCDeinstallProvider (WS2_32.83)
7667 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
7669 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
7670 *lpErrno = 0;
7671 return 0;
7675 /***********************************************************************
7676 * WSAAccept (WS2_32.26)
7678 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
7679 LPCONDITIONPROC lpfnCondition, DWORD_PTR dwCallbackData)
7682 int ret = 0, size;
7683 WSABUF CallerId, CallerData, CalleeId, CalleeData;
7684 /* QOS SQOS, GQOS; */
7685 GROUP g;
7686 SOCKET cs;
7687 SOCKADDR src_addr, dst_addr;
7689 TRACE("socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
7690 s, addr, addrlen, lpfnCondition, dwCallbackData);
7692 cs = WS_accept(s, addr, addrlen);
7693 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
7694 if (!lpfnCondition) return cs;
7696 if (addr && addrlen)
7698 CallerId.buf = (char *)addr;
7699 CallerId.len = *addrlen;
7701 else
7703 size = sizeof(src_addr);
7704 WS_getpeername(cs, &src_addr, &size);
7705 CallerId.buf = (char *)&src_addr;
7706 CallerId.len = size;
7708 CallerData.buf = NULL;
7709 CallerData.len = 0;
7711 size = sizeof(dst_addr);
7712 WS_getsockname(cs, &dst_addr, &size);
7714 CalleeId.buf = (char *)&dst_addr;
7715 CalleeId.len = sizeof(dst_addr);
7717 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
7718 &CalleeId, &CalleeData, &g, dwCallbackData);
7720 switch (ret)
7722 case CF_ACCEPT:
7723 return cs;
7724 case CF_DEFER:
7725 SERVER_START_REQ( set_socket_deferred )
7727 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
7728 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
7729 if ( !wine_server_call_err ( req ) )
7731 SetLastError( WSATRY_AGAIN );
7732 WS_closesocket( cs );
7735 SERVER_END_REQ;
7736 return SOCKET_ERROR;
7737 case CF_REJECT:
7738 WS_closesocket(cs);
7739 SetLastError(WSAECONNREFUSED);
7740 return SOCKET_ERROR;
7741 default:
7742 FIXME("Unknown return type from Condition function\n");
7743 SetLastError(WSAENOTSOCK);
7744 return SOCKET_ERROR;
7748 /***********************************************************************
7749 * WSADuplicateSocketA (WS2_32.32)
7751 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
7753 return WS_DuplicateSocket(FALSE, s, dwProcessId, (LPWSAPROTOCOL_INFOW) lpProtocolInfo);
7756 /***********************************************************************
7757 * WSADuplicateSocketW (WS2_32.33)
7759 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
7761 return WS_DuplicateSocket(TRUE, s, dwProcessId, lpProtocolInfo);
7764 /***********************************************************************
7765 * WSAInstallServiceClassA (WS2_32.48)
7767 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
7769 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
7770 SetLastError(WSAEACCES);
7771 return SOCKET_ERROR;
7774 /***********************************************************************
7775 * WSAInstallServiceClassW (WS2_32.49)
7777 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
7779 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
7780 SetLastError(WSAEACCES);
7781 return SOCKET_ERROR;
7784 /***********************************************************************
7785 * WSARemoveServiceClass (WS2_32.70)
7787 int WINAPI WSARemoveServiceClass(LPGUID info)
7789 FIXME("Request to remove service %p\n",info);
7790 SetLastError(WSATYPE_NOT_FOUND);
7791 return SOCKET_ERROR;
7794 /***********************************************************************
7795 * inet_ntop (WS2_32.@)
7797 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
7799 #ifdef HAVE_INET_NTOP
7800 struct WS_in6_addr *in6;
7801 struct WS_in_addr *in;
7802 PCSTR pdst;
7804 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
7805 if (!buffer)
7807 SetLastError( STATUS_INVALID_PARAMETER );
7808 return NULL;
7811 switch (family)
7813 case WS_AF_INET:
7815 in = addr;
7816 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
7817 break;
7819 case WS_AF_INET6:
7821 in6 = addr;
7822 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
7823 break;
7825 default:
7826 SetLastError( WSAEAFNOSUPPORT );
7827 return NULL;
7830 if (!pdst) SetLastError( STATUS_INVALID_PARAMETER );
7831 return pdst;
7832 #else
7833 FIXME( "not supported on this platform\n" );
7834 SetLastError( WSAEAFNOSUPPORT );
7835 return NULL;
7836 #endif
7839 /***********************************************************************
7840 * inet_pton (WS2_32.@)
7842 INT WINAPI WS_inet_pton( INT family, PCSTR addr, PVOID buffer)
7844 #ifdef HAVE_INET_PTON
7845 int unixaf, ret;
7847 TRACE("family %d, addr %s, buffer (%p)\n", family, debugstr_a(addr), buffer);
7849 if (!addr || !buffer)
7851 SetLastError(WSAEFAULT);
7852 return SOCKET_ERROR;
7855 unixaf = convert_af_w2u(family);
7856 if (unixaf != AF_INET && unixaf != AF_INET6)
7858 SetLastError(WSAEAFNOSUPPORT);
7859 return SOCKET_ERROR;
7862 ret = inet_pton(unixaf, addr, buffer);
7863 if (ret == -1) SetLastError(wsaErrno());
7864 return ret;
7865 #else
7866 FIXME( "not supported on this platform\n" );
7867 SetLastError( WSAEAFNOSUPPORT );
7868 return SOCKET_ERROR;
7869 #endif
7872 /***********************************************************************
7873 * InetPtonW (WS2_32.@)
7875 INT WINAPI InetPtonW(INT family, PCWSTR addr, PVOID buffer)
7877 char *addrA;
7878 int len;
7879 INT ret;
7881 TRACE("family %d, addr %s, buffer (%p)\n", family, debugstr_w(addr), buffer);
7883 if (!addr)
7885 SetLastError(WSAEFAULT);
7886 return SOCKET_ERROR;
7889 len = WideCharToMultiByte(CP_ACP, 0, addr, -1, NULL, 0, NULL, NULL);
7890 if (!(addrA = HeapAlloc(GetProcessHeap(), 0, len)))
7892 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7893 return SOCKET_ERROR;
7895 WideCharToMultiByte(CP_ACP, 0, addr, -1, addrA, len, NULL, NULL);
7897 ret = WS_inet_pton(family, addrA, buffer);
7899 HeapFree(GetProcessHeap(), 0, addrA);
7900 return ret;
7903 /***********************************************************************
7904 * WSAStringToAddressA (WS2_32.80)
7906 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
7907 INT AddressFamily,
7908 LPWSAPROTOCOL_INFOA lpProtocolInfo,
7909 LPSOCKADDR lpAddress,
7910 LPINT lpAddressLength)
7912 INT res=0;
7913 LPSTR workBuffer=NULL,ptrPort;
7915 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
7916 lpProtocolInfo, lpAddress, lpAddressLength );
7918 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
7920 if (!AddressString)
7922 SetLastError(WSAEINVAL);
7923 return SOCKET_ERROR;
7926 if (lpProtocolInfo)
7927 FIXME("ProtocolInfo not implemented.\n");
7929 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
7930 strlen(AddressString) + 1);
7931 if (!workBuffer)
7933 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7934 return SOCKET_ERROR;
7937 strcpy(workBuffer, AddressString);
7939 switch(AddressFamily)
7941 case WS_AF_INET:
7943 struct in_addr inetaddr;
7945 /* If lpAddressLength is too small, tell caller the size we need */
7946 if (*lpAddressLength < sizeof(SOCKADDR_IN))
7948 *lpAddressLength = sizeof(SOCKADDR_IN);
7949 res = WSAEFAULT;
7950 break;
7952 *lpAddressLength = sizeof(SOCKADDR_IN);
7953 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
7955 ((LPSOCKADDR_IN)lpAddress)->sin_family = WS_AF_INET;
7957 ptrPort = strchr(workBuffer, ':');
7958 if(ptrPort)
7960 /* User may have entered an IPv6 and asked to parse as IPv4 */
7961 if(strchr(ptrPort + 1, ':'))
7963 res = WSAEINVAL;
7964 break;
7966 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
7967 *ptrPort = '\0';
7969 else
7971 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
7974 if(inet_aton(workBuffer, &inetaddr) > 0)
7976 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
7977 res = 0;
7979 else
7980 res = WSAEINVAL;
7982 break;
7985 case WS_AF_INET6:
7987 struct in6_addr inetaddr;
7988 /* If lpAddressLength is too small, tell caller the size we need */
7989 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
7991 *lpAddressLength = sizeof(SOCKADDR_IN6);
7992 res = WSAEFAULT;
7993 break;
7995 #ifdef HAVE_INET_PTON
7996 *lpAddressLength = sizeof(SOCKADDR_IN6);
7997 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
7999 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
8001 /* This one is a bit tricky. An IPv6 address contains colons, so the
8002 * check from IPv4 doesn't work like that. However, IPv6 addresses that
8003 * contain a port are written with braces like [fd12:3456:7890::1]:12345
8004 * so what we will do is to look for ']', check if the next char is a
8005 * colon, and if it is, parse the port as in IPv4. */
8007 ptrPort = strchr(workBuffer, ']');
8008 if(ptrPort && *(++ptrPort) == ':')
8010 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort+1));
8011 *ptrPort = '\0';
8013 else
8015 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
8018 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
8020 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
8021 sizeof(struct in6_addr));
8022 res = 0;
8024 else
8025 #endif /* HAVE_INET_PTON */
8026 res = WSAEINVAL;
8028 break;
8030 default:
8031 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
8032 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
8033 res = WSAEINVAL;
8036 HeapFree(GetProcessHeap(), 0, workBuffer);
8038 if (!res) return 0;
8039 SetLastError(res);
8040 return SOCKET_ERROR;
8043 /***********************************************************************
8044 * WSAStringToAddressW (WS2_32.81)
8046 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
8047 * If this should be the case, it would be required to map these digits
8048 * to Unicode digits (0-9) using FoldString first.
8050 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
8051 INT AddressFamily,
8052 LPWSAPROTOCOL_INFOW lpProtocolInfo,
8053 LPSOCKADDR lpAddress,
8054 LPINT lpAddressLength)
8056 INT sBuffer,res=0;
8057 LPSTR workBuffer=NULL;
8058 WSAPROTOCOL_INFOA infoA;
8059 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
8061 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
8062 lpAddress, lpAddressLength );
8064 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
8066 /* if ProtocolInfo is available - convert to ANSI variant */
8067 if (lpProtocolInfo)
8069 lpProtoInfoA = &infoA;
8070 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
8072 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
8073 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
8075 SetLastError(WSAEINVAL);
8076 return SOCKET_ERROR;
8080 if (AddressString)
8082 /* Translate AddressString to ANSI code page - assumes that only
8083 standard digits 0-9 are used with this API call */
8084 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
8085 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
8087 if (workBuffer)
8089 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
8090 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
8091 lpAddress,lpAddressLength);
8092 HeapFree( GetProcessHeap(), 0, workBuffer );
8093 return res;
8095 else
8096 res = WSA_NOT_ENOUGH_MEMORY;
8098 else
8099 res = WSAEINVAL;
8101 SetLastError(res);
8102 return SOCKET_ERROR;
8105 /***********************************************************************
8106 * WSAAddressToStringA (WS2_32.27)
8108 * See WSAAddressToStringW
8110 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
8111 LPWSAPROTOCOL_INFOA info, LPSTR string,
8112 LPDWORD lenstr )
8114 DWORD size;
8115 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
8116 CHAR *p;
8118 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
8120 if (!sockaddr) return SOCKET_ERROR;
8121 if (!string || !lenstr) return SOCKET_ERROR;
8123 switch(sockaddr->sa_family)
8125 case WS_AF_INET:
8126 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
8127 sprintf( buffer, "%u.%u.%u.%u:%u",
8128 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
8129 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
8130 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
8131 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
8132 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
8134 p = strchr( buffer, ':' );
8135 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
8136 break;
8138 case WS_AF_INET6:
8140 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
8141 size_t slen;
8143 buffer[0] = 0;
8144 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
8145 if ((sockaddr6->sin6_port))
8146 strcpy(buffer, "[");
8147 slen = strlen(buffer);
8148 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, &buffer[slen], sizeof(buffer) - slen))
8150 SetLastError(WSAEINVAL);
8151 return SOCKET_ERROR;
8153 if ((sockaddr6->sin6_scope_id))
8154 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
8155 if ((sockaddr6->sin6_port))
8156 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
8157 break;
8160 default:
8161 SetLastError(WSAEINVAL);
8162 return SOCKET_ERROR;
8165 size = strlen( buffer ) + 1;
8167 if (*lenstr < size)
8169 *lenstr = size;
8170 SetLastError(WSAEFAULT);
8171 return SOCKET_ERROR;
8174 TRACE("=> %s,%u bytes\n", debugstr_a(buffer), size);
8175 *lenstr = size;
8176 strcpy( string, buffer );
8177 return 0;
8180 /***********************************************************************
8181 * WSAAddressToStringW (WS2_32.28)
8183 * Convert a sockaddr address into a readable address string.
8185 * PARAMS
8186 * sockaddr [I] Pointer to a sockaddr structure.
8187 * len [I] Size of the sockaddr structure.
8188 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
8189 * string [I/O] Pointer to a buffer to receive the address string.
8190 * lenstr [I/O] Size of the receive buffer in WCHARs.
8192 * RETURNS
8193 * Success: 0
8194 * Failure: SOCKET_ERROR
8196 * NOTES
8197 * The 'info' parameter is ignored.
8199 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
8200 LPWSAPROTOCOL_INFOW info, LPWSTR string,
8201 LPDWORD lenstr )
8203 INT ret;
8204 DWORD size;
8205 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
8206 CHAR bufAddr[54];
8208 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
8210 size = *lenstr;
8211 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
8213 if (ret) return ret;
8215 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
8217 if (*lenstr < size)
8219 *lenstr = size;
8220 SetLastError(WSAEFAULT);
8221 return SOCKET_ERROR;
8224 TRACE("=> %s,%u bytes\n", debugstr_w(buffer), size);
8225 *lenstr = size;
8226 lstrcpyW( string, buffer );
8227 return 0;
8230 /***********************************************************************
8231 * WSAEnumNameSpaceProvidersA (WS2_32.34)
8233 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
8235 FIXME( "(%p %p) Stub!\n", len, buffer );
8236 return 0;
8239 /***********************************************************************
8240 * WSAEnumNameSpaceProvidersW (WS2_32.35)
8242 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
8244 FIXME( "(%p %p) Stub!\n", len, buffer );
8245 return 0;
8248 /***********************************************************************
8249 * WSAGetQOSByName (WS2_32.41)
8251 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
8253 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
8254 return FALSE;
8257 /***********************************************************************
8258 * WSAGetServiceClassInfoA (WS2_32.42)
8260 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
8261 LPWSASERVICECLASSINFOA info )
8263 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
8264 len, info );
8265 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8266 return SOCKET_ERROR;
8269 /***********************************************************************
8270 * WSAGetServiceClassInfoW (WS2_32.43)
8272 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
8273 LPWSASERVICECLASSINFOW info )
8275 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
8276 len, info );
8277 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8278 return SOCKET_ERROR;
8281 /***********************************************************************
8282 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
8284 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
8286 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
8287 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8288 return SOCKET_ERROR;
8291 /***********************************************************************
8292 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
8294 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
8296 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
8297 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8298 return SOCKET_ERROR;
8301 /***********************************************************************
8302 * WSALookupServiceBeginA (WS2_32.59)
8304 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
8305 DWORD dwControlFlags,
8306 LPHANDLE lphLookup)
8308 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
8309 lphLookup);
8310 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8311 return SOCKET_ERROR;
8314 /***********************************************************************
8315 * WSALookupServiceBeginW (WS2_32.60)
8317 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
8318 DWORD dwControlFlags,
8319 LPHANDLE lphLookup)
8321 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
8322 lphLookup);
8323 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8324 return SOCKET_ERROR;
8327 /***********************************************************************
8328 * WSALookupServiceEnd (WS2_32.61)
8330 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
8332 FIXME("(%p) Stub!\n", lookup );
8333 return 0;
8336 /***********************************************************************
8337 * WSALookupServiceNextA (WS2_32.62)
8339 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
8341 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
8342 SetLastError(WSA_E_NO_MORE);
8343 return SOCKET_ERROR;
8346 /***********************************************************************
8347 * WSALookupServiceNextW (WS2_32.63)
8349 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
8351 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
8352 SetLastError(WSA_E_NO_MORE);
8353 return SOCKET_ERROR;
8356 /***********************************************************************
8357 * WSANtohl (WS2_32.64)
8359 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
8361 TRACE( "(%04lx 0x%08x %p)\n", s, netlong, lphostlong );
8363 if (!lphostlong) return WSAEFAULT;
8365 *lphostlong = ntohl( netlong );
8366 return 0;
8369 /***********************************************************************
8370 * WSANtohs (WS2_32.65)
8372 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
8374 TRACE( "(%04lx 0x%08x %p)\n", s, netshort, lphostshort );
8376 if (!lphostshort) return WSAEFAULT;
8378 *lphostshort = ntohs( netshort );
8379 return 0;
8382 /***********************************************************************
8383 * WSAProviderConfigChange (WS2_32.66)
8385 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
8386 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
8388 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
8389 return SOCKET_ERROR;
8392 /***********************************************************************
8393 * WSARecvDisconnect (WS2_32.68)
8395 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
8397 TRACE( "(%04lx %p)\n", s, disconnectdata );
8399 return WS_shutdown( s, SD_RECEIVE );
8402 /***********************************************************************
8403 * WSASetServiceA (WS2_32.76)
8405 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
8407 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
8408 return 0;
8411 /***********************************************************************
8412 * WSASetServiceW (WS2_32.77)
8414 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
8416 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
8417 return 0;
8420 /***********************************************************************
8421 * WSCEnableNSProvider (WS2_32.84)
8423 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
8425 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
8426 return 0;
8429 /***********************************************************************
8430 * WSCGetProviderPath (WS2_32.86)
8432 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
8434 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
8436 if (!errcode || !provider || !len) return WSAEFAULT;
8438 *errcode = WSAEINVAL;
8439 return SOCKET_ERROR;
8442 /***********************************************************************
8443 * WSCInstallNameSpace (WS2_32.87)
8445 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
8446 DWORD version, LPGUID provider )
8448 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
8449 namespace, version, debugstr_guid(provider) );
8450 return 0;
8453 /***********************************************************************
8454 * WSCUnInstallNameSpace (WS2_32.89)
8456 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
8458 FIXME("(%p) Stub!\n", lpProviderId);
8459 return NO_ERROR;
8462 /***********************************************************************
8463 * WSCWriteProviderOrder (WS2_32.91)
8465 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
8467 FIXME("(%p 0x%08x) Stub!\n", entry, number);
8468 return 0;
8471 /***********************************************************************
8472 * WSANSPIoctl (WS2_32.91)
8474 INT WINAPI WSANSPIoctl( HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer,
8475 DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer,
8476 LPDWORD lpcbBytesReturned, LPWSACOMPLETION lpCompletion )
8478 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup, dwControlCode,
8479 lpvInBuffer, cbInBuffer, lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpCompletion);
8480 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8481 return SOCKET_ERROR;
8484 /*****************************************************************************
8485 * WSAEnumProtocolsA [WS2_32.@]
8487 * see function WSAEnumProtocolsW
8489 INT WINAPI WSAEnumProtocolsA( LPINT protocols, LPWSAPROTOCOL_INFOA buffer, LPDWORD len )
8491 return WS_EnumProtocols( FALSE, protocols, (LPWSAPROTOCOL_INFOW) buffer, len);
8494 /*****************************************************************************
8495 * WSAEnumProtocolsW [WS2_32.@]
8497 * Retrieves information about specified set of active network protocols.
8499 * PARAMS
8500 * protocols [I] Pointer to null-terminated array of protocol id's. NULL
8501 * retrieves information on all available protocols.
8502 * buffer [I] Pointer to a buffer to be filled with WSAPROTOCOL_INFO
8503 * structures.
8504 * len [I/O] Pointer to a variable specifying buffer size. On output
8505 * the variable holds the number of bytes needed when the
8506 * specified size is too small.
8508 * RETURNS
8509 * Success: number of WSAPROTOCOL_INFO structures in buffer.
8510 * Failure: SOCKET_ERROR
8512 * NOTES
8513 * NT4SP5 does not return SPX if protocols == NULL
8515 * BUGS
8516 * - NT4SP5 returns in addition these list of NETBIOS protocols
8517 * (address family 17), each entry two times one for socket type 2 and 5
8519 * iProtocol szProtocol
8520 * 0x80000000 \Device\NwlnkNb
8521 * 0xfffffffa \Device\NetBT_CBENT7
8522 * 0xfffffffb \Device\Nbf_CBENT7
8523 * 0xfffffffc \Device\NetBT_NdisWan5
8524 * 0xfffffffd \Device\NetBT_El9202
8525 * 0xfffffffe \Device\Nbf_El9202
8526 * 0xffffffff \Device\Nbf_NdisWan4
8528 * - there is no check that the operating system supports the returned
8529 * protocols
8531 INT WINAPI WSAEnumProtocolsW( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
8533 return WS_EnumProtocols( TRUE, protocols, buffer, len);
8536 /*****************************************************************************
8537 * WSCEnumProtocols [WS2_32.@]
8539 * PARAMS
8540 * protocols [I] Null-terminated array of iProtocol values.
8541 * buffer [O] Buffer of WSAPROTOCOL_INFOW structures.
8542 * len [I/O] Size of buffer on input/output.
8543 * errno [O] Error code.
8545 * RETURNS
8546 * Success: number of protocols to be reported on.
8547 * Failure: SOCKET_ERROR. error is in errno.
8549 * BUGS
8550 * Doesn't supply info on layered protocols.
8553 INT WINAPI WSCEnumProtocols( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len, LPINT err )
8555 INT ret = WSAEnumProtocolsW( protocols, buffer, len );
8557 if (ret == SOCKET_ERROR) *err = WSAENOBUFS;
8559 return ret;