taskschd: IRegistrationInfo::put_Source() should accept NULL input.
[wine.git] / dlls / ws2_32 / socket.c
blob25ec72a2127b9ea38acdb18f97b85c2ad9b9f47c
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 */
244 extern ssize_t CDECL __wine_locked_recvmsg( int fd, struct msghdr *hdr, int flags );
247 * The actual definition of WSASendTo, wrapped in a different function name
248 * so that internal calls from ws2_32 itself will not trigger programs like
249 * Garena, which hooks WSASendTo/WSARecvFrom calls.
251 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
252 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
253 const struct WS_sockaddr *to, int tolen,
254 LPWSAOVERLAPPED lpOverlapped,
255 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine );
258 * Internal fundamental receive function, essentially WSARecvFrom with an
259 * additional parameter to support message control headers.
261 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
262 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
263 struct WS_sockaddr *lpFrom,
264 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
265 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
266 LPWSABUF lpControlBuffer );
268 /* critical section to protect some non-reentrant net function */
269 static CRITICAL_SECTION csWSgetXXXbyYYY;
270 static CRITICAL_SECTION_DEBUG critsect_debug =
272 0, 0, &csWSgetXXXbyYYY,
273 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
274 0, 0, { (DWORD_PTR)(__FILE__ ": csWSgetXXXbyYYY") }
276 static CRITICAL_SECTION csWSgetXXXbyYYY = { &critsect_debug, -1, 0, 0, 0, 0 };
278 union generic_unix_sockaddr
280 struct sockaddr addr;
281 char data[128]; /* should be big enough for all families */
284 static inline const char *debugstr_sockaddr( const struct WS_sockaddr *a )
286 if (!a) return "(nil)";
287 switch (a->sa_family)
289 case WS_AF_INET:
291 char buf[16];
292 const char *p;
293 struct WS_sockaddr_in *sin = (struct WS_sockaddr_in *)a;
295 p = WS_inet_ntop( WS_AF_INET, &sin->sin_addr, buf, sizeof(buf) );
296 if (!p)
297 p = "(unknown IPv4 address)";
299 return wine_dbg_sprintf("{ family AF_INET, address %s, port %d }",
300 p, ntohs(sin->sin_port));
302 case WS_AF_INET6:
304 char buf[46];
305 const char *p;
306 struct WS_sockaddr_in6 *sin = (struct WS_sockaddr_in6 *)a;
308 p = WS_inet_ntop( WS_AF_INET6, &sin->sin6_addr, buf, sizeof(buf) );
309 if (!p)
310 p = "(unknown IPv6 address)";
311 return wine_dbg_sprintf("{ family AF_INET6, address %s, port %d }",
312 p, ntohs(sin->sin6_port));
314 case WS_AF_IPX:
316 int i;
317 char netnum[16], nodenum[16];
318 struct WS_sockaddr_ipx *sin = (struct WS_sockaddr_ipx *)a;
320 for (i = 0;i < 4; i++) sprintf(netnum + i * 2, "%02X", (unsigned char) sin->sa_netnum[i]);
321 for (i = 0;i < 6; i++) sprintf(nodenum + i * 2, "%02X", (unsigned char) sin->sa_nodenum[i]);
323 return wine_dbg_sprintf("{ family AF_IPX, address %s.%s, ipx socket %d }",
324 netnum, nodenum, sin->sa_socket);
326 case WS_AF_IRDA:
328 DWORD addr;
330 memcpy( &addr, ((const SOCKADDR_IRDA *)a)->irdaDeviceID, sizeof(addr) );
331 addr = ntohl( addr );
332 return wine_dbg_sprintf("{ family AF_IRDA, addr %08x, name %s }",
333 addr,
334 ((const SOCKADDR_IRDA *)a)->irdaServiceName);
336 default:
337 return wine_dbg_sprintf("{ family %d }", a->sa_family);
341 static inline const char *debugstr_sockopt(int level, int optname)
343 const char *stropt = NULL, *strlevel = NULL;
345 #define DEBUG_SOCKLEVEL(x) case (x): strlevel = #x
346 #define DEBUG_SOCKOPT(x) case (x): stropt = #x; break
348 switch(level)
350 DEBUG_SOCKLEVEL(WS_SOL_SOCKET);
351 switch(optname)
353 DEBUG_SOCKOPT(WS_SO_ACCEPTCONN);
354 DEBUG_SOCKOPT(WS_SO_BROADCAST);
355 DEBUG_SOCKOPT(WS_SO_BSP_STATE);
356 DEBUG_SOCKOPT(WS_SO_CONDITIONAL_ACCEPT);
357 DEBUG_SOCKOPT(WS_SO_CONNECT_TIME);
358 DEBUG_SOCKOPT(WS_SO_DEBUG);
359 DEBUG_SOCKOPT(WS_SO_DONTLINGER);
360 DEBUG_SOCKOPT(WS_SO_DONTROUTE);
361 DEBUG_SOCKOPT(WS_SO_ERROR);
362 DEBUG_SOCKOPT(WS_SO_EXCLUSIVEADDRUSE);
363 DEBUG_SOCKOPT(WS_SO_GROUP_ID);
364 DEBUG_SOCKOPT(WS_SO_GROUP_PRIORITY);
365 DEBUG_SOCKOPT(WS_SO_KEEPALIVE);
366 DEBUG_SOCKOPT(WS_SO_LINGER);
367 DEBUG_SOCKOPT(WS_SO_MAX_MSG_SIZE);
368 DEBUG_SOCKOPT(WS_SO_OOBINLINE);
369 DEBUG_SOCKOPT(WS_SO_OPENTYPE);
370 DEBUG_SOCKOPT(WS_SO_PROTOCOL_INFOA);
371 DEBUG_SOCKOPT(WS_SO_PROTOCOL_INFOW);
372 DEBUG_SOCKOPT(WS_SO_RCVBUF);
373 DEBUG_SOCKOPT(WS_SO_RCVTIMEO);
374 DEBUG_SOCKOPT(WS_SO_REUSEADDR);
375 DEBUG_SOCKOPT(WS_SO_SNDBUF);
376 DEBUG_SOCKOPT(WS_SO_SNDTIMEO);
377 DEBUG_SOCKOPT(WS_SO_TYPE);
378 DEBUG_SOCKOPT(WS_SO_UPDATE_CONNECT_CONTEXT);
380 break;
382 DEBUG_SOCKLEVEL(WS_NSPROTO_IPX);
383 switch(optname)
385 DEBUG_SOCKOPT(WS_IPX_PTYPE);
386 DEBUG_SOCKOPT(WS_IPX_FILTERPTYPE);
387 DEBUG_SOCKOPT(WS_IPX_DSTYPE);
388 DEBUG_SOCKOPT(WS_IPX_RECVHDR);
389 DEBUG_SOCKOPT(WS_IPX_MAXSIZE);
390 DEBUG_SOCKOPT(WS_IPX_ADDRESS);
391 DEBUG_SOCKOPT(WS_IPX_MAX_ADAPTER_NUM);
393 break;
395 DEBUG_SOCKLEVEL(WS_SOL_IRLMP);
396 switch(optname)
398 DEBUG_SOCKOPT(WS_IRLMP_ENUMDEVICES);
400 break;
402 DEBUG_SOCKLEVEL(WS_IPPROTO_TCP);
403 switch(optname)
405 DEBUG_SOCKOPT(WS_TCP_BSDURGENT);
406 DEBUG_SOCKOPT(WS_TCP_EXPEDITED_1122);
407 DEBUG_SOCKOPT(WS_TCP_NODELAY);
409 break;
411 DEBUG_SOCKLEVEL(WS_IPPROTO_IP);
412 switch(optname)
414 DEBUG_SOCKOPT(WS_IP_ADD_MEMBERSHIP);
415 DEBUG_SOCKOPT(WS_IP_DONTFRAGMENT);
416 DEBUG_SOCKOPT(WS_IP_DROP_MEMBERSHIP);
417 DEBUG_SOCKOPT(WS_IP_HDRINCL);
418 DEBUG_SOCKOPT(WS_IP_MULTICAST_IF);
419 DEBUG_SOCKOPT(WS_IP_MULTICAST_LOOP);
420 DEBUG_SOCKOPT(WS_IP_MULTICAST_TTL);
421 DEBUG_SOCKOPT(WS_IP_OPTIONS);
422 DEBUG_SOCKOPT(WS_IP_PKTINFO);
423 DEBUG_SOCKOPT(WS_IP_RECEIVE_BROADCAST);
424 DEBUG_SOCKOPT(WS_IP_TOS);
425 DEBUG_SOCKOPT(WS_IP_TTL);
426 DEBUG_SOCKOPT(WS_IP_UNICAST_IF);
428 break;
430 DEBUG_SOCKLEVEL(WS_IPPROTO_IPV6);
431 switch(optname)
433 DEBUG_SOCKOPT(WS_IPV6_ADD_MEMBERSHIP);
434 DEBUG_SOCKOPT(WS_IPV6_DROP_MEMBERSHIP);
435 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_IF);
436 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_HOPS);
437 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_LOOP);
438 DEBUG_SOCKOPT(WS_IPV6_UNICAST_HOPS);
439 DEBUG_SOCKOPT(WS_IPV6_V6ONLY);
440 DEBUG_SOCKOPT(WS_IPV6_UNICAST_IF);
441 DEBUG_SOCKOPT(WS_IPV6_DONTFRAG);
443 break;
445 #undef DEBUG_SOCKLEVEL
446 #undef DEBUG_SOCKOPT
448 if (!strlevel)
449 strlevel = wine_dbg_sprintf("WS_0x%x", level);
450 if (!stropt)
451 stropt = wine_dbg_sprintf("WS_0x%x", optname);
453 return wine_dbg_sprintf("level %s, name %s", strlevel + 3, stropt + 3);
456 static inline const char *debugstr_optval(const char *optval, int optlenval)
458 if (optval && !IS_INTRESOURCE(optval) && optlenval >= 1 && optlenval <= sizeof(DWORD))
460 DWORD value = 0;
461 memcpy(&value, optval, optlenval);
462 return wine_dbg_sprintf("%p (%u)", optval, value);
464 return wine_dbg_sprintf("%p", optval);
467 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
468 #define SOCKET2HANDLE(s) ((HANDLE)(s))
469 #define HANDLE2SOCKET(h) ((SOCKET)(h))
471 /****************************************************************
472 * Async IO declarations
473 ****************************************************************/
475 typedef NTSTATUS async_callback_t( void *user, IO_STATUS_BLOCK *io, NTSTATUS status );
477 struct ws2_async_io
479 async_callback_t *callback; /* must be the first field */
480 struct ws2_async_io *next;
483 struct ws2_async_shutdown
485 struct ws2_async_io io;
486 HANDLE hSocket;
487 IO_STATUS_BLOCK iosb;
488 int type;
491 struct ws2_async
493 struct ws2_async_io io;
494 HANDLE hSocket;
495 LPWSAOVERLAPPED user_overlapped;
496 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
497 IO_STATUS_BLOCK local_iosb;
498 struct WS_sockaddr *addr;
499 union
501 int val; /* for send operations */
502 int *ptr; /* for recv operations */
503 } addrlen;
504 DWORD flags;
505 DWORD *lpFlags;
506 WSABUF *control;
507 unsigned int n_iovecs;
508 unsigned int first_iovec;
509 struct iovec iovec[1];
512 struct ws2_accept_async
514 struct ws2_async_io io;
515 HANDLE listen_socket;
516 HANDLE accept_socket;
517 LPOVERLAPPED user_overlapped;
518 ULONG_PTR cvalue;
519 PVOID buf; /* buffer to write data to */
520 int data_len;
521 int local_len;
522 int remote_len;
523 struct ws2_async *read;
526 struct ws2_transmitfile_async
528 struct ws2_async_io io;
529 char *buffer;
530 HANDLE file;
531 DWORD file_read;
532 DWORD file_bytes;
533 DWORD bytes_per_send;
534 TRANSMIT_FILE_BUFFERS buffers;
535 DWORD flags;
536 LARGE_INTEGER offset;
537 struct ws2_async write;
540 static struct ws2_async_io *async_io_freelist;
542 static void release_async_io( struct ws2_async_io *io )
544 for (;;)
546 struct ws2_async_io *next = async_io_freelist;
547 io->next = next;
548 if (InterlockedCompareExchangePointer( (void **)&async_io_freelist, io, next ) == next) return;
552 static struct ws2_async_io *alloc_async_io( DWORD size, async_callback_t callback )
554 /* first free remaining previous fileinfos */
556 struct ws2_async_io *io = InterlockedExchangePointer( (void **)&async_io_freelist, NULL );
558 while (io)
560 struct ws2_async_io *next = io->next;
561 HeapFree( GetProcessHeap(), 0, io );
562 io = next;
565 io = HeapAlloc( GetProcessHeap(), 0, size );
566 if (io) io->callback = callback;
567 return io;
570 static NTSTATUS register_async( int type, HANDLE handle, struct ws2_async_io *async, HANDLE event,
571 PIO_APC_ROUTINE apc, void *apc_context, IO_STATUS_BLOCK *io )
573 NTSTATUS status;
575 SERVER_START_REQ( register_async )
577 req->type = type;
578 req->async.handle = wine_server_obj_handle( handle );
579 req->async.user = wine_server_client_ptr( async );
580 req->async.iosb = wine_server_client_ptr( io );
581 req->async.event = wine_server_obj_handle( event );
582 req->async.apc = wine_server_client_ptr( apc );
583 req->async.apc_context = wine_server_client_ptr( apc_context );
584 status = wine_server_call( req );
586 SERVER_END_REQ;
588 return status;
591 /****************************************************************/
593 /* ----------------------------------- internal data */
595 /* ws_... struct conversion flags */
597 typedef struct /* WSAAsyncSelect() control struct */
599 HANDLE service, event, sock;
600 HWND hWnd;
601 UINT uMsg;
602 LONG lEvent;
603 } ws_select_info;
605 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
606 #define WS_MAX_UDP_DATAGRAM 1024
607 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
609 /* hostent's, servent's and protent's are stored in one buffer per thread,
610 * as documented on MSDN for the functions that return any of the buffers */
611 struct per_thread_data
613 int opentype;
614 struct WS_hostent *he_buffer;
615 struct WS_servent *se_buffer;
616 struct WS_protoent *pe_buffer;
617 struct pollfd *fd_cache;
618 unsigned int fd_count;
619 int he_len;
620 int se_len;
621 int pe_len;
622 char ntoa_buffer[16]; /* 4*3 digits + 3 '.' + 1 '\0' */
625 /* internal: routing description information */
626 struct route {
627 struct in_addr addr;
628 IF_INDEX interface;
629 DWORD metric, default_route;
632 static INT num_startup; /* reference counter */
633 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
635 /* function prototypes */
636 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length);
637 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
638 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
639 static struct WS_servent *WS_dup_se(const struct servent* p_se);
640 static int ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size);
642 int WSAIOCTL_GetInterfaceCount(void);
643 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
645 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus, ULONG Information );
647 #define MAP_OPTION(opt) { WS_##opt, opt }
649 static const int ws_flags_map[][2] =
651 MAP_OPTION( MSG_OOB ),
652 MAP_OPTION( MSG_PEEK ),
653 MAP_OPTION( MSG_DONTROUTE ),
654 MAP_OPTION( MSG_WAITALL ),
655 { WS_MSG_PARTIAL, 0 },
658 static const int ws_sock_map[][2] =
660 MAP_OPTION( SO_DEBUG ),
661 MAP_OPTION( SO_ACCEPTCONN ),
662 MAP_OPTION( SO_REUSEADDR ),
663 MAP_OPTION( SO_KEEPALIVE ),
664 MAP_OPTION( SO_DONTROUTE ),
665 MAP_OPTION( SO_BROADCAST ),
666 MAP_OPTION( SO_LINGER ),
667 MAP_OPTION( SO_OOBINLINE ),
668 MAP_OPTION( SO_SNDBUF ),
669 MAP_OPTION( SO_RCVBUF ),
670 MAP_OPTION( SO_ERROR ),
671 MAP_OPTION( SO_TYPE ),
672 #ifdef SO_RCVTIMEO
673 MAP_OPTION( SO_RCVTIMEO ),
674 #endif
675 #ifdef SO_SNDTIMEO
676 MAP_OPTION( SO_SNDTIMEO ),
677 #endif
680 static const int ws_tcp_map[][2] =
682 #ifdef TCP_NODELAY
683 MAP_OPTION( TCP_NODELAY ),
684 #endif
687 static const int ws_ip_map[][2] =
689 MAP_OPTION( IP_MULTICAST_IF ),
690 MAP_OPTION( IP_MULTICAST_TTL ),
691 MAP_OPTION( IP_MULTICAST_LOOP ),
692 MAP_OPTION( IP_ADD_MEMBERSHIP ),
693 MAP_OPTION( IP_DROP_MEMBERSHIP ),
694 MAP_OPTION( IP_OPTIONS ),
695 #ifdef IP_HDRINCL
696 MAP_OPTION( IP_HDRINCL ),
697 #endif
698 MAP_OPTION( IP_TOS ),
699 MAP_OPTION( IP_TTL ),
700 #ifdef IP_PKTINFO
701 MAP_OPTION( IP_PKTINFO ),
702 #endif
703 #ifdef IP_UNICAST_IF
704 MAP_OPTION( IP_UNICAST_IF ),
705 #endif
708 static const int ws_ipv6_map[][2] =
710 #ifdef IPV6_ADD_MEMBERSHIP
711 MAP_OPTION( IPV6_ADD_MEMBERSHIP ),
712 #endif
713 #ifdef IPV6_DROP_MEMBERSHIP
714 MAP_OPTION( IPV6_DROP_MEMBERSHIP ),
715 #endif
716 MAP_OPTION( IPV6_MULTICAST_IF ),
717 MAP_OPTION( IPV6_MULTICAST_HOPS ),
718 MAP_OPTION( IPV6_MULTICAST_LOOP ),
719 MAP_OPTION( IPV6_UNICAST_HOPS ),
720 MAP_OPTION( IPV6_V6ONLY ),
721 #ifdef IPV6_UNICAST_IF
722 MAP_OPTION( IPV6_UNICAST_IF ),
723 #endif
726 static const int ws_af_map[][2] =
728 MAP_OPTION( AF_UNSPEC ),
729 MAP_OPTION( AF_INET ),
730 MAP_OPTION( AF_INET6 ),
731 #ifdef HAS_IPX
732 MAP_OPTION( AF_IPX ),
733 #endif
734 #ifdef AF_IRDA
735 MAP_OPTION( AF_IRDA ),
736 #endif
737 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
740 static const int ws_socktype_map[][2] =
742 MAP_OPTION( SOCK_DGRAM ),
743 MAP_OPTION( SOCK_STREAM ),
744 MAP_OPTION( SOCK_RAW ),
745 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
748 static const int ws_proto_map[][2] =
750 MAP_OPTION( IPPROTO_IP ),
751 MAP_OPTION( IPPROTO_TCP ),
752 MAP_OPTION( IPPROTO_UDP ),
753 MAP_OPTION( IPPROTO_IPV6 ),
754 MAP_OPTION( IPPROTO_ICMP ),
755 MAP_OPTION( IPPROTO_IGMP ),
756 MAP_OPTION( IPPROTO_RAW ),
757 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
760 static const int ws_aiflag_map[][2] =
762 MAP_OPTION( AI_PASSIVE ),
763 MAP_OPTION( AI_CANONNAME ),
764 MAP_OPTION( AI_NUMERICHOST ),
765 #ifdef AI_NUMERICSERV
766 MAP_OPTION( AI_NUMERICSERV ),
767 #endif
768 #ifdef AI_V4MAPPED
769 MAP_OPTION( AI_V4MAPPED ),
770 #endif
771 MAP_OPTION( AI_ADDRCONFIG ),
774 static const int ws_niflag_map[][2] =
776 MAP_OPTION( NI_NOFQDN ),
777 MAP_OPTION( NI_NUMERICHOST ),
778 MAP_OPTION( NI_NAMEREQD ),
779 MAP_OPTION( NI_NUMERICSERV ),
780 MAP_OPTION( NI_DGRAM ),
783 static const int ws_eai_map[][2] =
785 MAP_OPTION( EAI_AGAIN ),
786 MAP_OPTION( EAI_BADFLAGS ),
787 MAP_OPTION( EAI_FAIL ),
788 MAP_OPTION( EAI_FAMILY ),
789 MAP_OPTION( EAI_MEMORY ),
790 /* Note: EAI_NODATA is deprecated, but still
791 * used by Windows and Linux... We map the newer
792 * EAI_NONAME to EAI_NODATA for now until Windows
793 * changes too.
795 #ifdef EAI_NODATA
796 MAP_OPTION( EAI_NODATA ),
797 #endif
798 #ifdef EAI_NONAME
799 { WS_EAI_NODATA, EAI_NONAME },
800 #endif
802 MAP_OPTION( EAI_SERVICE ),
803 MAP_OPTION( EAI_SOCKTYPE ),
804 { 0, 0 }
807 static const int ws_poll_map[][2] =
809 MAP_OPTION( POLLERR ),
810 MAP_OPTION( POLLHUP ),
811 MAP_OPTION( POLLNVAL ),
812 MAP_OPTION( POLLWRNORM ),
813 MAP_OPTION( POLLWRBAND ),
814 MAP_OPTION( POLLRDNORM ),
815 { WS_POLLRDBAND, POLLPRI }
818 static const char magic_loopback_addr[] = {127, 12, 34, 56};
820 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
821 #ifdef IP_PKTINFO
822 static inline WSACMSGHDR *fill_control_message(int level, int type, WSACMSGHDR *current, ULONG *maxsize, void *data, int len)
824 ULONG msgsize = sizeof(WSACMSGHDR) + WSA_CMSG_ALIGN(len);
825 char *ptr = (char *) current + sizeof(WSACMSGHDR);
827 /* Make sure there is at least enough room for this entry */
828 if (msgsize > *maxsize)
829 return NULL;
830 *maxsize -= msgsize;
831 /* Fill in the entry */
832 current->cmsg_len = sizeof(WSACMSGHDR) + len;
833 current->cmsg_level = level;
834 current->cmsg_type = type;
835 memcpy(ptr, data, len);
836 /* Return the pointer to where next entry should go */
837 return (WSACMSGHDR *) (ptr + WSA_CMSG_ALIGN(len));
839 #endif /* IP_PKTINFO */
841 static inline int convert_control_headers(struct msghdr *hdr, WSABUF *control)
843 #ifdef IP_PKTINFO
844 WSACMSGHDR *cmsg_win = (WSACMSGHDR *) control->buf, *ptr;
845 ULONG ctlsize = control->len;
846 struct cmsghdr *cmsg_unix;
848 ptr = cmsg_win;
849 /* Loop over all the headers, converting as appropriate */
850 for (cmsg_unix = CMSG_FIRSTHDR(hdr); cmsg_unix != NULL; cmsg_unix = CMSG_NXTHDR(hdr, cmsg_unix))
852 switch(cmsg_unix->cmsg_level)
854 case IPPROTO_IP:
855 switch(cmsg_unix->cmsg_type)
857 case IP_PKTINFO:
859 /* Convert the Unix IP_PKTINFO structure to the Windows version */
860 struct in_pktinfo *data_unix = (struct in_pktinfo *) CMSG_DATA(cmsg_unix);
861 struct WS_in_pktinfo data_win;
863 memcpy(&data_win.ipi_addr,&data_unix->ipi_addr.s_addr,4); /* 4 bytes = 32 address bits */
864 data_win.ipi_ifindex = data_unix->ipi_ifindex;
865 ptr = fill_control_message(WS_IPPROTO_IP, WS_IP_PKTINFO, ptr, &ctlsize,
866 (void*)&data_win, sizeof(data_win));
867 if (!ptr) goto error;
868 } break;
869 default:
870 FIXME("Unhandled IPPROTO_IP message header type %d\n", cmsg_unix->cmsg_type);
871 break;
873 break;
874 default:
875 FIXME("Unhandled message header level %d\n", cmsg_unix->cmsg_level);
876 break;
880 error:
881 /* Set the length of the returned control headers */
882 control->len = (ptr == NULL ? 0 : (char*)ptr - (char*)cmsg_win);
883 return (ptr != NULL);
884 #else /* IP_PKTINFO */
885 control->len = 0;
886 return 1;
887 #endif /* IP_PKTINFO */
889 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
891 /* ----------------------------------- error handling */
893 static NTSTATUS sock_get_ntstatus( int err )
895 switch ( err )
897 case EBADF: return STATUS_INVALID_HANDLE;
898 case EBUSY: return STATUS_DEVICE_BUSY;
899 case EPERM:
900 case EACCES: return STATUS_ACCESS_DENIED;
901 case EFAULT: return STATUS_NO_MEMORY;
902 case EINVAL: return STATUS_INVALID_PARAMETER;
903 case ENFILE:
904 case EMFILE: return STATUS_TOO_MANY_OPENED_FILES;
905 case EWOULDBLOCK: return STATUS_CANT_WAIT;
906 case EINPROGRESS: return STATUS_PENDING;
907 case EALREADY: return STATUS_NETWORK_BUSY;
908 case ENOTSOCK: return STATUS_OBJECT_TYPE_MISMATCH;
909 case EDESTADDRREQ: return STATUS_INVALID_PARAMETER;
910 case EMSGSIZE: return STATUS_BUFFER_OVERFLOW;
911 case EPROTONOSUPPORT:
912 case ESOCKTNOSUPPORT:
913 case EPFNOSUPPORT:
914 case EAFNOSUPPORT:
915 case EPROTOTYPE: return STATUS_NOT_SUPPORTED;
916 case ENOPROTOOPT: return STATUS_INVALID_PARAMETER;
917 case EOPNOTSUPP: return STATUS_NOT_SUPPORTED;
918 case EADDRINUSE: return STATUS_ADDRESS_ALREADY_ASSOCIATED;
919 case EADDRNOTAVAIL: return STATUS_INVALID_PARAMETER;
920 case ECONNREFUSED: return STATUS_CONNECTION_REFUSED;
921 case ESHUTDOWN: return STATUS_PIPE_DISCONNECTED;
922 case ENOTCONN: return STATUS_CONNECTION_DISCONNECTED;
923 case ETIMEDOUT: return STATUS_IO_TIMEOUT;
924 case ENETUNREACH: return STATUS_NETWORK_UNREACHABLE;
925 case ENETDOWN: return STATUS_NETWORK_BUSY;
926 case EPIPE:
927 case ECONNRESET: return STATUS_CONNECTION_RESET;
928 case ECONNABORTED: return STATUS_CONNECTION_ABORTED;
930 case 0: return STATUS_SUCCESS;
931 default:
932 WARN("Unknown errno %d!\n", err);
933 return STATUS_UNSUCCESSFUL;
937 static UINT sock_get_error( int err )
939 switch(err)
941 case EINTR: return WSAEINTR;
942 case EPERM:
943 case EACCES: return WSAEACCES;
944 case EFAULT: return WSAEFAULT;
945 case EINVAL: return WSAEINVAL;
946 case EMFILE: return WSAEMFILE;
947 case EWOULDBLOCK: return WSAEWOULDBLOCK;
948 case EINPROGRESS: return WSAEINPROGRESS;
949 case EALREADY: return WSAEALREADY;
950 case EBADF:
951 case ENOTSOCK: return WSAENOTSOCK;
952 case EDESTADDRREQ: return WSAEDESTADDRREQ;
953 case EMSGSIZE: return WSAEMSGSIZE;
954 case EPROTOTYPE: return WSAEPROTOTYPE;
955 case ENOPROTOOPT: return WSAENOPROTOOPT;
956 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
957 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
958 case EOPNOTSUPP: return WSAEOPNOTSUPP;
959 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
960 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
961 case EADDRINUSE: return WSAEADDRINUSE;
962 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
963 case ENETDOWN: return WSAENETDOWN;
964 case ENETUNREACH: return WSAENETUNREACH;
965 case ENETRESET: return WSAENETRESET;
966 case ECONNABORTED: return WSAECONNABORTED;
967 case EPIPE:
968 case ECONNRESET: return WSAECONNRESET;
969 case ENOBUFS: return WSAENOBUFS;
970 case EISCONN: return WSAEISCONN;
971 case ENOTCONN: return WSAENOTCONN;
972 case ESHUTDOWN: return WSAESHUTDOWN;
973 case ETOOMANYREFS: return WSAETOOMANYREFS;
974 case ETIMEDOUT: return WSAETIMEDOUT;
975 case ECONNREFUSED: return WSAECONNREFUSED;
976 case ELOOP: return WSAELOOP;
977 case ENAMETOOLONG: return WSAENAMETOOLONG;
978 case EHOSTDOWN: return WSAEHOSTDOWN;
979 case EHOSTUNREACH: return WSAEHOSTUNREACH;
980 case ENOTEMPTY: return WSAENOTEMPTY;
981 #ifdef EPROCLIM
982 case EPROCLIM: return WSAEPROCLIM;
983 #endif
984 #ifdef EUSERS
985 case EUSERS: return WSAEUSERS;
986 #endif
987 #ifdef EDQUOT
988 case EDQUOT: return WSAEDQUOT;
989 #endif
990 #ifdef ESTALE
991 case ESTALE: return WSAESTALE;
992 #endif
993 #ifdef EREMOTE
994 case EREMOTE: return WSAEREMOTE;
995 #endif
997 /* just in case we ever get here and there are no problems */
998 case 0: return 0;
999 default:
1000 WARN("Unknown errno %d!\n", err);
1001 return WSAEOPNOTSUPP;
1005 static UINT wsaErrno(void)
1007 int loc_errno = errno;
1008 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
1010 return sock_get_error( loc_errno );
1013 /* most ws2 overlapped functions return an ntstatus-based error code */
1014 static NTSTATUS wsaErrStatus(void)
1016 int loc_errno = errno;
1017 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
1019 return sock_get_ntstatus(loc_errno);
1022 static UINT wsaHerrno(int loc_errno)
1024 WARN("h_errno %d.\n", loc_errno);
1026 switch(loc_errno)
1028 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
1029 case TRY_AGAIN: return WSATRY_AGAIN;
1030 case NO_RECOVERY: return WSANO_RECOVERY;
1031 case NO_DATA: return WSANO_DATA;
1032 case ENOBUFS: return WSAENOBUFS;
1034 case 0: return 0;
1035 default:
1036 WARN("Unknown h_errno %d!\n", loc_errno);
1037 return WSAEOPNOTSUPP;
1041 static inline DWORD NtStatusToWSAError( const DWORD status )
1043 /* We only need to cover the status codes set by server async request handling */
1044 DWORD wserr;
1045 switch ( status )
1047 case STATUS_SUCCESS: wserr = 0; break;
1048 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
1049 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
1050 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
1051 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
1052 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
1053 case STATUS_NETWORK_BUSY: wserr = WSAEALREADY; break;
1054 case STATUS_NETWORK_UNREACHABLE: wserr = WSAENETUNREACH; break;
1055 case STATUS_CONNECTION_REFUSED: wserr = WSAECONNREFUSED; break;
1056 case STATUS_CONNECTION_DISCONNECTED: wserr = WSAENOTCONN; break;
1057 case STATUS_CONNECTION_RESET: wserr = WSAECONNRESET; break;
1058 case STATUS_CONNECTION_ABORTED: wserr = WSAECONNABORTED; break;
1059 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
1060 case STATUS_ADDRESS_ALREADY_ASSOCIATED: wserr = WSAEADDRINUSE; break;
1061 case STATUS_IO_TIMEOUT:
1062 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
1063 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
1064 case STATUS_ACCESS_DENIED: wserr = WSAEACCES; break;
1065 case STATUS_TOO_MANY_OPENED_FILES: wserr = WSAEMFILE; break;
1066 case STATUS_CANT_WAIT: wserr = WSAEWOULDBLOCK; break;
1067 case STATUS_BUFFER_OVERFLOW: wserr = WSAEMSGSIZE; break;
1068 case STATUS_NOT_SUPPORTED: wserr = WSAEOPNOTSUPP; break;
1069 case STATUS_HOST_UNREACHABLE: wserr = WSAEHOSTUNREACH; break;
1071 default:
1072 wserr = RtlNtStatusToDosError( status );
1073 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
1075 return wserr;
1078 /* set last error code from NT status without mapping WSA errors */
1079 static inline unsigned int set_error( unsigned int err )
1081 if (err)
1083 err = NtStatusToWSAError( err );
1084 SetLastError( err );
1086 return err;
1089 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
1091 int fd;
1092 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
1093 return -1;
1094 return fd;
1097 static inline void release_sock_fd( SOCKET s, int fd )
1099 wine_server_release_fd( SOCKET2HANDLE(s), fd );
1102 static void _enable_event( HANDLE s, unsigned int event,
1103 unsigned int sstate, unsigned int cstate )
1105 SERVER_START_REQ( enable_socket_event )
1107 req->handle = wine_server_obj_handle( s );
1108 req->mask = event;
1109 req->sstate = sstate;
1110 req->cstate = cstate;
1111 wine_server_call( req );
1113 SERVER_END_REQ;
1116 static NTSTATUS _is_blocking(SOCKET s, BOOL *ret)
1118 NTSTATUS status;
1119 SERVER_START_REQ( get_socket_event )
1121 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1122 req->service = FALSE;
1123 req->c_event = 0;
1124 status = wine_server_call( req );
1125 *ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
1127 SERVER_END_REQ;
1128 return status;
1131 static unsigned int _get_sock_mask(SOCKET s)
1133 unsigned int ret;
1134 SERVER_START_REQ( get_socket_event )
1136 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1137 req->service = FALSE;
1138 req->c_event = 0;
1139 wine_server_call( req );
1140 ret = reply->mask;
1142 SERVER_END_REQ;
1143 return ret;
1146 static void _sync_sock_state(SOCKET s)
1148 BOOL dummy;
1149 /* do a dummy wineserver request in order to let
1150 the wineserver run through its select loop once */
1151 (void)_is_blocking(s, &dummy);
1154 static void _get_sock_errors(SOCKET s, int *events)
1156 SERVER_START_REQ( get_socket_event )
1158 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1159 req->service = FALSE;
1160 req->c_event = 0;
1161 wine_server_set_reply( req, events, sizeof(int) * FD_MAX_EVENTS );
1162 wine_server_call( req );
1164 SERVER_END_REQ;
1167 static int _get_sock_error(SOCKET s, unsigned int bit)
1169 int events[FD_MAX_EVENTS];
1170 _get_sock_errors(s, events);
1171 return events[bit];
1174 static int _get_fd_type(int fd)
1176 int sock_type = -1;
1177 socklen_t optlen = sizeof(sock_type);
1178 getsockopt(fd, SOL_SOCKET, SO_TYPE, (char*) &sock_type, &optlen);
1179 return sock_type;
1182 static BOOL set_dont_fragment(SOCKET s, int level, BOOL value)
1184 int fd, optname;
1186 if (level == IPPROTO_IP)
1188 #ifdef IP_DONTFRAG
1189 optname = IP_DONTFRAG;
1190 #elif defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO) && defined(IP_PMTUDISC_DONT)
1191 optname = IP_MTU_DISCOVER;
1192 value = value ? IP_PMTUDISC_DO : IP_PMTUDISC_DONT;
1193 #else
1194 static int once;
1195 if (!once++)
1196 FIXME("IP_DONTFRAGMENT for IPv4 not supported in this platform\n");
1197 return TRUE; /* fake success */
1198 #endif
1200 else
1202 #ifdef IPV6_DONTFRAG
1203 optname = IPV6_DONTFRAG;
1204 #elif defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO) && defined(IPV6_PMTUDISC_DONT)
1205 optname = IPV6_MTU_DISCOVER;
1206 value = value ? IPV6_PMTUDISC_DO : IPV6_PMTUDISC_DONT;
1207 #else
1208 static int once;
1209 if (!once++)
1210 FIXME("IP_DONTFRAGMENT for IPv6 not supported in this platform\n");
1211 return TRUE; /* fake success */
1212 #endif
1215 fd = get_sock_fd(s, 0, NULL);
1216 if (fd == -1) return FALSE;
1218 if (!setsockopt(fd, level, optname, &value, sizeof(value)))
1219 value = TRUE;
1220 else
1222 WSASetLastError(wsaErrno());
1223 value = FALSE;
1226 release_sock_fd(s, fd);
1227 return value;
1230 static BOOL get_dont_fragment(SOCKET s, int level, BOOL *out)
1232 int fd, optname, value, not_expected;
1233 socklen_t optlen = sizeof(value);
1235 if (level == IPPROTO_IP)
1237 #ifdef IP_DONTFRAG
1238 optname = IP_DONTFRAG;
1239 not_expected = 0;
1240 #elif defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
1241 optname = IP_MTU_DISCOVER;
1242 not_expected = IP_PMTUDISC_DONT;
1243 #else
1244 static int once;
1245 if (!once++)
1246 FIXME("IP_DONTFRAGMENT for IPv4 not supported in this platform\n");
1247 return TRUE; /* fake success */
1248 #endif
1250 else
1252 #ifdef IPV6_DONTFRAG
1253 optname = IPV6_DONTFRAG;
1254 not_expected = 0;
1255 #elif defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DONT)
1256 optname = IPV6_MTU_DISCOVER;
1257 not_expected = IPV6_PMTUDISC_DONT;
1258 #else
1259 static int once;
1260 if (!once++)
1261 FIXME("IP_DONTFRAGMENT for IPv6 not supported in this platform\n");
1262 return TRUE; /* fake success */
1263 #endif
1266 fd = get_sock_fd(s, 0, NULL);
1267 if (fd == -1) return FALSE;
1269 if (!getsockopt(fd, level, optname, &value, &optlen))
1271 *out = value != not_expected;
1272 value = TRUE;
1274 else
1276 WSASetLastError(wsaErrno());
1277 value = FALSE;
1280 release_sock_fd(s, fd);
1281 return value;
1284 static struct per_thread_data *get_per_thread_data(void)
1286 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
1287 /* lazy initialization */
1288 if (!ptb)
1290 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
1291 NtCurrentTeb()->WinSockData = ptb;
1293 return ptb;
1296 static void free_per_thread_data(void)
1298 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
1300 if (!ptb) return;
1302 /* delete scratch buffers */
1303 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1304 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1305 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1306 HeapFree( GetProcessHeap(), 0, ptb->fd_cache );
1308 HeapFree( GetProcessHeap(), 0, ptb );
1309 NtCurrentTeb()->WinSockData = NULL;
1312 /***********************************************************************
1313 * DllMain (WS2_32.init)
1315 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
1317 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
1318 switch (fdwReason) {
1319 case DLL_PROCESS_ATTACH:
1320 break;
1321 case DLL_PROCESS_DETACH:
1322 if (fImpLoad) break;
1323 free_per_thread_data();
1324 DeleteCriticalSection(&csWSgetXXXbyYYY);
1325 break;
1326 case DLL_THREAD_DETACH:
1327 free_per_thread_data();
1328 break;
1330 return TRUE;
1333 /***********************************************************************
1334 * convert_flags()
1336 * Converts send/recv flags from Windows format.
1337 * Return the converted flag bits, unsupported flags remain unchanged.
1339 static int convert_flags(int flags)
1341 int i, out;
1342 if (!flags) return 0;
1344 for (out = i = 0; flags && i < sizeof(ws_flags_map) / sizeof(ws_flags_map[0]); i++)
1346 if (ws_flags_map[i][0] & flags)
1348 out |= ws_flags_map[i][1];
1349 flags &= ~ws_flags_map[i][0];
1352 if (flags)
1354 FIXME("Unknown send/recv flags 0x%x, using anyway...\n", flags);
1355 out |= flags;
1357 return out;
1360 /***********************************************************************
1361 * convert_sockopt()
1363 * Converts socket flags from Windows format.
1364 * Return 1 if converted, 0 if not (error).
1366 static int convert_sockopt(INT *level, INT *optname)
1368 unsigned int i;
1369 switch (*level)
1371 case WS_SOL_SOCKET:
1372 *level = SOL_SOCKET;
1373 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
1374 if( ws_sock_map[i][0] == *optname )
1376 *optname = ws_sock_map[i][1];
1377 return 1;
1380 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
1381 break;
1382 case WS_IPPROTO_TCP:
1383 *level = IPPROTO_TCP;
1384 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
1385 if ( ws_tcp_map[i][0] == *optname )
1387 *optname = ws_tcp_map[i][1];
1388 return 1;
1391 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
1392 break;
1393 case WS_IPPROTO_IP:
1394 *level = IPPROTO_IP;
1395 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
1396 if (ws_ip_map[i][0] == *optname )
1398 *optname = ws_ip_map[i][1];
1399 return 1;
1402 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
1403 break;
1404 case WS_IPPROTO_IPV6:
1405 *level = IPPROTO_IPV6;
1406 for(i=0; i<sizeof(ws_ipv6_map)/sizeof(ws_ipv6_map[0]); i++) {
1407 if (ws_ipv6_map[i][0] == *optname )
1409 *optname = ws_ipv6_map[i][1];
1410 return 1;
1413 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname);
1414 break;
1415 default: FIXME("Unimplemented or unknown socket level\n");
1417 return 0;
1420 /* ----------------------------------- Per-thread info (or per-process?) */
1422 static char *strdup_lower(const char *str)
1424 int i;
1425 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
1427 if (ret)
1429 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
1430 ret[i] = 0;
1432 else SetLastError(WSAENOBUFS);
1433 return ret;
1436 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
1437 * from an fd and return the value converted to milli seconds
1438 * or 0 if there is an infinite time out */
1439 static inline INT64 get_rcvsnd_timeo( int fd, BOOL is_recv)
1441 struct timeval tv;
1442 socklen_t len = sizeof(tv);
1443 int optname, res;
1445 if (is_recv)
1446 #ifdef SO_RCVTIMEO
1447 optname = SO_RCVTIMEO;
1448 #else
1449 return 0;
1450 #endif
1451 else
1452 #ifdef SO_SNDTIMEO
1453 optname = SO_SNDTIMEO;
1454 #else
1455 return 0;
1456 #endif
1458 res = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
1459 if (res < 0)
1460 return 0;
1461 return (UINT64)tv.tv_sec * 1000 + tv.tv_usec / 1000;
1464 /* utility: given an fd, will block until one of the events occurs */
1465 static inline int do_block( int fd, int events, int timeout )
1467 struct pollfd pfd;
1468 int ret;
1470 pfd.fd = fd;
1471 pfd.events = events;
1473 while ((ret = poll(&pfd, 1, timeout)) < 0)
1475 if (errno != EINTR)
1476 return -1;
1478 if( ret == 0 )
1479 return 0;
1480 return pfd.revents;
1483 static int
1484 convert_af_w2u(int windowsaf) {
1485 unsigned int i;
1487 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1488 if (ws_af_map[i][0] == windowsaf)
1489 return ws_af_map[i][1];
1490 FIXME("unhandled Windows address family %d\n", windowsaf);
1491 return -1;
1494 static int
1495 convert_af_u2w(int unixaf) {
1496 unsigned int i;
1498 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1499 if (ws_af_map[i][1] == unixaf)
1500 return ws_af_map[i][0];
1501 FIXME("unhandled UNIX address family %d\n", unixaf);
1502 return -1;
1505 static int
1506 convert_proto_w2u(int windowsproto) {
1507 unsigned int i;
1509 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1510 if (ws_proto_map[i][0] == windowsproto)
1511 return ws_proto_map[i][1];
1513 /* check for extended IPX */
1514 if (IS_IPX_PROTO(windowsproto))
1515 return windowsproto;
1517 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
1518 return -1;
1521 static int
1522 convert_proto_u2w(int unixproto) {
1523 unsigned int i;
1525 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1526 if (ws_proto_map[i][1] == unixproto)
1527 return ws_proto_map[i][0];
1529 /* if value is inside IPX range just return it - the kernel simply
1530 * echoes the value used in the socket() function */
1531 if (IS_IPX_PROTO(unixproto))
1532 return unixproto;
1534 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
1535 return -1;
1538 static int
1539 convert_socktype_w2u(int windowssocktype) {
1540 unsigned int i;
1542 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1543 if (ws_socktype_map[i][0] == windowssocktype)
1544 return ws_socktype_map[i][1];
1545 FIXME("unhandled Windows socket type %d\n", windowssocktype);
1546 return -1;
1549 static int
1550 convert_socktype_u2w(int unixsocktype) {
1551 unsigned int i;
1553 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1554 if (ws_socktype_map[i][1] == unixsocktype)
1555 return ws_socktype_map[i][0];
1556 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
1557 return -1;
1560 static int convert_poll_w2u(int events)
1562 int i, ret;
1563 for (i = ret = 0; events && i < sizeof(ws_poll_map) / sizeof(ws_poll_map[0]); i++)
1565 if (ws_poll_map[i][0] & events)
1567 ret |= ws_poll_map[i][1];
1568 events &= ~ws_poll_map[i][0];
1572 if (events)
1573 FIXME("Unsupported WSAPoll() flags 0x%x\n", events);
1574 return ret;
1577 static int convert_poll_u2w(int events)
1579 int i, ret;
1580 for (i = ret = 0; events && i < sizeof(ws_poll_map) / sizeof(ws_poll_map[0]); i++)
1582 if (ws_poll_map[i][1] & events)
1584 ret |= ws_poll_map[i][0];
1585 events &= ~ws_poll_map[i][1];
1589 if (events)
1590 FIXME("Unsupported poll() flags 0x%x\n", events);
1591 return ret;
1594 static int set_ipx_packettype(int sock, int ptype)
1596 #ifdef HAS_IPX
1597 int fd = get_sock_fd( sock, 0, NULL ), ret = 0;
1598 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", ptype, fd);
1600 if (fd == -1) return SOCKET_ERROR;
1602 /* We try to set the ipx type on ipx socket level. */
1603 #ifdef SOL_IPX
1604 if(setsockopt(fd, SOL_IPX, IPX_TYPE, &ptype, sizeof(ptype)) == -1)
1606 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
1607 ret = SOCKET_ERROR;
1609 #else
1611 struct ipx val;
1612 /* Should we retrieve val using a getsockopt call and then
1613 * set the modified one? */
1614 val.ipx_pt = ptype;
1615 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
1617 #endif
1618 release_sock_fd( sock, fd );
1619 return ret;
1620 #else
1621 WARN("IPX support is not enabled, can't set packet type\n");
1622 return SOCKET_ERROR;
1623 #endif
1626 /* ----------------------------------- API -----
1628 * Init / cleanup / error checking.
1631 /***********************************************************************
1632 * WSAStartup (WS2_32.115)
1634 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
1636 TRACE("verReq=%x\n", wVersionRequested);
1638 if (LOBYTE(wVersionRequested) < 1)
1639 return WSAVERNOTSUPPORTED;
1641 if (!lpWSAData) return WSAEINVAL;
1643 num_startup++;
1645 /* that's the whole of the negotiation for now */
1646 lpWSAData->wVersion = wVersionRequested;
1647 /* return winsock information */
1648 lpWSAData->wHighVersion = 0x0202;
1649 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
1650 strcpy(lpWSAData->szSystemStatus, "Running" );
1651 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
1652 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
1653 /* don't do anything with lpWSAData->lpVendorInfo */
1654 /* (some apps don't allocate the space for this field) */
1656 TRACE("succeeded starts: %d\n", num_startup);
1657 return 0;
1661 /***********************************************************************
1662 * WSACleanup (WS2_32.116)
1664 INT WINAPI WSACleanup(void)
1666 if (num_startup) {
1667 num_startup--;
1668 TRACE("pending cleanups: %d\n", num_startup);
1669 return 0;
1671 SetLastError(WSANOTINITIALISED);
1672 return SOCKET_ERROR;
1676 /***********************************************************************
1677 * WSAGetLastError (WS2_32.111)
1679 INT WINAPI WSAGetLastError(void)
1681 return GetLastError();
1684 /***********************************************************************
1685 * WSASetLastError (WS2_32.112)
1687 void WINAPI WSASetLastError(INT iError) {
1688 SetLastError(iError);
1691 static struct WS_hostent *check_buffer_he(int size)
1693 struct per_thread_data * ptb = get_per_thread_data();
1694 if (ptb->he_buffer)
1696 if (ptb->he_len >= size ) return ptb->he_buffer;
1697 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1699 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
1700 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
1701 return ptb->he_buffer;
1704 static struct WS_servent *check_buffer_se(int size)
1706 struct per_thread_data * ptb = get_per_thread_data();
1707 if (ptb->se_buffer)
1709 if (ptb->se_len >= size ) return ptb->se_buffer;
1710 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1712 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
1713 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
1714 return ptb->se_buffer;
1717 static struct WS_protoent *check_buffer_pe(int size)
1719 struct per_thread_data * ptb = get_per_thread_data();
1720 if (ptb->pe_buffer)
1722 if (ptb->pe_len >= size ) return ptb->pe_buffer;
1723 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1725 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
1726 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
1727 return ptb->pe_buffer;
1730 /* ----------------------------------- i/o APIs */
1732 static inline BOOL supported_pf(int pf)
1734 switch (pf)
1736 case WS_AF_INET:
1737 case WS_AF_INET6:
1738 return TRUE;
1739 #ifdef HAS_IPX
1740 case WS_AF_IPX:
1741 return TRUE;
1742 #endif
1743 #ifdef HAS_IRDA
1744 case WS_AF_IRDA:
1745 return TRUE;
1746 #endif
1747 default:
1748 return FALSE;
1752 static inline BOOL supported_protocol(int protocol)
1754 int i;
1755 for (i = 0; i < sizeof(valid_protocols) / sizeof(valid_protocols[0]); i++)
1756 if (protocol == valid_protocols[i])
1757 return TRUE;
1758 return FALSE;
1761 /**********************************************************************/
1763 /* Returns the length of the converted address if successful, 0 if it was too
1764 * small to start with or unknown family or invalid address buffer.
1766 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
1767 union generic_unix_sockaddr *uaddr)
1769 unsigned int uaddrlen = 0;
1771 if (!wsaddr)
1772 return 0;
1774 switch (wsaddr->sa_family)
1776 #ifdef HAS_IPX
1777 case WS_AF_IPX:
1779 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
1780 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
1782 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
1783 return 0;
1785 uaddrlen = sizeof(struct sockaddr_ipx);
1786 memset( uaddr, 0, uaddrlen );
1787 uipx->sipx_family=AF_IPX;
1788 uipx->sipx_port=wsipx->sa_socket;
1789 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1790 * in one go
1792 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
1793 #ifdef IPX_FRAME_NONE
1794 uipx->sipx_type=IPX_FRAME_NONE;
1795 #endif
1796 break;
1798 #endif
1799 case WS_AF_INET6: {
1800 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
1801 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
1803 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1804 * scope_id, one without.
1806 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
1807 uaddrlen = sizeof(struct sockaddr_in6);
1808 memset( uaddr, 0, uaddrlen );
1809 uin6->sin6_family = AF_INET6;
1810 uin6->sin6_port = win6->sin6_port;
1811 uin6->sin6_flowinfo = win6->sin6_flowinfo;
1812 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1813 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
1814 #endif
1815 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
1816 break;
1818 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
1819 return 0;
1821 case WS_AF_INET: {
1822 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
1823 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
1825 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
1826 return 0;
1827 uaddrlen = sizeof(struct sockaddr_in);
1828 memset( uaddr, 0, uaddrlen );
1829 uin->sin_family = AF_INET;
1830 uin->sin_port = win->sin_port;
1831 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
1832 break;
1834 #ifdef HAS_IRDA
1835 case WS_AF_IRDA: {
1836 struct sockaddr_irda *uin = (struct sockaddr_irda *)uaddr;
1837 const SOCKADDR_IRDA *win = (const SOCKADDR_IRDA *)wsaddr;
1839 if (wsaddrlen < sizeof(SOCKADDR_IRDA))
1840 return 0;
1841 uaddrlen = sizeof(struct sockaddr_irda);
1842 memset( uaddr, 0, uaddrlen );
1843 uin->sir_family = AF_IRDA;
1844 if (!strncmp( win->irdaServiceName, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1846 unsigned int lsap_sel = 0;
1848 sscanf( win->irdaServiceName, "LSAP-SEL%u", &lsap_sel );
1849 uin->sir_lsap_sel = lsap_sel;
1851 else
1853 uin->sir_lsap_sel = LSAP_ANY;
1854 memcpy( uin->sir_name, win->irdaServiceName, 25 );
1856 memcpy( &uin->sir_addr, win->irdaDeviceID, sizeof(uin->sir_addr) );
1857 break;
1859 #endif
1860 case WS_AF_UNSPEC: {
1861 /* Try to determine the needed space by the passed windows sockaddr space */
1862 switch (wsaddrlen) {
1863 default: /* likely an ipv4 address */
1864 case sizeof(struct WS_sockaddr_in):
1865 uaddrlen = sizeof(struct sockaddr_in);
1866 break;
1867 #ifdef HAS_IPX
1868 case sizeof(struct WS_sockaddr_ipx):
1869 uaddrlen = sizeof(struct sockaddr_ipx);
1870 break;
1871 #endif
1872 #ifdef HAS_IRDA
1873 case sizeof(SOCKADDR_IRDA):
1874 uaddrlen = sizeof(struct sockaddr_irda);
1875 break;
1876 #endif
1877 case sizeof(struct WS_sockaddr_in6):
1878 case sizeof(struct WS_sockaddr_in6_old):
1879 uaddrlen = sizeof(struct sockaddr_in6);
1880 break;
1882 memset( uaddr, 0, uaddrlen );
1883 break;
1885 default:
1886 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
1887 return 0;
1889 return uaddrlen;
1892 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
1894 switch (uaddr->sa_family)
1896 #ifdef HAS_IPX
1897 case AF_IPX:
1899 static const struct sockaddr_ipx emptyAddr;
1900 struct sockaddr_ipx *ipx = (struct sockaddr_ipx*) uaddr;
1901 return ipx->sipx_port
1902 || memcmp(&ipx->sipx_network, &emptyAddr.sipx_network, sizeof(emptyAddr.sipx_network))
1903 || memcmp(&ipx->sipx_node, &emptyAddr.sipx_node, sizeof(emptyAddr.sipx_node));
1905 #endif
1906 case AF_INET6:
1908 static const struct sockaddr_in6 emptyAddr;
1909 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
1910 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
1912 case AF_INET:
1914 static const struct sockaddr_in emptyAddr;
1915 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
1916 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
1918 case AF_UNSPEC:
1919 return FALSE;
1920 default:
1921 FIXME("unknown address family %d\n", uaddr->sa_family);
1922 return TRUE;
1926 /* Returns -1 if getsockname fails, 0 if not bound, 1 otherwise */
1927 static int is_fd_bound(int fd, union generic_unix_sockaddr *uaddr, socklen_t *uaddrlen)
1929 union generic_unix_sockaddr inaddr;
1930 socklen_t inlen;
1931 int res;
1933 if (!uaddr) uaddr = &inaddr;
1934 if (!uaddrlen) uaddrlen = &inlen;
1936 *uaddrlen = sizeof(inaddr);
1937 res = getsockname(fd, &uaddr->addr, uaddrlen);
1938 if (!res) res = is_sockaddr_bound(&uaddr->addr, *uaddrlen);
1939 return res;
1942 /* Returns 0 if successful, -1 if the buffer is too small */
1943 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
1945 int res;
1947 switch(uaddr->sa_family)
1949 #ifdef HAS_IPX
1950 case AF_IPX:
1952 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
1953 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
1955 res=-1;
1956 switch (*wsaddrlen) /* how much can we copy? */
1958 default:
1959 res=0; /* enough */
1960 *wsaddrlen = sizeof(*wsipx);
1961 wsipx->sa_socket=uipx->sipx_port;
1962 /* fall through */
1963 case 13:
1964 case 12:
1965 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
1966 /* fall through */
1967 case 11:
1968 case 10:
1969 case 9:
1970 case 8:
1971 case 7:
1972 case 6:
1973 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1974 /* fall through */
1975 case 5:
1976 case 4:
1977 case 3:
1978 case 2:
1979 wsipx->sa_family=WS_AF_IPX;
1980 /* fall through */
1981 case 1:
1982 case 0:
1983 /* way too small */
1984 break;
1987 break;
1988 #endif
1989 #ifdef HAS_IRDA
1990 case AF_IRDA: {
1991 const struct sockaddr_irda *uin = (const struct sockaddr_irda *)uaddr;
1992 SOCKADDR_IRDA *win = (SOCKADDR_IRDA *)wsaddr;
1994 if (*wsaddrlen < sizeof(SOCKADDR_IRDA))
1995 return -1;
1996 win->irdaAddressFamily = WS_AF_IRDA;
1997 memcpy( win->irdaDeviceID, &uin->sir_addr, sizeof(win->irdaDeviceID) );
1998 if (uin->sir_lsap_sel != LSAP_ANY)
1999 sprintf( win->irdaServiceName, "LSAP-SEL%u", uin->sir_lsap_sel );
2000 else
2001 memcpy( win->irdaServiceName, uin->sir_name,
2002 sizeof(win->irdaServiceName) );
2003 return 0;
2005 #endif
2006 case AF_INET6: {
2007 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
2008 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
2010 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
2011 return -1;
2012 win6old->sin6_family = WS_AF_INET6;
2013 win6old->sin6_port = uin6->sin6_port;
2014 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
2015 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
2016 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
2017 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
2018 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
2019 win6->sin6_scope_id = uin6->sin6_scope_id;
2020 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
2022 else
2023 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
2024 #else
2025 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
2026 #endif
2027 return 0;
2029 case AF_INET: {
2030 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
2031 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
2033 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
2034 return -1;
2035 win->sin_family = WS_AF_INET;
2036 win->sin_port = uin->sin_port;
2037 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
2038 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
2039 *wsaddrlen = sizeof(struct WS_sockaddr_in);
2040 return 0;
2042 case AF_UNSPEC: {
2043 memset(wsaddr,0,*wsaddrlen);
2044 return 0;
2046 default:
2047 FIXME("Unknown address family %d\n", uaddr->sa_family);
2048 return -1;
2050 return res;
2053 static INT WS_DuplicateSocket(BOOL unicode, SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo)
2055 HANDLE hProcess;
2056 int size;
2057 WSAPROTOCOL_INFOW infow;
2059 TRACE("(unicode %d, socket %04lx, processid %x, buffer %p)\n",
2060 unicode, s, dwProcessId, lpProtocolInfo);
2062 if (!ws_protocol_info(s, unicode, &infow, &size))
2063 return SOCKET_ERROR;
2065 if (!(hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId)))
2067 SetLastError(WSAEINVAL);
2068 return SOCKET_ERROR;
2071 if (!lpProtocolInfo)
2073 CloseHandle(hProcess);
2074 SetLastError(WSAEFAULT);
2075 return SOCKET_ERROR;
2078 /* I don't know what the real Windoze does next, this is a hack */
2079 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
2080 * the target use the global duplicate, or we could copy a reference to us to the structure
2081 * and let the target duplicate it from us, but let's do it as simple as possible */
2082 memcpy(lpProtocolInfo, &infow, size);
2083 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
2084 hProcess, (LPHANDLE)&lpProtocolInfo->dwServiceFlags3,
2085 0, FALSE, DUPLICATE_SAME_ACCESS);
2086 CloseHandle(hProcess);
2087 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
2088 return 0;
2091 /*****************************************************************************
2092 * WS_EnterSingleProtocolW [internal]
2094 * enters the protocol information of one given protocol into the given
2095 * buffer.
2097 * RETURNS
2098 * TRUE if a protocol was entered into the buffer.
2100 * BUGS
2101 * - only implemented for IPX, SPX, SPXII, TCP, UDP
2102 * - there is no check that the operating system supports the returned
2103 * protocols
2105 static BOOL WS_EnterSingleProtocolW( INT protocol, WSAPROTOCOL_INFOW* info )
2107 memset( info, 0, sizeof(WSAPROTOCOL_INFOW) );
2108 info->iProtocol = protocol;
2110 switch (protocol)
2112 case WS_IPPROTO_TCP:
2113 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_EXPEDITED_DATA |
2114 XP1_GRACEFUL_CLOSE | XP1_GUARANTEED_ORDER |
2115 XP1_GUARANTEED_DELIVERY;
2116 info->ProviderId = ProviderIdIP;
2117 info->dwCatalogEntryId = 0x3e9;
2118 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
2119 info->ProtocolChain.ChainLen = 1;
2120 info->iVersion = 2;
2121 info->iAddressFamily = WS_AF_INET;
2122 info->iMaxSockAddr = 0x10;
2123 info->iMinSockAddr = 0x10;
2124 info->iSocketType = WS_SOCK_STREAM;
2125 strcpyW( info->szProtocol, NameTcpW );
2126 break;
2128 case WS_IPPROTO_UDP:
2129 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_SUPPORT_BROADCAST |
2130 XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED |
2131 XP1_CONNECTIONLESS;
2132 info->ProviderId = ProviderIdIP;
2133 info->dwCatalogEntryId = 0x3ea;
2134 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
2135 info->ProtocolChain.ChainLen = 1;
2136 info->iVersion = 2;
2137 info->iAddressFamily = WS_AF_INET;
2138 info->iMaxSockAddr = 0x10;
2139 info->iMinSockAddr = 0x10;
2140 info->iSocketType = WS_SOCK_DGRAM;
2141 info->dwMessageSize = 0xffbb;
2142 strcpyW( info->szProtocol, NameUdpW );
2143 break;
2145 case WS_NSPROTO_IPX:
2146 info->dwServiceFlags1 = XP1_PARTIAL_MESSAGE | XP1_SUPPORT_BROADCAST |
2147 XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED |
2148 XP1_CONNECTIONLESS;
2149 info->ProviderId = ProviderIdIPX;
2150 info->dwCatalogEntryId = 0x406;
2151 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
2152 info->ProtocolChain.ChainLen = 1;
2153 info->iVersion = 2;
2154 info->iAddressFamily = WS_AF_IPX;
2155 info->iMaxSockAddr = 0x10;
2156 info->iMinSockAddr = 0x0e;
2157 info->iSocketType = WS_SOCK_DGRAM;
2158 info->iProtocolMaxOffset = 0xff;
2159 info->dwMessageSize = 0x240;
2160 strcpyW( info->szProtocol, NameIpxW );
2161 break;
2163 case WS_NSPROTO_SPX:
2164 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_PSEUDO_STREAM |
2165 XP1_MESSAGE_ORIENTED | XP1_GUARANTEED_ORDER |
2166 XP1_GUARANTEED_DELIVERY;
2167 info->ProviderId = ProviderIdSPX;
2168 info->dwCatalogEntryId = 0x407;
2169 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
2170 info->ProtocolChain.ChainLen = 1;
2171 info->iVersion = 2;
2172 info->iAddressFamily = WS_AF_IPX;
2173 info->iMaxSockAddr = 0x10;
2174 info->iMinSockAddr = 0x0e;
2175 info->iSocketType = WS_SOCK_SEQPACKET;
2176 info->dwMessageSize = 0xffffffff;
2177 strcpyW( info->szProtocol, NameSpxW );
2178 break;
2180 case WS_NSPROTO_SPXII:
2181 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_GRACEFUL_CLOSE |
2182 XP1_PSEUDO_STREAM | XP1_MESSAGE_ORIENTED |
2183 XP1_GUARANTEED_ORDER | XP1_GUARANTEED_DELIVERY;
2184 info->ProviderId = ProviderIdSPX;
2185 info->dwCatalogEntryId = 0x409;
2186 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
2187 info->ProtocolChain.ChainLen = 1;
2188 info->iVersion = 2;
2189 info->iAddressFamily = WS_AF_IPX;
2190 info->iMaxSockAddr = 0x10;
2191 info->iMinSockAddr = 0x0e;
2192 info->iSocketType = WS_SOCK_SEQPACKET;
2193 info->dwMessageSize = 0xffffffff;
2194 strcpyW( info->szProtocol, NameSpxIIW );
2195 break;
2197 default:
2198 FIXME("unknown Protocol <0x%08x>\n", protocol);
2199 return FALSE;
2201 return TRUE;
2204 /*****************************************************************************
2205 * WS_EnterSingleProtocolA [internal]
2207 * see function WS_EnterSingleProtocolW
2210 static BOOL WS_EnterSingleProtocolA( INT protocol, WSAPROTOCOL_INFOA* info )
2212 WSAPROTOCOL_INFOW infow;
2213 INT ret;
2214 memset( info, 0, sizeof(WSAPROTOCOL_INFOA) );
2216 ret = WS_EnterSingleProtocolW( protocol, &infow );
2217 if (ret)
2219 /* convert the structure from W to A */
2220 memcpy( info, &infow, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
2221 WideCharToMultiByte( CP_ACP, 0, infow.szProtocol, -1,
2222 info->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL );
2225 return ret;
2228 static INT WS_EnumProtocols( BOOL unicode, const INT *protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
2230 INT i = 0, items = 0;
2231 DWORD size = 0;
2232 union _info
2234 LPWSAPROTOCOL_INFOA a;
2235 LPWSAPROTOCOL_INFOW w;
2236 } info;
2237 info.w = buffer;
2239 if (!protocols) protocols = valid_protocols;
2241 while (protocols[i])
2243 if(supported_protocol(protocols[i++]))
2244 items++;
2247 size = items * (unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA));
2249 TRACE("unicode %d, protocols %p, buffer %p, length %p %d, items %d, required %d\n",
2250 unicode, protocols, buffer, len, len ? *len : 0, items, size);
2252 if (*len < size || !buffer)
2254 *len = size;
2255 SetLastError(WSAENOBUFS);
2256 return SOCKET_ERROR;
2259 for (i = items = 0; protocols[i]; i++)
2261 if (!supported_protocol(protocols[i])) continue;
2262 if (unicode)
2264 if (WS_EnterSingleProtocolW( protocols[i], &info.w[items] ))
2265 items++;
2267 else
2269 if (WS_EnterSingleProtocolA( protocols[i], &info.a[items] ))
2270 items++;
2273 return items;
2276 static BOOL ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size)
2278 NTSTATUS status;
2280 *size = unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA);
2281 memset(buffer, 0, *size);
2283 SERVER_START_REQ( get_socket_info )
2285 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
2286 status = wine_server_call( req );
2287 if (!status)
2289 buffer->iAddressFamily = convert_af_u2w(reply->family);
2290 buffer->iSocketType = convert_socktype_u2w(reply->type);
2291 buffer->iProtocol = convert_proto_u2w(reply->protocol);
2294 SERVER_END_REQ;
2296 if (status)
2298 unsigned int err = NtStatusToWSAError( status );
2299 SetLastError( err == WSAEBADF ? WSAENOTSOCK : err );
2300 return FALSE;
2303 if (unicode)
2304 WS_EnterSingleProtocolW( buffer->iProtocol, buffer);
2305 else
2306 WS_EnterSingleProtocolA( buffer->iProtocol, (WSAPROTOCOL_INFOA *)buffer);
2308 return TRUE;
2311 /**************************************************************************
2312 * Functions for handling overlapped I/O
2313 **************************************************************************/
2315 /* user APC called upon async completion */
2316 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
2318 struct ws2_async *wsa = arg;
2320 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
2321 iosb->Information, wsa->user_overlapped,
2322 wsa->flags );
2323 release_async_io( &wsa->io );
2326 /***********************************************************************
2327 * WS2_recv (INTERNAL)
2329 * Workhorse for both synchronous and asynchronous recv() operations.
2331 static int WS2_recv( int fd, struct ws2_async *wsa, int flags )
2333 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2334 char pktbuf[512];
2335 #endif
2336 struct msghdr hdr;
2337 union generic_unix_sockaddr unix_sockaddr;
2338 int n;
2340 hdr.msg_name = NULL;
2342 if (wsa->addr)
2344 hdr.msg_namelen = sizeof(unix_sockaddr);
2345 hdr.msg_name = &unix_sockaddr;
2347 else
2348 hdr.msg_namelen = 0;
2350 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
2351 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
2352 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2353 hdr.msg_accrights = NULL;
2354 hdr.msg_accrightslen = 0;
2355 #else
2356 hdr.msg_control = pktbuf;
2357 hdr.msg_controllen = sizeof(pktbuf);
2358 hdr.msg_flags = 0;
2359 #endif
2361 while ((n = __wine_locked_recvmsg( fd, &hdr, flags )) == -1)
2363 if (errno != EINTR)
2364 return -1;
2367 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2368 if (wsa->control)
2370 ERR("Message control headers cannot be properly supported on this system.\n");
2371 wsa->control->len = 0;
2373 #else
2374 if (wsa->control && !convert_control_headers(&hdr, wsa->control))
2376 WARN("Application passed insufficient room for control headers.\n");
2377 *wsa->lpFlags |= WS_MSG_CTRUNC;
2378 errno = EMSGSIZE;
2379 return -1;
2381 #endif
2383 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
2384 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
2386 * quoting linux 2.6 net/ipv4/tcp.c:
2387 * "According to UNIX98, msg_name/msg_namelen are ignored
2388 * on connected socket. I was just happy when found this 8) --ANK"
2390 * likewise MSDN says that lpFrom and lpFromlen are ignored for
2391 * connection-oriented sockets, so don't try to update lpFrom.
2393 if (wsa->addr && hdr.msg_namelen)
2394 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
2396 return n;
2399 /***********************************************************************
2400 * WS2_async_recv (INTERNAL)
2402 * Handler for overlapped recv() operations.
2404 static NTSTATUS WS2_async_recv( void *user, IO_STATUS_BLOCK *iosb, NTSTATUS status )
2406 struct ws2_async *wsa = user;
2407 int result = 0, fd;
2409 switch (status)
2411 case STATUS_ALERTED:
2412 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
2413 break;
2415 result = WS2_recv( fd, wsa, convert_flags(wsa->flags) );
2416 wine_server_release_fd( wsa->hSocket, fd );
2417 if (result >= 0)
2419 status = STATUS_SUCCESS;
2420 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
2422 else
2424 if (errno == EAGAIN)
2426 status = STATUS_PENDING;
2427 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
2429 else
2431 result = 0;
2432 status = wsaErrStatus();
2435 break;
2437 if (status != STATUS_PENDING)
2439 iosb->u.Status = status;
2440 iosb->Information = result;
2441 if (!wsa->completion_func)
2442 release_async_io( &wsa->io );
2444 return status;
2447 /***********************************************************************
2448 * WS2_async_accept_recv (INTERNAL)
2450 * This function is used to finish the read part of an accept request. It is
2451 * needed to place the completion on the correct socket (listener).
2453 static NTSTATUS WS2_async_accept_recv( void *user, IO_STATUS_BLOCK *iosb, NTSTATUS status )
2455 struct ws2_accept_async *wsa = user;
2457 status = WS2_async_recv( wsa->read, iosb, status );
2458 if (status == STATUS_PENDING)
2459 return status;
2461 if (wsa->cvalue)
2462 WS_AddCompletion( HANDLE2SOCKET(wsa->listen_socket), wsa->cvalue, iosb->u.Status, iosb->Information );
2464 release_async_io( &wsa->io );
2465 return status;
2468 /***********************************************************************
2469 * WS2_async_accept (INTERNAL)
2471 * This is the function called to satisfy the AcceptEx callback
2473 static NTSTATUS WS2_async_accept( void *user, IO_STATUS_BLOCK *iosb, NTSTATUS status )
2475 struct ws2_accept_async *wsa = user;
2476 int len;
2477 char *addr;
2479 TRACE("status: 0x%x listen: %p, accept: %p\n", status, wsa->listen_socket, wsa->accept_socket);
2481 if (status == STATUS_ALERTED)
2483 SERVER_START_REQ( accept_into_socket )
2485 req->lhandle = wine_server_obj_handle( wsa->listen_socket );
2486 req->ahandle = wine_server_obj_handle( wsa->accept_socket );
2487 status = wine_server_call( req );
2489 SERVER_END_REQ;
2491 if (status == STATUS_CANT_WAIT)
2492 return STATUS_PENDING;
2494 if (status == STATUS_INVALID_HANDLE)
2496 FIXME("AcceptEx accepting socket closed but request was not cancelled\n");
2497 status = STATUS_CANCELLED;
2500 else if (status == STATUS_HANDLES_CLOSED)
2501 status = STATUS_CANCELLED; /* strange windows behavior */
2503 if (status != STATUS_SUCCESS)
2504 goto finish;
2506 /* WS2 Spec says size param is extra 16 bytes long...what do we put in it? */
2507 addr = ((char *)wsa->buf) + wsa->data_len;
2508 len = wsa->local_len - sizeof(int);
2509 WS_getsockname(HANDLE2SOCKET(wsa->accept_socket),
2510 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
2511 *(int *)addr = len;
2513 addr += wsa->local_len;
2514 len = wsa->remote_len - sizeof(int);
2515 WS_getpeername(HANDLE2SOCKET(wsa->accept_socket),
2516 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
2517 *(int *)addr = len;
2519 if (!wsa->read)
2520 goto finish;
2522 wsa->io.callback = WS2_async_accept_recv;
2523 status = register_async( ASYNC_TYPE_READ, wsa->accept_socket, &wsa->io,
2524 wsa->user_overlapped->hEvent, NULL, NULL, iosb);
2526 if (status != STATUS_PENDING)
2527 goto finish;
2529 /* The APC has finished but no completion should be sent for the operation yet, additional processing
2530 * needs to be performed by WS2_async_accept_recv() first. */
2531 return STATUS_MORE_PROCESSING_REQUIRED;
2533 finish:
2534 iosb->u.Status = status;
2535 iosb->Information = 0;
2537 if (wsa->read) release_async_io( &wsa->read->io );
2538 release_async_io( &wsa->io );
2539 return status;
2542 /***********************************************************************
2543 * WS2_send (INTERNAL)
2545 * Workhorse for both synchronous and asynchronous send() operations.
2547 static int WS2_send( int fd, struct ws2_async *wsa, int flags )
2549 struct msghdr hdr;
2550 union generic_unix_sockaddr unix_addr;
2551 int n, ret;
2553 hdr.msg_name = NULL;
2554 hdr.msg_namelen = 0;
2556 if (wsa->addr)
2558 hdr.msg_name = &unix_addr;
2559 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
2560 if ( !hdr.msg_namelen )
2562 errno = EFAULT;
2563 return -1;
2566 #if defined(HAS_IPX) && defined(SOL_IPX)
2567 if(wsa->addr->sa_family == WS_AF_IPX)
2569 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
2570 int val=0;
2571 socklen_t len = sizeof(int);
2573 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
2574 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
2575 * the packet type and then we can retrieve it using getsockopt. After that we can set the
2576 * ipx type in the sockaddr_opx structure with the stored value.
2578 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
2579 uipx->sipx_type = val;
2581 #endif
2584 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
2585 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
2586 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2587 hdr.msg_accrights = NULL;
2588 hdr.msg_accrightslen = 0;
2589 #else
2590 hdr.msg_control = NULL;
2591 hdr.msg_controllen = 0;
2592 hdr.msg_flags = 0;
2593 #endif
2595 while ((ret = sendmsg(fd, &hdr, flags)) == -1)
2597 if (errno != EINTR)
2598 return -1;
2601 n = ret;
2602 while (wsa->first_iovec < wsa->n_iovecs && wsa->iovec[wsa->first_iovec].iov_len <= n)
2603 n -= wsa->iovec[wsa->first_iovec++].iov_len;
2604 if (wsa->first_iovec < wsa->n_iovecs)
2606 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
2607 wsa->iovec[wsa->first_iovec].iov_len -= n;
2609 return ret;
2612 /***********************************************************************
2613 * WS2_async_send (INTERNAL)
2615 * Handler for overlapped send() operations.
2617 static NTSTATUS WS2_async_send( void *user, IO_STATUS_BLOCK *iosb, NTSTATUS status )
2619 struct ws2_async *wsa = user;
2620 int result = 0, fd;
2622 switch (status)
2624 case STATUS_ALERTED:
2625 if ( wsa->n_iovecs <= wsa->first_iovec )
2627 /* Nothing to do */
2628 status = STATUS_SUCCESS;
2629 break;
2631 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
2632 break;
2634 /* check to see if the data is ready (non-blocking) */
2635 result = WS2_send( fd, wsa, convert_flags(wsa->flags) );
2636 wine_server_release_fd( wsa->hSocket, fd );
2638 if (result >= 0)
2640 if (wsa->first_iovec < wsa->n_iovecs)
2641 status = STATUS_PENDING;
2642 else
2643 status = STATUS_SUCCESS;
2645 iosb->Information += result;
2647 else if (errno == EAGAIN)
2649 status = STATUS_PENDING;
2651 else
2653 status = wsaErrStatus();
2655 break;
2657 if (status != STATUS_PENDING)
2659 iosb->u.Status = status;
2660 if (!wsa->completion_func)
2661 release_async_io( &wsa->io );
2663 return status;
2666 /***********************************************************************
2667 * WS2_async_shutdown (INTERNAL)
2669 * Handler for shutdown() operations on overlapped sockets.
2671 static NTSTATUS WS2_async_shutdown( void *user, IO_STATUS_BLOCK *iosb, NTSTATUS status )
2673 struct ws2_async_shutdown *wsa = user;
2674 int fd, err = 1;
2676 switch (status)
2678 case STATUS_ALERTED:
2679 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
2680 break;
2682 switch ( wsa->type )
2684 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
2685 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
2687 status = err ? wsaErrStatus() : STATUS_SUCCESS;
2688 wine_server_release_fd( wsa->hSocket, fd );
2689 break;
2691 iosb->u.Status = status;
2692 iosb->Information = 0;
2693 release_async_io( &wsa->io );
2694 return status;
2697 /***********************************************************************
2698 * WS2_register_async_shutdown (INTERNAL)
2700 * Helper function for WS_shutdown() on overlapped sockets.
2702 static int WS2_register_async_shutdown( SOCKET s, int type )
2704 struct ws2_async_shutdown *wsa;
2705 NTSTATUS status;
2707 TRACE("socket %04lx type %d\n", s, type);
2709 wsa = (struct ws2_async_shutdown *)alloc_async_io( sizeof(*wsa), WS2_async_shutdown );
2710 if ( !wsa )
2711 return WSAEFAULT;
2713 wsa->hSocket = SOCKET2HANDLE(s);
2714 wsa->type = type;
2716 status = register_async( type, wsa->hSocket, &wsa->io, 0, NULL, NULL, &wsa->iosb );
2717 if (status != STATUS_PENDING)
2719 HeapFree( GetProcessHeap(), 0, wsa );
2720 return NtStatusToWSAError( status );
2722 return 0;
2725 /***********************************************************************
2726 * accept (WS2_32.1)
2728 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr, int *addrlen32)
2730 NTSTATUS status;
2731 SOCKET as;
2732 BOOL is_blocking;
2734 TRACE("socket %04lx\n", s );
2735 status = _is_blocking(s, &is_blocking);
2736 if (status)
2737 goto error;
2739 do {
2740 /* try accepting first (if there is a deferred connection) */
2741 SERVER_START_REQ( accept_socket )
2743 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
2744 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
2745 req->attributes = OBJ_INHERIT;
2746 status = wine_server_call( req );
2747 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
2749 SERVER_END_REQ;
2750 if (!status)
2752 if (addr && addrlen32 && WS_getpeername(as, addr, addrlen32))
2754 WS_closesocket(as);
2755 return SOCKET_ERROR;
2757 TRACE("\taccepted %04lx\n", as);
2758 return as;
2760 if (is_blocking && status == STATUS_CANT_WAIT)
2762 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2763 /* block here */
2764 do_block(fd, POLLIN, -1);
2765 _sync_sock_state(s); /* let wineserver notice connection */
2766 release_sock_fd( s, fd );
2768 } while (is_blocking && status == STATUS_CANT_WAIT);
2770 error:
2771 set_error(status);
2772 WARN(" -> ERROR %d\n", GetLastError());
2773 return INVALID_SOCKET;
2776 /***********************************************************************
2777 * AcceptEx
2779 static BOOL WINAPI WS2_AcceptEx(SOCKET listener, SOCKET acceptor, PVOID dest, DWORD dest_len,
2780 DWORD local_addr_len, DWORD rem_addr_len, LPDWORD received,
2781 LPOVERLAPPED overlapped)
2783 DWORD status;
2784 struct ws2_accept_async *wsa;
2785 int fd;
2787 TRACE("(%04lx, %04lx, %p, %d, %d, %d, %p, %p)\n", listener, acceptor, dest, dest_len, local_addr_len,
2788 rem_addr_len, received, overlapped);
2790 if (!dest)
2792 SetLastError(WSAEINVAL);
2793 return FALSE;
2796 if (!overlapped)
2798 SetLastError(WSA_INVALID_PARAMETER);
2799 return FALSE;
2802 if (!rem_addr_len)
2804 SetLastError(WSAEFAULT);
2805 return FALSE;
2808 fd = get_sock_fd( listener, FILE_READ_DATA, NULL );
2809 if (fd == -1)
2811 SetLastError(WSAENOTSOCK);
2812 return FALSE;
2814 release_sock_fd( listener, fd );
2816 fd = get_sock_fd( acceptor, FILE_READ_DATA, NULL );
2817 if (fd == -1)
2819 SetLastError(WSAENOTSOCK);
2820 return FALSE;
2822 release_sock_fd( acceptor, fd );
2824 wsa = (struct ws2_accept_async *)alloc_async_io( sizeof(*wsa), WS2_async_accept );
2825 if(!wsa)
2827 SetLastError(WSAEFAULT);
2828 return FALSE;
2831 wsa->listen_socket = SOCKET2HANDLE(listener);
2832 wsa->accept_socket = SOCKET2HANDLE(acceptor);
2833 wsa->user_overlapped = overlapped;
2834 wsa->cvalue = !((ULONG_PTR)overlapped->hEvent & 1) ? (ULONG_PTR)overlapped : 0;
2835 wsa->buf = dest;
2836 wsa->data_len = dest_len;
2837 wsa->local_len = local_addr_len;
2838 wsa->remote_len = rem_addr_len;
2839 wsa->read = NULL;
2841 if (wsa->data_len)
2843 /* set up a read request if we need it */
2844 wsa->read = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[1]), WS2_async_accept_recv );
2845 if (!wsa->read)
2847 HeapFree( GetProcessHeap(), 0, wsa );
2848 SetLastError(WSAEFAULT);
2849 return FALSE;
2852 wsa->read->hSocket = wsa->accept_socket;
2853 wsa->read->flags = 0;
2854 wsa->read->lpFlags = &wsa->read->flags;
2855 wsa->read->addr = NULL;
2856 wsa->read->addrlen.ptr = NULL;
2857 wsa->read->control = NULL;
2858 wsa->read->n_iovecs = 1;
2859 wsa->read->first_iovec = 0;
2860 wsa->read->completion_func = NULL;
2861 wsa->read->iovec[0].iov_base = wsa->buf;
2862 wsa->read->iovec[0].iov_len = wsa->data_len;
2865 status = register_async( ASYNC_TYPE_READ, SOCKET2HANDLE(listener), &wsa->io,
2866 overlapped->hEvent, NULL, (void *)wsa->cvalue, (IO_STATUS_BLOCK *)overlapped );
2868 if(status != STATUS_PENDING)
2870 HeapFree( GetProcessHeap(), 0, wsa->read );
2871 HeapFree( GetProcessHeap(), 0, wsa );
2874 SetLastError( NtStatusToWSAError(status) );
2875 return FALSE;
2878 /***********************************************************************
2879 * WS2_ReadFile (INTERNAL)
2881 * Perform an APC-safe ReadFile operation
2883 static NTSTATUS WS2_ReadFile(HANDLE hFile, PIO_STATUS_BLOCK io_status, char* buffer, ULONG length,
2884 PLARGE_INTEGER offset)
2886 int result = -1, unix_handle;
2887 unsigned int options;
2888 NTSTATUS status;
2890 TRACE( "(%p,%p,0x%08x)\n", hFile, buffer,length );
2892 status = wine_server_handle_to_fd( hFile, FILE_READ_DATA, &unix_handle, &options );
2893 if (status) return status;
2895 while (result == -1)
2897 if (offset->QuadPart != FILE_USE_FILE_POINTER_POSITION)
2898 result = pread( unix_handle, buffer, length, offset->QuadPart );
2899 else
2900 result = read( unix_handle, buffer, length );
2901 if (errno != EINTR)
2902 break;
2905 if (!result)
2906 status = (length ? STATUS_END_OF_FILE : STATUS_SUCCESS);
2907 else if (result != -1)
2908 status = STATUS_SUCCESS;
2909 else if (errno != EAGAIN)
2910 status = wsaErrStatus();
2911 else
2912 status = STATUS_PENDING;
2914 wine_server_release_fd( hFile, unix_handle );
2915 TRACE("= 0x%08x (%d)\n", status, result);
2916 if (status == STATUS_SUCCESS || status == STATUS_END_OF_FILE)
2918 io_status->u.Status = status;
2919 io_status->Information = result;
2922 return status;
2925 /***********************************************************************
2926 * WS2_transmitfile_getbuffer (INTERNAL)
2928 * Pick the appropriate buffer for a TransmitFile send operation.
2930 static NTSTATUS WS2_transmitfile_getbuffer( int fd, struct ws2_transmitfile_async *wsa )
2932 /* send any incomplete writes from a previous iteration */
2933 if (wsa->write.first_iovec < wsa->write.n_iovecs)
2934 return STATUS_PENDING;
2936 /* process the header (if applicable) */
2937 if (wsa->buffers.Head)
2939 wsa->write.first_iovec = 0;
2940 wsa->write.n_iovecs = 1;
2941 wsa->write.iovec[0].iov_base = wsa->buffers.Head;
2942 wsa->write.iovec[0].iov_len = wsa->buffers.HeadLength;
2943 wsa->buffers.Head = NULL;
2944 return STATUS_PENDING;
2947 /* process the main file */
2948 if (wsa->file)
2950 DWORD bytes_per_send = wsa->bytes_per_send;
2951 IO_STATUS_BLOCK iosb;
2952 NTSTATUS status;
2954 iosb.Information = 0;
2955 /* when the size of the transfer is limited ensure that we don't go past that limit */
2956 if (wsa->file_bytes != 0)
2957 bytes_per_send = min(bytes_per_send, wsa->file_bytes - wsa->file_read);
2958 status = WS2_ReadFile( wsa->file, &iosb, wsa->buffer, bytes_per_send, &wsa->offset );
2959 if (wsa->offset.QuadPart != FILE_USE_FILE_POINTER_POSITION)
2960 wsa->offset.QuadPart += iosb.Information;
2961 if (status == STATUS_END_OF_FILE)
2962 wsa->file = NULL; /* continue on to the footer */
2963 else if (status != STATUS_SUCCESS)
2964 return status;
2965 else
2967 if (iosb.Information)
2969 wsa->write.first_iovec = 0;
2970 wsa->write.n_iovecs = 1;
2971 wsa->write.iovec[0].iov_base = wsa->buffer;
2972 wsa->write.iovec[0].iov_len = iosb.Information;
2973 wsa->file_read += iosb.Information;
2976 if (wsa->file_bytes != 0 && wsa->file_read >= wsa->file_bytes)
2977 wsa->file = NULL;
2979 return STATUS_PENDING;
2983 /* send the footer (if applicable) */
2984 if (wsa->buffers.Tail)
2986 wsa->write.first_iovec = 0;
2987 wsa->write.n_iovecs = 1;
2988 wsa->write.iovec[0].iov_base = wsa->buffers.Tail;
2989 wsa->write.iovec[0].iov_len = wsa->buffers.TailLength;
2990 wsa->buffers.Tail = NULL;
2991 return STATUS_PENDING;
2994 return STATUS_SUCCESS;
2997 /***********************************************************************
2998 * WS2_transmitfile_base (INTERNAL)
3000 * Shared implementation for both synchronous and asynchronous TransmitFile.
3002 static NTSTATUS WS2_transmitfile_base( int fd, struct ws2_transmitfile_async *wsa )
3004 NTSTATUS status;
3006 status = WS2_transmitfile_getbuffer( fd, wsa );
3007 if (status == STATUS_PENDING)
3009 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)wsa->write.user_overlapped;
3010 int n;
3012 n = WS2_send( fd, &wsa->write, convert_flags(wsa->write.flags) );
3013 if (n >= 0)
3015 if (iosb) iosb->Information += n;
3017 else if (errno != EAGAIN)
3018 return wsaErrStatus();
3021 return status;
3024 /***********************************************************************
3025 * WS2_async_transmitfile (INTERNAL)
3027 * Asynchronous callback for overlapped TransmitFile operations.
3029 static NTSTATUS WS2_async_transmitfile( void *user, IO_STATUS_BLOCK *iosb, NTSTATUS status )
3031 struct ws2_transmitfile_async *wsa = user;
3032 int fd;
3034 if (status == STATUS_ALERTED)
3036 if (!(status = wine_server_handle_to_fd( wsa->write.hSocket, FILE_WRITE_DATA, &fd, NULL )))
3038 status = WS2_transmitfile_base( fd, wsa );
3039 wine_server_release_fd( wsa->write.hSocket, fd );
3041 if (status == STATUS_PENDING)
3042 return status;
3045 iosb->u.Status = status;
3046 release_async_io( &wsa->io );
3047 return status;
3050 /***********************************************************************
3051 * TransmitFile
3053 static BOOL WINAPI WS2_TransmitFile( SOCKET s, HANDLE h, DWORD file_bytes, DWORD bytes_per_send,
3054 LPOVERLAPPED overlapped, LPTRANSMIT_FILE_BUFFERS buffers,
3055 DWORD flags )
3057 union generic_unix_sockaddr uaddr;
3058 socklen_t uaddrlen = sizeof(uaddr);
3059 struct ws2_transmitfile_async *wsa;
3060 NTSTATUS status;
3061 int fd;
3063 TRACE("(%lx, %p, %d, %d, %p, %p, %d)\n", s, h, file_bytes, bytes_per_send, overlapped,
3064 buffers, flags );
3066 fd = get_sock_fd( s, FILE_WRITE_DATA, NULL );
3067 if (fd == -1)
3069 WSASetLastError( WSAENOTSOCK );
3070 return FALSE;
3072 if (getpeername( fd, &uaddr.addr, &uaddrlen ) != 0)
3074 release_sock_fd( s, fd );
3075 WSASetLastError( WSAENOTCONN );
3076 return FALSE;
3078 if (flags)
3079 FIXME("Flags are not currently supported (0x%x).\n", flags);
3081 if (h && GetFileType( h ) != FILE_TYPE_DISK)
3083 FIXME("Non-disk file handles are not currently supported.\n");
3084 release_sock_fd( s, fd );
3085 WSASetLastError( WSAEOPNOTSUPP );
3086 return FALSE;
3089 /* set reasonable defaults when requested */
3090 if (!bytes_per_send)
3091 bytes_per_send = (1 << 16); /* Depends on OS version: PAGE_SIZE, 2*PAGE_SIZE, or 2^16 */
3093 if (!(wsa = (struct ws2_transmitfile_async *)alloc_async_io( sizeof(*wsa) + bytes_per_send,
3094 WS2_async_transmitfile )))
3096 release_sock_fd( s, fd );
3097 WSASetLastError( WSAEFAULT );
3098 return FALSE;
3100 if (buffers)
3101 wsa->buffers = *buffers;
3102 else
3103 memset(&wsa->buffers, 0x0, sizeof(wsa->buffers));
3104 wsa->buffer = (char *)(wsa + 1);
3105 wsa->file = h;
3106 wsa->file_read = 0;
3107 wsa->file_bytes = file_bytes;
3108 wsa->bytes_per_send = bytes_per_send;
3109 wsa->flags = flags;
3110 wsa->offset.QuadPart = FILE_USE_FILE_POINTER_POSITION;
3111 wsa->write.hSocket = SOCKET2HANDLE(s);
3112 wsa->write.addr = NULL;
3113 wsa->write.addrlen.val = 0;
3114 wsa->write.flags = 0;
3115 wsa->write.lpFlags = &wsa->flags;
3116 wsa->write.control = NULL;
3117 wsa->write.n_iovecs = 0;
3118 wsa->write.first_iovec = 0;
3119 wsa->write.user_overlapped = overlapped;
3120 if (overlapped)
3122 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)overlapped;
3123 int status;
3125 wsa->offset.u.LowPart = overlapped->u.s.Offset;
3126 wsa->offset.u.HighPart = overlapped->u.s.OffsetHigh;
3127 iosb->u.Status = STATUS_PENDING;
3128 iosb->Information = 0;
3129 status = register_async( ASYNC_TYPE_WRITE, SOCKET2HANDLE(s), &wsa->io,
3130 overlapped->hEvent, NULL, NULL, iosb );
3131 if(status != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
3132 release_sock_fd( s, fd );
3133 WSASetLastError( NtStatusToWSAError(status) );
3134 return FALSE;
3139 status = WS2_transmitfile_base( fd, wsa );
3140 if (status == STATUS_PENDING)
3142 /* block here */
3143 do_block(fd, POLLOUT, -1);
3144 _sync_sock_state(s); /* let wineserver notice connection */
3147 while (status == STATUS_PENDING);
3148 release_sock_fd( s, fd );
3150 if (status != STATUS_SUCCESS)
3151 WSASetLastError( NtStatusToWSAError(status) );
3152 HeapFree( GetProcessHeap(), 0, wsa );
3153 return (status == STATUS_SUCCESS);
3156 /***********************************************************************
3157 * GetAcceptExSockaddrs
3159 static void WINAPI WS2_GetAcceptExSockaddrs(PVOID buffer, DWORD data_size, DWORD local_size, DWORD remote_size,
3160 struct WS_sockaddr **local_addr, LPINT local_addr_len,
3161 struct WS_sockaddr **remote_addr, LPINT remote_addr_len)
3163 char *cbuf = buffer;
3164 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer, data_size, local_size, remote_size, local_addr,
3165 local_addr_len, remote_addr, remote_addr_len );
3166 cbuf += data_size;
3168 *local_addr_len = *(int *) cbuf;
3169 *local_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
3171 cbuf += local_size;
3173 *remote_addr_len = *(int *) cbuf;
3174 *remote_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
3177 /***********************************************************************
3178 * WSASendMsg
3180 int WINAPI WSASendMsg( SOCKET s, LPWSAMSG msg, DWORD dwFlags, LPDWORD lpNumberOfBytesSent,
3181 LPWSAOVERLAPPED lpOverlapped,
3182 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
3184 if (!msg)
3186 SetLastError( WSAEFAULT );
3187 return SOCKET_ERROR;
3190 return WS2_sendto( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesSent,
3191 dwFlags, msg->name, msg->namelen,
3192 lpOverlapped, lpCompletionRoutine );
3195 /***********************************************************************
3196 * WSARecvMsg
3198 * Perform a receive operation that is capable of returning message
3199 * control headers. It is important to note that the WSAMSG parameter
3200 * must remain valid throughout the operation, even when an overlapped
3201 * receive is performed.
3203 static int WINAPI WS2_WSARecvMsg( SOCKET s, LPWSAMSG msg, LPDWORD lpNumberOfBytesRecvd,
3204 LPWSAOVERLAPPED lpOverlapped,
3205 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3207 if (!msg)
3209 SetLastError( WSAEFAULT );
3210 return SOCKET_ERROR;
3213 return WS2_recv_base( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesRecvd,
3214 &msg->dwFlags, msg->name, &msg->namelen,
3215 lpOverlapped, lpCompletionRoutine, &msg->Control );
3218 /***********************************************************************
3219 * interface_bind (INTERNAL)
3221 * Take bind() calls on any name corresponding to a local network adapter and restrict the given socket to
3222 * operating only on the specified interface. This restriction consists of two components:
3223 * 1) An outgoing packet restriction suggesting the egress interface for all packets.
3224 * 2) An incoming packet restriction dropping packets not meant for the interface.
3225 * If the function succeeds in placing these restrictions (returns TRUE) then the name for the bind() may
3226 * safely be changed to INADDR_ANY, permitting the transmission and receipt of broadcast packets on the
3227 * socket. This behavior is only relevant to UDP sockets and is needed for applications that expect to be able
3228 * to receive broadcast packets on a socket that is bound to a specific network interface.
3230 static BOOL interface_bind( SOCKET s, int fd, struct sockaddr *addr )
3232 struct sockaddr_in *in_sock = (struct sockaddr_in *) addr;
3233 in_addr_t bind_addr = in_sock->sin_addr.s_addr;
3234 PIP_ADAPTER_INFO adapters = NULL, adapter;
3235 BOOL ret = FALSE;
3236 DWORD adap_size;
3237 int enable = 1;
3239 if (bind_addr == htonl(INADDR_ANY) || bind_addr == htonl(INADDR_LOOPBACK))
3240 return FALSE; /* Not binding to a network adapter, special interface binding unnecessary. */
3241 if (_get_fd_type(fd) != SOCK_DGRAM)
3242 return FALSE; /* Special interface binding is only necessary for UDP datagrams. */
3243 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
3244 goto cleanup;
3245 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
3246 if (adapters == NULL || GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
3247 goto cleanup;
3248 /* Search the IPv4 adapter list for the appropriate binding interface */
3249 for (adapter = adapters; adapter != NULL; adapter = adapter->Next)
3251 in_addr_t adapter_addr = (in_addr_t) inet_addr(adapter->IpAddressList.IpAddress.String);
3253 if (bind_addr == adapter_addr)
3255 #if defined(IP_BOUND_IF)
3256 /* IP_BOUND_IF sets both the incoming and outgoing restriction at once */
3257 if (setsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &adapter->Index, sizeof(adapter->Index)) != 0)
3258 goto cleanup;
3259 ret = TRUE;
3260 #elif defined(LINUX_BOUND_IF)
3261 in_addr_t ifindex = (in_addr_t) htonl(adapter->Index);
3262 struct interface_filter specific_interface_filter;
3263 struct sock_fprog filter_prog;
3265 if (setsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex, sizeof(ifindex)) != 0)
3266 goto cleanup; /* Failed to suggest egress interface */
3267 specific_interface_filter = generic_interface_filter;
3268 specific_interface_filter.iface_rule.k = adapter->Index;
3269 specific_interface_filter.ip_rule.k = htonl(adapter_addr);
3270 filter_prog.len = sizeof(generic_interface_filter)/sizeof(struct sock_filter);
3271 filter_prog.filter = (struct sock_filter *) &specific_interface_filter;
3272 if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog, sizeof(filter_prog)) != 0)
3273 goto cleanup; /* Failed to specify incoming packet filter */
3274 ret = TRUE;
3275 #else
3276 FIXME("Broadcast packets on interface-bound sockets are not currently supported on this platform, "
3277 "receiving broadcast packets will not work on socket %04lx.\n", s);
3278 #endif
3279 break;
3282 /* Will soon be switching to INADDR_ANY: permit address reuse */
3283 if (ret && setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) == 0)
3284 TRACE("Socket %04lx bound to interface index %d\n", s, adapter->Index);
3285 else
3286 ret = FALSE;
3288 cleanup:
3289 if(!ret)
3290 ERR("Failed to bind to interface, receiving broadcast packets will not work on socket %04lx.\n", s);
3291 HeapFree(GetProcessHeap(), 0, adapters);
3292 return ret;
3295 /***********************************************************************
3296 * bind (WS2_32.2)
3298 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
3300 int fd = get_sock_fd( s, 0, NULL );
3301 int res = SOCKET_ERROR;
3303 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
3305 if (fd != -1)
3307 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
3309 SetLastError(WSAEAFNOSUPPORT);
3311 else
3313 union generic_unix_sockaddr uaddr;
3314 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
3315 if (!uaddrlen)
3317 SetLastError(WSAEFAULT);
3319 else
3321 if (name->sa_family == WS_AF_INET)
3323 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
3324 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
3326 /* Trying to bind to the default host interface, using
3327 * INADDR_ANY instead*/
3328 WARN("Trying to bind to magic IP address, using "
3329 "INADDR_ANY instead.\n");
3330 in4->sin_addr.s_addr = htonl(INADDR_ANY);
3332 else if (interface_bind(s, fd, &uaddr.addr))
3333 in4->sin_addr.s_addr = htonl(INADDR_ANY);
3335 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
3337 int loc_errno = errno;
3338 WARN("\tfailure - errno = %i\n", errno);
3339 errno = loc_errno;
3340 switch (errno)
3342 case EADDRNOTAVAIL:
3343 SetLastError(WSAEINVAL);
3344 break;
3345 case EADDRINUSE:
3347 int optval = 0;
3348 socklen_t optlen = sizeof(optval);
3349 /* Windows >= 2003 will return different results depending on
3350 * SO_REUSEADDR, WSAEACCES may be returned representing that
3351 * the socket hijacking protection prevented the bind */
3352 if (!getsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&optval, &optlen) && optval)
3354 SetLastError(WSAEACCES);
3355 break;
3357 /* fall through */
3359 default:
3360 SetLastError(wsaErrno());
3361 break;
3364 else
3366 res=0; /* success */
3370 release_sock_fd( s, fd );
3372 return res;
3375 /***********************************************************************
3376 * closesocket (WS2_32.3)
3378 int WINAPI WS_closesocket(SOCKET s)
3380 int res = SOCKET_ERROR, fd;
3381 if (num_startup)
3383 fd = get_sock_fd(s, FILE_READ_DATA, NULL);
3384 if (fd >= 0)
3386 release_sock_fd(s, fd);
3387 if (CloseHandle(SOCKET2HANDLE(s)))
3388 res = 0;
3390 else
3391 SetLastError(WSAENOTSOCK);
3393 else
3394 SetLastError(WSANOTINITIALISED);
3395 TRACE("(socket %04lx) -> %d\n", s, res);
3396 return res;
3399 static int do_connect(int fd, const struct WS_sockaddr* name, int namelen)
3401 union generic_unix_sockaddr uaddr;
3402 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
3404 if (!uaddrlen)
3405 return WSAEFAULT;
3407 if (name->sa_family == WS_AF_INET)
3409 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
3410 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
3412 /* Trying to connect to magic replace-loopback address,
3413 * assuming we really want to connect to localhost */
3414 TRACE("Trying to connect to magic IP address, using "
3415 "INADDR_LOOPBACK instead.\n");
3416 in4->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
3420 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
3421 return 0;
3423 return wsaErrno();
3426 /***********************************************************************
3427 * connect (WS2_32.4)
3429 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
3431 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
3433 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
3435 if (fd != -1)
3437 NTSTATUS status;
3438 BOOL is_blocking;
3439 int ret = do_connect(fd, name, namelen);
3440 if (ret == 0)
3441 goto connect_success;
3443 if (ret == WSAEINPROGRESS)
3445 /* tell wineserver that a connection is in progress */
3446 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3447 FD_CONNECT,
3448 FD_WINE_CONNECTED|FD_WINE_LISTENING);
3449 status = _is_blocking( s, &is_blocking );
3450 if (status)
3452 release_sock_fd( s, fd );
3453 set_error( status );
3454 return SOCKET_ERROR;
3456 if (is_blocking)
3458 int result;
3459 /* block here */
3460 do_block(fd, POLLIN | POLLOUT, -1);
3461 _sync_sock_state(s); /* let wineserver notice connection */
3462 /* retrieve any error codes from it */
3463 result = _get_sock_error(s, FD_CONNECT_BIT);
3464 if (result)
3465 SetLastError(NtStatusToWSAError(result));
3466 else
3468 goto connect_success;
3471 else
3473 SetLastError(WSAEWOULDBLOCK);
3476 else
3478 SetLastError(ret);
3480 release_sock_fd( s, fd );
3482 return SOCKET_ERROR;
3484 connect_success:
3485 release_sock_fd( s, fd );
3486 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3487 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
3488 FD_CONNECT|FD_WINE_LISTENING);
3489 TRACE("\tconnected %04lx\n", s);
3490 return 0;
3493 /***********************************************************************
3494 * WSAConnect (WS2_32.30)
3496 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
3497 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
3498 LPQOS lpSQOS, LPQOS lpGQOS )
3500 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
3501 FIXME("unsupported parameters!\n");
3502 return WS_connect( s, name, namelen );
3505 /***********************************************************************
3506 * ConnectEx
3508 static BOOL WINAPI WS2_ConnectEx(SOCKET s, const struct WS_sockaddr* name, int namelen,
3509 PVOID sendBuf, DWORD sendBufLen, LPDWORD sent, LPOVERLAPPED ov)
3511 int fd, ret, status;
3513 if (!ov)
3515 SetLastError( ERROR_INVALID_PARAMETER );
3516 return FALSE;
3519 fd = get_sock_fd( s, FILE_READ_DATA, NULL );
3520 if (fd == -1)
3522 SetLastError( WSAENOTSOCK );
3523 return FALSE;
3526 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
3527 s, name, debugstr_sockaddr(name), namelen, sendBuf, sendBufLen, ov);
3529 ret = is_fd_bound(fd, NULL, NULL);
3530 if (ret <= 0)
3532 SetLastError(ret == -1 ? wsaErrno() : WSAEINVAL);
3533 release_sock_fd( s, fd );
3534 return FALSE;
3537 ret = do_connect(fd, name, namelen);
3538 if (ret == 0)
3540 WSABUF wsabuf;
3542 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3543 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
3544 FD_CONNECT|FD_WINE_LISTENING);
3546 wsabuf.len = sendBufLen;
3547 wsabuf.buf = (char*) sendBuf;
3549 /* WSASend takes care of completion if need be */
3550 if (WSASend(s, &wsabuf, sendBuf ? 1 : 0, sent, 0, ov, NULL) != SOCKET_ERROR)
3551 goto connection_success;
3553 else if (ret == WSAEINPROGRESS)
3555 struct ws2_async *wsa;
3556 ULONG_PTR cvalue = (((ULONG_PTR)ov->hEvent & 1) == 0) ? (ULONG_PTR)ov : 0;
3558 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3559 FD_CONNECT,
3560 FD_WINE_CONNECTED|FD_WINE_LISTENING);
3562 /* Indirectly call WSASend */
3563 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof( struct ws2_async, iovec[1] ), WS2_async_send )))
3565 SetLastError(WSAEFAULT);
3567 else
3569 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)ov;
3570 iosb->u.Status = STATUS_PENDING;
3571 iosb->Information = 0;
3573 wsa->hSocket = SOCKET2HANDLE(s);
3574 wsa->addr = NULL;
3575 wsa->addrlen.val = 0;
3576 wsa->flags = 0;
3577 wsa->lpFlags = &wsa->flags;
3578 wsa->control = NULL;
3579 wsa->n_iovecs = sendBuf ? 1 : 0;
3580 wsa->first_iovec = 0;
3581 wsa->completion_func = NULL;
3582 wsa->iovec[0].iov_base = sendBuf;
3583 wsa->iovec[0].iov_len = sendBufLen;
3585 status = register_async( ASYNC_TYPE_WRITE, wsa->hSocket, &wsa->io, ov->hEvent,
3586 NULL, (void *)cvalue, iosb );
3587 if (status != STATUS_PENDING) HeapFree(GetProcessHeap(), 0, wsa);
3589 /* If the connect already failed */
3590 if (status == STATUS_PIPE_DISCONNECTED)
3592 ov->Internal = _get_sock_error(s, FD_CONNECT_BIT);
3593 ov->InternalHigh = 0;
3594 if (cvalue) WS_AddCompletion( s, cvalue, ov->Internal, ov->InternalHigh );
3595 if (ov->hEvent) NtSetEvent( ov->hEvent, NULL );
3596 status = STATUS_PENDING;
3598 SetLastError( NtStatusToWSAError(status) );
3601 else
3603 SetLastError(ret);
3606 release_sock_fd( s, fd );
3607 return FALSE;
3609 connection_success:
3610 release_sock_fd( s, fd );
3611 return TRUE;
3614 /***********************************************************************
3615 * DisconnectEx
3617 static BOOL WINAPI WS2_DisconnectEx( SOCKET s, LPOVERLAPPED ov, DWORD flags, DWORD reserved )
3619 TRACE( "socket %04lx, ov %p, flags 0x%x, reserved 0x%x\n", s, ov, flags, reserved );
3621 if (flags & TF_REUSE_SOCKET)
3622 FIXME( "Reusing socket not supported yet\n" );
3624 if (ov)
3626 ov->Internal = STATUS_PENDING;
3627 ov->InternalHigh = 0;
3630 return !WS_shutdown( s, SD_BOTH );
3633 /***********************************************************************
3634 * getpeername (WS2_32.5)
3636 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
3638 int fd;
3639 int res;
3641 TRACE("socket %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
3643 fd = get_sock_fd( s, 0, NULL );
3644 res = SOCKET_ERROR;
3646 if (fd != -1)
3648 union generic_unix_sockaddr uaddr;
3649 socklen_t uaddrlen = sizeof(uaddr);
3651 if (getpeername(fd, &uaddr.addr, &uaddrlen) == 0)
3653 if (!name || !namelen)
3654 SetLastError(WSAEFAULT);
3655 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3656 /* The buffer was too small */
3657 SetLastError(WSAEFAULT);
3658 else
3660 res = 0;
3661 TRACE("=> %s\n", debugstr_sockaddr(name));
3664 else
3665 SetLastError(wsaErrno());
3666 release_sock_fd( s, fd );
3668 return res;
3671 /* When binding to an UDP address with filter support the getsockname call on the socket
3672 * will always return 0.0.0.0 instead of the filtered interface address. This function
3673 * checks if the socket is interface-bound on UDP and return the correct address.
3674 * This is required because applications often do a bind() with port zero followed by a
3675 * getsockname() to retrieve the port and address acquired.
3677 static void interface_bind_check(int fd, struct sockaddr_in *addr)
3679 #if !defined(IP_BOUND_IF) && !defined(LINUX_BOUND_IF)
3680 return;
3681 #else
3682 unsigned int ifindex;
3683 int ret;
3684 socklen_t len;
3686 /* Check for IPv4, address 0.0.0.0 and UDP socket */
3687 if (addr->sin_family != AF_INET || addr->sin_addr.s_addr != 0)
3688 return;
3689 if (_get_fd_type(fd) != SOCK_DGRAM)
3690 return;
3692 len = sizeof(ifindex);
3693 #if defined(IP_BOUND_IF)
3694 ret = getsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &ifindex, &len);
3695 #elif defined(LINUX_BOUND_IF)
3696 ret = getsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex, &len);
3697 if (!ret) ifindex = ntohl(ifindex);
3698 #endif
3699 if (!ret)
3701 PIP_ADAPTER_INFO adapters, adapter;
3702 DWORD adap_size;
3704 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
3705 return;
3706 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
3707 if (adapters && GetAdaptersInfo(adapters, &adap_size) == NO_ERROR)
3709 /* Search the IPv4 adapter list for the appropriate bound interface */
3710 for (adapter = adapters; adapter != NULL; adapter = adapter->Next)
3712 in_addr_t adapter_addr;
3713 if (adapter->Index != ifindex) continue;
3715 adapter_addr = inet_addr(adapter->IpAddressList.IpAddress.String);
3716 addr->sin_addr.s_addr = adapter_addr;
3717 TRACE("reporting interface address from adapter %d\n", ifindex);
3718 break;
3721 HeapFree(GetProcessHeap(), 0, adapters);
3723 #endif
3726 /***********************************************************************
3727 * getsockname (WS2_32.6)
3729 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
3731 int fd;
3732 int res;
3734 TRACE("socket %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
3736 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
3737 if( (name == NULL) || (namelen == NULL) )
3739 SetLastError( WSAEFAULT );
3740 return SOCKET_ERROR;
3743 fd = get_sock_fd( s, 0, NULL );
3744 res = SOCKET_ERROR;
3746 if (fd != -1)
3748 union generic_unix_sockaddr uaddr;
3749 socklen_t uaddrlen;
3750 int bound = is_fd_bound(fd, &uaddr, &uaddrlen);
3752 if (bound <= 0)
3754 SetLastError(bound == -1 ? wsaErrno() : WSAEINVAL);
3756 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3758 /* The buffer was too small */
3759 SetLastError(WSAEFAULT);
3761 else
3763 interface_bind_check(fd, (struct sockaddr_in*) &uaddr);
3764 if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3766 /* The buffer was too small */
3767 SetLastError(WSAEFAULT);
3769 else
3771 res = 0;
3772 TRACE("=> %s\n", debugstr_sockaddr(name));
3775 release_sock_fd( s, fd );
3777 return res;
3780 /***********************************************************************
3781 * getsockopt (WS2_32.7)
3783 INT WINAPI WS_getsockopt(SOCKET s, INT level,
3784 INT optname, char *optval, INT *optlen)
3786 int fd;
3787 INT ret = 0;
3789 TRACE("(socket %04lx, %s, optval %s, optlen %p (%d))\n", s,
3790 debugstr_sockopt(level, optname), debugstr_optval(optval, 0),
3791 optlen, optlen ? *optlen : 0);
3793 switch(level)
3795 case WS_SOL_SOCKET:
3797 switch(optname)
3799 /* Handle common cases. The special cases are below, sorted
3800 * alphabetically */
3801 case WS_SO_BROADCAST:
3802 case WS_SO_DEBUG:
3803 case WS_SO_KEEPALIVE:
3804 case WS_SO_OOBINLINE:
3805 case WS_SO_RCVBUF:
3806 case WS_SO_REUSEADDR:
3807 case WS_SO_SNDBUF:
3808 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3809 return SOCKET_ERROR;
3810 convert_sockopt(&level, &optname);
3811 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3813 SetLastError(wsaErrno());
3814 ret = SOCKET_ERROR;
3816 release_sock_fd( s, fd );
3817 return ret;
3818 case WS_SO_ACCEPTCONN:
3819 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3820 return SOCKET_ERROR;
3821 if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, optval, (socklen_t *)optlen) != 0 )
3823 SetLastError(wsaErrno());
3824 ret = SOCKET_ERROR;
3826 else
3828 /* BSD returns != 0 while Windows return exact == 1 */
3829 if (*(int *)optval) *(int *)optval = 1;
3831 release_sock_fd( s, fd );
3832 return ret;
3833 case WS_SO_BSP_STATE:
3835 int req_size, addr_size;
3836 WSAPROTOCOL_INFOW infow;
3837 CSADDR_INFO *csinfo;
3839 ret = ws_protocol_info(s, TRUE, &infow, &addr_size);
3840 if (ret)
3842 if (infow.iAddressFamily == WS_AF_INET)
3843 addr_size = sizeof(struct sockaddr_in);
3844 else if (infow.iAddressFamily == WS_AF_INET6)
3845 addr_size = sizeof(struct sockaddr_in6);
3846 else
3848 FIXME("Family %d is unsupported for SO_BSP_STATE\n", infow.iAddressFamily);
3849 SetLastError(WSAEAFNOSUPPORT);
3850 return SOCKET_ERROR;
3853 req_size = sizeof(CSADDR_INFO) + addr_size * 2;
3854 if (*optlen < req_size)
3856 ret = 0;
3857 SetLastError(WSAEFAULT);
3859 else
3861 union generic_unix_sockaddr uaddr;
3862 socklen_t uaddrlen;
3864 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3865 return SOCKET_ERROR;
3867 csinfo = (CSADDR_INFO*) optval;
3869 /* Check if the sock is bound */
3870 if (is_fd_bound(fd, &uaddr, &uaddrlen) == 1)
3872 csinfo->LocalAddr.lpSockaddr =
3873 (LPSOCKADDR) (optval + sizeof(CSADDR_INFO));
3874 ws_sockaddr_u2ws(&uaddr.addr, csinfo->LocalAddr.lpSockaddr, &addr_size);
3875 csinfo->LocalAddr.iSockaddrLength = addr_size;
3877 else
3879 csinfo->LocalAddr.lpSockaddr = NULL;
3880 csinfo->LocalAddr.iSockaddrLength = 0;
3883 /* Check if the sock is connected */
3884 if (!getpeername(fd, &uaddr.addr, &uaddrlen) &&
3885 is_sockaddr_bound(&uaddr.addr, uaddrlen))
3887 csinfo->RemoteAddr.lpSockaddr =
3888 (LPSOCKADDR) (optval + sizeof(CSADDR_INFO) + addr_size);
3889 ws_sockaddr_u2ws(&uaddr.addr, csinfo->RemoteAddr.lpSockaddr, &addr_size);
3890 csinfo->RemoteAddr.iSockaddrLength = addr_size;
3892 else
3894 csinfo->RemoteAddr.lpSockaddr = NULL;
3895 csinfo->RemoteAddr.iSockaddrLength = 0;
3898 csinfo->iSocketType = infow.iSocketType;
3899 csinfo->iProtocol = infow.iProtocol;
3900 release_sock_fd( s, fd );
3903 return ret ? 0 : SOCKET_ERROR;
3905 case WS_SO_DONTLINGER:
3907 struct linger lingval;
3908 socklen_t len = sizeof(struct linger);
3910 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
3912 SetLastError(WSAEFAULT);
3913 return SOCKET_ERROR;
3915 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3916 return SOCKET_ERROR;
3918 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
3920 SetLastError(wsaErrno());
3921 ret = SOCKET_ERROR;
3923 else
3925 *(BOOL *)optval = !lingval.l_onoff;
3926 *optlen = sizeof(BOOL);
3929 release_sock_fd( s, fd );
3930 return ret;
3933 case WS_SO_CONNECT_TIME:
3935 static int pretendtime = 0;
3936 struct WS_sockaddr addr;
3937 int len = sizeof(addr);
3939 if (!optlen || *optlen < sizeof(DWORD) || !optval)
3941 SetLastError(WSAEFAULT);
3942 return SOCKET_ERROR;
3944 if (WS_getpeername(s, &addr, &len) == SOCKET_ERROR)
3945 *(DWORD *)optval = ~0u;
3946 else
3948 if (!pretendtime) FIXME("WS_SO_CONNECT_TIME - faking results\n");
3949 *(DWORD *)optval = pretendtime++;
3951 *optlen = sizeof(DWORD);
3952 return ret;
3954 /* As mentioned in setsockopt, Windows ignores this, so we
3955 * always return true here */
3956 case WS_SO_DONTROUTE:
3957 if (!optlen || *optlen < sizeof(BOOL) || !optval)
3959 SetLastError(WSAEFAULT);
3960 return SOCKET_ERROR;
3962 *(BOOL *)optval = TRUE;
3963 *optlen = sizeof(BOOL);
3964 return 0;
3966 case WS_SO_ERROR:
3968 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3969 return SOCKET_ERROR;
3970 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, optval, (socklen_t *)optlen) != 0 )
3972 SetLastError(wsaErrno());
3973 ret = SOCKET_ERROR;
3975 release_sock_fd( s, fd );
3977 /* The wineserver may have swallowed the error before us */
3978 if (!ret && *(int*) optval == 0)
3980 int i, events[FD_MAX_EVENTS];
3981 _get_sock_errors(s, events);
3982 for (i = 0; i < FD_MAX_EVENTS; i++)
3984 if(events[i])
3986 events[i] = NtStatusToWSAError(events[i]);
3987 TRACE("returning SO_ERROR %d from wine server\n", events[i]);
3988 *(int*) optval = events[i];
3989 break;
3993 return ret;
3996 case WS_SO_LINGER:
3998 struct linger lingval;
3999 socklen_t len = sizeof(struct linger);
4001 /* struct linger and LINGER have different sizes */
4002 if (!optlen || *optlen < sizeof(LINGER) || !optval)
4004 SetLastError(WSAEFAULT);
4005 return SOCKET_ERROR;
4007 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4008 return SOCKET_ERROR;
4010 if (_get_fd_type(fd) == SOCK_DGRAM)
4012 SetLastError(WSAENOPROTOOPT);
4013 ret = SOCKET_ERROR;
4015 else if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0)
4017 SetLastError(wsaErrno());
4018 ret = SOCKET_ERROR;
4020 else
4022 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
4023 ((LINGER *)optval)->l_linger = lingval.l_linger;
4024 *optlen = sizeof(struct linger);
4027 release_sock_fd( s, fd );
4028 return ret;
4031 case WS_SO_MAX_MSG_SIZE:
4032 if (!optlen || *optlen < sizeof(int) || !optval)
4034 SetLastError(WSAEFAULT);
4035 return SOCKET_ERROR;
4037 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
4038 *(int *)optval = 65507;
4039 *optlen = sizeof(int);
4040 return 0;
4042 /* SO_OPENTYPE does not require a valid socket handle. */
4043 case WS_SO_OPENTYPE:
4044 if (!optlen || *optlen < sizeof(int) || !optval)
4046 SetLastError(WSAEFAULT);
4047 return SOCKET_ERROR;
4049 *(int *)optval = get_per_thread_data()->opentype;
4050 *optlen = sizeof(int);
4051 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
4052 return 0;
4053 case WS_SO_PROTOCOL_INFOA:
4054 case WS_SO_PROTOCOL_INFOW:
4056 int size;
4057 WSAPROTOCOL_INFOW infow;
4059 ret = ws_protocol_info(s, optname == WS_SO_PROTOCOL_INFOW, &infow, &size);
4060 if (ret)
4062 if (!optlen || !optval || *optlen < size)
4064 if(optlen) *optlen = size;
4065 ret = 0;
4066 SetLastError(WSAEFAULT);
4068 else
4069 memcpy(optval, &infow, size);
4071 return ret ? 0 : SOCKET_ERROR;
4073 case WS_SO_RCVTIMEO:
4074 case WS_SO_SNDTIMEO:
4076 INT64 timeout;
4078 if (!optlen || *optlen < sizeof(int)|| !optval)
4080 SetLastError(WSAEFAULT);
4081 return SOCKET_ERROR;
4083 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4084 return SOCKET_ERROR;
4086 timeout = get_rcvsnd_timeo(fd, optname == WS_SO_RCVTIMEO);
4087 *(int *)optval = timeout <= UINT_MAX ? timeout : UINT_MAX;
4089 release_sock_fd( s, fd );
4090 return ret;
4092 case WS_SO_TYPE:
4094 int sock_type;
4095 if (!optlen || *optlen < sizeof(int) || !optval)
4097 SetLastError(WSAEFAULT);
4098 return SOCKET_ERROR;
4100 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4101 return SOCKET_ERROR;
4103 sock_type = _get_fd_type(fd);
4104 if (sock_type == -1)
4106 SetLastError(wsaErrno());
4107 ret = SOCKET_ERROR;
4109 else
4110 (*(int *)optval) = convert_socktype_u2w(sock_type);
4112 release_sock_fd( s, fd );
4113 return ret;
4115 default:
4116 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
4117 SetLastError(WSAENOPROTOOPT);
4118 return SOCKET_ERROR;
4119 } /* end switch(optname) */
4120 }/* end case WS_SOL_SOCKET */
4121 #ifdef HAS_IPX
4122 case WS_NSPROTO_IPX:
4124 struct WS_sockaddr_ipx addr;
4125 IPX_ADDRESS_DATA *data;
4126 int namelen;
4127 switch(optname)
4129 case WS_IPX_PTYPE:
4130 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
4131 #ifdef SOL_IPX
4132 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (socklen_t *)optlen) == -1)
4134 ret = SOCKET_ERROR;
4136 #else
4138 struct ipx val;
4139 socklen_t len=sizeof(struct ipx);
4140 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
4141 ret = SOCKET_ERROR;
4142 else
4143 *optval = (int)val.ipx_pt;
4145 #endif
4146 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
4147 release_sock_fd( s, fd );
4148 return ret;
4150 case WS_IPX_ADDRESS:
4152 * On a Win2000 system with one network card there are usually
4153 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
4154 * Using this call you can then retrieve info about this all.
4155 * In case of Linux it is a bit different. Usually you have
4156 * only "one" device active and further it is not possible to
4157 * query things like the linkspeed.
4159 FIXME("IPX_ADDRESS\n");
4160 namelen = sizeof(struct WS_sockaddr_ipx);
4161 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
4162 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
4164 data = (IPX_ADDRESS_DATA*)optval;
4165 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
4166 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
4167 data->adapternum = 0;
4168 data->wan = FALSE; /* We are not on a wan for now .. */
4169 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
4170 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
4171 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
4172 * note 1MB = 1000kB in this case */
4173 return 0;
4175 case WS_IPX_MAX_ADAPTER_NUM:
4176 FIXME("IPX_MAX_ADAPTER_NUM\n");
4177 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
4178 return 0;
4180 default:
4181 FIXME("IPX optname:%x\n", optname);
4182 return SOCKET_ERROR;
4183 }/* end switch(optname) */
4184 } /* end case WS_NSPROTO_IPX */
4185 #endif
4187 #ifdef HAS_IRDA
4188 #define MAX_IRDA_DEVICES 10
4190 case WS_SOL_IRLMP:
4191 switch(optname)
4193 case WS_IRLMP_ENUMDEVICES:
4195 char buf[sizeof(struct irda_device_list) +
4196 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
4197 int res;
4198 socklen_t len = sizeof(buf);
4200 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4201 return SOCKET_ERROR;
4202 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
4203 release_sock_fd( s, fd );
4204 if (res < 0)
4206 SetLastError(wsaErrno());
4207 return SOCKET_ERROR;
4209 else
4211 struct irda_device_list *src = (struct irda_device_list *)buf;
4212 DEVICELIST *dst = (DEVICELIST *)optval;
4213 INT needed = sizeof(DEVICELIST);
4214 unsigned int i;
4216 if (src->len > 0)
4217 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
4218 if (*optlen < needed)
4220 SetLastError(WSAEFAULT);
4221 return SOCKET_ERROR;
4223 *optlen = needed;
4224 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
4225 dst->numDevice = src->len;
4226 for (i = 0; i < src->len; i++)
4228 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
4229 src->dev[i].saddr, src->dev[i].daddr,
4230 src->dev[i].info, src->dev[i].hints[0],
4231 src->dev[i].hints[1]);
4232 memcpy( dst->Device[i].irdaDeviceID,
4233 &src->dev[i].daddr,
4234 sizeof(dst->Device[i].irdaDeviceID) ) ;
4235 memcpy( dst->Device[i].irdaDeviceName,
4236 src->dev[i].info,
4237 sizeof(dst->Device[i].irdaDeviceName) ) ;
4238 memcpy( &dst->Device[i].irdaDeviceHints1,
4239 &src->dev[i].hints[0],
4240 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
4241 memcpy( &dst->Device[i].irdaDeviceHints2,
4242 &src->dev[i].hints[1],
4243 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
4244 dst->Device[i].irdaCharSet = src->dev[i].charset;
4246 return 0;
4249 default:
4250 FIXME("IrDA optname:0x%x\n", optname);
4251 return SOCKET_ERROR;
4253 break; /* case WS_SOL_IRLMP */
4254 #undef MAX_IRDA_DEVICES
4255 #endif
4257 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
4258 case WS_IPPROTO_TCP:
4259 switch(optname)
4261 case WS_TCP_NODELAY:
4262 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4263 return SOCKET_ERROR;
4264 convert_sockopt(&level, &optname);
4265 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
4267 SetLastError(wsaErrno());
4268 ret = SOCKET_ERROR;
4270 release_sock_fd( s, fd );
4271 return ret;
4273 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
4274 return SOCKET_ERROR;
4276 case WS_IPPROTO_IP:
4277 switch(optname)
4279 case WS_IP_ADD_MEMBERSHIP:
4280 case WS_IP_DROP_MEMBERSHIP:
4281 #ifdef IP_HDRINCL
4282 case WS_IP_HDRINCL:
4283 #endif
4284 case WS_IP_MULTICAST_IF:
4285 case WS_IP_MULTICAST_LOOP:
4286 case WS_IP_MULTICAST_TTL:
4287 case WS_IP_OPTIONS:
4288 #ifdef IP_PKTINFO
4289 case WS_IP_PKTINFO:
4290 #endif
4291 case WS_IP_TOS:
4292 case WS_IP_TTL:
4293 #ifdef IP_UNICAST_IF
4294 case WS_IP_UNICAST_IF:
4295 #endif
4296 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4297 return SOCKET_ERROR;
4298 convert_sockopt(&level, &optname);
4299 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
4301 SetLastError(wsaErrno());
4302 ret = SOCKET_ERROR;
4304 release_sock_fd( s, fd );
4305 return ret;
4306 case WS_IP_DONTFRAGMENT:
4307 return get_dont_fragment(s, IPPROTO_IP, (BOOL *)optval) ? 0 : SOCKET_ERROR;
4309 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
4310 return SOCKET_ERROR;
4312 case WS_IPPROTO_IPV6:
4313 switch(optname)
4315 #ifdef IPV6_ADD_MEMBERSHIP
4316 case WS_IPV6_ADD_MEMBERSHIP:
4317 #endif
4318 #ifdef IPV6_DROP_MEMBERSHIP
4319 case WS_IPV6_DROP_MEMBERSHIP:
4320 #endif
4321 case WS_IPV6_MULTICAST_IF:
4322 case WS_IPV6_MULTICAST_HOPS:
4323 case WS_IPV6_MULTICAST_LOOP:
4324 case WS_IPV6_UNICAST_HOPS:
4325 case WS_IPV6_V6ONLY:
4326 #ifdef IPV6_UNICAST_IF
4327 case WS_IPV6_UNICAST_IF:
4328 #endif
4329 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4330 return SOCKET_ERROR;
4331 convert_sockopt(&level, &optname);
4332 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
4334 SetLastError(wsaErrno());
4335 ret = SOCKET_ERROR;
4337 release_sock_fd( s, fd );
4338 return ret;
4339 case WS_IPV6_DONTFRAG:
4340 return get_dont_fragment(s, IPPROTO_IPV6, (BOOL *)optval) ? 0 : SOCKET_ERROR;
4342 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
4343 return SOCKET_ERROR;
4345 default:
4346 WARN("Unknown level: 0x%08x\n", level);
4347 SetLastError(WSAEINVAL);
4348 return SOCKET_ERROR;
4349 } /* end switch(level) */
4352 /***********************************************************************
4353 * htonl (WS2_32.8)
4355 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
4357 return htonl(hostlong);
4361 /***********************************************************************
4362 * htons (WS2_32.9)
4364 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
4366 return htons(hostshort);
4369 /***********************************************************************
4370 * WSAHtonl (WS2_32.46)
4371 * From MSDN description of error codes, this function should also
4372 * check if WinSock has been initialized and the socket is a valid
4373 * socket. But why? This function only translates a host byte order
4374 * u_long into a network byte order u_long...
4376 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
4378 if (lpnetlong)
4380 *lpnetlong = htonl(hostlong);
4381 return 0;
4383 SetLastError(WSAEFAULT);
4384 return SOCKET_ERROR;
4387 /***********************************************************************
4388 * WSAHtons (WS2_32.47)
4389 * From MSDN description of error codes, this function should also
4390 * check if WinSock has been initialized and the socket is a valid
4391 * socket. But why? This function only translates a host byte order
4392 * u_short into a network byte order u_short...
4394 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
4397 if (lpnetshort)
4399 *lpnetshort = htons(hostshort);
4400 return 0;
4402 SetLastError(WSAEFAULT);
4403 return SOCKET_ERROR;
4407 /***********************************************************************
4408 * inet_addr (WS2_32.11)
4410 WS_u_long WINAPI WS_inet_addr(const char *cp)
4412 if (!cp) return INADDR_NONE;
4413 return inet_addr(cp);
4417 /***********************************************************************
4418 * ntohl (WS2_32.14)
4420 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
4422 return ntohl(netlong);
4426 /***********************************************************************
4427 * ntohs (WS2_32.15)
4429 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
4431 return ntohs(netshort);
4435 /***********************************************************************
4436 * inet_ntoa (WS2_32.12)
4438 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
4440 unsigned int long_ip = ntohl(in.WS_s_addr);
4441 struct per_thread_data *data = get_per_thread_data();
4443 sprintf( data->ntoa_buffer, "%u.%u.%u.%u",
4444 (long_ip >> 24) & 0xff,
4445 (long_ip >> 16) & 0xff,
4446 (long_ip >> 8) & 0xff,
4447 long_ip & 0xff);
4449 return data->ntoa_buffer;
4452 static const char *debugstr_wsaioctl(DWORD code)
4454 const char *name = NULL, *buf_type, *family;
4456 #define IOCTL_NAME(x) case x: name = #x; break
4457 switch (code)
4459 IOCTL_NAME(WS_FIONBIO);
4460 IOCTL_NAME(WS_FIONREAD);
4461 IOCTL_NAME(WS_SIOCATMARK);
4462 /* IOCTL_NAME(WS_SIO_ACQUIRE_PORT_RESERVATION); */
4463 IOCTL_NAME(WS_SIO_ADDRESS_LIST_CHANGE);
4464 IOCTL_NAME(WS_SIO_ADDRESS_LIST_QUERY);
4465 IOCTL_NAME(WS_SIO_ASSOCIATE_HANDLE);
4466 /* IOCTL_NAME(WS_SIO_ASSOCIATE_PORT_RESERVATION);
4467 IOCTL_NAME(WS_SIO_BASE_HANDLE);
4468 IOCTL_NAME(WS_SIO_BSP_HANDLE);
4469 IOCTL_NAME(WS_SIO_BSP_HANDLE_SELECT);
4470 IOCTL_NAME(WS_SIO_BSP_HANDLE_POLL);
4471 IOCTL_NAME(WS_SIO_CHK_QOS); */
4472 IOCTL_NAME(WS_SIO_ENABLE_CIRCULAR_QUEUEING);
4473 IOCTL_NAME(WS_SIO_FIND_ROUTE);
4474 IOCTL_NAME(WS_SIO_FLUSH);
4475 IOCTL_NAME(WS_SIO_GET_BROADCAST_ADDRESS);
4476 IOCTL_NAME(WS_SIO_GET_EXTENSION_FUNCTION_POINTER);
4477 IOCTL_NAME(WS_SIO_GET_GROUP_QOS);
4478 IOCTL_NAME(WS_SIO_GET_INTERFACE_LIST);
4479 /* IOCTL_NAME(WS_SIO_GET_INTERFACE_LIST_EX); */
4480 IOCTL_NAME(WS_SIO_GET_QOS);
4481 /* IOCTL_NAME(WS_SIO_IDEAL_SEND_BACKLOG_CHANGE);
4482 IOCTL_NAME(WS_SIO_IDEAL_SEND_BACKLOG_QUERY); */
4483 IOCTL_NAME(WS_SIO_KEEPALIVE_VALS);
4484 IOCTL_NAME(WS_SIO_MULTIPOINT_LOOPBACK);
4485 IOCTL_NAME(WS_SIO_MULTICAST_SCOPE);
4486 /* IOCTL_NAME(WS_SIO_QUERY_RSS_SCALABILITY_INFO);
4487 IOCTL_NAME(WS_SIO_QUERY_WFP_ALE_ENDPOINT_HANDLE); */
4488 IOCTL_NAME(WS_SIO_RCVALL);
4489 IOCTL_NAME(WS_SIO_RCVALL_IGMPMCAST);
4490 IOCTL_NAME(WS_SIO_RCVALL_MCAST);
4491 /* IOCTL_NAME(WS_SIO_RELEASE_PORT_RESERVATION); */
4492 IOCTL_NAME(WS_SIO_ROUTING_INTERFACE_CHANGE);
4493 IOCTL_NAME(WS_SIO_ROUTING_INTERFACE_QUERY);
4494 IOCTL_NAME(WS_SIO_SET_COMPATIBILITY_MODE);
4495 IOCTL_NAME(WS_SIO_SET_GROUP_QOS);
4496 IOCTL_NAME(WS_SIO_SET_QOS);
4497 IOCTL_NAME(WS_SIO_TRANSLATE_HANDLE);
4498 IOCTL_NAME(WS_SIO_UDP_CONNRESET);
4500 #undef IOCTL_NAME
4502 if (name)
4503 return name + 3;
4505 /* If this is not a known code split its bits */
4506 switch(code & 0x18000000)
4508 case WS_IOC_WS2:
4509 family = "IOC_WS2";
4510 break;
4511 case WS_IOC_PROTOCOL:
4512 family = "IOC_PROTOCOL";
4513 break;
4514 case WS_IOC_VENDOR:
4515 family = "IOC_VENDOR";
4516 break;
4517 default: /* WS_IOC_UNIX */
4519 BYTE size = (code >> 16) & WS_IOCPARM_MASK;
4520 char x = (code & 0xff00) >> 8;
4521 BYTE y = code & 0xff;
4522 char args[14];
4524 switch (code & (WS_IOC_VOID|WS_IOC_INOUT))
4526 case WS_IOC_VOID:
4527 buf_type = "_IO";
4528 sprintf(args, "%d, %d", x, y);
4529 break;
4530 case WS_IOC_IN:
4531 buf_type = "_IOW";
4532 sprintf(args, "'%c', %d, %d", x, y, size);
4533 break;
4534 case WS_IOC_OUT:
4535 buf_type = "_IOR";
4536 sprintf(args, "'%c', %d, %d", x, y, size);
4537 break;
4538 default:
4539 buf_type = "?";
4540 sprintf(args, "'%c', %d, %d", x, y, size);
4541 break;
4543 return wine_dbg_sprintf("%s(%s)", buf_type, args);
4547 /* We are different from WS_IOC_UNIX. */
4548 switch (code & (WS_IOC_VOID|WS_IOC_INOUT))
4550 case WS_IOC_VOID:
4551 buf_type = "_WSAIO";
4552 break;
4553 case WS_IOC_INOUT:
4554 buf_type = "_WSAIORW";
4555 break;
4556 case WS_IOC_IN:
4557 buf_type = "_WSAIOW";
4558 break;
4559 case WS_IOC_OUT:
4560 buf_type = "_WSAIOR";
4561 break;
4562 default:
4563 buf_type = "?";
4564 break;
4567 return wine_dbg_sprintf("%s(%s, %d)", buf_type, family,
4568 (USHORT)(code & 0xffff));
4571 /* do an ioctl call through the server */
4572 static DWORD server_ioctl_sock( SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size,
4573 LPVOID out_buff, DWORD out_size, LPDWORD ret_size,
4574 LPWSAOVERLAPPED overlapped,
4575 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
4577 HANDLE event = overlapped ? overlapped->hEvent : 0;
4578 HANDLE handle = SOCKET2HANDLE( s );
4579 struct ws2_async *wsa = NULL;
4580 IO_STATUS_BLOCK *io = (PIO_STATUS_BLOCK)overlapped, iosb;
4581 void *cvalue = NULL;
4582 NTSTATUS status;
4584 if (completion)
4586 if (!(wsa = (struct ws2_async *)alloc_async_io( sizeof(*wsa), NULL )))
4587 return WSA_NOT_ENOUGH_MEMORY;
4588 wsa->hSocket = handle;
4589 wsa->user_overlapped = overlapped;
4590 wsa->completion_func = completion;
4591 if (!io) io = &wsa->local_iosb;
4592 cvalue = wsa;
4594 else if (!io)
4595 io = &iosb;
4596 else if (!((ULONG_PTR)overlapped->hEvent & 1))
4597 cvalue = overlapped;
4599 status = NtDeviceIoControlFile( handle, event, wsa ? ws2_async_apc : NULL, cvalue, io, code,
4600 in_buff, in_size, out_buff, out_size );
4601 if (status == STATUS_NOT_SUPPORTED)
4603 FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
4604 code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
4606 else if (status == STATUS_SUCCESS)
4607 *ret_size = io->Information; /* "Information" is the size written to the output buffer */
4609 if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, wsa );
4611 return NtStatusToWSAError( status );
4614 /**********************************************************************
4615 * WSAIoctl (WS2_32.50)
4618 INT WINAPI WSAIoctl(SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size, LPVOID out_buff,
4619 DWORD out_size, LPDWORD ret_size, LPWSAOVERLAPPED overlapped,
4620 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
4622 int fd;
4623 DWORD status = 0, total = 0;
4625 TRACE("%04lx, %s, %p, %d, %p, %d, %p, %p, %p\n",
4626 s, debugstr_wsaioctl(code), in_buff, in_size, out_buff, out_size, ret_size, overlapped, completion);
4628 switch (code)
4630 case WS_FIONBIO:
4631 if (in_size != sizeof(WS_u_long) || IS_INTRESOURCE(in_buff))
4633 SetLastError(WSAEFAULT);
4634 return SOCKET_ERROR;
4636 TRACE("-> FIONBIO (%x)\n", *(WS_u_long*)in_buff);
4637 if (_get_sock_mask(s))
4639 /* AsyncSelect()'ed sockets are always nonblocking */
4640 if (!*(WS_u_long *)in_buff) status = WSAEINVAL;
4641 break;
4643 if (*(WS_u_long *)in_buff)
4644 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
4645 else
4646 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
4647 break;
4649 case WS_FIONREAD:
4651 #if defined(linux)
4652 int listening = 0;
4653 socklen_t len = sizeof(listening);
4654 #endif
4655 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
4657 SetLastError(WSAEFAULT);
4658 return SOCKET_ERROR;
4660 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
4662 #if defined(linux)
4663 /* On Linux, FIONREAD on listening socket always fails (see tcp(7)).
4664 However, it succeeds on native. */
4665 if (!getsockopt( fd, SOL_SOCKET, SO_ACCEPTCONN, &listening, &len ) && listening)
4666 (*(WS_u_long *) out_buff) = 0;
4667 else
4668 #endif
4669 if (ioctl(fd, FIONREAD, out_buff ) == -1)
4670 status = wsaErrno();
4671 release_sock_fd( s, fd );
4672 break;
4675 case WS_SIOCATMARK:
4677 unsigned int oob = 0, atmark = 0;
4678 socklen_t oobsize = sizeof(int);
4679 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
4681 SetLastError(WSAEFAULT);
4682 return SOCKET_ERROR;
4684 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
4685 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
4686 if ((getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &oob, &oobsize ) == -1)
4687 || (!oob && ioctl(fd, SIOCATMARK, &atmark ) == -1))
4688 status = wsaErrno();
4689 else
4691 /* The SIOCATMARK value read from ioctl() is reversed
4692 * because BSD returns TRUE if it's in the OOB mark
4693 * while Windows returns TRUE if there are NO OOB bytes.
4695 (*(WS_u_long *) out_buff) = oob || !atmark;
4698 release_sock_fd( s, fd );
4699 break;
4702 case WS_FIOASYNC:
4703 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
4704 SetLastError(WSAEINVAL);
4705 return SOCKET_ERROR;
4707 case WS_SIO_GET_INTERFACE_LIST:
4709 INTERFACE_INFO* intArray = out_buff;
4710 DWORD size, numInt = 0, apiReturn;
4712 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
4714 if (!out_buff || !ret_size)
4716 SetLastError(WSAEFAULT);
4717 return SOCKET_ERROR;
4720 fd = get_sock_fd( s, 0, NULL );
4721 if (fd == -1) return SOCKET_ERROR;
4723 apiReturn = GetAdaptersInfo(NULL, &size);
4724 if (apiReturn == ERROR_BUFFER_OVERFLOW)
4726 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
4728 if (table)
4730 if (GetAdaptersInfo(table, &size) == NO_ERROR)
4732 PIP_ADAPTER_INFO ptr;
4734 for (ptr = table, numInt = 0; ptr; ptr = ptr->Next)
4736 unsigned int addr, mask, bcast;
4737 struct ifreq ifInfo;
4739 /* Skip interfaces without an IPv4 address. */
4740 if (ptr->IpAddressList.IpAddress.String[0] == '\0')
4741 continue;
4743 if ((numInt + 1)*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > out_size)
4745 WARN("Buffer too small = %u, out_size = %u\n", numInt + 1, out_size);
4746 status = WSAEFAULT;
4747 break;
4750 /* Socket Status Flags */
4751 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
4752 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
4754 ERR("Error obtaining status flags for socket!\n");
4755 status = WSAEINVAL;
4756 break;
4758 else
4760 /* set flags; the values of IFF_* are not the same
4761 under Linux and Windows, therefore must generate
4762 new flags */
4763 intArray->iiFlags = 0;
4764 if (ifInfo.ifr_flags & IFF_BROADCAST)
4765 intArray->iiFlags |= WS_IFF_BROADCAST;
4766 #ifdef IFF_POINTOPOINT
4767 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
4768 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
4769 #endif
4770 if (ifInfo.ifr_flags & IFF_LOOPBACK)
4771 intArray->iiFlags |= WS_IFF_LOOPBACK;
4772 if (ifInfo.ifr_flags & IFF_UP)
4773 intArray->iiFlags |= WS_IFF_UP;
4774 if (ifInfo.ifr_flags & IFF_MULTICAST)
4775 intArray->iiFlags |= WS_IFF_MULTICAST;
4778 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
4779 mask = inet_addr(ptr->IpAddressList.IpMask.String);
4780 bcast = addr | ~mask;
4781 intArray->iiAddress.AddressIn.sin_family = WS_AF_INET;
4782 intArray->iiAddress.AddressIn.sin_port = 0;
4783 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr = addr;
4785 intArray->iiNetmask.AddressIn.sin_family = WS_AF_INET;
4786 intArray->iiNetmask.AddressIn.sin_port = 0;
4787 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr = mask;
4789 intArray->iiBroadcastAddress.AddressIn.sin_family = WS_AF_INET;
4790 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
4791 intArray->iiBroadcastAddress.AddressIn.sin_addr.WS_s_addr = bcast;
4792 intArray++;
4793 numInt++;
4796 else
4798 ERR("Unable to get interface table!\n");
4799 status = WSAEINVAL;
4801 HeapFree(GetProcessHeap(),0,table);
4803 else status = WSAEINVAL;
4805 else if (apiReturn != ERROR_NO_DATA)
4807 ERR("Unable to get interface table!\n");
4808 status = WSAEINVAL;
4810 /* Calculate the size of the array being returned */
4811 total = sizeof(INTERFACE_INFO) * numInt;
4812 release_sock_fd( s, fd );
4813 break;
4816 case WS_SIO_ADDRESS_LIST_QUERY:
4818 DWORD size;
4820 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
4822 if (!ret_size)
4824 SetLastError(WSAEFAULT);
4825 return SOCKET_ERROR;
4828 if (out_size && out_size < FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[0]))
4830 *ret_size = 0;
4831 SetLastError(WSAEINVAL);
4832 return SOCKET_ERROR;
4835 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
4837 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
4838 SOCKET_ADDRESS_LIST *sa_list;
4839 SOCKADDR_IN *sockaddr;
4840 SOCKET_ADDRESS *sa;
4841 unsigned int i;
4842 DWORD num;
4844 if (!table || GetAdaptersInfo(table, &size))
4846 HeapFree(GetProcessHeap(), 0, table);
4847 status = WSAEINVAL;
4848 break;
4851 for (p = table, num = 0; p; p = p->Next)
4852 if (p->IpAddressList.IpAddress.String[0]) num++;
4854 total = FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[num]) + num * sizeof(*sockaddr);
4855 if (total > out_size || !out_buff)
4857 *ret_size = total;
4858 HeapFree(GetProcessHeap(), 0, table);
4859 status = WSAEFAULT;
4860 break;
4863 sa_list = out_buff;
4864 sa = sa_list->Address;
4865 sockaddr = (SOCKADDR_IN *)&sa[num];
4866 sa_list->iAddressCount = num;
4868 for (p = table, i = 0; p; p = p->Next)
4870 if (!p->IpAddressList.IpAddress.String[0]) continue;
4872 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
4873 sa[i].iSockaddrLength = sizeof(SOCKADDR);
4875 sockaddr[i].sin_family = WS_AF_INET;
4876 sockaddr[i].sin_port = 0;
4877 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
4878 i++;
4881 HeapFree(GetProcessHeap(), 0, table);
4883 else
4885 WARN("unable to get IP address list\n");
4886 status = WSAEINVAL;
4888 break;
4891 case WS_SIO_FLUSH:
4892 FIXME("SIO_FLUSH: stub.\n");
4893 break;
4895 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
4897 #define EXTENSION_FUNCTION(x, y) { x, y, #y },
4898 static const struct
4900 GUID guid;
4901 void *func_ptr;
4902 const char *name;
4903 } guid_funcs[] = {
4904 EXTENSION_FUNCTION(WSAID_CONNECTEX, WS2_ConnectEx)
4905 EXTENSION_FUNCTION(WSAID_DISCONNECTEX, WS2_DisconnectEx)
4906 EXTENSION_FUNCTION(WSAID_ACCEPTEX, WS2_AcceptEx)
4907 EXTENSION_FUNCTION(WSAID_GETACCEPTEXSOCKADDRS, WS2_GetAcceptExSockaddrs)
4908 EXTENSION_FUNCTION(WSAID_TRANSMITFILE, WS2_TransmitFile)
4909 /* EXTENSION_FUNCTION(WSAID_TRANSMITPACKETS, WS2_TransmitPackets) */
4910 EXTENSION_FUNCTION(WSAID_WSARECVMSG, WS2_WSARecvMsg)
4911 EXTENSION_FUNCTION(WSAID_WSASENDMSG, WSASendMsg)
4913 #undef EXTENSION_FUNCTION
4914 BOOL found = FALSE;
4915 unsigned int i;
4917 for (i = 0; i < sizeof(guid_funcs) / sizeof(guid_funcs[0]); i++)
4919 if (IsEqualGUID(&guid_funcs[i].guid, in_buff))
4921 found = TRUE;
4922 break;
4926 if (found)
4928 TRACE("-> got %s\n", guid_funcs[i].name);
4929 *(void **)out_buff = guid_funcs[i].func_ptr;
4930 total = sizeof(void *);
4931 break;
4934 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff));
4935 status = WSAEOPNOTSUPP;
4936 break;
4938 case WS_SIO_KEEPALIVE_VALS:
4940 struct tcp_keepalive *k;
4941 int keepalive, keepidle, keepintvl;
4943 if (!in_buff || in_size < sizeof(struct tcp_keepalive))
4945 SetLastError(WSAEFAULT);
4946 return SOCKET_ERROR;
4949 k = in_buff;
4950 keepalive = k->onoff ? 1 : 0;
4951 keepidle = max( 1, (k->keepalivetime + 500) / 1000 );
4952 keepintvl = max( 1, (k->keepaliveinterval + 500) / 1000 );
4954 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
4956 fd = get_sock_fd(s, 0, NULL);
4957 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
4958 status = WSAEINVAL;
4959 #if defined(TCP_KEEPIDLE) || defined(TCP_KEEPINTVL)
4960 /* these values need to be set only if SO_KEEPALIVE is enabled */
4961 else if(keepalive)
4963 #ifndef TCP_KEEPIDLE
4964 FIXME("ignoring keepalive timeout\n");
4965 #else
4966 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
4967 status = WSAEINVAL;
4968 else
4969 #endif
4970 #ifdef TCP_KEEPINTVL
4971 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
4972 status = WSAEINVAL;
4973 #else
4974 FIXME("ignoring keepalive interval\n");
4975 #endif
4977 #else
4978 else
4979 FIXME("ignoring keepalive interval and timeout\n");
4980 #endif
4981 release_sock_fd(s, fd);
4982 break;
4984 case WS_SIO_ROUTING_INTERFACE_QUERY:
4986 struct WS_sockaddr *daddr = (struct WS_sockaddr *)in_buff;
4987 struct WS_sockaddr_in *daddr_in = (struct WS_sockaddr_in *)daddr;
4988 struct WS_sockaddr_in *saddr_in = out_buff;
4989 MIB_IPFORWARDROW row;
4990 PMIB_IPADDRTABLE ipAddrTable = NULL;
4991 DWORD size, i, found_index;
4993 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
4995 if (!in_buff || in_size < sizeof(struct WS_sockaddr) ||
4996 !out_buff || out_size < sizeof(struct WS_sockaddr_in) || !ret_size)
4998 SetLastError(WSAEFAULT);
4999 return SOCKET_ERROR;
5001 if (daddr->sa_family != WS_AF_INET)
5003 FIXME("unsupported address family %d\n", daddr->sa_family);
5004 status = WSAEAFNOSUPPORT;
5005 break;
5007 if (GetBestRoute(daddr_in->sin_addr.S_un.S_addr, 0, &row) != NOERROR ||
5008 GetIpAddrTable(NULL, &size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
5010 status = WSAEFAULT;
5011 break;
5013 ipAddrTable = HeapAlloc(GetProcessHeap(), 0, size);
5014 if (GetIpAddrTable(ipAddrTable, &size, FALSE))
5016 HeapFree(GetProcessHeap(), 0, ipAddrTable);
5017 status = WSAEFAULT;
5018 break;
5020 for (i = 0, found_index = ipAddrTable->dwNumEntries;
5021 i < ipAddrTable->dwNumEntries; i++)
5023 if (ipAddrTable->table[i].dwIndex == row.dwForwardIfIndex)
5024 found_index = i;
5026 if (found_index == ipAddrTable->dwNumEntries)
5028 ERR("no matching IP address for interface %d\n",
5029 row.dwForwardIfIndex);
5030 HeapFree(GetProcessHeap(), 0, ipAddrTable);
5031 status = WSAEFAULT;
5032 break;
5034 saddr_in->sin_family = WS_AF_INET;
5035 saddr_in->sin_addr.S_un.S_addr = ipAddrTable->table[found_index].dwAddr;
5036 saddr_in->sin_port = 0;
5037 total = sizeof(struct WS_sockaddr_in);
5038 HeapFree(GetProcessHeap(), 0, ipAddrTable);
5039 break;
5041 case WS_SIO_SET_COMPATIBILITY_MODE:
5042 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
5043 status = WSAEOPNOTSUPP;
5044 break;
5045 case WS_SIO_UDP_CONNRESET:
5046 FIXME("WS_SIO_UDP_CONNRESET stub\n");
5047 break;
5048 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
5049 SetLastError(WSAEOPNOTSUPP);
5050 return SOCKET_ERROR;
5051 default:
5052 status = WSAEOPNOTSUPP;
5053 break;
5056 if (status == WSAEOPNOTSUPP)
5058 status = server_ioctl_sock(s, code, in_buff, in_size, out_buff, out_size, &total,
5059 overlapped, completion);
5060 if (status != WSAEOPNOTSUPP)
5062 if (status == 0 || status == WSA_IO_PENDING)
5063 TRACE("-> %s request\n", debugstr_wsaioctl(code));
5064 else
5065 ERR("-> %s request failed with status 0x%x\n", debugstr_wsaioctl(code), status);
5067 /* overlapped and completion operations will be handled by the server */
5068 completion = NULL;
5069 overlapped = NULL;
5071 else
5072 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code));
5075 if (completion)
5077 FIXME( "completion routine %p not supported\n", completion );
5079 else if (overlapped)
5081 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
5082 overlapped->Internal = status;
5083 overlapped->InternalHigh = total;
5084 if (overlapped->hEvent) NtSetEvent( overlapped->hEvent, NULL );
5085 if (cvalue) WS_AddCompletion( HANDLE2SOCKET(s), cvalue, status, total );
5088 if (!status)
5090 if (ret_size) *ret_size = total;
5091 return 0;
5093 SetLastError( status );
5094 return SOCKET_ERROR;
5098 /***********************************************************************
5099 * ioctlsocket (WS2_32.10)
5101 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
5103 DWORD ret_size;
5104 return WSAIoctl( s, cmd, argp, sizeof(WS_u_long), argp, sizeof(WS_u_long), &ret_size, NULL, NULL );
5107 /***********************************************************************
5108 * listen (WS2_32.13)
5110 int WINAPI WS_listen(SOCKET s, int backlog)
5112 int fd = get_sock_fd( s, FILE_READ_DATA, NULL ), ret = SOCKET_ERROR;
5114 TRACE("socket %04lx, backlog %d\n", s, backlog);
5115 if (fd != -1)
5117 int bound = is_fd_bound(fd, NULL, NULL);
5119 if (bound <= 0)
5121 SetLastError(bound == -1 ? wsaErrno() : WSAEINVAL);
5123 else if (listen(fd, backlog) == 0)
5125 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
5126 FD_WINE_LISTENING,
5127 FD_CONNECT|FD_WINE_CONNECTED);
5128 ret = 0;
5130 else
5131 SetLastError(wsaErrno());
5132 release_sock_fd( s, fd );
5134 else
5135 SetLastError(WSAENOTSOCK);
5136 return ret;
5139 /***********************************************************************
5140 * recv (WS2_32.16)
5142 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
5144 DWORD n, dwFlags = flags;
5145 WSABUF wsabuf;
5147 wsabuf.len = len;
5148 wsabuf.buf = buf;
5150 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
5151 return SOCKET_ERROR;
5152 else
5153 return n;
5156 /***********************************************************************
5157 * recvfrom (WS2_32.17)
5159 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
5160 struct WS_sockaddr *from, int *fromlen)
5162 DWORD n, dwFlags = flags;
5163 WSABUF wsabuf;
5165 wsabuf.len = len;
5166 wsabuf.buf = buf;
5168 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL, NULL) == SOCKET_ERROR )
5169 return SOCKET_ERROR;
5170 else
5171 return n;
5174 /* allocate a poll array for the corresponding fd sets */
5175 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
5176 const WS_fd_set *exceptfds, int *count_ptr )
5178 unsigned int i, j = 0, count = 0;
5179 struct pollfd *fds;
5180 struct per_thread_data *ptb = get_per_thread_data();
5182 if (readfds) count += readfds->fd_count;
5183 if (writefds) count += writefds->fd_count;
5184 if (exceptfds) count += exceptfds->fd_count;
5185 *count_ptr = count;
5186 if (!count)
5188 SetLastError(WSAEINVAL);
5189 return NULL;
5192 /* check if the cache can hold all descriptors, if not do the resizing */
5193 if (ptb->fd_count < count)
5195 if (!(fds = HeapAlloc(GetProcessHeap(), 0, count * sizeof(fds[0]))))
5197 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
5198 return NULL;
5200 HeapFree(GetProcessHeap(), 0, ptb->fd_cache);
5201 ptb->fd_cache = fds;
5202 ptb->fd_count = count;
5204 else
5205 fds = ptb->fd_cache;
5207 if (readfds)
5208 for (i = 0; i < readfds->fd_count; i++, j++)
5210 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
5211 if (fds[j].fd == -1) goto failed;
5212 fds[j].revents = 0;
5213 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1)
5215 fds[j].events = POLLIN;
5217 else
5219 release_sock_fd( readfds->fd_array[i], fds[j].fd );
5220 fds[j].fd = -1;
5221 fds[j].events = 0;
5224 if (writefds)
5225 for (i = 0; i < writefds->fd_count; i++, j++)
5227 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
5228 if (fds[j].fd == -1) goto failed;
5229 fds[j].revents = 0;
5230 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1 ||
5231 _get_fd_type(fds[j].fd) == SOCK_DGRAM)
5233 fds[j].events = POLLOUT;
5235 else
5237 release_sock_fd( writefds->fd_array[i], fds[j].fd );
5238 fds[j].fd = -1;
5239 fds[j].events = 0;
5242 if (exceptfds)
5243 for (i = 0; i < exceptfds->fd_count; i++, j++)
5245 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
5246 if (fds[j].fd == -1) goto failed;
5247 fds[j].revents = 0;
5248 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1)
5250 int oob_inlined = 0;
5251 socklen_t olen = sizeof(oob_inlined);
5253 fds[j].events = POLLHUP;
5255 /* Check if we need to test for urgent data or not */
5256 getsockopt(fds[j].fd, SOL_SOCKET, SO_OOBINLINE, (char*) &oob_inlined, &olen);
5257 if (!oob_inlined)
5258 fds[j].events |= POLLPRI;
5260 else
5262 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
5263 fds[j].fd = -1;
5264 fds[j].events = 0;
5267 return fds;
5269 failed:
5270 count = j;
5271 j = 0;
5272 if (readfds)
5273 for (i = 0; i < readfds->fd_count && j < count; i++, j++)
5274 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
5275 if (writefds)
5276 for (i = 0; i < writefds->fd_count && j < count; i++, j++)
5277 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
5278 if (exceptfds)
5279 for (i = 0; i < exceptfds->fd_count && j < count; i++, j++)
5280 if (fds[j].fd != -1) release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
5281 return NULL;
5284 /* release the file descriptor obtained in fd_sets_to_poll */
5285 /* must be called with the original fd_set arrays, before calling get_poll_results */
5286 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
5287 const WS_fd_set *exceptfds, struct pollfd *fds )
5289 unsigned int i, j = 0;
5291 if (readfds)
5293 for (i = 0; i < readfds->fd_count; i++, j++)
5294 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
5296 if (writefds)
5298 for (i = 0; i < writefds->fd_count; i++, j++)
5299 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
5301 if (exceptfds)
5303 for (i = 0; i < exceptfds->fd_count; i++, j++)
5305 if (fds[j].fd == -1) continue;
5306 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
5307 if (fds[j].revents & POLLHUP)
5309 int fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
5310 if (fd != -1)
5311 release_sock_fd( exceptfds->fd_array[i], fd );
5312 else
5313 fds[j].revents = 0;
5319 static int do_poll(struct pollfd *pollfds, int count, int timeout)
5321 struct timeval tv1, tv2;
5322 int ret, torig = timeout;
5324 if (timeout > 0) gettimeofday( &tv1, 0 );
5326 while ((ret = poll( pollfds, count, timeout )) < 0)
5328 if (errno != EINTR) break;
5329 if (timeout < 0) continue;
5330 if (timeout == 0) return 0;
5332 gettimeofday( &tv2, 0 );
5334 tv2.tv_sec -= tv1.tv_sec;
5335 tv2.tv_usec -= tv1.tv_usec;
5336 if (tv2.tv_usec < 0)
5338 tv2.tv_usec += 1000000;
5339 tv2.tv_sec -= 1;
5342 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
5343 if (timeout <= 0) return 0;
5345 return ret;
5348 /* map the poll results back into the Windows fd sets */
5349 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
5350 const struct pollfd *fds )
5352 const struct pollfd *poll_writefds = fds + (readfds ? readfds->fd_count : 0);
5353 const struct pollfd *poll_exceptfds = poll_writefds + (writefds ? writefds->fd_count : 0);
5354 unsigned int i, k, total = 0;
5356 if (readfds)
5358 for (i = k = 0; i < readfds->fd_count; i++)
5360 if (fds[i].revents ||
5361 (readfds == writefds && (poll_writefds[i].revents & POLLOUT) && !(poll_writefds[i].revents & POLLHUP)) ||
5362 (readfds == exceptfds && poll_exceptfds[i].revents))
5363 readfds->fd_array[k++] = readfds->fd_array[i];
5365 readfds->fd_count = k;
5366 total += k;
5368 if (writefds && writefds != readfds)
5370 for (i = k = 0; i < writefds->fd_count; i++)
5372 if (((poll_writefds[i].revents & POLLOUT) && !(poll_writefds[i].revents & POLLHUP)) ||
5373 (writefds == exceptfds && poll_exceptfds[i].revents))
5374 writefds->fd_array[k++] = writefds->fd_array[i];
5376 writefds->fd_count = k;
5377 total += k;
5379 if (exceptfds && exceptfds != readfds && exceptfds != writefds)
5381 for (i = k = 0; i < exceptfds->fd_count; i++)
5382 if (poll_exceptfds[i].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
5383 exceptfds->fd_count = k;
5384 total += k;
5386 return total;
5389 /***********************************************************************
5390 * select (WS2_32.18)
5392 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
5393 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
5394 const struct WS_timeval* ws_timeout)
5396 struct pollfd *pollfds;
5397 int count, ret, timeout = -1;
5399 TRACE("read %p, write %p, excp %p timeout %p\n",
5400 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
5402 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )))
5403 return SOCKET_ERROR;
5405 if (ws_timeout)
5406 timeout = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
5408 ret = do_poll(pollfds, count, timeout);
5409 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
5411 if (ret == -1) SetLastError(wsaErrno());
5412 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
5413 return ret;
5416 /***********************************************************************
5417 * WSAPoll
5419 int WINAPI WSAPoll(WSAPOLLFD *wfds, ULONG count, int timeout)
5421 int i, ret;
5422 struct pollfd *ufds;
5424 if (!count)
5426 SetLastError(WSAEINVAL);
5427 return SOCKET_ERROR;
5429 if (!wfds)
5431 SetLastError(WSAEFAULT);
5432 return SOCKET_ERROR;
5435 if (!(ufds = HeapAlloc(GetProcessHeap(), 0, count * sizeof(ufds[0]))))
5437 SetLastError(WSAENOBUFS);
5438 return SOCKET_ERROR;
5441 for (i = 0; i < count; i++)
5443 ufds[i].fd = get_sock_fd(wfds[i].fd, 0, NULL);
5444 ufds[i].events = convert_poll_w2u(wfds[i].events);
5445 ufds[i].revents = 0;
5448 ret = do_poll(ufds, count, timeout);
5450 for (i = 0; i < count; i++)
5452 if (ufds[i].fd != -1)
5454 release_sock_fd(wfds[i].fd, ufds[i].fd);
5455 if (ufds[i].revents & POLLHUP)
5457 /* Check if the socket still exists */
5458 int fd = get_sock_fd(wfds[i].fd, 0, NULL);
5459 if (fd != -1)
5461 wfds[i].revents = WS_POLLHUP;
5462 release_sock_fd(wfds[i].fd, fd);
5464 else
5465 wfds[i].revents = WS_POLLNVAL;
5467 else
5468 wfds[i].revents = convert_poll_u2w(ufds[i].revents);
5470 else
5471 wfds[i].revents = WS_POLLNVAL;
5474 HeapFree(GetProcessHeap(), 0, ufds);
5475 return ret;
5478 /* helper to send completion messages for client-only i/o operation case */
5479 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
5480 ULONG Information )
5482 SERVER_START_REQ( add_fd_completion )
5484 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
5485 req->cvalue = CompletionValue;
5486 req->status = CompletionStatus;
5487 req->information = Information;
5488 wine_server_call( req );
5490 SERVER_END_REQ;
5494 /***********************************************************************
5495 * send (WS2_32.19)
5497 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
5499 DWORD n;
5500 WSABUF wsabuf;
5502 wsabuf.len = len;
5503 wsabuf.buf = (char*) buf;
5505 if ( WS2_sendto( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
5506 return SOCKET_ERROR;
5507 else
5508 return n;
5511 /***********************************************************************
5512 * WSASend (WS2_32.72)
5514 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5515 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
5516 LPWSAOVERLAPPED lpOverlapped,
5517 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5519 return WS2_sendto( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
5520 NULL, 0, lpOverlapped, lpCompletionRoutine );
5523 /***********************************************************************
5524 * WSASendDisconnect (WS2_32.73)
5526 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
5528 return WS_shutdown( s, SD_SEND );
5532 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5533 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
5534 const struct WS_sockaddr *to, int tolen,
5535 LPWSAOVERLAPPED lpOverlapped,
5536 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5538 unsigned int i, options;
5539 int n, fd, err, overlapped, flags;
5540 struct ws2_async *wsa = NULL, localwsa;
5541 int totalLength = 0;
5542 DWORD bytes_sent;
5543 BOOL is_blocking;
5545 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
5546 s, lpBuffers, dwBufferCount, dwFlags,
5547 to, tolen, lpOverlapped, lpCompletionRoutine);
5549 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
5550 TRACE( "fd=%d, options=%x\n", fd, options );
5552 if ( fd == -1 ) return SOCKET_ERROR;
5554 if (!lpOverlapped && !lpNumberOfBytesSent)
5556 err = WSAEFAULT;
5557 goto error;
5560 overlapped = (lpOverlapped || lpCompletionRoutine) &&
5561 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
5562 if (overlapped || dwBufferCount > 1)
5564 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[dwBufferCount]),
5565 WS2_async_send )))
5567 err = WSAEFAULT;
5568 goto error;
5571 else
5572 wsa = &localwsa;
5574 wsa->hSocket = SOCKET2HANDLE(s);
5575 wsa->addr = (struct WS_sockaddr *)to;
5576 wsa->addrlen.val = tolen;
5577 wsa->flags = dwFlags;
5578 wsa->lpFlags = &wsa->flags;
5579 wsa->control = NULL;
5580 wsa->n_iovecs = dwBufferCount;
5581 wsa->first_iovec = 0;
5582 for ( i = 0; i < dwBufferCount; i++ )
5584 wsa->iovec[i].iov_base = lpBuffers[i].buf;
5585 wsa->iovec[i].iov_len = lpBuffers[i].len;
5586 totalLength += lpBuffers[i].len;
5589 flags = convert_flags(dwFlags);
5590 n = WS2_send( fd, wsa, flags );
5591 if (n == -1 && errno != EAGAIN)
5593 err = wsaErrno();
5594 goto error;
5597 if (overlapped)
5599 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
5600 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
5602 wsa->user_overlapped = lpOverlapped;
5603 wsa->completion_func = lpCompletionRoutine;
5604 release_sock_fd( s, fd );
5606 if (n == -1 || n < totalLength)
5608 iosb->u.Status = STATUS_PENDING;
5609 iosb->Information = n == -1 ? 0 : n;
5611 if (wsa->completion_func)
5612 err = register_async( ASYNC_TYPE_WRITE, wsa->hSocket, &wsa->io, NULL,
5613 ws2_async_apc, wsa, iosb );
5614 else
5615 err = register_async( ASYNC_TYPE_WRITE, wsa->hSocket, &wsa->io, lpOverlapped->hEvent,
5616 NULL, (void *)cvalue, iosb );
5618 /* Enable the event only after starting the async. The server will deliver it as soon as
5619 the async is done. */
5620 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
5622 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
5623 SetLastError(NtStatusToWSAError( err ));
5624 return SOCKET_ERROR;
5627 iosb->u.Status = STATUS_SUCCESS;
5628 iosb->Information = n;
5629 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = n;
5630 if (!wsa->completion_func)
5632 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
5633 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
5634 HeapFree( GetProcessHeap(), 0, wsa );
5636 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
5637 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
5638 SetLastError(ERROR_SUCCESS);
5639 return 0;
5642 if ((err = _is_blocking( s, &is_blocking )))
5644 err = NtStatusToWSAError( err );
5645 goto error;
5648 if ( is_blocking )
5650 /* On a blocking non-overlapped stream socket,
5651 * sending blocks until the entire buffer is sent. */
5652 DWORD timeout_start = GetTickCount();
5654 bytes_sent = n == -1 ? 0 : n;
5656 while (wsa->first_iovec < wsa->n_iovecs)
5658 struct pollfd pfd;
5659 int poll_timeout = -1;
5660 INT64 timeout = get_rcvsnd_timeo(fd, FALSE);
5662 if (timeout)
5664 timeout -= GetTickCount() - timeout_start;
5665 if (timeout < 0) poll_timeout = 0;
5666 else poll_timeout = timeout <= INT_MAX ? timeout : INT_MAX;
5669 pfd.fd = fd;
5670 pfd.events = POLLOUT;
5672 if (!poll_timeout || !poll( &pfd, 1, poll_timeout ))
5674 err = WSAETIMEDOUT;
5675 goto error; /* msdn says a timeout in send is fatal */
5678 n = WS2_send( fd, wsa, flags );
5679 if (n == -1 && errno != EAGAIN)
5681 err = wsaErrno();
5682 goto error;
5685 if (n >= 0)
5686 bytes_sent += n;
5689 else /* non-blocking */
5691 if (n < totalLength)
5692 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
5693 if (n == -1)
5695 err = WSAEWOULDBLOCK;
5696 goto error;
5698 bytes_sent = n;
5701 TRACE(" -> %i bytes\n", bytes_sent);
5703 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = bytes_sent;
5704 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
5705 release_sock_fd( s, fd );
5706 SetLastError(ERROR_SUCCESS);
5707 return 0;
5709 error:
5710 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
5711 release_sock_fd( s, fd );
5712 WARN(" -> ERROR %d\n", err);
5713 SetLastError(err);
5714 return SOCKET_ERROR;
5717 /***********************************************************************
5718 * WSASendTo (WS2_32.74)
5720 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5721 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
5722 const struct WS_sockaddr *to, int tolen,
5723 LPWSAOVERLAPPED lpOverlapped,
5724 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5726 return WS2_sendto( s, lpBuffers, dwBufferCount,
5727 lpNumberOfBytesSent, dwFlags,
5728 to, tolen,
5729 lpOverlapped, lpCompletionRoutine );
5732 /***********************************************************************
5733 * sendto (WS2_32.20)
5735 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
5736 const struct WS_sockaddr *to, int tolen)
5738 DWORD n;
5739 WSABUF wsabuf;
5741 wsabuf.len = len;
5742 wsabuf.buf = (char*) buf;
5744 if ( WS2_sendto(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
5745 return SOCKET_ERROR;
5746 else
5747 return n;
5750 /***********************************************************************
5751 * setsockopt (WS2_32.21)
5753 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
5754 const char *optval, int optlen)
5756 int fd;
5757 int woptval;
5758 struct linger linger;
5759 struct timeval tval;
5761 TRACE("(socket %04lx, %s, optval %s, optlen %d)\n", s,
5762 debugstr_sockopt(level, optname), debugstr_optval(optval, optlen),
5763 optlen);
5765 /* some broken apps pass the value directly instead of a pointer to it */
5766 if(optlen && IS_INTRESOURCE(optval))
5768 SetLastError(WSAEFAULT);
5769 return SOCKET_ERROR;
5772 switch(level)
5774 case WS_SOL_SOCKET:
5775 switch(optname)
5777 /* Some options need some conversion before they can be sent to
5778 * setsockopt. The conversions are done here, then they will fall through
5779 * to the general case. Special options that are not passed to
5780 * setsockopt follow below that.*/
5782 case WS_SO_DONTLINGER:
5783 if (!optval)
5785 SetLastError(WSAEFAULT);
5786 return SOCKET_ERROR;
5788 linger.l_onoff = *(const int*)optval == 0;
5789 linger.l_linger = 0;
5790 level = SOL_SOCKET;
5791 optname = SO_LINGER;
5792 optval = (char*)&linger;
5793 optlen = sizeof(struct linger);
5794 break;
5796 case WS_SO_LINGER:
5797 if (!optval)
5799 SetLastError(WSAEFAULT);
5800 return SOCKET_ERROR;
5802 linger.l_onoff = ((LINGER*)optval)->l_onoff;
5803 linger.l_linger = ((LINGER*)optval)->l_linger;
5804 level = SOL_SOCKET;
5805 optname = SO_LINGER;
5806 optval = (char*)&linger;
5807 optlen = sizeof(struct linger);
5808 break;
5810 case WS_SO_RCVBUF:
5811 if (*(const int*)optval < 2048)
5813 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
5814 return 0;
5816 /* Fall through */
5818 /* The options listed here don't need any special handling. Thanks to
5819 * the conversion happening above, options from there will fall through
5820 * to this, too.*/
5821 case WS_SO_ACCEPTCONN:
5822 case WS_SO_BROADCAST:
5823 case WS_SO_ERROR:
5824 case WS_SO_KEEPALIVE:
5825 case WS_SO_OOBINLINE:
5826 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
5827 * however, using it the BSD way fixes bug 8513 and seems to be what
5828 * most programmers assume, anyway */
5829 case WS_SO_REUSEADDR:
5830 case WS_SO_SNDBUF:
5831 case WS_SO_TYPE:
5832 convert_sockopt(&level, &optname);
5833 break;
5835 /* SO_DEBUG is a privileged operation, ignore it. */
5836 case WS_SO_DEBUG:
5837 TRACE("Ignoring SO_DEBUG\n");
5838 return 0;
5840 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
5841 * socket. According to MSDN, this option is silently ignored.*/
5842 case WS_SO_DONTROUTE:
5843 TRACE("Ignoring SO_DONTROUTE\n");
5844 return 0;
5846 /* Stops two sockets from being bound to the same port. Always happens
5847 * on unix systems, so just drop it. */
5848 case WS_SO_EXCLUSIVEADDRUSE:
5849 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
5850 return 0;
5852 /* After a ConnectEx call succeeds, the socket can't be used with half of the
5853 * normal winsock functions on windows. We don't have that problem. */
5854 case WS_SO_UPDATE_CONNECT_CONTEXT:
5855 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
5856 return 0;
5858 /* After a AcceptEx call succeeds, the socket can't be used with half of the
5859 * normal winsock functions on windows. We don't have that problem. */
5860 case WS_SO_UPDATE_ACCEPT_CONTEXT:
5861 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
5862 return 0;
5864 /* SO_OPENTYPE does not require a valid socket handle. */
5865 case WS_SO_OPENTYPE:
5866 if (!optlen || optlen < sizeof(int) || !optval)
5868 SetLastError(WSAEFAULT);
5869 return SOCKET_ERROR;
5871 get_per_thread_data()->opentype = *(const int *)optval;
5872 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
5873 return 0;
5875 #ifdef SO_RCVTIMEO
5876 case WS_SO_RCVTIMEO:
5877 #endif
5878 #ifdef SO_SNDTIMEO
5879 case WS_SO_SNDTIMEO:
5880 #endif
5881 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
5882 if (optval && optlen == sizeof(UINT32)) {
5883 /* WinSock passes milliseconds instead of struct timeval */
5884 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
5885 tval.tv_sec = *(const UINT32*)optval / 1000;
5886 /* min of 500 milliseconds */
5887 if (tval.tv_sec == 0 && tval.tv_usec && tval.tv_usec < 500000)
5888 tval.tv_usec = 500000;
5889 optlen = sizeof(struct timeval);
5890 optval = (char*)&tval;
5891 } else if (optlen == sizeof(struct timeval)) {
5892 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
5893 } else {
5894 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
5895 return 0;
5897 convert_sockopt(&level, &optname);
5898 break;
5899 #endif
5901 case WS_SO_RANDOMIZE_PORT:
5902 FIXME("Ignoring WS_SO_RANDOMIZE_PORT\n");
5903 return 0;
5905 case WS_SO_PORT_SCALABILITY:
5906 FIXME("Ignoring WS_SO_PORT_SCALABILITY\n");
5907 return 0;
5909 case WS_SO_REUSE_UNICASTPORT:
5910 FIXME("Ignoring WS_SO_REUSE_UNICASTPORT\n");
5911 return 0;
5913 case WS_SO_REUSE_MULTICASTPORT:
5914 FIXME("Ignoring WS_SO_REUSE_MULTICASTPORT\n");
5915 return 0;
5917 default:
5918 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
5919 SetLastError(WSAENOPROTOOPT);
5920 return SOCKET_ERROR;
5922 break; /* case WS_SOL_SOCKET */
5924 #ifdef HAS_IPX
5925 case WS_NSPROTO_IPX:
5926 switch(optname)
5928 case WS_IPX_PTYPE:
5929 return set_ipx_packettype(s, *(int*)optval);
5931 case WS_IPX_FILTERPTYPE:
5932 /* Sets the receive filter packet type, at the moment we don't support it */
5933 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
5934 /* Returning 0 is better for now than returning a SOCKET_ERROR */
5935 return 0;
5937 default:
5938 FIXME("opt_name:%x\n", optname);
5939 return SOCKET_ERROR;
5941 break; /* case WS_NSPROTO_IPX */
5942 #endif
5944 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
5945 case WS_IPPROTO_TCP:
5946 switch(optname)
5948 case WS_TCP_NODELAY:
5949 convert_sockopt(&level, &optname);
5950 break;
5951 default:
5952 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
5953 return SOCKET_ERROR;
5955 break;
5957 case WS_IPPROTO_IP:
5958 switch(optname)
5960 case WS_IP_ADD_MEMBERSHIP:
5961 case WS_IP_DROP_MEMBERSHIP:
5962 #ifdef IP_HDRINCL
5963 case WS_IP_HDRINCL:
5964 #endif
5965 case WS_IP_MULTICAST_IF:
5966 case WS_IP_MULTICAST_LOOP:
5967 case WS_IP_MULTICAST_TTL:
5968 case WS_IP_OPTIONS:
5969 #ifdef IP_PKTINFO
5970 case WS_IP_PKTINFO:
5971 #endif
5972 case WS_IP_TOS:
5973 case WS_IP_TTL:
5974 #ifdef IP_UNICAST_IF
5975 case WS_IP_UNICAST_IF:
5976 #endif
5977 convert_sockopt(&level, &optname);
5978 break;
5979 case WS_IP_DONTFRAGMENT:
5980 return set_dont_fragment(s, IPPROTO_IP, *(BOOL *)optval) ? 0 : SOCKET_ERROR;
5981 default:
5982 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
5983 return SOCKET_ERROR;
5985 break;
5987 case WS_IPPROTO_IPV6:
5988 switch(optname)
5990 #ifdef IPV6_ADD_MEMBERSHIP
5991 case WS_IPV6_ADD_MEMBERSHIP:
5992 #endif
5993 #ifdef IPV6_DROP_MEMBERSHIP
5994 case WS_IPV6_DROP_MEMBERSHIP:
5995 #endif
5996 case WS_IPV6_MULTICAST_IF:
5997 case WS_IPV6_MULTICAST_HOPS:
5998 case WS_IPV6_MULTICAST_LOOP:
5999 case WS_IPV6_UNICAST_HOPS:
6000 #ifdef IPV6_UNICAST_IF
6001 case WS_IPV6_UNICAST_IF:
6002 #endif
6003 convert_sockopt(&level, &optname);
6004 break;
6005 case WS_IPV6_DONTFRAG:
6006 return set_dont_fragment(s, IPPROTO_IPV6, *(BOOL *)optval) ? 0 : SOCKET_ERROR;
6007 case WS_IPV6_PROTECTION_LEVEL:
6008 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
6009 return 0;
6010 case WS_IPV6_V6ONLY:
6012 union generic_unix_sockaddr uaddr;
6013 socklen_t uaddrlen;
6014 int bound;
6016 fd = get_sock_fd( s, 0, NULL );
6017 if (fd == -1) return SOCKET_ERROR;
6019 bound = is_fd_bound(fd, &uaddr, &uaddrlen);
6020 release_sock_fd( s, fd );
6021 if (bound == 0 && uaddr.addr.sa_family == AF_INET)
6023 /* Changing IPV6_V6ONLY succeeds on AF_INET (IPv4) socket
6024 * on Windows (with IPv6 support) if the socket is unbound.
6025 * It is essentially a noop, though Windows does store the value
6027 WARN("Silently ignoring IPPROTO_IPV6+IPV6_V6ONLY on AF_INET socket\n");
6028 return 0;
6030 level = IPPROTO_IPV6;
6031 optname = IPV6_V6ONLY;
6032 break;
6034 default:
6035 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
6036 return SOCKET_ERROR;
6038 break;
6040 default:
6041 WARN("Unknown level: 0x%08x\n", level);
6042 SetLastError(WSAEINVAL);
6043 return SOCKET_ERROR;
6044 } /* end switch(level) */
6046 /* avoid endianness issues if argument is a 16-bit int */
6047 if (optval && optlen < sizeof(int))
6049 woptval= *((const INT16 *) optval);
6050 optval= (char*) &woptval;
6051 woptval&= (1 << optlen * 8) - 1;
6052 optlen=sizeof(int);
6054 fd = get_sock_fd( s, 0, NULL );
6055 if (fd == -1) return SOCKET_ERROR;
6057 if (setsockopt(fd, level, optname, optval, optlen) == 0)
6059 #ifdef __APPLE__
6060 if (level == SOL_SOCKET && optname == SO_REUSEADDR &&
6061 setsockopt(fd, level, SO_REUSEPORT, optval, optlen) != 0)
6063 SetLastError(wsaErrno());
6064 release_sock_fd( s, fd );
6065 return SOCKET_ERROR;
6067 #endif
6068 release_sock_fd( s, fd );
6069 return 0;
6071 TRACE("Setting socket error, %d\n", wsaErrno());
6072 SetLastError(wsaErrno());
6073 release_sock_fd( s, fd );
6075 return SOCKET_ERROR;
6078 /***********************************************************************
6079 * shutdown (WS2_32.22)
6081 int WINAPI WS_shutdown(SOCKET s, int how)
6083 int fd, err = WSAENOTSOCK;
6084 unsigned int options = 0, clear_flags = 0;
6086 fd = get_sock_fd( s, 0, &options );
6087 TRACE("socket %04lx, how 0x%x, options 0x%x\n", s, how, options );
6089 if (fd == -1)
6090 return SOCKET_ERROR;
6092 switch( how )
6094 case SD_RECEIVE: /* drop receives */
6095 clear_flags |= FD_READ;
6096 break;
6097 case SD_SEND: /* drop sends */
6098 clear_flags |= FD_WRITE;
6099 break;
6100 case SD_BOTH: /* drop all */
6101 clear_flags |= FD_READ|FD_WRITE;
6102 /*fall through */
6103 default:
6104 clear_flags |= FD_WINE_LISTENING;
6107 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
6109 switch ( how )
6111 case SD_RECEIVE:
6112 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
6113 break;
6114 case SD_SEND:
6115 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
6116 break;
6117 case SD_BOTH:
6118 default:
6119 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
6120 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
6121 break;
6123 if (err) goto error;
6125 else /* non-overlapped mode */
6127 if ( shutdown( fd, how ) )
6129 err = wsaErrno();
6130 goto error;
6134 release_sock_fd( s, fd );
6135 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
6136 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
6137 return 0;
6139 error:
6140 release_sock_fd( s, fd );
6141 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
6142 SetLastError( err );
6143 return SOCKET_ERROR;
6146 /***********************************************************************
6147 * socket (WS2_32.23)
6149 SOCKET WINAPI WS_socket(int af, int type, int protocol)
6151 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
6153 return WSASocketW( af, type, protocol, NULL, 0,
6154 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
6158 /***********************************************************************
6159 * gethostbyaddr (WS2_32.51)
6161 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
6163 struct WS_hostent *retval = NULL;
6164 struct hostent* host;
6165 int unixtype = convert_af_w2u(type);
6166 const char *paddr = addr;
6167 unsigned long loopback;
6168 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6169 char *extrabuf;
6170 int ebufsize = 1024;
6171 struct hostent hostentry;
6172 int locerr = ENOBUFS;
6173 #endif
6175 /* convert back the magic loopback address if necessary */
6176 if (unixtype == AF_INET && len == 4 && !memcmp(addr, magic_loopback_addr, 4))
6178 loopback = htonl(INADDR_LOOPBACK);
6179 paddr = (char*) &loopback;
6182 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6183 host = NULL;
6184 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
6185 while(extrabuf) {
6186 int res = gethostbyaddr_r(paddr, len, unixtype,
6187 &hostentry, extrabuf, ebufsize, &host, &locerr);
6188 if (res != ERANGE) break;
6189 ebufsize *=2;
6190 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
6192 if (host) retval = WS_dup_he(host);
6193 else SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
6194 HeapFree(GetProcessHeap(),0,extrabuf);
6195 #else
6196 EnterCriticalSection( &csWSgetXXXbyYYY );
6197 host = gethostbyaddr(paddr, len, unixtype);
6198 if (host) retval = WS_dup_he(host);
6199 else SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
6200 LeaveCriticalSection( &csWSgetXXXbyYYY );
6201 #endif
6202 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
6203 return retval;
6206 /***********************************************************************
6207 * WS_compare_routes_by_metric_asc (INTERNAL)
6209 * Comparison function for qsort(), for sorting two routes (struct route)
6210 * by metric in ascending order.
6212 static int WS_compare_routes_by_metric_asc(const void *left, const void *right)
6214 const struct route *a = left, *b = right;
6215 if (a->default_route && b->default_route)
6216 return a->default_route - b->default_route;
6217 if (a->default_route && !b->default_route)
6218 return -1;
6219 if (b->default_route && !a->default_route)
6220 return 1;
6221 return a->metric - b->metric;
6224 /***********************************************************************
6225 * WS_get_local_ips (INTERNAL)
6227 * Returns the list of local IP addresses by going through the network
6228 * adapters and using the local routing table to sort the addresses
6229 * from highest routing priority to lowest routing priority. This
6230 * functionality is inferred from the description for obtaining local
6231 * IP addresses given in the Knowledge Base Article Q160215.
6233 * Please note that the returned hostent is only freed when the thread
6234 * closes and is replaced if another hostent is requested.
6236 static struct WS_hostent* WS_get_local_ips( char *hostname )
6238 int numroutes = 0, i, j, default_routes = 0;
6239 DWORD n;
6240 PIP_ADAPTER_INFO adapters = NULL, k;
6241 struct WS_hostent *hostlist = NULL;
6242 PMIB_IPFORWARDTABLE routes = NULL;
6243 struct route *route_addrs = NULL;
6244 DWORD adap_size, route_size;
6246 /* Obtain the size of the adapter list and routing table, also allocate memory */
6247 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
6248 return NULL;
6249 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
6250 return NULL;
6251 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
6252 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
6253 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
6254 if (adapters == NULL || routes == NULL || route_addrs == NULL)
6255 goto cleanup;
6256 /* Obtain the adapter list and the full routing table */
6257 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
6258 goto cleanup;
6259 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
6260 goto cleanup;
6261 /* Store the interface associated with each route */
6262 for (n = 0; n < routes->dwNumEntries; n++)
6264 IF_INDEX ifindex;
6265 DWORD ifmetric, ifdefault = 0;
6266 BOOL exists = FALSE;
6268 /* Check if this is a default route (there may be more than one) */
6269 if (!routes->table[n].dwForwardDest)
6270 ifdefault = ++default_routes;
6271 else if (routes->table[n].u1.ForwardType != MIB_IPROUTE_TYPE_DIRECT)
6272 continue;
6273 ifindex = routes->table[n].dwForwardIfIndex;
6274 ifmetric = routes->table[n].dwForwardMetric1;
6275 /* Only store the lowest valued metric for an interface */
6276 for (j = 0; j < numroutes; j++)
6278 if (route_addrs[j].interface == ifindex)
6280 if (route_addrs[j].metric > ifmetric)
6281 route_addrs[j].metric = ifmetric;
6282 exists = TRUE;
6285 if (exists)
6286 continue;
6287 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
6288 if (route_addrs == NULL)
6289 goto cleanup; /* Memory allocation error, fail gracefully */
6290 route_addrs[numroutes].interface = ifindex;
6291 route_addrs[numroutes].metric = ifmetric;
6292 route_addrs[numroutes].default_route = ifdefault;
6293 /* If no IP is found in the next step (for whatever reason)
6294 * then fall back to the magic loopback address.
6296 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
6297 numroutes++;
6299 if (numroutes == 0)
6300 goto cleanup; /* No routes, fall back to the Magic IP */
6301 /* Find the IP address associated with each found interface */
6302 for (i = 0; i < numroutes; i++)
6304 for (k = adapters; k != NULL; k = k->Next)
6306 char *ip = k->IpAddressList.IpAddress.String;
6308 if (route_addrs[i].interface == k->Index)
6309 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
6312 /* Allocate a hostent and enough memory for all the IPs,
6313 * including the NULL at the end of the list.
6315 hostlist = WS_create_he(hostname, 1, 0, numroutes+1, sizeof(struct in_addr));
6316 if (hostlist == NULL)
6317 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
6318 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
6319 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
6320 hostlist->h_addrtype = AF_INET;
6321 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
6322 /* Reorder the entries before placing them in the host list. Windows expects
6323 * the IP list in order from highest priority to lowest (the critical thing
6324 * is that most applications expect the first IP to be the default route).
6326 if (numroutes > 1)
6327 qsort(route_addrs, numroutes, sizeof(struct route), WS_compare_routes_by_metric_asc);
6329 for (i = 0; i < numroutes; i++)
6330 (*(struct in_addr *) hostlist->h_addr_list[i]) = route_addrs[i].addr;
6332 /* Cleanup all allocated memory except the address list,
6333 * the address list is used by the calling app.
6335 cleanup:
6336 HeapFree(GetProcessHeap(), 0, route_addrs);
6337 HeapFree(GetProcessHeap(), 0, adapters);
6338 HeapFree(GetProcessHeap(), 0, routes);
6339 return hostlist;
6342 /***********************************************************************
6343 * gethostbyname (WS2_32.52)
6345 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
6347 struct WS_hostent *retval = NULL;
6348 struct hostent* host;
6349 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6350 char *extrabuf;
6351 int ebufsize=1024;
6352 struct hostent hostentry;
6353 int locerr = ENOBUFS;
6354 #endif
6355 char hostname[100];
6356 if(!num_startup) {
6357 SetLastError(WSANOTINITIALISED);
6358 return NULL;
6360 if( gethostname( hostname, 100) == -1) {
6361 SetLastError(WSAENOBUFS); /* appropriate ? */
6362 return retval;
6364 if( !name || !name[0]) {
6365 name = hostname;
6367 /* If the hostname of the local machine is requested then return the
6368 * complete list of local IP addresses */
6369 if(strcmp(name, hostname) == 0)
6370 retval = WS_get_local_ips(hostname);
6371 /* If any other hostname was requested (or the routing table lookup failed)
6372 * then return the IP found by the host OS */
6373 if(retval == NULL)
6375 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6376 host = NULL;
6377 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
6378 while(extrabuf) {
6379 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
6380 if( res != ERANGE) break;
6381 ebufsize *=2;
6382 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
6384 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
6385 #else
6386 EnterCriticalSection( &csWSgetXXXbyYYY );
6387 host = gethostbyname(name);
6388 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
6389 #endif
6390 if (host) retval = WS_dup_he(host);
6391 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6392 HeapFree(GetProcessHeap(),0,extrabuf);
6393 #else
6394 LeaveCriticalSection( &csWSgetXXXbyYYY );
6395 #endif
6397 if (retval && retval->h_addr_list[0][0] == 127 &&
6398 strcmp(name, "localhost") != 0)
6400 /* hostname != "localhost" but has loopback address. replace by our
6401 * special address.*/
6402 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
6404 TRACE( "%s ret %p\n", debugstr_a(name), retval );
6405 return retval;
6409 /***********************************************************************
6410 * getprotobyname (WS2_32.53)
6412 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
6414 struct WS_protoent* retval = NULL;
6415 #ifdef HAVE_GETPROTOBYNAME
6416 struct protoent* proto;
6417 EnterCriticalSection( &csWSgetXXXbyYYY );
6418 if( (proto = getprotobyname(name)) != NULL )
6420 retval = WS_dup_pe(proto);
6422 else {
6423 MESSAGE("protocol %s not found; You might want to add "
6424 "this to /etc/protocols\n", debugstr_a(name) );
6425 SetLastError(WSANO_DATA);
6427 LeaveCriticalSection( &csWSgetXXXbyYYY );
6428 #endif
6429 TRACE( "%s ret %p\n", debugstr_a(name), retval );
6430 return retval;
6434 /***********************************************************************
6435 * getprotobynumber (WS2_32.54)
6437 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
6439 struct WS_protoent* retval = NULL;
6440 #ifdef HAVE_GETPROTOBYNUMBER
6441 struct protoent* proto;
6442 EnterCriticalSection( &csWSgetXXXbyYYY );
6443 if( (proto = getprotobynumber(number)) != NULL )
6445 retval = WS_dup_pe(proto);
6447 else {
6448 MESSAGE("protocol number %d not found; You might want to add "
6449 "this to /etc/protocols\n", number );
6450 SetLastError(WSANO_DATA);
6452 LeaveCriticalSection( &csWSgetXXXbyYYY );
6453 #endif
6454 TRACE("%i ret %p\n", number, retval);
6455 return retval;
6459 /***********************************************************************
6460 * getservbyname (WS2_32.55)
6462 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
6464 struct WS_servent* retval = NULL;
6465 struct servent* serv;
6466 char *name_str;
6467 char *proto_str = NULL;
6469 if (!(name_str = strdup_lower(name))) return NULL;
6471 if (proto && *proto)
6473 if (!(proto_str = strdup_lower(proto)))
6475 HeapFree( GetProcessHeap(), 0, name_str );
6476 return NULL;
6480 EnterCriticalSection( &csWSgetXXXbyYYY );
6481 serv = getservbyname(name_str, proto_str);
6482 if( serv != NULL )
6484 retval = WS_dup_se(serv);
6486 else SetLastError(WSANO_DATA);
6487 LeaveCriticalSection( &csWSgetXXXbyYYY );
6488 HeapFree( GetProcessHeap(), 0, proto_str );
6489 HeapFree( GetProcessHeap(), 0, name_str );
6490 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
6491 return retval;
6494 /***********************************************************************
6495 * freeaddrinfo (WS2_32.@)
6497 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
6499 while (res) {
6500 struct WS_addrinfo *next;
6502 HeapFree(GetProcessHeap(),0,res->ai_canonname);
6503 HeapFree(GetProcessHeap(),0,res->ai_addr);
6504 next = res->ai_next;
6505 HeapFree(GetProcessHeap(),0,res);
6506 res = next;
6510 /* helper functions for getaddrinfo()/getnameinfo() */
6511 static int convert_aiflag_w2u(int winflags) {
6512 unsigned int i;
6513 int unixflags = 0;
6515 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
6516 if (ws_aiflag_map[i][0] & winflags) {
6517 unixflags |= ws_aiflag_map[i][1];
6518 winflags &= ~ws_aiflag_map[i][0];
6520 if (winflags)
6521 FIXME("Unhandled windows AI_xxx flags 0x%x\n", winflags);
6522 return unixflags;
6525 static int convert_niflag_w2u(int winflags) {
6526 unsigned int i;
6527 int unixflags = 0;
6529 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
6530 if (ws_niflag_map[i][0] & winflags) {
6531 unixflags |= ws_niflag_map[i][1];
6532 winflags &= ~ws_niflag_map[i][0];
6534 if (winflags)
6535 FIXME("Unhandled windows NI_xxx flags 0x%x\n", winflags);
6536 return unixflags;
6539 static int convert_aiflag_u2w(int unixflags) {
6540 unsigned int i;
6541 int winflags = 0;
6543 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
6544 if (ws_aiflag_map[i][1] & unixflags) {
6545 winflags |= ws_aiflag_map[i][0];
6546 unixflags &= ~ws_aiflag_map[i][1];
6548 if (unixflags)
6549 WARN("Unhandled UNIX AI_xxx flags 0x%x\n", unixflags);
6550 return winflags;
6553 static int convert_eai_u2w(int unixret) {
6554 int i;
6556 if (!unixret) return 0;
6558 for (i=0;ws_eai_map[i][0];i++)
6559 if (ws_eai_map[i][1] == unixret)
6560 return ws_eai_map[i][0];
6562 if (unixret == EAI_SYSTEM)
6563 /* There are broken versions of glibc which return EAI_SYSTEM
6564 * and set errno to 0 instead of returning EAI_NONAME.
6566 return errno ? sock_get_error( errno ) : WS_EAI_NONAME;
6568 FIXME("Unhandled unix EAI_xxx ret %d\n", unixret);
6569 return unixret;
6572 static char *get_fqdn(void)
6574 char *ret;
6575 DWORD size = 0;
6577 GetComputerNameExA( ComputerNamePhysicalDnsFullyQualified, NULL, &size );
6578 if (GetLastError() != ERROR_MORE_DATA) return NULL;
6579 if (!(ret = HeapAlloc( GetProcessHeap(), 0, size ))) return NULL;
6580 if (!GetComputerNameExA( ComputerNamePhysicalDnsFullyQualified, ret, &size ))
6582 HeapFree( GetProcessHeap(), 0, ret );
6583 return NULL;
6585 return ret;
6588 /***********************************************************************
6589 * getaddrinfo (WS2_32.@)
6591 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
6593 #ifdef HAVE_GETADDRINFO
6594 struct addrinfo *unixaires = NULL;
6595 int result;
6596 struct addrinfo unixhints, *punixhints = NULL;
6597 char *dot, *nodeV6 = NULL, *fqdn;
6598 const char *node;
6599 size_t hostname_len = 0;
6601 *res = NULL;
6602 if (!nodename && !servname)
6604 SetLastError(WSAHOST_NOT_FOUND);
6605 return WSAHOST_NOT_FOUND;
6608 fqdn = get_fqdn();
6609 if (!fqdn) return WSA_NOT_ENOUGH_MEMORY;
6610 dot = strchr(fqdn, '.');
6611 if (dot)
6612 hostname_len = dot - fqdn;
6614 if (!nodename)
6615 node = NULL;
6616 else if (!nodename[0])
6617 node = fqdn;
6618 else
6620 node = nodename;
6622 /* Check for [ipv6] or [ipv6]:portnumber, which are supported by Windows */
6623 if (!hints || hints->ai_family == WS_AF_UNSPEC || hints->ai_family == WS_AF_INET6)
6625 char *close_bracket;
6627 if (node[0] == '[' && (close_bracket = strchr(node + 1, ']')))
6629 nodeV6 = HeapAlloc(GetProcessHeap(), 0, close_bracket - node);
6630 if (!nodeV6)
6632 HeapFree(GetProcessHeap(), 0, fqdn);
6633 return WSA_NOT_ENOUGH_MEMORY;
6635 lstrcpynA(nodeV6, node + 1, close_bracket - node);
6636 node = nodeV6;
6641 /* servname tweak required by OSX and BSD kernels */
6642 if (servname && !servname[0]) servname = "0";
6644 if (hints) {
6645 punixhints = &unixhints;
6647 memset(&unixhints, 0, sizeof(unixhints));
6648 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
6650 /* zero is a wildcard, no need to convert */
6651 if (hints->ai_family)
6652 punixhints->ai_family = convert_af_w2u(hints->ai_family);
6653 if (hints->ai_socktype)
6654 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
6655 if (hints->ai_protocol)
6656 punixhints->ai_protocol = max(convert_proto_w2u(hints->ai_protocol), 0);
6658 if (punixhints->ai_socktype < 0)
6660 SetLastError(WSAESOCKTNOSUPPORT);
6661 HeapFree(GetProcessHeap(), 0, fqdn);
6662 HeapFree(GetProcessHeap(), 0, nodeV6);
6663 return SOCKET_ERROR;
6666 /* windows allows invalid combinations of socket type and protocol, unix does not.
6667 * fix the parameters here to make getaddrinfo call always work */
6668 if (punixhints->ai_protocol == IPPROTO_TCP &&
6669 punixhints->ai_socktype != SOCK_STREAM && punixhints->ai_socktype != SOCK_SEQPACKET)
6670 punixhints->ai_socktype = 0;
6672 else if (punixhints->ai_protocol == IPPROTO_UDP && punixhints->ai_socktype != SOCK_DGRAM)
6673 punixhints->ai_socktype = 0;
6675 else if (IS_IPX_PROTO(punixhints->ai_protocol) && punixhints->ai_socktype != SOCK_DGRAM)
6676 punixhints->ai_socktype = 0;
6678 else if (punixhints->ai_protocol == IPPROTO_IPV6)
6679 punixhints->ai_protocol = 0;
6682 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
6683 result = getaddrinfo(node, servname, punixhints, &unixaires);
6685 if (result && (!hints || !(hints->ai_flags & WS_AI_NUMERICHOST))
6686 && (!strcmp(fqdn, node) || (!strncmp(fqdn, node, hostname_len) && !node[hostname_len])))
6688 /* If it didn't work it means the host name IP is not in /etc/hosts, try again
6689 * by sending a NULL host and avoid sending a NULL servname too because that
6690 * is invalid */
6691 ERR_(winediag)("Failed to resolve your host name IP\n");
6692 result = getaddrinfo(NULL, servname ? servname : "0", punixhints, &unixaires);
6694 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
6695 HeapFree(GetProcessHeap(), 0, fqdn);
6696 HeapFree(GetProcessHeap(), 0, nodeV6);
6698 if (!result) {
6699 struct addrinfo *xuai = unixaires;
6700 struct WS_addrinfo **xai = res;
6702 *xai = NULL;
6703 while (xuai) {
6704 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
6705 SIZE_T len;
6707 if (!ai)
6708 goto outofmem;
6710 *xai = ai;xai = &ai->ai_next;
6711 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
6712 ai->ai_family = convert_af_u2w(xuai->ai_family);
6713 /* copy whatever was sent in the hints */
6714 if(hints) {
6715 ai->ai_socktype = hints->ai_socktype;
6716 ai->ai_protocol = hints->ai_protocol;
6717 } else {
6718 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
6719 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
6721 if (xuai->ai_canonname) {
6722 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
6723 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
6724 if (!ai->ai_canonname)
6725 goto outofmem;
6726 strcpy(ai->ai_canonname,xuai->ai_canonname);
6728 len = xuai->ai_addrlen;
6729 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
6730 if (!ai->ai_addr)
6731 goto outofmem;
6732 ai->ai_addrlen = len;
6733 do {
6734 int winlen = ai->ai_addrlen;
6736 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
6737 ai->ai_addrlen = winlen;
6738 break;
6740 len = 2*len;
6741 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
6742 if (!ai->ai_addr)
6743 goto outofmem;
6744 ai->ai_addrlen = len;
6745 } while (1);
6746 xuai = xuai->ai_next;
6748 freeaddrinfo(unixaires);
6750 if (TRACE_ON(winsock))
6752 struct WS_addrinfo *ai = *res;
6753 while (ai)
6755 TRACE("=> %p, flags %#x, family %d, type %d, protocol %d, len %ld, name %s, addr %s\n",
6756 ai, ai->ai_flags, ai->ai_family, ai->ai_socktype, ai->ai_protocol, ai->ai_addrlen,
6757 ai->ai_canonname, debugstr_sockaddr(ai->ai_addr));
6758 ai = ai->ai_next;
6761 } else
6762 result = convert_eai_u2w(result);
6764 SetLastError(result);
6765 return result;
6767 outofmem:
6768 if (*res) WS_freeaddrinfo(*res);
6769 if (unixaires) freeaddrinfo(unixaires);
6770 return WSA_NOT_ENOUGH_MEMORY;
6771 #else
6772 FIXME("getaddrinfo() failed, not found during buildtime.\n");
6773 return EAI_FAIL;
6774 #endif
6777 static ADDRINFOEXW *addrinfo_AtoW(const struct WS_addrinfo *ai)
6779 ADDRINFOEXW *ret;
6781 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(ADDRINFOEXW)))) return NULL;
6782 ret->ai_flags = ai->ai_flags;
6783 ret->ai_family = ai->ai_family;
6784 ret->ai_socktype = ai->ai_socktype;
6785 ret->ai_protocol = ai->ai_protocol;
6786 ret->ai_addrlen = ai->ai_addrlen;
6787 ret->ai_canonname = NULL;
6788 ret->ai_addr = NULL;
6789 ret->ai_blob = NULL;
6790 ret->ai_bloblen = 0;
6791 ret->ai_provider = NULL;
6792 ret->ai_next = NULL;
6793 if (ai->ai_canonname)
6795 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
6796 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR))))
6798 HeapFree(GetProcessHeap(), 0, ret);
6799 return NULL;
6801 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
6803 if (ai->ai_addr)
6805 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, ai->ai_addrlen)))
6807 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
6808 HeapFree(GetProcessHeap(), 0, ret);
6809 return NULL;
6811 memcpy(ret->ai_addr, ai->ai_addr, ai->ai_addrlen);
6813 return ret;
6816 static ADDRINFOEXW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
6818 ADDRINFOEXW *ret, *infoW;
6820 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
6821 while (info->ai_next)
6823 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
6825 FreeAddrInfoExW(ret);
6826 return NULL;
6828 infoW = infoW->ai_next;
6829 info = info->ai_next;
6831 return ret;
6834 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
6836 struct WS_addrinfo *ret;
6838 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
6839 ret->ai_flags = ai->ai_flags;
6840 ret->ai_family = ai->ai_family;
6841 ret->ai_socktype = ai->ai_socktype;
6842 ret->ai_protocol = ai->ai_protocol;
6843 ret->ai_addrlen = ai->ai_addrlen;
6844 ret->ai_canonname = NULL;
6845 ret->ai_addr = NULL;
6846 ret->ai_next = NULL;
6847 if (ai->ai_canonname)
6849 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
6850 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
6852 HeapFree(GetProcessHeap(), 0, ret);
6853 return NULL;
6855 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
6857 if (ai->ai_addr)
6859 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
6861 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
6862 HeapFree(GetProcessHeap(), 0, ret);
6863 return NULL;
6865 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
6867 return ret;
6870 struct getaddrinfo_args
6872 OVERLAPPED *overlapped;
6873 ADDRINFOEXW **result;
6874 char *nodename;
6875 char *servname;
6878 static void WINAPI getaddrinfo_callback(TP_CALLBACK_INSTANCE *instance, void *context)
6880 struct getaddrinfo_args *args = context;
6881 OVERLAPPED *overlapped = args->overlapped;
6882 HANDLE event = overlapped->hEvent;
6883 struct WS_addrinfo *res;
6884 int ret;
6886 ret = WS_getaddrinfo(args->nodename, args->servname, NULL, &res);
6887 if (res)
6889 *args->result = addrinfo_list_AtoW(res);
6890 overlapped->u.Pointer = args->result;
6891 WS_freeaddrinfo(res);
6894 HeapFree(GetProcessHeap(), 0, args->nodename);
6895 HeapFree(GetProcessHeap(), 0, args->servname);
6896 HeapFree(GetProcessHeap(), 0, args);
6898 overlapped->Internal = ret;
6899 if (event) SetEvent(event);
6902 static int WS_getaddrinfoW(const WCHAR *nodename, const WCHAR *servname, const struct WS_addrinfo *hints, ADDRINFOEXW **res, OVERLAPPED *overlapped)
6904 int ret = EAI_MEMORY, len, i;
6905 char *nodenameA = NULL, *servnameA = NULL;
6906 struct WS_addrinfo *resA;
6907 WCHAR *local_nodenameW = (WCHAR *)nodename;
6909 *res = NULL;
6910 if (nodename)
6912 /* Is this an IDN? Most likely if any char is above the Ascii table, this
6913 * is the simplest validation possible, further validation will be done by
6914 * the native getaddrinfo() */
6915 for (i = 0; nodename[i]; i++)
6917 if (nodename[i] > 'z')
6918 break;
6920 if (nodename[i])
6922 if (hints && (hints->ai_flags & WS_AI_DISABLE_IDN_ENCODING))
6924 /* Name requires conversion but it was disabled */
6925 ret = WSAHOST_NOT_FOUND;
6926 WSASetLastError(ret);
6927 goto end;
6930 len = IdnToAscii(0, nodename, -1, NULL, 0);
6931 if (!len)
6933 ERR("Failed to convert %s to punycode\n", debugstr_w(nodename));
6934 ret = EAI_FAIL;
6935 goto end;
6937 if (!(local_nodenameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) goto end;
6938 IdnToAscii(0, nodename, -1, local_nodenameW, len);
6941 if (local_nodenameW)
6943 len = WideCharToMultiByte(CP_ACP, 0, local_nodenameW, -1, NULL, 0, NULL, NULL);
6944 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) goto end;
6945 WideCharToMultiByte(CP_ACP, 0, local_nodenameW, -1, nodenameA, len, NULL, NULL);
6947 if (servname)
6949 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
6950 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len))) goto end;
6951 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
6954 if (overlapped)
6956 struct getaddrinfo_args *args;
6958 if (!(args = HeapAlloc(GetProcessHeap(), 0, sizeof(*args)))) goto end;
6959 args->overlapped = overlapped;
6960 args->result = res;
6961 args->nodename = nodenameA;
6962 args->servname = servnameA;
6964 overlapped->Internal = WSAEINPROGRESS;
6965 if (!TrySubmitThreadpoolCallback(getaddrinfo_callback, args, NULL))
6967 HeapFree(GetProcessHeap(), 0, args);
6968 ret = GetLastError();
6969 goto end;
6973 if (local_nodenameW != nodename)
6974 HeapFree(GetProcessHeap(), 0, local_nodenameW);
6975 WSASetLastError(ERROR_IO_PENDING);
6976 return ERROR_IO_PENDING;
6979 ret = WS_getaddrinfo(nodenameA, servnameA, hints, &resA);
6980 if (!ret)
6982 *res = addrinfo_list_AtoW(resA);
6983 WS_freeaddrinfo(resA);
6986 end:
6987 if (local_nodenameW != nodename)
6988 HeapFree(GetProcessHeap(), 0, local_nodenameW);
6989 HeapFree(GetProcessHeap(), 0, nodenameA);
6990 HeapFree(GetProcessHeap(), 0, servnameA);
6991 return ret;
6994 /***********************************************************************
6995 * GetAddrInfoExW (WS2_32.@)
6997 int WINAPI GetAddrInfoExW(const WCHAR *name, const WCHAR *servname, DWORD namespace, GUID *namespace_id,
6998 const ADDRINFOEXW *hints, ADDRINFOEXW **result, struct timeval *timeout, OVERLAPPED *overlapped,
6999 LPLOOKUPSERVICE_COMPLETION_ROUTINE completion_routine, HANDLE *handle)
7001 int ret;
7003 TRACE("(%s %s %x %s %p %p %p %p %p %p)\n", debugstr_w(name), debugstr_w(servname), namespace,
7004 debugstr_guid(namespace_id), hints, result, timeout, overlapped, completion_routine, handle);
7006 if (namespace != NS_DNS)
7007 FIXME("Unsupported namespace %u\n", namespace);
7008 if (namespace_id)
7009 FIXME("Unsupported naemspace_id %s\n", debugstr_guid(namespace_id));
7010 if (hints)
7011 FIXME("Unsupported hints\n");
7012 if (timeout)
7013 FIXME("Unsupported timeout\n");
7014 if (completion_routine)
7015 FIXME("Unsupported completion_routine\n");
7016 if (handle)
7017 FIXME("Unsupported cancel handle\n");
7019 ret = WS_getaddrinfoW(name, servname, NULL, result, overlapped);
7020 if (ret) return ret;
7021 if (handle) *handle = (HANDLE)0xdeadbeef;
7022 return 0;
7025 /***********************************************************************
7026 * GetAddrInfoExOverlappedResult (WS2_32.@)
7028 int WINAPI GetAddrInfoExOverlappedResult(OVERLAPPED *overlapped)
7030 TRACE("(%p)\n", overlapped);
7031 return overlapped->Internal;
7034 /***********************************************************************
7035 * GetAddrInfoExCancel (WS2_32.@)
7037 int WINAPI GetAddrInfoExCancel(HANDLE *handle)
7039 FIXME("(%p)\n", handle);
7040 return WSA_INVALID_HANDLE;
7043 /***********************************************************************
7044 * GetAddrInfoW (WS2_32.@)
7046 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
7048 struct WS_addrinfo *hintsA = NULL;
7049 ADDRINFOEXW *resex;
7050 int ret = EAI_MEMORY;
7052 TRACE("nodename %s, servname %s, hints %p, result %p\n",
7053 debugstr_w(nodename), debugstr_w(servname), hints, res);
7055 *res = NULL;
7056 if (hints) hintsA = addrinfo_WtoA(hints);
7057 ret = WS_getaddrinfoW(nodename, servname, hintsA, &resex, NULL);
7058 WS_freeaddrinfo(hintsA);
7059 if (ret) return ret;
7061 if (resex)
7063 /* ADDRINFOEXW has layout compatible with ADDRINFOW except for ai_next field,
7064 * so we may convert it in place */
7065 *res = (ADDRINFOW*)resex;
7066 do {
7067 ((ADDRINFOW*)resex)->ai_next = (ADDRINFOW*)resex->ai_next;
7068 resex = resex->ai_next;
7069 } while (resex);
7071 return 0;
7074 /***********************************************************************
7075 * FreeAddrInfoW (WS2_32.@)
7077 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
7079 while (ai)
7081 ADDRINFOW *next;
7082 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
7083 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
7084 next = ai->ai_next;
7085 HeapFree(GetProcessHeap(), 0, ai);
7086 ai = next;
7090 /***********************************************************************
7091 * FreeAddrInfoExW (WS2_32.@)
7093 void WINAPI FreeAddrInfoExW(ADDRINFOEXW *ai)
7095 TRACE("(%p)\n", ai);
7097 while (ai)
7099 ADDRINFOEXW *next;
7100 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
7101 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
7102 next = ai->ai_next;
7103 HeapFree(GetProcessHeap(), 0, ai);
7104 ai = next;
7108 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
7109 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
7111 #ifdef HAVE_GETNAMEINFO
7112 int ret;
7113 union generic_unix_sockaddr sa_u;
7114 unsigned int size;
7116 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
7117 serv, servlen, flags);
7119 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
7120 if (!size)
7122 SetLastError(WSAEFAULT);
7123 return WSA_NOT_ENOUGH_MEMORY;
7125 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
7126 return convert_eai_u2w(ret);
7127 #else
7128 FIXME("getnameinfo() failed, not found during buildtime.\n");
7129 return EAI_FAIL;
7130 #endif
7133 int WINAPI GetNameInfoW(const SOCKADDR *sa, WS_socklen_t salen, PWCHAR host,
7134 DWORD hostlen, PWCHAR serv, DWORD servlen, INT flags)
7136 int ret;
7137 char *hostA = NULL, *servA = NULL;
7139 if (host && (!(hostA = HeapAlloc(GetProcessHeap(), 0, hostlen)))) return EAI_MEMORY;
7140 if (serv && (!(servA = HeapAlloc(GetProcessHeap(), 0, servlen))))
7142 HeapFree(GetProcessHeap(), 0, hostA);
7143 return EAI_MEMORY;
7146 ret = WS_getnameinfo(sa, salen, hostA, hostlen, servA, servlen, flags);
7147 if (!ret)
7149 if (host) MultiByteToWideChar(CP_ACP, 0, hostA, -1, host, hostlen);
7150 if (serv) MultiByteToWideChar(CP_ACP, 0, servA, -1, serv, servlen);
7153 HeapFree(GetProcessHeap(), 0, hostA);
7154 HeapFree(GetProcessHeap(), 0, servA);
7155 return ret;
7158 /***********************************************************************
7159 * getservbyport (WS2_32.56)
7161 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
7163 struct WS_servent* retval = NULL;
7164 #ifdef HAVE_GETSERVBYPORT
7165 struct servent* serv;
7166 char *proto_str = NULL;
7168 if (proto && *proto)
7170 if (!(proto_str = strdup_lower(proto))) return NULL;
7172 EnterCriticalSection( &csWSgetXXXbyYYY );
7173 if( (serv = getservbyport(port, proto_str)) != NULL ) {
7174 retval = WS_dup_se(serv);
7176 else SetLastError(WSANO_DATA);
7177 LeaveCriticalSection( &csWSgetXXXbyYYY );
7178 HeapFree( GetProcessHeap(), 0, proto_str );
7179 #endif
7180 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
7181 return retval;
7185 /***********************************************************************
7186 * gethostname (WS2_32.57)
7188 int WINAPI WS_gethostname(char *name, int namelen)
7190 char buf[256];
7191 int len;
7193 TRACE("name %p, len %d\n", name, namelen);
7195 if (!name)
7197 SetLastError(WSAEFAULT);
7198 return SOCKET_ERROR;
7201 if (gethostname(buf, sizeof(buf)) != 0)
7203 SetLastError(wsaErrno());
7204 return SOCKET_ERROR;
7207 TRACE("<- '%s'\n", buf);
7208 len = strlen(buf);
7209 if (len > 15)
7210 WARN("Windows supports NetBIOS name length up to 15 bytes!\n");
7211 if (namelen <= len)
7213 SetLastError(WSAEFAULT);
7214 WARN("<- not enough space for hostname, required %d, got %d!\n", len + 1, namelen);
7215 return SOCKET_ERROR;
7217 strcpy(name, buf);
7218 return 0;
7222 /* ------------------------------------- Windows sockets extensions -- *
7224 * ------------------------------------------------------------------- */
7226 /***********************************************************************
7227 * WSAEnumNetworkEvents (WS2_32.36)
7229 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
7231 int ret;
7232 int i;
7233 int errors[FD_MAX_EVENTS];
7235 TRACE("%04lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
7237 SERVER_START_REQ( get_socket_event )
7239 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
7240 req->service = TRUE;
7241 req->c_event = wine_server_obj_handle( hEvent );
7242 wine_server_set_reply( req, errors, sizeof(errors) );
7243 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
7245 SERVER_END_REQ;
7246 if (!ret)
7248 for (i = 0; i < FD_MAX_EVENTS; i++)
7250 if (lpEvent->lNetworkEvents & (1 << i))
7251 lpEvent->iErrorCode[i] = NtStatusToWSAError(errors[i]);
7253 return 0;
7255 SetLastError(WSAEINVAL);
7256 return SOCKET_ERROR;
7259 /***********************************************************************
7260 * WSAEventSelect (WS2_32.39)
7262 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
7264 int ret;
7266 TRACE("%04lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
7268 SERVER_START_REQ( set_socket_event )
7270 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
7271 req->mask = lEvent;
7272 req->event = wine_server_obj_handle( hEvent );
7273 req->window = 0;
7274 req->msg = 0;
7275 ret = wine_server_call( req );
7277 SERVER_END_REQ;
7278 if (!ret) return 0;
7279 SetLastError(WSAEINVAL);
7280 return SOCKET_ERROR;
7283 /**********************************************************************
7284 * WSAGetOverlappedResult (WS2_32.40)
7286 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
7287 LPDWORD lpcbTransfer, BOOL fWait,
7288 LPDWORD lpdwFlags )
7290 NTSTATUS status;
7292 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
7293 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
7295 if ( lpOverlapped == NULL )
7297 ERR( "Invalid pointer\n" );
7298 SetLastError(WSA_INVALID_PARAMETER);
7299 return FALSE;
7302 status = lpOverlapped->Internal;
7303 if (status == STATUS_PENDING)
7305 if (!fWait)
7307 SetLastError( WSA_IO_INCOMPLETE );
7308 return FALSE;
7311 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
7312 INFINITE ) == WAIT_FAILED)
7313 return FALSE;
7314 status = lpOverlapped->Internal;
7317 if ( lpcbTransfer )
7318 *lpcbTransfer = lpOverlapped->InternalHigh;
7320 if ( lpdwFlags )
7321 *lpdwFlags = lpOverlapped->u.s.Offset;
7323 if (status) SetLastError( RtlNtStatusToDosError(status) );
7324 return !status;
7328 /***********************************************************************
7329 * WSAAsyncSelect (WS2_32.101)
7331 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
7333 int ret;
7335 TRACE("%04lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
7337 SERVER_START_REQ( set_socket_event )
7339 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
7340 req->mask = lEvent;
7341 req->event = 0;
7342 req->window = wine_server_user_handle( hWnd );
7343 req->msg = uMsg;
7344 ret = wine_server_call( req );
7346 SERVER_END_REQ;
7347 if (!ret) return 0;
7348 SetLastError(WSAEINVAL);
7349 return SOCKET_ERROR;
7352 /***********************************************************************
7353 * WSACreateEvent (WS2_32.31)
7356 WSAEVENT WINAPI WSACreateEvent(void)
7358 /* Create a manual-reset event, with initial state: unsignaled */
7359 TRACE("\n");
7361 return CreateEventW(NULL, TRUE, FALSE, NULL);
7364 /***********************************************************************
7365 * WSACloseEvent (WS2_32.29)
7368 BOOL WINAPI WSACloseEvent(WSAEVENT event)
7370 TRACE ("event=%p\n", event);
7372 return CloseHandle(event);
7375 /***********************************************************************
7376 * WSASocketA (WS2_32.78)
7379 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
7380 LPWSAPROTOCOL_INFOA lpProtocolInfo,
7381 GROUP g, DWORD dwFlags)
7383 INT len;
7384 WSAPROTOCOL_INFOW info;
7386 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
7387 af, type, protocol, lpProtocolInfo, g, dwFlags);
7389 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
7391 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
7392 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
7393 info.szProtocol, WSAPROTOCOL_LEN + 1);
7395 if (!len)
7397 SetLastError(WSAEINVAL);
7398 return SOCKET_ERROR;
7401 return WSASocketW(af, type, protocol, &info, g, dwFlags);
7404 /***********************************************************************
7405 * WSASocketW (WS2_32.79)
7408 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
7409 LPWSAPROTOCOL_INFOW lpProtocolInfo,
7410 GROUP g, DWORD dwFlags)
7412 SOCKET ret;
7413 DWORD err;
7414 int unixaf, unixtype, ipxptype = -1;
7417 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
7418 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
7421 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
7422 af, type, protocol, lpProtocolInfo, g, dwFlags );
7424 if (!num_startup)
7426 err = WSANOTINITIALISED;
7427 goto done;
7430 /* hack for WSADuplicateSocket */
7431 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
7432 ret = lpProtocolInfo->dwServiceFlags3;
7433 TRACE("\tgot duplicate %04lx\n", ret);
7434 return ret;
7437 if (lpProtocolInfo)
7439 if (af == FROM_PROTOCOL_INFO || !af)
7440 af = lpProtocolInfo->iAddressFamily;
7441 if (type == FROM_PROTOCOL_INFO || !type)
7442 type = lpProtocolInfo->iSocketType;
7443 if (protocol == FROM_PROTOCOL_INFO || !protocol)
7444 protocol = lpProtocolInfo->iProtocol;
7447 if (!type && (af || protocol))
7449 int autoproto = protocol;
7450 WSAPROTOCOL_INFOW infow;
7452 /* default to the first valid protocol */
7453 if (!autoproto)
7454 autoproto = valid_protocols[0];
7455 else if(IS_IPX_PROTO(autoproto))
7456 autoproto = WS_NSPROTO_IPX;
7458 if (WS_EnterSingleProtocolW(autoproto, &infow))
7460 type = infow.iSocketType;
7462 /* after win2003 it's no longer possible to pass AF_UNSPEC
7463 using the protocol info struct */
7464 if (!lpProtocolInfo && af == WS_AF_UNSPEC)
7465 af = infow.iAddressFamily;
7470 Windows has an extension to the IPX protocol that allows one to create sockets
7471 and set the IPX packet type at the same time, to do that a caller will use
7472 a protocol like NSPROTO_IPX + <PACKET TYPE>
7474 if (IS_IPX_PROTO(protocol))
7475 ipxptype = protocol - WS_NSPROTO_IPX;
7477 /* convert the socket family, type and protocol */
7478 unixaf = convert_af_w2u(af);
7479 unixtype = convert_socktype_w2u(type);
7480 protocol = convert_proto_w2u(protocol);
7481 if (unixaf == AF_UNSPEC) unixaf = -1;
7483 /* filter invalid parameters */
7484 if (protocol < 0)
7486 /* the type could not be converted */
7487 if (type && unixtype < 0)
7489 err = WSAESOCKTNOSUPPORT;
7490 goto done;
7493 err = WSAEPROTONOSUPPORT;
7494 goto done;
7496 if (unixaf < 0)
7498 /* both family and protocol can't be invalid */
7499 if (protocol <= 0)
7501 err = WSAEINVAL;
7502 goto done;
7505 /* family could not be converted and neither socket type */
7506 if (unixtype < 0 && af >= 0)
7509 err = WSAESOCKTNOSUPPORT;
7510 goto done;
7513 err = WSAEAFNOSUPPORT;
7514 goto done;
7517 SERVER_START_REQ( create_socket )
7519 req->family = unixaf;
7520 req->type = unixtype;
7521 req->protocol = protocol;
7522 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
7523 req->attributes = (dwFlags & WSA_FLAG_NO_HANDLE_INHERIT) ? 0 : OBJ_INHERIT;
7524 req->flags = dwFlags & ~WSA_FLAG_NO_HANDLE_INHERIT;
7525 set_error( wine_server_call( req ) );
7526 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
7528 SERVER_END_REQ;
7529 if (ret)
7531 TRACE("\tcreated %04lx\n", ret );
7532 if (ipxptype > 0)
7533 set_ipx_packettype(ret, ipxptype);
7535 /* ensure IP_DONTFRAGMENT is disabled, in Linux the global default can be enabled */
7536 if (unixaf == AF_INET || unixaf == AF_INET6)
7537 set_dont_fragment(ret, unixaf == AF_INET6 ? IPPROTO_IPV6 : IPPROTO_IP, FALSE);
7539 #ifdef IPV6_V6ONLY
7540 if (unixaf == AF_INET6)
7542 int fd = get_sock_fd(ret, 0, NULL);
7543 if (fd != -1)
7545 /* IPV6_V6ONLY is set by default on Windows */
7546 int enable = 1;
7547 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)))
7548 WARN("\tsetting IPV6_V6ONLY failed - errno = %i\n", errno);
7549 release_sock_fd(ret, fd);
7552 #endif
7553 return ret;
7556 err = GetLastError();
7557 if (err == WSAEACCES) /* raw socket denied */
7559 if (type == SOCK_RAW)
7560 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
7561 else
7562 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
7564 else
7566 /* invalid combination of valid parameters, like SOCK_STREAM + IPPROTO_UDP */
7567 if (err == WSAEINVAL)
7568 err = WSAESOCKTNOSUPPORT;
7569 else if (err == WSAEOPNOTSUPP)
7570 err = WSAEPROTONOSUPPORT;
7573 done:
7574 WARN("\t\tfailed, error %d!\n", err);
7575 SetLastError(err);
7576 return INVALID_SOCKET;
7579 /***********************************************************************
7580 * WSAJoinLeaf (WS2_32.58)
7583 SOCKET WINAPI WSAJoinLeaf(
7584 SOCKET s,
7585 const struct WS_sockaddr *addr,
7586 int addrlen,
7587 LPWSABUF lpCallerData,
7588 LPWSABUF lpCalleeData,
7589 LPQOS lpSQOS,
7590 LPQOS lpGQOS,
7591 DWORD dwFlags)
7593 FIXME("stub.\n");
7594 return INVALID_SOCKET;
7597 /***********************************************************************
7598 * __WSAFDIsSet (WS2_32.151)
7600 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
7602 int i = set->fd_count, ret = 0;
7604 while (i--)
7605 if (set->fd_array[i] == s)
7607 ret = 1;
7608 break;
7611 TRACE("(socket %04lx, fd_set %p, count %i) <- %d\n", s, set, set->fd_count, ret);
7612 return ret;
7615 /***********************************************************************
7616 * WSAIsBlocking (WS2_32.114)
7618 BOOL WINAPI WSAIsBlocking(void)
7620 /* By default WinSock should set all its sockets to non-blocking mode
7621 * and poll in PeekMessage loop when processing "blocking" ones. This
7622 * function is supposed to tell if the program is in this loop. Our
7623 * blocking calls are truly blocking so we always return FALSE.
7625 * Note: It is allowed to call this function without prior WSAStartup().
7628 TRACE("\n");
7629 return FALSE;
7632 /***********************************************************************
7633 * WSACancelBlockingCall (WS2_32.113)
7635 INT WINAPI WSACancelBlockingCall(void)
7637 TRACE("\n");
7638 return 0;
7641 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
7643 FIXME("How was this called?\n");
7644 return x();
7648 /***********************************************************************
7649 * WSASetBlockingHook (WS2_32.109)
7651 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
7653 FARPROC prev = blocking_hook;
7654 blocking_hook = lpBlockFunc;
7655 TRACE("hook %p\n", lpBlockFunc);
7656 return prev;
7660 /***********************************************************************
7661 * WSAUnhookBlockingHook (WS2_32.110)
7663 INT WINAPI WSAUnhookBlockingHook(void)
7665 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
7666 return 0;
7670 /* ----------------------------------- end of API stuff */
7672 /* ----------------------------------- helper functions -
7674 * TODO: Merge WS_dup_..() stuff into one function that
7675 * would operate with a generic structure containing internal
7676 * pointers (via a template of some kind).
7679 static int list_size(char** l, int item_size)
7681 int i,j = 0;
7682 if(l)
7683 { for(i=0;l[i];i++)
7684 j += (item_size) ? item_size : strlen(l[i]) + 1;
7685 j += (i + 1) * sizeof(char*); }
7686 return j;
7689 static int list_dup(char** l_src, char** l_to, int item_size)
7691 char *p;
7692 int i;
7694 for (i = 0; l_src[i]; i++) ;
7695 p = (char *)(l_to + i + 1);
7696 for (i = 0; l_src[i]; i++)
7698 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
7699 memcpy(p, l_src[i], count);
7700 l_to[i] = p;
7701 p += count;
7703 l_to[i] = NULL;
7704 return p - (char *)l_to;
7707 /* ----- hostent */
7709 /* create a hostent entry
7711 * Creates the entry with enough memory for the name, aliases
7712 * addresses, and the address pointers. Also copies the name
7713 * and sets up all the pointers.
7715 * NOTE: The alias and address lists must be allocated with room
7716 * for the NULL item terminating the list. This is true even if
7717 * the list has no items ("aliases" and "addresses" must be
7718 * at least "1", a truly empty list is invalid).
7720 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length)
7722 struct WS_hostent *p_to;
7723 char *p;
7724 int size = (sizeof(struct WS_hostent) +
7725 strlen(name) + 1 +
7726 sizeof(char *) * aliases +
7727 aliases_size +
7728 sizeof(char *) * addresses +
7729 address_length * (addresses - 1)), i;
7731 if (!(p_to = check_buffer_he(size))) return NULL;
7732 memset(p_to, 0, size);
7734 /* Use the memory in the same way winsock does.
7735 * First set the pointer for aliases, second set the pointers for addresses.
7736 * Third fill the addresses indexes, fourth jump aliases names size.
7737 * Fifth fill the hostname.
7738 * NOTE: This method is valid for OS version's >= XP.
7740 p = (char *)(p_to + 1);
7741 p_to->h_aliases = (char **)p;
7742 p += sizeof(char *)*aliases;
7744 p_to->h_addr_list = (char **)p;
7745 p += sizeof(char *)*addresses;
7747 for (i = 0, addresses--; i < addresses; i++, p += address_length)
7748 p_to->h_addr_list[i] = p;
7750 /* NOTE: h_aliases must be filled in manually because we don't know each string
7751 * size, leave these pointers NULL (already set to NULL by memset earlier).
7753 p += aliases_size;
7755 p_to->h_name = p;
7756 strcpy(p, name);
7758 return p_to;
7761 /* duplicate hostent entry
7762 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
7763 * Ditto for protoent and servent.
7765 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
7767 int i, addresses = 0, alias_size = 0;
7768 struct WS_hostent *p_to;
7769 char *p;
7771 for( i = 0; p_he->h_aliases[i]; i++) alias_size += strlen(p_he->h_aliases[i]) + 1;
7772 while (p_he->h_addr_list[addresses]) addresses++;
7774 p_to = WS_create_he(p_he->h_name, i + 1, alias_size, addresses + 1, p_he->h_length);
7776 if (!p_to) return NULL;
7777 p_to->h_addrtype = convert_af_u2w(p_he->h_addrtype);
7778 p_to->h_length = p_he->h_length;
7780 for(i = 0, p = p_to->h_addr_list[0]; p_he->h_addr_list[i]; i++, p += p_to->h_length)
7781 memcpy(p, p_he->h_addr_list[i], p_to->h_length);
7783 /* Fill the aliases after the IP data */
7784 for(i = 0; p_he->h_aliases[i]; i++)
7786 p_to->h_aliases[i] = p;
7787 strcpy(p, p_he->h_aliases[i]);
7788 p += strlen(p) + 1;
7791 return p_to;
7794 /* ----- protoent */
7796 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
7798 char *p;
7799 struct WS_protoent *p_to;
7801 int size = (sizeof(*p_pe) +
7802 strlen(p_pe->p_name) + 1 +
7803 list_size(p_pe->p_aliases, 0));
7805 if (!(p_to = check_buffer_pe(size))) return NULL;
7806 p_to->p_proto = p_pe->p_proto;
7808 p = (char *)(p_to + 1);
7809 p_to->p_name = p;
7810 strcpy(p, p_pe->p_name);
7811 p += strlen(p) + 1;
7813 p_to->p_aliases = (char **)p;
7814 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
7815 return p_to;
7818 /* ----- servent */
7820 static struct WS_servent *WS_dup_se(const struct servent* p_se)
7822 char *p;
7823 struct WS_servent *p_to;
7825 int size = (sizeof(*p_se) +
7826 strlen(p_se->s_proto) + 1 +
7827 strlen(p_se->s_name) + 1 +
7828 list_size(p_se->s_aliases, 0));
7830 if (!(p_to = check_buffer_se(size))) return NULL;
7831 p_to->s_port = p_se->s_port;
7833 p = (char *)(p_to + 1);
7834 p_to->s_name = p;
7835 strcpy(p, p_se->s_name);
7836 p += strlen(p) + 1;
7838 p_to->s_proto = p;
7839 strcpy(p, p_se->s_proto);
7840 p += strlen(p) + 1;
7842 p_to->s_aliases = (char **)p;
7843 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
7844 return p_to;
7848 /***********************************************************************
7849 * WSARecv (WS2_32.67)
7851 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
7852 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
7853 LPWSAOVERLAPPED lpOverlapped,
7854 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
7856 return WS2_recv_base(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
7857 NULL, NULL, lpOverlapped, lpCompletionRoutine, NULL);
7860 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
7861 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
7862 struct WS_sockaddr *lpFrom,
7863 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
7864 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
7865 LPWSABUF lpControlBuffer )
7867 unsigned int i, options;
7868 int n, fd, err, overlapped, flags;
7869 struct ws2_async *wsa = NULL, localwsa;
7870 BOOL is_blocking;
7871 DWORD timeout_start = GetTickCount();
7872 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
7874 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
7875 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
7876 (lpFromlen ? *lpFromlen : -1),
7877 lpOverlapped, lpCompletionRoutine);
7879 fd = get_sock_fd( s, FILE_READ_DATA, &options );
7880 TRACE( "fd=%d, options=%x\n", fd, options );
7882 if (fd == -1) return SOCKET_ERROR;
7884 if (*lpFlags & WS_MSG_OOB)
7886 /* It's invalid to receive OOB data from an OOBINLINED socket
7887 * as OOB data is turned into normal data. */
7888 socklen_t len = sizeof(n);
7889 if (!getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, (char*) &n, &len) && n)
7891 err = WSAEINVAL;
7892 goto error;
7896 overlapped = (lpOverlapped || lpCompletionRoutine) &&
7897 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
7898 if (overlapped || dwBufferCount > 1)
7900 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[dwBufferCount]),
7901 WS2_async_recv )))
7903 err = WSAEFAULT;
7904 goto error;
7907 else
7908 wsa = &localwsa;
7910 wsa->hSocket = SOCKET2HANDLE(s);
7911 wsa->flags = *lpFlags;
7912 wsa->lpFlags = lpFlags;
7913 wsa->addr = lpFrom;
7914 wsa->addrlen.ptr = lpFromlen;
7915 wsa->control = lpControlBuffer;
7916 wsa->n_iovecs = dwBufferCount;
7917 wsa->first_iovec = 0;
7918 for (i = 0; i < dwBufferCount; i++)
7920 /* check buffer first to trigger write watches */
7921 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
7923 err = WSAEFAULT;
7924 goto error;
7926 wsa->iovec[i].iov_base = lpBuffers[i].buf;
7927 wsa->iovec[i].iov_len = lpBuffers[i].len;
7930 flags = convert_flags(wsa->flags);
7931 for (;;)
7933 n = WS2_recv( fd, wsa, flags );
7934 if (n == -1)
7936 /* Unix-like systems return EINVAL when attempting to read OOB data from
7937 * an empty socket buffer, convert that to a Windows expected return. */
7938 if ((flags & MSG_OOB) && errno == EINVAL)
7939 errno = EWOULDBLOCK;
7941 if (errno != EAGAIN)
7943 err = wsaErrno();
7944 goto error;
7947 else if (lpNumberOfBytesRecvd) *lpNumberOfBytesRecvd = n;
7949 if (overlapped)
7951 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
7953 wsa->user_overlapped = lpOverlapped;
7954 wsa->completion_func = lpCompletionRoutine;
7955 release_sock_fd( s, fd );
7957 if (n == -1)
7959 iosb->u.Status = STATUS_PENDING;
7960 iosb->Information = 0;
7962 if (wsa->completion_func)
7963 err = register_async( ASYNC_TYPE_READ, wsa->hSocket, &wsa->io, NULL,
7964 ws2_async_apc, wsa, iosb );
7965 else
7966 err = register_async( ASYNC_TYPE_READ, wsa->hSocket, &wsa->io, lpOverlapped->hEvent,
7967 NULL, (void *)cvalue, iosb );
7969 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
7970 SetLastError(NtStatusToWSAError( err ));
7971 return SOCKET_ERROR;
7974 iosb->u.Status = STATUS_SUCCESS;
7975 iosb->Information = n;
7976 if (!wsa->completion_func)
7978 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
7979 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
7980 HeapFree( GetProcessHeap(), 0, wsa );
7982 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
7983 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
7984 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7985 return 0;
7988 if (n != -1) break;
7990 if ((err = _is_blocking( s, &is_blocking )))
7992 err = NtStatusToWSAError( err );
7993 goto error;
7996 if ( is_blocking )
7998 struct pollfd pfd;
7999 int poll_timeout = -1;
8000 INT64 timeout = get_rcvsnd_timeo(fd, TRUE);
8002 if (timeout)
8004 timeout -= GetTickCount() - timeout_start;
8005 if (timeout < 0) poll_timeout = 0;
8006 else poll_timeout = timeout <= INT_MAX ? timeout : INT_MAX;
8009 pfd.fd = fd;
8010 pfd.events = POLLIN;
8011 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
8013 if (!poll_timeout || !poll( &pfd, 1, poll_timeout ))
8015 err = WSAETIMEDOUT;
8016 /* a timeout is not fatal */
8017 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
8018 goto error;
8021 else
8023 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
8024 err = WSAEWOULDBLOCK;
8025 goto error;
8029 TRACE(" -> %i bytes\n", n);
8030 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
8031 release_sock_fd( s, fd );
8032 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
8033 SetLastError(ERROR_SUCCESS);
8035 return 0;
8037 error:
8038 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
8039 release_sock_fd( s, fd );
8040 WARN(" -> ERROR %d\n", err);
8041 SetLastError( err );
8042 return SOCKET_ERROR;
8045 /***********************************************************************
8046 * WSARecvFrom (WS2_32.69)
8048 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
8049 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
8050 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
8051 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
8054 return WS2_recv_base( s, lpBuffers, dwBufferCount,
8055 lpNumberOfBytesRecvd, lpFlags,
8056 lpFrom, lpFromlen,
8057 lpOverlapped, lpCompletionRoutine, NULL );
8060 /***********************************************************************
8061 * WSCInstallProvider (WS2_32.88)
8063 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
8064 LPCWSTR lpszProviderDllPath,
8065 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
8066 DWORD dwNumberOfEntries,
8067 LPINT lpErrno )
8069 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
8070 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
8071 dwNumberOfEntries, lpErrno);
8072 *lpErrno = 0;
8073 return 0;
8077 /***********************************************************************
8078 * WSCDeinstallProvider (WS2_32.83)
8080 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
8082 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
8083 *lpErrno = 0;
8084 return 0;
8088 /***********************************************************************
8089 * WSAAccept (WS2_32.26)
8091 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
8092 LPCONDITIONPROC lpfnCondition, DWORD_PTR dwCallbackData)
8095 int ret = 0, size;
8096 WSABUF CallerId, CallerData, CalleeId, CalleeData;
8097 /* QOS SQOS, GQOS; */
8098 GROUP g;
8099 SOCKET cs;
8100 SOCKADDR src_addr, dst_addr;
8102 TRACE("socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
8103 s, addr, addrlen, lpfnCondition, dwCallbackData);
8105 cs = WS_accept(s, addr, addrlen);
8106 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
8107 if (!lpfnCondition) return cs;
8109 if (addr && addrlen)
8111 CallerId.buf = (char *)addr;
8112 CallerId.len = *addrlen;
8114 else
8116 size = sizeof(src_addr);
8117 WS_getpeername(cs, &src_addr, &size);
8118 CallerId.buf = (char *)&src_addr;
8119 CallerId.len = size;
8121 CallerData.buf = NULL;
8122 CallerData.len = 0;
8124 size = sizeof(dst_addr);
8125 WS_getsockname(cs, &dst_addr, &size);
8127 CalleeId.buf = (char *)&dst_addr;
8128 CalleeId.len = sizeof(dst_addr);
8130 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
8131 &CalleeId, &CalleeData, &g, dwCallbackData);
8133 switch (ret)
8135 case CF_ACCEPT:
8136 return cs;
8137 case CF_DEFER:
8138 SERVER_START_REQ( set_socket_deferred )
8140 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
8141 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
8142 if ( !wine_server_call_err ( req ) )
8144 SetLastError( WSATRY_AGAIN );
8145 WS_closesocket( cs );
8148 SERVER_END_REQ;
8149 return SOCKET_ERROR;
8150 case CF_REJECT:
8151 WS_closesocket(cs);
8152 SetLastError(WSAECONNREFUSED);
8153 return SOCKET_ERROR;
8154 default:
8155 FIXME("Unknown return type from Condition function\n");
8156 SetLastError(WSAENOTSOCK);
8157 return SOCKET_ERROR;
8161 /***********************************************************************
8162 * WSADuplicateSocketA (WS2_32.32)
8164 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
8166 return WS_DuplicateSocket(FALSE, s, dwProcessId, (LPWSAPROTOCOL_INFOW) lpProtocolInfo);
8169 /***********************************************************************
8170 * WSADuplicateSocketW (WS2_32.33)
8172 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
8174 return WS_DuplicateSocket(TRUE, s, dwProcessId, lpProtocolInfo);
8177 /***********************************************************************
8178 * WSAInstallServiceClassA (WS2_32.48)
8180 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
8182 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
8183 SetLastError(WSAEACCES);
8184 return SOCKET_ERROR;
8187 /***********************************************************************
8188 * WSAInstallServiceClassW (WS2_32.49)
8190 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
8192 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
8193 SetLastError(WSAEACCES);
8194 return SOCKET_ERROR;
8197 /***********************************************************************
8198 * WSARemoveServiceClass (WS2_32.70)
8200 int WINAPI WSARemoveServiceClass(LPGUID info)
8202 FIXME("Request to remove service %s\n", debugstr_guid(info));
8203 SetLastError(WSATYPE_NOT_FOUND);
8204 return SOCKET_ERROR;
8207 /***********************************************************************
8208 * inet_ntop (WS2_32.@)
8210 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
8212 #ifdef HAVE_INET_NTOP
8213 struct WS_in6_addr *in6;
8214 struct WS_in_addr *in;
8215 PCSTR pdst;
8217 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
8218 if (!buffer)
8220 SetLastError( STATUS_INVALID_PARAMETER );
8221 return NULL;
8224 switch (family)
8226 case WS_AF_INET:
8228 in = addr;
8229 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
8230 break;
8232 case WS_AF_INET6:
8234 in6 = addr;
8235 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
8236 break;
8238 default:
8239 SetLastError( WSAEAFNOSUPPORT );
8240 return NULL;
8243 if (!pdst) SetLastError( STATUS_INVALID_PARAMETER );
8244 return pdst;
8245 #else
8246 FIXME( "not supported on this platform\n" );
8247 SetLastError( WSAEAFNOSUPPORT );
8248 return NULL;
8249 #endif
8252 /***********************************************************************
8253 * inet_pton (WS2_32.@)
8255 INT WINAPI WS_inet_pton( INT family, PCSTR addr, PVOID buffer)
8257 #ifdef HAVE_INET_PTON
8258 int unixaf, ret;
8260 TRACE("family %d, addr %s, buffer (%p)\n", family, debugstr_a(addr), buffer);
8262 if (!addr || !buffer)
8264 SetLastError(WSAEFAULT);
8265 return SOCKET_ERROR;
8268 unixaf = convert_af_w2u(family);
8269 if (unixaf != AF_INET && unixaf != AF_INET6)
8271 SetLastError(WSAEAFNOSUPPORT);
8272 return SOCKET_ERROR;
8275 ret = inet_pton(unixaf, addr, buffer);
8276 if (ret == -1) SetLastError(wsaErrno());
8277 return ret;
8278 #else
8279 FIXME( "not supported on this platform\n" );
8280 SetLastError( WSAEAFNOSUPPORT );
8281 return SOCKET_ERROR;
8282 #endif
8285 /***********************************************************************
8286 * InetPtonW (WS2_32.@)
8288 INT WINAPI InetPtonW(INT family, PCWSTR addr, PVOID buffer)
8290 char *addrA;
8291 int len;
8292 INT ret;
8294 TRACE("family %d, addr %s, buffer (%p)\n", family, debugstr_w(addr), buffer);
8296 if (!addr)
8298 SetLastError(WSAEFAULT);
8299 return SOCKET_ERROR;
8302 len = WideCharToMultiByte(CP_ACP, 0, addr, -1, NULL, 0, NULL, NULL);
8303 if (!(addrA = HeapAlloc(GetProcessHeap(), 0, len)))
8305 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8306 return SOCKET_ERROR;
8308 WideCharToMultiByte(CP_ACP, 0, addr, -1, addrA, len, NULL, NULL);
8310 ret = WS_inet_pton(family, addrA, buffer);
8312 HeapFree(GetProcessHeap(), 0, addrA);
8313 return ret;
8316 /***********************************************************************
8317 * InetNtopW (WS2_32.@)
8319 PCWSTR WINAPI InetNtopW(INT family, PVOID addr, PWSTR buffer, SIZE_T len)
8321 char bufferA[WS_INET6_ADDRSTRLEN];
8322 PWSTR ret = NULL;
8324 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
8326 if (WS_inet_ntop(family, addr, bufferA, sizeof(bufferA)))
8328 if (MultiByteToWideChar(CP_ACP, 0, bufferA, -1, buffer, len))
8329 ret = buffer;
8330 else
8331 SetLastError(ERROR_INVALID_PARAMETER);
8333 return ret;
8336 /***********************************************************************
8337 * WSAStringToAddressA (WS2_32.80)
8339 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
8340 INT AddressFamily,
8341 LPWSAPROTOCOL_INFOA lpProtocolInfo,
8342 LPSOCKADDR lpAddress,
8343 LPINT lpAddressLength)
8345 INT res=0;
8346 LPSTR workBuffer=NULL,ptrPort;
8348 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
8349 lpProtocolInfo, lpAddress, lpAddressLength );
8351 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
8353 if (!AddressString)
8355 SetLastError(WSAEINVAL);
8356 return SOCKET_ERROR;
8359 if (lpProtocolInfo)
8360 FIXME("ProtocolInfo not implemented.\n");
8362 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
8363 strlen(AddressString) + 1);
8364 if (!workBuffer)
8366 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8367 return SOCKET_ERROR;
8370 strcpy(workBuffer, AddressString);
8372 switch(AddressFamily)
8374 case WS_AF_INET:
8376 struct in_addr inetaddr;
8378 /* If lpAddressLength is too small, tell caller the size we need */
8379 if (*lpAddressLength < sizeof(SOCKADDR_IN))
8381 *lpAddressLength = sizeof(SOCKADDR_IN);
8382 res = WSAEFAULT;
8383 break;
8385 *lpAddressLength = sizeof(SOCKADDR_IN);
8386 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
8388 ((LPSOCKADDR_IN)lpAddress)->sin_family = WS_AF_INET;
8390 ptrPort = strchr(workBuffer, ':');
8391 if(ptrPort)
8393 /* User may have entered an IPv6 and asked to parse as IPv4 */
8394 if(strchr(ptrPort + 1, ':'))
8396 res = WSAEINVAL;
8397 break;
8399 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
8400 *ptrPort = '\0';
8403 if(inet_aton(workBuffer, &inetaddr) > 0)
8405 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
8406 res = 0;
8408 else
8409 res = WSAEINVAL;
8411 break;
8413 case WS_AF_INET6:
8415 struct in6_addr inetaddr;
8416 char *ptrAddr = workBuffer;
8418 /* If lpAddressLength is too small, tell caller the size we need */
8419 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
8421 *lpAddressLength = sizeof(SOCKADDR_IN6);
8422 res = WSAEFAULT;
8423 break;
8425 #ifdef HAVE_INET_PTON
8426 *lpAddressLength = sizeof(SOCKADDR_IN6);
8427 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
8429 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
8431 /* Valid IPv6 addresses can also be surrounded by [ ], and in this case
8432 * a port number may follow after like in [fd12:3456:7890::1]:12345
8433 * We need to cut the brackets and find the port if any. */
8435 if(*workBuffer == '[')
8437 ptrPort = strchr(workBuffer, ']');
8438 if (!ptrPort)
8440 SetLastError(WSAEINVAL);
8441 return SOCKET_ERROR;
8444 if (ptrPort[1] == ':')
8445 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort + 2));
8447 *ptrPort = '\0';
8448 ptrAddr = workBuffer + 1;
8451 if(inet_pton(AF_INET6, ptrAddr, &inetaddr) > 0)
8453 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
8454 sizeof(struct in6_addr));
8455 res = 0;
8457 else
8458 #endif /* HAVE_INET_PTON */
8459 res = WSAEINVAL;
8461 break;
8463 default:
8464 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
8465 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
8466 res = WSAEINVAL;
8469 HeapFree(GetProcessHeap(), 0, workBuffer);
8471 if (!res) return 0;
8472 SetLastError(res);
8473 return SOCKET_ERROR;
8476 /***********************************************************************
8477 * WSAStringToAddressW (WS2_32.81)
8479 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
8480 * If this should be the case, it would be required to map these digits
8481 * to Unicode digits (0-9) using FoldString first.
8483 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
8484 INT AddressFamily,
8485 LPWSAPROTOCOL_INFOW lpProtocolInfo,
8486 LPSOCKADDR lpAddress,
8487 LPINT lpAddressLength)
8489 INT sBuffer,res=0;
8490 LPSTR workBuffer=NULL;
8491 WSAPROTOCOL_INFOA infoA;
8492 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
8494 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
8495 lpAddress, lpAddressLength );
8497 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
8499 /* if ProtocolInfo is available - convert to ANSI variant */
8500 if (lpProtocolInfo)
8502 lpProtoInfoA = &infoA;
8503 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
8505 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
8506 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
8508 SetLastError(WSAEINVAL);
8509 return SOCKET_ERROR;
8513 if (AddressString)
8515 /* Translate AddressString to ANSI code page - assumes that only
8516 standard digits 0-9 are used with this API call */
8517 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
8518 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
8520 if (workBuffer)
8522 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
8523 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
8524 lpAddress,lpAddressLength);
8525 HeapFree( GetProcessHeap(), 0, workBuffer );
8526 return res;
8528 else
8529 res = WSA_NOT_ENOUGH_MEMORY;
8531 else
8532 res = WSAEINVAL;
8534 SetLastError(res);
8535 return SOCKET_ERROR;
8538 /***********************************************************************
8539 * WSAAddressToStringA (WS2_32.27)
8541 * See WSAAddressToStringW
8543 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
8544 LPWSAPROTOCOL_INFOA info, LPSTR string,
8545 LPDWORD lenstr )
8547 DWORD size;
8548 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
8549 CHAR *p;
8551 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
8553 if (!sockaddr) return SOCKET_ERROR;
8554 if (!string || !lenstr) return SOCKET_ERROR;
8556 switch(sockaddr->sa_family)
8558 case WS_AF_INET:
8560 unsigned int long_ip = ntohl(((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr);
8561 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
8562 sprintf( buffer, "%u.%u.%u.%u:%u",
8563 (long_ip >> 24) & 0xff,
8564 (long_ip >> 16) & 0xff,
8565 (long_ip >> 8) & 0xff,
8566 long_ip & 0xff,
8567 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
8569 p = strchr( buffer, ':' );
8570 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
8571 break;
8573 case WS_AF_INET6:
8575 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
8576 size_t slen;
8578 buffer[0] = 0;
8579 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
8580 if ((sockaddr6->sin6_port))
8581 strcpy(buffer, "[");
8582 slen = strlen(buffer);
8583 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, &buffer[slen], sizeof(buffer) - slen))
8585 SetLastError(WSAEINVAL);
8586 return SOCKET_ERROR;
8588 if ((sockaddr6->sin6_scope_id))
8589 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
8590 if ((sockaddr6->sin6_port))
8591 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
8592 break;
8595 default:
8596 SetLastError(WSAEINVAL);
8597 return SOCKET_ERROR;
8600 size = strlen( buffer ) + 1;
8602 if (*lenstr < size)
8604 *lenstr = size;
8605 SetLastError(WSAEFAULT);
8606 return SOCKET_ERROR;
8609 TRACE("=> %s,%u bytes\n", debugstr_a(buffer), size);
8610 *lenstr = size;
8611 strcpy( string, buffer );
8612 return 0;
8615 /***********************************************************************
8616 * WSAAddressToStringW (WS2_32.28)
8618 * Convert a sockaddr address into a readable address string.
8620 * PARAMS
8621 * sockaddr [I] Pointer to a sockaddr structure.
8622 * len [I] Size of the sockaddr structure.
8623 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
8624 * string [I/O] Pointer to a buffer to receive the address string.
8625 * lenstr [I/O] Size of the receive buffer in WCHARs.
8627 * RETURNS
8628 * Success: 0
8629 * Failure: SOCKET_ERROR
8631 * NOTES
8632 * The 'info' parameter is ignored.
8634 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
8635 LPWSAPROTOCOL_INFOW info, LPWSTR string,
8636 LPDWORD lenstr )
8638 INT ret;
8639 DWORD size;
8640 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
8641 CHAR bufAddr[54];
8643 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
8645 size = *lenstr;
8646 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
8648 if (ret) return ret;
8650 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
8652 if (*lenstr < size)
8654 *lenstr = size;
8655 SetLastError(WSAEFAULT);
8656 return SOCKET_ERROR;
8659 TRACE("=> %s,%u bytes\n", debugstr_w(buffer), size);
8660 *lenstr = size;
8661 lstrcpyW( string, buffer );
8662 return 0;
8665 /***********************************************************************
8666 * WSAEnumNameSpaceProvidersA (WS2_32.34)
8668 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
8670 FIXME( "(%p %p) Stub!\n", len, buffer );
8671 return 0;
8674 /***********************************************************************
8675 * WSAEnumNameSpaceProvidersW (WS2_32.35)
8677 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
8679 FIXME( "(%p %p) Stub!\n", len, buffer );
8680 return 0;
8683 /***********************************************************************
8684 * WSAGetQOSByName (WS2_32.41)
8686 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
8688 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
8689 return FALSE;
8692 /***********************************************************************
8693 * WSAGetServiceClassInfoA (WS2_32.42)
8695 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
8696 LPWSASERVICECLASSINFOA info )
8698 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
8699 len, info );
8700 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8701 return SOCKET_ERROR;
8704 /***********************************************************************
8705 * WSAGetServiceClassInfoW (WS2_32.43)
8707 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
8708 LPWSASERVICECLASSINFOW info )
8710 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
8711 len, info );
8712 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8713 return SOCKET_ERROR;
8716 /***********************************************************************
8717 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
8719 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
8721 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
8722 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8723 return SOCKET_ERROR;
8726 /***********************************************************************
8727 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
8729 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
8731 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
8732 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8733 return SOCKET_ERROR;
8736 /***********************************************************************
8737 * WSALookupServiceBeginA (WS2_32.59)
8739 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
8740 DWORD dwControlFlags,
8741 LPHANDLE lphLookup)
8743 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
8744 lphLookup);
8745 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8746 return SOCKET_ERROR;
8749 /***********************************************************************
8750 * WSALookupServiceBeginW (WS2_32.60)
8752 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
8753 DWORD dwControlFlags,
8754 LPHANDLE lphLookup)
8756 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
8757 lphLookup);
8758 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8759 return SOCKET_ERROR;
8762 /***********************************************************************
8763 * WSALookupServiceEnd (WS2_32.61)
8765 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
8767 FIXME("(%p) Stub!\n", lookup );
8768 return 0;
8771 /***********************************************************************
8772 * WSALookupServiceNextA (WS2_32.62)
8774 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
8776 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
8777 SetLastError(WSA_E_NO_MORE);
8778 return SOCKET_ERROR;
8781 /***********************************************************************
8782 * WSALookupServiceNextW (WS2_32.63)
8784 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
8786 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
8787 SetLastError(WSA_E_NO_MORE);
8788 return SOCKET_ERROR;
8791 /***********************************************************************
8792 * WSANtohl (WS2_32.64)
8794 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
8796 TRACE( "(%04lx 0x%08x %p)\n", s, netlong, lphostlong );
8798 if (!lphostlong) return WSAEFAULT;
8800 *lphostlong = ntohl( netlong );
8801 return 0;
8804 /***********************************************************************
8805 * WSANtohs (WS2_32.65)
8807 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
8809 TRACE( "(%04lx 0x%08x %p)\n", s, netshort, lphostshort );
8811 if (!lphostshort) return WSAEFAULT;
8813 *lphostshort = ntohs( netshort );
8814 return 0;
8817 /***********************************************************************
8818 * WSAProviderConfigChange (WS2_32.66)
8820 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
8821 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
8823 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
8824 return SOCKET_ERROR;
8827 /***********************************************************************
8828 * WSARecvDisconnect (WS2_32.68)
8830 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
8832 TRACE( "(%04lx %p)\n", s, disconnectdata );
8834 return WS_shutdown( s, SD_RECEIVE );
8837 /***********************************************************************
8838 * WSASetServiceA (WS2_32.76)
8840 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
8842 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
8843 return 0;
8846 /***********************************************************************
8847 * WSASetServiceW (WS2_32.77)
8849 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
8851 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
8852 return 0;
8855 /***********************************************************************
8856 * WSCEnableNSProvider (WS2_32.84)
8858 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
8860 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
8861 return 0;
8864 /***********************************************************************
8865 * WSCGetProviderPath (WS2_32.86)
8867 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
8869 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
8871 if (!errcode || !provider || !len) return WSAEFAULT;
8873 *errcode = WSAEINVAL;
8874 return SOCKET_ERROR;
8877 /***********************************************************************
8878 * WSCInstallNameSpace (WS2_32.87)
8880 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
8881 DWORD version, LPGUID provider )
8883 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
8884 namespace, version, debugstr_guid(provider) );
8885 return 0;
8888 /***********************************************************************
8889 * WSCUnInstallNameSpace (WS2_32.89)
8891 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
8893 FIXME("(%s) Stub!\n", debugstr_guid(lpProviderId));
8894 return NO_ERROR;
8897 /***********************************************************************
8898 * WSCWriteProviderOrder (WS2_32.91)
8900 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
8902 FIXME("(%p 0x%08x) Stub!\n", entry, number);
8903 return 0;
8906 /***********************************************************************
8907 * WSANSPIoctl (WS2_32.91)
8909 INT WINAPI WSANSPIoctl( HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer,
8910 DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer,
8911 LPDWORD lpcbBytesReturned, LPWSACOMPLETION lpCompletion )
8913 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup, dwControlCode,
8914 lpvInBuffer, cbInBuffer, lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpCompletion);
8915 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8916 return SOCKET_ERROR;
8919 /*****************************************************************************
8920 * WSAEnumProtocolsA [WS2_32.@]
8922 * see function WSAEnumProtocolsW
8924 INT WINAPI WSAEnumProtocolsA( LPINT protocols, LPWSAPROTOCOL_INFOA buffer, LPDWORD len )
8926 return WS_EnumProtocols( FALSE, protocols, (LPWSAPROTOCOL_INFOW) buffer, len);
8929 /*****************************************************************************
8930 * WSAEnumProtocolsW [WS2_32.@]
8932 * Retrieves information about specified set of active network protocols.
8934 * PARAMS
8935 * protocols [I] Pointer to null-terminated array of protocol id's. NULL
8936 * retrieves information on all available protocols.
8937 * buffer [I] Pointer to a buffer to be filled with WSAPROTOCOL_INFO
8938 * structures.
8939 * len [I/O] Pointer to a variable specifying buffer size. On output
8940 * the variable holds the number of bytes needed when the
8941 * specified size is too small.
8943 * RETURNS
8944 * Success: number of WSAPROTOCOL_INFO structures in buffer.
8945 * Failure: SOCKET_ERROR
8947 * NOTES
8948 * NT4SP5 does not return SPX if protocols == NULL
8950 * BUGS
8951 * - NT4SP5 returns in addition these list of NETBIOS protocols
8952 * (address family 17), each entry two times one for socket type 2 and 5
8954 * iProtocol szProtocol
8955 * 0x80000000 \Device\NwlnkNb
8956 * 0xfffffffa \Device\NetBT_CBENT7
8957 * 0xfffffffb \Device\Nbf_CBENT7
8958 * 0xfffffffc \Device\NetBT_NdisWan5
8959 * 0xfffffffd \Device\NetBT_El9202
8960 * 0xfffffffe \Device\Nbf_El9202
8961 * 0xffffffff \Device\Nbf_NdisWan4
8963 * - there is no check that the operating system supports the returned
8964 * protocols
8966 INT WINAPI WSAEnumProtocolsW( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
8968 return WS_EnumProtocols( TRUE, protocols, buffer, len);
8971 /*****************************************************************************
8972 * WSCEnumProtocols [WS2_32.@]
8974 * PARAMS
8975 * protocols [I] Null-terminated array of iProtocol values.
8976 * buffer [O] Buffer of WSAPROTOCOL_INFOW structures.
8977 * len [I/O] Size of buffer on input/output.
8978 * errno [O] Error code.
8980 * RETURNS
8981 * Success: number of protocols to be reported on.
8982 * Failure: SOCKET_ERROR. error is in errno.
8984 * BUGS
8985 * Doesn't supply info on layered protocols.
8988 INT WINAPI WSCEnumProtocols( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len, LPINT err )
8990 INT ret = WSAEnumProtocolsW( protocols, buffer, len );
8992 if (ret == SOCKET_ERROR) *err = WSAENOBUFS;
8994 return ret;