ws2_32: Add a couple of options to sockopt debug.
[wine/multimedia.git] / dlls / ws2_32 / socket.c
blobd31f0b4a8de8212c228394f281fddcf76e8052c5
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 char magic_loopback_addr[] = {127, 12, 34, 56};
778 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
779 #ifdef IP_PKTINFO
780 static inline WSACMSGHDR *fill_control_message(int level, int type, WSACMSGHDR *current, ULONG *maxsize, void *data, int len)
782 ULONG msgsize = sizeof(WSACMSGHDR) + WSA_CMSG_ALIGN(len);
783 char *ptr = (char *) current + sizeof(WSACMSGHDR);
785 /* Make sure there is at least enough room for this entry */
786 if (msgsize > *maxsize)
787 return NULL;
788 *maxsize -= msgsize;
789 /* Fill in the entry */
790 current->cmsg_len = sizeof(WSACMSGHDR) + len;
791 current->cmsg_level = level;
792 current->cmsg_type = type;
793 memcpy(ptr, data, len);
794 /* Return the pointer to where next entry should go */
795 return (WSACMSGHDR *) (ptr + WSA_CMSG_ALIGN(len));
797 #endif /* IP_PKTINFO */
799 static inline int convert_control_headers(struct msghdr *hdr, WSABUF *control)
801 #ifdef IP_PKTINFO
802 WSACMSGHDR *cmsg_win = (WSACMSGHDR *) control->buf, *ptr;
803 ULONG ctlsize = control->len;
804 struct cmsghdr *cmsg_unix;
806 ptr = cmsg_win;
807 /* Loop over all the headers, converting as appropriate */
808 for (cmsg_unix = CMSG_FIRSTHDR(hdr); cmsg_unix != NULL; cmsg_unix = CMSG_NXTHDR(hdr, cmsg_unix))
810 switch(cmsg_unix->cmsg_level)
812 case IPPROTO_IP:
813 switch(cmsg_unix->cmsg_type)
815 case IP_PKTINFO:
817 /* Convert the Unix IP_PKTINFO structure to the Windows version */
818 struct in_pktinfo *data_unix = (struct in_pktinfo *) CMSG_DATA(cmsg_unix);
819 struct WS_in_pktinfo data_win;
821 memcpy(&data_win.ipi_addr,&data_unix->ipi_addr.s_addr,4); /* 4 bytes = 32 address bits */
822 data_win.ipi_ifindex = data_unix->ipi_ifindex;
823 ptr = fill_control_message(WS_IPPROTO_IP, WS_IP_PKTINFO, ptr, &ctlsize,
824 (void*)&data_win, sizeof(data_win));
825 if (!ptr) goto error;
826 } break;
827 default:
828 FIXME("Unhandled IPPROTO_IP message header type %d\n", cmsg_unix->cmsg_type);
829 break;
831 break;
832 default:
833 FIXME("Unhandled message header level %d\n", cmsg_unix->cmsg_level);
834 break;
838 error:
839 /* Set the length of the returned control headers */
840 control->len = (ptr == NULL ? 0 : (char*)ptr - (char*)cmsg_win);
841 return (ptr != NULL);
842 #else /* IP_PKTINFO */
843 control->len = 0;
844 return 1;
845 #endif /* IP_PKTINFO */
847 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
849 /* ----------------------------------- error handling */
851 static NTSTATUS sock_get_ntstatus( int err )
853 switch ( err )
855 case EBADF: return STATUS_INVALID_HANDLE;
856 case EBUSY: return STATUS_DEVICE_BUSY;
857 case EPERM:
858 case EACCES: return STATUS_ACCESS_DENIED;
859 case EFAULT: return STATUS_NO_MEMORY;
860 case EINVAL: return STATUS_INVALID_PARAMETER;
861 case ENFILE:
862 case EMFILE: return STATUS_TOO_MANY_OPENED_FILES;
863 case EWOULDBLOCK: return STATUS_CANT_WAIT;
864 case EINPROGRESS: return STATUS_PENDING;
865 case EALREADY: return STATUS_NETWORK_BUSY;
866 case ENOTSOCK: return STATUS_OBJECT_TYPE_MISMATCH;
867 case EDESTADDRREQ: return STATUS_INVALID_PARAMETER;
868 case EMSGSIZE: return STATUS_BUFFER_OVERFLOW;
869 case EPROTONOSUPPORT:
870 case ESOCKTNOSUPPORT:
871 case EPFNOSUPPORT:
872 case EAFNOSUPPORT:
873 case EPROTOTYPE: return STATUS_NOT_SUPPORTED;
874 case ENOPROTOOPT: return STATUS_INVALID_PARAMETER;
875 case EOPNOTSUPP: return STATUS_NOT_SUPPORTED;
876 case EADDRINUSE: return STATUS_ADDRESS_ALREADY_ASSOCIATED;
877 case EADDRNOTAVAIL: return STATUS_INVALID_PARAMETER;
878 case ECONNREFUSED: return STATUS_CONNECTION_REFUSED;
879 case ESHUTDOWN: return STATUS_PIPE_DISCONNECTED;
880 case ENOTCONN: return STATUS_CONNECTION_DISCONNECTED;
881 case ETIMEDOUT: return STATUS_IO_TIMEOUT;
882 case ENETUNREACH: return STATUS_NETWORK_UNREACHABLE;
883 case ENETDOWN: return STATUS_NETWORK_BUSY;
884 case EPIPE:
885 case ECONNRESET: return STATUS_CONNECTION_RESET;
886 case ECONNABORTED: return STATUS_CONNECTION_ABORTED;
888 case 0: return STATUS_SUCCESS;
889 default:
890 WARN("Unknown errno %d!\n", err);
891 return STATUS_UNSUCCESSFUL;
895 static UINT sock_get_error( int err )
897 switch(err)
899 case EINTR: return WSAEINTR;
900 case EPERM:
901 case EACCES: return WSAEACCES;
902 case EFAULT: return WSAEFAULT;
903 case EINVAL: return WSAEINVAL;
904 case EMFILE: return WSAEMFILE;
905 case EWOULDBLOCK: return WSAEWOULDBLOCK;
906 case EINPROGRESS: return WSAEINPROGRESS;
907 case EALREADY: return WSAEALREADY;
908 case EBADF:
909 case ENOTSOCK: return WSAENOTSOCK;
910 case EDESTADDRREQ: return WSAEDESTADDRREQ;
911 case EMSGSIZE: return WSAEMSGSIZE;
912 case EPROTOTYPE: return WSAEPROTOTYPE;
913 case ENOPROTOOPT: return WSAENOPROTOOPT;
914 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
915 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
916 case EOPNOTSUPP: return WSAEOPNOTSUPP;
917 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
918 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
919 case EADDRINUSE: return WSAEADDRINUSE;
920 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
921 case ENETDOWN: return WSAENETDOWN;
922 case ENETUNREACH: return WSAENETUNREACH;
923 case ENETRESET: return WSAENETRESET;
924 case ECONNABORTED: return WSAECONNABORTED;
925 case EPIPE:
926 case ECONNRESET: return WSAECONNRESET;
927 case ENOBUFS: return WSAENOBUFS;
928 case EISCONN: return WSAEISCONN;
929 case ENOTCONN: return WSAENOTCONN;
930 case ESHUTDOWN: return WSAESHUTDOWN;
931 case ETOOMANYREFS: return WSAETOOMANYREFS;
932 case ETIMEDOUT: return WSAETIMEDOUT;
933 case ECONNREFUSED: return WSAECONNREFUSED;
934 case ELOOP: return WSAELOOP;
935 case ENAMETOOLONG: return WSAENAMETOOLONG;
936 case EHOSTDOWN: return WSAEHOSTDOWN;
937 case EHOSTUNREACH: return WSAEHOSTUNREACH;
938 case ENOTEMPTY: return WSAENOTEMPTY;
939 #ifdef EPROCLIM
940 case EPROCLIM: return WSAEPROCLIM;
941 #endif
942 #ifdef EUSERS
943 case EUSERS: return WSAEUSERS;
944 #endif
945 #ifdef EDQUOT
946 case EDQUOT: return WSAEDQUOT;
947 #endif
948 #ifdef ESTALE
949 case ESTALE: return WSAESTALE;
950 #endif
951 #ifdef EREMOTE
952 case EREMOTE: return WSAEREMOTE;
953 #endif
955 /* just in case we ever get here and there are no problems */
956 case 0: return 0;
957 default:
958 WARN("Unknown errno %d!\n", err);
959 return WSAEOPNOTSUPP;
963 static UINT wsaErrno(void)
965 int loc_errno = errno;
966 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
968 return sock_get_error( loc_errno );
971 /* most ws2 overlapped functions return an ntstatus-based error code */
972 static NTSTATUS wsaErrStatus(void)
974 int loc_errno = errno;
975 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
977 return sock_get_ntstatus(loc_errno);
980 static UINT wsaHerrno(int loc_errno)
982 WARN("h_errno %d.\n", loc_errno);
984 switch(loc_errno)
986 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
987 case TRY_AGAIN: return WSATRY_AGAIN;
988 case NO_RECOVERY: return WSANO_RECOVERY;
989 case NO_DATA: return WSANO_DATA;
990 case ENOBUFS: return WSAENOBUFS;
992 case 0: return 0;
993 default:
994 WARN("Unknown h_errno %d!\n", loc_errno);
995 return WSAEOPNOTSUPP;
999 static inline DWORD NtStatusToWSAError( const DWORD status )
1001 /* We only need to cover the status codes set by server async request handling */
1002 DWORD wserr;
1003 switch ( status )
1005 case STATUS_SUCCESS: wserr = 0; break;
1006 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
1007 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
1008 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
1009 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
1010 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
1011 case STATUS_NETWORK_BUSY: wserr = WSAEALREADY; break;
1012 case STATUS_NETWORK_UNREACHABLE: wserr = WSAENETUNREACH; break;
1013 case STATUS_CONNECTION_REFUSED: wserr = WSAECONNREFUSED; break;
1014 case STATUS_CONNECTION_DISCONNECTED: wserr = WSAENOTCONN; break;
1015 case STATUS_CONNECTION_RESET: wserr = WSAECONNRESET; break;
1016 case STATUS_CONNECTION_ABORTED: wserr = WSAECONNABORTED; break;
1017 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
1018 case STATUS_ADDRESS_ALREADY_ASSOCIATED: wserr = WSAEADDRINUSE; break;
1019 case STATUS_IO_TIMEOUT:
1020 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
1021 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
1022 case STATUS_ACCESS_DENIED: wserr = WSAEACCES; break;
1023 case STATUS_TOO_MANY_OPENED_FILES: wserr = WSAEMFILE; break;
1024 case STATUS_CANT_WAIT: wserr = WSAEWOULDBLOCK; break;
1025 case STATUS_BUFFER_OVERFLOW: wserr = WSAEMSGSIZE; break;
1026 case STATUS_NOT_SUPPORTED: wserr = WSAEOPNOTSUPP; break;
1027 case STATUS_HOST_UNREACHABLE: wserr = WSAEHOSTUNREACH; break;
1029 default:
1030 wserr = RtlNtStatusToDosError( status );
1031 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
1033 return wserr;
1036 /* set last error code from NT status without mapping WSA errors */
1037 static inline unsigned int set_error( unsigned int err )
1039 if (err)
1041 err = NtStatusToWSAError( err );
1042 SetLastError( err );
1044 return err;
1047 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
1049 int fd;
1050 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
1051 return -1;
1052 return fd;
1055 static inline void release_sock_fd( SOCKET s, int fd )
1057 wine_server_release_fd( SOCKET2HANDLE(s), fd );
1060 static void _enable_event( HANDLE s, unsigned int event,
1061 unsigned int sstate, unsigned int cstate )
1063 SERVER_START_REQ( enable_socket_event )
1065 req->handle = wine_server_obj_handle( s );
1066 req->mask = event;
1067 req->sstate = sstate;
1068 req->cstate = cstate;
1069 wine_server_call( req );
1071 SERVER_END_REQ;
1074 static NTSTATUS _is_blocking(SOCKET s, BOOL *ret)
1076 NTSTATUS status;
1077 SERVER_START_REQ( get_socket_event )
1079 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1080 req->service = FALSE;
1081 req->c_event = 0;
1082 status = wine_server_call( req );
1083 *ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
1085 SERVER_END_REQ;
1086 return status;
1089 static unsigned int _get_sock_mask(SOCKET s)
1091 unsigned int ret;
1092 SERVER_START_REQ( get_socket_event )
1094 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1095 req->service = FALSE;
1096 req->c_event = 0;
1097 wine_server_call( req );
1098 ret = reply->mask;
1100 SERVER_END_REQ;
1101 return ret;
1104 static void _sync_sock_state(SOCKET s)
1106 BOOL dummy;
1107 /* do a dummy wineserver request in order to let
1108 the wineserver run through its select loop once */
1109 (void)_is_blocking(s, &dummy);
1112 static void _get_sock_errors(SOCKET s, int *events)
1114 SERVER_START_REQ( get_socket_event )
1116 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1117 req->service = FALSE;
1118 req->c_event = 0;
1119 wine_server_set_reply( req, events, sizeof(int) * FD_MAX_EVENTS );
1120 wine_server_call( req );
1122 SERVER_END_REQ;
1125 static int _get_sock_error(SOCKET s, unsigned int bit)
1127 int events[FD_MAX_EVENTS];
1128 _get_sock_errors(s, events);
1129 return events[bit];
1132 static int _get_fd_type(int fd)
1134 int sock_type = -1;
1135 socklen_t optlen = sizeof(sock_type);
1136 getsockopt(fd, SOL_SOCKET, SO_TYPE, (char*) &sock_type, &optlen);
1137 return sock_type;
1140 static struct per_thread_data *get_per_thread_data(void)
1142 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
1143 /* lazy initialization */
1144 if (!ptb)
1146 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
1147 NtCurrentTeb()->WinSockData = ptb;
1149 return ptb;
1152 static void free_per_thread_data(void)
1154 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
1156 if (!ptb) return;
1158 /* delete scratch buffers */
1159 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1160 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1161 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1162 ptb->he_buffer = NULL;
1163 ptb->se_buffer = NULL;
1164 ptb->pe_buffer = NULL;
1166 HeapFree( GetProcessHeap(), 0, ptb );
1167 NtCurrentTeb()->WinSockData = NULL;
1170 /***********************************************************************
1171 * DllMain (WS2_32.init)
1173 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
1175 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
1176 switch (fdwReason) {
1177 case DLL_PROCESS_ATTACH:
1178 break;
1179 case DLL_PROCESS_DETACH:
1180 if (fImpLoad) break;
1181 free_per_thread_data();
1182 DeleteCriticalSection(&csWSgetXXXbyYYY);
1183 break;
1184 case DLL_THREAD_DETACH:
1185 free_per_thread_data();
1186 break;
1188 return TRUE;
1191 /***********************************************************************
1192 * convert_flags()
1194 * Converts send/recv flags from Windows format.
1195 * Return the converted flag bits, unsupported flags remain unchanged.
1197 static int convert_flags(int flags)
1199 int i, out;
1200 if (!flags) return 0;
1202 for (out = i = 0; flags && i < sizeof(ws_flags_map) / sizeof(ws_flags_map[0]); i++)
1204 if (ws_flags_map[i][0] & flags)
1206 out |= ws_flags_map[i][1];
1207 flags &= ~ws_flags_map[i][0];
1210 if (flags)
1212 FIXME("Unknown send/recv flags 0x%x, using anyway...\n", flags);
1213 out |= flags;
1215 return out;
1218 /***********************************************************************
1219 * convert_sockopt()
1221 * Converts socket flags from Windows format.
1222 * Return 1 if converted, 0 if not (error).
1224 static int convert_sockopt(INT *level, INT *optname)
1226 unsigned int i;
1227 switch (*level)
1229 case WS_SOL_SOCKET:
1230 *level = SOL_SOCKET;
1231 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
1232 if( ws_sock_map[i][0] == *optname )
1234 *optname = ws_sock_map[i][1];
1235 return 1;
1238 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
1239 break;
1240 case WS_IPPROTO_TCP:
1241 *level = IPPROTO_TCP;
1242 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
1243 if ( ws_tcp_map[i][0] == *optname )
1245 *optname = ws_tcp_map[i][1];
1246 return 1;
1249 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
1250 break;
1251 case WS_IPPROTO_IP:
1252 *level = IPPROTO_IP;
1253 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
1254 if (ws_ip_map[i][0] == *optname )
1256 *optname = ws_ip_map[i][1];
1257 return 1;
1260 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
1261 break;
1262 case WS_IPPROTO_IPV6:
1263 *level = IPPROTO_IPV6;
1264 for(i=0; i<sizeof(ws_ipv6_map)/sizeof(ws_ipv6_map[0]); i++) {
1265 if (ws_ipv6_map[i][0] == *optname )
1267 *optname = ws_ipv6_map[i][1];
1268 return 1;
1271 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname);
1272 break;
1273 default: FIXME("Unimplemented or unknown socket level\n");
1275 return 0;
1278 /* ----------------------------------- Per-thread info (or per-process?) */
1280 static char *strdup_lower(const char *str)
1282 int i;
1283 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
1285 if (ret)
1287 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
1288 ret[i] = 0;
1290 else SetLastError(WSAENOBUFS);
1291 return ret;
1294 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
1295 * from an fd and return the value converted to milli seconds
1296 * or 0 if there is an infinite time out */
1297 static inline INT64 get_rcvsnd_timeo( int fd, BOOL is_recv)
1299 struct timeval tv;
1300 socklen_t len = sizeof(tv);
1301 int optname, res;
1303 if (is_recv)
1304 #ifdef SO_RCVTIMEO
1305 optname = SO_RCVTIMEO;
1306 #else
1307 return 0;
1308 #endif
1309 else
1310 #ifdef SO_SNDTIMEO
1311 optname = SO_SNDTIMEO;
1312 #else
1313 return 0;
1314 #endif
1316 res = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
1317 if (res < 0)
1318 return 0;
1319 return (UINT64)tv.tv_sec * 1000 + tv.tv_usec / 1000;
1322 /* utility: given an fd, will block until one of the events occurs */
1323 static inline int do_block( int fd, int events, int timeout )
1325 struct pollfd pfd;
1326 int ret;
1328 pfd.fd = fd;
1329 pfd.events = events;
1331 while ((ret = poll(&pfd, 1, timeout)) < 0)
1333 if (errno != EINTR)
1334 return -1;
1336 if( ret == 0 )
1337 return 0;
1338 return pfd.revents;
1341 static int
1342 convert_af_w2u(int windowsaf) {
1343 unsigned int i;
1345 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1346 if (ws_af_map[i][0] == windowsaf)
1347 return ws_af_map[i][1];
1348 FIXME("unhandled Windows address family %d\n", windowsaf);
1349 return -1;
1352 static int
1353 convert_af_u2w(int unixaf) {
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][1] == unixaf)
1358 return ws_af_map[i][0];
1359 FIXME("unhandled UNIX address family %d\n", unixaf);
1360 return -1;
1363 static int
1364 convert_proto_w2u(int windowsproto) {
1365 unsigned int i;
1367 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1368 if (ws_proto_map[i][0] == windowsproto)
1369 return ws_proto_map[i][1];
1371 /* check for extended IPX */
1372 if (IS_IPX_PROTO(windowsproto))
1373 return windowsproto;
1375 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
1376 return -1;
1379 static int
1380 convert_proto_u2w(int unixproto) {
1381 unsigned int i;
1383 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1384 if (ws_proto_map[i][1] == unixproto)
1385 return ws_proto_map[i][0];
1387 /* if value is inside IPX range just return it - the kernel simply
1388 * echoes the value used in the socket() function */
1389 if (IS_IPX_PROTO(unixproto))
1390 return unixproto;
1392 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
1393 return -1;
1396 static int
1397 convert_socktype_w2u(int windowssocktype) {
1398 unsigned int i;
1400 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1401 if (ws_socktype_map[i][0] == windowssocktype)
1402 return ws_socktype_map[i][1];
1403 FIXME("unhandled Windows socket type %d\n", windowssocktype);
1404 return -1;
1407 static int
1408 convert_socktype_u2w(int unixsocktype) {
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][1] == unixsocktype)
1413 return ws_socktype_map[i][0];
1414 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
1415 return -1;
1418 static int set_ipx_packettype(int sock, int ptype)
1420 #ifdef HAS_IPX
1421 int fd = get_sock_fd( sock, 0, NULL ), ret = 0;
1422 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", ptype, fd);
1424 if (fd == -1) return SOCKET_ERROR;
1426 /* We try to set the ipx type on ipx socket level. */
1427 #ifdef SOL_IPX
1428 if(setsockopt(fd, SOL_IPX, IPX_TYPE, &ptype, sizeof(ptype)) == -1)
1430 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
1431 ret = SOCKET_ERROR;
1433 #else
1435 struct ipx val;
1436 /* Should we retrieve val using a getsockopt call and then
1437 * set the modified one? */
1438 val.ipx_pt = ptype;
1439 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
1441 #endif
1442 release_sock_fd( sock, fd );
1443 return ret;
1444 #else
1445 WARN("IPX support is not enabled, can't set packet type\n");
1446 return SOCKET_ERROR;
1447 #endif
1450 /* ----------------------------------- API -----
1452 * Init / cleanup / error checking.
1455 /***********************************************************************
1456 * WSAStartup (WS2_32.115)
1458 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
1460 TRACE("verReq=%x\n", wVersionRequested);
1462 if (LOBYTE(wVersionRequested) < 1)
1463 return WSAVERNOTSUPPORTED;
1465 if (!lpWSAData) return WSAEINVAL;
1467 num_startup++;
1469 /* that's the whole of the negotiation for now */
1470 lpWSAData->wVersion = wVersionRequested;
1471 /* return winsock information */
1472 lpWSAData->wHighVersion = 0x0202;
1473 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
1474 strcpy(lpWSAData->szSystemStatus, "Running" );
1475 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
1476 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
1477 /* don't do anything with lpWSAData->lpVendorInfo */
1478 /* (some apps don't allocate the space for this field) */
1480 TRACE("succeeded starts: %d\n", num_startup);
1481 return 0;
1485 /***********************************************************************
1486 * WSACleanup (WS2_32.116)
1488 INT WINAPI WSACleanup(void)
1490 if (num_startup) {
1491 num_startup--;
1492 TRACE("pending cleanups: %d\n", num_startup);
1493 return 0;
1495 SetLastError(WSANOTINITIALISED);
1496 return SOCKET_ERROR;
1500 /***********************************************************************
1501 * WSAGetLastError (WS2_32.111)
1503 INT WINAPI WSAGetLastError(void)
1505 return GetLastError();
1508 /***********************************************************************
1509 * WSASetLastError (WS2_32.112)
1511 void WINAPI WSASetLastError(INT iError) {
1512 SetLastError(iError);
1515 static struct WS_hostent *check_buffer_he(int size)
1517 struct per_thread_data * ptb = get_per_thread_data();
1518 if (ptb->he_buffer)
1520 if (ptb->he_len >= size ) return ptb->he_buffer;
1521 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1523 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
1524 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
1525 return ptb->he_buffer;
1528 static struct WS_servent *check_buffer_se(int size)
1530 struct per_thread_data * ptb = get_per_thread_data();
1531 if (ptb->se_buffer)
1533 if (ptb->se_len >= size ) return ptb->se_buffer;
1534 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1536 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
1537 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
1538 return ptb->se_buffer;
1541 static struct WS_protoent *check_buffer_pe(int size)
1543 struct per_thread_data * ptb = get_per_thread_data();
1544 if (ptb->pe_buffer)
1546 if (ptb->pe_len >= size ) return ptb->pe_buffer;
1547 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1549 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
1550 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
1551 return ptb->pe_buffer;
1554 /* ----------------------------------- i/o APIs */
1556 static inline BOOL supported_pf(int pf)
1558 switch (pf)
1560 case WS_AF_INET:
1561 case WS_AF_INET6:
1562 return TRUE;
1563 #ifdef HAS_IPX
1564 case WS_AF_IPX:
1565 return TRUE;
1566 #endif
1567 #ifdef HAS_IRDA
1568 case WS_AF_IRDA:
1569 return TRUE;
1570 #endif
1571 default:
1572 return FALSE;
1576 static inline BOOL supported_protocol(int protocol)
1578 int i;
1579 for (i = 0; i < sizeof(valid_protocols) / sizeof(valid_protocols[0]); i++)
1580 if (protocol == valid_protocols[i])
1581 return TRUE;
1582 return FALSE;
1585 /**********************************************************************/
1587 /* Returns the length of the converted address if successful, 0 if it was too small to
1588 * start with.
1590 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
1591 union generic_unix_sockaddr *uaddr)
1593 unsigned int uaddrlen = 0;
1595 switch (wsaddr->sa_family)
1597 #ifdef HAS_IPX
1598 case WS_AF_IPX:
1600 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
1601 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
1603 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
1604 return 0;
1606 uaddrlen = sizeof(struct sockaddr_ipx);
1607 memset( uaddr, 0, uaddrlen );
1608 uipx->sipx_family=AF_IPX;
1609 uipx->sipx_port=wsipx->sa_socket;
1610 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1611 * in one go
1613 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
1614 #ifdef IPX_FRAME_NONE
1615 uipx->sipx_type=IPX_FRAME_NONE;
1616 #endif
1617 break;
1619 #endif
1620 case WS_AF_INET6: {
1621 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
1622 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
1624 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1625 * scope_id, one without.
1627 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
1628 uaddrlen = sizeof(struct sockaddr_in6);
1629 memset( uaddr, 0, uaddrlen );
1630 uin6->sin6_family = AF_INET6;
1631 uin6->sin6_port = win6->sin6_port;
1632 uin6->sin6_flowinfo = win6->sin6_flowinfo;
1633 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1634 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
1635 #endif
1636 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
1637 break;
1639 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
1640 return 0;
1642 case WS_AF_INET: {
1643 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
1644 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
1646 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
1647 return 0;
1648 uaddrlen = sizeof(struct sockaddr_in);
1649 memset( uaddr, 0, uaddrlen );
1650 uin->sin_family = AF_INET;
1651 uin->sin_port = win->sin_port;
1652 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
1653 break;
1655 #ifdef HAS_IRDA
1656 case WS_AF_IRDA: {
1657 struct sockaddr_irda *uin = (struct sockaddr_irda *)uaddr;
1658 const SOCKADDR_IRDA *win = (const SOCKADDR_IRDA *)wsaddr;
1660 if (wsaddrlen < sizeof(SOCKADDR_IRDA))
1661 return 0;
1662 uaddrlen = sizeof(struct sockaddr_irda);
1663 memset( uaddr, 0, uaddrlen );
1664 uin->sir_family = AF_IRDA;
1665 if (!strncmp( win->irdaServiceName, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1667 unsigned int lsap_sel = 0;
1669 sscanf( win->irdaServiceName, "LSAP-SEL%u", &lsap_sel );
1670 uin->sir_lsap_sel = lsap_sel;
1672 else
1674 uin->sir_lsap_sel = LSAP_ANY;
1675 memcpy( uin->sir_name, win->irdaServiceName, 25 );
1677 memcpy( &uin->sir_addr, win->irdaDeviceID, sizeof(uin->sir_addr) );
1678 break;
1680 #endif
1681 case WS_AF_UNSPEC: {
1682 /* Try to determine the needed space by the passed windows sockaddr space */
1683 switch (wsaddrlen) {
1684 default: /* likely an ipv4 address */
1685 case sizeof(struct WS_sockaddr_in):
1686 uaddrlen = sizeof(struct sockaddr_in);
1687 break;
1688 #ifdef HAS_IPX
1689 case sizeof(struct WS_sockaddr_ipx):
1690 uaddrlen = sizeof(struct sockaddr_ipx);
1691 break;
1692 #endif
1693 #ifdef HAS_IRDA
1694 case sizeof(SOCKADDR_IRDA):
1695 uaddrlen = sizeof(struct sockaddr_irda);
1696 break;
1697 #endif
1698 case sizeof(struct WS_sockaddr_in6):
1699 case sizeof(struct WS_sockaddr_in6_old):
1700 uaddrlen = sizeof(struct sockaddr_in6);
1701 break;
1703 memset( uaddr, 0, uaddrlen );
1704 break;
1706 default:
1707 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
1708 return 0;
1710 return uaddrlen;
1713 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
1715 switch (uaddr->sa_family)
1717 #ifdef HAS_IPX
1718 case AF_IPX:
1720 static const struct sockaddr_ipx emptyAddr;
1721 struct sockaddr_ipx *ipx = (struct sockaddr_ipx*) uaddr;
1722 return ipx->sipx_port
1723 || memcmp(&ipx->sipx_network, &emptyAddr.sipx_network, sizeof(emptyAddr.sipx_network))
1724 || memcmp(&ipx->sipx_node, &emptyAddr.sipx_node, sizeof(emptyAddr.sipx_node));
1726 #endif
1727 case AF_INET6:
1729 static const struct sockaddr_in6 emptyAddr;
1730 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
1731 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
1733 case AF_INET:
1735 static const struct sockaddr_in emptyAddr;
1736 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
1737 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
1739 case AF_UNSPEC:
1740 return FALSE;
1741 default:
1742 FIXME("unknown address family %d\n", uaddr->sa_family);
1743 return TRUE;
1747 /* Returns -1 if getsockname fails, 0 if not bound, 1 otherwise */
1748 static int is_fd_bound(int fd, union generic_unix_sockaddr *uaddr, socklen_t *uaddrlen)
1750 union generic_unix_sockaddr inaddr;
1751 socklen_t inlen;
1752 int res;
1754 if (!uaddr) uaddr = &inaddr;
1755 if (!uaddrlen) uaddrlen = &inlen;
1757 *uaddrlen = sizeof(inaddr);
1758 res = getsockname(fd, &uaddr->addr, uaddrlen);
1759 if (!res) res = is_sockaddr_bound(&uaddr->addr, *uaddrlen);
1760 return res;
1763 /* Returns 0 if successful, -1 if the buffer is too small */
1764 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
1766 int res;
1768 switch(uaddr->sa_family)
1770 #ifdef HAS_IPX
1771 case AF_IPX:
1773 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
1774 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
1776 res=-1;
1777 switch (*wsaddrlen) /* how much can we copy? */
1779 default:
1780 res=0; /* enough */
1781 *wsaddrlen = sizeof(*wsipx);
1782 wsipx->sa_socket=uipx->sipx_port;
1783 /* fall through */
1784 case 13:
1785 case 12:
1786 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
1787 /* fall through */
1788 case 11:
1789 case 10:
1790 case 9:
1791 case 8:
1792 case 7:
1793 case 6:
1794 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1795 /* fall through */
1796 case 5:
1797 case 4:
1798 case 3:
1799 case 2:
1800 wsipx->sa_family=WS_AF_IPX;
1801 /* fall through */
1802 case 1:
1803 case 0:
1804 /* way too small */
1805 break;
1808 break;
1809 #endif
1810 #ifdef HAS_IRDA
1811 case AF_IRDA: {
1812 const struct sockaddr_irda *uin = (const struct sockaddr_irda *)uaddr;
1813 SOCKADDR_IRDA *win = (SOCKADDR_IRDA *)wsaddr;
1815 if (*wsaddrlen < sizeof(SOCKADDR_IRDA))
1816 return -1;
1817 win->irdaAddressFamily = WS_AF_IRDA;
1818 memcpy( win->irdaDeviceID, &uin->sir_addr, sizeof(win->irdaDeviceID) );
1819 if (uin->sir_lsap_sel != LSAP_ANY)
1820 sprintf( win->irdaServiceName, "LSAP-SEL%u", uin->sir_lsap_sel );
1821 else
1822 memcpy( win->irdaServiceName, uin->sir_name,
1823 sizeof(win->irdaServiceName) );
1824 return 0;
1826 #endif
1827 case AF_INET6: {
1828 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1829 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1831 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1832 return -1;
1833 win6old->sin6_family = WS_AF_INET6;
1834 win6old->sin6_port = uin6->sin6_port;
1835 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1836 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1837 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1838 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1839 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1840 win6->sin6_scope_id = uin6->sin6_scope_id;
1841 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1843 else
1844 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1845 #else
1846 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1847 #endif
1848 return 0;
1850 case AF_INET: {
1851 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1852 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1854 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1855 return -1;
1856 win->sin_family = WS_AF_INET;
1857 win->sin_port = uin->sin_port;
1858 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1859 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1860 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1861 return 0;
1863 case AF_UNSPEC: {
1864 memset(wsaddr,0,*wsaddrlen);
1865 return 0;
1867 default:
1868 FIXME("Unknown address family %d\n", uaddr->sa_family);
1869 return -1;
1871 return res;
1874 static INT WS_DuplicateSocket(BOOL unicode, SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo)
1876 HANDLE hProcess;
1877 int size;
1878 WSAPROTOCOL_INFOW infow;
1880 TRACE("(unicode %d, socket %04lx, processid %x, buffer %p)\n",
1881 unicode, s, dwProcessId, lpProtocolInfo);
1883 if (!ws_protocol_info(s, unicode, &infow, &size))
1884 return SOCKET_ERROR;
1886 if (!(hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId)))
1888 SetLastError(WSAEINVAL);
1889 return SOCKET_ERROR;
1892 if (!lpProtocolInfo)
1894 CloseHandle(hProcess);
1895 SetLastError(WSAEFAULT);
1896 return SOCKET_ERROR;
1899 /* I don't know what the real Windoze does next, this is a hack */
1900 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
1901 * the target use the global duplicate, or we could copy a reference to us to the structure
1902 * and let the target duplicate it from us, but let's do it as simple as possible */
1903 memcpy(lpProtocolInfo, &infow, size);
1904 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
1905 hProcess, (LPHANDLE)&lpProtocolInfo->dwServiceFlags3,
1906 0, FALSE, DUPLICATE_SAME_ACCESS);
1907 CloseHandle(hProcess);
1908 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
1909 return 0;
1912 /*****************************************************************************
1913 * WS_EnterSingleProtocolW [internal]
1915 * enters the protocol information of one given protocol into the given
1916 * buffer.
1918 * RETURNS
1919 * TRUE if a protocol was entered into the buffer.
1921 * BUGS
1922 * - only implemented for IPX, SPX, SPXII, TCP, UDP
1923 * - there is no check that the operating system supports the returned
1924 * protocols
1926 static BOOL WS_EnterSingleProtocolW( INT protocol, WSAPROTOCOL_INFOW* info )
1928 memset( info, 0, sizeof(WSAPROTOCOL_INFOW) );
1929 info->iProtocol = protocol;
1931 switch (protocol)
1933 case WS_IPPROTO_TCP:
1934 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_EXPEDITED_DATA |
1935 XP1_GRACEFUL_CLOSE | XP1_GUARANTEED_ORDER |
1936 XP1_GUARANTEED_DELIVERY;
1937 info->ProviderId = ProviderIdIP;
1938 info->dwCatalogEntryId = 0x3e9;
1939 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1940 info->ProtocolChain.ChainLen = 1;
1941 info->iVersion = 2;
1942 info->iAddressFamily = WS_AF_INET;
1943 info->iMaxSockAddr = 0x10;
1944 info->iMinSockAddr = 0x10;
1945 info->iSocketType = WS_SOCK_STREAM;
1946 strcpyW( info->szProtocol, NameTcpW );
1947 break;
1949 case WS_IPPROTO_UDP:
1950 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_SUPPORT_BROADCAST |
1951 XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED |
1952 XP1_CONNECTIONLESS;
1953 info->ProviderId = ProviderIdIP;
1954 info->dwCatalogEntryId = 0x3ea;
1955 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1956 info->ProtocolChain.ChainLen = 1;
1957 info->iVersion = 2;
1958 info->iAddressFamily = WS_AF_INET;
1959 info->iMaxSockAddr = 0x10;
1960 info->iMinSockAddr = 0x10;
1961 info->iSocketType = WS_SOCK_DGRAM;
1962 info->dwMessageSize = 0xffbb;
1963 strcpyW( info->szProtocol, NameUdpW );
1964 break;
1966 case WS_NSPROTO_IPX:
1967 info->dwServiceFlags1 = XP1_PARTIAL_MESSAGE | XP1_SUPPORT_BROADCAST |
1968 XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED |
1969 XP1_CONNECTIONLESS;
1970 info->ProviderId = ProviderIdIPX;
1971 info->dwCatalogEntryId = 0x406;
1972 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1973 info->ProtocolChain.ChainLen = 1;
1974 info->iVersion = 2;
1975 info->iAddressFamily = WS_AF_IPX;
1976 info->iMaxSockAddr = 0x10;
1977 info->iMinSockAddr = 0x0e;
1978 info->iSocketType = WS_SOCK_DGRAM;
1979 info->iProtocolMaxOffset = 0xff;
1980 info->dwMessageSize = 0x240;
1981 strcpyW( info->szProtocol, NameIpxW );
1982 break;
1984 case WS_NSPROTO_SPX:
1985 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_PSEUDO_STREAM |
1986 XP1_MESSAGE_ORIENTED | XP1_GUARANTEED_ORDER |
1987 XP1_GUARANTEED_DELIVERY;
1988 info->ProviderId = ProviderIdSPX;
1989 info->dwCatalogEntryId = 0x407;
1990 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1991 info->ProtocolChain.ChainLen = 1;
1992 info->iVersion = 2;
1993 info->iAddressFamily = WS_AF_IPX;
1994 info->iMaxSockAddr = 0x10;
1995 info->iMinSockAddr = 0x0e;
1996 info->iSocketType = WS_SOCK_SEQPACKET;
1997 info->dwMessageSize = 0xffffffff;
1998 strcpyW( info->szProtocol, NameSpxW );
1999 break;
2001 case WS_NSPROTO_SPXII:
2002 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_GRACEFUL_CLOSE |
2003 XP1_PSEUDO_STREAM | XP1_MESSAGE_ORIENTED |
2004 XP1_GUARANTEED_ORDER | XP1_GUARANTEED_DELIVERY;
2005 info->ProviderId = ProviderIdSPX;
2006 info->dwCatalogEntryId = 0x409;
2007 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
2008 info->ProtocolChain.ChainLen = 1;
2009 info->iVersion = 2;
2010 info->iAddressFamily = WS_AF_IPX;
2011 info->iMaxSockAddr = 0x10;
2012 info->iMinSockAddr = 0x0e;
2013 info->iSocketType = WS_SOCK_SEQPACKET;
2014 info->dwMessageSize = 0xffffffff;
2015 strcpyW( info->szProtocol, NameSpxIIW );
2016 break;
2018 default:
2019 FIXME("unknown Protocol <0x%08x>\n", protocol);
2020 return FALSE;
2022 return TRUE;
2025 /*****************************************************************************
2026 * WS_EnterSingleProtocolA [internal]
2028 * see function WS_EnterSingleProtocolW
2031 static BOOL WS_EnterSingleProtocolA( INT protocol, WSAPROTOCOL_INFOA* info )
2033 WSAPROTOCOL_INFOW infow;
2034 INT ret;
2035 memset( info, 0, sizeof(WSAPROTOCOL_INFOA) );
2037 ret = WS_EnterSingleProtocolW( protocol, &infow );
2038 if (ret)
2040 /* convert the structure from W to A */
2041 memcpy( info, &infow, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
2042 WideCharToMultiByte( CP_ACP, 0, infow.szProtocol, -1,
2043 info->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL );
2046 return ret;
2049 static INT WS_EnumProtocols( BOOL unicode, const INT *protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
2051 INT i = 0, items = 0;
2052 DWORD size = 0;
2053 union _info
2055 LPWSAPROTOCOL_INFOA a;
2056 LPWSAPROTOCOL_INFOW w;
2057 } info;
2058 info.w = buffer;
2060 if (!protocols) protocols = valid_protocols;
2062 while (protocols[i])
2064 if(supported_protocol(protocols[i++]))
2065 items++;
2068 size = items * (unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA));
2070 TRACE("unicode %d, protocols %p, buffer %p, length %p %d, items %d, required %d\n",
2071 unicode, protocols, buffer, len, len ? *len : 0, items, size);
2073 if (*len < size || !buffer)
2075 *len = size;
2076 SetLastError(WSAENOBUFS);
2077 return SOCKET_ERROR;
2080 for (i = items = 0; protocols[i]; i++)
2082 if (!supported_protocol(protocols[i])) continue;
2083 if (unicode)
2085 if (WS_EnterSingleProtocolW( protocols[i], &info.w[items] ))
2086 items++;
2088 else
2090 if (WS_EnterSingleProtocolA( protocols[i], &info.a[items] ))
2091 items++;
2094 return items;
2097 static BOOL ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size)
2099 NTSTATUS status;
2101 *size = unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA);
2102 memset(buffer, 0, *size);
2104 SERVER_START_REQ( get_socket_info )
2106 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
2107 status = wine_server_call( req );
2108 if (!status)
2110 buffer->iAddressFamily = convert_af_u2w(reply->family);
2111 buffer->iSocketType = convert_socktype_u2w(reply->type);
2112 buffer->iProtocol = convert_proto_u2w(reply->protocol);
2115 SERVER_END_REQ;
2117 if (status)
2119 unsigned int err = NtStatusToWSAError( status );
2120 SetLastError( err == WSAEBADF ? WSAENOTSOCK : err );
2121 return FALSE;
2124 if (unicode)
2125 WS_EnterSingleProtocolW( buffer->iProtocol, buffer);
2126 else
2127 WS_EnterSingleProtocolA( buffer->iProtocol, (WSAPROTOCOL_INFOA *)buffer);
2129 return TRUE;
2132 /**************************************************************************
2133 * Functions for handling overlapped I/O
2134 **************************************************************************/
2136 /* user APC called upon async completion */
2137 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
2139 struct ws2_async *wsa = arg;
2141 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
2142 iosb->Information, wsa->user_overlapped,
2143 wsa->flags );
2144 release_async_io( &wsa->io );
2147 /***********************************************************************
2148 * WS2_recv (INTERNAL)
2150 * Workhorse for both synchronous and asynchronous recv() operations.
2152 static int WS2_recv( int fd, struct ws2_async *wsa, int flags )
2154 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2155 char pktbuf[512];
2156 #endif
2157 struct msghdr hdr;
2158 union generic_unix_sockaddr unix_sockaddr;
2159 int n;
2161 hdr.msg_name = NULL;
2163 if (wsa->addr)
2165 hdr.msg_namelen = sizeof(unix_sockaddr);
2166 hdr.msg_name = &unix_sockaddr;
2168 else
2169 hdr.msg_namelen = 0;
2171 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
2172 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
2173 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2174 hdr.msg_accrights = NULL;
2175 hdr.msg_accrightslen = 0;
2176 #else
2177 hdr.msg_control = pktbuf;
2178 hdr.msg_controllen = sizeof(pktbuf);
2179 hdr.msg_flags = 0;
2180 #endif
2182 while ((n = recvmsg(fd, &hdr, flags)) == -1)
2184 if (errno != EINTR)
2185 return -1;
2188 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2189 if (wsa->control)
2191 ERR("Message control headers cannot be properly supported on this system.\n");
2192 wsa->control->len = 0;
2194 #else
2195 if (wsa->control && !convert_control_headers(&hdr, wsa->control))
2197 WARN("Application passed insufficient room for control headers.\n");
2198 *wsa->lpFlags |= WS_MSG_CTRUNC;
2199 errno = EMSGSIZE;
2200 return -1;
2202 #endif
2204 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
2205 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
2207 * quoting linux 2.6 net/ipv4/tcp.c:
2208 * "According to UNIX98, msg_name/msg_namelen are ignored
2209 * on connected socket. I was just happy when found this 8) --ANK"
2211 * likewise MSDN says that lpFrom and lpFromlen are ignored for
2212 * connection-oriented sockets, so don't try to update lpFrom.
2214 if (wsa->addr && hdr.msg_namelen)
2215 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
2217 return n;
2220 /***********************************************************************
2221 * WS2_async_recv (INTERNAL)
2223 * Handler for overlapped recv() operations.
2225 static NTSTATUS WS2_async_recv( void *user, IO_STATUS_BLOCK *iosb,
2226 NTSTATUS status, void **apc, void **arg )
2228 struct ws2_async *wsa = user;
2229 int result = 0, fd;
2231 switch (status)
2233 case STATUS_ALERTED:
2234 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
2235 break;
2237 result = WS2_recv( fd, wsa, convert_flags(wsa->flags) );
2238 wine_server_release_fd( wsa->hSocket, fd );
2239 if (result >= 0)
2241 status = STATUS_SUCCESS;
2242 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
2244 else
2246 if (errno == EAGAIN)
2248 status = STATUS_PENDING;
2249 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
2251 else
2253 result = 0;
2254 status = wsaErrStatus();
2257 break;
2259 if (status != STATUS_PENDING)
2261 iosb->u.Status = status;
2262 iosb->Information = result;
2263 if (wsa->completion_func)
2265 *apc = ws2_async_apc;
2266 *arg = wsa;
2268 else
2269 release_async_io( &wsa->io );
2271 return status;
2274 /***********************************************************************
2275 * WS2_async_accept_recv (INTERNAL)
2277 * This function is used to finish the read part of an accept request. It is
2278 * needed to place the completion on the correct socket (listener).
2280 static NTSTATUS WS2_async_accept_recv( void *user, IO_STATUS_BLOCK *iosb,
2281 NTSTATUS status, void **apc, void **arg )
2283 void *junk;
2284 struct ws2_accept_async *wsa = user;
2286 status = WS2_async_recv( wsa->read, iosb, status, &junk, &junk );
2287 if (status == STATUS_PENDING)
2288 return status;
2290 if (wsa->cvalue)
2291 WS_AddCompletion( HANDLE2SOCKET(wsa->listen_socket), wsa->cvalue, iosb->u.Status, iosb->Information );
2293 release_async_io( &wsa->io );
2294 return status;
2297 /***********************************************************************
2298 * WS2_async_accept (INTERNAL)
2300 * This is the function called to satisfy the AcceptEx callback
2302 static NTSTATUS WS2_async_accept( void *user, IO_STATUS_BLOCK *iosb,
2303 NTSTATUS status, void **apc, void **arg )
2305 struct ws2_accept_async *wsa = user;
2306 int len;
2307 char *addr;
2309 TRACE("status: 0x%x listen: %p, accept: %p\n", status, wsa->listen_socket, wsa->accept_socket);
2311 if (status == STATUS_ALERTED)
2313 SERVER_START_REQ( accept_into_socket )
2315 req->lhandle = wine_server_obj_handle( wsa->listen_socket );
2316 req->ahandle = wine_server_obj_handle( wsa->accept_socket );
2317 status = wine_server_call( req );
2319 SERVER_END_REQ;
2321 if (status == STATUS_CANT_WAIT)
2322 return STATUS_PENDING;
2324 if (status == STATUS_INVALID_HANDLE)
2326 FIXME("AcceptEx accepting socket closed but request was not cancelled\n");
2327 status = STATUS_CANCELLED;
2330 else if (status == STATUS_HANDLES_CLOSED)
2331 status = STATUS_CANCELLED; /* strange windows behavior */
2333 if (status != STATUS_SUCCESS)
2334 goto finish;
2336 /* WS2 Spec says size param is extra 16 bytes long...what do we put in it? */
2337 addr = ((char *)wsa->buf) + wsa->data_len;
2338 len = wsa->local_len - sizeof(int);
2339 WS_getsockname(HANDLE2SOCKET(wsa->accept_socket),
2340 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
2341 *(int *)addr = len;
2343 addr += wsa->local_len;
2344 len = wsa->remote_len - sizeof(int);
2345 WS_getpeername(HANDLE2SOCKET(wsa->accept_socket),
2346 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
2347 *(int *)addr = len;
2349 if (!wsa->read)
2350 goto finish;
2352 SERVER_START_REQ( register_async )
2354 req->type = ASYNC_TYPE_READ;
2355 req->async.handle = wine_server_obj_handle( wsa->accept_socket );
2356 req->async.event = wine_server_obj_handle( wsa->user_overlapped->hEvent );
2357 req->async.callback = wine_server_client_ptr( WS2_async_accept_recv );
2358 req->async.iosb = wine_server_client_ptr( iosb );
2359 req->async.arg = wine_server_client_ptr( wsa );
2360 status = wine_server_call( req );
2362 SERVER_END_REQ;
2364 if (status != STATUS_PENDING)
2365 goto finish;
2367 /* The APC has finished but no completion should be sent for the operation yet, additional processing
2368 * needs to be performed by WS2_async_accept_recv() first. */
2369 return STATUS_MORE_PROCESSING_REQUIRED;
2371 finish:
2372 iosb->u.Status = status;
2373 iosb->Information = 0;
2375 if (wsa->read) release_async_io( &wsa->read->io );
2376 release_async_io( &wsa->io );
2377 return status;
2380 /***********************************************************************
2381 * WS2_send (INTERNAL)
2383 * Workhorse for both synchronous and asynchronous send() operations.
2385 static int WS2_send( int fd, struct ws2_async *wsa, int flags )
2387 struct msghdr hdr;
2388 union generic_unix_sockaddr unix_addr;
2389 int n, ret;
2391 hdr.msg_name = NULL;
2392 hdr.msg_namelen = 0;
2394 if (wsa->addr)
2396 hdr.msg_name = &unix_addr;
2397 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
2398 if ( !hdr.msg_namelen )
2400 errno = EFAULT;
2401 return -1;
2404 #if defined(HAS_IPX) && defined(SOL_IPX)
2405 if(wsa->addr->sa_family == WS_AF_IPX)
2407 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
2408 int val=0;
2409 socklen_t len = sizeof(int);
2411 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
2412 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
2413 * the packet type and then we can retrieve it using getsockopt. After that we can set the
2414 * ipx type in the sockaddr_opx structure with the stored value.
2416 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
2417 uipx->sipx_type = val;
2419 #endif
2422 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
2423 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
2424 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2425 hdr.msg_accrights = NULL;
2426 hdr.msg_accrightslen = 0;
2427 #else
2428 hdr.msg_control = NULL;
2429 hdr.msg_controllen = 0;
2430 hdr.msg_flags = 0;
2431 #endif
2433 while ((ret = sendmsg(fd, &hdr, flags)) == -1)
2435 if (errno != EINTR)
2436 return -1;
2439 n = ret;
2440 while (wsa->first_iovec < wsa->n_iovecs && wsa->iovec[wsa->first_iovec].iov_len <= n)
2441 n -= wsa->iovec[wsa->first_iovec++].iov_len;
2442 if (wsa->first_iovec < wsa->n_iovecs)
2444 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
2445 wsa->iovec[wsa->first_iovec].iov_len -= n;
2447 return ret;
2450 /***********************************************************************
2451 * WS2_async_send (INTERNAL)
2453 * Handler for overlapped send() operations.
2455 static NTSTATUS WS2_async_send( void *user, IO_STATUS_BLOCK *iosb,
2456 NTSTATUS status, void **apc, void **arg )
2458 struct ws2_async *wsa = user;
2459 int result = 0, fd;
2461 switch (status)
2463 case STATUS_ALERTED:
2464 if ( wsa->n_iovecs <= wsa->first_iovec )
2466 /* Nothing to do */
2467 status = STATUS_SUCCESS;
2468 break;
2470 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
2471 break;
2473 /* check to see if the data is ready (non-blocking) */
2474 result = WS2_send( fd, wsa, convert_flags(wsa->flags) );
2475 wine_server_release_fd( wsa->hSocket, fd );
2477 if (result >= 0)
2479 if (wsa->first_iovec < wsa->n_iovecs)
2480 status = STATUS_PENDING;
2481 else
2482 status = STATUS_SUCCESS;
2484 iosb->Information += result;
2486 else if (errno == EAGAIN)
2488 status = STATUS_PENDING;
2490 else
2492 status = wsaErrStatus();
2494 break;
2496 if (status != STATUS_PENDING)
2498 iosb->u.Status = status;
2499 if (wsa->completion_func)
2501 *apc = ws2_async_apc;
2502 *arg = wsa;
2504 else
2505 release_async_io( &wsa->io );
2507 return status;
2510 /***********************************************************************
2511 * WS2_async_shutdown (INTERNAL)
2513 * Handler for shutdown() operations on overlapped sockets.
2515 static NTSTATUS WS2_async_shutdown( void *user, IO_STATUS_BLOCK *iosb,
2516 NTSTATUS status, void **apc, void **arg )
2518 struct ws2_async_shutdown *wsa = user;
2519 int fd, err = 1;
2521 switch (status)
2523 case STATUS_ALERTED:
2524 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
2525 break;
2527 switch ( wsa->type )
2529 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
2530 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
2532 status = err ? wsaErrStatus() : STATUS_SUCCESS;
2533 wine_server_release_fd( wsa->hSocket, fd );
2534 break;
2536 iosb->u.Status = status;
2537 iosb->Information = 0;
2538 release_async_io( &wsa->io );
2539 return status;
2542 /***********************************************************************
2543 * WS2_register_async_shutdown (INTERNAL)
2545 * Helper function for WS_shutdown() on overlapped sockets.
2547 static int WS2_register_async_shutdown( SOCKET s, int type )
2549 struct ws2_async_shutdown *wsa;
2550 NTSTATUS status;
2552 TRACE("socket %04lx type %d\n", s, type);
2554 wsa = (struct ws2_async_shutdown *)alloc_async_io( sizeof(*wsa) );
2555 if ( !wsa )
2556 return WSAEFAULT;
2558 wsa->hSocket = SOCKET2HANDLE(s);
2559 wsa->type = type;
2561 SERVER_START_REQ( register_async )
2563 req->type = type;
2564 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2565 req->async.callback = wine_server_client_ptr( WS2_async_shutdown );
2566 req->async.iosb = wine_server_client_ptr( &wsa->iosb );
2567 req->async.arg = wine_server_client_ptr( wsa );
2568 req->async.cvalue = 0;
2569 status = wine_server_call( req );
2571 SERVER_END_REQ;
2573 if (status != STATUS_PENDING)
2575 HeapFree( GetProcessHeap(), 0, wsa );
2576 return NtStatusToWSAError( status );
2578 return 0;
2581 /***********************************************************************
2582 * accept (WS2_32.1)
2584 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr, int *addrlen32)
2586 NTSTATUS status;
2587 SOCKET as;
2588 BOOL is_blocking;
2590 TRACE("socket %04lx\n", s );
2591 status = _is_blocking(s, &is_blocking);
2592 if (status)
2594 set_error(status);
2595 return INVALID_SOCKET;
2598 do {
2599 /* try accepting first (if there is a deferred connection) */
2600 SERVER_START_REQ( accept_socket )
2602 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
2603 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
2604 req->attributes = OBJ_INHERIT;
2605 status = wine_server_call( req );
2606 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
2608 SERVER_END_REQ;
2609 if (!status)
2611 if (addr && WS_getpeername(as, addr, addrlen32))
2613 WS_closesocket(as);
2614 return SOCKET_ERROR;
2616 TRACE("\taccepted %04lx\n", as);
2617 return as;
2619 if (is_blocking && status == STATUS_CANT_WAIT)
2621 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2622 /* block here */
2623 do_block(fd, POLLIN, -1);
2624 _sync_sock_state(s); /* let wineserver notice connection */
2625 release_sock_fd( s, fd );
2627 } while (is_blocking && status == STATUS_CANT_WAIT);
2629 set_error(status);
2630 return INVALID_SOCKET;
2633 /***********************************************************************
2634 * AcceptEx
2636 static BOOL WINAPI WS2_AcceptEx(SOCKET listener, SOCKET acceptor, PVOID dest, DWORD dest_len,
2637 DWORD local_addr_len, DWORD rem_addr_len, LPDWORD received,
2638 LPOVERLAPPED overlapped)
2640 DWORD status;
2641 struct ws2_accept_async *wsa;
2642 int fd;
2644 TRACE("(%04lx, %04lx, %p, %d, %d, %d, %p, %p)\n", listener, acceptor, dest, dest_len, local_addr_len,
2645 rem_addr_len, received, overlapped);
2647 if (!dest)
2649 SetLastError(WSAEINVAL);
2650 return FALSE;
2653 if (!overlapped)
2655 SetLastError(WSA_INVALID_PARAMETER);
2656 return FALSE;
2659 if (!rem_addr_len)
2661 SetLastError(WSAEFAULT);
2662 return FALSE;
2665 fd = get_sock_fd( listener, FILE_READ_DATA, NULL );
2666 if (fd == -1)
2668 SetLastError(WSAENOTSOCK);
2669 return FALSE;
2671 release_sock_fd( listener, fd );
2673 fd = get_sock_fd( acceptor, FILE_READ_DATA, NULL );
2674 if (fd == -1)
2676 SetLastError(WSAENOTSOCK);
2677 return FALSE;
2679 release_sock_fd( acceptor, fd );
2681 wsa = (struct ws2_accept_async *)alloc_async_io( sizeof(*wsa) );
2682 if(!wsa)
2684 SetLastError(WSAEFAULT);
2685 return FALSE;
2688 wsa->listen_socket = SOCKET2HANDLE(listener);
2689 wsa->accept_socket = SOCKET2HANDLE(acceptor);
2690 wsa->user_overlapped = overlapped;
2691 wsa->cvalue = !((ULONG_PTR)overlapped->hEvent & 1) ? (ULONG_PTR)overlapped : 0;
2692 wsa->buf = dest;
2693 wsa->data_len = dest_len;
2694 wsa->local_len = local_addr_len;
2695 wsa->remote_len = rem_addr_len;
2696 wsa->read = NULL;
2698 if (wsa->data_len)
2700 /* set up a read request if we need it */
2701 wsa->read = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[1]) );
2702 if (!wsa->read)
2704 HeapFree( GetProcessHeap(), 0, wsa );
2705 SetLastError(WSAEFAULT);
2706 return FALSE;
2709 wsa->read->hSocket = wsa->accept_socket;
2710 wsa->read->flags = 0;
2711 wsa->read->lpFlags = &wsa->read->flags;
2712 wsa->read->addr = NULL;
2713 wsa->read->addrlen.ptr = NULL;
2714 wsa->read->control = NULL;
2715 wsa->read->n_iovecs = 1;
2716 wsa->read->first_iovec = 0;
2717 wsa->read->completion_func = NULL;
2718 wsa->read->iovec[0].iov_base = wsa->buf;
2719 wsa->read->iovec[0].iov_len = wsa->data_len;
2722 SERVER_START_REQ( register_async )
2724 req->type = ASYNC_TYPE_READ;
2725 req->async.handle = wine_server_obj_handle( SOCKET2HANDLE(listener) );
2726 req->async.event = wine_server_obj_handle( overlapped->hEvent );
2727 req->async.callback = wine_server_client_ptr( WS2_async_accept );
2728 req->async.iosb = wine_server_client_ptr( overlapped );
2729 req->async.arg = wine_server_client_ptr( wsa );
2730 req->async.cvalue = wsa->cvalue;
2731 status = wine_server_call( req );
2733 SERVER_END_REQ;
2735 if(status != STATUS_PENDING)
2737 HeapFree( GetProcessHeap(), 0, wsa->read );
2738 HeapFree( GetProcessHeap(), 0, wsa );
2741 SetLastError( NtStatusToWSAError(status) );
2742 return FALSE;
2745 /***********************************************************************
2746 * WS2_ReadFile (INTERNAL)
2748 * Perform an APC-safe ReadFile operation
2750 static NTSTATUS WS2_ReadFile(HANDLE hFile, PIO_STATUS_BLOCK io_status, char* buffer, ULONG length,
2751 PLARGE_INTEGER offset)
2753 int result = -1, unix_handle;
2754 unsigned int options;
2755 NTSTATUS status;
2757 TRACE( "(%p,%p,0x%08x)\n", hFile, buffer,length );
2759 status = wine_server_handle_to_fd( hFile, FILE_READ_DATA, &unix_handle, &options );
2760 if (status) return status;
2762 while (result == -1)
2764 if (offset->QuadPart != FILE_USE_FILE_POINTER_POSITION)
2765 result = pread( unix_handle, buffer, length, offset->QuadPart );
2766 else
2767 result = read( unix_handle, buffer, length );
2768 if (errno != EINTR)
2769 break;
2772 if (!result)
2773 status = (length ? STATUS_END_OF_FILE : STATUS_SUCCESS);
2774 else if (result != -1)
2775 status = STATUS_SUCCESS;
2776 else if (errno != EAGAIN)
2777 status = wsaErrStatus();
2778 else
2779 status = STATUS_PENDING;
2781 wine_server_release_fd( hFile, unix_handle );
2782 TRACE("= 0x%08x (%d)\n", status, result);
2783 if (status == STATUS_SUCCESS || status == STATUS_END_OF_FILE)
2785 io_status->u.Status = status;
2786 io_status->Information = result;
2789 return status;
2792 /***********************************************************************
2793 * WS2_transmitfile_getbuffer (INTERNAL)
2795 * Pick the appropriate buffer for a TransmitFile send operation.
2797 static NTSTATUS WS2_transmitfile_getbuffer( int fd, struct ws2_transmitfile_async *wsa )
2799 /* send any incomplete writes from a previous iteration */
2800 if (wsa->write.first_iovec < wsa->write.n_iovecs)
2801 return STATUS_PENDING;
2803 /* process the header (if applicable) */
2804 if (wsa->buffers.Head)
2806 wsa->write.first_iovec = 0;
2807 wsa->write.n_iovecs = 1;
2808 wsa->write.iovec[0].iov_base = wsa->buffers.Head;
2809 wsa->write.iovec[0].iov_len = wsa->buffers.HeadLength;
2810 wsa->buffers.Head = NULL;
2811 return STATUS_PENDING;
2814 /* process the main file */
2815 if (wsa->file)
2817 DWORD bytes_per_send = wsa->bytes_per_send;
2818 IO_STATUS_BLOCK iosb;
2819 NTSTATUS status;
2821 iosb.Information = 0;
2822 /* when the size of the transfer is limited ensure that we don't go past that limit */
2823 if (wsa->file_bytes != 0)
2824 bytes_per_send = min(bytes_per_send, wsa->file_bytes - wsa->file_read);
2825 status = WS2_ReadFile( wsa->file, &iosb, wsa->buffer, bytes_per_send, &wsa->offset );
2826 if (wsa->offset.QuadPart != FILE_USE_FILE_POINTER_POSITION)
2827 wsa->offset.QuadPart += iosb.Information;
2828 if (status == STATUS_END_OF_FILE)
2829 wsa->file = NULL; /* continue on to the footer */
2830 else if (status != STATUS_SUCCESS)
2831 return status;
2832 else
2834 if (iosb.Information)
2836 wsa->write.first_iovec = 0;
2837 wsa->write.n_iovecs = 1;
2838 wsa->write.iovec[0].iov_base = wsa->buffer;
2839 wsa->write.iovec[0].iov_len = iosb.Information;
2840 wsa->file_read += iosb.Information;
2843 if (wsa->file_bytes != 0 && wsa->file_read >= wsa->file_bytes)
2844 wsa->file = NULL;
2846 return STATUS_PENDING;
2850 /* send the footer (if applicable) */
2851 if (wsa->buffers.Tail)
2853 wsa->write.first_iovec = 0;
2854 wsa->write.n_iovecs = 1;
2855 wsa->write.iovec[0].iov_base = wsa->buffers.Tail;
2856 wsa->write.iovec[0].iov_len = wsa->buffers.TailLength;
2857 wsa->buffers.Tail = NULL;
2858 return STATUS_PENDING;
2861 return STATUS_SUCCESS;
2864 /***********************************************************************
2865 * WS2_transmitfile_base (INTERNAL)
2867 * Shared implementation for both synchronous and asynchronous TransmitFile.
2869 static NTSTATUS WS2_transmitfile_base( int fd, struct ws2_transmitfile_async *wsa )
2871 NTSTATUS status;
2873 status = WS2_transmitfile_getbuffer( fd, wsa );
2874 if (status == STATUS_PENDING)
2876 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)wsa->write.user_overlapped;
2877 int n;
2879 n = WS2_send( fd, &wsa->write, convert_flags(wsa->write.flags) );
2880 if (n >= 0)
2882 if (iosb) iosb->Information += n;
2884 else if (errno != EAGAIN)
2885 return wsaErrStatus();
2888 return status;
2891 /***********************************************************************
2892 * WS2_async_transmitfile (INTERNAL)
2894 * Asynchronous callback for overlapped TransmitFile operations.
2896 static NTSTATUS WS2_async_transmitfile( void *user, IO_STATUS_BLOCK *iosb,
2897 NTSTATUS status, void **apc, void **arg )
2899 struct ws2_transmitfile_async *wsa = user;
2900 int fd;
2902 if (status == STATUS_ALERTED)
2904 if (!(status = wine_server_handle_to_fd( wsa->write.hSocket, FILE_WRITE_DATA, &fd, NULL )))
2906 status = WS2_transmitfile_base( fd, wsa );
2907 wine_server_release_fd( wsa->write.hSocket, fd );
2909 if (status == STATUS_PENDING)
2910 return status;
2913 iosb->u.Status = status;
2914 release_async_io( &wsa->io );
2915 return status;
2918 /***********************************************************************
2919 * TransmitFile
2921 static BOOL WINAPI WS2_TransmitFile( SOCKET s, HANDLE h, DWORD file_bytes, DWORD bytes_per_send,
2922 LPOVERLAPPED overlapped, LPTRANSMIT_FILE_BUFFERS buffers,
2923 DWORD flags )
2925 union generic_unix_sockaddr uaddr;
2926 unsigned int uaddrlen = sizeof(uaddr);
2927 struct ws2_transmitfile_async *wsa;
2928 NTSTATUS status;
2929 int fd;
2931 TRACE("(%lx, %p, %d, %d, %p, %p, %d)\n", s, h, file_bytes, bytes_per_send, overlapped,
2932 buffers, flags );
2934 fd = get_sock_fd( s, FILE_WRITE_DATA, NULL );
2935 if (fd == -1)
2937 WSASetLastError( WSAENOTSOCK );
2938 return FALSE;
2940 if (getpeername( fd, &uaddr.addr, &uaddrlen ) != 0)
2942 release_sock_fd( s, fd );
2943 WSASetLastError( WSAENOTCONN );
2944 return FALSE;
2946 if (flags)
2947 FIXME("Flags are not currently supported (0x%x).\n", flags);
2949 if (h && GetFileType( h ) != FILE_TYPE_DISK)
2951 FIXME("Non-disk file handles are not currently supported.\n");
2952 release_sock_fd( s, fd );
2953 WSASetLastError( WSAEOPNOTSUPP );
2954 return FALSE;
2957 /* set reasonable defaults when requested */
2958 if (!bytes_per_send)
2959 bytes_per_send = (1 << 16); /* Depends on OS version: PAGE_SIZE, 2*PAGE_SIZE, or 2^16 */
2961 if (!(wsa = (struct ws2_transmitfile_async *)alloc_async_io( sizeof(*wsa) + bytes_per_send )))
2963 release_sock_fd( s, fd );
2964 WSASetLastError( WSAEFAULT );
2965 return FALSE;
2967 if (buffers)
2968 wsa->buffers = *buffers;
2969 else
2970 memset(&wsa->buffers, 0x0, sizeof(wsa->buffers));
2971 wsa->buffer = (char *)(wsa + 1);
2972 wsa->file = h;
2973 wsa->file_read = 0;
2974 wsa->file_bytes = file_bytes;
2975 wsa->bytes_per_send = bytes_per_send;
2976 wsa->flags = flags;
2977 wsa->offset.QuadPart = FILE_USE_FILE_POINTER_POSITION;
2978 wsa->write.hSocket = SOCKET2HANDLE(s);
2979 wsa->write.addr = NULL;
2980 wsa->write.addrlen.val = 0;
2981 wsa->write.flags = 0;
2982 wsa->write.lpFlags = &wsa->flags;
2983 wsa->write.control = NULL;
2984 wsa->write.n_iovecs = 0;
2985 wsa->write.first_iovec = 0;
2986 wsa->write.user_overlapped = overlapped;
2987 if (overlapped)
2989 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)overlapped;
2990 int status;
2992 wsa->offset.u.LowPart = overlapped->u.s.Offset;
2993 wsa->offset.u.HighPart = overlapped->u.s.OffsetHigh;
2994 iosb->u.Status = STATUS_PENDING;
2995 iosb->Information = 0;
2996 SERVER_START_REQ( register_async )
2998 req->type = ASYNC_TYPE_WRITE;
2999 req->async.handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
3000 req->async.event = wine_server_obj_handle( overlapped->hEvent );
3001 req->async.callback = wine_server_client_ptr( WS2_async_transmitfile );
3002 req->async.iosb = wine_server_client_ptr( iosb );
3003 req->async.arg = wine_server_client_ptr( wsa );
3004 status = wine_server_call( req );
3006 SERVER_END_REQ;
3008 if(status != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
3009 release_sock_fd( s, fd );
3010 WSASetLastError( NtStatusToWSAError(status) );
3011 return FALSE;
3016 status = WS2_transmitfile_base( fd, wsa );
3017 if (status == STATUS_PENDING)
3019 /* block here */
3020 do_block(fd, POLLOUT, -1);
3021 _sync_sock_state(s); /* let wineserver notice connection */
3024 while (status == STATUS_PENDING);
3025 release_sock_fd( s, fd );
3027 if (status != STATUS_SUCCESS)
3028 WSASetLastError( NtStatusToWSAError(status) );
3029 HeapFree( GetProcessHeap(), 0, wsa );
3030 return (status == STATUS_SUCCESS);
3033 /***********************************************************************
3034 * GetAcceptExSockaddrs
3036 static void WINAPI WS2_GetAcceptExSockaddrs(PVOID buffer, DWORD data_size, DWORD local_size, DWORD remote_size,
3037 struct WS_sockaddr **local_addr, LPINT local_addr_len,
3038 struct WS_sockaddr **remote_addr, LPINT remote_addr_len)
3040 char *cbuf = buffer;
3041 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer, data_size, local_size, remote_size, local_addr,
3042 local_addr_len, remote_addr, remote_addr_len );
3043 cbuf += data_size;
3045 *local_addr_len = *(int *) cbuf;
3046 *local_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
3048 cbuf += local_size;
3050 *remote_addr_len = *(int *) cbuf;
3051 *remote_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
3054 /***********************************************************************
3055 * WSASendMsg
3057 int WINAPI WSASendMsg( SOCKET s, LPWSAMSG msg, DWORD dwFlags, LPDWORD lpNumberOfBytesSent,
3058 LPWSAOVERLAPPED lpOverlapped,
3059 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
3061 if (!msg)
3063 SetLastError( WSAEFAULT );
3064 return SOCKET_ERROR;
3067 return WS2_sendto( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesSent,
3068 dwFlags, msg->name, msg->namelen,
3069 lpOverlapped, lpCompletionRoutine );
3072 /***********************************************************************
3073 * WSARecvMsg
3075 * Perform a receive operation that is capable of returning message
3076 * control headers. It is important to note that the WSAMSG parameter
3077 * must remain valid throughout the operation, even when an overlapped
3078 * receive is performed.
3080 static int WINAPI WS2_WSARecvMsg( SOCKET s, LPWSAMSG msg, LPDWORD lpNumberOfBytesRecvd,
3081 LPWSAOVERLAPPED lpOverlapped,
3082 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3084 if (!msg)
3086 SetLastError( WSAEFAULT );
3087 return SOCKET_ERROR;
3090 return WS2_recv_base( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesRecvd,
3091 &msg->dwFlags, msg->name, &msg->namelen,
3092 lpOverlapped, lpCompletionRoutine, &msg->Control );
3095 /***********************************************************************
3096 * interface_bind (INTERNAL)
3098 * Take bind() calls on any name corresponding to a local network adapter and restrict the given socket to
3099 * operating only on the specified interface. This restriction consists of two components:
3100 * 1) An outgoing packet restriction suggesting the egress interface for all packets.
3101 * 2) An incoming packet restriction dropping packets not meant for the interface.
3102 * If the function succeeds in placing these restrictions (returns TRUE) then the name for the bind() may
3103 * safely be changed to INADDR_ANY, permitting the transmission and receipt of broadcast packets on the
3104 * socket. This behavior is only relevant to UDP sockets and is needed for applications that expect to be able
3105 * to receive broadcast packets on a socket that is bound to a specific network interface.
3107 static BOOL interface_bind( SOCKET s, int fd, struct sockaddr *addr )
3109 struct sockaddr_in *in_sock = (struct sockaddr_in *) addr;
3110 in_addr_t bind_addr = in_sock->sin_addr.s_addr;
3111 PIP_ADAPTER_INFO adapters = NULL, adapter;
3112 BOOL ret = FALSE;
3113 DWORD adap_size;
3114 int enable = 1;
3116 if (bind_addr == htonl(INADDR_ANY) || bind_addr == htonl(INADDR_LOOPBACK))
3117 return FALSE; /* Not binding to a network adapter, special interface binding unnecessary. */
3118 if (_get_fd_type(fd) != SOCK_DGRAM)
3119 return FALSE; /* Special interface binding is only necessary for UDP datagrams. */
3120 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
3121 goto cleanup;
3122 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
3123 if (adapters == NULL || GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
3124 goto cleanup;
3125 /* Search the IPv4 adapter list for the appropriate binding interface */
3126 for (adapter = adapters; adapter != NULL; adapter = adapter->Next)
3128 in_addr_t adapter_addr = (in_addr_t) inet_addr(adapter->IpAddressList.IpAddress.String);
3130 if (bind_addr == adapter_addr)
3132 #if defined(IP_BOUND_IF)
3133 /* IP_BOUND_IF sets both the incoming and outgoing restriction at once */
3134 if (setsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &adapter->Index, sizeof(adapter->Index)) != 0)
3135 goto cleanup;
3136 ret = TRUE;
3137 #elif defined(LINUX_BOUND_IF)
3138 in_addr_t ifindex = (in_addr_t) htonl(adapter->Index);
3139 struct interface_filter specific_interface_filter;
3140 struct sock_fprog filter_prog;
3142 if (setsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex, sizeof(ifindex)) != 0)
3143 goto cleanup; /* Failed to suggest egress interface */
3144 specific_interface_filter = generic_interface_filter;
3145 specific_interface_filter.iface_rule.k = adapter->Index;
3146 specific_interface_filter.ip_rule.k = htonl(adapter_addr);
3147 filter_prog.len = sizeof(generic_interface_filter)/sizeof(struct sock_filter);
3148 filter_prog.filter = (struct sock_filter *) &specific_interface_filter;
3149 if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog, sizeof(filter_prog)) != 0)
3150 goto cleanup; /* Failed to specify incoming packet filter */
3151 ret = TRUE;
3152 #else
3153 FIXME("Broadcast packets on interface-bound sockets are not currently supported on this platform, "
3154 "receiving broadcast packets will not work on socket %04lx.\n", s);
3155 #endif
3156 break;
3159 /* Will soon be switching to INADDR_ANY: permit address reuse */
3160 if (ret && setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) == 0)
3161 TRACE("Socket %04lx bound to interface index %d\n", s, adapter->Index);
3162 else
3163 ret = FALSE;
3165 cleanup:
3166 if(!ret)
3167 ERR("Failed to bind to interface, receiving broadcast packets will not work on socket %04lx.\n", s);
3168 HeapFree(GetProcessHeap(), 0, adapters);
3169 return ret;
3172 /***********************************************************************
3173 * bind (WS2_32.2)
3175 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
3177 int fd = get_sock_fd( s, 0, NULL );
3178 int res = SOCKET_ERROR;
3180 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
3182 if (fd != -1)
3184 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
3186 SetLastError(WSAEAFNOSUPPORT);
3188 else
3190 union generic_unix_sockaddr uaddr;
3191 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
3192 if (!uaddrlen)
3194 SetLastError(WSAEFAULT);
3196 else
3198 #ifdef IPV6_V6ONLY
3199 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
3200 if (name->sa_family == WS_AF_INET6 &&
3201 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
3203 int enable = 1;
3204 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
3206 release_sock_fd( s, fd );
3207 SetLastError(WSAEAFNOSUPPORT);
3208 return SOCKET_ERROR;
3211 #endif
3212 if (name->sa_family == WS_AF_INET)
3214 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
3215 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
3217 /* Trying to bind to the default host interface, using
3218 * INADDR_ANY instead*/
3219 WARN("Trying to bind to magic IP address, using "
3220 "INADDR_ANY instead.\n");
3221 in4->sin_addr.s_addr = htonl(INADDR_ANY);
3223 else if (interface_bind(s, fd, &uaddr.addr))
3224 in4->sin_addr.s_addr = htonl(INADDR_ANY);
3226 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
3228 int loc_errno = errno;
3229 WARN("\tfailure - errno = %i\n", errno);
3230 errno = loc_errno;
3231 switch (errno)
3233 case EADDRNOTAVAIL:
3234 SetLastError(WSAEINVAL);
3235 break;
3236 case EADDRINUSE:
3238 int optval = 0;
3239 socklen_t optlen = sizeof(optval);
3240 /* Windows >= 2003 will return different results depending on
3241 * SO_REUSEADDR, WSAEACCES may be returned representing that
3242 * the socket hijacking protection prevented the bind */
3243 if (!getsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&optval, &optlen) && optval)
3245 SetLastError(WSAEACCES);
3246 break;
3248 /* fall through */
3250 default:
3251 SetLastError(wsaErrno());
3252 break;
3255 else
3257 res=0; /* success */
3261 release_sock_fd( s, fd );
3263 return res;
3266 /***********************************************************************
3267 * closesocket (WS2_32.3)
3269 int WINAPI WS_closesocket(SOCKET s)
3271 int res = SOCKET_ERROR, fd;
3272 if (num_startup)
3274 fd = get_sock_fd(s, FILE_READ_DATA, NULL);
3275 if (fd >= 0)
3277 release_sock_fd(s, fd);
3278 if (CloseHandle(SOCKET2HANDLE(s)))
3279 res = 0;
3281 else
3282 SetLastError(WSAENOTSOCK);
3284 else
3285 SetLastError(WSANOTINITIALISED);
3286 TRACE("(socket %04lx) -> %d\n", s, res);
3287 return res;
3290 static int do_connect(int fd, const struct WS_sockaddr* name, int namelen)
3292 union generic_unix_sockaddr uaddr;
3293 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
3295 if (!uaddrlen)
3296 return WSAEFAULT;
3298 if (name->sa_family == WS_AF_INET)
3300 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
3301 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
3303 /* Trying to connect to magic replace-loopback address,
3304 * assuming we really want to connect to localhost */
3305 TRACE("Trying to connect to magic IP address, using "
3306 "INADDR_LOOPBACK instead.\n");
3307 in4->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
3311 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
3312 return 0;
3314 return wsaErrno();
3317 /***********************************************************************
3318 * connect (WS2_32.4)
3320 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
3322 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
3324 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
3326 if (fd != -1)
3328 NTSTATUS status;
3329 BOOL is_blocking;
3330 int ret = do_connect(fd, name, namelen);
3331 if (ret == 0)
3332 goto connect_success;
3334 if (ret == WSAEINPROGRESS)
3336 /* tell wineserver that a connection is in progress */
3337 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3338 FD_CONNECT,
3339 FD_WINE_CONNECTED|FD_WINE_LISTENING);
3340 status = _is_blocking( s, &is_blocking );
3341 if (status)
3343 release_sock_fd( s, fd );
3344 set_error( status );
3345 return SOCKET_ERROR;
3347 if (is_blocking)
3349 int result;
3350 /* block here */
3351 do_block(fd, POLLIN | POLLOUT, -1);
3352 _sync_sock_state(s); /* let wineserver notice connection */
3353 /* retrieve any error codes from it */
3354 result = _get_sock_error(s, FD_CONNECT_BIT);
3355 if (result)
3356 SetLastError(NtStatusToWSAError(result));
3357 else
3359 goto connect_success;
3362 else
3364 SetLastError(WSAEWOULDBLOCK);
3367 else
3369 SetLastError(ret);
3371 release_sock_fd( s, fd );
3373 return SOCKET_ERROR;
3375 connect_success:
3376 release_sock_fd( s, fd );
3377 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3378 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
3379 FD_CONNECT|FD_WINE_LISTENING);
3380 TRACE("\tconnected %04lx\n", s);
3381 return 0;
3384 /***********************************************************************
3385 * WSAConnect (WS2_32.30)
3387 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
3388 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
3389 LPQOS lpSQOS, LPQOS lpGQOS )
3391 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
3392 FIXME("unsupported parameters!\n");
3393 return WS_connect( s, name, namelen );
3396 /***********************************************************************
3397 * ConnectEx
3399 static BOOL WINAPI WS2_ConnectEx(SOCKET s, const struct WS_sockaddr* name, int namelen,
3400 PVOID sendBuf, DWORD sendBufLen, LPDWORD sent, LPOVERLAPPED ov)
3402 int fd, ret, status;
3404 if (!ov)
3406 SetLastError( ERROR_INVALID_PARAMETER );
3407 return FALSE;
3410 fd = get_sock_fd( s, FILE_READ_DATA, NULL );
3411 if (fd == -1)
3413 SetLastError( WSAENOTSOCK );
3414 return FALSE;
3417 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
3418 s, name, debugstr_sockaddr(name), namelen, sendBuf, sendBufLen, ov);
3420 ret = is_fd_bound(fd, NULL, NULL);
3421 if (ret <= 0)
3423 SetLastError(ret == -1 ? wsaErrno() : WSAEINVAL);
3424 release_sock_fd( s, fd );
3425 return FALSE;
3428 ret = do_connect(fd, name, namelen);
3429 if (ret == 0)
3431 WSABUF wsabuf;
3433 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3434 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
3435 FD_CONNECT|FD_WINE_LISTENING);
3437 wsabuf.len = sendBufLen;
3438 wsabuf.buf = (char*) sendBuf;
3440 /* WSASend takes care of completion if need be */
3441 if (WSASend(s, &wsabuf, sendBuf ? 1 : 0, sent, 0, ov, NULL) != SOCKET_ERROR)
3442 goto connection_success;
3444 else if (ret == WSAEINPROGRESS)
3446 struct ws2_async *wsa;
3447 ULONG_PTR cvalue = (((ULONG_PTR)ov->hEvent & 1) == 0) ? (ULONG_PTR)ov : 0;
3449 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3450 FD_CONNECT,
3451 FD_WINE_CONNECTED|FD_WINE_LISTENING);
3453 /* Indirectly call WSASend */
3454 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof( struct ws2_async, iovec[1] ))))
3456 SetLastError(WSAEFAULT);
3458 else
3460 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)ov;
3461 iosb->u.Status = STATUS_PENDING;
3462 iosb->Information = 0;
3464 wsa->hSocket = SOCKET2HANDLE(s);
3465 wsa->addr = NULL;
3466 wsa->addrlen.val = 0;
3467 wsa->flags = 0;
3468 wsa->lpFlags = &wsa->flags;
3469 wsa->control = NULL;
3470 wsa->n_iovecs = sendBuf ? 1 : 0;
3471 wsa->first_iovec = 0;
3472 wsa->completion_func = NULL;
3473 wsa->iovec[0].iov_base = sendBuf;
3474 wsa->iovec[0].iov_len = sendBufLen;
3476 SERVER_START_REQ( register_async )
3478 req->type = ASYNC_TYPE_WRITE;
3479 req->async.handle = wine_server_obj_handle( wsa->hSocket );
3480 req->async.callback = wine_server_client_ptr( WS2_async_send );
3481 req->async.iosb = wine_server_client_ptr( iosb );
3482 req->async.arg = wine_server_client_ptr( wsa );
3483 req->async.event = wine_server_obj_handle( ov->hEvent );
3484 req->async.cvalue = cvalue;
3485 status = wine_server_call( req );
3487 SERVER_END_REQ;
3489 if (status != STATUS_PENDING) HeapFree(GetProcessHeap(), 0, wsa);
3491 /* If the connect already failed */
3492 if (status == STATUS_PIPE_DISCONNECTED)
3493 status = _get_sock_error(s, FD_CONNECT_BIT);
3494 SetLastError( NtStatusToWSAError(status) );
3497 else
3499 SetLastError(ret);
3502 release_sock_fd( s, fd );
3503 return FALSE;
3505 connection_success:
3506 release_sock_fd( s, fd );
3507 return TRUE;
3511 /***********************************************************************
3512 * getpeername (WS2_32.5)
3514 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
3516 int fd;
3517 int res;
3519 TRACE("socket %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
3521 fd = get_sock_fd( s, 0, NULL );
3522 res = SOCKET_ERROR;
3524 if (fd != -1)
3526 union generic_unix_sockaddr uaddr;
3527 socklen_t uaddrlen = sizeof(uaddr);
3529 if (getpeername(fd, &uaddr.addr, &uaddrlen) == 0)
3531 if (!name || !namelen)
3532 SetLastError(WSAEFAULT);
3533 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3534 /* The buffer was too small */
3535 SetLastError(WSAEFAULT);
3536 else
3538 res = 0;
3539 TRACE("=> %s\n", debugstr_sockaddr(name));
3542 else
3543 SetLastError(wsaErrno());
3544 release_sock_fd( s, fd );
3546 return res;
3549 /* When binding to an UDP address with filter support the getsockname call on the socket
3550 * will always return 0.0.0.0 instead of the filtered interface address. This function
3551 * checks if the socket is interface-bound on UDP and return the correct address.
3552 * This is required because applications often do a bind() with port zero followed by a
3553 * getsockname() to retrieve the port and address acquired.
3555 static void interface_bind_check(int fd, struct sockaddr_in *addr)
3557 #if !defined(IP_BOUND_IF) && !defined(LINUX_BOUND_IF)
3558 return;
3559 #else
3560 int ifindex;
3561 socklen_t len;
3563 /* Check for IPv4, address 0.0.0.0 and UDP socket */
3564 if (addr->sin_family != AF_INET || addr->sin_addr.s_addr != 0)
3565 return;
3566 if (_get_fd_type(fd) != SOCK_DGRAM)
3567 return;
3569 ifindex = -1;
3570 len = sizeof(ifindex);
3571 #if defined(IP_BOUND_IF)
3572 getsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &ifindex, &len);
3573 #elif defined(LINUX_BOUND_IF)
3574 getsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex, &len);
3575 if (ifindex > 0) ifindex = ntohl(ifindex);
3576 #endif
3577 if (ifindex > 0)
3579 PIP_ADAPTER_INFO adapters, adapter;
3580 DWORD adap_size;
3582 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
3583 return;
3584 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
3585 if (adapters && GetAdaptersInfo(adapters, &adap_size) == NO_ERROR)
3587 /* Search the IPv4 adapter list for the appropriate bound interface */
3588 for (adapter = adapters; adapter != NULL; adapter = adapter->Next)
3590 in_addr_t adapter_addr;
3591 if (adapter->Index != ifindex) continue;
3593 adapter_addr = inet_addr(adapter->IpAddressList.IpAddress.String);
3594 addr->sin_addr.s_addr = adapter_addr;
3595 TRACE("reporting interface address from adapter %d\n", ifindex);
3596 break;
3599 HeapFree(GetProcessHeap(), 0, adapters);
3601 #endif
3604 /***********************************************************************
3605 * getsockname (WS2_32.6)
3607 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
3609 int fd;
3610 int res;
3612 TRACE("socket %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
3614 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
3615 if( (name == NULL) || (namelen == NULL) )
3617 SetLastError( WSAEFAULT );
3618 return SOCKET_ERROR;
3621 fd = get_sock_fd( s, 0, NULL );
3622 res = SOCKET_ERROR;
3624 if (fd != -1)
3626 union generic_unix_sockaddr uaddr;
3627 socklen_t uaddrlen;
3628 int bound = is_fd_bound(fd, &uaddr, &uaddrlen);
3630 if (bound <= 0)
3632 SetLastError(bound == -1 ? wsaErrno() : WSAEINVAL);
3634 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3636 /* The buffer was too small */
3637 SetLastError(WSAEFAULT);
3639 else
3641 interface_bind_check(fd, (struct sockaddr_in*) &uaddr);
3642 if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3644 /* The buffer was too small */
3645 SetLastError(WSAEFAULT);
3647 else
3649 res = 0;
3650 TRACE("=> %s\n", debugstr_sockaddr(name));
3653 release_sock_fd( s, fd );
3655 return res;
3658 /***********************************************************************
3659 * getsockopt (WS2_32.7)
3661 INT WINAPI WS_getsockopt(SOCKET s, INT level,
3662 INT optname, char *optval, INT *optlen)
3664 int fd;
3665 INT ret = 0;
3667 TRACE("(socket %04lx, %s, optval %s, optlen %p (%d))\n", s,
3668 debugstr_sockopt(level, optname), debugstr_optval(optval, 0),
3669 optlen, optlen ? *optlen : 0);
3671 switch(level)
3673 case WS_SOL_SOCKET:
3675 switch(optname)
3677 /* Handle common cases. The special cases are below, sorted
3678 * alphabetically */
3679 case WS_SO_BROADCAST:
3680 case WS_SO_DEBUG:
3681 case WS_SO_KEEPALIVE:
3682 case WS_SO_OOBINLINE:
3683 case WS_SO_RCVBUF:
3684 case WS_SO_REUSEADDR:
3685 case WS_SO_SNDBUF:
3686 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3687 return SOCKET_ERROR;
3688 convert_sockopt(&level, &optname);
3689 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3691 SetLastError(wsaErrno());
3692 ret = SOCKET_ERROR;
3694 release_sock_fd( s, fd );
3695 return ret;
3696 case WS_SO_ACCEPTCONN:
3697 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3698 return SOCKET_ERROR;
3699 if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, optval, (socklen_t *)optlen) != 0 )
3701 SetLastError(wsaErrno());
3702 ret = SOCKET_ERROR;
3704 else
3706 /* BSD returns != 0 while Windows return exact == 1 */
3707 if (*(int *)optval) *(int *)optval = 1;
3709 release_sock_fd( s, fd );
3710 return ret;
3711 case WS_SO_BSP_STATE:
3713 int req_size, addr_size;
3714 WSAPROTOCOL_INFOW infow;
3715 CSADDR_INFO *csinfo;
3717 ret = ws_protocol_info(s, TRUE, &infow, &addr_size);
3718 if (ret)
3720 if (infow.iAddressFamily == WS_AF_INET)
3721 addr_size = sizeof(struct sockaddr_in);
3722 else if (infow.iAddressFamily == WS_AF_INET6)
3723 addr_size = sizeof(struct sockaddr_in6);
3724 else
3726 FIXME("Family %d is unsupported for SO_BSP_STATE\n", infow.iAddressFamily);
3727 SetLastError(WSAEAFNOSUPPORT);
3728 return SOCKET_ERROR;
3731 req_size = sizeof(CSADDR_INFO) + addr_size * 2;
3732 if (*optlen < req_size)
3734 ret = 0;
3735 SetLastError(WSAEFAULT);
3737 else
3739 union generic_unix_sockaddr uaddr;
3740 socklen_t uaddrlen;
3742 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3743 return SOCKET_ERROR;
3745 csinfo = (CSADDR_INFO*) optval;
3747 /* Check if the sock is bound */
3748 if (is_fd_bound(fd, &uaddr, &uaddrlen) == 1)
3750 csinfo->LocalAddr.lpSockaddr =
3751 (LPSOCKADDR) (optval + sizeof(CSADDR_INFO));
3752 ws_sockaddr_u2ws(&uaddr.addr, csinfo->LocalAddr.lpSockaddr, &addr_size);
3753 csinfo->LocalAddr.iSockaddrLength = addr_size;
3755 else
3757 csinfo->LocalAddr.lpSockaddr = NULL;
3758 csinfo->LocalAddr.iSockaddrLength = 0;
3761 /* Check if the sock is connected */
3762 if (!getpeername(fd, &uaddr.addr, &uaddrlen) &&
3763 is_sockaddr_bound(&uaddr.addr, uaddrlen))
3765 csinfo->RemoteAddr.lpSockaddr =
3766 (LPSOCKADDR) (optval + sizeof(CSADDR_INFO) + addr_size);
3767 ws_sockaddr_u2ws(&uaddr.addr, csinfo->RemoteAddr.lpSockaddr, &addr_size);
3768 csinfo->RemoteAddr.iSockaddrLength = addr_size;
3770 else
3772 csinfo->RemoteAddr.lpSockaddr = NULL;
3773 csinfo->RemoteAddr.iSockaddrLength = 0;
3776 csinfo->iSocketType = infow.iSocketType;
3777 csinfo->iProtocol = infow.iProtocol;
3778 release_sock_fd( s, fd );
3781 return ret ? 0 : SOCKET_ERROR;
3783 case WS_SO_DONTLINGER:
3785 struct linger lingval;
3786 socklen_t len = sizeof(struct linger);
3788 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
3790 SetLastError(WSAEFAULT);
3791 return SOCKET_ERROR;
3793 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3794 return SOCKET_ERROR;
3796 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
3798 SetLastError(wsaErrno());
3799 ret = SOCKET_ERROR;
3801 else
3803 *(BOOL *)optval = !lingval.l_onoff;
3804 *optlen = sizeof(BOOL);
3807 release_sock_fd( s, fd );
3808 return ret;
3811 case WS_SO_CONNECT_TIME:
3813 static int pretendtime = 0;
3814 struct WS_sockaddr addr;
3815 int len = sizeof(addr);
3817 if (!optlen || *optlen < sizeof(DWORD) || !optval)
3819 SetLastError(WSAEFAULT);
3820 return SOCKET_ERROR;
3822 if (WS_getpeername(s, &addr, &len) == SOCKET_ERROR)
3823 *(DWORD *)optval = ~0u;
3824 else
3826 if (!pretendtime) FIXME("WS_SO_CONNECT_TIME - faking results\n");
3827 *(DWORD *)optval = pretendtime++;
3829 *optlen = sizeof(DWORD);
3830 return ret;
3832 /* As mentioned in setsockopt, Windows ignores this, so we
3833 * always return true here */
3834 case WS_SO_DONTROUTE:
3835 if (!optlen || *optlen < sizeof(BOOL) || !optval)
3837 SetLastError(WSAEFAULT);
3838 return SOCKET_ERROR;
3840 *(BOOL *)optval = TRUE;
3841 *optlen = sizeof(BOOL);
3842 return 0;
3844 case WS_SO_ERROR:
3846 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3847 return SOCKET_ERROR;
3848 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, optval, (socklen_t *)optlen) != 0 )
3850 SetLastError(wsaErrno());
3851 ret = SOCKET_ERROR;
3853 release_sock_fd( s, fd );
3855 /* The wineserver may have swallowed the error before us */
3856 if (!ret && *(int*) optval == 0)
3858 int i, events[FD_MAX_EVENTS];
3859 _get_sock_errors(s, events);
3860 for (i = 0; i < FD_MAX_EVENTS; i++)
3862 if(events[i])
3864 events[i] = NtStatusToWSAError(events[i]);
3865 TRACE("returning SO_ERROR %d from wine server\n", events[i]);
3866 *(int*) optval = events[i];
3867 break;
3871 return ret;
3874 case WS_SO_LINGER:
3876 struct linger lingval;
3877 socklen_t len = sizeof(struct linger);
3879 /* struct linger and LINGER have different sizes */
3880 if (!optlen || *optlen < sizeof(LINGER) || !optval)
3882 SetLastError(WSAEFAULT);
3883 return SOCKET_ERROR;
3885 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3886 return SOCKET_ERROR;
3888 if (_get_fd_type(fd) == SOCK_DGRAM)
3890 SetLastError(WSAENOPROTOOPT);
3891 ret = SOCKET_ERROR;
3893 else if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0)
3895 SetLastError(wsaErrno());
3896 ret = SOCKET_ERROR;
3898 else
3900 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
3901 ((LINGER *)optval)->l_linger = lingval.l_linger;
3902 *optlen = sizeof(struct linger);
3905 release_sock_fd( s, fd );
3906 return ret;
3909 case WS_SO_MAX_MSG_SIZE:
3910 if (!optlen || *optlen < sizeof(int) || !optval)
3912 SetLastError(WSAEFAULT);
3913 return SOCKET_ERROR;
3915 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
3916 *(int *)optval = 65507;
3917 *optlen = sizeof(int);
3918 return 0;
3920 /* SO_OPENTYPE does not require a valid socket handle. */
3921 case WS_SO_OPENTYPE:
3922 if (!optlen || *optlen < sizeof(int) || !optval)
3924 SetLastError(WSAEFAULT);
3925 return SOCKET_ERROR;
3927 *(int *)optval = get_per_thread_data()->opentype;
3928 *optlen = sizeof(int);
3929 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
3930 return 0;
3931 case WS_SO_PROTOCOL_INFOA:
3932 case WS_SO_PROTOCOL_INFOW:
3934 int size;
3935 WSAPROTOCOL_INFOW infow;
3937 ret = ws_protocol_info(s, optname == WS_SO_PROTOCOL_INFOW, &infow, &size);
3938 if (ret)
3940 if (!optlen || !optval || *optlen < size)
3942 if(optlen) *optlen = size;
3943 ret = 0;
3944 SetLastError(WSAEFAULT);
3946 else
3947 memcpy(optval, &infow, size);
3949 return ret ? 0 : SOCKET_ERROR;
3951 case WS_SO_RCVTIMEO:
3952 case WS_SO_SNDTIMEO:
3954 INT64 timeout;
3956 if (!optlen || *optlen < sizeof(int)|| !optval)
3958 SetLastError(WSAEFAULT);
3959 return SOCKET_ERROR;
3961 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3962 return SOCKET_ERROR;
3964 timeout = get_rcvsnd_timeo(fd, optname == WS_SO_RCVTIMEO);
3965 *(int *)optval = timeout <= UINT_MAX ? timeout : UINT_MAX;
3967 release_sock_fd( s, fd );
3968 return ret;
3970 case WS_SO_TYPE:
3972 int sock_type;
3973 if (!optlen || *optlen < sizeof(int) || !optval)
3975 SetLastError(WSAEFAULT);
3976 return SOCKET_ERROR;
3978 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3979 return SOCKET_ERROR;
3981 sock_type = _get_fd_type(fd);
3982 if (sock_type == -1)
3984 SetLastError(wsaErrno());
3985 ret = SOCKET_ERROR;
3987 else
3988 (*(int *)optval) = convert_socktype_u2w(sock_type);
3990 release_sock_fd( s, fd );
3991 return ret;
3993 default:
3994 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
3995 SetLastError(WSAENOPROTOOPT);
3996 return SOCKET_ERROR;
3997 } /* end switch(optname) */
3998 }/* end case WS_SOL_SOCKET */
3999 #ifdef HAS_IPX
4000 case WS_NSPROTO_IPX:
4002 struct WS_sockaddr_ipx addr;
4003 IPX_ADDRESS_DATA *data;
4004 int namelen;
4005 switch(optname)
4007 case WS_IPX_PTYPE:
4008 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
4009 #ifdef SOL_IPX
4010 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (socklen_t *)optlen) == -1)
4012 ret = SOCKET_ERROR;
4014 #else
4016 struct ipx val;
4017 socklen_t len=sizeof(struct ipx);
4018 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
4019 ret = SOCKET_ERROR;
4020 else
4021 *optval = (int)val.ipx_pt;
4023 #endif
4024 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
4025 release_sock_fd( s, fd );
4026 return ret;
4028 case WS_IPX_ADDRESS:
4030 * On a Win2000 system with one network card there are usually
4031 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
4032 * Using this call you can then retrieve info about this all.
4033 * In case of Linux it is a bit different. Usually you have
4034 * only "one" device active and further it is not possible to
4035 * query things like the linkspeed.
4037 FIXME("IPX_ADDRESS\n");
4038 namelen = sizeof(struct WS_sockaddr_ipx);
4039 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
4040 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
4042 data = (IPX_ADDRESS_DATA*)optval;
4043 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
4044 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
4045 data->adapternum = 0;
4046 data->wan = FALSE; /* We are not on a wan for now .. */
4047 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
4048 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
4049 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
4050 * note 1MB = 1000kB in this case */
4051 return 0;
4053 case WS_IPX_MAX_ADAPTER_NUM:
4054 FIXME("IPX_MAX_ADAPTER_NUM\n");
4055 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
4056 return 0;
4058 default:
4059 FIXME("IPX optname:%x\n", optname);
4060 return SOCKET_ERROR;
4061 }/* end switch(optname) */
4062 } /* end case WS_NSPROTO_IPX */
4063 #endif
4065 #ifdef HAS_IRDA
4066 #define MAX_IRDA_DEVICES 10
4068 case WS_SOL_IRLMP:
4069 switch(optname)
4071 case WS_IRLMP_ENUMDEVICES:
4073 char buf[sizeof(struct irda_device_list) +
4074 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
4075 int res;
4076 socklen_t len = sizeof(buf);
4078 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4079 return SOCKET_ERROR;
4080 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
4081 release_sock_fd( s, fd );
4082 if (res < 0)
4084 SetLastError(wsaErrno());
4085 return SOCKET_ERROR;
4087 else
4089 struct irda_device_list *src = (struct irda_device_list *)buf;
4090 DEVICELIST *dst = (DEVICELIST *)optval;
4091 INT needed = sizeof(DEVICELIST);
4092 unsigned int i;
4094 if (src->len > 0)
4095 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
4096 if (*optlen < needed)
4098 SetLastError(WSAEFAULT);
4099 return SOCKET_ERROR;
4101 *optlen = needed;
4102 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
4103 dst->numDevice = src->len;
4104 for (i = 0; i < src->len; i++)
4106 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
4107 src->dev[i].saddr, src->dev[i].daddr,
4108 src->dev[i].info, src->dev[i].hints[0],
4109 src->dev[i].hints[1]);
4110 memcpy( dst->Device[i].irdaDeviceID,
4111 &src->dev[i].daddr,
4112 sizeof(dst->Device[i].irdaDeviceID) ) ;
4113 memcpy( dst->Device[i].irdaDeviceName,
4114 src->dev[i].info,
4115 sizeof(dst->Device[i].irdaDeviceName) ) ;
4116 memcpy( &dst->Device[i].irdaDeviceHints1,
4117 &src->dev[i].hints[0],
4118 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
4119 memcpy( &dst->Device[i].irdaDeviceHints2,
4120 &src->dev[i].hints[1],
4121 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
4122 dst->Device[i].irdaCharSet = src->dev[i].charset;
4124 return 0;
4127 default:
4128 FIXME("IrDA optname:0x%x\n", optname);
4129 return SOCKET_ERROR;
4131 break; /* case WS_SOL_IRLMP */
4132 #undef MAX_IRDA_DEVICES
4133 #endif
4135 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
4136 case WS_IPPROTO_TCP:
4137 switch(optname)
4139 case WS_TCP_NODELAY:
4140 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4141 return SOCKET_ERROR;
4142 convert_sockopt(&level, &optname);
4143 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
4145 SetLastError(wsaErrno());
4146 ret = SOCKET_ERROR;
4148 release_sock_fd( s, fd );
4149 return ret;
4151 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
4152 return SOCKET_ERROR;
4154 case WS_IPPROTO_IP:
4155 switch(optname)
4157 case WS_IP_ADD_MEMBERSHIP:
4158 case WS_IP_DROP_MEMBERSHIP:
4159 #ifdef IP_HDRINCL
4160 case WS_IP_HDRINCL:
4161 #endif
4162 case WS_IP_MULTICAST_IF:
4163 case WS_IP_MULTICAST_LOOP:
4164 case WS_IP_MULTICAST_TTL:
4165 case WS_IP_OPTIONS:
4166 #ifdef IP_PKTINFO
4167 case WS_IP_PKTINFO:
4168 #endif
4169 case WS_IP_TOS:
4170 case WS_IP_TTL:
4171 #ifdef IP_UNICAST_IF
4172 case WS_IP_UNICAST_IF:
4173 #endif
4174 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4175 return SOCKET_ERROR;
4176 convert_sockopt(&level, &optname);
4177 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
4179 SetLastError(wsaErrno());
4180 ret = SOCKET_ERROR;
4182 release_sock_fd( s, fd );
4183 return ret;
4184 case WS_IP_DONTFRAGMENT:
4185 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
4186 *(BOOL*)optval = FALSE;
4187 return 0;
4189 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
4190 return SOCKET_ERROR;
4192 case WS_IPPROTO_IPV6:
4193 switch(optname)
4195 #ifdef IPV6_ADD_MEMBERSHIP
4196 case WS_IPV6_ADD_MEMBERSHIP:
4197 #endif
4198 #ifdef IPV6_DROP_MEMBERSHIP
4199 case WS_IPV6_DROP_MEMBERSHIP:
4200 #endif
4201 case WS_IPV6_MULTICAST_IF:
4202 case WS_IPV6_MULTICAST_HOPS:
4203 case WS_IPV6_MULTICAST_LOOP:
4204 case WS_IPV6_UNICAST_HOPS:
4205 case WS_IPV6_V6ONLY:
4206 #ifdef IPV6_UNICAST_IF
4207 case WS_IPV6_UNICAST_IF:
4208 #endif
4209 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4210 return SOCKET_ERROR;
4211 convert_sockopt(&level, &optname);
4212 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
4214 SetLastError(wsaErrno());
4215 ret = SOCKET_ERROR;
4217 release_sock_fd( s, fd );
4218 return ret;
4219 case WS_IPV6_DONTFRAG:
4220 FIXME("WS_IPV6_DONTFRAG is always false!\n");
4221 *(BOOL*)optval = FALSE;
4222 return 0;
4224 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
4225 return SOCKET_ERROR;
4227 default:
4228 WARN("Unknown level: 0x%08x\n", level);
4229 SetLastError(WSAEINVAL);
4230 return SOCKET_ERROR;
4231 } /* end switch(level) */
4234 /***********************************************************************
4235 * htonl (WS2_32.8)
4237 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
4239 return htonl(hostlong);
4243 /***********************************************************************
4244 * htons (WS2_32.9)
4246 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
4248 return htons(hostshort);
4251 /***********************************************************************
4252 * WSAHtonl (WS2_32.46)
4253 * From MSDN description of error codes, this function should also
4254 * check if WinSock has been initialized and the socket is a valid
4255 * socket. But why? This function only translates a host byte order
4256 * u_long into a network byte order u_long...
4258 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
4260 if (lpnetlong)
4262 *lpnetlong = htonl(hostlong);
4263 return 0;
4265 SetLastError(WSAEFAULT);
4266 return SOCKET_ERROR;
4269 /***********************************************************************
4270 * WSAHtons (WS2_32.47)
4271 * From MSDN description of error codes, this function should also
4272 * check if WinSock has been initialized and the socket is a valid
4273 * socket. But why? This function only translates a host byte order
4274 * u_short into a network byte order u_short...
4276 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
4279 if (lpnetshort)
4281 *lpnetshort = htons(hostshort);
4282 return 0;
4284 SetLastError(WSAEFAULT);
4285 return SOCKET_ERROR;
4289 /***********************************************************************
4290 * inet_addr (WS2_32.11)
4292 WS_u_long WINAPI WS_inet_addr(const char *cp)
4294 if (!cp) return INADDR_NONE;
4295 return inet_addr(cp);
4299 /***********************************************************************
4300 * ntohl (WS2_32.14)
4302 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
4304 return ntohl(netlong);
4308 /***********************************************************************
4309 * ntohs (WS2_32.15)
4311 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
4313 return ntohs(netshort);
4317 /***********************************************************************
4318 * inet_ntoa (WS2_32.12)
4320 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
4322 struct per_thread_data *data = get_per_thread_data();
4324 sprintf( data->ntoa_buffer, "%u.%u.%u.%u",
4325 (unsigned int)(ntohl( in.WS_s_addr ) >> 24 & 0xff),
4326 (unsigned int)(ntohl( in.WS_s_addr ) >> 16 & 0xff),
4327 (unsigned int)(ntohl( in.WS_s_addr ) >> 8 & 0xff),
4328 (unsigned int)(ntohl( in.WS_s_addr ) & 0xff) );
4330 return data->ntoa_buffer;
4333 static const char *debugstr_wsaioctl(DWORD ioctl)
4335 const char *buf_type, *family;
4337 switch(ioctl & 0x18000000)
4339 case WS_IOC_WS2:
4340 family = "IOC_WS2";
4341 break;
4342 case WS_IOC_PROTOCOL:
4343 family = "IOC_PROTOCOL";
4344 break;
4345 case WS_IOC_VENDOR:
4346 family = "IOC_VENDOR";
4347 break;
4348 default: /* WS_IOC_UNIX */
4350 BYTE size = (ioctl >> 16) & WS_IOCPARM_MASK;
4351 char x = (ioctl & 0xff00) >> 8;
4352 BYTE y = ioctl & 0xff;
4353 char args[14];
4355 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
4357 case WS_IOC_VOID:
4358 buf_type = "_IO";
4359 sprintf(args, "%d, %d", x, y);
4360 break;
4361 case WS_IOC_IN:
4362 buf_type = "_IOW";
4363 sprintf(args, "'%c', %d, %d", x, y, size);
4364 break;
4365 case WS_IOC_OUT:
4366 buf_type = "_IOR";
4367 sprintf(args, "'%c', %d, %d", x, y, size);
4368 break;
4369 default:
4370 buf_type = "?";
4371 sprintf(args, "'%c', %d, %d", x, y, size);
4372 break;
4374 return wine_dbg_sprintf("%s(%s)", buf_type, args);
4378 /* We are different from WS_IOC_UNIX. */
4379 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
4381 case WS_IOC_VOID:
4382 buf_type = "_WSAIO";
4383 break;
4384 case WS_IOC_INOUT:
4385 buf_type = "_WSAIORW";
4386 break;
4387 case WS_IOC_IN:
4388 buf_type = "_WSAIOW";
4389 break;
4390 case WS_IOC_OUT:
4391 buf_type = "_WSAIOR";
4392 break;
4393 default:
4394 buf_type = "?";
4395 break;
4398 return wine_dbg_sprintf("%s(%s, %d)", buf_type, family,
4399 (USHORT)(ioctl & 0xffff));
4402 /* do an ioctl call through the server */
4403 static DWORD server_ioctl_sock( SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size,
4404 LPVOID out_buff, DWORD out_size, LPDWORD ret_size,
4405 LPWSAOVERLAPPED overlapped,
4406 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
4408 HANDLE event = overlapped ? overlapped->hEvent : 0;
4409 HANDLE handle = SOCKET2HANDLE( s );
4410 struct ws2_async *wsa;
4411 NTSTATUS status;
4412 PIO_STATUS_BLOCK io;
4414 if (!(wsa = (struct ws2_async *)alloc_async_io( sizeof(*wsa) )))
4415 return WSA_NOT_ENOUGH_MEMORY;
4416 wsa->hSocket = handle;
4417 wsa->user_overlapped = overlapped;
4418 wsa->completion_func = completion;
4419 io = (overlapped ? (PIO_STATUS_BLOCK)overlapped : &wsa->local_iosb);
4421 status = NtDeviceIoControlFile( handle, event, ws2_async_apc, wsa, io, code,
4422 in_buff, in_size, out_buff, out_size );
4423 if (status == STATUS_NOT_SUPPORTED)
4425 FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
4426 code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
4428 else if (status == STATUS_SUCCESS)
4429 *ret_size = io->Information; /* "Information" is the size written to the output buffer */
4431 if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, wsa );
4433 return NtStatusToWSAError( status );
4436 /**********************************************************************
4437 * WSAIoctl (WS2_32.50)
4440 INT WINAPI WSAIoctl(SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size, LPVOID out_buff,
4441 DWORD out_size, LPDWORD ret_size, LPWSAOVERLAPPED overlapped,
4442 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
4444 int fd;
4445 DWORD status = 0, total = 0;
4447 TRACE("%04lx, %s, %p, %d, %p, %d, %p, %p, %p\n",
4448 s, debugstr_wsaioctl(code), in_buff, in_size, out_buff, out_size, ret_size, overlapped, completion);
4450 switch (code)
4452 case WS_FIONBIO:
4453 if (in_size != sizeof(WS_u_long) || IS_INTRESOURCE(in_buff))
4455 SetLastError(WSAEFAULT);
4456 return SOCKET_ERROR;
4458 TRACE("-> FIONBIO (%x)\n", *(WS_u_long*)in_buff);
4459 if (_get_sock_mask(s))
4461 /* AsyncSelect()'ed sockets are always nonblocking */
4462 if (!*(WS_u_long *)in_buff) status = WSAEINVAL;
4463 break;
4465 if (*(WS_u_long *)in_buff)
4466 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
4467 else
4468 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
4469 break;
4471 case WS_FIONREAD:
4473 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
4475 SetLastError(WSAEFAULT);
4476 return SOCKET_ERROR;
4478 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
4479 if (ioctl(fd, FIONREAD, out_buff ) == -1)
4480 status = wsaErrno();
4481 release_sock_fd( s, fd );
4482 break;
4485 case WS_SIOCATMARK:
4487 unsigned int oob = 0, atmark = 0;
4488 socklen_t oobsize = sizeof(int);
4489 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
4491 SetLastError(WSAEFAULT);
4492 return SOCKET_ERROR;
4494 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
4495 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
4496 if ((getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &oob, &oobsize ) == -1)
4497 || (!oob && ioctl(fd, SIOCATMARK, &atmark ) == -1))
4498 status = wsaErrno();
4499 else
4501 /* The SIOCATMARK value read from ioctl() is reversed
4502 * because BSD returns TRUE if it's in the OOB mark
4503 * while Windows returns TRUE if there are NO OOB bytes.
4505 (*(WS_u_long *) out_buff) = oob || !atmark;
4508 release_sock_fd( s, fd );
4509 break;
4512 case WS_FIOASYNC:
4513 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
4514 SetLastError(WSAEINVAL);
4515 return SOCKET_ERROR;
4517 case WS_SIO_GET_INTERFACE_LIST:
4519 INTERFACE_INFO* intArray = out_buff;
4520 DWORD size, numInt = 0, apiReturn;
4522 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
4524 if (!out_buff || !ret_size)
4526 SetLastError(WSAEFAULT);
4527 return SOCKET_ERROR;
4530 fd = get_sock_fd( s, 0, NULL );
4531 if (fd == -1) return SOCKET_ERROR;
4533 apiReturn = GetAdaptersInfo(NULL, &size);
4534 if (apiReturn == ERROR_BUFFER_OVERFLOW)
4536 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
4538 if (table)
4540 if (GetAdaptersInfo(table, &size) == NO_ERROR)
4542 PIP_ADAPTER_INFO ptr;
4544 for (ptr = table, numInt = 0; ptr; ptr = ptr->Next)
4546 unsigned int addr, mask, bcast;
4547 struct ifreq ifInfo;
4549 /* Skip interfaces without an IPv4 address. */
4550 if (ptr->IpAddressList.IpAddress.String[0] == '\0')
4551 continue;
4553 if ((numInt + 1)*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > out_size)
4555 WARN("Buffer too small = %u, out_size = %u\n", numInt + 1, out_size);
4556 status = WSAEFAULT;
4557 break;
4560 /* Socket Status Flags */
4561 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
4562 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
4564 ERR("Error obtaining status flags for socket!\n");
4565 status = WSAEINVAL;
4566 break;
4568 else
4570 /* set flags; the values of IFF_* are not the same
4571 under Linux and Windows, therefore must generate
4572 new flags */
4573 intArray->iiFlags = 0;
4574 if (ifInfo.ifr_flags & IFF_BROADCAST)
4575 intArray->iiFlags |= WS_IFF_BROADCAST;
4576 #ifdef IFF_POINTOPOINT
4577 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
4578 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
4579 #endif
4580 if (ifInfo.ifr_flags & IFF_LOOPBACK)
4581 intArray->iiFlags |= WS_IFF_LOOPBACK;
4582 if (ifInfo.ifr_flags & IFF_UP)
4583 intArray->iiFlags |= WS_IFF_UP;
4584 if (ifInfo.ifr_flags & IFF_MULTICAST)
4585 intArray->iiFlags |= WS_IFF_MULTICAST;
4588 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
4589 mask = inet_addr(ptr->IpAddressList.IpMask.String);
4590 bcast = addr | ~mask;
4591 intArray->iiAddress.AddressIn.sin_family = AF_INET;
4592 intArray->iiAddress.AddressIn.sin_port = 0;
4593 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
4594 addr;
4595 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
4596 intArray->iiNetmask.AddressIn.sin_port = 0;
4597 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
4598 mask;
4599 intArray->iiBroadcastAddress.AddressIn.sin_family =
4600 AF_INET;
4601 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
4602 intArray->iiBroadcastAddress.AddressIn.sin_addr.
4603 WS_s_addr = bcast;
4604 intArray++;
4605 numInt++;
4608 else
4610 ERR("Unable to get interface table!\n");
4611 status = WSAEINVAL;
4613 HeapFree(GetProcessHeap(),0,table);
4615 else status = WSAEINVAL;
4617 else if (apiReturn != ERROR_NO_DATA)
4619 ERR("Unable to get interface table!\n");
4620 status = WSAEINVAL;
4622 /* Calculate the size of the array being returned */
4623 total = sizeof(INTERFACE_INFO) * numInt;
4624 release_sock_fd( s, fd );
4625 break;
4628 case WS_SIO_ADDRESS_LIST_QUERY:
4630 DWORD size;
4632 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
4634 if (!ret_size)
4636 SetLastError(WSAEFAULT);
4637 return SOCKET_ERROR;
4640 if (out_size && out_size < FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[0]))
4642 *ret_size = 0;
4643 SetLastError(WSAEINVAL);
4644 return SOCKET_ERROR;
4647 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
4649 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
4650 SOCKET_ADDRESS_LIST *sa_list;
4651 SOCKADDR_IN *sockaddr;
4652 SOCKET_ADDRESS *sa;
4653 unsigned int i;
4654 DWORD num;
4656 if (!table || GetAdaptersInfo(table, &size))
4658 HeapFree(GetProcessHeap(), 0, table);
4659 status = WSAEINVAL;
4660 break;
4663 for (p = table, num = 0; p; p = p->Next)
4664 if (p->IpAddressList.IpAddress.String[0]) num++;
4666 total = FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[num]) + num * sizeof(*sockaddr);
4667 if (total > out_size || !out_buff)
4669 *ret_size = total;
4670 HeapFree(GetProcessHeap(), 0, table);
4671 status = WSAEFAULT;
4672 break;
4675 sa_list = out_buff;
4676 sa = sa_list->Address;
4677 sockaddr = (SOCKADDR_IN *)&sa[num];
4678 sa_list->iAddressCount = num;
4680 for (p = table, i = 0; p; p = p->Next)
4682 if (!p->IpAddressList.IpAddress.String[0]) continue;
4684 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
4685 sa[i].iSockaddrLength = sizeof(SOCKADDR);
4687 sockaddr[i].sin_family = AF_INET;
4688 sockaddr[i].sin_port = 0;
4689 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
4690 i++;
4693 HeapFree(GetProcessHeap(), 0, table);
4695 else
4697 WARN("unable to get IP address list\n");
4698 status = WSAEINVAL;
4700 break;
4703 case WS_SIO_FLUSH:
4704 FIXME("SIO_FLUSH: stub.\n");
4705 break;
4707 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
4709 static const GUID connectex_guid = WSAID_CONNECTEX;
4710 static const GUID disconnectex_guid = WSAID_DISCONNECTEX;
4711 static const GUID acceptex_guid = WSAID_ACCEPTEX;
4712 static const GUID getaccepexsockaddrs_guid = WSAID_GETACCEPTEXSOCKADDRS;
4713 static const GUID transmitfile_guid = WSAID_TRANSMITFILE;
4714 static const GUID transmitpackets_guid = WSAID_TRANSMITPACKETS;
4715 static const GUID wsarecvmsg_guid = WSAID_WSARECVMSG;
4716 static const GUID wsasendmsg_guid = WSAID_WSASENDMSG;
4718 if ( IsEqualGUID(&connectex_guid, in_buff) )
4720 *(LPFN_CONNECTEX *)out_buff = WS2_ConnectEx;
4721 break;
4723 else if ( IsEqualGUID(&disconnectex_guid, in_buff) )
4725 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented DisconnectEx\n");
4727 else if ( IsEqualGUID(&acceptex_guid, in_buff) )
4729 *(LPFN_ACCEPTEX *)out_buff = WS2_AcceptEx;
4730 break;
4732 else if ( IsEqualGUID(&getaccepexsockaddrs_guid, in_buff) )
4734 *(LPFN_GETACCEPTEXSOCKADDRS *)out_buff = WS2_GetAcceptExSockaddrs;
4735 break;
4737 else if ( IsEqualGUID(&transmitfile_guid, in_buff) )
4739 *(LPFN_TRANSMITFILE *)out_buff = WS2_TransmitFile;
4740 break;
4742 else if ( IsEqualGUID(&transmitpackets_guid, in_buff) )
4744 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitPackets\n");
4746 else if ( IsEqualGUID(&wsarecvmsg_guid, in_buff) )
4748 *(LPFN_WSARECVMSG *)out_buff = WS2_WSARecvMsg;
4749 break;
4751 else if ( IsEqualGUID(&wsasendmsg_guid, in_buff) )
4753 *(LPFN_WSASENDMSG *)out_buff = WSASendMsg;
4754 break;
4756 else
4757 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff));
4759 status = WSAEOPNOTSUPP;
4760 break;
4762 case WS_SIO_KEEPALIVE_VALS:
4764 struct tcp_keepalive *k;
4765 int keepalive, keepidle, keepintvl;
4767 if (!in_buff || in_size < sizeof(struct tcp_keepalive))
4769 SetLastError(WSAEFAULT);
4770 return SOCKET_ERROR;
4773 k = in_buff;
4774 keepalive = k->onoff ? 1 : 0;
4775 keepidle = max( 1, (k->keepalivetime + 500) / 1000 );
4776 keepintvl = max( 1, (k->keepaliveinterval + 500) / 1000 );
4778 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
4780 fd = get_sock_fd(s, 0, NULL);
4781 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
4782 status = WSAEINVAL;
4783 #if defined(TCP_KEEPIDLE) || defined(TCP_KEEPINTVL)
4784 /* these values need to be set only if SO_KEEPALIVE is enabled */
4785 else if(keepalive)
4787 #ifndef TCP_KEEPIDLE
4788 FIXME("ignoring keepalive timeout\n");
4789 #else
4790 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
4791 status = WSAEINVAL;
4792 else
4793 #endif
4794 #ifdef TCP_KEEPINTVL
4795 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
4796 status = WSAEINVAL;
4797 #else
4798 FIXME("ignoring keepalive interval\n");
4799 #endif
4801 #else
4802 else
4803 FIXME("ignoring keepalive interval and timeout\n");
4804 #endif
4805 release_sock_fd(s, fd);
4806 break;
4808 case WS_SIO_ROUTING_INTERFACE_QUERY:
4810 struct WS_sockaddr *daddr = (struct WS_sockaddr *)in_buff;
4811 struct WS_sockaddr_in *daddr_in = (struct WS_sockaddr_in *)daddr;
4812 struct WS_sockaddr_in *saddr_in = out_buff;
4813 MIB_IPFORWARDROW row;
4814 PMIB_IPADDRTABLE ipAddrTable = NULL;
4815 DWORD size, i, found_index;
4817 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
4819 if (!in_buff || in_size < sizeof(struct WS_sockaddr) ||
4820 !out_buff || out_size < sizeof(struct WS_sockaddr_in) || !ret_size)
4822 SetLastError(WSAEFAULT);
4823 return SOCKET_ERROR;
4825 if (daddr->sa_family != AF_INET)
4827 FIXME("unsupported address family %d\n", daddr->sa_family);
4828 status = WSAEAFNOSUPPORT;
4829 break;
4831 if (GetBestRoute(daddr_in->sin_addr.S_un.S_addr, 0, &row) != NOERROR ||
4832 GetIpAddrTable(NULL, &size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
4834 status = WSAEFAULT;
4835 break;
4837 ipAddrTable = HeapAlloc(GetProcessHeap(), 0, size);
4838 if (GetIpAddrTable(ipAddrTable, &size, FALSE))
4840 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4841 status = WSAEFAULT;
4842 break;
4844 for (i = 0, found_index = ipAddrTable->dwNumEntries;
4845 i < ipAddrTable->dwNumEntries; i++)
4847 if (ipAddrTable->table[i].dwIndex == row.dwForwardIfIndex)
4848 found_index = i;
4850 if (found_index == ipAddrTable->dwNumEntries)
4852 ERR("no matching IP address for interface %d\n",
4853 row.dwForwardIfIndex);
4854 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4855 status = WSAEFAULT;
4856 break;
4858 saddr_in->sin_family = AF_INET;
4859 saddr_in->sin_addr.S_un.S_addr = ipAddrTable->table[found_index].dwAddr;
4860 saddr_in->sin_port = 0;
4861 total = sizeof(struct WS_sockaddr_in);
4862 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4863 break;
4865 case WS_SIO_SET_COMPATIBILITY_MODE:
4866 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
4867 status = WSAEOPNOTSUPP;
4868 break;
4869 case WS_SIO_UDP_CONNRESET:
4870 FIXME("WS_SIO_UDP_CONNRESET stub\n");
4871 break;
4872 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
4873 SetLastError(WSAEOPNOTSUPP);
4874 return SOCKET_ERROR;
4875 default:
4876 status = WSAEOPNOTSUPP;
4877 break;
4880 if (status == WSAEOPNOTSUPP)
4882 status = server_ioctl_sock(s, code, in_buff, in_size, out_buff, out_size, &total,
4883 overlapped, completion);
4884 if (status != WSAEOPNOTSUPP)
4886 if (status == 0 || status == WSA_IO_PENDING)
4887 TRACE("-> %s request\n", debugstr_wsaioctl(code));
4888 else
4889 ERR("-> %s request failed with status 0x%x\n", debugstr_wsaioctl(code), status);
4891 /* overlapped and completion operations will be handled by the server */
4892 completion = NULL;
4893 overlapped = NULL;
4895 else
4896 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code));
4899 if (completion)
4901 FIXME( "completion routine %p not supported\n", completion );
4903 else if (overlapped)
4905 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
4906 overlapped->Internal = status;
4907 overlapped->InternalHigh = total;
4908 if (overlapped->hEvent) NtSetEvent( overlapped->hEvent, NULL );
4909 if (cvalue) WS_AddCompletion( HANDLE2SOCKET(s), cvalue, status, total );
4912 if (!status)
4914 if (ret_size) *ret_size = total;
4915 return 0;
4917 SetLastError( status );
4918 return SOCKET_ERROR;
4922 /***********************************************************************
4923 * ioctlsocket (WS2_32.10)
4925 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
4927 DWORD ret_size;
4928 return WSAIoctl( s, cmd, argp, sizeof(WS_u_long), argp, sizeof(WS_u_long), &ret_size, NULL, NULL );
4931 /***********************************************************************
4932 * listen (WS2_32.13)
4934 int WINAPI WS_listen(SOCKET s, int backlog)
4936 int fd = get_sock_fd( s, FILE_READ_DATA, NULL ), ret = SOCKET_ERROR;
4938 TRACE("socket %04lx, backlog %d\n", s, backlog);
4939 if (fd != -1)
4941 int bound = is_fd_bound(fd, NULL, NULL);
4943 if (bound <= 0)
4945 SetLastError(bound == -1 ? wsaErrno() : WSAEINVAL);
4947 else if (listen(fd, backlog) == 0)
4949 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
4950 FD_WINE_LISTENING,
4951 FD_CONNECT|FD_WINE_CONNECTED);
4952 ret = 0;
4954 else
4955 SetLastError(wsaErrno());
4956 release_sock_fd( s, fd );
4958 else
4959 SetLastError(WSAENOTSOCK);
4960 return ret;
4963 /***********************************************************************
4964 * recv (WS2_32.16)
4966 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
4968 DWORD n, dwFlags = flags;
4969 WSABUF wsabuf;
4971 wsabuf.len = len;
4972 wsabuf.buf = buf;
4974 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
4975 return SOCKET_ERROR;
4976 else
4977 return n;
4980 /***********************************************************************
4981 * recvfrom (WS2_32.17)
4983 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
4984 struct WS_sockaddr *from, int *fromlen)
4986 DWORD n, dwFlags = flags;
4987 WSABUF wsabuf;
4989 wsabuf.len = len;
4990 wsabuf.buf = buf;
4992 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL, NULL) == SOCKET_ERROR )
4993 return SOCKET_ERROR;
4994 else
4995 return n;
4998 /* allocate a poll array for the corresponding fd sets */
4999 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
5000 const WS_fd_set *exceptfds, int *count_ptr )
5002 unsigned int i, j = 0, count = 0;
5003 struct pollfd *fds;
5005 if (readfds) count += readfds->fd_count;
5006 if (writefds) count += writefds->fd_count;
5007 if (exceptfds) count += exceptfds->fd_count;
5008 *count_ptr = count;
5009 if (!count)
5011 SetLastError(WSAEINVAL);
5012 return NULL;
5014 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0]))))
5016 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
5017 return NULL;
5019 if (readfds)
5020 for (i = 0; i < readfds->fd_count; i++, j++)
5022 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
5023 if (fds[j].fd == -1) goto failed;
5024 fds[j].revents = 0;
5025 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1)
5027 fds[j].events = POLLIN;
5029 else
5031 release_sock_fd( readfds->fd_array[i], fds[j].fd );
5032 fds[j].fd = -1;
5033 fds[j].events = 0;
5036 if (writefds)
5037 for (i = 0; i < writefds->fd_count; i++, j++)
5039 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
5040 if (fds[j].fd == -1) goto failed;
5041 fds[j].revents = 0;
5042 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1 ||
5043 _get_fd_type(fds[j].fd) == SOCK_DGRAM)
5045 fds[j].events = POLLOUT;
5047 else
5049 release_sock_fd( writefds->fd_array[i], fds[j].fd );
5050 fds[j].fd = -1;
5051 fds[j].events = 0;
5054 if (exceptfds)
5055 for (i = 0; i < exceptfds->fd_count; i++, j++)
5057 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
5058 if (fds[j].fd == -1) goto failed;
5059 fds[j].revents = 0;
5060 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1)
5062 int oob_inlined = 0;
5063 socklen_t olen = sizeof(oob_inlined);
5065 fds[j].events = POLLHUP;
5067 /* Check if we need to test for urgent data or not */
5068 getsockopt(fds[j].fd, SOL_SOCKET, SO_OOBINLINE, (char*) &oob_inlined, &olen);
5069 if (!oob_inlined)
5070 fds[j].events |= POLLPRI;
5072 else
5074 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
5075 fds[j].fd = -1;
5076 fds[j].events = 0;
5079 return fds;
5081 failed:
5082 count = j;
5083 j = 0;
5084 if (readfds)
5085 for (i = 0; i < readfds->fd_count && j < count; i++, j++)
5086 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
5087 if (writefds)
5088 for (i = 0; i < writefds->fd_count && j < count; i++, j++)
5089 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
5090 if (exceptfds)
5091 for (i = 0; i < exceptfds->fd_count && j < count; i++, j++)
5092 if (fds[j].fd != -1) release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
5093 HeapFree( GetProcessHeap(), 0, fds );
5094 return NULL;
5097 /* release the file descriptor obtained in fd_sets_to_poll */
5098 /* must be called with the original fd_set arrays, before calling get_poll_results */
5099 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
5100 const WS_fd_set *exceptfds, struct pollfd *fds )
5102 unsigned int i, j = 0;
5104 if (readfds)
5106 for (i = 0; i < readfds->fd_count; i++, j++)
5107 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
5109 if (writefds)
5111 for (i = 0; i < writefds->fd_count; i++, j++)
5112 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
5114 if (exceptfds)
5116 for (i = 0; i < exceptfds->fd_count; i++, j++)
5118 if (fds[j].fd == -1) continue;
5119 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
5120 if (fds[j].revents & POLLHUP)
5122 int fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
5123 if (fd != -1)
5124 release_sock_fd( exceptfds->fd_array[i], fd );
5125 else
5126 fds[j].revents = 0;
5132 static int do_poll(struct pollfd *pollfds, int count, int timeout)
5134 struct timeval tv1, tv2;
5135 int ret, torig = timeout;
5137 if (timeout > 0) gettimeofday( &tv1, 0 );
5139 while ((ret = poll( pollfds, count, timeout )) < 0)
5141 if (errno != EINTR) break;
5142 if (timeout < 0) continue;
5143 if (timeout == 0) return 0;
5145 gettimeofday( &tv2, 0 );
5147 tv2.tv_sec -= tv1.tv_sec;
5148 tv2.tv_usec -= tv1.tv_usec;
5149 if (tv2.tv_usec < 0)
5151 tv2.tv_usec += 1000000;
5152 tv2.tv_sec -= 1;
5155 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
5156 if (timeout <= 0) return 0;
5158 return ret;
5161 /* map the poll results back into the Windows fd sets */
5162 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
5163 const struct pollfd *fds )
5165 const struct pollfd *poll_writefds = fds + (readfds ? readfds->fd_count : 0);
5166 const struct pollfd *poll_exceptfds = poll_writefds + (writefds ? writefds->fd_count : 0);
5167 unsigned int i, k, total = 0;
5169 if (readfds)
5171 for (i = k = 0; i < readfds->fd_count; i++)
5173 if (fds[i].revents ||
5174 (readfds == writefds && (poll_writefds[i].revents & POLLOUT) && !(poll_writefds[i].revents & POLLHUP)) ||
5175 (readfds == exceptfds && poll_exceptfds[i].revents))
5176 readfds->fd_array[k++] = readfds->fd_array[i];
5178 readfds->fd_count = k;
5179 total += k;
5181 if (writefds && writefds != readfds)
5183 for (i = k = 0; i < writefds->fd_count; i++)
5185 if (((poll_writefds[i].revents & POLLOUT) && !(poll_writefds[i].revents & POLLHUP)) ||
5186 (writefds == exceptfds && poll_exceptfds[i].revents))
5187 writefds->fd_array[k++] = writefds->fd_array[i];
5189 writefds->fd_count = k;
5190 total += k;
5192 if (exceptfds && exceptfds != readfds && exceptfds != writefds)
5194 for (i = k = 0; i < exceptfds->fd_count; i++)
5195 if (poll_exceptfds[i].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
5196 exceptfds->fd_count = k;
5197 total += k;
5199 return total;
5202 /***********************************************************************
5203 * select (WS2_32.18)
5205 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
5206 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
5207 const struct WS_timeval* ws_timeout)
5209 struct pollfd *pollfds;
5210 int count, ret, timeout = -1;
5212 TRACE("read %p, write %p, excp %p timeout %p\n",
5213 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
5215 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )))
5216 return SOCKET_ERROR;
5218 if (ws_timeout)
5219 timeout = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
5221 ret = do_poll(pollfds, count, timeout);
5222 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
5224 if (ret == -1) SetLastError(wsaErrno());
5225 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
5226 HeapFree( GetProcessHeap(), 0, pollfds );
5227 return ret;
5230 /* helper to send completion messages for client-only i/o operation case */
5231 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
5232 ULONG Information )
5234 SERVER_START_REQ( add_fd_completion )
5236 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
5237 req->cvalue = CompletionValue;
5238 req->status = CompletionStatus;
5239 req->information = Information;
5240 wine_server_call( req );
5242 SERVER_END_REQ;
5246 /***********************************************************************
5247 * send (WS2_32.19)
5249 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
5251 DWORD n;
5252 WSABUF wsabuf;
5254 wsabuf.len = len;
5255 wsabuf.buf = (char*) buf;
5257 if ( WS2_sendto( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
5258 return SOCKET_ERROR;
5259 else
5260 return n;
5263 /***********************************************************************
5264 * WSASend (WS2_32.72)
5266 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5267 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
5268 LPWSAOVERLAPPED lpOverlapped,
5269 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5271 return WS2_sendto( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
5272 NULL, 0, lpOverlapped, lpCompletionRoutine );
5275 /***********************************************************************
5276 * WSASendDisconnect (WS2_32.73)
5278 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
5280 return WS_shutdown( s, SD_SEND );
5284 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5285 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
5286 const struct WS_sockaddr *to, int tolen,
5287 LPWSAOVERLAPPED lpOverlapped,
5288 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5290 unsigned int i, options;
5291 int n, fd, err, overlapped, flags;
5292 struct ws2_async *wsa = NULL, localwsa;
5293 int totalLength = 0;
5294 DWORD bytes_sent;
5295 BOOL is_blocking;
5297 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
5298 s, lpBuffers, dwBufferCount, dwFlags,
5299 to, tolen, lpOverlapped, lpCompletionRoutine);
5301 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
5302 TRACE( "fd=%d, options=%x\n", fd, options );
5304 if ( fd == -1 ) return SOCKET_ERROR;
5306 if (!lpOverlapped && !lpNumberOfBytesSent)
5308 err = WSAEFAULT;
5309 goto error;
5312 overlapped = (lpOverlapped || lpCompletionRoutine) &&
5313 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
5314 if (overlapped || dwBufferCount > 1)
5316 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[dwBufferCount]))))
5318 err = WSAEFAULT;
5319 goto error;
5322 else
5323 wsa = &localwsa;
5325 wsa->hSocket = SOCKET2HANDLE(s);
5326 wsa->addr = (struct WS_sockaddr *)to;
5327 wsa->addrlen.val = tolen;
5328 wsa->flags = dwFlags;
5329 wsa->lpFlags = &wsa->flags;
5330 wsa->control = NULL;
5331 wsa->n_iovecs = dwBufferCount;
5332 wsa->first_iovec = 0;
5333 for ( i = 0; i < dwBufferCount; i++ )
5335 wsa->iovec[i].iov_base = lpBuffers[i].buf;
5336 wsa->iovec[i].iov_len = lpBuffers[i].len;
5337 totalLength += lpBuffers[i].len;
5340 flags = convert_flags(dwFlags);
5341 n = WS2_send( fd, wsa, flags );
5342 if (n == -1 && errno != EAGAIN)
5344 err = wsaErrno();
5345 goto error;
5348 if (overlapped)
5350 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
5351 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
5353 wsa->user_overlapped = lpOverlapped;
5354 wsa->completion_func = lpCompletionRoutine;
5355 release_sock_fd( s, fd );
5357 if (n == -1 || n < totalLength)
5359 iosb->u.Status = STATUS_PENDING;
5360 iosb->Information = n == -1 ? 0 : n;
5362 SERVER_START_REQ( register_async )
5364 req->type = ASYNC_TYPE_WRITE;
5365 req->async.handle = wine_server_obj_handle( wsa->hSocket );
5366 req->async.callback = wine_server_client_ptr( WS2_async_send );
5367 req->async.iosb = wine_server_client_ptr( iosb );
5368 req->async.arg = wine_server_client_ptr( wsa );
5369 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
5370 req->async.cvalue = cvalue;
5371 err = wine_server_call( req );
5373 SERVER_END_REQ;
5375 /* Enable the event only after starting the async. The server will deliver it as soon as
5376 the async is done. */
5377 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
5379 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
5380 SetLastError(NtStatusToWSAError( err ));
5381 return SOCKET_ERROR;
5384 iosb->u.Status = STATUS_SUCCESS;
5385 iosb->Information = n;
5386 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = n;
5387 if (!wsa->completion_func)
5389 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
5390 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
5391 HeapFree( GetProcessHeap(), 0, wsa );
5393 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
5394 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
5395 SetLastError(ERROR_SUCCESS);
5396 return 0;
5399 if ((err = _is_blocking( s, &is_blocking )))
5401 err = NtStatusToWSAError( err );
5402 goto error;
5405 if ( is_blocking )
5407 /* On a blocking non-overlapped stream socket,
5408 * sending blocks until the entire buffer is sent. */
5409 DWORD timeout_start = GetTickCount();
5411 bytes_sent = n == -1 ? 0 : n;
5413 while (wsa->first_iovec < wsa->n_iovecs)
5415 struct pollfd pfd;
5416 int poll_timeout = -1;
5417 INT64 timeout = get_rcvsnd_timeo(fd, FALSE);
5419 if (timeout)
5421 timeout -= GetTickCount() - timeout_start;
5422 if (timeout < 0) poll_timeout = 0;
5423 else poll_timeout = timeout <= INT_MAX ? timeout : INT_MAX;
5426 pfd.fd = fd;
5427 pfd.events = POLLOUT;
5429 if (!poll_timeout || !poll( &pfd, 1, poll_timeout ))
5431 err = WSAETIMEDOUT;
5432 goto error; /* msdn says a timeout in send is fatal */
5435 n = WS2_send( fd, wsa, flags );
5436 if (n == -1 && errno != EAGAIN)
5438 err = wsaErrno();
5439 goto error;
5442 if (n >= 0)
5443 bytes_sent += n;
5446 else /* non-blocking */
5448 if (n < totalLength)
5449 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
5450 if (n == -1)
5452 err = WSAEWOULDBLOCK;
5453 goto error;
5455 bytes_sent = n;
5458 TRACE(" -> %i bytes\n", bytes_sent);
5460 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = bytes_sent;
5461 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
5462 release_sock_fd( s, fd );
5463 SetLastError(ERROR_SUCCESS);
5464 return 0;
5466 error:
5467 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
5468 release_sock_fd( s, fd );
5469 WARN(" -> ERROR %d\n", err);
5470 SetLastError(err);
5471 return SOCKET_ERROR;
5474 /***********************************************************************
5475 * WSASendTo (WS2_32.74)
5477 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5478 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
5479 const struct WS_sockaddr *to, int tolen,
5480 LPWSAOVERLAPPED lpOverlapped,
5481 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5483 return WS2_sendto( s, lpBuffers, dwBufferCount,
5484 lpNumberOfBytesSent, dwFlags,
5485 to, tolen,
5486 lpOverlapped, lpCompletionRoutine );
5489 /***********************************************************************
5490 * sendto (WS2_32.20)
5492 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
5493 const struct WS_sockaddr *to, int tolen)
5495 DWORD n;
5496 WSABUF wsabuf;
5498 wsabuf.len = len;
5499 wsabuf.buf = (char*) buf;
5501 if ( WS2_sendto(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
5502 return SOCKET_ERROR;
5503 else
5504 return n;
5507 /***********************************************************************
5508 * setsockopt (WS2_32.21)
5510 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
5511 const char *optval, int optlen)
5513 int fd;
5514 int woptval;
5515 struct linger linger;
5516 struct timeval tval;
5518 TRACE("(socket %04lx, %s, optval %s, optlen %d)\n", s,
5519 debugstr_sockopt(level, optname), debugstr_optval(optval, optlen),
5520 optlen);
5522 /* some broken apps pass the value directly instead of a pointer to it */
5523 if(optlen && IS_INTRESOURCE(optval))
5525 SetLastError(WSAEFAULT);
5526 return SOCKET_ERROR;
5529 switch(level)
5531 case WS_SOL_SOCKET:
5532 switch(optname)
5534 /* Some options need some conversion before they can be sent to
5535 * setsockopt. The conversions are done here, then they will fall through
5536 * to the general case. Special options that are not passed to
5537 * setsockopt follow below that.*/
5539 case WS_SO_DONTLINGER:
5540 if (!optval)
5542 SetLastError(WSAEFAULT);
5543 return SOCKET_ERROR;
5545 linger.l_onoff = *(const int*)optval == 0;
5546 linger.l_linger = 0;
5547 level = SOL_SOCKET;
5548 optname = SO_LINGER;
5549 optval = (char*)&linger;
5550 optlen = sizeof(struct linger);
5551 break;
5553 case WS_SO_LINGER:
5554 if (!optval)
5556 SetLastError(WSAEFAULT);
5557 return SOCKET_ERROR;
5559 linger.l_onoff = ((LINGER*)optval)->l_onoff;
5560 linger.l_linger = ((LINGER*)optval)->l_linger;
5561 level = SOL_SOCKET;
5562 optname = SO_LINGER;
5563 optval = (char*)&linger;
5564 optlen = sizeof(struct linger);
5565 break;
5567 case WS_SO_RCVBUF:
5568 if (*(const int*)optval < 2048)
5570 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
5571 return 0;
5573 /* Fall through */
5575 /* The options listed here don't need any special handling. Thanks to
5576 * the conversion happening above, options from there will fall through
5577 * to this, too.*/
5578 case WS_SO_ACCEPTCONN:
5579 case WS_SO_BROADCAST:
5580 case WS_SO_ERROR:
5581 case WS_SO_KEEPALIVE:
5582 case WS_SO_OOBINLINE:
5583 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
5584 * however, using it the BSD way fixes bug 8513 and seems to be what
5585 * most programmers assume, anyway */
5586 case WS_SO_REUSEADDR:
5587 case WS_SO_SNDBUF:
5588 case WS_SO_TYPE:
5589 convert_sockopt(&level, &optname);
5590 break;
5592 /* SO_DEBUG is a privileged operation, ignore it. */
5593 case WS_SO_DEBUG:
5594 TRACE("Ignoring SO_DEBUG\n");
5595 return 0;
5597 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
5598 * socket. According to MSDN, this option is silently ignored.*/
5599 case WS_SO_DONTROUTE:
5600 TRACE("Ignoring SO_DONTROUTE\n");
5601 return 0;
5603 /* Stops two sockets from being bound to the same port. Always happens
5604 * on unix systems, so just drop it. */
5605 case WS_SO_EXCLUSIVEADDRUSE:
5606 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
5607 return 0;
5609 /* After a ConnectEx call succeeds, the socket can't be used with half of the
5610 * normal winsock functions on windows. We don't have that problem. */
5611 case WS_SO_UPDATE_CONNECT_CONTEXT:
5612 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
5613 return 0;
5615 /* After a AcceptEx call succeeds, the socket can't be used with half of the
5616 * normal winsock functions on windows. We don't have that problem. */
5617 case WS_SO_UPDATE_ACCEPT_CONTEXT:
5618 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
5619 return 0;
5621 /* SO_OPENTYPE does not require a valid socket handle. */
5622 case WS_SO_OPENTYPE:
5623 if (!optlen || optlen < sizeof(int) || !optval)
5625 SetLastError(WSAEFAULT);
5626 return SOCKET_ERROR;
5628 get_per_thread_data()->opentype = *(const int *)optval;
5629 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
5630 return 0;
5632 #ifdef SO_RCVTIMEO
5633 case WS_SO_RCVTIMEO:
5634 #endif
5635 #ifdef SO_SNDTIMEO
5636 case WS_SO_SNDTIMEO:
5637 #endif
5638 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
5639 if (optval && optlen == sizeof(UINT32)) {
5640 /* WinSock passes milliseconds instead of struct timeval */
5641 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
5642 tval.tv_sec = *(const UINT32*)optval / 1000;
5643 /* min of 500 milliseconds */
5644 if (tval.tv_sec == 0 && tval.tv_usec && tval.tv_usec < 500000)
5645 tval.tv_usec = 500000;
5646 optlen = sizeof(struct timeval);
5647 optval = (char*)&tval;
5648 } else if (optlen == sizeof(struct timeval)) {
5649 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
5650 } else {
5651 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
5652 return 0;
5654 convert_sockopt(&level, &optname);
5655 break;
5656 #endif
5658 default:
5659 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
5660 SetLastError(WSAENOPROTOOPT);
5661 return SOCKET_ERROR;
5663 break; /* case WS_SOL_SOCKET */
5665 #ifdef HAS_IPX
5666 case WS_NSPROTO_IPX:
5667 switch(optname)
5669 case WS_IPX_PTYPE:
5670 return set_ipx_packettype(s, *(int*)optval);
5672 case WS_IPX_FILTERPTYPE:
5673 /* Sets the receive filter packet type, at the moment we don't support it */
5674 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
5675 /* Returning 0 is better for now than returning a SOCKET_ERROR */
5676 return 0;
5678 default:
5679 FIXME("opt_name:%x\n", optname);
5680 return SOCKET_ERROR;
5682 break; /* case WS_NSPROTO_IPX */
5683 #endif
5685 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
5686 case WS_IPPROTO_TCP:
5687 switch(optname)
5689 case WS_TCP_NODELAY:
5690 convert_sockopt(&level, &optname);
5691 break;
5692 default:
5693 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
5694 return SOCKET_ERROR;
5696 break;
5698 case WS_IPPROTO_IP:
5699 switch(optname)
5701 case WS_IP_ADD_MEMBERSHIP:
5702 case WS_IP_DROP_MEMBERSHIP:
5703 #ifdef IP_HDRINCL
5704 case WS_IP_HDRINCL:
5705 #endif
5706 case WS_IP_MULTICAST_IF:
5707 case WS_IP_MULTICAST_LOOP:
5708 case WS_IP_MULTICAST_TTL:
5709 case WS_IP_OPTIONS:
5710 #ifdef IP_PKTINFO
5711 case WS_IP_PKTINFO:
5712 #endif
5713 case WS_IP_TOS:
5714 case WS_IP_TTL:
5715 #ifdef IP_UNICAST_IF
5716 case WS_IP_UNICAST_IF:
5717 #endif
5718 convert_sockopt(&level, &optname);
5719 break;
5720 case WS_IP_DONTFRAGMENT:
5721 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
5722 return 0;
5723 default:
5724 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
5725 return SOCKET_ERROR;
5727 break;
5729 case WS_IPPROTO_IPV6:
5730 switch(optname)
5732 #ifdef IPV6_ADD_MEMBERSHIP
5733 case WS_IPV6_ADD_MEMBERSHIP:
5734 #endif
5735 #ifdef IPV6_DROP_MEMBERSHIP
5736 case WS_IPV6_DROP_MEMBERSHIP:
5737 #endif
5738 case WS_IPV6_MULTICAST_IF:
5739 case WS_IPV6_MULTICAST_HOPS:
5740 case WS_IPV6_MULTICAST_LOOP:
5741 case WS_IPV6_UNICAST_HOPS:
5742 case WS_IPV6_V6ONLY:
5743 #ifdef IPV6_UNICAST_IF
5744 case WS_IPV6_UNICAST_IF:
5745 #endif
5746 convert_sockopt(&level, &optname);
5747 break;
5748 case WS_IPV6_DONTFRAG:
5749 FIXME("IPV6_DONTFRAG is silently ignored!\n");
5750 return 0;
5751 case WS_IPV6_PROTECTION_LEVEL:
5752 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
5753 return 0;
5754 default:
5755 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
5756 return SOCKET_ERROR;
5758 break;
5760 default:
5761 WARN("Unknown level: 0x%08x\n", level);
5762 SetLastError(WSAEINVAL);
5763 return SOCKET_ERROR;
5764 } /* end switch(level) */
5766 /* avoid endianness issues if argument is a 16-bit int */
5767 if (optval && optlen < sizeof(int))
5769 woptval= *((const INT16 *) optval);
5770 optval= (char*) &woptval;
5771 woptval&= (1 << optlen * 8) - 1;
5772 optlen=sizeof(int);
5774 fd = get_sock_fd( s, 0, NULL );
5775 if (fd == -1) return SOCKET_ERROR;
5777 if (setsockopt(fd, level, optname, optval, optlen) == 0)
5779 #ifdef __APPLE__
5780 if (level == SOL_SOCKET && optname == SO_REUSEADDR &&
5781 setsockopt(fd, level, SO_REUSEPORT, optval, optlen) != 0)
5783 SetLastError(wsaErrno());
5784 release_sock_fd( s, fd );
5785 return SOCKET_ERROR;
5787 #endif
5788 release_sock_fd( s, fd );
5789 return 0;
5791 TRACE("Setting socket error, %d\n", wsaErrno());
5792 SetLastError(wsaErrno());
5793 release_sock_fd( s, fd );
5795 return SOCKET_ERROR;
5798 /***********************************************************************
5799 * shutdown (WS2_32.22)
5801 int WINAPI WS_shutdown(SOCKET s, int how)
5803 int fd, err = WSAENOTSOCK;
5804 unsigned int options = 0, clear_flags = 0;
5806 fd = get_sock_fd( s, 0, &options );
5807 TRACE("socket %04lx, how 0x%x, options 0x%x\n", s, how, options );
5809 if (fd == -1)
5810 return SOCKET_ERROR;
5812 switch( how )
5814 case SD_RECEIVE: /* drop receives */
5815 clear_flags |= FD_READ;
5816 break;
5817 case SD_SEND: /* drop sends */
5818 clear_flags |= FD_WRITE;
5819 break;
5820 case SD_BOTH: /* drop all */
5821 clear_flags |= FD_READ|FD_WRITE;
5822 /*fall through */
5823 default:
5824 clear_flags |= FD_WINE_LISTENING;
5827 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
5829 switch ( how )
5831 case SD_RECEIVE:
5832 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
5833 break;
5834 case SD_SEND:
5835 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
5836 break;
5837 case SD_BOTH:
5838 default:
5839 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
5840 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
5841 break;
5843 if (err) goto error;
5845 else /* non-overlapped mode */
5847 if ( shutdown( fd, how ) )
5849 err = wsaErrno();
5850 goto error;
5854 release_sock_fd( s, fd );
5855 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
5856 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
5857 return 0;
5859 error:
5860 release_sock_fd( s, fd );
5861 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
5862 SetLastError( err );
5863 return SOCKET_ERROR;
5866 /***********************************************************************
5867 * socket (WS2_32.23)
5869 SOCKET WINAPI WS_socket(int af, int type, int protocol)
5871 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
5873 return WSASocketW( af, type, protocol, NULL, 0,
5874 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
5878 /***********************************************************************
5879 * gethostbyaddr (WS2_32.51)
5881 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
5883 struct WS_hostent *retval = NULL;
5884 struct hostent* host;
5885 int unixtype = convert_af_w2u(type);
5886 const char *paddr = addr;
5887 unsigned long loopback;
5888 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5889 char *extrabuf;
5890 int ebufsize = 1024;
5891 struct hostent hostentry;
5892 int locerr = ENOBUFS;
5893 #endif
5895 /* convert back the magic loopback address if necessary */
5896 if (unixtype == AF_INET && len == 4 && !memcmp(addr, magic_loopback_addr, 4))
5898 loopback = htonl(INADDR_LOOPBACK);
5899 paddr = (char*) &loopback;
5902 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5903 host = NULL;
5904 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
5905 while(extrabuf) {
5906 int res = gethostbyaddr_r(paddr, len, unixtype,
5907 &hostentry, extrabuf, ebufsize, &host, &locerr);
5908 if (res != ERANGE) break;
5909 ebufsize *=2;
5910 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
5912 if (host) retval = WS_dup_he(host);
5913 else SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
5914 HeapFree(GetProcessHeap(),0,extrabuf);
5915 #else
5916 EnterCriticalSection( &csWSgetXXXbyYYY );
5917 host = gethostbyaddr(paddr, len, unixtype);
5918 if (host) retval = WS_dup_he(host);
5919 else SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
5920 LeaveCriticalSection( &csWSgetXXXbyYYY );
5921 #endif
5922 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
5923 return retval;
5926 /***********************************************************************
5927 * WS_compare_routes_by_metric_asc (INTERNAL)
5929 * Comparison function for qsort(), for sorting two routes (struct route)
5930 * by metric in ascending order.
5932 static int WS_compare_routes_by_metric_asc(const void *left, const void *right)
5934 return ((const struct route*)left)->metric - ((const struct route*)right)->metric;
5937 /***********************************************************************
5938 * WS_get_local_ips (INTERNAL)
5940 * Returns the list of local IP addresses by going through the network
5941 * adapters and using the local routing table to sort the addresses
5942 * from highest routing priority to lowest routing priority. This
5943 * functionality is inferred from the description for obtaining local
5944 * IP addresses given in the Knowledge Base Article Q160215.
5946 * Please note that the returned hostent is only freed when the thread
5947 * closes and is replaced if another hostent is requested.
5949 static struct WS_hostent* WS_get_local_ips( char *hostname )
5951 int numroutes = 0, i, j;
5952 DWORD n;
5953 PIP_ADAPTER_INFO adapters = NULL, k;
5954 struct WS_hostent *hostlist = NULL;
5955 PMIB_IPFORWARDTABLE routes = NULL;
5956 struct route *route_addrs = NULL;
5957 DWORD adap_size, route_size;
5959 /* Obtain the size of the adapter list and routing table, also allocate memory */
5960 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
5961 return NULL;
5962 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
5963 return NULL;
5964 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
5965 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
5966 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
5967 if (adapters == NULL || routes == NULL || route_addrs == NULL)
5968 goto cleanup;
5969 /* Obtain the adapter list and the full routing table */
5970 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
5971 goto cleanup;
5972 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
5973 goto cleanup;
5974 /* Store the interface associated with each route */
5975 for (n = 0; n < routes->dwNumEntries; n++)
5977 IF_INDEX ifindex;
5978 DWORD ifmetric;
5979 BOOL exists = FALSE;
5981 if (routes->table[n].u1.ForwardType != MIB_IPROUTE_TYPE_DIRECT)
5982 continue;
5983 ifindex = routes->table[n].dwForwardIfIndex;
5984 ifmetric = routes->table[n].dwForwardMetric1;
5985 /* Only store the lowest valued metric for an interface */
5986 for (j = 0; j < numroutes; j++)
5988 if (route_addrs[j].interface == ifindex)
5990 if (route_addrs[j].metric > ifmetric)
5991 route_addrs[j].metric = ifmetric;
5992 exists = TRUE;
5995 if (exists)
5996 continue;
5997 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
5998 if (route_addrs == NULL)
5999 goto cleanup; /* Memory allocation error, fail gracefully */
6000 route_addrs[numroutes].interface = ifindex;
6001 route_addrs[numroutes].metric = ifmetric;
6002 /* If no IP is found in the next step (for whatever reason)
6003 * then fall back to the magic loopback address.
6005 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
6006 numroutes++;
6008 if (numroutes == 0)
6009 goto cleanup; /* No routes, fall back to the Magic IP */
6010 /* Find the IP address associated with each found interface */
6011 for (i = 0; i < numroutes; i++)
6013 for (k = adapters; k != NULL; k = k->Next)
6015 char *ip = k->IpAddressList.IpAddress.String;
6017 if (route_addrs[i].interface == k->Index)
6018 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
6021 /* Allocate a hostent and enough memory for all the IPs,
6022 * including the NULL at the end of the list.
6024 hostlist = WS_create_he(hostname, 1, 0, numroutes+1, sizeof(struct in_addr));
6025 if (hostlist == NULL)
6026 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
6027 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
6028 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
6029 hostlist->h_addrtype = AF_INET;
6030 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
6031 /* Reorder the entries before placing them in the host list. Windows expects
6032 * the IP list in order from highest priority to lowest (the critical thing
6033 * is that most applications expect the first IP to be the default route).
6035 if (numroutes > 1)
6036 qsort(route_addrs, numroutes, sizeof(struct route), WS_compare_routes_by_metric_asc);
6038 for (i = 0; i < numroutes; i++)
6039 (*(struct in_addr *) hostlist->h_addr_list[i]) = route_addrs[i].addr;
6041 /* Cleanup all allocated memory except the address list,
6042 * the address list is used by the calling app.
6044 cleanup:
6045 HeapFree(GetProcessHeap(), 0, route_addrs);
6046 HeapFree(GetProcessHeap(), 0, adapters);
6047 HeapFree(GetProcessHeap(), 0, routes);
6048 return hostlist;
6051 /***********************************************************************
6052 * gethostbyname (WS2_32.52)
6054 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
6056 struct WS_hostent *retval = NULL;
6057 struct hostent* host;
6058 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6059 char *extrabuf;
6060 int ebufsize=1024;
6061 struct hostent hostentry;
6062 int locerr = ENOBUFS;
6063 #endif
6064 char hostname[100];
6065 if(!num_startup) {
6066 SetLastError(WSANOTINITIALISED);
6067 return NULL;
6069 if( gethostname( hostname, 100) == -1) {
6070 SetLastError(WSAENOBUFS); /* appropriate ? */
6071 return retval;
6073 if( !name || !name[0]) {
6074 name = hostname;
6076 /* If the hostname of the local machine is requested then return the
6077 * complete list of local IP addresses */
6078 if(strcmp(name, hostname) == 0)
6079 retval = WS_get_local_ips(hostname);
6080 /* If any other hostname was requested (or the routing table lookup failed)
6081 * then return the IP found by the host OS */
6082 if(retval == NULL)
6084 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6085 host = NULL;
6086 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
6087 while(extrabuf) {
6088 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
6089 if( res != ERANGE) break;
6090 ebufsize *=2;
6091 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
6093 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
6094 #else
6095 EnterCriticalSection( &csWSgetXXXbyYYY );
6096 host = gethostbyname(name);
6097 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
6098 #endif
6099 if (host) retval = WS_dup_he(host);
6100 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6101 HeapFree(GetProcessHeap(),0,extrabuf);
6102 #else
6103 LeaveCriticalSection( &csWSgetXXXbyYYY );
6104 #endif
6106 if (retval && retval->h_addr_list[0][0] == 127 &&
6107 strcmp(name, "localhost") != 0)
6109 /* hostname != "localhost" but has loopback address. replace by our
6110 * special address.*/
6111 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
6113 TRACE( "%s ret %p\n", debugstr_a(name), retval );
6114 return retval;
6118 /***********************************************************************
6119 * getprotobyname (WS2_32.53)
6121 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
6123 struct WS_protoent* retval = NULL;
6124 #ifdef HAVE_GETPROTOBYNAME
6125 struct protoent* proto;
6126 EnterCriticalSection( &csWSgetXXXbyYYY );
6127 if( (proto = getprotobyname(name)) != NULL )
6129 retval = WS_dup_pe(proto);
6131 else {
6132 MESSAGE("protocol %s not found; You might want to add "
6133 "this to /etc/protocols\n", debugstr_a(name) );
6134 SetLastError(WSANO_DATA);
6136 LeaveCriticalSection( &csWSgetXXXbyYYY );
6137 #endif
6138 TRACE( "%s ret %p\n", debugstr_a(name), retval );
6139 return retval;
6143 /***********************************************************************
6144 * getprotobynumber (WS2_32.54)
6146 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
6148 struct WS_protoent* retval = NULL;
6149 #ifdef HAVE_GETPROTOBYNUMBER
6150 struct protoent* proto;
6151 EnterCriticalSection( &csWSgetXXXbyYYY );
6152 if( (proto = getprotobynumber(number)) != NULL )
6154 retval = WS_dup_pe(proto);
6156 else {
6157 MESSAGE("protocol number %d not found; You might want to add "
6158 "this to /etc/protocols\n", number );
6159 SetLastError(WSANO_DATA);
6161 LeaveCriticalSection( &csWSgetXXXbyYYY );
6162 #endif
6163 TRACE("%i ret %p\n", number, retval);
6164 return retval;
6168 /***********************************************************************
6169 * getservbyname (WS2_32.55)
6171 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
6173 struct WS_servent* retval = NULL;
6174 struct servent* serv;
6175 char *name_str;
6176 char *proto_str = NULL;
6178 if (!(name_str = strdup_lower(name))) return NULL;
6180 if (proto && *proto)
6182 if (!(proto_str = strdup_lower(proto)))
6184 HeapFree( GetProcessHeap(), 0, name_str );
6185 return NULL;
6189 EnterCriticalSection( &csWSgetXXXbyYYY );
6190 serv = getservbyname(name_str, proto_str);
6191 if( serv != NULL )
6193 retval = WS_dup_se(serv);
6195 else SetLastError(WSANO_DATA);
6196 LeaveCriticalSection( &csWSgetXXXbyYYY );
6197 HeapFree( GetProcessHeap(), 0, proto_str );
6198 HeapFree( GetProcessHeap(), 0, name_str );
6199 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
6200 return retval;
6203 /***********************************************************************
6204 * freeaddrinfo (WS2_32.@)
6206 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
6208 while (res) {
6209 struct WS_addrinfo *next;
6211 HeapFree(GetProcessHeap(),0,res->ai_canonname);
6212 HeapFree(GetProcessHeap(),0,res->ai_addr);
6213 next = res->ai_next;
6214 HeapFree(GetProcessHeap(),0,res);
6215 res = next;
6219 /* helper functions for getaddrinfo()/getnameinfo() */
6220 static int convert_aiflag_w2u(int winflags) {
6221 unsigned int i;
6222 int unixflags = 0;
6224 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
6225 if (ws_aiflag_map[i][0] & winflags) {
6226 unixflags |= ws_aiflag_map[i][1];
6227 winflags &= ~ws_aiflag_map[i][0];
6229 if (winflags)
6230 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
6231 return unixflags;
6234 static int convert_niflag_w2u(int winflags) {
6235 unsigned int i;
6236 int unixflags = 0;
6238 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
6239 if (ws_niflag_map[i][0] & winflags) {
6240 unixflags |= ws_niflag_map[i][1];
6241 winflags &= ~ws_niflag_map[i][0];
6243 if (winflags)
6244 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
6245 return unixflags;
6248 static int convert_aiflag_u2w(int unixflags) {
6249 unsigned int i;
6250 int winflags = 0;
6252 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
6253 if (ws_aiflag_map[i][1] & unixflags) {
6254 winflags |= ws_aiflag_map[i][0];
6255 unixflags &= ~ws_aiflag_map[i][1];
6257 if (unixflags) /* will warn usually */
6258 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
6259 return winflags;
6262 static int convert_eai_u2w(int unixret) {
6263 int i;
6265 if (!unixret) return 0;
6267 for (i=0;ws_eai_map[i][0];i++)
6268 if (ws_eai_map[i][1] == unixret)
6269 return ws_eai_map[i][0];
6271 if (unixret == EAI_SYSTEM)
6272 /* There are broken versions of glibc which return EAI_SYSTEM
6273 * and set errno to 0 instead of returning EAI_NONAME.
6275 return errno ? sock_get_error( errno ) : WS_EAI_NONAME;
6277 FIXME("Unhandled unix EAI_xxx ret %d\n", unixret);
6278 return unixret;
6281 static char *get_hostname(void)
6283 char *ret;
6284 DWORD size = 0;
6286 GetComputerNameExA( ComputerNamePhysicalDnsHostname, NULL, &size );
6287 if (GetLastError() != ERROR_MORE_DATA) return NULL;
6288 if (!(ret = HeapAlloc( GetProcessHeap(), 0, size ))) return NULL;
6289 if (!GetComputerNameExA( ComputerNamePhysicalDnsHostname, ret, &size ))
6291 HeapFree( GetProcessHeap(), 0, ret );
6292 return NULL;
6294 return ret;
6297 /***********************************************************************
6298 * getaddrinfo (WS2_32.@)
6300 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
6302 #ifdef HAVE_GETADDRINFO
6303 struct addrinfo *unixaires = NULL;
6304 int result;
6305 struct addrinfo unixhints, *punixhints = NULL;
6306 char *hostname;
6307 const char *node;
6309 *res = NULL;
6310 if (!nodename && !servname)
6312 SetLastError(WSAHOST_NOT_FOUND);
6313 return WSAHOST_NOT_FOUND;
6316 hostname = get_hostname();
6317 if (!hostname) return WSA_NOT_ENOUGH_MEMORY;
6319 if (!nodename)
6320 node = NULL;
6321 else if (!nodename[0])
6322 node = hostname;
6323 else
6324 node = nodename;
6326 /* servname tweak required by OSX and BSD kernels */
6327 if (servname && !servname[0]) servname = "0";
6329 if (hints) {
6330 punixhints = &unixhints;
6332 memset(&unixhints, 0, sizeof(unixhints));
6333 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
6335 /* zero is a wildcard, no need to convert */
6336 if (hints->ai_family)
6337 punixhints->ai_family = convert_af_w2u(hints->ai_family);
6338 if (hints->ai_socktype)
6339 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
6340 if (hints->ai_protocol)
6341 punixhints->ai_protocol = max(convert_proto_w2u(hints->ai_protocol), 0);
6343 if (punixhints->ai_socktype < 0)
6345 SetLastError(WSAESOCKTNOSUPPORT);
6346 HeapFree(GetProcessHeap(), 0, hostname);
6347 return SOCKET_ERROR;
6350 /* windows allows invalid combinations of socket type and protocol, unix does not.
6351 * fix the parameters here to make getaddrinfo call always work */
6352 if (punixhints->ai_protocol == IPPROTO_TCP &&
6353 punixhints->ai_socktype != SOCK_STREAM && punixhints->ai_socktype != SOCK_SEQPACKET)
6354 punixhints->ai_socktype = 0;
6356 else if (punixhints->ai_protocol == IPPROTO_UDP && punixhints->ai_socktype != SOCK_DGRAM)
6357 punixhints->ai_socktype = 0;
6359 else if (IS_IPX_PROTO(punixhints->ai_protocol) && punixhints->ai_socktype != SOCK_DGRAM)
6360 punixhints->ai_socktype = 0;
6363 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
6364 result = getaddrinfo(node, servname, punixhints, &unixaires);
6366 if (result && !strcmp(hostname, node))
6368 /* If it didn't work it means the host name IP is not in /etc/hosts, try again
6369 * by sending a NULL host and avoid sending a NULL servname too because that
6370 * is invalid */
6371 ERR_(winediag)("Failed to resolve your host name IP\n");
6372 result = getaddrinfo(NULL, servname ? servname : "0", punixhints, &unixaires);
6374 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
6375 HeapFree(GetProcessHeap(), 0, hostname);
6377 if (!result) {
6378 struct addrinfo *xuai = unixaires;
6379 struct WS_addrinfo **xai = res;
6381 *xai = NULL;
6382 while (xuai) {
6383 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
6384 SIZE_T len;
6386 if (!ai)
6387 goto outofmem;
6389 *xai = ai;xai = &ai->ai_next;
6390 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
6391 ai->ai_family = convert_af_u2w(xuai->ai_family);
6392 /* copy whatever was sent in the hints */
6393 if(hints) {
6394 ai->ai_socktype = hints->ai_socktype;
6395 ai->ai_protocol = hints->ai_protocol;
6396 } else {
6397 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
6398 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
6400 if (xuai->ai_canonname) {
6401 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
6402 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
6403 if (!ai->ai_canonname)
6404 goto outofmem;
6405 strcpy(ai->ai_canonname,xuai->ai_canonname);
6407 len = xuai->ai_addrlen;
6408 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
6409 if (!ai->ai_addr)
6410 goto outofmem;
6411 ai->ai_addrlen = len;
6412 do {
6413 int winlen = ai->ai_addrlen;
6415 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
6416 ai->ai_addrlen = winlen;
6417 break;
6419 len = 2*len;
6420 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
6421 if (!ai->ai_addr)
6422 goto outofmem;
6423 ai->ai_addrlen = len;
6424 } while (1);
6425 xuai = xuai->ai_next;
6427 freeaddrinfo(unixaires);
6429 if (TRACE_ON(winsock))
6431 struct WS_addrinfo *ai = *res;
6432 while (ai)
6434 TRACE("=> %p, flags %#x, family %d, type %d, protocol %d, len %ld, name %s, addr %s\n",
6435 ai, ai->ai_flags, ai->ai_family, ai->ai_socktype, ai->ai_protocol, ai->ai_addrlen,
6436 ai->ai_canonname, debugstr_sockaddr(ai->ai_addr));
6437 ai = ai->ai_next;
6440 } else
6441 result = convert_eai_u2w(result);
6443 SetLastError(result);
6444 return result;
6446 outofmem:
6447 if (*res) WS_freeaddrinfo(*res);
6448 if (unixaires) freeaddrinfo(unixaires);
6449 return WSA_NOT_ENOUGH_MEMORY;
6450 #else
6451 FIXME("getaddrinfo() failed, not found during buildtime.\n");
6452 return EAI_FAIL;
6453 #endif
6456 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
6458 struct WS_addrinfoW *ret;
6460 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
6461 ret->ai_flags = ai->ai_flags;
6462 ret->ai_family = ai->ai_family;
6463 ret->ai_socktype = ai->ai_socktype;
6464 ret->ai_protocol = ai->ai_protocol;
6465 ret->ai_addrlen = ai->ai_addrlen;
6466 ret->ai_canonname = NULL;
6467 ret->ai_addr = NULL;
6468 ret->ai_next = NULL;
6469 if (ai->ai_canonname)
6471 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
6472 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR))))
6474 HeapFree(GetProcessHeap(), 0, ret);
6475 return NULL;
6477 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
6479 if (ai->ai_addr)
6481 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, ai->ai_addrlen)))
6483 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
6484 HeapFree(GetProcessHeap(), 0, ret);
6485 return NULL;
6487 memcpy(ret->ai_addr, ai->ai_addr, ai->ai_addrlen);
6489 return ret;
6492 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
6494 struct WS_addrinfoW *ret, *infoW;
6496 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
6497 while (info->ai_next)
6499 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
6501 FreeAddrInfoW(ret);
6502 return NULL;
6504 infoW = infoW->ai_next;
6505 info = info->ai_next;
6507 return ret;
6510 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
6512 struct WS_addrinfo *ret;
6514 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
6515 ret->ai_flags = ai->ai_flags;
6516 ret->ai_family = ai->ai_family;
6517 ret->ai_socktype = ai->ai_socktype;
6518 ret->ai_protocol = ai->ai_protocol;
6519 ret->ai_addrlen = ai->ai_addrlen;
6520 ret->ai_canonname = NULL;
6521 ret->ai_addr = NULL;
6522 ret->ai_next = NULL;
6523 if (ai->ai_canonname)
6525 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
6526 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
6528 HeapFree(GetProcessHeap(), 0, ret);
6529 return NULL;
6531 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
6533 if (ai->ai_addr)
6535 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
6537 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
6538 HeapFree(GetProcessHeap(), 0, ret);
6539 return NULL;
6541 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
6543 return ret;
6546 /***********************************************************************
6547 * GetAddrInfoExW (WS2_32.@)
6549 int WINAPI GetAddrInfoExW(const WCHAR *name, const WCHAR *servname, DWORD namespace, GUID *namespace_id,
6550 const ADDRINFOEXW *hints, ADDRINFOEXW **result, struct timeval *timeout, OVERLAPPED *overlapped,
6551 LPLOOKUPSERVICE_COMPLETION_ROUTINE completion_routine, HANDLE *handle)
6553 FIXME("(%s %s %x %s %p %p %p %p %p %p)\n", debugstr_w(name), debugstr_w(servname), namespace,
6554 debugstr_guid(namespace_id), hints, result, timeout, overlapped, completion_routine, handle);
6555 return WSAHOST_NOT_FOUND;
6558 /***********************************************************************
6559 * GetAddrInfoW (WS2_32.@)
6561 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
6563 int ret, len;
6564 char *nodenameA = NULL, *servnameA = NULL;
6565 struct WS_addrinfo *resA, *hintsA = NULL;
6567 *res = NULL;
6568 if (nodename)
6570 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
6571 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
6572 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
6574 if (servname)
6576 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
6577 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
6579 HeapFree(GetProcessHeap(), 0, nodenameA);
6580 return EAI_MEMORY;
6582 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
6585 if (hints) hintsA = addrinfo_WtoA(hints);
6586 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
6587 WS_freeaddrinfo(hintsA);
6589 if (!ret)
6591 *res = addrinfo_list_AtoW(resA);
6592 WS_freeaddrinfo(resA);
6595 HeapFree(GetProcessHeap(), 0, nodenameA);
6596 HeapFree(GetProcessHeap(), 0, servnameA);
6597 return ret;
6600 /***********************************************************************
6601 * FreeAddrInfoW (WS2_32.@)
6603 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
6605 while (ai)
6607 ADDRINFOW *next;
6608 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
6609 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
6610 next = ai->ai_next;
6611 HeapFree(GetProcessHeap(), 0, ai);
6612 ai = next;
6616 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
6617 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
6619 #ifdef HAVE_GETNAMEINFO
6620 int ret;
6621 union generic_unix_sockaddr sa_u;
6622 unsigned int size;
6624 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
6625 serv, servlen, flags);
6627 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
6628 if (!size)
6630 SetLastError(WSAEFAULT);
6631 return WSA_NOT_ENOUGH_MEMORY;
6633 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
6634 return convert_eai_u2w(ret);
6635 #else
6636 FIXME("getnameinfo() failed, not found during buildtime.\n");
6637 return EAI_FAIL;
6638 #endif
6641 int WINAPI GetNameInfoW(const SOCKADDR *sa, WS_socklen_t salen, PWCHAR host,
6642 DWORD hostlen, PWCHAR serv, DWORD servlen, INT flags)
6644 int ret;
6645 char *hostA = NULL, *servA = NULL;
6647 if (host && (!(hostA = HeapAlloc(GetProcessHeap(), 0, hostlen)))) return EAI_MEMORY;
6648 if (serv && (!(servA = HeapAlloc(GetProcessHeap(), 0, servlen))))
6650 HeapFree(GetProcessHeap(), 0, hostA);
6651 return EAI_MEMORY;
6654 ret = WS_getnameinfo(sa, salen, hostA, hostlen, servA, servlen, flags);
6655 if (!ret)
6657 if (host) MultiByteToWideChar(CP_ACP, 0, hostA, -1, host, hostlen);
6658 if (serv) MultiByteToWideChar(CP_ACP, 0, servA, -1, serv, servlen);
6661 HeapFree(GetProcessHeap(), 0, hostA);
6662 HeapFree(GetProcessHeap(), 0, servA);
6663 return ret;
6666 /***********************************************************************
6667 * getservbyport (WS2_32.56)
6669 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
6671 struct WS_servent* retval = NULL;
6672 #ifdef HAVE_GETSERVBYPORT
6673 struct servent* serv;
6674 char *proto_str = NULL;
6676 if (proto && *proto)
6678 if (!(proto_str = strdup_lower(proto))) return NULL;
6680 EnterCriticalSection( &csWSgetXXXbyYYY );
6681 if( (serv = getservbyport(port, proto_str)) != NULL ) {
6682 retval = WS_dup_se(serv);
6684 else SetLastError(WSANO_DATA);
6685 LeaveCriticalSection( &csWSgetXXXbyYYY );
6686 HeapFree( GetProcessHeap(), 0, proto_str );
6687 #endif
6688 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
6689 return retval;
6693 /***********************************************************************
6694 * gethostname (WS2_32.57)
6696 int WINAPI WS_gethostname(char *name, int namelen)
6698 char buf[256];
6699 int len;
6701 TRACE("name %p, len %d\n", name, namelen);
6703 if (!name)
6705 SetLastError(WSAEFAULT);
6706 return SOCKET_ERROR;
6709 if (gethostname(buf, sizeof(buf)) != 0)
6711 SetLastError(wsaErrno());
6712 return SOCKET_ERROR;
6715 TRACE("<- '%s'\n", buf);
6716 len = strlen(buf);
6717 if (len > 15)
6718 WARN("Windows supports NetBIOS name length up to 15 bytes!\n");
6719 if (namelen <= len)
6721 SetLastError(WSAEFAULT);
6722 WARN("<- not enough space for hostname, required %d, got %d!\n", len + 1, namelen);
6723 return SOCKET_ERROR;
6725 strcpy(name, buf);
6726 return 0;
6730 /* ------------------------------------- Windows sockets extensions -- *
6732 * ------------------------------------------------------------------- */
6734 /***********************************************************************
6735 * WSAEnumNetworkEvents (WS2_32.36)
6737 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
6739 int ret;
6740 int i;
6741 int errors[FD_MAX_EVENTS];
6743 TRACE("%04lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
6745 SERVER_START_REQ( get_socket_event )
6747 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6748 req->service = TRUE;
6749 req->c_event = wine_server_obj_handle( hEvent );
6750 wine_server_set_reply( req, errors, sizeof(errors) );
6751 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
6753 SERVER_END_REQ;
6754 if (!ret)
6756 for (i = 0; i < FD_MAX_EVENTS; i++)
6757 lpEvent->iErrorCode[i] = NtStatusToWSAError(errors[i]);
6758 return 0;
6760 SetLastError(WSAEINVAL);
6761 return SOCKET_ERROR;
6764 /***********************************************************************
6765 * WSAEventSelect (WS2_32.39)
6767 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
6769 int ret;
6771 TRACE("%04lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
6773 SERVER_START_REQ( set_socket_event )
6775 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6776 req->mask = lEvent;
6777 req->event = wine_server_obj_handle( hEvent );
6778 req->window = 0;
6779 req->msg = 0;
6780 ret = wine_server_call( req );
6782 SERVER_END_REQ;
6783 if (!ret) return 0;
6784 SetLastError(WSAEINVAL);
6785 return SOCKET_ERROR;
6788 /**********************************************************************
6789 * WSAGetOverlappedResult (WS2_32.40)
6791 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
6792 LPDWORD lpcbTransfer, BOOL fWait,
6793 LPDWORD lpdwFlags )
6795 NTSTATUS status;
6797 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
6798 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
6800 if ( lpOverlapped == NULL )
6802 ERR( "Invalid pointer\n" );
6803 SetLastError(WSA_INVALID_PARAMETER);
6804 return FALSE;
6807 status = lpOverlapped->Internal;
6808 if (status == STATUS_PENDING)
6810 if (!fWait)
6812 SetLastError( WSA_IO_INCOMPLETE );
6813 return FALSE;
6816 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
6817 INFINITE ) == WAIT_FAILED)
6818 return FALSE;
6819 status = lpOverlapped->Internal;
6822 if ( lpcbTransfer )
6823 *lpcbTransfer = lpOverlapped->InternalHigh;
6825 if ( lpdwFlags )
6826 *lpdwFlags = lpOverlapped->u.s.Offset;
6828 if (status) SetLastError( RtlNtStatusToDosError(status) );
6829 return !status;
6833 /***********************************************************************
6834 * WSAAsyncSelect (WS2_32.101)
6836 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
6838 int ret;
6840 TRACE("%04lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
6842 SERVER_START_REQ( set_socket_event )
6844 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6845 req->mask = lEvent;
6846 req->event = 0;
6847 req->window = wine_server_user_handle( hWnd );
6848 req->msg = uMsg;
6849 ret = wine_server_call( req );
6851 SERVER_END_REQ;
6852 if (!ret) return 0;
6853 SetLastError(WSAEINVAL);
6854 return SOCKET_ERROR;
6857 /***********************************************************************
6858 * WSACreateEvent (WS2_32.31)
6861 WSAEVENT WINAPI WSACreateEvent(void)
6863 /* Create a manual-reset event, with initial state: unsignaled */
6864 TRACE("\n");
6866 return CreateEventW(NULL, TRUE, FALSE, NULL);
6869 /***********************************************************************
6870 * WSACloseEvent (WS2_32.29)
6873 BOOL WINAPI WSACloseEvent(WSAEVENT event)
6875 TRACE ("event=%p\n", event);
6877 return CloseHandle(event);
6880 /***********************************************************************
6881 * WSASocketA (WS2_32.78)
6884 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
6885 LPWSAPROTOCOL_INFOA lpProtocolInfo,
6886 GROUP g, DWORD dwFlags)
6888 INT len;
6889 WSAPROTOCOL_INFOW info;
6891 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
6892 af, type, protocol, lpProtocolInfo, g, dwFlags);
6894 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
6896 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
6897 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
6898 info.szProtocol, WSAPROTOCOL_LEN + 1);
6900 if (!len)
6902 SetLastError(WSAEINVAL);
6903 return SOCKET_ERROR;
6906 return WSASocketW(af, type, protocol, &info, g, dwFlags);
6909 /***********************************************************************
6910 * WSASocketW (WS2_32.79)
6913 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
6914 LPWSAPROTOCOL_INFOW lpProtocolInfo,
6915 GROUP g, DWORD dwFlags)
6917 SOCKET ret;
6918 DWORD err;
6919 int unixaf, unixtype, ipxptype = -1;
6922 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
6923 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
6926 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
6927 af, type, protocol, lpProtocolInfo, g, dwFlags );
6929 if (!num_startup)
6931 err = WSANOTINITIALISED;
6932 goto done;
6935 /* hack for WSADuplicateSocket */
6936 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
6937 ret = lpProtocolInfo->dwServiceFlags3;
6938 TRACE("\tgot duplicate %04lx\n", ret);
6939 return ret;
6942 if (lpProtocolInfo)
6944 if (af == FROM_PROTOCOL_INFO || !af)
6945 af = lpProtocolInfo->iAddressFamily;
6946 if (type == FROM_PROTOCOL_INFO || !type)
6947 type = lpProtocolInfo->iSocketType;
6948 if (protocol == FROM_PROTOCOL_INFO || !protocol)
6949 protocol = lpProtocolInfo->iProtocol;
6952 if (!type && (af || protocol))
6954 int autoproto = protocol;
6955 WSAPROTOCOL_INFOW infow;
6957 /* default to the first valid protocol */
6958 if (!autoproto)
6959 autoproto = valid_protocols[0];
6960 else if(IS_IPX_PROTO(autoproto))
6961 autoproto = WS_NSPROTO_IPX;
6963 if (WS_EnterSingleProtocolW(autoproto, &infow))
6965 type = infow.iSocketType;
6967 /* after win2003 it's no longer possible to pass AF_UNSPEC
6968 using the protocol info struct */
6969 if (!lpProtocolInfo && af == WS_AF_UNSPEC)
6970 af = infow.iAddressFamily;
6975 Windows has an extension to the IPX protocol that allows one to create sockets
6976 and set the IPX packet type at the same time, to do that a caller will use
6977 a protocol like NSPROTO_IPX + <PACKET TYPE>
6979 if (IS_IPX_PROTO(protocol))
6980 ipxptype = protocol - WS_NSPROTO_IPX;
6982 /* convert the socket family, type and protocol */
6983 unixaf = convert_af_w2u(af);
6984 unixtype = convert_socktype_w2u(type);
6985 protocol = convert_proto_w2u(protocol);
6986 if (unixaf == AF_UNSPEC) unixaf = -1;
6988 /* filter invalid parameters */
6989 if (protocol < 0)
6991 /* the type could not be converted */
6992 if (type && unixtype < 0)
6994 err = WSAESOCKTNOSUPPORT;
6995 goto done;
6998 err = WSAEPROTONOSUPPORT;
6999 goto done;
7001 if (unixaf < 0)
7003 /* both family and protocol can't be invalid */
7004 if (protocol <= 0)
7006 err = WSAEINVAL;
7007 goto done;
7010 /* family could not be converted and neither socket type */
7011 if (unixtype < 0 && af >= 0)
7014 err = WSAESOCKTNOSUPPORT;
7015 goto done;
7018 err = WSAEAFNOSUPPORT;
7019 goto done;
7022 SERVER_START_REQ( create_socket )
7024 req->family = unixaf;
7025 req->type = unixtype;
7026 req->protocol = protocol;
7027 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
7028 req->attributes = (dwFlags & WSA_FLAG_NO_HANDLE_INHERIT) ? 0 : OBJ_INHERIT;
7029 req->flags = dwFlags & ~WSA_FLAG_NO_HANDLE_INHERIT;
7030 set_error( wine_server_call( req ) );
7031 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
7033 SERVER_END_REQ;
7034 if (ret)
7036 TRACE("\tcreated %04lx\n", ret );
7037 if (ipxptype > 0)
7038 set_ipx_packettype(ret, ipxptype);
7039 return ret;
7042 err = GetLastError();
7043 if (err == WSAEACCES) /* raw socket denied */
7045 if (type == SOCK_RAW)
7046 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
7047 else
7048 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
7050 else
7052 /* invalid combination of valid parameters, like SOCK_STREAM + IPPROTO_UDP */
7053 if (err == WSAEINVAL)
7054 err = WSAESOCKTNOSUPPORT;
7055 else if (err == WSAEOPNOTSUPP)
7056 err = WSAEPROTONOSUPPORT;
7059 done:
7060 WARN("\t\tfailed, error %d!\n", err);
7061 SetLastError(err);
7062 return INVALID_SOCKET;
7065 /***********************************************************************
7066 * WSAJoinLeaf (WS2_32.58)
7069 SOCKET WINAPI WSAJoinLeaf(
7070 SOCKET s,
7071 const struct WS_sockaddr *addr,
7072 int addrlen,
7073 LPWSABUF lpCallerData,
7074 LPWSABUF lpCalleeData,
7075 LPQOS lpSQOS,
7076 LPQOS lpGQOS,
7077 DWORD dwFlags)
7079 FIXME("stub.\n");
7080 return INVALID_SOCKET;
7083 /***********************************************************************
7084 * __WSAFDIsSet (WS2_32.151)
7086 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
7088 int i = set->fd_count, ret = 0;
7090 while (i--)
7091 if (set->fd_array[i] == s)
7093 ret = 1;
7094 break;
7097 TRACE("(socket %04lx, fd_set %p, count %i) <- %d\n", s, set, set->fd_count, ret);
7098 return ret;
7101 /***********************************************************************
7102 * WSAIsBlocking (WS2_32.114)
7104 BOOL WINAPI WSAIsBlocking(void)
7106 /* By default WinSock should set all its sockets to non-blocking mode
7107 * and poll in PeekMessage loop when processing "blocking" ones. This
7108 * function is supposed to tell if the program is in this loop. Our
7109 * blocking calls are truly blocking so we always return FALSE.
7111 * Note: It is allowed to call this function without prior WSAStartup().
7114 TRACE("\n");
7115 return FALSE;
7118 /***********************************************************************
7119 * WSACancelBlockingCall (WS2_32.113)
7121 INT WINAPI WSACancelBlockingCall(void)
7123 TRACE("\n");
7124 return 0;
7127 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
7129 FIXME("How was this called?\n");
7130 return x();
7134 /***********************************************************************
7135 * WSASetBlockingHook (WS2_32.109)
7137 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
7139 FARPROC prev = blocking_hook;
7140 blocking_hook = lpBlockFunc;
7141 TRACE("hook %p\n", lpBlockFunc);
7142 return prev;
7146 /***********************************************************************
7147 * WSAUnhookBlockingHook (WS2_32.110)
7149 INT WINAPI WSAUnhookBlockingHook(void)
7151 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
7152 return 0;
7156 /* ----------------------------------- end of API stuff */
7158 /* ----------------------------------- helper functions -
7160 * TODO: Merge WS_dup_..() stuff into one function that
7161 * would operate with a generic structure containing internal
7162 * pointers (via a template of some kind).
7165 static int list_size(char** l, int item_size)
7167 int i,j = 0;
7168 if(l)
7169 { for(i=0;l[i];i++)
7170 j += (item_size) ? item_size : strlen(l[i]) + 1;
7171 j += (i + 1) * sizeof(char*); }
7172 return j;
7175 static int list_dup(char** l_src, char** l_to, int item_size)
7177 char *p;
7178 int i;
7180 for (i = 0; l_src[i]; i++) ;
7181 p = (char *)(l_to + i + 1);
7182 for (i = 0; l_src[i]; i++)
7184 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
7185 memcpy(p, l_src[i], count);
7186 l_to[i] = p;
7187 p += count;
7189 l_to[i] = NULL;
7190 return p - (char *)l_to;
7193 /* ----- hostent */
7195 /* create a hostent entry
7197 * Creates the entry with enough memory for the name, aliases
7198 * addresses, and the address pointers. Also copies the name
7199 * and sets up all the pointers.
7201 * NOTE: The alias and address lists must be allocated with room
7202 * for the NULL item terminating the list. This is true even if
7203 * the list has no items ("aliases" and "addresses" must be
7204 * at least "1", a truly empty list is invalid).
7206 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length)
7208 struct WS_hostent *p_to;
7209 char *p;
7210 int size = (sizeof(struct WS_hostent) +
7211 strlen(name) + 1 +
7212 sizeof(char *) * aliases +
7213 aliases_size +
7214 sizeof(char *) * addresses +
7215 address_length * (addresses - 1)), i;
7217 if (!(p_to = check_buffer_he(size))) return NULL;
7218 memset(p_to, 0, size);
7220 /* Use the memory in the same way winsock does.
7221 * First set the pointer for aliases, second set the pointers for addresses.
7222 * Third fill the addresses indexes, fourth jump aliases names size.
7223 * Fifth fill the hostname.
7224 * NOTE: This method is valid for OS version's >= XP.
7226 p = (char *)(p_to + 1);
7227 p_to->h_aliases = (char **)p;
7228 p += sizeof(char *)*aliases;
7230 p_to->h_addr_list = (char **)p;
7231 p += sizeof(char *)*addresses;
7233 for (i = 0, addresses--; i < addresses; i++, p += address_length)
7234 p_to->h_addr_list[i] = p;
7236 /* NOTE: h_aliases must be filled in manually because we don't know each string
7237 * size, leave these pointers NULL (already set to NULL by memset earlier).
7239 p += aliases_size;
7241 p_to->h_name = p;
7242 strcpy(p, name);
7244 return p_to;
7247 /* duplicate hostent entry
7248 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
7249 * Ditto for protoent and servent.
7251 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
7253 int i, addresses = 0, alias_size = 0;
7254 struct WS_hostent *p_to;
7255 char *p;
7257 for( i = 0; p_he->h_aliases[i]; i++) alias_size += strlen(p_he->h_aliases[i]) + 1;
7258 while (p_he->h_addr_list[addresses]) addresses++;
7260 p_to = WS_create_he(p_he->h_name, i + 1, alias_size, addresses + 1, p_he->h_length);
7262 if (!p_to) return NULL;
7263 p_to->h_addrtype = convert_af_u2w(p_he->h_addrtype);
7264 p_to->h_length = p_he->h_length;
7266 for(i = 0, p = p_to->h_addr_list[0]; p_he->h_addr_list[i]; i++, p += p_to->h_length)
7267 memcpy(p, p_he->h_addr_list[i], p_to->h_length);
7269 /* Fill the aliases after the IP data */
7270 for(i = 0; p_he->h_aliases[i]; i++)
7272 p_to->h_aliases[i] = p;
7273 strcpy(p, p_he->h_aliases[i]);
7274 p += strlen(p) + 1;
7277 return p_to;
7280 /* ----- protoent */
7282 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
7284 char *p;
7285 struct WS_protoent *p_to;
7287 int size = (sizeof(*p_pe) +
7288 strlen(p_pe->p_name) + 1 +
7289 list_size(p_pe->p_aliases, 0));
7291 if (!(p_to = check_buffer_pe(size))) return NULL;
7292 p_to->p_proto = p_pe->p_proto;
7294 p = (char *)(p_to + 1);
7295 p_to->p_name = p;
7296 strcpy(p, p_pe->p_name);
7297 p += strlen(p) + 1;
7299 p_to->p_aliases = (char **)p;
7300 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
7301 return p_to;
7304 /* ----- servent */
7306 static struct WS_servent *WS_dup_se(const struct servent* p_se)
7308 char *p;
7309 struct WS_servent *p_to;
7311 int size = (sizeof(*p_se) +
7312 strlen(p_se->s_proto) + 1 +
7313 strlen(p_se->s_name) + 1 +
7314 list_size(p_se->s_aliases, 0));
7316 if (!(p_to = check_buffer_se(size))) return NULL;
7317 p_to->s_port = p_se->s_port;
7319 p = (char *)(p_to + 1);
7320 p_to->s_name = p;
7321 strcpy(p, p_se->s_name);
7322 p += strlen(p) + 1;
7324 p_to->s_proto = p;
7325 strcpy(p, p_se->s_proto);
7326 p += strlen(p) + 1;
7328 p_to->s_aliases = (char **)p;
7329 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
7330 return p_to;
7334 /***********************************************************************
7335 * WSARecv (WS2_32.67)
7337 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
7338 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
7339 LPWSAOVERLAPPED lpOverlapped,
7340 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
7342 return WS2_recv_base(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
7343 NULL, NULL, lpOverlapped, lpCompletionRoutine, NULL);
7346 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
7347 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
7348 struct WS_sockaddr *lpFrom,
7349 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
7350 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
7351 LPWSABUF lpControlBuffer )
7353 unsigned int i, options;
7354 int n, fd, err, overlapped, flags;
7355 struct ws2_async *wsa = NULL, localwsa;
7356 BOOL is_blocking;
7357 DWORD timeout_start = GetTickCount();
7358 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
7360 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
7361 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
7362 (lpFromlen ? *lpFromlen : -1),
7363 lpOverlapped, lpCompletionRoutine);
7365 fd = get_sock_fd( s, FILE_READ_DATA, &options );
7366 TRACE( "fd=%d, options=%x\n", fd, options );
7368 if (fd == -1) return SOCKET_ERROR;
7370 if (*lpFlags & WS_MSG_OOB)
7372 /* It's invalid to receive OOB data from an OOBINLINED socket
7373 * as OOB data is turned into normal data. */
7374 i = sizeof(n);
7375 if (!getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, (char*) &n, &i) && n)
7377 err = WSAEINVAL;
7378 goto error;
7382 overlapped = (lpOverlapped || lpCompletionRoutine) &&
7383 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
7384 if (overlapped || dwBufferCount > 1)
7386 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[dwBufferCount]))))
7388 err = WSAEFAULT;
7389 goto error;
7392 else
7393 wsa = &localwsa;
7395 wsa->hSocket = SOCKET2HANDLE(s);
7396 wsa->flags = *lpFlags;
7397 wsa->lpFlags = lpFlags;
7398 wsa->addr = lpFrom;
7399 wsa->addrlen.ptr = lpFromlen;
7400 wsa->control = lpControlBuffer;
7401 wsa->n_iovecs = dwBufferCount;
7402 wsa->first_iovec = 0;
7403 for (i = 0; i < dwBufferCount; i++)
7405 /* check buffer first to trigger write watches */
7406 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
7408 err = WSAEFAULT;
7409 goto error;
7411 wsa->iovec[i].iov_base = lpBuffers[i].buf;
7412 wsa->iovec[i].iov_len = lpBuffers[i].len;
7415 flags = convert_flags(wsa->flags);
7416 for (;;)
7418 n = WS2_recv( fd, wsa, flags );
7419 if (n == -1)
7421 /* Unix-like systems return EINVAL when attempting to read OOB data from
7422 * an empty socket buffer, convert that to a Windows expected return. */
7423 if ((flags & MSG_OOB) && errno == EINVAL)
7424 errno = EWOULDBLOCK;
7426 if (errno != EAGAIN)
7428 int loc_errno = errno;
7429 err = wsaErrno();
7430 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
7431 goto error;
7434 else if (lpNumberOfBytesRecvd) *lpNumberOfBytesRecvd = n;
7436 if (overlapped)
7438 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
7440 wsa->user_overlapped = lpOverlapped;
7441 wsa->completion_func = lpCompletionRoutine;
7442 release_sock_fd( s, fd );
7444 if (n == -1)
7446 iosb->u.Status = STATUS_PENDING;
7447 iosb->Information = 0;
7449 SERVER_START_REQ( register_async )
7451 req->type = ASYNC_TYPE_READ;
7452 req->async.handle = wine_server_obj_handle( wsa->hSocket );
7453 req->async.callback = wine_server_client_ptr( WS2_async_recv );
7454 req->async.iosb = wine_server_client_ptr( iosb );
7455 req->async.arg = wine_server_client_ptr( wsa );
7456 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
7457 req->async.cvalue = cvalue;
7458 err = wine_server_call( req );
7460 SERVER_END_REQ;
7462 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
7463 SetLastError(NtStatusToWSAError( err ));
7464 return SOCKET_ERROR;
7467 iosb->u.Status = STATUS_SUCCESS;
7468 iosb->Information = n;
7469 if (!wsa->completion_func)
7471 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
7472 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
7473 HeapFree( GetProcessHeap(), 0, wsa );
7475 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
7476 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
7477 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7478 return 0;
7481 if (n != -1) break;
7483 if ((err = _is_blocking( s, &is_blocking )))
7485 err = NtStatusToWSAError( err );
7486 goto error;
7489 if ( is_blocking )
7491 struct pollfd pfd;
7492 int poll_timeout = -1;
7493 INT64 timeout = get_rcvsnd_timeo(fd, TRUE);
7495 if (timeout)
7497 timeout -= GetTickCount() - timeout_start;
7498 if (timeout < 0) poll_timeout = 0;
7499 else poll_timeout = timeout <= INT_MAX ? timeout : INT_MAX;
7502 pfd.fd = fd;
7503 pfd.events = POLLIN;
7504 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
7506 if (!poll_timeout || !poll( &pfd, 1, poll_timeout ))
7508 err = WSAETIMEDOUT;
7509 /* a timeout is not fatal */
7510 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7511 goto error;
7514 else
7516 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7517 err = WSAEWOULDBLOCK;
7518 goto error;
7522 TRACE(" -> %i bytes\n", n);
7523 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
7524 release_sock_fd( s, fd );
7525 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7526 SetLastError(ERROR_SUCCESS);
7528 return 0;
7530 error:
7531 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
7532 release_sock_fd( s, fd );
7533 WARN(" -> ERROR %d\n", err);
7534 SetLastError( err );
7535 return SOCKET_ERROR;
7538 /***********************************************************************
7539 * WSARecvFrom (WS2_32.69)
7541 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
7542 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
7543 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
7544 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
7547 return WS2_recv_base( s, lpBuffers, dwBufferCount,
7548 lpNumberOfBytesRecvd, lpFlags,
7549 lpFrom, lpFromlen,
7550 lpOverlapped, lpCompletionRoutine, NULL );
7553 /***********************************************************************
7554 * WSCInstallProvider (WS2_32.88)
7556 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
7557 LPCWSTR lpszProviderDllPath,
7558 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
7559 DWORD dwNumberOfEntries,
7560 LPINT lpErrno )
7562 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
7563 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
7564 dwNumberOfEntries, lpErrno);
7565 *lpErrno = 0;
7566 return 0;
7570 /***********************************************************************
7571 * WSCDeinstallProvider (WS2_32.83)
7573 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
7575 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
7576 *lpErrno = 0;
7577 return 0;
7581 /***********************************************************************
7582 * WSAAccept (WS2_32.26)
7584 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
7585 LPCONDITIONPROC lpfnCondition, DWORD_PTR dwCallbackData)
7588 int ret = 0, size;
7589 WSABUF CallerId, CallerData, CalleeId, CalleeData;
7590 /* QOS SQOS, GQOS; */
7591 GROUP g;
7592 SOCKET cs;
7593 SOCKADDR src_addr, dst_addr;
7595 TRACE("socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
7596 s, addr, addrlen, lpfnCondition, dwCallbackData);
7598 cs = WS_accept(s, addr, addrlen);
7599 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
7600 if (!lpfnCondition) return cs;
7602 if (addr && addrlen)
7604 CallerId.buf = (char *)addr;
7605 CallerId.len = *addrlen;
7607 else
7609 size = sizeof(src_addr);
7610 WS_getpeername(cs, &src_addr, &size);
7611 CallerId.buf = (char *)&src_addr;
7612 CallerId.len = size;
7614 CallerData.buf = NULL;
7615 CallerData.len = 0;
7617 size = sizeof(dst_addr);
7618 WS_getsockname(cs, &dst_addr, &size);
7620 CalleeId.buf = (char *)&dst_addr;
7621 CalleeId.len = sizeof(dst_addr);
7623 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
7624 &CalleeId, &CalleeData, &g, dwCallbackData);
7626 switch (ret)
7628 case CF_ACCEPT:
7629 return cs;
7630 case CF_DEFER:
7631 SERVER_START_REQ( set_socket_deferred )
7633 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
7634 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
7635 if ( !wine_server_call_err ( req ) )
7637 SetLastError( WSATRY_AGAIN );
7638 WS_closesocket( cs );
7641 SERVER_END_REQ;
7642 return SOCKET_ERROR;
7643 case CF_REJECT:
7644 WS_closesocket(cs);
7645 SetLastError(WSAECONNREFUSED);
7646 return SOCKET_ERROR;
7647 default:
7648 FIXME("Unknown return type from Condition function\n");
7649 SetLastError(WSAENOTSOCK);
7650 return SOCKET_ERROR;
7654 /***********************************************************************
7655 * WSADuplicateSocketA (WS2_32.32)
7657 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
7659 return WS_DuplicateSocket(FALSE, s, dwProcessId, (LPWSAPROTOCOL_INFOW) lpProtocolInfo);
7662 /***********************************************************************
7663 * WSADuplicateSocketW (WS2_32.33)
7665 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
7667 return WS_DuplicateSocket(TRUE, s, dwProcessId, lpProtocolInfo);
7670 /***********************************************************************
7671 * WSAInstallServiceClassA (WS2_32.48)
7673 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
7675 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
7676 SetLastError(WSAEACCES);
7677 return SOCKET_ERROR;
7680 /***********************************************************************
7681 * WSAInstallServiceClassW (WS2_32.49)
7683 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
7685 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
7686 SetLastError(WSAEACCES);
7687 return SOCKET_ERROR;
7690 /***********************************************************************
7691 * WSARemoveServiceClass (WS2_32.70)
7693 int WINAPI WSARemoveServiceClass(LPGUID info)
7695 FIXME("Request to remove service %p\n",info);
7696 SetLastError(WSATYPE_NOT_FOUND);
7697 return SOCKET_ERROR;
7700 /***********************************************************************
7701 * inet_ntop (WS2_32.@)
7703 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
7705 #ifdef HAVE_INET_NTOP
7706 struct WS_in6_addr *in6;
7707 struct WS_in_addr *in;
7708 PCSTR pdst;
7710 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
7711 if (!buffer)
7713 SetLastError( STATUS_INVALID_PARAMETER );
7714 return NULL;
7717 switch (family)
7719 case WS_AF_INET:
7721 in = addr;
7722 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
7723 break;
7725 case WS_AF_INET6:
7727 in6 = addr;
7728 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
7729 break;
7731 default:
7732 SetLastError( WSAEAFNOSUPPORT );
7733 return NULL;
7736 if (!pdst) SetLastError( STATUS_INVALID_PARAMETER );
7737 return pdst;
7738 #else
7739 FIXME( "not supported on this platform\n" );
7740 SetLastError( WSAEAFNOSUPPORT );
7741 return NULL;
7742 #endif
7745 /***********************************************************************
7746 * inet_pton (WS2_32.@)
7748 INT WINAPI WS_inet_pton( INT family, PCSTR addr, PVOID buffer)
7750 #ifdef HAVE_INET_PTON
7751 int unixaf, ret;
7753 TRACE("family %d, addr %s, buffer (%p)\n", family, debugstr_a(addr), buffer);
7755 if (!addr || !buffer)
7757 SetLastError(WSAEFAULT);
7758 return SOCKET_ERROR;
7761 unixaf = convert_af_w2u(family);
7762 if (unixaf != AF_INET && unixaf != AF_INET6)
7764 SetLastError(WSAEAFNOSUPPORT);
7765 return SOCKET_ERROR;
7768 ret = inet_pton(unixaf, addr, buffer);
7769 if (ret == -1) SetLastError(wsaErrno());
7770 return ret;
7771 #else
7772 FIXME( "not supported on this platform\n" );
7773 SetLastError( WSAEAFNOSUPPORT );
7774 return SOCKET_ERROR;
7775 #endif
7778 /***********************************************************************
7779 * InetPtonW (WS2_32.@)
7781 INT WINAPI InetPtonW(INT family, PCWSTR addr, PVOID buffer)
7783 char *addrA;
7784 int len;
7785 INT ret;
7787 TRACE("family %d, addr %s, buffer (%p)\n", family, debugstr_w(addr), buffer);
7789 if (!addr)
7791 SetLastError(WSAEFAULT);
7792 return SOCKET_ERROR;
7795 len = WideCharToMultiByte(CP_ACP, 0, addr, -1, NULL, 0, NULL, NULL);
7796 if (!(addrA = HeapAlloc(GetProcessHeap(), 0, len)))
7798 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7799 return SOCKET_ERROR;
7801 WideCharToMultiByte(CP_ACP, 0, addr, -1, addrA, len, NULL, NULL);
7803 ret = WS_inet_pton(family, addrA, buffer);
7805 HeapFree(GetProcessHeap(), 0, addrA);
7806 return ret;
7809 /***********************************************************************
7810 * WSAStringToAddressA (WS2_32.80)
7812 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
7813 INT AddressFamily,
7814 LPWSAPROTOCOL_INFOA lpProtocolInfo,
7815 LPSOCKADDR lpAddress,
7816 LPINT lpAddressLength)
7818 INT res=0;
7819 LPSTR workBuffer=NULL,ptrPort;
7821 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
7822 lpProtocolInfo, lpAddress, lpAddressLength );
7824 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
7826 if (!AddressString)
7828 SetLastError(WSAEINVAL);
7829 return SOCKET_ERROR;
7832 if (lpProtocolInfo)
7833 FIXME("ProtocolInfo not implemented.\n");
7835 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
7836 strlen(AddressString) + 1);
7837 if (!workBuffer)
7839 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7840 return SOCKET_ERROR;
7843 strcpy(workBuffer, AddressString);
7845 switch(AddressFamily)
7847 case WS_AF_INET:
7849 struct in_addr inetaddr;
7851 /* If lpAddressLength is too small, tell caller the size we need */
7852 if (*lpAddressLength < sizeof(SOCKADDR_IN))
7854 *lpAddressLength = sizeof(SOCKADDR_IN);
7855 res = WSAEFAULT;
7856 break;
7858 *lpAddressLength = sizeof(SOCKADDR_IN);
7859 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
7861 ((LPSOCKADDR_IN)lpAddress)->sin_family = WS_AF_INET;
7863 ptrPort = strchr(workBuffer, ':');
7864 if(ptrPort)
7866 /* User may have entered an IPv6 and asked to parse as IPv4 */
7867 if(strchr(ptrPort + 1, ':'))
7869 res = WSAEINVAL;
7870 break;
7872 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
7873 *ptrPort = '\0';
7875 else
7877 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
7880 if(inet_aton(workBuffer, &inetaddr) > 0)
7882 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
7883 res = 0;
7885 else
7886 res = WSAEINVAL;
7888 break;
7891 case WS_AF_INET6:
7893 struct in6_addr inetaddr;
7894 /* If lpAddressLength is too small, tell caller the size we need */
7895 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
7897 *lpAddressLength = sizeof(SOCKADDR_IN6);
7898 res = WSAEFAULT;
7899 break;
7901 #ifdef HAVE_INET_PTON
7902 *lpAddressLength = sizeof(SOCKADDR_IN6);
7903 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
7905 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
7907 /* This one is a bit tricky. An IPv6 address contains colons, so the
7908 * check from IPv4 doesn't work like that. However, IPv6 addresses that
7909 * contain a port are written with braces like [fd12:3456:7890::1]:12345
7910 * so what we will do is to look for ']', check if the next char is a
7911 * colon, and if it is, parse the port as in IPv4. */
7913 ptrPort = strchr(workBuffer, ']');
7914 if(ptrPort && *(++ptrPort) == ':')
7916 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort+1));
7917 *ptrPort = '\0';
7919 else
7921 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
7924 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
7926 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
7927 sizeof(struct in6_addr));
7928 res = 0;
7930 else
7931 #endif /* HAVE_INET_PTON */
7932 res = WSAEINVAL;
7934 break;
7936 default:
7937 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
7938 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
7939 res = WSAEINVAL;
7942 HeapFree(GetProcessHeap(), 0, workBuffer);
7944 if (!res) return 0;
7945 SetLastError(res);
7946 return SOCKET_ERROR;
7949 /***********************************************************************
7950 * WSAStringToAddressW (WS2_32.81)
7952 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
7953 * If this should be the case, it would be required to map these digits
7954 * to Unicode digits (0-9) using FoldString first.
7956 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
7957 INT AddressFamily,
7958 LPWSAPROTOCOL_INFOW lpProtocolInfo,
7959 LPSOCKADDR lpAddress,
7960 LPINT lpAddressLength)
7962 INT sBuffer,res=0;
7963 LPSTR workBuffer=NULL;
7964 WSAPROTOCOL_INFOA infoA;
7965 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
7967 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
7968 lpAddress, lpAddressLength );
7970 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
7972 /* if ProtocolInfo is available - convert to ANSI variant */
7973 if (lpProtocolInfo)
7975 lpProtoInfoA = &infoA;
7976 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
7978 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
7979 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
7981 SetLastError(WSAEINVAL);
7982 return SOCKET_ERROR;
7986 if (AddressString)
7988 /* Translate AddressString to ANSI code page - assumes that only
7989 standard digits 0-9 are used with this API call */
7990 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
7991 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
7993 if (workBuffer)
7995 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
7996 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
7997 lpAddress,lpAddressLength);
7998 HeapFree( GetProcessHeap(), 0, workBuffer );
7999 return res;
8001 else
8002 res = WSA_NOT_ENOUGH_MEMORY;
8004 else
8005 res = WSAEINVAL;
8007 SetLastError(res);
8008 return SOCKET_ERROR;
8011 /***********************************************************************
8012 * WSAAddressToStringA (WS2_32.27)
8014 * See WSAAddressToStringW
8016 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
8017 LPWSAPROTOCOL_INFOA info, LPSTR string,
8018 LPDWORD lenstr )
8020 DWORD size;
8021 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
8022 CHAR *p;
8024 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
8026 if (!sockaddr) return SOCKET_ERROR;
8027 if (!string || !lenstr) return SOCKET_ERROR;
8029 switch(sockaddr->sa_family)
8031 case WS_AF_INET:
8032 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
8033 sprintf( buffer, "%u.%u.%u.%u:%u",
8034 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
8035 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
8036 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
8037 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
8038 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
8040 p = strchr( buffer, ':' );
8041 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
8042 break;
8044 case WS_AF_INET6:
8046 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
8047 size_t slen;
8049 buffer[0] = 0;
8050 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
8051 if ((sockaddr6->sin6_port))
8052 strcpy(buffer, "[");
8053 slen = strlen(buffer);
8054 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, &buffer[slen], sizeof(buffer) - slen))
8056 SetLastError(WSAEINVAL);
8057 return SOCKET_ERROR;
8059 if ((sockaddr6->sin6_scope_id))
8060 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
8061 if ((sockaddr6->sin6_port))
8062 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
8063 break;
8066 default:
8067 SetLastError(WSAEINVAL);
8068 return SOCKET_ERROR;
8071 size = strlen( buffer ) + 1;
8073 if (*lenstr < size)
8075 *lenstr = size;
8076 SetLastError(WSAEFAULT);
8077 return SOCKET_ERROR;
8080 TRACE("=> %s,%u bytes\n", debugstr_a(buffer), size);
8081 *lenstr = size;
8082 strcpy( string, buffer );
8083 return 0;
8086 /***********************************************************************
8087 * WSAAddressToStringW (WS2_32.28)
8089 * Convert a sockaddr address into a readable address string.
8091 * PARAMS
8092 * sockaddr [I] Pointer to a sockaddr structure.
8093 * len [I] Size of the sockaddr structure.
8094 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
8095 * string [I/O] Pointer to a buffer to receive the address string.
8096 * lenstr [I/O] Size of the receive buffer in WCHARs.
8098 * RETURNS
8099 * Success: 0
8100 * Failure: SOCKET_ERROR
8102 * NOTES
8103 * The 'info' parameter is ignored.
8105 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
8106 LPWSAPROTOCOL_INFOW info, LPWSTR string,
8107 LPDWORD lenstr )
8109 INT ret;
8110 DWORD size;
8111 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
8112 CHAR bufAddr[54];
8114 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
8116 size = *lenstr;
8117 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
8119 if (ret) return ret;
8121 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
8123 if (*lenstr < size)
8125 *lenstr = size;
8126 SetLastError(WSAEFAULT);
8127 return SOCKET_ERROR;
8130 TRACE("=> %s,%u bytes\n", debugstr_w(buffer), size);
8131 *lenstr = size;
8132 lstrcpyW( string, buffer );
8133 return 0;
8136 /***********************************************************************
8137 * WSAEnumNameSpaceProvidersA (WS2_32.34)
8139 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
8141 FIXME( "(%p %p) Stub!\n", len, buffer );
8142 return 0;
8145 /***********************************************************************
8146 * WSAEnumNameSpaceProvidersW (WS2_32.35)
8148 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
8150 FIXME( "(%p %p) Stub!\n", len, buffer );
8151 return 0;
8154 /***********************************************************************
8155 * WSAGetQOSByName (WS2_32.41)
8157 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
8159 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
8160 return FALSE;
8163 /***********************************************************************
8164 * WSAGetServiceClassInfoA (WS2_32.42)
8166 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
8167 LPWSASERVICECLASSINFOA info )
8169 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
8170 len, info );
8171 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8172 return SOCKET_ERROR;
8175 /***********************************************************************
8176 * WSAGetServiceClassInfoW (WS2_32.43)
8178 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
8179 LPWSASERVICECLASSINFOW info )
8181 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
8182 len, info );
8183 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8184 return SOCKET_ERROR;
8187 /***********************************************************************
8188 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
8190 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
8192 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
8193 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8194 return SOCKET_ERROR;
8197 /***********************************************************************
8198 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
8200 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
8202 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
8203 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8204 return SOCKET_ERROR;
8207 /***********************************************************************
8208 * WSALookupServiceBeginA (WS2_32.59)
8210 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
8211 DWORD dwControlFlags,
8212 LPHANDLE lphLookup)
8214 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
8215 lphLookup);
8216 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8217 return SOCKET_ERROR;
8220 /***********************************************************************
8221 * WSALookupServiceBeginW (WS2_32.60)
8223 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
8224 DWORD dwControlFlags,
8225 LPHANDLE lphLookup)
8227 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
8228 lphLookup);
8229 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8230 return SOCKET_ERROR;
8233 /***********************************************************************
8234 * WSALookupServiceEnd (WS2_32.61)
8236 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
8238 FIXME("(%p) Stub!\n", lookup );
8239 return 0;
8242 /***********************************************************************
8243 * WSALookupServiceNextA (WS2_32.62)
8245 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
8247 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
8248 SetLastError(WSA_E_NO_MORE);
8249 return SOCKET_ERROR;
8252 /***********************************************************************
8253 * WSALookupServiceNextW (WS2_32.63)
8255 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
8257 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
8258 SetLastError(WSA_E_NO_MORE);
8259 return SOCKET_ERROR;
8262 /***********************************************************************
8263 * WSANtohl (WS2_32.64)
8265 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
8267 TRACE( "(%04lx 0x%08x %p)\n", s, netlong, lphostlong );
8269 if (!lphostlong) return WSAEFAULT;
8271 *lphostlong = ntohl( netlong );
8272 return 0;
8275 /***********************************************************************
8276 * WSANtohs (WS2_32.65)
8278 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
8280 TRACE( "(%04lx 0x%08x %p)\n", s, netshort, lphostshort );
8282 if (!lphostshort) return WSAEFAULT;
8284 *lphostshort = ntohs( netshort );
8285 return 0;
8288 /***********************************************************************
8289 * WSAProviderConfigChange (WS2_32.66)
8291 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
8292 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
8294 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
8295 return SOCKET_ERROR;
8298 /***********************************************************************
8299 * WSARecvDisconnect (WS2_32.68)
8301 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
8303 TRACE( "(%04lx %p)\n", s, disconnectdata );
8305 return WS_shutdown( s, SD_RECEIVE );
8308 /***********************************************************************
8309 * WSASetServiceA (WS2_32.76)
8311 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
8313 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
8314 return 0;
8317 /***********************************************************************
8318 * WSASetServiceW (WS2_32.77)
8320 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
8322 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
8323 return 0;
8326 /***********************************************************************
8327 * WSCEnableNSProvider (WS2_32.84)
8329 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
8331 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
8332 return 0;
8335 /***********************************************************************
8336 * WSCGetProviderPath (WS2_32.86)
8338 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
8340 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
8342 if (!errcode || !provider || !len) return WSAEFAULT;
8344 *errcode = WSAEINVAL;
8345 return SOCKET_ERROR;
8348 /***********************************************************************
8349 * WSCInstallNameSpace (WS2_32.87)
8351 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
8352 DWORD version, LPGUID provider )
8354 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
8355 namespace, version, debugstr_guid(provider) );
8356 return 0;
8359 /***********************************************************************
8360 * WSCUnInstallNameSpace (WS2_32.89)
8362 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
8364 FIXME("(%p) Stub!\n", lpProviderId);
8365 return NO_ERROR;
8368 /***********************************************************************
8369 * WSCWriteProviderOrder (WS2_32.91)
8371 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
8373 FIXME("(%p 0x%08x) Stub!\n", entry, number);
8374 return 0;
8377 /***********************************************************************
8378 * WSANSPIoctl (WS2_32.91)
8380 INT WINAPI WSANSPIoctl( HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer,
8381 DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer,
8382 LPDWORD lpcbBytesReturned, LPWSACOMPLETION lpCompletion )
8384 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup, dwControlCode,
8385 lpvInBuffer, cbInBuffer, lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpCompletion);
8386 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8387 return SOCKET_ERROR;
8390 /*****************************************************************************
8391 * WSAEnumProtocolsA [WS2_32.@]
8393 * see function WSAEnumProtocolsW
8395 INT WINAPI WSAEnumProtocolsA( LPINT protocols, LPWSAPROTOCOL_INFOA buffer, LPDWORD len )
8397 return WS_EnumProtocols( FALSE, protocols, (LPWSAPROTOCOL_INFOW) buffer, len);
8400 /*****************************************************************************
8401 * WSAEnumProtocolsW [WS2_32.@]
8403 * Retrieves information about specified set of active network protocols.
8405 * PARAMS
8406 * protocols [I] Pointer to null-terminated array of protocol id's. NULL
8407 * retrieves information on all available protocols.
8408 * buffer [I] Pointer to a buffer to be filled with WSAPROTOCOL_INFO
8409 * structures.
8410 * len [I/O] Pointer to a variable specifying buffer size. On output
8411 * the variable holds the number of bytes needed when the
8412 * specified size is too small.
8414 * RETURNS
8415 * Success: number of WSAPROTOCOL_INFO structures in buffer.
8416 * Failure: SOCKET_ERROR
8418 * NOTES
8419 * NT4SP5 does not return SPX if protocols == NULL
8421 * BUGS
8422 * - NT4SP5 returns in addition these list of NETBIOS protocols
8423 * (address family 17), each entry two times one for socket type 2 and 5
8425 * iProtocol szProtocol
8426 * 0x80000000 \Device\NwlnkNb
8427 * 0xfffffffa \Device\NetBT_CBENT7
8428 * 0xfffffffb \Device\Nbf_CBENT7
8429 * 0xfffffffc \Device\NetBT_NdisWan5
8430 * 0xfffffffd \Device\NetBT_El9202
8431 * 0xfffffffe \Device\Nbf_El9202
8432 * 0xffffffff \Device\Nbf_NdisWan4
8434 * - there is no check that the operating system supports the returned
8435 * protocols
8437 INT WINAPI WSAEnumProtocolsW( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
8439 return WS_EnumProtocols( TRUE, protocols, buffer, len);
8442 /*****************************************************************************
8443 * WSCEnumProtocols [WS2_32.@]
8445 * PARAMS
8446 * protocols [I] Null-terminated array of iProtocol values.
8447 * buffer [O] Buffer of WSAPROTOCOL_INFOW structures.
8448 * len [I/O] Size of buffer on input/output.
8449 * errno [O] Error code.
8451 * RETURNS
8452 * Success: number of protocols to be reported on.
8453 * Failure: SOCKET_ERROR. error is in errno.
8455 * BUGS
8456 * Doesn't supply info on layered protocols.
8459 INT WINAPI WSCEnumProtocols( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len, LPINT err )
8461 INT ret = WSAEnumProtocolsW( protocols, buffer, len );
8463 if (ret == SOCKET_ERROR) *err = WSAENOBUFS;
8465 return ret;