ws2_32: Use register_async for WS2_async_send.
[wine.git] / dlls / ws2_32 / socket.c
blob22ff4797f8ca7b41239e09e16b1d904a12ab8165
1 /*
2 * based on Windows Sockets 1.1 specs
4 * Copyright (C) 1993,1994,1996,1997 John Brezak, Erik Bos, Alex Korobka.
5 * Copyright (C) 2001 Stefan Leichter
6 * Copyright (C) 2004 Hans Leidekker
7 * Copyright (C) 2005 Marcus Meissner
8 * Copyright (C) 2006-2008 Kai Blin
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24 * NOTE: If you make any changes to fix a particular app, make sure
25 * they don't break something else like Netscape or telnet and ftp
26 * clients and servers (www.winsite.com got a lot of those).
29 #include "config.h"
30 #include "wine/port.h"
32 #include <stdarg.h>
33 #include <stdio.h>
34 #include <string.h>
35 #include <sys/types.h>
36 #include <limits.h>
37 #ifdef HAVE_SYS_IPC_H
38 # include <sys/ipc.h>
39 #endif
40 #ifdef HAVE_SYS_IOCTL_H
41 # include <sys/ioctl.h>
42 #endif
43 #ifdef HAVE_SYS_FILIO_H
44 # include <sys/filio.h>
45 #endif
46 #ifdef HAVE_SYS_SOCKIO_H
47 # include <sys/sockio.h>
48 #endif
50 #if defined(__EMX__)
51 # include <sys/so_ioctl.h>
52 #endif
54 #ifdef HAVE_SYS_PARAM_H
55 # include <sys/param.h>
56 #endif
58 #ifdef HAVE_SYS_MSG_H
59 # include <sys/msg.h>
60 #endif
61 #ifdef HAVE_SYS_WAIT_H
62 # include <sys/wait.h>
63 #endif
64 #ifdef HAVE_SYS_UIO_H
65 # include <sys/uio.h>
66 #endif
67 #ifdef HAVE_SYS_SOCKET_H
68 #include <sys/socket.h>
69 #endif
70 #ifdef HAVE_NETINET_IN_H
71 # include <netinet/in.h>
72 #endif
73 #ifdef HAVE_NETINET_TCP_H
74 # include <netinet/tcp.h>
75 #endif
76 #ifdef HAVE_ARPA_INET_H
77 # include <arpa/inet.h>
78 #endif
79 #include <ctype.h>
80 #include <fcntl.h>
81 #include <errno.h>
82 #ifdef HAVE_NETDB_H
83 #include <netdb.h>
84 #endif
85 #ifdef HAVE_UNISTD_H
86 # include <unistd.h>
87 #endif
88 #include <stdlib.h>
89 #ifdef HAVE_ARPA_NAMESER_H
90 # include <arpa/nameser.h>
91 #endif
92 #ifdef HAVE_RESOLV_H
93 # include <resolv.h>
94 #endif
95 #ifdef HAVE_NET_IF_H
96 # include <net/if.h>
97 #endif
98 #ifdef HAVE_LINUX_FILTER_H
99 # include <linux/filter.h>
100 #endif
102 #ifdef HAVE_NETIPX_IPX_H
103 # include <netipx/ipx.h>
104 #elif defined(HAVE_LINUX_IPX_H)
105 # ifdef HAVE_ASM_TYPES_H
106 # include <asm/types.h>
107 # endif
108 # ifdef HAVE_LINUX_TYPES_H
109 # include <linux/types.h>
110 # endif
111 # include <linux/ipx.h>
112 #endif
113 #if defined(SOL_IPX) || defined(SO_DEFAULT_HEADERS)
114 # define HAS_IPX
115 #endif
117 #ifdef HAVE_LINUX_IRDA_H
118 # ifdef HAVE_LINUX_TYPES_H
119 # include <linux/types.h>
120 # endif
121 # include <linux/irda.h>
122 # define HAS_IRDA
123 #endif
125 #ifdef HAVE_POLL_H
126 #include <poll.h>
127 #endif
128 #ifdef HAVE_SYS_POLL_H
129 # include <sys/poll.h>
130 #endif
131 #ifdef HAVE_SYS_TIME_H
132 # include <sys/time.h>
133 #endif
135 #define NONAMELESSUNION
136 #define NONAMELESSSTRUCT
137 #include "ntstatus.h"
138 #define WIN32_NO_STATUS
139 #include "windef.h"
140 #include "winbase.h"
141 #include "wingdi.h"
142 #include "winuser.h"
143 #include "winerror.h"
144 #include "winnls.h"
145 #include "winsock2.h"
146 #include "mswsock.h"
147 #include "ws2tcpip.h"
148 #include "ws2spi.h"
149 #include "wsipx.h"
150 #include "wsnwlink.h"
151 #include "wshisotp.h"
152 #include "mstcpip.h"
153 #include "af_irda.h"
154 #include "winnt.h"
155 #define USE_WC_PREFIX /* For CMSG_DATA */
156 #include "iphlpapi.h"
157 #include "wine/server.h"
158 #include "wine/debug.h"
159 #include "wine/exception.h"
160 #include "wine/unicode.h"
162 #if defined(linux) && !defined(IP_UNICAST_IF)
163 #define IP_UNICAST_IF 50
164 #endif
166 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
167 # define sipx_network sipx_addr.x_net
168 # define sipx_node sipx_addr.x_host.c_host
169 #endif /* __FreeBSD__ */
171 #ifndef INADDR_NONE
172 #define INADDR_NONE ~0UL
173 #endif
175 #if !defined(TCP_KEEPIDLE) && defined(TCP_KEEPALIVE)
176 /* TCP_KEEPALIVE is the Mac OS name for TCP_KEEPIDLE */
177 #define TCP_KEEPIDLE TCP_KEEPALIVE
178 #endif
180 #define FILE_USE_FILE_POINTER_POSITION ((LONGLONG)-2)
182 WINE_DEFAULT_DEBUG_CHANNEL(winsock);
183 WINE_DECLARE_DEBUG_CHANNEL(winediag);
185 /* names of the protocols */
186 static const WCHAR NameIpxW[] = {'I', 'P', 'X', '\0'};
187 static const WCHAR NameSpxW[] = {'S', 'P', 'X', '\0'};
188 static const WCHAR NameSpxIIW[] = {'S', 'P', 'X', ' ', 'I', 'I', '\0'};
189 static const WCHAR NameTcpW[] = {'T', 'C', 'P', '/', 'I', 'P', '\0'};
190 static const WCHAR NameUdpW[] = {'U', 'D', 'P', '/', 'I', 'P', '\0'};
192 /* Taken from Win2k */
193 static const GUID ProviderIdIP = { 0xe70f1aa0, 0xab8b, 0x11cf,
194 { 0x8c, 0xa3, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
195 static const GUID ProviderIdIPX = { 0x11058240, 0xbe47, 0x11cf,
196 { 0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
197 static const GUID ProviderIdSPX = { 0x11058241, 0xbe47, 0x11cf,
198 { 0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
200 static const INT valid_protocols[] =
202 WS_IPPROTO_TCP,
203 WS_IPPROTO_UDP,
204 WS_NSPROTO_IPX,
205 WS_NSPROTO_SPX,
206 WS_NSPROTO_SPXII,
210 #define IS_IPX_PROTO(X) ((X) >= WS_NSPROTO_IPX && (X) <= WS_NSPROTO_IPX + 255)
212 #if defined(IP_UNICAST_IF) && defined(SO_ATTACH_FILTER)
213 # define LINUX_BOUND_IF
214 struct interface_filter {
215 struct sock_filter iface_memaddr;
216 struct sock_filter iface_rule;
217 struct sock_filter ip_memaddr;
218 struct sock_filter ip_rule;
219 struct sock_filter return_keep;
220 struct sock_filter return_dump;
222 # define FILTER_JUMP_DUMP(here) (u_char)(offsetof(struct interface_filter, return_dump) \
223 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
224 /sizeof(struct sock_filter)
225 # define FILTER_JUMP_KEEP(here) (u_char)(offsetof(struct interface_filter, return_keep) \
226 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
227 /sizeof(struct sock_filter)
228 # define FILTER_JUMP_NEXT() (u_char)(0)
229 # define SKF_NET_DESTIP 16 /* offset in the network header to the destination IP */
230 static struct interface_filter generic_interface_filter = {
231 /* This filter rule allows incoming packets on the specified interface, which works for all
232 * remotely generated packets and for locally generated broadcast packets. */
233 BPF_STMT(BPF_LD+BPF_W+BPF_ABS, SKF_AD_OFF+SKF_AD_IFINDEX),
234 BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0xdeadbeef, FILTER_JUMP_KEEP(iface_rule), FILTER_JUMP_NEXT()),
235 /* This rule allows locally generated packets targeted at the specific IP address of the chosen
236 * adapter (local packets not destined for the broadcast address do not have IFINDEX set) */
237 BPF_STMT(BPF_LD+BPF_W+BPF_ABS, SKF_NET_OFF+SKF_NET_DESTIP),
238 BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0xdeadbeef, FILTER_JUMP_KEEP(ip_rule), FILTER_JUMP_DUMP(ip_rule)),
239 BPF_STMT(BPF_RET+BPF_K, (u_int)-1), /* keep packet */
240 BPF_STMT(BPF_RET+BPF_K, 0) /* dump packet */
242 #endif /* LINUX_BOUND_IF */
245 * The actual definition of WSASendTo, wrapped in a different function name
246 * so that internal calls from ws2_32 itself will not trigger programs like
247 * Garena, which hooks WSASendTo/WSARecvFrom calls.
249 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
250 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
251 const struct WS_sockaddr *to, int tolen,
252 LPWSAOVERLAPPED lpOverlapped,
253 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine );
256 * Internal fundamental receive function, essentially WSARecvFrom with an
257 * additional parameter to support message control headers.
259 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
260 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
261 struct WS_sockaddr *lpFrom,
262 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
263 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
264 LPWSABUF lpControlBuffer );
266 /* critical section to protect some non-reentrant net function */
267 static CRITICAL_SECTION csWSgetXXXbyYYY;
268 static CRITICAL_SECTION_DEBUG critsect_debug =
270 0, 0, &csWSgetXXXbyYYY,
271 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
272 0, 0, { (DWORD_PTR)(__FILE__ ": csWSgetXXXbyYYY") }
274 static CRITICAL_SECTION csWSgetXXXbyYYY = { &critsect_debug, -1, 0, 0, 0, 0 };
276 union generic_unix_sockaddr
278 struct sockaddr addr;
279 char data[128]; /* should be big enough for all families */
282 static inline const char *debugstr_sockaddr( const struct WS_sockaddr *a )
284 if (!a) return "(nil)";
285 switch (a->sa_family)
287 case WS_AF_INET:
289 char buf[16];
290 const char *p;
291 struct WS_sockaddr_in *sin = (struct WS_sockaddr_in *)a;
293 p = WS_inet_ntop( WS_AF_INET, &sin->sin_addr, buf, sizeof(buf) );
294 if (!p)
295 p = "(unknown IPv4 address)";
297 return wine_dbg_sprintf("{ family AF_INET, address %s, port %d }",
298 p, ntohs(sin->sin_port));
300 case WS_AF_INET6:
302 char buf[46];
303 const char *p;
304 struct WS_sockaddr_in6 *sin = (struct WS_sockaddr_in6 *)a;
306 p = WS_inet_ntop( WS_AF_INET6, &sin->sin6_addr, buf, sizeof(buf) );
307 if (!p)
308 p = "(unknown IPv6 address)";
309 return wine_dbg_sprintf("{ family AF_INET6, address %s, port %d }",
310 p, ntohs(sin->sin6_port));
312 case WS_AF_IPX:
314 int i;
315 char netnum[16], nodenum[16];
316 struct WS_sockaddr_ipx *sin = (struct WS_sockaddr_ipx *)a;
318 for (i = 0;i < 4; i++) sprintf(netnum + i * 2, "%02X", (unsigned char) sin->sa_netnum[i]);
319 for (i = 0;i < 6; i++) sprintf(nodenum + i * 2, "%02X", (unsigned char) sin->sa_nodenum[i]);
321 return wine_dbg_sprintf("{ family AF_IPX, address %s.%s, ipx socket %d }",
322 netnum, nodenum, sin->sa_socket);
324 case WS_AF_IRDA:
326 DWORD addr;
328 memcpy( &addr, ((const SOCKADDR_IRDA *)a)->irdaDeviceID, sizeof(addr) );
329 addr = ntohl( addr );
330 return wine_dbg_sprintf("{ family AF_IRDA, addr %08x, name %s }",
331 addr,
332 ((const SOCKADDR_IRDA *)a)->irdaServiceName);
334 default:
335 return wine_dbg_sprintf("{ family %d }", a->sa_family);
339 static inline const char *debugstr_sockopt(int level, int optname)
341 const char *stropt = NULL, *strlevel = NULL;
343 #define DEBUG_SOCKLEVEL(x) case (x): strlevel = #x
344 #define DEBUG_SOCKOPT(x) case (x): stropt = #x; break
346 switch(level)
348 DEBUG_SOCKLEVEL(WS_SOL_SOCKET);
349 switch(optname)
351 DEBUG_SOCKOPT(WS_SO_ACCEPTCONN);
352 DEBUG_SOCKOPT(WS_SO_BROADCAST);
353 DEBUG_SOCKOPT(WS_SO_BSP_STATE);
354 DEBUG_SOCKOPT(WS_SO_CONDITIONAL_ACCEPT);
355 DEBUG_SOCKOPT(WS_SO_CONNECT_TIME);
356 DEBUG_SOCKOPT(WS_SO_DEBUG);
357 DEBUG_SOCKOPT(WS_SO_DONTLINGER);
358 DEBUG_SOCKOPT(WS_SO_DONTROUTE);
359 DEBUG_SOCKOPT(WS_SO_ERROR);
360 DEBUG_SOCKOPT(WS_SO_EXCLUSIVEADDRUSE);
361 DEBUG_SOCKOPT(WS_SO_GROUP_ID);
362 DEBUG_SOCKOPT(WS_SO_GROUP_PRIORITY);
363 DEBUG_SOCKOPT(WS_SO_KEEPALIVE);
364 DEBUG_SOCKOPT(WS_SO_LINGER);
365 DEBUG_SOCKOPT(WS_SO_MAX_MSG_SIZE);
366 DEBUG_SOCKOPT(WS_SO_OOBINLINE);
367 DEBUG_SOCKOPT(WS_SO_OPENTYPE);
368 DEBUG_SOCKOPT(WS_SO_PROTOCOL_INFOA);
369 DEBUG_SOCKOPT(WS_SO_PROTOCOL_INFOW);
370 DEBUG_SOCKOPT(WS_SO_RCVBUF);
371 DEBUG_SOCKOPT(WS_SO_RCVTIMEO);
372 DEBUG_SOCKOPT(WS_SO_REUSEADDR);
373 DEBUG_SOCKOPT(WS_SO_SNDBUF);
374 DEBUG_SOCKOPT(WS_SO_SNDTIMEO);
375 DEBUG_SOCKOPT(WS_SO_TYPE);
376 DEBUG_SOCKOPT(WS_SO_UPDATE_CONNECT_CONTEXT);
378 break;
380 DEBUG_SOCKLEVEL(WS_NSPROTO_IPX);
381 switch(optname)
383 DEBUG_SOCKOPT(WS_IPX_PTYPE);
384 DEBUG_SOCKOPT(WS_IPX_FILTERPTYPE);
385 DEBUG_SOCKOPT(WS_IPX_DSTYPE);
386 DEBUG_SOCKOPT(WS_IPX_RECVHDR);
387 DEBUG_SOCKOPT(WS_IPX_MAXSIZE);
388 DEBUG_SOCKOPT(WS_IPX_ADDRESS);
389 DEBUG_SOCKOPT(WS_IPX_MAX_ADAPTER_NUM);
391 break;
393 DEBUG_SOCKLEVEL(WS_SOL_IRLMP);
394 switch(optname)
396 DEBUG_SOCKOPT(WS_IRLMP_ENUMDEVICES);
398 break;
400 DEBUG_SOCKLEVEL(WS_IPPROTO_TCP);
401 switch(optname)
403 DEBUG_SOCKOPT(WS_TCP_BSDURGENT);
404 DEBUG_SOCKOPT(WS_TCP_EXPEDITED_1122);
405 DEBUG_SOCKOPT(WS_TCP_NODELAY);
407 break;
409 DEBUG_SOCKLEVEL(WS_IPPROTO_IP);
410 switch(optname)
412 DEBUG_SOCKOPT(WS_IP_ADD_MEMBERSHIP);
413 DEBUG_SOCKOPT(WS_IP_DONTFRAGMENT);
414 DEBUG_SOCKOPT(WS_IP_DROP_MEMBERSHIP);
415 DEBUG_SOCKOPT(WS_IP_HDRINCL);
416 DEBUG_SOCKOPT(WS_IP_MULTICAST_IF);
417 DEBUG_SOCKOPT(WS_IP_MULTICAST_LOOP);
418 DEBUG_SOCKOPT(WS_IP_MULTICAST_TTL);
419 DEBUG_SOCKOPT(WS_IP_OPTIONS);
420 DEBUG_SOCKOPT(WS_IP_PKTINFO);
421 DEBUG_SOCKOPT(WS_IP_RECEIVE_BROADCAST);
422 DEBUG_SOCKOPT(WS_IP_TOS);
423 DEBUG_SOCKOPT(WS_IP_TTL);
424 DEBUG_SOCKOPT(WS_IP_UNICAST_IF);
426 break;
428 DEBUG_SOCKLEVEL(WS_IPPROTO_IPV6);
429 switch(optname)
431 DEBUG_SOCKOPT(WS_IPV6_ADD_MEMBERSHIP);
432 DEBUG_SOCKOPT(WS_IPV6_DROP_MEMBERSHIP);
433 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_IF);
434 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_HOPS);
435 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_LOOP);
436 DEBUG_SOCKOPT(WS_IPV6_UNICAST_HOPS);
437 DEBUG_SOCKOPT(WS_IPV6_V6ONLY);
438 DEBUG_SOCKOPT(WS_IPV6_UNICAST_IF);
439 DEBUG_SOCKOPT(WS_IPV6_DONTFRAG);
441 break;
443 #undef DEBUG_SOCKLEVEL
444 #undef DEBUG_SOCKOPT
446 if (!strlevel)
447 strlevel = wine_dbg_sprintf("WS_0x%x", level);
448 if (!stropt)
449 stropt = wine_dbg_sprintf("WS_0x%x", optname);
451 return wine_dbg_sprintf("level %s, name %s", strlevel + 3, stropt + 3);
454 static inline const char *debugstr_optval(const char *optval, int optlenval)
456 if (optval && !IS_INTRESOURCE(optval) && optlenval >= 1 && optlenval <= sizeof(DWORD))
458 DWORD value = 0;
459 memcpy(&value, optval, optlenval);
460 return wine_dbg_sprintf("%p (%u)", optval, value);
462 return wine_dbg_sprintf("%p", optval);
465 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
466 #define SOCKET2HANDLE(s) ((HANDLE)(s))
467 #define HANDLE2SOCKET(h) ((SOCKET)(h))
469 /****************************************************************
470 * Async IO declarations
471 ****************************************************************/
473 struct ws2_async_io
475 struct ws2_async_io *next;
478 struct ws2_async_shutdown
480 struct ws2_async_io io;
481 HANDLE hSocket;
482 IO_STATUS_BLOCK iosb;
483 int type;
486 struct ws2_async
488 struct ws2_async_io io;
489 HANDLE hSocket;
490 LPWSAOVERLAPPED user_overlapped;
491 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
492 IO_STATUS_BLOCK local_iosb;
493 struct WS_sockaddr *addr;
494 union
496 int val; /* for send operations */
497 int *ptr; /* for recv operations */
498 } addrlen;
499 DWORD flags;
500 DWORD *lpFlags;
501 WSABUF *control;
502 unsigned int n_iovecs;
503 unsigned int first_iovec;
504 struct iovec iovec[1];
507 struct ws2_accept_async
509 struct ws2_async_io io;
510 HANDLE listen_socket;
511 HANDLE accept_socket;
512 LPOVERLAPPED user_overlapped;
513 ULONG_PTR cvalue;
514 PVOID buf; /* buffer to write data to */
515 int data_len;
516 int local_len;
517 int remote_len;
518 struct ws2_async *read;
521 struct ws2_transmitfile_async
523 struct ws2_async_io io;
524 char *buffer;
525 HANDLE file;
526 DWORD file_read;
527 DWORD file_bytes;
528 DWORD bytes_per_send;
529 TRANSMIT_FILE_BUFFERS buffers;
530 DWORD flags;
531 LARGE_INTEGER offset;
532 struct ws2_async write;
535 static struct ws2_async_io *async_io_freelist;
537 static void release_async_io( struct ws2_async_io *io )
539 for (;;)
541 struct ws2_async_io *next = async_io_freelist;
542 io->next = next;
543 if (InterlockedCompareExchangePointer( (void **)&async_io_freelist, io, next ) == next) return;
547 static struct ws2_async_io *alloc_async_io( DWORD size )
549 /* first free remaining previous fileinfos */
551 struct ws2_async_io *io = InterlockedExchangePointer( (void **)&async_io_freelist, NULL );
553 while (io)
555 struct ws2_async_io *next = io->next;
556 HeapFree( GetProcessHeap(), 0, io );
557 io = next;
560 return HeapAlloc( GetProcessHeap(), 0, size );
563 typedef NTSTATUS async_callback_t( void *user, IO_STATUS_BLOCK *io, NTSTATUS status, void **apc, void **arg );
565 static NTSTATUS register_async( int type, HANDLE handle, async_callback_t callback, void *arg, HANDLE event,
566 PIO_APC_ROUTINE apc, void *apc_context, IO_STATUS_BLOCK *io )
568 NTSTATUS status;
570 SERVER_START_REQ( register_async )
572 req->type = type;
573 req->async.handle = wine_server_obj_handle( handle );
574 req->async.callback = wine_server_client_ptr( callback );
575 req->async.iosb = wine_server_client_ptr( io );
576 req->async.arg = wine_server_client_ptr( arg );
577 req->async.event = wine_server_obj_handle( event );
578 req->async.cvalue = wine_server_client_ptr( apc ? 0 : apc_context );
579 status = wine_server_call( req );
581 SERVER_END_REQ;
583 return status;
586 /****************************************************************/
588 /* ----------------------------------- internal data */
590 /* ws_... struct conversion flags */
592 typedef struct /* WSAAsyncSelect() control struct */
594 HANDLE service, event, sock;
595 HWND hWnd;
596 UINT uMsg;
597 LONG lEvent;
598 } ws_select_info;
600 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
601 #define WS_MAX_UDP_DATAGRAM 1024
602 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
604 /* hostent's, servent's and protent's are stored in one buffer per thread,
605 * as documented on MSDN for the functions that return any of the buffers */
606 struct per_thread_data
608 int opentype;
609 struct WS_hostent *he_buffer;
610 struct WS_servent *se_buffer;
611 struct WS_protoent *pe_buffer;
612 struct pollfd *fd_cache;
613 unsigned int fd_count;
614 int he_len;
615 int se_len;
616 int pe_len;
617 char ntoa_buffer[16]; /* 4*3 digits + 3 '.' + 1 '\0' */
620 /* internal: routing description information */
621 struct route {
622 struct in_addr addr;
623 IF_INDEX interface;
624 DWORD metric, default_route;
627 static INT num_startup; /* reference counter */
628 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
630 /* function prototypes */
631 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length);
632 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
633 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
634 static struct WS_servent *WS_dup_se(const struct servent* p_se);
635 static int ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size);
637 int WSAIOCTL_GetInterfaceCount(void);
638 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
640 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus, ULONG Information );
642 #define MAP_OPTION(opt) { WS_##opt, opt }
644 static const int ws_flags_map[][2] =
646 MAP_OPTION( MSG_OOB ),
647 MAP_OPTION( MSG_PEEK ),
648 MAP_OPTION( MSG_DONTROUTE ),
649 MAP_OPTION( MSG_WAITALL ),
650 { WS_MSG_PARTIAL, 0 },
653 static const int ws_sock_map[][2] =
655 MAP_OPTION( SO_DEBUG ),
656 MAP_OPTION( SO_ACCEPTCONN ),
657 MAP_OPTION( SO_REUSEADDR ),
658 MAP_OPTION( SO_KEEPALIVE ),
659 MAP_OPTION( SO_DONTROUTE ),
660 MAP_OPTION( SO_BROADCAST ),
661 MAP_OPTION( SO_LINGER ),
662 MAP_OPTION( SO_OOBINLINE ),
663 MAP_OPTION( SO_SNDBUF ),
664 MAP_OPTION( SO_RCVBUF ),
665 MAP_OPTION( SO_ERROR ),
666 MAP_OPTION( SO_TYPE ),
667 #ifdef SO_RCVTIMEO
668 MAP_OPTION( SO_RCVTIMEO ),
669 #endif
670 #ifdef SO_SNDTIMEO
671 MAP_OPTION( SO_SNDTIMEO ),
672 #endif
675 static const int ws_tcp_map[][2] =
677 #ifdef TCP_NODELAY
678 MAP_OPTION( TCP_NODELAY ),
679 #endif
682 static const int ws_ip_map[][2] =
684 MAP_OPTION( IP_MULTICAST_IF ),
685 MAP_OPTION( IP_MULTICAST_TTL ),
686 MAP_OPTION( IP_MULTICAST_LOOP ),
687 MAP_OPTION( IP_ADD_MEMBERSHIP ),
688 MAP_OPTION( IP_DROP_MEMBERSHIP ),
689 MAP_OPTION( IP_OPTIONS ),
690 #ifdef IP_HDRINCL
691 MAP_OPTION( IP_HDRINCL ),
692 #endif
693 MAP_OPTION( IP_TOS ),
694 MAP_OPTION( IP_TTL ),
695 #ifdef IP_PKTINFO
696 MAP_OPTION( IP_PKTINFO ),
697 #endif
698 #ifdef IP_UNICAST_IF
699 MAP_OPTION( IP_UNICAST_IF ),
700 #endif
703 static const int ws_ipv6_map[][2] =
705 #ifdef IPV6_ADD_MEMBERSHIP
706 MAP_OPTION( IPV6_ADD_MEMBERSHIP ),
707 #endif
708 #ifdef IPV6_DROP_MEMBERSHIP
709 MAP_OPTION( IPV6_DROP_MEMBERSHIP ),
710 #endif
711 MAP_OPTION( IPV6_MULTICAST_IF ),
712 MAP_OPTION( IPV6_MULTICAST_HOPS ),
713 MAP_OPTION( IPV6_MULTICAST_LOOP ),
714 MAP_OPTION( IPV6_UNICAST_HOPS ),
715 MAP_OPTION( IPV6_V6ONLY ),
716 #ifdef IPV6_UNICAST_IF
717 MAP_OPTION( IPV6_UNICAST_IF ),
718 #endif
721 static const int ws_af_map[][2] =
723 MAP_OPTION( AF_UNSPEC ),
724 MAP_OPTION( AF_INET ),
725 MAP_OPTION( AF_INET6 ),
726 #ifdef HAS_IPX
727 MAP_OPTION( AF_IPX ),
728 #endif
729 #ifdef AF_IRDA
730 MAP_OPTION( AF_IRDA ),
731 #endif
732 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
735 static const int ws_socktype_map[][2] =
737 MAP_OPTION( SOCK_DGRAM ),
738 MAP_OPTION( SOCK_STREAM ),
739 MAP_OPTION( SOCK_RAW ),
740 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
743 static const int ws_proto_map[][2] =
745 MAP_OPTION( IPPROTO_IP ),
746 MAP_OPTION( IPPROTO_TCP ),
747 MAP_OPTION( IPPROTO_UDP ),
748 MAP_OPTION( IPPROTO_IPV6 ),
749 MAP_OPTION( IPPROTO_ICMP ),
750 MAP_OPTION( IPPROTO_IGMP ),
751 MAP_OPTION( IPPROTO_RAW ),
752 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
755 static const int ws_aiflag_map[][2] =
757 MAP_OPTION( AI_PASSIVE ),
758 MAP_OPTION( AI_CANONNAME ),
759 MAP_OPTION( AI_NUMERICHOST ),
760 #ifdef AI_NUMERICSERV
761 MAP_OPTION( AI_NUMERICSERV ),
762 #endif
763 #ifdef AI_V4MAPPED
764 MAP_OPTION( AI_V4MAPPED ),
765 #endif
766 MAP_OPTION( AI_ADDRCONFIG ),
769 static const int ws_niflag_map[][2] =
771 MAP_OPTION( NI_NOFQDN ),
772 MAP_OPTION( NI_NUMERICHOST ),
773 MAP_OPTION( NI_NAMEREQD ),
774 MAP_OPTION( NI_NUMERICSERV ),
775 MAP_OPTION( NI_DGRAM ),
778 static const int ws_eai_map[][2] =
780 MAP_OPTION( EAI_AGAIN ),
781 MAP_OPTION( EAI_BADFLAGS ),
782 MAP_OPTION( EAI_FAIL ),
783 MAP_OPTION( EAI_FAMILY ),
784 MAP_OPTION( EAI_MEMORY ),
785 /* Note: EAI_NODATA is deprecated, but still
786 * used by Windows and Linux... We map the newer
787 * EAI_NONAME to EAI_NODATA for now until Windows
788 * changes too.
790 #ifdef EAI_NODATA
791 MAP_OPTION( EAI_NODATA ),
792 #endif
793 #ifdef EAI_NONAME
794 { WS_EAI_NODATA, EAI_NONAME },
795 #endif
797 MAP_OPTION( EAI_SERVICE ),
798 MAP_OPTION( EAI_SOCKTYPE ),
799 { 0, 0 }
802 static const int ws_poll_map[][2] =
804 MAP_OPTION( POLLERR ),
805 MAP_OPTION( POLLHUP ),
806 MAP_OPTION( POLLNVAL ),
807 MAP_OPTION( POLLWRNORM ),
808 MAP_OPTION( POLLWRBAND ),
809 MAP_OPTION( POLLRDNORM ),
810 { WS_POLLRDBAND, POLLPRI }
813 static const char magic_loopback_addr[] = {127, 12, 34, 56};
815 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
816 #ifdef IP_PKTINFO
817 static inline WSACMSGHDR *fill_control_message(int level, int type, WSACMSGHDR *current, ULONG *maxsize, void *data, int len)
819 ULONG msgsize = sizeof(WSACMSGHDR) + WSA_CMSG_ALIGN(len);
820 char *ptr = (char *) current + sizeof(WSACMSGHDR);
822 /* Make sure there is at least enough room for this entry */
823 if (msgsize > *maxsize)
824 return NULL;
825 *maxsize -= msgsize;
826 /* Fill in the entry */
827 current->cmsg_len = sizeof(WSACMSGHDR) + len;
828 current->cmsg_level = level;
829 current->cmsg_type = type;
830 memcpy(ptr, data, len);
831 /* Return the pointer to where next entry should go */
832 return (WSACMSGHDR *) (ptr + WSA_CMSG_ALIGN(len));
834 #endif /* IP_PKTINFO */
836 static inline int convert_control_headers(struct msghdr *hdr, WSABUF *control)
838 #ifdef IP_PKTINFO
839 WSACMSGHDR *cmsg_win = (WSACMSGHDR *) control->buf, *ptr;
840 ULONG ctlsize = control->len;
841 struct cmsghdr *cmsg_unix;
843 ptr = cmsg_win;
844 /* Loop over all the headers, converting as appropriate */
845 for (cmsg_unix = CMSG_FIRSTHDR(hdr); cmsg_unix != NULL; cmsg_unix = CMSG_NXTHDR(hdr, cmsg_unix))
847 switch(cmsg_unix->cmsg_level)
849 case IPPROTO_IP:
850 switch(cmsg_unix->cmsg_type)
852 case IP_PKTINFO:
854 /* Convert the Unix IP_PKTINFO structure to the Windows version */
855 struct in_pktinfo *data_unix = (struct in_pktinfo *) CMSG_DATA(cmsg_unix);
856 struct WS_in_pktinfo data_win;
858 memcpy(&data_win.ipi_addr,&data_unix->ipi_addr.s_addr,4); /* 4 bytes = 32 address bits */
859 data_win.ipi_ifindex = data_unix->ipi_ifindex;
860 ptr = fill_control_message(WS_IPPROTO_IP, WS_IP_PKTINFO, ptr, &ctlsize,
861 (void*)&data_win, sizeof(data_win));
862 if (!ptr) goto error;
863 } break;
864 default:
865 FIXME("Unhandled IPPROTO_IP message header type %d\n", cmsg_unix->cmsg_type);
866 break;
868 break;
869 default:
870 FIXME("Unhandled message header level %d\n", cmsg_unix->cmsg_level);
871 break;
875 error:
876 /* Set the length of the returned control headers */
877 control->len = (ptr == NULL ? 0 : (char*)ptr - (char*)cmsg_win);
878 return (ptr != NULL);
879 #else /* IP_PKTINFO */
880 control->len = 0;
881 return 1;
882 #endif /* IP_PKTINFO */
884 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
886 /* ----------------------------------- error handling */
888 static NTSTATUS sock_get_ntstatus( int err )
890 switch ( err )
892 case EBADF: return STATUS_INVALID_HANDLE;
893 case EBUSY: return STATUS_DEVICE_BUSY;
894 case EPERM:
895 case EACCES: return STATUS_ACCESS_DENIED;
896 case EFAULT: return STATUS_NO_MEMORY;
897 case EINVAL: return STATUS_INVALID_PARAMETER;
898 case ENFILE:
899 case EMFILE: return STATUS_TOO_MANY_OPENED_FILES;
900 case EWOULDBLOCK: return STATUS_CANT_WAIT;
901 case EINPROGRESS: return STATUS_PENDING;
902 case EALREADY: return STATUS_NETWORK_BUSY;
903 case ENOTSOCK: return STATUS_OBJECT_TYPE_MISMATCH;
904 case EDESTADDRREQ: return STATUS_INVALID_PARAMETER;
905 case EMSGSIZE: return STATUS_BUFFER_OVERFLOW;
906 case EPROTONOSUPPORT:
907 case ESOCKTNOSUPPORT:
908 case EPFNOSUPPORT:
909 case EAFNOSUPPORT:
910 case EPROTOTYPE: return STATUS_NOT_SUPPORTED;
911 case ENOPROTOOPT: return STATUS_INVALID_PARAMETER;
912 case EOPNOTSUPP: return STATUS_NOT_SUPPORTED;
913 case EADDRINUSE: return STATUS_ADDRESS_ALREADY_ASSOCIATED;
914 case EADDRNOTAVAIL: return STATUS_INVALID_PARAMETER;
915 case ECONNREFUSED: return STATUS_CONNECTION_REFUSED;
916 case ESHUTDOWN: return STATUS_PIPE_DISCONNECTED;
917 case ENOTCONN: return STATUS_CONNECTION_DISCONNECTED;
918 case ETIMEDOUT: return STATUS_IO_TIMEOUT;
919 case ENETUNREACH: return STATUS_NETWORK_UNREACHABLE;
920 case ENETDOWN: return STATUS_NETWORK_BUSY;
921 case EPIPE:
922 case ECONNRESET: return STATUS_CONNECTION_RESET;
923 case ECONNABORTED: return STATUS_CONNECTION_ABORTED;
925 case 0: return STATUS_SUCCESS;
926 default:
927 WARN("Unknown errno %d!\n", err);
928 return STATUS_UNSUCCESSFUL;
932 static UINT sock_get_error( int err )
934 switch(err)
936 case EINTR: return WSAEINTR;
937 case EPERM:
938 case EACCES: return WSAEACCES;
939 case EFAULT: return WSAEFAULT;
940 case EINVAL: return WSAEINVAL;
941 case EMFILE: return WSAEMFILE;
942 case EWOULDBLOCK: return WSAEWOULDBLOCK;
943 case EINPROGRESS: return WSAEINPROGRESS;
944 case EALREADY: return WSAEALREADY;
945 case EBADF:
946 case ENOTSOCK: return WSAENOTSOCK;
947 case EDESTADDRREQ: return WSAEDESTADDRREQ;
948 case EMSGSIZE: return WSAEMSGSIZE;
949 case EPROTOTYPE: return WSAEPROTOTYPE;
950 case ENOPROTOOPT: return WSAENOPROTOOPT;
951 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
952 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
953 case EOPNOTSUPP: return WSAEOPNOTSUPP;
954 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
955 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
956 case EADDRINUSE: return WSAEADDRINUSE;
957 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
958 case ENETDOWN: return WSAENETDOWN;
959 case ENETUNREACH: return WSAENETUNREACH;
960 case ENETRESET: return WSAENETRESET;
961 case ECONNABORTED: return WSAECONNABORTED;
962 case EPIPE:
963 case ECONNRESET: return WSAECONNRESET;
964 case ENOBUFS: return WSAENOBUFS;
965 case EISCONN: return WSAEISCONN;
966 case ENOTCONN: return WSAENOTCONN;
967 case ESHUTDOWN: return WSAESHUTDOWN;
968 case ETOOMANYREFS: return WSAETOOMANYREFS;
969 case ETIMEDOUT: return WSAETIMEDOUT;
970 case ECONNREFUSED: return WSAECONNREFUSED;
971 case ELOOP: return WSAELOOP;
972 case ENAMETOOLONG: return WSAENAMETOOLONG;
973 case EHOSTDOWN: return WSAEHOSTDOWN;
974 case EHOSTUNREACH: return WSAEHOSTUNREACH;
975 case ENOTEMPTY: return WSAENOTEMPTY;
976 #ifdef EPROCLIM
977 case EPROCLIM: return WSAEPROCLIM;
978 #endif
979 #ifdef EUSERS
980 case EUSERS: return WSAEUSERS;
981 #endif
982 #ifdef EDQUOT
983 case EDQUOT: return WSAEDQUOT;
984 #endif
985 #ifdef ESTALE
986 case ESTALE: return WSAESTALE;
987 #endif
988 #ifdef EREMOTE
989 case EREMOTE: return WSAEREMOTE;
990 #endif
992 /* just in case we ever get here and there are no problems */
993 case 0: return 0;
994 default:
995 WARN("Unknown errno %d!\n", err);
996 return WSAEOPNOTSUPP;
1000 static UINT wsaErrno(void)
1002 int loc_errno = errno;
1003 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
1005 return sock_get_error( loc_errno );
1008 /* most ws2 overlapped functions return an ntstatus-based error code */
1009 static NTSTATUS wsaErrStatus(void)
1011 int loc_errno = errno;
1012 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
1014 return sock_get_ntstatus(loc_errno);
1017 static UINT wsaHerrno(int loc_errno)
1019 WARN("h_errno %d.\n", loc_errno);
1021 switch(loc_errno)
1023 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
1024 case TRY_AGAIN: return WSATRY_AGAIN;
1025 case NO_RECOVERY: return WSANO_RECOVERY;
1026 case NO_DATA: return WSANO_DATA;
1027 case ENOBUFS: return WSAENOBUFS;
1029 case 0: return 0;
1030 default:
1031 WARN("Unknown h_errno %d!\n", loc_errno);
1032 return WSAEOPNOTSUPP;
1036 static inline DWORD NtStatusToWSAError( const DWORD status )
1038 /* We only need to cover the status codes set by server async request handling */
1039 DWORD wserr;
1040 switch ( status )
1042 case STATUS_SUCCESS: wserr = 0; break;
1043 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
1044 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
1045 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
1046 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
1047 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
1048 case STATUS_NETWORK_BUSY: wserr = WSAEALREADY; break;
1049 case STATUS_NETWORK_UNREACHABLE: wserr = WSAENETUNREACH; break;
1050 case STATUS_CONNECTION_REFUSED: wserr = WSAECONNREFUSED; break;
1051 case STATUS_CONNECTION_DISCONNECTED: wserr = WSAENOTCONN; break;
1052 case STATUS_CONNECTION_RESET: wserr = WSAECONNRESET; break;
1053 case STATUS_CONNECTION_ABORTED: wserr = WSAECONNABORTED; break;
1054 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
1055 case STATUS_ADDRESS_ALREADY_ASSOCIATED: wserr = WSAEADDRINUSE; break;
1056 case STATUS_IO_TIMEOUT:
1057 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
1058 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
1059 case STATUS_ACCESS_DENIED: wserr = WSAEACCES; break;
1060 case STATUS_TOO_MANY_OPENED_FILES: wserr = WSAEMFILE; break;
1061 case STATUS_CANT_WAIT: wserr = WSAEWOULDBLOCK; break;
1062 case STATUS_BUFFER_OVERFLOW: wserr = WSAEMSGSIZE; break;
1063 case STATUS_NOT_SUPPORTED: wserr = WSAEOPNOTSUPP; break;
1064 case STATUS_HOST_UNREACHABLE: wserr = WSAEHOSTUNREACH; break;
1066 default:
1067 wserr = RtlNtStatusToDosError( status );
1068 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
1070 return wserr;
1073 /* set last error code from NT status without mapping WSA errors */
1074 static inline unsigned int set_error( unsigned int err )
1076 if (err)
1078 err = NtStatusToWSAError( err );
1079 SetLastError( err );
1081 return err;
1084 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
1086 int fd;
1087 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
1088 return -1;
1089 return fd;
1092 static inline void release_sock_fd( SOCKET s, int fd )
1094 wine_server_release_fd( SOCKET2HANDLE(s), fd );
1097 static void _enable_event( HANDLE s, unsigned int event,
1098 unsigned int sstate, unsigned int cstate )
1100 SERVER_START_REQ( enable_socket_event )
1102 req->handle = wine_server_obj_handle( s );
1103 req->mask = event;
1104 req->sstate = sstate;
1105 req->cstate = cstate;
1106 wine_server_call( req );
1108 SERVER_END_REQ;
1111 static NTSTATUS _is_blocking(SOCKET s, BOOL *ret)
1113 NTSTATUS status;
1114 SERVER_START_REQ( get_socket_event )
1116 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1117 req->service = FALSE;
1118 req->c_event = 0;
1119 status = wine_server_call( req );
1120 *ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
1122 SERVER_END_REQ;
1123 return status;
1126 static unsigned int _get_sock_mask(SOCKET s)
1128 unsigned int ret;
1129 SERVER_START_REQ( get_socket_event )
1131 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1132 req->service = FALSE;
1133 req->c_event = 0;
1134 wine_server_call( req );
1135 ret = reply->mask;
1137 SERVER_END_REQ;
1138 return ret;
1141 static void _sync_sock_state(SOCKET s)
1143 BOOL dummy;
1144 /* do a dummy wineserver request in order to let
1145 the wineserver run through its select loop once */
1146 (void)_is_blocking(s, &dummy);
1149 static void _get_sock_errors(SOCKET s, int *events)
1151 SERVER_START_REQ( get_socket_event )
1153 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1154 req->service = FALSE;
1155 req->c_event = 0;
1156 wine_server_set_reply( req, events, sizeof(int) * FD_MAX_EVENTS );
1157 wine_server_call( req );
1159 SERVER_END_REQ;
1162 static int _get_sock_error(SOCKET s, unsigned int bit)
1164 int events[FD_MAX_EVENTS];
1165 _get_sock_errors(s, events);
1166 return events[bit];
1169 static int _get_fd_type(int fd)
1171 int sock_type = -1;
1172 socklen_t optlen = sizeof(sock_type);
1173 getsockopt(fd, SOL_SOCKET, SO_TYPE, (char*) &sock_type, &optlen);
1174 return sock_type;
1177 static BOOL set_dont_fragment(SOCKET s, int level, BOOL value)
1179 int fd, optname;
1181 if (level == IPPROTO_IP)
1183 #ifdef IP_DONTFRAG
1184 optname = IP_DONTFRAG;
1185 #elif defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO) && defined(IP_PMTUDISC_DONT)
1186 optname = IP_MTU_DISCOVER;
1187 value = value ? IP_PMTUDISC_DO : IP_PMTUDISC_DONT;
1188 #else
1189 static int once;
1190 if (!once++)
1191 FIXME("IP_DONTFRAGMENT for IPv4 not supported in this platform\n");
1192 return TRUE; /* fake success */
1193 #endif
1195 else
1197 #ifdef IPV6_DONTFRAG
1198 optname = IPV6_DONTFRAG;
1199 #elif defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO) && defined(IPV6_PMTUDISC_DONT)
1200 optname = IPV6_MTU_DISCOVER;
1201 value = value ? IPV6_PMTUDISC_DO : IPV6_PMTUDISC_DONT;
1202 #else
1203 static int once;
1204 if (!once++)
1205 FIXME("IP_DONTFRAGMENT for IPv6 not supported in this platform\n");
1206 return TRUE; /* fake success */
1207 #endif
1210 fd = get_sock_fd(s, 0, NULL);
1211 if (fd == -1) return FALSE;
1213 if (!setsockopt(fd, level, optname, &value, sizeof(value)))
1214 value = TRUE;
1215 else
1217 WSASetLastError(wsaErrno());
1218 value = FALSE;
1221 release_sock_fd(s, fd);
1222 return value;
1225 static BOOL get_dont_fragment(SOCKET s, int level, BOOL *out)
1227 int fd, optname, value, not_expected;
1228 socklen_t optlen = sizeof(value);
1230 if (level == IPPROTO_IP)
1232 #ifdef IP_DONTFRAG
1233 optname = IP_DONTFRAG;
1234 not_expected = 0;
1235 #elif defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
1236 optname = IP_MTU_DISCOVER;
1237 not_expected = IP_PMTUDISC_DONT;
1238 #else
1239 static int once;
1240 if (!once++)
1241 FIXME("IP_DONTFRAGMENT for IPv4 not supported in this platform\n");
1242 return TRUE; /* fake success */
1243 #endif
1245 else
1247 #ifdef IPV6_DONTFRAG
1248 optname = IPV6_DONTFRAG;
1249 not_expected = 0;
1250 #elif defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DONT)
1251 optname = IPV6_MTU_DISCOVER;
1252 not_expected = IPV6_PMTUDISC_DONT;
1253 #else
1254 static int once;
1255 if (!once++)
1256 FIXME("IP_DONTFRAGMENT for IPv6 not supported in this platform\n");
1257 return TRUE; /* fake success */
1258 #endif
1261 fd = get_sock_fd(s, 0, NULL);
1262 if (fd == -1) return FALSE;
1264 if (!getsockopt(fd, level, optname, &value, &optlen))
1266 *out = value != not_expected;
1267 value = TRUE;
1269 else
1271 WSASetLastError(wsaErrno());
1272 value = FALSE;
1275 release_sock_fd(s, fd);
1276 return value;
1279 static struct per_thread_data *get_per_thread_data(void)
1281 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
1282 /* lazy initialization */
1283 if (!ptb)
1285 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
1286 NtCurrentTeb()->WinSockData = ptb;
1288 return ptb;
1291 static void free_per_thread_data(void)
1293 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
1295 if (!ptb) return;
1297 /* delete scratch buffers */
1298 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1299 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1300 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1301 HeapFree( GetProcessHeap(), 0, ptb->fd_cache );
1303 HeapFree( GetProcessHeap(), 0, ptb );
1304 NtCurrentTeb()->WinSockData = NULL;
1307 /***********************************************************************
1308 * DllMain (WS2_32.init)
1310 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
1312 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
1313 switch (fdwReason) {
1314 case DLL_PROCESS_ATTACH:
1315 break;
1316 case DLL_PROCESS_DETACH:
1317 if (fImpLoad) break;
1318 free_per_thread_data();
1319 DeleteCriticalSection(&csWSgetXXXbyYYY);
1320 break;
1321 case DLL_THREAD_DETACH:
1322 free_per_thread_data();
1323 break;
1325 return TRUE;
1328 /***********************************************************************
1329 * convert_flags()
1331 * Converts send/recv flags from Windows format.
1332 * Return the converted flag bits, unsupported flags remain unchanged.
1334 static int convert_flags(int flags)
1336 int i, out;
1337 if (!flags) return 0;
1339 for (out = i = 0; flags && i < sizeof(ws_flags_map) / sizeof(ws_flags_map[0]); i++)
1341 if (ws_flags_map[i][0] & flags)
1343 out |= ws_flags_map[i][1];
1344 flags &= ~ws_flags_map[i][0];
1347 if (flags)
1349 FIXME("Unknown send/recv flags 0x%x, using anyway...\n", flags);
1350 out |= flags;
1352 return out;
1355 /***********************************************************************
1356 * convert_sockopt()
1358 * Converts socket flags from Windows format.
1359 * Return 1 if converted, 0 if not (error).
1361 static int convert_sockopt(INT *level, INT *optname)
1363 unsigned int i;
1364 switch (*level)
1366 case WS_SOL_SOCKET:
1367 *level = SOL_SOCKET;
1368 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
1369 if( ws_sock_map[i][0] == *optname )
1371 *optname = ws_sock_map[i][1];
1372 return 1;
1375 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
1376 break;
1377 case WS_IPPROTO_TCP:
1378 *level = IPPROTO_TCP;
1379 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
1380 if ( ws_tcp_map[i][0] == *optname )
1382 *optname = ws_tcp_map[i][1];
1383 return 1;
1386 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
1387 break;
1388 case WS_IPPROTO_IP:
1389 *level = IPPROTO_IP;
1390 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
1391 if (ws_ip_map[i][0] == *optname )
1393 *optname = ws_ip_map[i][1];
1394 return 1;
1397 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
1398 break;
1399 case WS_IPPROTO_IPV6:
1400 *level = IPPROTO_IPV6;
1401 for(i=0; i<sizeof(ws_ipv6_map)/sizeof(ws_ipv6_map[0]); i++) {
1402 if (ws_ipv6_map[i][0] == *optname )
1404 *optname = ws_ipv6_map[i][1];
1405 return 1;
1408 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname);
1409 break;
1410 default: FIXME("Unimplemented or unknown socket level\n");
1412 return 0;
1415 /* ----------------------------------- Per-thread info (or per-process?) */
1417 static char *strdup_lower(const char *str)
1419 int i;
1420 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
1422 if (ret)
1424 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
1425 ret[i] = 0;
1427 else SetLastError(WSAENOBUFS);
1428 return ret;
1431 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
1432 * from an fd and return the value converted to milli seconds
1433 * or 0 if there is an infinite time out */
1434 static inline INT64 get_rcvsnd_timeo( int fd, BOOL is_recv)
1436 struct timeval tv;
1437 socklen_t len = sizeof(tv);
1438 int optname, res;
1440 if (is_recv)
1441 #ifdef SO_RCVTIMEO
1442 optname = SO_RCVTIMEO;
1443 #else
1444 return 0;
1445 #endif
1446 else
1447 #ifdef SO_SNDTIMEO
1448 optname = SO_SNDTIMEO;
1449 #else
1450 return 0;
1451 #endif
1453 res = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
1454 if (res < 0)
1455 return 0;
1456 return (UINT64)tv.tv_sec * 1000 + tv.tv_usec / 1000;
1459 /* utility: given an fd, will block until one of the events occurs */
1460 static inline int do_block( int fd, int events, int timeout )
1462 struct pollfd pfd;
1463 int ret;
1465 pfd.fd = fd;
1466 pfd.events = events;
1468 while ((ret = poll(&pfd, 1, timeout)) < 0)
1470 if (errno != EINTR)
1471 return -1;
1473 if( ret == 0 )
1474 return 0;
1475 return pfd.revents;
1478 static int
1479 convert_af_w2u(int windowsaf) {
1480 unsigned int i;
1482 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1483 if (ws_af_map[i][0] == windowsaf)
1484 return ws_af_map[i][1];
1485 FIXME("unhandled Windows address family %d\n", windowsaf);
1486 return -1;
1489 static int
1490 convert_af_u2w(int unixaf) {
1491 unsigned int i;
1493 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1494 if (ws_af_map[i][1] == unixaf)
1495 return ws_af_map[i][0];
1496 FIXME("unhandled UNIX address family %d\n", unixaf);
1497 return -1;
1500 static int
1501 convert_proto_w2u(int windowsproto) {
1502 unsigned int i;
1504 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1505 if (ws_proto_map[i][0] == windowsproto)
1506 return ws_proto_map[i][1];
1508 /* check for extended IPX */
1509 if (IS_IPX_PROTO(windowsproto))
1510 return windowsproto;
1512 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
1513 return -1;
1516 static int
1517 convert_proto_u2w(int unixproto) {
1518 unsigned int i;
1520 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1521 if (ws_proto_map[i][1] == unixproto)
1522 return ws_proto_map[i][0];
1524 /* if value is inside IPX range just return it - the kernel simply
1525 * echoes the value used in the socket() function */
1526 if (IS_IPX_PROTO(unixproto))
1527 return unixproto;
1529 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
1530 return -1;
1533 static int
1534 convert_socktype_w2u(int windowssocktype) {
1535 unsigned int i;
1537 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1538 if (ws_socktype_map[i][0] == windowssocktype)
1539 return ws_socktype_map[i][1];
1540 FIXME("unhandled Windows socket type %d\n", windowssocktype);
1541 return -1;
1544 static int
1545 convert_socktype_u2w(int unixsocktype) {
1546 unsigned int i;
1548 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1549 if (ws_socktype_map[i][1] == unixsocktype)
1550 return ws_socktype_map[i][0];
1551 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
1552 return -1;
1555 static int convert_poll_w2u(int events)
1557 int i, ret;
1558 for (i = ret = 0; events && i < sizeof(ws_poll_map) / sizeof(ws_poll_map[0]); i++)
1560 if (ws_poll_map[i][0] & events)
1562 ret |= ws_poll_map[i][1];
1563 events &= ~ws_poll_map[i][0];
1567 if (events)
1568 FIXME("Unsupported WSAPoll() flags 0x%x\n", events);
1569 return ret;
1572 static int convert_poll_u2w(int events)
1574 int i, ret;
1575 for (i = ret = 0; events && i < sizeof(ws_poll_map) / sizeof(ws_poll_map[0]); i++)
1577 if (ws_poll_map[i][1] & events)
1579 ret |= ws_poll_map[i][0];
1580 events &= ~ws_poll_map[i][1];
1584 if (events)
1585 FIXME("Unsupported poll() flags 0x%x\n", events);
1586 return ret;
1589 static int set_ipx_packettype(int sock, int ptype)
1591 #ifdef HAS_IPX
1592 int fd = get_sock_fd( sock, 0, NULL ), ret = 0;
1593 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", ptype, fd);
1595 if (fd == -1) return SOCKET_ERROR;
1597 /* We try to set the ipx type on ipx socket level. */
1598 #ifdef SOL_IPX
1599 if(setsockopt(fd, SOL_IPX, IPX_TYPE, &ptype, sizeof(ptype)) == -1)
1601 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
1602 ret = SOCKET_ERROR;
1604 #else
1606 struct ipx val;
1607 /* Should we retrieve val using a getsockopt call and then
1608 * set the modified one? */
1609 val.ipx_pt = ptype;
1610 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
1612 #endif
1613 release_sock_fd( sock, fd );
1614 return ret;
1615 #else
1616 WARN("IPX support is not enabled, can't set packet type\n");
1617 return SOCKET_ERROR;
1618 #endif
1621 /* ----------------------------------- API -----
1623 * Init / cleanup / error checking.
1626 /***********************************************************************
1627 * WSAStartup (WS2_32.115)
1629 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
1631 TRACE("verReq=%x\n", wVersionRequested);
1633 if (LOBYTE(wVersionRequested) < 1)
1634 return WSAVERNOTSUPPORTED;
1636 if (!lpWSAData) return WSAEINVAL;
1638 num_startup++;
1640 /* that's the whole of the negotiation for now */
1641 lpWSAData->wVersion = wVersionRequested;
1642 /* return winsock information */
1643 lpWSAData->wHighVersion = 0x0202;
1644 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
1645 strcpy(lpWSAData->szSystemStatus, "Running" );
1646 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
1647 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
1648 /* don't do anything with lpWSAData->lpVendorInfo */
1649 /* (some apps don't allocate the space for this field) */
1651 TRACE("succeeded starts: %d\n", num_startup);
1652 return 0;
1656 /***********************************************************************
1657 * WSACleanup (WS2_32.116)
1659 INT WINAPI WSACleanup(void)
1661 if (num_startup) {
1662 num_startup--;
1663 TRACE("pending cleanups: %d\n", num_startup);
1664 return 0;
1666 SetLastError(WSANOTINITIALISED);
1667 return SOCKET_ERROR;
1671 /***********************************************************************
1672 * WSAGetLastError (WS2_32.111)
1674 INT WINAPI WSAGetLastError(void)
1676 return GetLastError();
1679 /***********************************************************************
1680 * WSASetLastError (WS2_32.112)
1682 void WINAPI WSASetLastError(INT iError) {
1683 SetLastError(iError);
1686 static struct WS_hostent *check_buffer_he(int size)
1688 struct per_thread_data * ptb = get_per_thread_data();
1689 if (ptb->he_buffer)
1691 if (ptb->he_len >= size ) return ptb->he_buffer;
1692 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1694 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
1695 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
1696 return ptb->he_buffer;
1699 static struct WS_servent *check_buffer_se(int size)
1701 struct per_thread_data * ptb = get_per_thread_data();
1702 if (ptb->se_buffer)
1704 if (ptb->se_len >= size ) return ptb->se_buffer;
1705 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1707 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
1708 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
1709 return ptb->se_buffer;
1712 static struct WS_protoent *check_buffer_pe(int size)
1714 struct per_thread_data * ptb = get_per_thread_data();
1715 if (ptb->pe_buffer)
1717 if (ptb->pe_len >= size ) return ptb->pe_buffer;
1718 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1720 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
1721 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
1722 return ptb->pe_buffer;
1725 /* ----------------------------------- i/o APIs */
1727 static inline BOOL supported_pf(int pf)
1729 switch (pf)
1731 case WS_AF_INET:
1732 case WS_AF_INET6:
1733 return TRUE;
1734 #ifdef HAS_IPX
1735 case WS_AF_IPX:
1736 return TRUE;
1737 #endif
1738 #ifdef HAS_IRDA
1739 case WS_AF_IRDA:
1740 return TRUE;
1741 #endif
1742 default:
1743 return FALSE;
1747 static inline BOOL supported_protocol(int protocol)
1749 int i;
1750 for (i = 0; i < sizeof(valid_protocols) / sizeof(valid_protocols[0]); i++)
1751 if (protocol == valid_protocols[i])
1752 return TRUE;
1753 return FALSE;
1756 /**********************************************************************/
1758 /* Returns the length of the converted address if successful, 0 if it was too
1759 * small to start with or unknown family or invalid address buffer.
1761 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
1762 union generic_unix_sockaddr *uaddr)
1764 unsigned int uaddrlen = 0;
1766 if (!wsaddr)
1767 return 0;
1769 switch (wsaddr->sa_family)
1771 #ifdef HAS_IPX
1772 case WS_AF_IPX:
1774 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
1775 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
1777 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
1778 return 0;
1780 uaddrlen = sizeof(struct sockaddr_ipx);
1781 memset( uaddr, 0, uaddrlen );
1782 uipx->sipx_family=AF_IPX;
1783 uipx->sipx_port=wsipx->sa_socket;
1784 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1785 * in one go
1787 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
1788 #ifdef IPX_FRAME_NONE
1789 uipx->sipx_type=IPX_FRAME_NONE;
1790 #endif
1791 break;
1793 #endif
1794 case WS_AF_INET6: {
1795 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
1796 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
1798 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1799 * scope_id, one without.
1801 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
1802 uaddrlen = sizeof(struct sockaddr_in6);
1803 memset( uaddr, 0, uaddrlen );
1804 uin6->sin6_family = AF_INET6;
1805 uin6->sin6_port = win6->sin6_port;
1806 uin6->sin6_flowinfo = win6->sin6_flowinfo;
1807 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1808 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
1809 #endif
1810 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
1811 break;
1813 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
1814 return 0;
1816 case WS_AF_INET: {
1817 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
1818 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
1820 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
1821 return 0;
1822 uaddrlen = sizeof(struct sockaddr_in);
1823 memset( uaddr, 0, uaddrlen );
1824 uin->sin_family = AF_INET;
1825 uin->sin_port = win->sin_port;
1826 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
1827 break;
1829 #ifdef HAS_IRDA
1830 case WS_AF_IRDA: {
1831 struct sockaddr_irda *uin = (struct sockaddr_irda *)uaddr;
1832 const SOCKADDR_IRDA *win = (const SOCKADDR_IRDA *)wsaddr;
1834 if (wsaddrlen < sizeof(SOCKADDR_IRDA))
1835 return 0;
1836 uaddrlen = sizeof(struct sockaddr_irda);
1837 memset( uaddr, 0, uaddrlen );
1838 uin->sir_family = AF_IRDA;
1839 if (!strncmp( win->irdaServiceName, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1841 unsigned int lsap_sel = 0;
1843 sscanf( win->irdaServiceName, "LSAP-SEL%u", &lsap_sel );
1844 uin->sir_lsap_sel = lsap_sel;
1846 else
1848 uin->sir_lsap_sel = LSAP_ANY;
1849 memcpy( uin->sir_name, win->irdaServiceName, 25 );
1851 memcpy( &uin->sir_addr, win->irdaDeviceID, sizeof(uin->sir_addr) );
1852 break;
1854 #endif
1855 case WS_AF_UNSPEC: {
1856 /* Try to determine the needed space by the passed windows sockaddr space */
1857 switch (wsaddrlen) {
1858 default: /* likely an ipv4 address */
1859 case sizeof(struct WS_sockaddr_in):
1860 uaddrlen = sizeof(struct sockaddr_in);
1861 break;
1862 #ifdef HAS_IPX
1863 case sizeof(struct WS_sockaddr_ipx):
1864 uaddrlen = sizeof(struct sockaddr_ipx);
1865 break;
1866 #endif
1867 #ifdef HAS_IRDA
1868 case sizeof(SOCKADDR_IRDA):
1869 uaddrlen = sizeof(struct sockaddr_irda);
1870 break;
1871 #endif
1872 case sizeof(struct WS_sockaddr_in6):
1873 case sizeof(struct WS_sockaddr_in6_old):
1874 uaddrlen = sizeof(struct sockaddr_in6);
1875 break;
1877 memset( uaddr, 0, uaddrlen );
1878 break;
1880 default:
1881 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
1882 return 0;
1884 return uaddrlen;
1887 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
1889 switch (uaddr->sa_family)
1891 #ifdef HAS_IPX
1892 case AF_IPX:
1894 static const struct sockaddr_ipx emptyAddr;
1895 struct sockaddr_ipx *ipx = (struct sockaddr_ipx*) uaddr;
1896 return ipx->sipx_port
1897 || memcmp(&ipx->sipx_network, &emptyAddr.sipx_network, sizeof(emptyAddr.sipx_network))
1898 || memcmp(&ipx->sipx_node, &emptyAddr.sipx_node, sizeof(emptyAddr.sipx_node));
1900 #endif
1901 case AF_INET6:
1903 static const struct sockaddr_in6 emptyAddr;
1904 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
1905 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
1907 case AF_INET:
1909 static const struct sockaddr_in emptyAddr;
1910 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
1911 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
1913 case AF_UNSPEC:
1914 return FALSE;
1915 default:
1916 FIXME("unknown address family %d\n", uaddr->sa_family);
1917 return TRUE;
1921 /* Returns -1 if getsockname fails, 0 if not bound, 1 otherwise */
1922 static int is_fd_bound(int fd, union generic_unix_sockaddr *uaddr, socklen_t *uaddrlen)
1924 union generic_unix_sockaddr inaddr;
1925 socklen_t inlen;
1926 int res;
1928 if (!uaddr) uaddr = &inaddr;
1929 if (!uaddrlen) uaddrlen = &inlen;
1931 *uaddrlen = sizeof(inaddr);
1932 res = getsockname(fd, &uaddr->addr, uaddrlen);
1933 if (!res) res = is_sockaddr_bound(&uaddr->addr, *uaddrlen);
1934 return res;
1937 /* Returns 0 if successful, -1 if the buffer is too small */
1938 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
1940 int res;
1942 switch(uaddr->sa_family)
1944 #ifdef HAS_IPX
1945 case AF_IPX:
1947 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
1948 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
1950 res=-1;
1951 switch (*wsaddrlen) /* how much can we copy? */
1953 default:
1954 res=0; /* enough */
1955 *wsaddrlen = sizeof(*wsipx);
1956 wsipx->sa_socket=uipx->sipx_port;
1957 /* fall through */
1958 case 13:
1959 case 12:
1960 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
1961 /* fall through */
1962 case 11:
1963 case 10:
1964 case 9:
1965 case 8:
1966 case 7:
1967 case 6:
1968 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1969 /* fall through */
1970 case 5:
1971 case 4:
1972 case 3:
1973 case 2:
1974 wsipx->sa_family=WS_AF_IPX;
1975 /* fall through */
1976 case 1:
1977 case 0:
1978 /* way too small */
1979 break;
1982 break;
1983 #endif
1984 #ifdef HAS_IRDA
1985 case AF_IRDA: {
1986 const struct sockaddr_irda *uin = (const struct sockaddr_irda *)uaddr;
1987 SOCKADDR_IRDA *win = (SOCKADDR_IRDA *)wsaddr;
1989 if (*wsaddrlen < sizeof(SOCKADDR_IRDA))
1990 return -1;
1991 win->irdaAddressFamily = WS_AF_IRDA;
1992 memcpy( win->irdaDeviceID, &uin->sir_addr, sizeof(win->irdaDeviceID) );
1993 if (uin->sir_lsap_sel != LSAP_ANY)
1994 sprintf( win->irdaServiceName, "LSAP-SEL%u", uin->sir_lsap_sel );
1995 else
1996 memcpy( win->irdaServiceName, uin->sir_name,
1997 sizeof(win->irdaServiceName) );
1998 return 0;
2000 #endif
2001 case AF_INET6: {
2002 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
2003 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
2005 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
2006 return -1;
2007 win6old->sin6_family = WS_AF_INET6;
2008 win6old->sin6_port = uin6->sin6_port;
2009 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
2010 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
2011 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
2012 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
2013 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
2014 win6->sin6_scope_id = uin6->sin6_scope_id;
2015 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
2017 else
2018 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
2019 #else
2020 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
2021 #endif
2022 return 0;
2024 case AF_INET: {
2025 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
2026 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
2028 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
2029 return -1;
2030 win->sin_family = WS_AF_INET;
2031 win->sin_port = uin->sin_port;
2032 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
2033 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
2034 *wsaddrlen = sizeof(struct WS_sockaddr_in);
2035 return 0;
2037 case AF_UNSPEC: {
2038 memset(wsaddr,0,*wsaddrlen);
2039 return 0;
2041 default:
2042 FIXME("Unknown address family %d\n", uaddr->sa_family);
2043 return -1;
2045 return res;
2048 static INT WS_DuplicateSocket(BOOL unicode, SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo)
2050 HANDLE hProcess;
2051 int size;
2052 WSAPROTOCOL_INFOW infow;
2054 TRACE("(unicode %d, socket %04lx, processid %x, buffer %p)\n",
2055 unicode, s, dwProcessId, lpProtocolInfo);
2057 if (!ws_protocol_info(s, unicode, &infow, &size))
2058 return SOCKET_ERROR;
2060 if (!(hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId)))
2062 SetLastError(WSAEINVAL);
2063 return SOCKET_ERROR;
2066 if (!lpProtocolInfo)
2068 CloseHandle(hProcess);
2069 SetLastError(WSAEFAULT);
2070 return SOCKET_ERROR;
2073 /* I don't know what the real Windoze does next, this is a hack */
2074 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
2075 * the target use the global duplicate, or we could copy a reference to us to the structure
2076 * and let the target duplicate it from us, but let's do it as simple as possible */
2077 memcpy(lpProtocolInfo, &infow, size);
2078 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
2079 hProcess, (LPHANDLE)&lpProtocolInfo->dwServiceFlags3,
2080 0, FALSE, DUPLICATE_SAME_ACCESS);
2081 CloseHandle(hProcess);
2082 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
2083 return 0;
2086 /*****************************************************************************
2087 * WS_EnterSingleProtocolW [internal]
2089 * enters the protocol information of one given protocol into the given
2090 * buffer.
2092 * RETURNS
2093 * TRUE if a protocol was entered into the buffer.
2095 * BUGS
2096 * - only implemented for IPX, SPX, SPXII, TCP, UDP
2097 * - there is no check that the operating system supports the returned
2098 * protocols
2100 static BOOL WS_EnterSingleProtocolW( INT protocol, WSAPROTOCOL_INFOW* info )
2102 memset( info, 0, sizeof(WSAPROTOCOL_INFOW) );
2103 info->iProtocol = protocol;
2105 switch (protocol)
2107 case WS_IPPROTO_TCP:
2108 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_EXPEDITED_DATA |
2109 XP1_GRACEFUL_CLOSE | XP1_GUARANTEED_ORDER |
2110 XP1_GUARANTEED_DELIVERY;
2111 info->ProviderId = ProviderIdIP;
2112 info->dwCatalogEntryId = 0x3e9;
2113 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
2114 info->ProtocolChain.ChainLen = 1;
2115 info->iVersion = 2;
2116 info->iAddressFamily = WS_AF_INET;
2117 info->iMaxSockAddr = 0x10;
2118 info->iMinSockAddr = 0x10;
2119 info->iSocketType = WS_SOCK_STREAM;
2120 strcpyW( info->szProtocol, NameTcpW );
2121 break;
2123 case WS_IPPROTO_UDP:
2124 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_SUPPORT_BROADCAST |
2125 XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED |
2126 XP1_CONNECTIONLESS;
2127 info->ProviderId = ProviderIdIP;
2128 info->dwCatalogEntryId = 0x3ea;
2129 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
2130 info->ProtocolChain.ChainLen = 1;
2131 info->iVersion = 2;
2132 info->iAddressFamily = WS_AF_INET;
2133 info->iMaxSockAddr = 0x10;
2134 info->iMinSockAddr = 0x10;
2135 info->iSocketType = WS_SOCK_DGRAM;
2136 info->dwMessageSize = 0xffbb;
2137 strcpyW( info->szProtocol, NameUdpW );
2138 break;
2140 case WS_NSPROTO_IPX:
2141 info->dwServiceFlags1 = XP1_PARTIAL_MESSAGE | XP1_SUPPORT_BROADCAST |
2142 XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED |
2143 XP1_CONNECTIONLESS;
2144 info->ProviderId = ProviderIdIPX;
2145 info->dwCatalogEntryId = 0x406;
2146 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
2147 info->ProtocolChain.ChainLen = 1;
2148 info->iVersion = 2;
2149 info->iAddressFamily = WS_AF_IPX;
2150 info->iMaxSockAddr = 0x10;
2151 info->iMinSockAddr = 0x0e;
2152 info->iSocketType = WS_SOCK_DGRAM;
2153 info->iProtocolMaxOffset = 0xff;
2154 info->dwMessageSize = 0x240;
2155 strcpyW( info->szProtocol, NameIpxW );
2156 break;
2158 case WS_NSPROTO_SPX:
2159 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_PSEUDO_STREAM |
2160 XP1_MESSAGE_ORIENTED | XP1_GUARANTEED_ORDER |
2161 XP1_GUARANTEED_DELIVERY;
2162 info->ProviderId = ProviderIdSPX;
2163 info->dwCatalogEntryId = 0x407;
2164 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
2165 info->ProtocolChain.ChainLen = 1;
2166 info->iVersion = 2;
2167 info->iAddressFamily = WS_AF_IPX;
2168 info->iMaxSockAddr = 0x10;
2169 info->iMinSockAddr = 0x0e;
2170 info->iSocketType = WS_SOCK_SEQPACKET;
2171 info->dwMessageSize = 0xffffffff;
2172 strcpyW( info->szProtocol, NameSpxW );
2173 break;
2175 case WS_NSPROTO_SPXII:
2176 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_GRACEFUL_CLOSE |
2177 XP1_PSEUDO_STREAM | XP1_MESSAGE_ORIENTED |
2178 XP1_GUARANTEED_ORDER | XP1_GUARANTEED_DELIVERY;
2179 info->ProviderId = ProviderIdSPX;
2180 info->dwCatalogEntryId = 0x409;
2181 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
2182 info->ProtocolChain.ChainLen = 1;
2183 info->iVersion = 2;
2184 info->iAddressFamily = WS_AF_IPX;
2185 info->iMaxSockAddr = 0x10;
2186 info->iMinSockAddr = 0x0e;
2187 info->iSocketType = WS_SOCK_SEQPACKET;
2188 info->dwMessageSize = 0xffffffff;
2189 strcpyW( info->szProtocol, NameSpxIIW );
2190 break;
2192 default:
2193 FIXME("unknown Protocol <0x%08x>\n", protocol);
2194 return FALSE;
2196 return TRUE;
2199 /*****************************************************************************
2200 * WS_EnterSingleProtocolA [internal]
2202 * see function WS_EnterSingleProtocolW
2205 static BOOL WS_EnterSingleProtocolA( INT protocol, WSAPROTOCOL_INFOA* info )
2207 WSAPROTOCOL_INFOW infow;
2208 INT ret;
2209 memset( info, 0, sizeof(WSAPROTOCOL_INFOA) );
2211 ret = WS_EnterSingleProtocolW( protocol, &infow );
2212 if (ret)
2214 /* convert the structure from W to A */
2215 memcpy( info, &infow, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
2216 WideCharToMultiByte( CP_ACP, 0, infow.szProtocol, -1,
2217 info->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL );
2220 return ret;
2223 static INT WS_EnumProtocols( BOOL unicode, const INT *protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
2225 INT i = 0, items = 0;
2226 DWORD size = 0;
2227 union _info
2229 LPWSAPROTOCOL_INFOA a;
2230 LPWSAPROTOCOL_INFOW w;
2231 } info;
2232 info.w = buffer;
2234 if (!protocols) protocols = valid_protocols;
2236 while (protocols[i])
2238 if(supported_protocol(protocols[i++]))
2239 items++;
2242 size = items * (unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA));
2244 TRACE("unicode %d, protocols %p, buffer %p, length %p %d, items %d, required %d\n",
2245 unicode, protocols, buffer, len, len ? *len : 0, items, size);
2247 if (*len < size || !buffer)
2249 *len = size;
2250 SetLastError(WSAENOBUFS);
2251 return SOCKET_ERROR;
2254 for (i = items = 0; protocols[i]; i++)
2256 if (!supported_protocol(protocols[i])) continue;
2257 if (unicode)
2259 if (WS_EnterSingleProtocolW( protocols[i], &info.w[items] ))
2260 items++;
2262 else
2264 if (WS_EnterSingleProtocolA( protocols[i], &info.a[items] ))
2265 items++;
2268 return items;
2271 static BOOL ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size)
2273 NTSTATUS status;
2275 *size = unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA);
2276 memset(buffer, 0, *size);
2278 SERVER_START_REQ( get_socket_info )
2280 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
2281 status = wine_server_call( req );
2282 if (!status)
2284 buffer->iAddressFamily = convert_af_u2w(reply->family);
2285 buffer->iSocketType = convert_socktype_u2w(reply->type);
2286 buffer->iProtocol = convert_proto_u2w(reply->protocol);
2289 SERVER_END_REQ;
2291 if (status)
2293 unsigned int err = NtStatusToWSAError( status );
2294 SetLastError( err == WSAEBADF ? WSAENOTSOCK : err );
2295 return FALSE;
2298 if (unicode)
2299 WS_EnterSingleProtocolW( buffer->iProtocol, buffer);
2300 else
2301 WS_EnterSingleProtocolA( buffer->iProtocol, (WSAPROTOCOL_INFOA *)buffer);
2303 return TRUE;
2306 /**************************************************************************
2307 * Functions for handling overlapped I/O
2308 **************************************************************************/
2310 /* user APC called upon async completion */
2311 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
2313 struct ws2_async *wsa = arg;
2315 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
2316 iosb->Information, wsa->user_overlapped,
2317 wsa->flags );
2318 release_async_io( &wsa->io );
2321 /***********************************************************************
2322 * WS2_recv (INTERNAL)
2324 * Workhorse for both synchronous and asynchronous recv() operations.
2326 static int WS2_recv( int fd, struct ws2_async *wsa, int flags )
2328 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2329 char pktbuf[512];
2330 #endif
2331 struct msghdr hdr;
2332 union generic_unix_sockaddr unix_sockaddr;
2333 int n;
2335 hdr.msg_name = NULL;
2337 if (wsa->addr)
2339 hdr.msg_namelen = sizeof(unix_sockaddr);
2340 hdr.msg_name = &unix_sockaddr;
2342 else
2343 hdr.msg_namelen = 0;
2345 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
2346 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
2347 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2348 hdr.msg_accrights = NULL;
2349 hdr.msg_accrightslen = 0;
2350 #else
2351 hdr.msg_control = pktbuf;
2352 hdr.msg_controllen = sizeof(pktbuf);
2353 hdr.msg_flags = 0;
2354 #endif
2356 while ((n = recvmsg(fd, &hdr, flags)) == -1)
2358 if (errno != EINTR)
2359 return -1;
2362 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2363 if (wsa->control)
2365 ERR("Message control headers cannot be properly supported on this system.\n");
2366 wsa->control->len = 0;
2368 #else
2369 if (wsa->control && !convert_control_headers(&hdr, wsa->control))
2371 WARN("Application passed insufficient room for control headers.\n");
2372 *wsa->lpFlags |= WS_MSG_CTRUNC;
2373 errno = EMSGSIZE;
2374 return -1;
2376 #endif
2378 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
2379 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
2381 * quoting linux 2.6 net/ipv4/tcp.c:
2382 * "According to UNIX98, msg_name/msg_namelen are ignored
2383 * on connected socket. I was just happy when found this 8) --ANK"
2385 * likewise MSDN says that lpFrom and lpFromlen are ignored for
2386 * connection-oriented sockets, so don't try to update lpFrom.
2388 if (wsa->addr && hdr.msg_namelen)
2389 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
2391 return n;
2394 /***********************************************************************
2395 * WS2_async_recv (INTERNAL)
2397 * Handler for overlapped recv() operations.
2399 static NTSTATUS WS2_async_recv( void *user, IO_STATUS_BLOCK *iosb,
2400 NTSTATUS status, void **apc, void **arg )
2402 struct ws2_async *wsa = user;
2403 int result = 0, fd;
2405 switch (status)
2407 case STATUS_ALERTED:
2408 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
2409 break;
2411 result = WS2_recv( fd, wsa, convert_flags(wsa->flags) );
2412 wine_server_release_fd( wsa->hSocket, fd );
2413 if (result >= 0)
2415 status = STATUS_SUCCESS;
2416 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
2418 else
2420 if (errno == EAGAIN)
2422 status = STATUS_PENDING;
2423 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
2425 else
2427 result = 0;
2428 status = wsaErrStatus();
2431 break;
2433 if (status != STATUS_PENDING)
2435 iosb->u.Status = status;
2436 iosb->Information = result;
2437 if (wsa->completion_func)
2439 *apc = ws2_async_apc;
2440 *arg = wsa;
2442 else
2443 release_async_io( &wsa->io );
2445 return status;
2448 /***********************************************************************
2449 * WS2_async_accept_recv (INTERNAL)
2451 * This function is used to finish the read part of an accept request. It is
2452 * needed to place the completion on the correct socket (listener).
2454 static NTSTATUS WS2_async_accept_recv( void *user, IO_STATUS_BLOCK *iosb,
2455 NTSTATUS status, void **apc, void **arg )
2457 void *junk;
2458 struct ws2_accept_async *wsa = user;
2460 status = WS2_async_recv( wsa->read, iosb, status, &junk, &junk );
2461 if (status == STATUS_PENDING)
2462 return status;
2464 if (wsa->cvalue)
2465 WS_AddCompletion( HANDLE2SOCKET(wsa->listen_socket), wsa->cvalue, iosb->u.Status, iosb->Information );
2467 release_async_io( &wsa->io );
2468 return status;
2471 /***********************************************************************
2472 * WS2_async_accept (INTERNAL)
2474 * This is the function called to satisfy the AcceptEx callback
2476 static NTSTATUS WS2_async_accept( void *user, IO_STATUS_BLOCK *iosb,
2477 NTSTATUS status, void **apc, void **arg )
2479 struct ws2_accept_async *wsa = user;
2480 int len;
2481 char *addr;
2483 TRACE("status: 0x%x listen: %p, accept: %p\n", status, wsa->listen_socket, wsa->accept_socket);
2485 if (status == STATUS_ALERTED)
2487 SERVER_START_REQ( accept_into_socket )
2489 req->lhandle = wine_server_obj_handle( wsa->listen_socket );
2490 req->ahandle = wine_server_obj_handle( wsa->accept_socket );
2491 status = wine_server_call( req );
2493 SERVER_END_REQ;
2495 if (status == STATUS_CANT_WAIT)
2496 return STATUS_PENDING;
2498 if (status == STATUS_INVALID_HANDLE)
2500 FIXME("AcceptEx accepting socket closed but request was not cancelled\n");
2501 status = STATUS_CANCELLED;
2504 else if (status == STATUS_HANDLES_CLOSED)
2505 status = STATUS_CANCELLED; /* strange windows behavior */
2507 if (status != STATUS_SUCCESS)
2508 goto finish;
2510 /* WS2 Spec says size param is extra 16 bytes long...what do we put in it? */
2511 addr = ((char *)wsa->buf) + wsa->data_len;
2512 len = wsa->local_len - sizeof(int);
2513 WS_getsockname(HANDLE2SOCKET(wsa->accept_socket),
2514 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
2515 *(int *)addr = len;
2517 addr += wsa->local_len;
2518 len = wsa->remote_len - sizeof(int);
2519 WS_getpeername(HANDLE2SOCKET(wsa->accept_socket),
2520 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
2521 *(int *)addr = len;
2523 if (!wsa->read)
2524 goto finish;
2526 status = register_async( ASYNC_TYPE_READ, wsa->accept_socket, WS2_async_accept_recv, wsa,
2527 wsa->user_overlapped->hEvent, NULL, NULL, iosb);
2529 if (status != STATUS_PENDING)
2530 goto finish;
2532 /* The APC has finished but no completion should be sent for the operation yet, additional processing
2533 * needs to be performed by WS2_async_accept_recv() first. */
2534 return STATUS_MORE_PROCESSING_REQUIRED;
2536 finish:
2537 iosb->u.Status = status;
2538 iosb->Information = 0;
2540 if (wsa->read) release_async_io( &wsa->read->io );
2541 release_async_io( &wsa->io );
2542 return status;
2545 /***********************************************************************
2546 * WS2_send (INTERNAL)
2548 * Workhorse for both synchronous and asynchronous send() operations.
2550 static int WS2_send( int fd, struct ws2_async *wsa, int flags )
2552 struct msghdr hdr;
2553 union generic_unix_sockaddr unix_addr;
2554 int n, ret;
2556 hdr.msg_name = NULL;
2557 hdr.msg_namelen = 0;
2559 if (wsa->addr)
2561 hdr.msg_name = &unix_addr;
2562 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
2563 if ( !hdr.msg_namelen )
2565 errno = EFAULT;
2566 return -1;
2569 #if defined(HAS_IPX) && defined(SOL_IPX)
2570 if(wsa->addr->sa_family == WS_AF_IPX)
2572 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
2573 int val=0;
2574 socklen_t len = sizeof(int);
2576 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
2577 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
2578 * the packet type and then we can retrieve it using getsockopt. After that we can set the
2579 * ipx type in the sockaddr_opx structure with the stored value.
2581 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
2582 uipx->sipx_type = val;
2584 #endif
2587 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
2588 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
2589 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2590 hdr.msg_accrights = NULL;
2591 hdr.msg_accrightslen = 0;
2592 #else
2593 hdr.msg_control = NULL;
2594 hdr.msg_controllen = 0;
2595 hdr.msg_flags = 0;
2596 #endif
2598 while ((ret = sendmsg(fd, &hdr, flags)) == -1)
2600 if (errno != EINTR)
2601 return -1;
2604 n = ret;
2605 while (wsa->first_iovec < wsa->n_iovecs && wsa->iovec[wsa->first_iovec].iov_len <= n)
2606 n -= wsa->iovec[wsa->first_iovec++].iov_len;
2607 if (wsa->first_iovec < wsa->n_iovecs)
2609 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
2610 wsa->iovec[wsa->first_iovec].iov_len -= n;
2612 return ret;
2615 /***********************************************************************
2616 * WS2_async_send (INTERNAL)
2618 * Handler for overlapped send() operations.
2620 static NTSTATUS WS2_async_send( void *user, IO_STATUS_BLOCK *iosb,
2621 NTSTATUS status, void **apc, void **arg )
2623 struct ws2_async *wsa = user;
2624 int result = 0, fd;
2626 switch (status)
2628 case STATUS_ALERTED:
2629 if ( wsa->n_iovecs <= wsa->first_iovec )
2631 /* Nothing to do */
2632 status = STATUS_SUCCESS;
2633 break;
2635 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
2636 break;
2638 /* check to see if the data is ready (non-blocking) */
2639 result = WS2_send( fd, wsa, convert_flags(wsa->flags) );
2640 wine_server_release_fd( wsa->hSocket, fd );
2642 if (result >= 0)
2644 if (wsa->first_iovec < wsa->n_iovecs)
2645 status = STATUS_PENDING;
2646 else
2647 status = STATUS_SUCCESS;
2649 iosb->Information += result;
2651 else if (errno == EAGAIN)
2653 status = STATUS_PENDING;
2655 else
2657 status = wsaErrStatus();
2659 break;
2661 if (status != STATUS_PENDING)
2663 iosb->u.Status = status;
2664 if (wsa->completion_func)
2666 *apc = ws2_async_apc;
2667 *arg = wsa;
2669 else
2670 release_async_io( &wsa->io );
2672 return status;
2675 /***********************************************************************
2676 * WS2_async_shutdown (INTERNAL)
2678 * Handler for shutdown() operations on overlapped sockets.
2680 static NTSTATUS WS2_async_shutdown( void *user, IO_STATUS_BLOCK *iosb,
2681 NTSTATUS status, void **apc, void **arg )
2683 struct ws2_async_shutdown *wsa = user;
2684 int fd, err = 1;
2686 switch (status)
2688 case STATUS_ALERTED:
2689 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
2690 break;
2692 switch ( wsa->type )
2694 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
2695 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
2697 status = err ? wsaErrStatus() : STATUS_SUCCESS;
2698 wine_server_release_fd( wsa->hSocket, fd );
2699 break;
2701 iosb->u.Status = status;
2702 iosb->Information = 0;
2703 release_async_io( &wsa->io );
2704 return status;
2707 /***********************************************************************
2708 * WS2_register_async_shutdown (INTERNAL)
2710 * Helper function for WS_shutdown() on overlapped sockets.
2712 static int WS2_register_async_shutdown( SOCKET s, int type )
2714 struct ws2_async_shutdown *wsa;
2715 NTSTATUS status;
2717 TRACE("socket %04lx type %d\n", s, type);
2719 wsa = (struct ws2_async_shutdown *)alloc_async_io( sizeof(*wsa) );
2720 if ( !wsa )
2721 return WSAEFAULT;
2723 wsa->hSocket = SOCKET2HANDLE(s);
2724 wsa->type = type;
2726 status = register_async( type, wsa->hSocket, WS2_async_shutdown, wsa, 0, NULL, NULL, &wsa->iosb );
2727 if (status != STATUS_PENDING)
2729 HeapFree( GetProcessHeap(), 0, wsa );
2730 return NtStatusToWSAError( status );
2732 return 0;
2735 /***********************************************************************
2736 * accept (WS2_32.1)
2738 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr, int *addrlen32)
2740 NTSTATUS status;
2741 SOCKET as;
2742 BOOL is_blocking;
2744 TRACE("socket %04lx\n", s );
2745 status = _is_blocking(s, &is_blocking);
2746 if (status)
2747 goto error;
2749 do {
2750 /* try accepting first (if there is a deferred connection) */
2751 SERVER_START_REQ( accept_socket )
2753 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
2754 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
2755 req->attributes = OBJ_INHERIT;
2756 status = wine_server_call( req );
2757 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
2759 SERVER_END_REQ;
2760 if (!status)
2762 if (addr && addrlen32 && WS_getpeername(as, addr, addrlen32))
2764 WS_closesocket(as);
2765 return SOCKET_ERROR;
2767 TRACE("\taccepted %04lx\n", as);
2768 return as;
2770 if (is_blocking && status == STATUS_CANT_WAIT)
2772 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2773 /* block here */
2774 do_block(fd, POLLIN, -1);
2775 _sync_sock_state(s); /* let wineserver notice connection */
2776 release_sock_fd( s, fd );
2778 } while (is_blocking && status == STATUS_CANT_WAIT);
2780 error:
2781 set_error(status);
2782 WARN(" -> ERROR %d\n", GetLastError());
2783 return INVALID_SOCKET;
2786 /***********************************************************************
2787 * AcceptEx
2789 static BOOL WINAPI WS2_AcceptEx(SOCKET listener, SOCKET acceptor, PVOID dest, DWORD dest_len,
2790 DWORD local_addr_len, DWORD rem_addr_len, LPDWORD received,
2791 LPOVERLAPPED overlapped)
2793 DWORD status;
2794 struct ws2_accept_async *wsa;
2795 int fd;
2797 TRACE("(%04lx, %04lx, %p, %d, %d, %d, %p, %p)\n", listener, acceptor, dest, dest_len, local_addr_len,
2798 rem_addr_len, received, overlapped);
2800 if (!dest)
2802 SetLastError(WSAEINVAL);
2803 return FALSE;
2806 if (!overlapped)
2808 SetLastError(WSA_INVALID_PARAMETER);
2809 return FALSE;
2812 if (!rem_addr_len)
2814 SetLastError(WSAEFAULT);
2815 return FALSE;
2818 fd = get_sock_fd( listener, FILE_READ_DATA, NULL );
2819 if (fd == -1)
2821 SetLastError(WSAENOTSOCK);
2822 return FALSE;
2824 release_sock_fd( listener, fd );
2826 fd = get_sock_fd( acceptor, FILE_READ_DATA, NULL );
2827 if (fd == -1)
2829 SetLastError(WSAENOTSOCK);
2830 return FALSE;
2832 release_sock_fd( acceptor, fd );
2834 wsa = (struct ws2_accept_async *)alloc_async_io( sizeof(*wsa) );
2835 if(!wsa)
2837 SetLastError(WSAEFAULT);
2838 return FALSE;
2841 wsa->listen_socket = SOCKET2HANDLE(listener);
2842 wsa->accept_socket = SOCKET2HANDLE(acceptor);
2843 wsa->user_overlapped = overlapped;
2844 wsa->cvalue = !((ULONG_PTR)overlapped->hEvent & 1) ? (ULONG_PTR)overlapped : 0;
2845 wsa->buf = dest;
2846 wsa->data_len = dest_len;
2847 wsa->local_len = local_addr_len;
2848 wsa->remote_len = rem_addr_len;
2849 wsa->read = NULL;
2851 if (wsa->data_len)
2853 /* set up a read request if we need it */
2854 wsa->read = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[1]) );
2855 if (!wsa->read)
2857 HeapFree( GetProcessHeap(), 0, wsa );
2858 SetLastError(WSAEFAULT);
2859 return FALSE;
2862 wsa->read->hSocket = wsa->accept_socket;
2863 wsa->read->flags = 0;
2864 wsa->read->lpFlags = &wsa->read->flags;
2865 wsa->read->addr = NULL;
2866 wsa->read->addrlen.ptr = NULL;
2867 wsa->read->control = NULL;
2868 wsa->read->n_iovecs = 1;
2869 wsa->read->first_iovec = 0;
2870 wsa->read->completion_func = NULL;
2871 wsa->read->iovec[0].iov_base = wsa->buf;
2872 wsa->read->iovec[0].iov_len = wsa->data_len;
2875 status = register_async( ASYNC_TYPE_READ, SOCKET2HANDLE(listener), WS2_async_accept, wsa,
2876 overlapped->hEvent, NULL, (void *)wsa->cvalue, (IO_STATUS_BLOCK *)overlapped );
2878 if(status != STATUS_PENDING)
2880 HeapFree( GetProcessHeap(), 0, wsa->read );
2881 HeapFree( GetProcessHeap(), 0, wsa );
2884 SetLastError( NtStatusToWSAError(status) );
2885 return FALSE;
2888 /***********************************************************************
2889 * WS2_ReadFile (INTERNAL)
2891 * Perform an APC-safe ReadFile operation
2893 static NTSTATUS WS2_ReadFile(HANDLE hFile, PIO_STATUS_BLOCK io_status, char* buffer, ULONG length,
2894 PLARGE_INTEGER offset)
2896 int result = -1, unix_handle;
2897 unsigned int options;
2898 NTSTATUS status;
2900 TRACE( "(%p,%p,0x%08x)\n", hFile, buffer,length );
2902 status = wine_server_handle_to_fd( hFile, FILE_READ_DATA, &unix_handle, &options );
2903 if (status) return status;
2905 while (result == -1)
2907 if (offset->QuadPart != FILE_USE_FILE_POINTER_POSITION)
2908 result = pread( unix_handle, buffer, length, offset->QuadPart );
2909 else
2910 result = read( unix_handle, buffer, length );
2911 if (errno != EINTR)
2912 break;
2915 if (!result)
2916 status = (length ? STATUS_END_OF_FILE : STATUS_SUCCESS);
2917 else if (result != -1)
2918 status = STATUS_SUCCESS;
2919 else if (errno != EAGAIN)
2920 status = wsaErrStatus();
2921 else
2922 status = STATUS_PENDING;
2924 wine_server_release_fd( hFile, unix_handle );
2925 TRACE("= 0x%08x (%d)\n", status, result);
2926 if (status == STATUS_SUCCESS || status == STATUS_END_OF_FILE)
2928 io_status->u.Status = status;
2929 io_status->Information = result;
2932 return status;
2935 /***********************************************************************
2936 * WS2_transmitfile_getbuffer (INTERNAL)
2938 * Pick the appropriate buffer for a TransmitFile send operation.
2940 static NTSTATUS WS2_transmitfile_getbuffer( int fd, struct ws2_transmitfile_async *wsa )
2942 /* send any incomplete writes from a previous iteration */
2943 if (wsa->write.first_iovec < wsa->write.n_iovecs)
2944 return STATUS_PENDING;
2946 /* process the header (if applicable) */
2947 if (wsa->buffers.Head)
2949 wsa->write.first_iovec = 0;
2950 wsa->write.n_iovecs = 1;
2951 wsa->write.iovec[0].iov_base = wsa->buffers.Head;
2952 wsa->write.iovec[0].iov_len = wsa->buffers.HeadLength;
2953 wsa->buffers.Head = NULL;
2954 return STATUS_PENDING;
2957 /* process the main file */
2958 if (wsa->file)
2960 DWORD bytes_per_send = wsa->bytes_per_send;
2961 IO_STATUS_BLOCK iosb;
2962 NTSTATUS status;
2964 iosb.Information = 0;
2965 /* when the size of the transfer is limited ensure that we don't go past that limit */
2966 if (wsa->file_bytes != 0)
2967 bytes_per_send = min(bytes_per_send, wsa->file_bytes - wsa->file_read);
2968 status = WS2_ReadFile( wsa->file, &iosb, wsa->buffer, bytes_per_send, &wsa->offset );
2969 if (wsa->offset.QuadPart != FILE_USE_FILE_POINTER_POSITION)
2970 wsa->offset.QuadPart += iosb.Information;
2971 if (status == STATUS_END_OF_FILE)
2972 wsa->file = NULL; /* continue on to the footer */
2973 else if (status != STATUS_SUCCESS)
2974 return status;
2975 else
2977 if (iosb.Information)
2979 wsa->write.first_iovec = 0;
2980 wsa->write.n_iovecs = 1;
2981 wsa->write.iovec[0].iov_base = wsa->buffer;
2982 wsa->write.iovec[0].iov_len = iosb.Information;
2983 wsa->file_read += iosb.Information;
2986 if (wsa->file_bytes != 0 && wsa->file_read >= wsa->file_bytes)
2987 wsa->file = NULL;
2989 return STATUS_PENDING;
2993 /* send the footer (if applicable) */
2994 if (wsa->buffers.Tail)
2996 wsa->write.first_iovec = 0;
2997 wsa->write.n_iovecs = 1;
2998 wsa->write.iovec[0].iov_base = wsa->buffers.Tail;
2999 wsa->write.iovec[0].iov_len = wsa->buffers.TailLength;
3000 wsa->buffers.Tail = NULL;
3001 return STATUS_PENDING;
3004 return STATUS_SUCCESS;
3007 /***********************************************************************
3008 * WS2_transmitfile_base (INTERNAL)
3010 * Shared implementation for both synchronous and asynchronous TransmitFile.
3012 static NTSTATUS WS2_transmitfile_base( int fd, struct ws2_transmitfile_async *wsa )
3014 NTSTATUS status;
3016 status = WS2_transmitfile_getbuffer( fd, wsa );
3017 if (status == STATUS_PENDING)
3019 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)wsa->write.user_overlapped;
3020 int n;
3022 n = WS2_send( fd, &wsa->write, convert_flags(wsa->write.flags) );
3023 if (n >= 0)
3025 if (iosb) iosb->Information += n;
3027 else if (errno != EAGAIN)
3028 return wsaErrStatus();
3031 return status;
3034 /***********************************************************************
3035 * WS2_async_transmitfile (INTERNAL)
3037 * Asynchronous callback for overlapped TransmitFile operations.
3039 static NTSTATUS WS2_async_transmitfile( void *user, IO_STATUS_BLOCK *iosb,
3040 NTSTATUS status, void **apc, void **arg )
3042 struct ws2_transmitfile_async *wsa = user;
3043 int fd;
3045 if (status == STATUS_ALERTED)
3047 if (!(status = wine_server_handle_to_fd( wsa->write.hSocket, FILE_WRITE_DATA, &fd, NULL )))
3049 status = WS2_transmitfile_base( fd, wsa );
3050 wine_server_release_fd( wsa->write.hSocket, fd );
3052 if (status == STATUS_PENDING)
3053 return status;
3056 iosb->u.Status = status;
3057 release_async_io( &wsa->io );
3058 return status;
3061 /***********************************************************************
3062 * TransmitFile
3064 static BOOL WINAPI WS2_TransmitFile( SOCKET s, HANDLE h, DWORD file_bytes, DWORD bytes_per_send,
3065 LPOVERLAPPED overlapped, LPTRANSMIT_FILE_BUFFERS buffers,
3066 DWORD flags )
3068 union generic_unix_sockaddr uaddr;
3069 unsigned int uaddrlen = sizeof(uaddr);
3070 struct ws2_transmitfile_async *wsa;
3071 NTSTATUS status;
3072 int fd;
3074 TRACE("(%lx, %p, %d, %d, %p, %p, %d)\n", s, h, file_bytes, bytes_per_send, overlapped,
3075 buffers, flags );
3077 fd = get_sock_fd( s, FILE_WRITE_DATA, NULL );
3078 if (fd == -1)
3080 WSASetLastError( WSAENOTSOCK );
3081 return FALSE;
3083 if (getpeername( fd, &uaddr.addr, &uaddrlen ) != 0)
3085 release_sock_fd( s, fd );
3086 WSASetLastError( WSAENOTCONN );
3087 return FALSE;
3089 if (flags)
3090 FIXME("Flags are not currently supported (0x%x).\n", flags);
3092 if (h && GetFileType( h ) != FILE_TYPE_DISK)
3094 FIXME("Non-disk file handles are not currently supported.\n");
3095 release_sock_fd( s, fd );
3096 WSASetLastError( WSAEOPNOTSUPP );
3097 return FALSE;
3100 /* set reasonable defaults when requested */
3101 if (!bytes_per_send)
3102 bytes_per_send = (1 << 16); /* Depends on OS version: PAGE_SIZE, 2*PAGE_SIZE, or 2^16 */
3104 if (!(wsa = (struct ws2_transmitfile_async *)alloc_async_io( sizeof(*wsa) + bytes_per_send )))
3106 release_sock_fd( s, fd );
3107 WSASetLastError( WSAEFAULT );
3108 return FALSE;
3110 if (buffers)
3111 wsa->buffers = *buffers;
3112 else
3113 memset(&wsa->buffers, 0x0, sizeof(wsa->buffers));
3114 wsa->buffer = (char *)(wsa + 1);
3115 wsa->file = h;
3116 wsa->file_read = 0;
3117 wsa->file_bytes = file_bytes;
3118 wsa->bytes_per_send = bytes_per_send;
3119 wsa->flags = flags;
3120 wsa->offset.QuadPart = FILE_USE_FILE_POINTER_POSITION;
3121 wsa->write.hSocket = SOCKET2HANDLE(s);
3122 wsa->write.addr = NULL;
3123 wsa->write.addrlen.val = 0;
3124 wsa->write.flags = 0;
3125 wsa->write.lpFlags = &wsa->flags;
3126 wsa->write.control = NULL;
3127 wsa->write.n_iovecs = 0;
3128 wsa->write.first_iovec = 0;
3129 wsa->write.user_overlapped = overlapped;
3130 if (overlapped)
3132 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)overlapped;
3133 int status;
3135 wsa->offset.u.LowPart = overlapped->u.s.Offset;
3136 wsa->offset.u.HighPart = overlapped->u.s.OffsetHigh;
3137 iosb->u.Status = STATUS_PENDING;
3138 iosb->Information = 0;
3139 status = register_async( ASYNC_TYPE_WRITE, SOCKET2HANDLE(s), WS2_async_transmitfile, wsa,
3140 overlapped->hEvent, NULL, NULL, iosb );
3141 if(status != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
3142 release_sock_fd( s, fd );
3143 WSASetLastError( NtStatusToWSAError(status) );
3144 return FALSE;
3149 status = WS2_transmitfile_base( fd, wsa );
3150 if (status == STATUS_PENDING)
3152 /* block here */
3153 do_block(fd, POLLOUT, -1);
3154 _sync_sock_state(s); /* let wineserver notice connection */
3157 while (status == STATUS_PENDING);
3158 release_sock_fd( s, fd );
3160 if (status != STATUS_SUCCESS)
3161 WSASetLastError( NtStatusToWSAError(status) );
3162 HeapFree( GetProcessHeap(), 0, wsa );
3163 return (status == STATUS_SUCCESS);
3166 /***********************************************************************
3167 * GetAcceptExSockaddrs
3169 static void WINAPI WS2_GetAcceptExSockaddrs(PVOID buffer, DWORD data_size, DWORD local_size, DWORD remote_size,
3170 struct WS_sockaddr **local_addr, LPINT local_addr_len,
3171 struct WS_sockaddr **remote_addr, LPINT remote_addr_len)
3173 char *cbuf = buffer;
3174 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer, data_size, local_size, remote_size, local_addr,
3175 local_addr_len, remote_addr, remote_addr_len );
3176 cbuf += data_size;
3178 *local_addr_len = *(int *) cbuf;
3179 *local_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
3181 cbuf += local_size;
3183 *remote_addr_len = *(int *) cbuf;
3184 *remote_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
3187 /***********************************************************************
3188 * WSASendMsg
3190 int WINAPI WSASendMsg( SOCKET s, LPWSAMSG msg, DWORD dwFlags, LPDWORD lpNumberOfBytesSent,
3191 LPWSAOVERLAPPED lpOverlapped,
3192 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
3194 if (!msg)
3196 SetLastError( WSAEFAULT );
3197 return SOCKET_ERROR;
3200 return WS2_sendto( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesSent,
3201 dwFlags, msg->name, msg->namelen,
3202 lpOverlapped, lpCompletionRoutine );
3205 /***********************************************************************
3206 * WSARecvMsg
3208 * Perform a receive operation that is capable of returning message
3209 * control headers. It is important to note that the WSAMSG parameter
3210 * must remain valid throughout the operation, even when an overlapped
3211 * receive is performed.
3213 static int WINAPI WS2_WSARecvMsg( SOCKET s, LPWSAMSG msg, LPDWORD lpNumberOfBytesRecvd,
3214 LPWSAOVERLAPPED lpOverlapped,
3215 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3217 if (!msg)
3219 SetLastError( WSAEFAULT );
3220 return SOCKET_ERROR;
3223 return WS2_recv_base( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesRecvd,
3224 &msg->dwFlags, msg->name, &msg->namelen,
3225 lpOverlapped, lpCompletionRoutine, &msg->Control );
3228 /***********************************************************************
3229 * interface_bind (INTERNAL)
3231 * Take bind() calls on any name corresponding to a local network adapter and restrict the given socket to
3232 * operating only on the specified interface. This restriction consists of two components:
3233 * 1) An outgoing packet restriction suggesting the egress interface for all packets.
3234 * 2) An incoming packet restriction dropping packets not meant for the interface.
3235 * If the function succeeds in placing these restrictions (returns TRUE) then the name for the bind() may
3236 * safely be changed to INADDR_ANY, permitting the transmission and receipt of broadcast packets on the
3237 * socket. This behavior is only relevant to UDP sockets and is needed for applications that expect to be able
3238 * to receive broadcast packets on a socket that is bound to a specific network interface.
3240 static BOOL interface_bind( SOCKET s, int fd, struct sockaddr *addr )
3242 struct sockaddr_in *in_sock = (struct sockaddr_in *) addr;
3243 in_addr_t bind_addr = in_sock->sin_addr.s_addr;
3244 PIP_ADAPTER_INFO adapters = NULL, adapter;
3245 BOOL ret = FALSE;
3246 DWORD adap_size;
3247 int enable = 1;
3249 if (bind_addr == htonl(INADDR_ANY) || bind_addr == htonl(INADDR_LOOPBACK))
3250 return FALSE; /* Not binding to a network adapter, special interface binding unnecessary. */
3251 if (_get_fd_type(fd) != SOCK_DGRAM)
3252 return FALSE; /* Special interface binding is only necessary for UDP datagrams. */
3253 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
3254 goto cleanup;
3255 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
3256 if (adapters == NULL || GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
3257 goto cleanup;
3258 /* Search the IPv4 adapter list for the appropriate binding interface */
3259 for (adapter = adapters; adapter != NULL; adapter = adapter->Next)
3261 in_addr_t adapter_addr = (in_addr_t) inet_addr(adapter->IpAddressList.IpAddress.String);
3263 if (bind_addr == adapter_addr)
3265 #if defined(IP_BOUND_IF)
3266 /* IP_BOUND_IF sets both the incoming and outgoing restriction at once */
3267 if (setsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &adapter->Index, sizeof(adapter->Index)) != 0)
3268 goto cleanup;
3269 ret = TRUE;
3270 #elif defined(LINUX_BOUND_IF)
3271 in_addr_t ifindex = (in_addr_t) htonl(adapter->Index);
3272 struct interface_filter specific_interface_filter;
3273 struct sock_fprog filter_prog;
3275 if (setsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex, sizeof(ifindex)) != 0)
3276 goto cleanup; /* Failed to suggest egress interface */
3277 specific_interface_filter = generic_interface_filter;
3278 specific_interface_filter.iface_rule.k = adapter->Index;
3279 specific_interface_filter.ip_rule.k = htonl(adapter_addr);
3280 filter_prog.len = sizeof(generic_interface_filter)/sizeof(struct sock_filter);
3281 filter_prog.filter = (struct sock_filter *) &specific_interface_filter;
3282 if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog, sizeof(filter_prog)) != 0)
3283 goto cleanup; /* Failed to specify incoming packet filter */
3284 ret = TRUE;
3285 #else
3286 FIXME("Broadcast packets on interface-bound sockets are not currently supported on this platform, "
3287 "receiving broadcast packets will not work on socket %04lx.\n", s);
3288 #endif
3289 break;
3292 /* Will soon be switching to INADDR_ANY: permit address reuse */
3293 if (ret && setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) == 0)
3294 TRACE("Socket %04lx bound to interface index %d\n", s, adapter->Index);
3295 else
3296 ret = FALSE;
3298 cleanup:
3299 if(!ret)
3300 ERR("Failed to bind to interface, receiving broadcast packets will not work on socket %04lx.\n", s);
3301 HeapFree(GetProcessHeap(), 0, adapters);
3302 return ret;
3305 /***********************************************************************
3306 * bind (WS2_32.2)
3308 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
3310 int fd = get_sock_fd( s, 0, NULL );
3311 int res = SOCKET_ERROR;
3313 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
3315 if (fd != -1)
3317 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
3319 SetLastError(WSAEAFNOSUPPORT);
3321 else
3323 union generic_unix_sockaddr uaddr;
3324 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
3325 if (!uaddrlen)
3327 SetLastError(WSAEFAULT);
3329 else
3331 if (name->sa_family == WS_AF_INET)
3333 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
3334 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
3336 /* Trying to bind to the default host interface, using
3337 * INADDR_ANY instead*/
3338 WARN("Trying to bind to magic IP address, using "
3339 "INADDR_ANY instead.\n");
3340 in4->sin_addr.s_addr = htonl(INADDR_ANY);
3342 else if (interface_bind(s, fd, &uaddr.addr))
3343 in4->sin_addr.s_addr = htonl(INADDR_ANY);
3345 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
3347 int loc_errno = errno;
3348 WARN("\tfailure - errno = %i\n", errno);
3349 errno = loc_errno;
3350 switch (errno)
3352 case EADDRNOTAVAIL:
3353 SetLastError(WSAEINVAL);
3354 break;
3355 case EADDRINUSE:
3357 int optval = 0;
3358 socklen_t optlen = sizeof(optval);
3359 /* Windows >= 2003 will return different results depending on
3360 * SO_REUSEADDR, WSAEACCES may be returned representing that
3361 * the socket hijacking protection prevented the bind */
3362 if (!getsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&optval, &optlen) && optval)
3364 SetLastError(WSAEACCES);
3365 break;
3367 /* fall through */
3369 default:
3370 SetLastError(wsaErrno());
3371 break;
3374 else
3376 res=0; /* success */
3380 release_sock_fd( s, fd );
3382 return res;
3385 /***********************************************************************
3386 * closesocket (WS2_32.3)
3388 int WINAPI WS_closesocket(SOCKET s)
3390 int res = SOCKET_ERROR, fd;
3391 if (num_startup)
3393 fd = get_sock_fd(s, FILE_READ_DATA, NULL);
3394 if (fd >= 0)
3396 release_sock_fd(s, fd);
3397 if (CloseHandle(SOCKET2HANDLE(s)))
3398 res = 0;
3400 else
3401 SetLastError(WSAENOTSOCK);
3403 else
3404 SetLastError(WSANOTINITIALISED);
3405 TRACE("(socket %04lx) -> %d\n", s, res);
3406 return res;
3409 static int do_connect(int fd, const struct WS_sockaddr* name, int namelen)
3411 union generic_unix_sockaddr uaddr;
3412 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
3414 if (!uaddrlen)
3415 return WSAEFAULT;
3417 if (name->sa_family == WS_AF_INET)
3419 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
3420 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
3422 /* Trying to connect to magic replace-loopback address,
3423 * assuming we really want to connect to localhost */
3424 TRACE("Trying to connect to magic IP address, using "
3425 "INADDR_LOOPBACK instead.\n");
3426 in4->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
3430 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
3431 return 0;
3433 return wsaErrno();
3436 /***********************************************************************
3437 * connect (WS2_32.4)
3439 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
3441 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
3443 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
3445 if (fd != -1)
3447 NTSTATUS status;
3448 BOOL is_blocking;
3449 int ret = do_connect(fd, name, namelen);
3450 if (ret == 0)
3451 goto connect_success;
3453 if (ret == WSAEINPROGRESS)
3455 /* tell wineserver that a connection is in progress */
3456 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3457 FD_CONNECT,
3458 FD_WINE_CONNECTED|FD_WINE_LISTENING);
3459 status = _is_blocking( s, &is_blocking );
3460 if (status)
3462 release_sock_fd( s, fd );
3463 set_error( status );
3464 return SOCKET_ERROR;
3466 if (is_blocking)
3468 int result;
3469 /* block here */
3470 do_block(fd, POLLIN | POLLOUT, -1);
3471 _sync_sock_state(s); /* let wineserver notice connection */
3472 /* retrieve any error codes from it */
3473 result = _get_sock_error(s, FD_CONNECT_BIT);
3474 if (result)
3475 SetLastError(NtStatusToWSAError(result));
3476 else
3478 goto connect_success;
3481 else
3483 SetLastError(WSAEWOULDBLOCK);
3486 else
3488 SetLastError(ret);
3490 release_sock_fd( s, fd );
3492 return SOCKET_ERROR;
3494 connect_success:
3495 release_sock_fd( s, fd );
3496 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3497 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
3498 FD_CONNECT|FD_WINE_LISTENING);
3499 TRACE("\tconnected %04lx\n", s);
3500 return 0;
3503 /***********************************************************************
3504 * WSAConnect (WS2_32.30)
3506 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
3507 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
3508 LPQOS lpSQOS, LPQOS lpGQOS )
3510 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
3511 FIXME("unsupported parameters!\n");
3512 return WS_connect( s, name, namelen );
3515 /***********************************************************************
3516 * ConnectEx
3518 static BOOL WINAPI WS2_ConnectEx(SOCKET s, const struct WS_sockaddr* name, int namelen,
3519 PVOID sendBuf, DWORD sendBufLen, LPDWORD sent, LPOVERLAPPED ov)
3521 int fd, ret, status;
3523 if (!ov)
3525 SetLastError( ERROR_INVALID_PARAMETER );
3526 return FALSE;
3529 fd = get_sock_fd( s, FILE_READ_DATA, NULL );
3530 if (fd == -1)
3532 SetLastError( WSAENOTSOCK );
3533 return FALSE;
3536 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
3537 s, name, debugstr_sockaddr(name), namelen, sendBuf, sendBufLen, ov);
3539 ret = is_fd_bound(fd, NULL, NULL);
3540 if (ret <= 0)
3542 SetLastError(ret == -1 ? wsaErrno() : WSAEINVAL);
3543 release_sock_fd( s, fd );
3544 return FALSE;
3547 ret = do_connect(fd, name, namelen);
3548 if (ret == 0)
3550 WSABUF wsabuf;
3552 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3553 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
3554 FD_CONNECT|FD_WINE_LISTENING);
3556 wsabuf.len = sendBufLen;
3557 wsabuf.buf = (char*) sendBuf;
3559 /* WSASend takes care of completion if need be */
3560 if (WSASend(s, &wsabuf, sendBuf ? 1 : 0, sent, 0, ov, NULL) != SOCKET_ERROR)
3561 goto connection_success;
3563 else if (ret == WSAEINPROGRESS)
3565 struct ws2_async *wsa;
3566 ULONG_PTR cvalue = (((ULONG_PTR)ov->hEvent & 1) == 0) ? (ULONG_PTR)ov : 0;
3568 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3569 FD_CONNECT,
3570 FD_WINE_CONNECTED|FD_WINE_LISTENING);
3572 /* Indirectly call WSASend */
3573 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof( struct ws2_async, iovec[1] ))))
3575 SetLastError(WSAEFAULT);
3577 else
3579 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)ov;
3580 iosb->u.Status = STATUS_PENDING;
3581 iosb->Information = 0;
3583 wsa->hSocket = SOCKET2HANDLE(s);
3584 wsa->addr = NULL;
3585 wsa->addrlen.val = 0;
3586 wsa->flags = 0;
3587 wsa->lpFlags = &wsa->flags;
3588 wsa->control = NULL;
3589 wsa->n_iovecs = sendBuf ? 1 : 0;
3590 wsa->first_iovec = 0;
3591 wsa->completion_func = NULL;
3592 wsa->iovec[0].iov_base = sendBuf;
3593 wsa->iovec[0].iov_len = sendBufLen;
3595 status = register_async( ASYNC_TYPE_WRITE, wsa->hSocket, WS2_async_send, wsa, ov->hEvent,
3596 NULL, (void *)cvalue, iosb );
3597 if (status != STATUS_PENDING) HeapFree(GetProcessHeap(), 0, wsa);
3599 /* If the connect already failed */
3600 if (status == STATUS_PIPE_DISCONNECTED)
3601 status = _get_sock_error(s, FD_CONNECT_BIT);
3602 SetLastError( NtStatusToWSAError(status) );
3605 else
3607 SetLastError(ret);
3610 release_sock_fd( s, fd );
3611 return FALSE;
3613 connection_success:
3614 release_sock_fd( s, fd );
3615 return TRUE;
3618 /***********************************************************************
3619 * DisconnectEx
3621 static BOOL WINAPI WS2_DisconnectEx( SOCKET s, LPOVERLAPPED ov, DWORD flags, DWORD reserved )
3623 TRACE( "socket %04lx, ov %p, flags 0x%x, reserved 0x%x\n", s, ov, flags, reserved );
3625 if (flags & TF_REUSE_SOCKET)
3626 FIXME( "Reusing socket not supported yet\n" );
3628 if (ov)
3630 ov->Internal = STATUS_PENDING;
3631 ov->InternalHigh = 0;
3634 return !WS_shutdown( s, SD_BOTH );
3637 /***********************************************************************
3638 * getpeername (WS2_32.5)
3640 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
3642 int fd;
3643 int res;
3645 TRACE("socket %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
3647 fd = get_sock_fd( s, 0, NULL );
3648 res = SOCKET_ERROR;
3650 if (fd != -1)
3652 union generic_unix_sockaddr uaddr;
3653 socklen_t uaddrlen = sizeof(uaddr);
3655 if (getpeername(fd, &uaddr.addr, &uaddrlen) == 0)
3657 if (!name || !namelen)
3658 SetLastError(WSAEFAULT);
3659 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3660 /* The buffer was too small */
3661 SetLastError(WSAEFAULT);
3662 else
3664 res = 0;
3665 TRACE("=> %s\n", debugstr_sockaddr(name));
3668 else
3669 SetLastError(wsaErrno());
3670 release_sock_fd( s, fd );
3672 return res;
3675 /* When binding to an UDP address with filter support the getsockname call on the socket
3676 * will always return 0.0.0.0 instead of the filtered interface address. This function
3677 * checks if the socket is interface-bound on UDP and return the correct address.
3678 * This is required because applications often do a bind() with port zero followed by a
3679 * getsockname() to retrieve the port and address acquired.
3681 static void interface_bind_check(int fd, struct sockaddr_in *addr)
3683 #if !defined(IP_BOUND_IF) && !defined(LINUX_BOUND_IF)
3684 return;
3685 #else
3686 int ifindex;
3687 socklen_t len;
3689 /* Check for IPv4, address 0.0.0.0 and UDP socket */
3690 if (addr->sin_family != AF_INET || addr->sin_addr.s_addr != 0)
3691 return;
3692 if (_get_fd_type(fd) != SOCK_DGRAM)
3693 return;
3695 ifindex = -1;
3696 len = sizeof(ifindex);
3697 #if defined(IP_BOUND_IF)
3698 getsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &ifindex, &len);
3699 #elif defined(LINUX_BOUND_IF)
3700 getsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex, &len);
3701 if (ifindex > 0) ifindex = ntohl(ifindex);
3702 #endif
3703 if (ifindex > 0)
3705 PIP_ADAPTER_INFO adapters, adapter;
3706 DWORD adap_size;
3708 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
3709 return;
3710 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
3711 if (adapters && GetAdaptersInfo(adapters, &adap_size) == NO_ERROR)
3713 /* Search the IPv4 adapter list for the appropriate bound interface */
3714 for (adapter = adapters; adapter != NULL; adapter = adapter->Next)
3716 in_addr_t adapter_addr;
3717 if (adapter->Index != ifindex) continue;
3719 adapter_addr = inet_addr(adapter->IpAddressList.IpAddress.String);
3720 addr->sin_addr.s_addr = adapter_addr;
3721 TRACE("reporting interface address from adapter %d\n", ifindex);
3722 break;
3725 HeapFree(GetProcessHeap(), 0, adapters);
3727 #endif
3730 /***********************************************************************
3731 * getsockname (WS2_32.6)
3733 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
3735 int fd;
3736 int res;
3738 TRACE("socket %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
3740 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
3741 if( (name == NULL) || (namelen == NULL) )
3743 SetLastError( WSAEFAULT );
3744 return SOCKET_ERROR;
3747 fd = get_sock_fd( s, 0, NULL );
3748 res = SOCKET_ERROR;
3750 if (fd != -1)
3752 union generic_unix_sockaddr uaddr;
3753 socklen_t uaddrlen;
3754 int bound = is_fd_bound(fd, &uaddr, &uaddrlen);
3756 if (bound <= 0)
3758 SetLastError(bound == -1 ? wsaErrno() : WSAEINVAL);
3760 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3762 /* The buffer was too small */
3763 SetLastError(WSAEFAULT);
3765 else
3767 interface_bind_check(fd, (struct sockaddr_in*) &uaddr);
3768 if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3770 /* The buffer was too small */
3771 SetLastError(WSAEFAULT);
3773 else
3775 res = 0;
3776 TRACE("=> %s\n", debugstr_sockaddr(name));
3779 release_sock_fd( s, fd );
3781 return res;
3784 /***********************************************************************
3785 * getsockopt (WS2_32.7)
3787 INT WINAPI WS_getsockopt(SOCKET s, INT level,
3788 INT optname, char *optval, INT *optlen)
3790 int fd;
3791 INT ret = 0;
3793 TRACE("(socket %04lx, %s, optval %s, optlen %p (%d))\n", s,
3794 debugstr_sockopt(level, optname), debugstr_optval(optval, 0),
3795 optlen, optlen ? *optlen : 0);
3797 switch(level)
3799 case WS_SOL_SOCKET:
3801 switch(optname)
3803 /* Handle common cases. The special cases are below, sorted
3804 * alphabetically */
3805 case WS_SO_BROADCAST:
3806 case WS_SO_DEBUG:
3807 case WS_SO_KEEPALIVE:
3808 case WS_SO_OOBINLINE:
3809 case WS_SO_RCVBUF:
3810 case WS_SO_REUSEADDR:
3811 case WS_SO_SNDBUF:
3812 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3813 return SOCKET_ERROR;
3814 convert_sockopt(&level, &optname);
3815 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3817 SetLastError(wsaErrno());
3818 ret = SOCKET_ERROR;
3820 release_sock_fd( s, fd );
3821 return ret;
3822 case WS_SO_ACCEPTCONN:
3823 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3824 return SOCKET_ERROR;
3825 if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, optval, (socklen_t *)optlen) != 0 )
3827 SetLastError(wsaErrno());
3828 ret = SOCKET_ERROR;
3830 else
3832 /* BSD returns != 0 while Windows return exact == 1 */
3833 if (*(int *)optval) *(int *)optval = 1;
3835 release_sock_fd( s, fd );
3836 return ret;
3837 case WS_SO_BSP_STATE:
3839 int req_size, addr_size;
3840 WSAPROTOCOL_INFOW infow;
3841 CSADDR_INFO *csinfo;
3843 ret = ws_protocol_info(s, TRUE, &infow, &addr_size);
3844 if (ret)
3846 if (infow.iAddressFamily == WS_AF_INET)
3847 addr_size = sizeof(struct sockaddr_in);
3848 else if (infow.iAddressFamily == WS_AF_INET6)
3849 addr_size = sizeof(struct sockaddr_in6);
3850 else
3852 FIXME("Family %d is unsupported for SO_BSP_STATE\n", infow.iAddressFamily);
3853 SetLastError(WSAEAFNOSUPPORT);
3854 return SOCKET_ERROR;
3857 req_size = sizeof(CSADDR_INFO) + addr_size * 2;
3858 if (*optlen < req_size)
3860 ret = 0;
3861 SetLastError(WSAEFAULT);
3863 else
3865 union generic_unix_sockaddr uaddr;
3866 socklen_t uaddrlen;
3868 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3869 return SOCKET_ERROR;
3871 csinfo = (CSADDR_INFO*) optval;
3873 /* Check if the sock is bound */
3874 if (is_fd_bound(fd, &uaddr, &uaddrlen) == 1)
3876 csinfo->LocalAddr.lpSockaddr =
3877 (LPSOCKADDR) (optval + sizeof(CSADDR_INFO));
3878 ws_sockaddr_u2ws(&uaddr.addr, csinfo->LocalAddr.lpSockaddr, &addr_size);
3879 csinfo->LocalAddr.iSockaddrLength = addr_size;
3881 else
3883 csinfo->LocalAddr.lpSockaddr = NULL;
3884 csinfo->LocalAddr.iSockaddrLength = 0;
3887 /* Check if the sock is connected */
3888 if (!getpeername(fd, &uaddr.addr, &uaddrlen) &&
3889 is_sockaddr_bound(&uaddr.addr, uaddrlen))
3891 csinfo->RemoteAddr.lpSockaddr =
3892 (LPSOCKADDR) (optval + sizeof(CSADDR_INFO) + addr_size);
3893 ws_sockaddr_u2ws(&uaddr.addr, csinfo->RemoteAddr.lpSockaddr, &addr_size);
3894 csinfo->RemoteAddr.iSockaddrLength = addr_size;
3896 else
3898 csinfo->RemoteAddr.lpSockaddr = NULL;
3899 csinfo->RemoteAddr.iSockaddrLength = 0;
3902 csinfo->iSocketType = infow.iSocketType;
3903 csinfo->iProtocol = infow.iProtocol;
3904 release_sock_fd( s, fd );
3907 return ret ? 0 : SOCKET_ERROR;
3909 case WS_SO_DONTLINGER:
3911 struct linger lingval;
3912 socklen_t len = sizeof(struct linger);
3914 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
3916 SetLastError(WSAEFAULT);
3917 return SOCKET_ERROR;
3919 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3920 return SOCKET_ERROR;
3922 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
3924 SetLastError(wsaErrno());
3925 ret = SOCKET_ERROR;
3927 else
3929 *(BOOL *)optval = !lingval.l_onoff;
3930 *optlen = sizeof(BOOL);
3933 release_sock_fd( s, fd );
3934 return ret;
3937 case WS_SO_CONNECT_TIME:
3939 static int pretendtime = 0;
3940 struct WS_sockaddr addr;
3941 int len = sizeof(addr);
3943 if (!optlen || *optlen < sizeof(DWORD) || !optval)
3945 SetLastError(WSAEFAULT);
3946 return SOCKET_ERROR;
3948 if (WS_getpeername(s, &addr, &len) == SOCKET_ERROR)
3949 *(DWORD *)optval = ~0u;
3950 else
3952 if (!pretendtime) FIXME("WS_SO_CONNECT_TIME - faking results\n");
3953 *(DWORD *)optval = pretendtime++;
3955 *optlen = sizeof(DWORD);
3956 return ret;
3958 /* As mentioned in setsockopt, Windows ignores this, so we
3959 * always return true here */
3960 case WS_SO_DONTROUTE:
3961 if (!optlen || *optlen < sizeof(BOOL) || !optval)
3963 SetLastError(WSAEFAULT);
3964 return SOCKET_ERROR;
3966 *(BOOL *)optval = TRUE;
3967 *optlen = sizeof(BOOL);
3968 return 0;
3970 case WS_SO_ERROR:
3972 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3973 return SOCKET_ERROR;
3974 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, optval, (socklen_t *)optlen) != 0 )
3976 SetLastError(wsaErrno());
3977 ret = SOCKET_ERROR;
3979 release_sock_fd( s, fd );
3981 /* The wineserver may have swallowed the error before us */
3982 if (!ret && *(int*) optval == 0)
3984 int i, events[FD_MAX_EVENTS];
3985 _get_sock_errors(s, events);
3986 for (i = 0; i < FD_MAX_EVENTS; i++)
3988 if(events[i])
3990 events[i] = NtStatusToWSAError(events[i]);
3991 TRACE("returning SO_ERROR %d from wine server\n", events[i]);
3992 *(int*) optval = events[i];
3993 break;
3997 return ret;
4000 case WS_SO_LINGER:
4002 struct linger lingval;
4003 socklen_t len = sizeof(struct linger);
4005 /* struct linger and LINGER have different sizes */
4006 if (!optlen || *optlen < sizeof(LINGER) || !optval)
4008 SetLastError(WSAEFAULT);
4009 return SOCKET_ERROR;
4011 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4012 return SOCKET_ERROR;
4014 if (_get_fd_type(fd) == SOCK_DGRAM)
4016 SetLastError(WSAENOPROTOOPT);
4017 ret = SOCKET_ERROR;
4019 else if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0)
4021 SetLastError(wsaErrno());
4022 ret = SOCKET_ERROR;
4024 else
4026 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
4027 ((LINGER *)optval)->l_linger = lingval.l_linger;
4028 *optlen = sizeof(struct linger);
4031 release_sock_fd( s, fd );
4032 return ret;
4035 case WS_SO_MAX_MSG_SIZE:
4036 if (!optlen || *optlen < sizeof(int) || !optval)
4038 SetLastError(WSAEFAULT);
4039 return SOCKET_ERROR;
4041 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
4042 *(int *)optval = 65507;
4043 *optlen = sizeof(int);
4044 return 0;
4046 /* SO_OPENTYPE does not require a valid socket handle. */
4047 case WS_SO_OPENTYPE:
4048 if (!optlen || *optlen < sizeof(int) || !optval)
4050 SetLastError(WSAEFAULT);
4051 return SOCKET_ERROR;
4053 *(int *)optval = get_per_thread_data()->opentype;
4054 *optlen = sizeof(int);
4055 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
4056 return 0;
4057 case WS_SO_PROTOCOL_INFOA:
4058 case WS_SO_PROTOCOL_INFOW:
4060 int size;
4061 WSAPROTOCOL_INFOW infow;
4063 ret = ws_protocol_info(s, optname == WS_SO_PROTOCOL_INFOW, &infow, &size);
4064 if (ret)
4066 if (!optlen || !optval || *optlen < size)
4068 if(optlen) *optlen = size;
4069 ret = 0;
4070 SetLastError(WSAEFAULT);
4072 else
4073 memcpy(optval, &infow, size);
4075 return ret ? 0 : SOCKET_ERROR;
4077 case WS_SO_RCVTIMEO:
4078 case WS_SO_SNDTIMEO:
4080 INT64 timeout;
4082 if (!optlen || *optlen < sizeof(int)|| !optval)
4084 SetLastError(WSAEFAULT);
4085 return SOCKET_ERROR;
4087 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4088 return SOCKET_ERROR;
4090 timeout = get_rcvsnd_timeo(fd, optname == WS_SO_RCVTIMEO);
4091 *(int *)optval = timeout <= UINT_MAX ? timeout : UINT_MAX;
4093 release_sock_fd( s, fd );
4094 return ret;
4096 case WS_SO_TYPE:
4098 int sock_type;
4099 if (!optlen || *optlen < sizeof(int) || !optval)
4101 SetLastError(WSAEFAULT);
4102 return SOCKET_ERROR;
4104 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4105 return SOCKET_ERROR;
4107 sock_type = _get_fd_type(fd);
4108 if (sock_type == -1)
4110 SetLastError(wsaErrno());
4111 ret = SOCKET_ERROR;
4113 else
4114 (*(int *)optval) = convert_socktype_u2w(sock_type);
4116 release_sock_fd( s, fd );
4117 return ret;
4119 default:
4120 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
4121 SetLastError(WSAENOPROTOOPT);
4122 return SOCKET_ERROR;
4123 } /* end switch(optname) */
4124 }/* end case WS_SOL_SOCKET */
4125 #ifdef HAS_IPX
4126 case WS_NSPROTO_IPX:
4128 struct WS_sockaddr_ipx addr;
4129 IPX_ADDRESS_DATA *data;
4130 int namelen;
4131 switch(optname)
4133 case WS_IPX_PTYPE:
4134 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
4135 #ifdef SOL_IPX
4136 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (socklen_t *)optlen) == -1)
4138 ret = SOCKET_ERROR;
4140 #else
4142 struct ipx val;
4143 socklen_t len=sizeof(struct ipx);
4144 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
4145 ret = SOCKET_ERROR;
4146 else
4147 *optval = (int)val.ipx_pt;
4149 #endif
4150 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
4151 release_sock_fd( s, fd );
4152 return ret;
4154 case WS_IPX_ADDRESS:
4156 * On a Win2000 system with one network card there are usually
4157 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
4158 * Using this call you can then retrieve info about this all.
4159 * In case of Linux it is a bit different. Usually you have
4160 * only "one" device active and further it is not possible to
4161 * query things like the linkspeed.
4163 FIXME("IPX_ADDRESS\n");
4164 namelen = sizeof(struct WS_sockaddr_ipx);
4165 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
4166 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
4168 data = (IPX_ADDRESS_DATA*)optval;
4169 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
4170 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
4171 data->adapternum = 0;
4172 data->wan = FALSE; /* We are not on a wan for now .. */
4173 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
4174 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
4175 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
4176 * note 1MB = 1000kB in this case */
4177 return 0;
4179 case WS_IPX_MAX_ADAPTER_NUM:
4180 FIXME("IPX_MAX_ADAPTER_NUM\n");
4181 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
4182 return 0;
4184 default:
4185 FIXME("IPX optname:%x\n", optname);
4186 return SOCKET_ERROR;
4187 }/* end switch(optname) */
4188 } /* end case WS_NSPROTO_IPX */
4189 #endif
4191 #ifdef HAS_IRDA
4192 #define MAX_IRDA_DEVICES 10
4194 case WS_SOL_IRLMP:
4195 switch(optname)
4197 case WS_IRLMP_ENUMDEVICES:
4199 char buf[sizeof(struct irda_device_list) +
4200 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
4201 int res;
4202 socklen_t len = sizeof(buf);
4204 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4205 return SOCKET_ERROR;
4206 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
4207 release_sock_fd( s, fd );
4208 if (res < 0)
4210 SetLastError(wsaErrno());
4211 return SOCKET_ERROR;
4213 else
4215 struct irda_device_list *src = (struct irda_device_list *)buf;
4216 DEVICELIST *dst = (DEVICELIST *)optval;
4217 INT needed = sizeof(DEVICELIST);
4218 unsigned int i;
4220 if (src->len > 0)
4221 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
4222 if (*optlen < needed)
4224 SetLastError(WSAEFAULT);
4225 return SOCKET_ERROR;
4227 *optlen = needed;
4228 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
4229 dst->numDevice = src->len;
4230 for (i = 0; i < src->len; i++)
4232 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
4233 src->dev[i].saddr, src->dev[i].daddr,
4234 src->dev[i].info, src->dev[i].hints[0],
4235 src->dev[i].hints[1]);
4236 memcpy( dst->Device[i].irdaDeviceID,
4237 &src->dev[i].daddr,
4238 sizeof(dst->Device[i].irdaDeviceID) ) ;
4239 memcpy( dst->Device[i].irdaDeviceName,
4240 src->dev[i].info,
4241 sizeof(dst->Device[i].irdaDeviceName) ) ;
4242 memcpy( &dst->Device[i].irdaDeviceHints1,
4243 &src->dev[i].hints[0],
4244 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
4245 memcpy( &dst->Device[i].irdaDeviceHints2,
4246 &src->dev[i].hints[1],
4247 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
4248 dst->Device[i].irdaCharSet = src->dev[i].charset;
4250 return 0;
4253 default:
4254 FIXME("IrDA optname:0x%x\n", optname);
4255 return SOCKET_ERROR;
4257 break; /* case WS_SOL_IRLMP */
4258 #undef MAX_IRDA_DEVICES
4259 #endif
4261 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
4262 case WS_IPPROTO_TCP:
4263 switch(optname)
4265 case WS_TCP_NODELAY:
4266 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4267 return SOCKET_ERROR;
4268 convert_sockopt(&level, &optname);
4269 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
4271 SetLastError(wsaErrno());
4272 ret = SOCKET_ERROR;
4274 release_sock_fd( s, fd );
4275 return ret;
4277 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
4278 return SOCKET_ERROR;
4280 case WS_IPPROTO_IP:
4281 switch(optname)
4283 case WS_IP_ADD_MEMBERSHIP:
4284 case WS_IP_DROP_MEMBERSHIP:
4285 #ifdef IP_HDRINCL
4286 case WS_IP_HDRINCL:
4287 #endif
4288 case WS_IP_MULTICAST_IF:
4289 case WS_IP_MULTICAST_LOOP:
4290 case WS_IP_MULTICAST_TTL:
4291 case WS_IP_OPTIONS:
4292 #ifdef IP_PKTINFO
4293 case WS_IP_PKTINFO:
4294 #endif
4295 case WS_IP_TOS:
4296 case WS_IP_TTL:
4297 #ifdef IP_UNICAST_IF
4298 case WS_IP_UNICAST_IF:
4299 #endif
4300 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4301 return SOCKET_ERROR;
4302 convert_sockopt(&level, &optname);
4303 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
4305 SetLastError(wsaErrno());
4306 ret = SOCKET_ERROR;
4308 release_sock_fd( s, fd );
4309 return ret;
4310 case WS_IP_DONTFRAGMENT:
4311 return get_dont_fragment(s, IPPROTO_IP, (BOOL *)optval) ? 0 : SOCKET_ERROR;
4313 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
4314 return SOCKET_ERROR;
4316 case WS_IPPROTO_IPV6:
4317 switch(optname)
4319 #ifdef IPV6_ADD_MEMBERSHIP
4320 case WS_IPV6_ADD_MEMBERSHIP:
4321 #endif
4322 #ifdef IPV6_DROP_MEMBERSHIP
4323 case WS_IPV6_DROP_MEMBERSHIP:
4324 #endif
4325 case WS_IPV6_MULTICAST_IF:
4326 case WS_IPV6_MULTICAST_HOPS:
4327 case WS_IPV6_MULTICAST_LOOP:
4328 case WS_IPV6_UNICAST_HOPS:
4329 case WS_IPV6_V6ONLY:
4330 #ifdef IPV6_UNICAST_IF
4331 case WS_IPV6_UNICAST_IF:
4332 #endif
4333 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4334 return SOCKET_ERROR;
4335 convert_sockopt(&level, &optname);
4336 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
4338 SetLastError(wsaErrno());
4339 ret = SOCKET_ERROR;
4341 release_sock_fd( s, fd );
4342 return ret;
4343 case WS_IPV6_DONTFRAG:
4344 return get_dont_fragment(s, IPPROTO_IPV6, (BOOL *)optval) ? 0 : SOCKET_ERROR;
4346 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
4347 return SOCKET_ERROR;
4349 default:
4350 WARN("Unknown level: 0x%08x\n", level);
4351 SetLastError(WSAEINVAL);
4352 return SOCKET_ERROR;
4353 } /* end switch(level) */
4356 /***********************************************************************
4357 * htonl (WS2_32.8)
4359 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
4361 return htonl(hostlong);
4365 /***********************************************************************
4366 * htons (WS2_32.9)
4368 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
4370 return htons(hostshort);
4373 /***********************************************************************
4374 * WSAHtonl (WS2_32.46)
4375 * From MSDN description of error codes, this function should also
4376 * check if WinSock has been initialized and the socket is a valid
4377 * socket. But why? This function only translates a host byte order
4378 * u_long into a network byte order u_long...
4380 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
4382 if (lpnetlong)
4384 *lpnetlong = htonl(hostlong);
4385 return 0;
4387 SetLastError(WSAEFAULT);
4388 return SOCKET_ERROR;
4391 /***********************************************************************
4392 * WSAHtons (WS2_32.47)
4393 * From MSDN description of error codes, this function should also
4394 * check if WinSock has been initialized and the socket is a valid
4395 * socket. But why? This function only translates a host byte order
4396 * u_short into a network byte order u_short...
4398 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
4401 if (lpnetshort)
4403 *lpnetshort = htons(hostshort);
4404 return 0;
4406 SetLastError(WSAEFAULT);
4407 return SOCKET_ERROR;
4411 /***********************************************************************
4412 * inet_addr (WS2_32.11)
4414 WS_u_long WINAPI WS_inet_addr(const char *cp)
4416 if (!cp) return INADDR_NONE;
4417 return inet_addr(cp);
4421 /***********************************************************************
4422 * ntohl (WS2_32.14)
4424 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
4426 return ntohl(netlong);
4430 /***********************************************************************
4431 * ntohs (WS2_32.15)
4433 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
4435 return ntohs(netshort);
4439 /***********************************************************************
4440 * inet_ntoa (WS2_32.12)
4442 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
4444 unsigned int long_ip = ntohl(in.WS_s_addr);
4445 struct per_thread_data *data = get_per_thread_data();
4447 sprintf( data->ntoa_buffer, "%u.%u.%u.%u",
4448 (long_ip >> 24) & 0xff,
4449 (long_ip >> 16) & 0xff,
4450 (long_ip >> 8) & 0xff,
4451 long_ip & 0xff);
4453 return data->ntoa_buffer;
4456 static const char *debugstr_wsaioctl(DWORD code)
4458 const char *name = NULL, *buf_type, *family;
4460 #define IOCTL_NAME(x) case x: name = #x; break
4461 switch (code)
4463 IOCTL_NAME(WS_FIONBIO);
4464 IOCTL_NAME(WS_FIONREAD);
4465 IOCTL_NAME(WS_SIOCATMARK);
4466 /* IOCTL_NAME(WS_SIO_ACQUIRE_PORT_RESERVATION); */
4467 IOCTL_NAME(WS_SIO_ADDRESS_LIST_CHANGE);
4468 IOCTL_NAME(WS_SIO_ADDRESS_LIST_QUERY);
4469 IOCTL_NAME(WS_SIO_ASSOCIATE_HANDLE);
4470 /* IOCTL_NAME(WS_SIO_ASSOCIATE_PORT_RESERVATION);
4471 IOCTL_NAME(WS_SIO_BASE_HANDLE);
4472 IOCTL_NAME(WS_SIO_BSP_HANDLE);
4473 IOCTL_NAME(WS_SIO_BSP_HANDLE_SELECT);
4474 IOCTL_NAME(WS_SIO_BSP_HANDLE_POLL);
4475 IOCTL_NAME(WS_SIO_CHK_QOS); */
4476 IOCTL_NAME(WS_SIO_ENABLE_CIRCULAR_QUEUEING);
4477 IOCTL_NAME(WS_SIO_FIND_ROUTE);
4478 IOCTL_NAME(WS_SIO_FLUSH);
4479 IOCTL_NAME(WS_SIO_GET_BROADCAST_ADDRESS);
4480 IOCTL_NAME(WS_SIO_GET_EXTENSION_FUNCTION_POINTER);
4481 IOCTL_NAME(WS_SIO_GET_GROUP_QOS);
4482 IOCTL_NAME(WS_SIO_GET_INTERFACE_LIST);
4483 /* IOCTL_NAME(WS_SIO_GET_INTERFACE_LIST_EX); */
4484 IOCTL_NAME(WS_SIO_GET_QOS);
4485 /* IOCTL_NAME(WS_SIO_IDEAL_SEND_BACKLOG_CHANGE);
4486 IOCTL_NAME(WS_SIO_IDEAL_SEND_BACKLOG_QUERY); */
4487 IOCTL_NAME(WS_SIO_KEEPALIVE_VALS);
4488 IOCTL_NAME(WS_SIO_MULTIPOINT_LOOPBACK);
4489 IOCTL_NAME(WS_SIO_MULTICAST_SCOPE);
4490 /* IOCTL_NAME(WS_SIO_QUERY_RSS_SCALABILITY_INFO);
4491 IOCTL_NAME(WS_SIO_QUERY_WFP_ALE_ENDPOINT_HANDLE); */
4492 IOCTL_NAME(WS_SIO_RCVALL);
4493 IOCTL_NAME(WS_SIO_RCVALL_IGMPMCAST);
4494 IOCTL_NAME(WS_SIO_RCVALL_MCAST);
4495 /* IOCTL_NAME(WS_SIO_RELEASE_PORT_RESERVATION); */
4496 IOCTL_NAME(WS_SIO_ROUTING_INTERFACE_CHANGE);
4497 IOCTL_NAME(WS_SIO_ROUTING_INTERFACE_QUERY);
4498 IOCTL_NAME(WS_SIO_SET_COMPATIBILITY_MODE);
4499 IOCTL_NAME(WS_SIO_SET_GROUP_QOS);
4500 IOCTL_NAME(WS_SIO_SET_QOS);
4501 IOCTL_NAME(WS_SIO_TRANSLATE_HANDLE);
4502 IOCTL_NAME(WS_SIO_UDP_CONNRESET);
4504 #undef IOCTL_NAME
4506 if (name)
4507 return name + 3;
4509 /* If this is not a known code split its bits */
4510 switch(code & 0x18000000)
4512 case WS_IOC_WS2:
4513 family = "IOC_WS2";
4514 break;
4515 case WS_IOC_PROTOCOL:
4516 family = "IOC_PROTOCOL";
4517 break;
4518 case WS_IOC_VENDOR:
4519 family = "IOC_VENDOR";
4520 break;
4521 default: /* WS_IOC_UNIX */
4523 BYTE size = (code >> 16) & WS_IOCPARM_MASK;
4524 char x = (code & 0xff00) >> 8;
4525 BYTE y = code & 0xff;
4526 char args[14];
4528 switch (code & (WS_IOC_VOID|WS_IOC_INOUT))
4530 case WS_IOC_VOID:
4531 buf_type = "_IO";
4532 sprintf(args, "%d, %d", x, y);
4533 break;
4534 case WS_IOC_IN:
4535 buf_type = "_IOW";
4536 sprintf(args, "'%c', %d, %d", x, y, size);
4537 break;
4538 case WS_IOC_OUT:
4539 buf_type = "_IOR";
4540 sprintf(args, "'%c', %d, %d", x, y, size);
4541 break;
4542 default:
4543 buf_type = "?";
4544 sprintf(args, "'%c', %d, %d", x, y, size);
4545 break;
4547 return wine_dbg_sprintf("%s(%s)", buf_type, args);
4551 /* We are different from WS_IOC_UNIX. */
4552 switch (code & (WS_IOC_VOID|WS_IOC_INOUT))
4554 case WS_IOC_VOID:
4555 buf_type = "_WSAIO";
4556 break;
4557 case WS_IOC_INOUT:
4558 buf_type = "_WSAIORW";
4559 break;
4560 case WS_IOC_IN:
4561 buf_type = "_WSAIOW";
4562 break;
4563 case WS_IOC_OUT:
4564 buf_type = "_WSAIOR";
4565 break;
4566 default:
4567 buf_type = "?";
4568 break;
4571 return wine_dbg_sprintf("%s(%s, %d)", buf_type, family,
4572 (USHORT)(code & 0xffff));
4575 /* do an ioctl call through the server */
4576 static DWORD server_ioctl_sock( SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size,
4577 LPVOID out_buff, DWORD out_size, LPDWORD ret_size,
4578 LPWSAOVERLAPPED overlapped,
4579 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
4581 HANDLE event = overlapped ? overlapped->hEvent : 0;
4582 HANDLE handle = SOCKET2HANDLE( s );
4583 struct ws2_async *wsa = NULL;
4584 IO_STATUS_BLOCK *io = (PIO_STATUS_BLOCK)overlapped, iosb;
4585 void *cvalue = NULL;
4586 NTSTATUS status;
4588 if (completion)
4590 if (!(wsa = (struct ws2_async *)alloc_async_io( sizeof(*wsa) )))
4591 return WSA_NOT_ENOUGH_MEMORY;
4592 wsa->hSocket = handle;
4593 wsa->user_overlapped = overlapped;
4594 wsa->completion_func = completion;
4595 if (!io) io = &wsa->local_iosb;
4596 cvalue = wsa;
4598 else if (!io)
4599 io = &iosb;
4600 else if (!((ULONG_PTR)overlapped->hEvent & 1))
4601 cvalue = overlapped;
4603 status = NtDeviceIoControlFile( handle, event, wsa ? ws2_async_apc : NULL, cvalue, io, code,
4604 in_buff, in_size, out_buff, out_size );
4605 if (status == STATUS_NOT_SUPPORTED)
4607 FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
4608 code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
4610 else if (status == STATUS_SUCCESS)
4611 *ret_size = io->Information; /* "Information" is the size written to the output buffer */
4613 if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, wsa );
4615 return NtStatusToWSAError( status );
4618 /**********************************************************************
4619 * WSAIoctl (WS2_32.50)
4622 INT WINAPI WSAIoctl(SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size, LPVOID out_buff,
4623 DWORD out_size, LPDWORD ret_size, LPWSAOVERLAPPED overlapped,
4624 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
4626 int fd;
4627 DWORD status = 0, total = 0;
4629 TRACE("%04lx, %s, %p, %d, %p, %d, %p, %p, %p\n",
4630 s, debugstr_wsaioctl(code), in_buff, in_size, out_buff, out_size, ret_size, overlapped, completion);
4632 switch (code)
4634 case WS_FIONBIO:
4635 if (in_size != sizeof(WS_u_long) || IS_INTRESOURCE(in_buff))
4637 SetLastError(WSAEFAULT);
4638 return SOCKET_ERROR;
4640 TRACE("-> FIONBIO (%x)\n", *(WS_u_long*)in_buff);
4641 if (_get_sock_mask(s))
4643 /* AsyncSelect()'ed sockets are always nonblocking */
4644 if (!*(WS_u_long *)in_buff) status = WSAEINVAL;
4645 break;
4647 if (*(WS_u_long *)in_buff)
4648 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
4649 else
4650 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
4651 break;
4653 case WS_FIONREAD:
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;
4661 if (ioctl(fd, FIONREAD, out_buff ) == -1)
4662 status = wsaErrno();
4663 release_sock_fd( s, fd );
4664 break;
4667 case WS_SIOCATMARK:
4669 unsigned int oob = 0, atmark = 0;
4670 socklen_t oobsize = sizeof(int);
4671 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
4673 SetLastError(WSAEFAULT);
4674 return SOCKET_ERROR;
4676 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
4677 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
4678 if ((getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &oob, &oobsize ) == -1)
4679 || (!oob && ioctl(fd, SIOCATMARK, &atmark ) == -1))
4680 status = wsaErrno();
4681 else
4683 /* The SIOCATMARK value read from ioctl() is reversed
4684 * because BSD returns TRUE if it's in the OOB mark
4685 * while Windows returns TRUE if there are NO OOB bytes.
4687 (*(WS_u_long *) out_buff) = oob || !atmark;
4690 release_sock_fd( s, fd );
4691 break;
4694 case WS_FIOASYNC:
4695 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
4696 SetLastError(WSAEINVAL);
4697 return SOCKET_ERROR;
4699 case WS_SIO_GET_INTERFACE_LIST:
4701 INTERFACE_INFO* intArray = out_buff;
4702 DWORD size, numInt = 0, apiReturn;
4704 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
4706 if (!out_buff || !ret_size)
4708 SetLastError(WSAEFAULT);
4709 return SOCKET_ERROR;
4712 fd = get_sock_fd( s, 0, NULL );
4713 if (fd == -1) return SOCKET_ERROR;
4715 apiReturn = GetAdaptersInfo(NULL, &size);
4716 if (apiReturn == ERROR_BUFFER_OVERFLOW)
4718 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
4720 if (table)
4722 if (GetAdaptersInfo(table, &size) == NO_ERROR)
4724 PIP_ADAPTER_INFO ptr;
4726 for (ptr = table, numInt = 0; ptr; ptr = ptr->Next)
4728 unsigned int addr, mask, bcast;
4729 struct ifreq ifInfo;
4731 /* Skip interfaces without an IPv4 address. */
4732 if (ptr->IpAddressList.IpAddress.String[0] == '\0')
4733 continue;
4735 if ((numInt + 1)*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > out_size)
4737 WARN("Buffer too small = %u, out_size = %u\n", numInt + 1, out_size);
4738 status = WSAEFAULT;
4739 break;
4742 /* Socket Status Flags */
4743 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
4744 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
4746 ERR("Error obtaining status flags for socket!\n");
4747 status = WSAEINVAL;
4748 break;
4750 else
4752 /* set flags; the values of IFF_* are not the same
4753 under Linux and Windows, therefore must generate
4754 new flags */
4755 intArray->iiFlags = 0;
4756 if (ifInfo.ifr_flags & IFF_BROADCAST)
4757 intArray->iiFlags |= WS_IFF_BROADCAST;
4758 #ifdef IFF_POINTOPOINT
4759 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
4760 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
4761 #endif
4762 if (ifInfo.ifr_flags & IFF_LOOPBACK)
4763 intArray->iiFlags |= WS_IFF_LOOPBACK;
4764 if (ifInfo.ifr_flags & IFF_UP)
4765 intArray->iiFlags |= WS_IFF_UP;
4766 if (ifInfo.ifr_flags & IFF_MULTICAST)
4767 intArray->iiFlags |= WS_IFF_MULTICAST;
4770 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
4771 mask = inet_addr(ptr->IpAddressList.IpMask.String);
4772 bcast = addr | ~mask;
4773 intArray->iiAddress.AddressIn.sin_family = WS_AF_INET;
4774 intArray->iiAddress.AddressIn.sin_port = 0;
4775 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr = addr;
4777 intArray->iiNetmask.AddressIn.sin_family = WS_AF_INET;
4778 intArray->iiNetmask.AddressIn.sin_port = 0;
4779 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr = mask;
4781 intArray->iiBroadcastAddress.AddressIn.sin_family = WS_AF_INET;
4782 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
4783 intArray->iiBroadcastAddress.AddressIn.sin_addr.WS_s_addr = bcast;
4784 intArray++;
4785 numInt++;
4788 else
4790 ERR("Unable to get interface table!\n");
4791 status = WSAEINVAL;
4793 HeapFree(GetProcessHeap(),0,table);
4795 else status = WSAEINVAL;
4797 else if (apiReturn != ERROR_NO_DATA)
4799 ERR("Unable to get interface table!\n");
4800 status = WSAEINVAL;
4802 /* Calculate the size of the array being returned */
4803 total = sizeof(INTERFACE_INFO) * numInt;
4804 release_sock_fd( s, fd );
4805 break;
4808 case WS_SIO_ADDRESS_LIST_QUERY:
4810 DWORD size;
4812 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
4814 if (!ret_size)
4816 SetLastError(WSAEFAULT);
4817 return SOCKET_ERROR;
4820 if (out_size && out_size < FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[0]))
4822 *ret_size = 0;
4823 SetLastError(WSAEINVAL);
4824 return SOCKET_ERROR;
4827 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
4829 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
4830 SOCKET_ADDRESS_LIST *sa_list;
4831 SOCKADDR_IN *sockaddr;
4832 SOCKET_ADDRESS *sa;
4833 unsigned int i;
4834 DWORD num;
4836 if (!table || GetAdaptersInfo(table, &size))
4838 HeapFree(GetProcessHeap(), 0, table);
4839 status = WSAEINVAL;
4840 break;
4843 for (p = table, num = 0; p; p = p->Next)
4844 if (p->IpAddressList.IpAddress.String[0]) num++;
4846 total = FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[num]) + num * sizeof(*sockaddr);
4847 if (total > out_size || !out_buff)
4849 *ret_size = total;
4850 HeapFree(GetProcessHeap(), 0, table);
4851 status = WSAEFAULT;
4852 break;
4855 sa_list = out_buff;
4856 sa = sa_list->Address;
4857 sockaddr = (SOCKADDR_IN *)&sa[num];
4858 sa_list->iAddressCount = num;
4860 for (p = table, i = 0; p; p = p->Next)
4862 if (!p->IpAddressList.IpAddress.String[0]) continue;
4864 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
4865 sa[i].iSockaddrLength = sizeof(SOCKADDR);
4867 sockaddr[i].sin_family = WS_AF_INET;
4868 sockaddr[i].sin_port = 0;
4869 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
4870 i++;
4873 HeapFree(GetProcessHeap(), 0, table);
4875 else
4877 WARN("unable to get IP address list\n");
4878 status = WSAEINVAL;
4880 break;
4883 case WS_SIO_FLUSH:
4884 FIXME("SIO_FLUSH: stub.\n");
4885 break;
4887 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
4889 #define EXTENSION_FUNCTION(x, y) { x, y, #y },
4890 static const struct
4892 GUID guid;
4893 void *func_ptr;
4894 const char *name;
4895 } guid_funcs[] = {
4896 EXTENSION_FUNCTION(WSAID_CONNECTEX, WS2_ConnectEx)
4897 EXTENSION_FUNCTION(WSAID_DISCONNECTEX, WS2_DisconnectEx)
4898 EXTENSION_FUNCTION(WSAID_ACCEPTEX, WS2_AcceptEx)
4899 EXTENSION_FUNCTION(WSAID_GETACCEPTEXSOCKADDRS, WS2_GetAcceptExSockaddrs)
4900 EXTENSION_FUNCTION(WSAID_TRANSMITFILE, WS2_TransmitFile)
4901 /* EXTENSION_FUNCTION(WSAID_TRANSMITPACKETS, WS2_TransmitPackets) */
4902 EXTENSION_FUNCTION(WSAID_WSARECVMSG, WS2_WSARecvMsg)
4903 EXTENSION_FUNCTION(WSAID_WSASENDMSG, WSASendMsg)
4905 #undef EXTENSION_FUNCTION
4906 BOOL found = FALSE;
4907 unsigned int i;
4909 for (i = 0; i < sizeof(guid_funcs) / sizeof(guid_funcs[0]); i++)
4911 if (IsEqualGUID(&guid_funcs[i].guid, in_buff))
4913 found = TRUE;
4914 break;
4918 if (found)
4920 TRACE("-> got %s\n", guid_funcs[i].name);
4921 *(void **)out_buff = guid_funcs[i].func_ptr;
4922 break;
4925 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff));
4926 status = WSAEOPNOTSUPP;
4927 break;
4929 case WS_SIO_KEEPALIVE_VALS:
4931 struct tcp_keepalive *k;
4932 int keepalive, keepidle, keepintvl;
4934 if (!in_buff || in_size < sizeof(struct tcp_keepalive))
4936 SetLastError(WSAEFAULT);
4937 return SOCKET_ERROR;
4940 k = in_buff;
4941 keepalive = k->onoff ? 1 : 0;
4942 keepidle = max( 1, (k->keepalivetime + 500) / 1000 );
4943 keepintvl = max( 1, (k->keepaliveinterval + 500) / 1000 );
4945 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
4947 fd = get_sock_fd(s, 0, NULL);
4948 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
4949 status = WSAEINVAL;
4950 #if defined(TCP_KEEPIDLE) || defined(TCP_KEEPINTVL)
4951 /* these values need to be set only if SO_KEEPALIVE is enabled */
4952 else if(keepalive)
4954 #ifndef TCP_KEEPIDLE
4955 FIXME("ignoring keepalive timeout\n");
4956 #else
4957 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
4958 status = WSAEINVAL;
4959 else
4960 #endif
4961 #ifdef TCP_KEEPINTVL
4962 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
4963 status = WSAEINVAL;
4964 #else
4965 FIXME("ignoring keepalive interval\n");
4966 #endif
4968 #else
4969 else
4970 FIXME("ignoring keepalive interval and timeout\n");
4971 #endif
4972 release_sock_fd(s, fd);
4973 break;
4975 case WS_SIO_ROUTING_INTERFACE_QUERY:
4977 struct WS_sockaddr *daddr = (struct WS_sockaddr *)in_buff;
4978 struct WS_sockaddr_in *daddr_in = (struct WS_sockaddr_in *)daddr;
4979 struct WS_sockaddr_in *saddr_in = out_buff;
4980 MIB_IPFORWARDROW row;
4981 PMIB_IPADDRTABLE ipAddrTable = NULL;
4982 DWORD size, i, found_index;
4984 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
4986 if (!in_buff || in_size < sizeof(struct WS_sockaddr) ||
4987 !out_buff || out_size < sizeof(struct WS_sockaddr_in) || !ret_size)
4989 SetLastError(WSAEFAULT);
4990 return SOCKET_ERROR;
4992 if (daddr->sa_family != WS_AF_INET)
4994 FIXME("unsupported address family %d\n", daddr->sa_family);
4995 status = WSAEAFNOSUPPORT;
4996 break;
4998 if (GetBestRoute(daddr_in->sin_addr.S_un.S_addr, 0, &row) != NOERROR ||
4999 GetIpAddrTable(NULL, &size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
5001 status = WSAEFAULT;
5002 break;
5004 ipAddrTable = HeapAlloc(GetProcessHeap(), 0, size);
5005 if (GetIpAddrTable(ipAddrTable, &size, FALSE))
5007 HeapFree(GetProcessHeap(), 0, ipAddrTable);
5008 status = WSAEFAULT;
5009 break;
5011 for (i = 0, found_index = ipAddrTable->dwNumEntries;
5012 i < ipAddrTable->dwNumEntries; i++)
5014 if (ipAddrTable->table[i].dwIndex == row.dwForwardIfIndex)
5015 found_index = i;
5017 if (found_index == ipAddrTable->dwNumEntries)
5019 ERR("no matching IP address for interface %d\n",
5020 row.dwForwardIfIndex);
5021 HeapFree(GetProcessHeap(), 0, ipAddrTable);
5022 status = WSAEFAULT;
5023 break;
5025 saddr_in->sin_family = WS_AF_INET;
5026 saddr_in->sin_addr.S_un.S_addr = ipAddrTable->table[found_index].dwAddr;
5027 saddr_in->sin_port = 0;
5028 total = sizeof(struct WS_sockaddr_in);
5029 HeapFree(GetProcessHeap(), 0, ipAddrTable);
5030 break;
5032 case WS_SIO_SET_COMPATIBILITY_MODE:
5033 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
5034 status = WSAEOPNOTSUPP;
5035 break;
5036 case WS_SIO_UDP_CONNRESET:
5037 FIXME("WS_SIO_UDP_CONNRESET stub\n");
5038 break;
5039 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
5040 SetLastError(WSAEOPNOTSUPP);
5041 return SOCKET_ERROR;
5042 default:
5043 status = WSAEOPNOTSUPP;
5044 break;
5047 if (status == WSAEOPNOTSUPP)
5049 status = server_ioctl_sock(s, code, in_buff, in_size, out_buff, out_size, &total,
5050 overlapped, completion);
5051 if (status != WSAEOPNOTSUPP)
5053 if (status == 0 || status == WSA_IO_PENDING)
5054 TRACE("-> %s request\n", debugstr_wsaioctl(code));
5055 else
5056 ERR("-> %s request failed with status 0x%x\n", debugstr_wsaioctl(code), status);
5058 /* overlapped and completion operations will be handled by the server */
5059 completion = NULL;
5060 overlapped = NULL;
5062 else
5063 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code));
5066 if (completion)
5068 FIXME( "completion routine %p not supported\n", completion );
5070 else if (overlapped)
5072 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
5073 overlapped->Internal = status;
5074 overlapped->InternalHigh = total;
5075 if (overlapped->hEvent) NtSetEvent( overlapped->hEvent, NULL );
5076 if (cvalue) WS_AddCompletion( HANDLE2SOCKET(s), cvalue, status, total );
5079 if (!status)
5081 if (ret_size) *ret_size = total;
5082 return 0;
5084 SetLastError( status );
5085 return SOCKET_ERROR;
5089 /***********************************************************************
5090 * ioctlsocket (WS2_32.10)
5092 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
5094 DWORD ret_size;
5095 return WSAIoctl( s, cmd, argp, sizeof(WS_u_long), argp, sizeof(WS_u_long), &ret_size, NULL, NULL );
5098 /***********************************************************************
5099 * listen (WS2_32.13)
5101 int WINAPI WS_listen(SOCKET s, int backlog)
5103 int fd = get_sock_fd( s, FILE_READ_DATA, NULL ), ret = SOCKET_ERROR;
5105 TRACE("socket %04lx, backlog %d\n", s, backlog);
5106 if (fd != -1)
5108 int bound = is_fd_bound(fd, NULL, NULL);
5110 if (bound <= 0)
5112 SetLastError(bound == -1 ? wsaErrno() : WSAEINVAL);
5114 else if (listen(fd, backlog) == 0)
5116 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
5117 FD_WINE_LISTENING,
5118 FD_CONNECT|FD_WINE_CONNECTED);
5119 ret = 0;
5121 else
5122 SetLastError(wsaErrno());
5123 release_sock_fd( s, fd );
5125 else
5126 SetLastError(WSAENOTSOCK);
5127 return ret;
5130 /***********************************************************************
5131 * recv (WS2_32.16)
5133 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
5135 DWORD n, dwFlags = flags;
5136 WSABUF wsabuf;
5138 wsabuf.len = len;
5139 wsabuf.buf = buf;
5141 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
5142 return SOCKET_ERROR;
5143 else
5144 return n;
5147 /***********************************************************************
5148 * recvfrom (WS2_32.17)
5150 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
5151 struct WS_sockaddr *from, int *fromlen)
5153 DWORD n, dwFlags = flags;
5154 WSABUF wsabuf;
5156 wsabuf.len = len;
5157 wsabuf.buf = buf;
5159 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL, NULL) == SOCKET_ERROR )
5160 return SOCKET_ERROR;
5161 else
5162 return n;
5165 /* allocate a poll array for the corresponding fd sets */
5166 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
5167 const WS_fd_set *exceptfds, int *count_ptr )
5169 unsigned int i, j = 0, count = 0;
5170 struct pollfd *fds;
5171 struct per_thread_data *ptb = get_per_thread_data();
5173 if (readfds) count += readfds->fd_count;
5174 if (writefds) count += writefds->fd_count;
5175 if (exceptfds) count += exceptfds->fd_count;
5176 *count_ptr = count;
5177 if (!count)
5179 SetLastError(WSAEINVAL);
5180 return NULL;
5183 /* check if the cache can hold all descriptors, if not do the resizing */
5184 if (ptb->fd_count < count)
5186 if (!(fds = HeapAlloc(GetProcessHeap(), 0, count * sizeof(fds[0]))))
5188 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
5189 return NULL;
5191 HeapFree(GetProcessHeap(), 0, ptb->fd_cache);
5192 ptb->fd_cache = fds;
5193 ptb->fd_count = count;
5195 else
5196 fds = ptb->fd_cache;
5198 if (readfds)
5199 for (i = 0; i < readfds->fd_count; i++, j++)
5201 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
5202 if (fds[j].fd == -1) goto failed;
5203 fds[j].revents = 0;
5204 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1)
5206 fds[j].events = POLLIN;
5208 else
5210 release_sock_fd( readfds->fd_array[i], fds[j].fd );
5211 fds[j].fd = -1;
5212 fds[j].events = 0;
5215 if (writefds)
5216 for (i = 0; i < writefds->fd_count; i++, j++)
5218 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
5219 if (fds[j].fd == -1) goto failed;
5220 fds[j].revents = 0;
5221 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1 ||
5222 _get_fd_type(fds[j].fd) == SOCK_DGRAM)
5224 fds[j].events = POLLOUT;
5226 else
5228 release_sock_fd( writefds->fd_array[i], fds[j].fd );
5229 fds[j].fd = -1;
5230 fds[j].events = 0;
5233 if (exceptfds)
5234 for (i = 0; i < exceptfds->fd_count; i++, j++)
5236 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
5237 if (fds[j].fd == -1) goto failed;
5238 fds[j].revents = 0;
5239 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1)
5241 int oob_inlined = 0;
5242 socklen_t olen = sizeof(oob_inlined);
5244 fds[j].events = POLLHUP;
5246 /* Check if we need to test for urgent data or not */
5247 getsockopt(fds[j].fd, SOL_SOCKET, SO_OOBINLINE, (char*) &oob_inlined, &olen);
5248 if (!oob_inlined)
5249 fds[j].events |= POLLPRI;
5251 else
5253 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
5254 fds[j].fd = -1;
5255 fds[j].events = 0;
5258 return fds;
5260 failed:
5261 count = j;
5262 j = 0;
5263 if (readfds)
5264 for (i = 0; i < readfds->fd_count && j < count; i++, j++)
5265 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
5266 if (writefds)
5267 for (i = 0; i < writefds->fd_count && j < count; i++, j++)
5268 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
5269 if (exceptfds)
5270 for (i = 0; i < exceptfds->fd_count && j < count; i++, j++)
5271 if (fds[j].fd != -1) release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
5272 return NULL;
5275 /* release the file descriptor obtained in fd_sets_to_poll */
5276 /* must be called with the original fd_set arrays, before calling get_poll_results */
5277 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
5278 const WS_fd_set *exceptfds, struct pollfd *fds )
5280 unsigned int i, j = 0;
5282 if (readfds)
5284 for (i = 0; i < readfds->fd_count; i++, j++)
5285 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
5287 if (writefds)
5289 for (i = 0; i < writefds->fd_count; i++, j++)
5290 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
5292 if (exceptfds)
5294 for (i = 0; i < exceptfds->fd_count; i++, j++)
5296 if (fds[j].fd == -1) continue;
5297 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
5298 if (fds[j].revents & POLLHUP)
5300 int fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
5301 if (fd != -1)
5302 release_sock_fd( exceptfds->fd_array[i], fd );
5303 else
5304 fds[j].revents = 0;
5310 static int do_poll(struct pollfd *pollfds, int count, int timeout)
5312 struct timeval tv1, tv2;
5313 int ret, torig = timeout;
5315 if (timeout > 0) gettimeofday( &tv1, 0 );
5317 while ((ret = poll( pollfds, count, timeout )) < 0)
5319 if (errno != EINTR) break;
5320 if (timeout < 0) continue;
5321 if (timeout == 0) return 0;
5323 gettimeofday( &tv2, 0 );
5325 tv2.tv_sec -= tv1.tv_sec;
5326 tv2.tv_usec -= tv1.tv_usec;
5327 if (tv2.tv_usec < 0)
5329 tv2.tv_usec += 1000000;
5330 tv2.tv_sec -= 1;
5333 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
5334 if (timeout <= 0) return 0;
5336 return ret;
5339 /* map the poll results back into the Windows fd sets */
5340 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
5341 const struct pollfd *fds )
5343 const struct pollfd *poll_writefds = fds + (readfds ? readfds->fd_count : 0);
5344 const struct pollfd *poll_exceptfds = poll_writefds + (writefds ? writefds->fd_count : 0);
5345 unsigned int i, k, total = 0;
5347 if (readfds)
5349 for (i = k = 0; i < readfds->fd_count; i++)
5351 if (fds[i].revents ||
5352 (readfds == writefds && (poll_writefds[i].revents & POLLOUT) && !(poll_writefds[i].revents & POLLHUP)) ||
5353 (readfds == exceptfds && poll_exceptfds[i].revents))
5354 readfds->fd_array[k++] = readfds->fd_array[i];
5356 readfds->fd_count = k;
5357 total += k;
5359 if (writefds && writefds != readfds)
5361 for (i = k = 0; i < writefds->fd_count; i++)
5363 if (((poll_writefds[i].revents & POLLOUT) && !(poll_writefds[i].revents & POLLHUP)) ||
5364 (writefds == exceptfds && poll_exceptfds[i].revents))
5365 writefds->fd_array[k++] = writefds->fd_array[i];
5367 writefds->fd_count = k;
5368 total += k;
5370 if (exceptfds && exceptfds != readfds && exceptfds != writefds)
5372 for (i = k = 0; i < exceptfds->fd_count; i++)
5373 if (poll_exceptfds[i].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
5374 exceptfds->fd_count = k;
5375 total += k;
5377 return total;
5380 /***********************************************************************
5381 * select (WS2_32.18)
5383 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
5384 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
5385 const struct WS_timeval* ws_timeout)
5387 struct pollfd *pollfds;
5388 int count, ret, timeout = -1;
5390 TRACE("read %p, write %p, excp %p timeout %p\n",
5391 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
5393 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )))
5394 return SOCKET_ERROR;
5396 if (ws_timeout)
5397 timeout = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
5399 ret = do_poll(pollfds, count, timeout);
5400 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
5402 if (ret == -1) SetLastError(wsaErrno());
5403 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
5404 return ret;
5407 /***********************************************************************
5408 * WSAPoll
5410 int WINAPI WSAPoll(WSAPOLLFD *wfds, ULONG count, int timeout)
5412 int i, ret;
5413 struct pollfd *ufds;
5415 if (!count)
5417 SetLastError(WSAEINVAL);
5418 return SOCKET_ERROR;
5420 if (!wfds)
5422 SetLastError(WSAEFAULT);
5423 return SOCKET_ERROR;
5426 if (!(ufds = HeapAlloc(GetProcessHeap(), 0, count * sizeof(ufds[0]))))
5428 SetLastError(WSAENOBUFS);
5429 return SOCKET_ERROR;
5432 for (i = 0; i < count; i++)
5434 ufds[i].fd = get_sock_fd(wfds[i].fd, 0, NULL);
5435 ufds[i].events = convert_poll_w2u(wfds[i].events);
5436 ufds[i].revents = 0;
5439 ret = do_poll(ufds, count, timeout);
5441 for (i = 0; i < count; i++)
5443 if (ufds[i].fd != -1)
5445 release_sock_fd(wfds[i].fd, ufds[i].fd);
5446 if (ufds[i].revents & POLLHUP)
5448 /* Check if the socket still exists */
5449 int fd = get_sock_fd(wfds[i].fd, 0, NULL);
5450 if (fd != -1)
5452 wfds[i].revents = WS_POLLHUP;
5453 release_sock_fd(wfds[i].fd, fd);
5455 else
5456 wfds[i].revents = WS_POLLNVAL;
5458 else
5459 wfds[i].revents = convert_poll_u2w(ufds[i].revents);
5461 else
5462 wfds[i].revents = WS_POLLNVAL;
5465 HeapFree(GetProcessHeap(), 0, ufds);
5466 return ret;
5469 /* helper to send completion messages for client-only i/o operation case */
5470 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
5471 ULONG Information )
5473 SERVER_START_REQ( add_fd_completion )
5475 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
5476 req->cvalue = CompletionValue;
5477 req->status = CompletionStatus;
5478 req->information = Information;
5479 wine_server_call( req );
5481 SERVER_END_REQ;
5485 /***********************************************************************
5486 * send (WS2_32.19)
5488 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
5490 DWORD n;
5491 WSABUF wsabuf;
5493 wsabuf.len = len;
5494 wsabuf.buf = (char*) buf;
5496 if ( WS2_sendto( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
5497 return SOCKET_ERROR;
5498 else
5499 return n;
5502 /***********************************************************************
5503 * WSASend (WS2_32.72)
5505 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5506 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
5507 LPWSAOVERLAPPED lpOverlapped,
5508 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5510 return WS2_sendto( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
5511 NULL, 0, lpOverlapped, lpCompletionRoutine );
5514 /***********************************************************************
5515 * WSASendDisconnect (WS2_32.73)
5517 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
5519 return WS_shutdown( s, SD_SEND );
5523 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5524 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
5525 const struct WS_sockaddr *to, int tolen,
5526 LPWSAOVERLAPPED lpOverlapped,
5527 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5529 unsigned int i, options;
5530 int n, fd, err, overlapped, flags;
5531 struct ws2_async *wsa = NULL, localwsa;
5532 int totalLength = 0;
5533 DWORD bytes_sent;
5534 BOOL is_blocking;
5536 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
5537 s, lpBuffers, dwBufferCount, dwFlags,
5538 to, tolen, lpOverlapped, lpCompletionRoutine);
5540 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
5541 TRACE( "fd=%d, options=%x\n", fd, options );
5543 if ( fd == -1 ) return SOCKET_ERROR;
5545 if (!lpOverlapped && !lpNumberOfBytesSent)
5547 err = WSAEFAULT;
5548 goto error;
5551 overlapped = (lpOverlapped || lpCompletionRoutine) &&
5552 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
5553 if (overlapped || dwBufferCount > 1)
5555 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[dwBufferCount]))))
5557 err = WSAEFAULT;
5558 goto error;
5561 else
5562 wsa = &localwsa;
5564 wsa->hSocket = SOCKET2HANDLE(s);
5565 wsa->addr = (struct WS_sockaddr *)to;
5566 wsa->addrlen.val = tolen;
5567 wsa->flags = dwFlags;
5568 wsa->lpFlags = &wsa->flags;
5569 wsa->control = NULL;
5570 wsa->n_iovecs = dwBufferCount;
5571 wsa->first_iovec = 0;
5572 for ( i = 0; i < dwBufferCount; i++ )
5574 wsa->iovec[i].iov_base = lpBuffers[i].buf;
5575 wsa->iovec[i].iov_len = lpBuffers[i].len;
5576 totalLength += lpBuffers[i].len;
5579 flags = convert_flags(dwFlags);
5580 n = WS2_send( fd, wsa, flags );
5581 if (n == -1 && errno != EAGAIN)
5583 err = wsaErrno();
5584 goto error;
5587 if (overlapped)
5589 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
5590 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
5592 wsa->user_overlapped = lpOverlapped;
5593 wsa->completion_func = lpCompletionRoutine;
5594 release_sock_fd( s, fd );
5596 if (n == -1 || n < totalLength)
5598 iosb->u.Status = STATUS_PENDING;
5599 iosb->Information = n == -1 ? 0 : n;
5601 if (wsa->completion_func)
5602 err = register_async( ASYNC_TYPE_WRITE, wsa->hSocket, WS2_async_send, wsa, NULL,
5603 ws2_async_apc, wsa, iosb );
5604 else
5605 err = register_async( ASYNC_TYPE_WRITE, wsa->hSocket, WS2_async_send, wsa, lpOverlapped->hEvent,
5606 NULL, (void *)cvalue, iosb );
5608 /* Enable the event only after starting the async. The server will deliver it as soon as
5609 the async is done. */
5610 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
5612 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
5613 SetLastError(NtStatusToWSAError( err ));
5614 return SOCKET_ERROR;
5617 iosb->u.Status = STATUS_SUCCESS;
5618 iosb->Information = n;
5619 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = n;
5620 if (!wsa->completion_func)
5622 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
5623 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
5624 HeapFree( GetProcessHeap(), 0, wsa );
5626 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
5627 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
5628 SetLastError(ERROR_SUCCESS);
5629 return 0;
5632 if ((err = _is_blocking( s, &is_blocking )))
5634 err = NtStatusToWSAError( err );
5635 goto error;
5638 if ( is_blocking )
5640 /* On a blocking non-overlapped stream socket,
5641 * sending blocks until the entire buffer is sent. */
5642 DWORD timeout_start = GetTickCount();
5644 bytes_sent = n == -1 ? 0 : n;
5646 while (wsa->first_iovec < wsa->n_iovecs)
5648 struct pollfd pfd;
5649 int poll_timeout = -1;
5650 INT64 timeout = get_rcvsnd_timeo(fd, FALSE);
5652 if (timeout)
5654 timeout -= GetTickCount() - timeout_start;
5655 if (timeout < 0) poll_timeout = 0;
5656 else poll_timeout = timeout <= INT_MAX ? timeout : INT_MAX;
5659 pfd.fd = fd;
5660 pfd.events = POLLOUT;
5662 if (!poll_timeout || !poll( &pfd, 1, poll_timeout ))
5664 err = WSAETIMEDOUT;
5665 goto error; /* msdn says a timeout in send is fatal */
5668 n = WS2_send( fd, wsa, flags );
5669 if (n == -1 && errno != EAGAIN)
5671 err = wsaErrno();
5672 goto error;
5675 if (n >= 0)
5676 bytes_sent += n;
5679 else /* non-blocking */
5681 if (n < totalLength)
5682 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
5683 if (n == -1)
5685 err = WSAEWOULDBLOCK;
5686 goto error;
5688 bytes_sent = n;
5691 TRACE(" -> %i bytes\n", bytes_sent);
5693 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = bytes_sent;
5694 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
5695 release_sock_fd( s, fd );
5696 SetLastError(ERROR_SUCCESS);
5697 return 0;
5699 error:
5700 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
5701 release_sock_fd( s, fd );
5702 WARN(" -> ERROR %d\n", err);
5703 SetLastError(err);
5704 return SOCKET_ERROR;
5707 /***********************************************************************
5708 * WSASendTo (WS2_32.74)
5710 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5711 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
5712 const struct WS_sockaddr *to, int tolen,
5713 LPWSAOVERLAPPED lpOverlapped,
5714 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5716 return WS2_sendto( s, lpBuffers, dwBufferCount,
5717 lpNumberOfBytesSent, dwFlags,
5718 to, tolen,
5719 lpOverlapped, lpCompletionRoutine );
5722 /***********************************************************************
5723 * sendto (WS2_32.20)
5725 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
5726 const struct WS_sockaddr *to, int tolen)
5728 DWORD n;
5729 WSABUF wsabuf;
5731 wsabuf.len = len;
5732 wsabuf.buf = (char*) buf;
5734 if ( WS2_sendto(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
5735 return SOCKET_ERROR;
5736 else
5737 return n;
5740 /***********************************************************************
5741 * setsockopt (WS2_32.21)
5743 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
5744 const char *optval, int optlen)
5746 int fd;
5747 int woptval;
5748 struct linger linger;
5749 struct timeval tval;
5751 TRACE("(socket %04lx, %s, optval %s, optlen %d)\n", s,
5752 debugstr_sockopt(level, optname), debugstr_optval(optval, optlen),
5753 optlen);
5755 /* some broken apps pass the value directly instead of a pointer to it */
5756 if(optlen && IS_INTRESOURCE(optval))
5758 SetLastError(WSAEFAULT);
5759 return SOCKET_ERROR;
5762 switch(level)
5764 case WS_SOL_SOCKET:
5765 switch(optname)
5767 /* Some options need some conversion before they can be sent to
5768 * setsockopt. The conversions are done here, then they will fall through
5769 * to the general case. Special options that are not passed to
5770 * setsockopt follow below that.*/
5772 case WS_SO_DONTLINGER:
5773 if (!optval)
5775 SetLastError(WSAEFAULT);
5776 return SOCKET_ERROR;
5778 linger.l_onoff = *(const int*)optval == 0;
5779 linger.l_linger = 0;
5780 level = SOL_SOCKET;
5781 optname = SO_LINGER;
5782 optval = (char*)&linger;
5783 optlen = sizeof(struct linger);
5784 break;
5786 case WS_SO_LINGER:
5787 if (!optval)
5789 SetLastError(WSAEFAULT);
5790 return SOCKET_ERROR;
5792 linger.l_onoff = ((LINGER*)optval)->l_onoff;
5793 linger.l_linger = ((LINGER*)optval)->l_linger;
5794 level = SOL_SOCKET;
5795 optname = SO_LINGER;
5796 optval = (char*)&linger;
5797 optlen = sizeof(struct linger);
5798 break;
5800 case WS_SO_RCVBUF:
5801 if (*(const int*)optval < 2048)
5803 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
5804 return 0;
5806 /* Fall through */
5808 /* The options listed here don't need any special handling. Thanks to
5809 * the conversion happening above, options from there will fall through
5810 * to this, too.*/
5811 case WS_SO_ACCEPTCONN:
5812 case WS_SO_BROADCAST:
5813 case WS_SO_ERROR:
5814 case WS_SO_KEEPALIVE:
5815 case WS_SO_OOBINLINE:
5816 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
5817 * however, using it the BSD way fixes bug 8513 and seems to be what
5818 * most programmers assume, anyway */
5819 case WS_SO_REUSEADDR:
5820 case WS_SO_SNDBUF:
5821 case WS_SO_TYPE:
5822 convert_sockopt(&level, &optname);
5823 break;
5825 /* SO_DEBUG is a privileged operation, ignore it. */
5826 case WS_SO_DEBUG:
5827 TRACE("Ignoring SO_DEBUG\n");
5828 return 0;
5830 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
5831 * socket. According to MSDN, this option is silently ignored.*/
5832 case WS_SO_DONTROUTE:
5833 TRACE("Ignoring SO_DONTROUTE\n");
5834 return 0;
5836 /* Stops two sockets from being bound to the same port. Always happens
5837 * on unix systems, so just drop it. */
5838 case WS_SO_EXCLUSIVEADDRUSE:
5839 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
5840 return 0;
5842 /* After a ConnectEx call succeeds, the socket can't be used with half of the
5843 * normal winsock functions on windows. We don't have that problem. */
5844 case WS_SO_UPDATE_CONNECT_CONTEXT:
5845 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
5846 return 0;
5848 /* After a AcceptEx call succeeds, the socket can't be used with half of the
5849 * normal winsock functions on windows. We don't have that problem. */
5850 case WS_SO_UPDATE_ACCEPT_CONTEXT:
5851 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
5852 return 0;
5854 /* SO_OPENTYPE does not require a valid socket handle. */
5855 case WS_SO_OPENTYPE:
5856 if (!optlen || optlen < sizeof(int) || !optval)
5858 SetLastError(WSAEFAULT);
5859 return SOCKET_ERROR;
5861 get_per_thread_data()->opentype = *(const int *)optval;
5862 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
5863 return 0;
5865 #ifdef SO_RCVTIMEO
5866 case WS_SO_RCVTIMEO:
5867 #endif
5868 #ifdef SO_SNDTIMEO
5869 case WS_SO_SNDTIMEO:
5870 #endif
5871 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
5872 if (optval && optlen == sizeof(UINT32)) {
5873 /* WinSock passes milliseconds instead of struct timeval */
5874 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
5875 tval.tv_sec = *(const UINT32*)optval / 1000;
5876 /* min of 500 milliseconds */
5877 if (tval.tv_sec == 0 && tval.tv_usec && tval.tv_usec < 500000)
5878 tval.tv_usec = 500000;
5879 optlen = sizeof(struct timeval);
5880 optval = (char*)&tval;
5881 } else if (optlen == sizeof(struct timeval)) {
5882 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
5883 } else {
5884 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
5885 return 0;
5887 convert_sockopt(&level, &optname);
5888 break;
5889 #endif
5891 default:
5892 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
5893 SetLastError(WSAENOPROTOOPT);
5894 return SOCKET_ERROR;
5896 break; /* case WS_SOL_SOCKET */
5898 #ifdef HAS_IPX
5899 case WS_NSPROTO_IPX:
5900 switch(optname)
5902 case WS_IPX_PTYPE:
5903 return set_ipx_packettype(s, *(int*)optval);
5905 case WS_IPX_FILTERPTYPE:
5906 /* Sets the receive filter packet type, at the moment we don't support it */
5907 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
5908 /* Returning 0 is better for now than returning a SOCKET_ERROR */
5909 return 0;
5911 default:
5912 FIXME("opt_name:%x\n", optname);
5913 return SOCKET_ERROR;
5915 break; /* case WS_NSPROTO_IPX */
5916 #endif
5918 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
5919 case WS_IPPROTO_TCP:
5920 switch(optname)
5922 case WS_TCP_NODELAY:
5923 convert_sockopt(&level, &optname);
5924 break;
5925 default:
5926 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
5927 return SOCKET_ERROR;
5929 break;
5931 case WS_IPPROTO_IP:
5932 switch(optname)
5934 case WS_IP_ADD_MEMBERSHIP:
5935 case WS_IP_DROP_MEMBERSHIP:
5936 #ifdef IP_HDRINCL
5937 case WS_IP_HDRINCL:
5938 #endif
5939 case WS_IP_MULTICAST_IF:
5940 case WS_IP_MULTICAST_LOOP:
5941 case WS_IP_MULTICAST_TTL:
5942 case WS_IP_OPTIONS:
5943 #ifdef IP_PKTINFO
5944 case WS_IP_PKTINFO:
5945 #endif
5946 case WS_IP_TOS:
5947 case WS_IP_TTL:
5948 #ifdef IP_UNICAST_IF
5949 case WS_IP_UNICAST_IF:
5950 #endif
5951 convert_sockopt(&level, &optname);
5952 break;
5953 case WS_IP_DONTFRAGMENT:
5954 return set_dont_fragment(s, IPPROTO_IP, *(BOOL *)optval) ? 0 : SOCKET_ERROR;
5955 default:
5956 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
5957 return SOCKET_ERROR;
5959 break;
5961 case WS_IPPROTO_IPV6:
5962 switch(optname)
5964 #ifdef IPV6_ADD_MEMBERSHIP
5965 case WS_IPV6_ADD_MEMBERSHIP:
5966 #endif
5967 #ifdef IPV6_DROP_MEMBERSHIP
5968 case WS_IPV6_DROP_MEMBERSHIP:
5969 #endif
5970 case WS_IPV6_MULTICAST_IF:
5971 case WS_IPV6_MULTICAST_HOPS:
5972 case WS_IPV6_MULTICAST_LOOP:
5973 case WS_IPV6_UNICAST_HOPS:
5974 #ifdef IPV6_UNICAST_IF
5975 case WS_IPV6_UNICAST_IF:
5976 #endif
5977 convert_sockopt(&level, &optname);
5978 break;
5979 case WS_IPV6_DONTFRAG:
5980 return set_dont_fragment(s, IPPROTO_IPV6, *(BOOL *)optval) ? 0 : SOCKET_ERROR;
5981 case WS_IPV6_PROTECTION_LEVEL:
5982 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
5983 return 0;
5984 case WS_IPV6_V6ONLY:
5986 union generic_unix_sockaddr uaddr;
5987 socklen_t uaddrlen;
5988 int bound;
5990 fd = get_sock_fd( s, 0, NULL );
5991 if (fd == -1) return SOCKET_ERROR;
5993 bound = is_fd_bound(fd, &uaddr, &uaddrlen);
5994 release_sock_fd( s, fd );
5995 if (bound == 0 && uaddr.addr.sa_family == AF_INET)
5997 /* Changing IPV6_V6ONLY succeeds on AF_INET (IPv4) socket
5998 * on Windows (with IPv6 support) if the socket is unbound.
5999 * It is essentially a noop, though Windows does store the value
6001 WARN("Silently ignoring IPPROTO_IPV6+IPV6_V6ONLY on AF_INET socket\n");
6002 return 0;
6004 level = IPPROTO_IPV6;
6005 optname = IPV6_V6ONLY;
6006 break;
6008 default:
6009 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
6010 return SOCKET_ERROR;
6012 break;
6014 default:
6015 WARN("Unknown level: 0x%08x\n", level);
6016 SetLastError(WSAEINVAL);
6017 return SOCKET_ERROR;
6018 } /* end switch(level) */
6020 /* avoid endianness issues if argument is a 16-bit int */
6021 if (optval && optlen < sizeof(int))
6023 woptval= *((const INT16 *) optval);
6024 optval= (char*) &woptval;
6025 woptval&= (1 << optlen * 8) - 1;
6026 optlen=sizeof(int);
6028 fd = get_sock_fd( s, 0, NULL );
6029 if (fd == -1) return SOCKET_ERROR;
6031 if (setsockopt(fd, level, optname, optval, optlen) == 0)
6033 #ifdef __APPLE__
6034 if (level == SOL_SOCKET && optname == SO_REUSEADDR &&
6035 setsockopt(fd, level, SO_REUSEPORT, optval, optlen) != 0)
6037 SetLastError(wsaErrno());
6038 release_sock_fd( s, fd );
6039 return SOCKET_ERROR;
6041 #endif
6042 release_sock_fd( s, fd );
6043 return 0;
6045 TRACE("Setting socket error, %d\n", wsaErrno());
6046 SetLastError(wsaErrno());
6047 release_sock_fd( s, fd );
6049 return SOCKET_ERROR;
6052 /***********************************************************************
6053 * shutdown (WS2_32.22)
6055 int WINAPI WS_shutdown(SOCKET s, int how)
6057 int fd, err = WSAENOTSOCK;
6058 unsigned int options = 0, clear_flags = 0;
6060 fd = get_sock_fd( s, 0, &options );
6061 TRACE("socket %04lx, how 0x%x, options 0x%x\n", s, how, options );
6063 if (fd == -1)
6064 return SOCKET_ERROR;
6066 switch( how )
6068 case SD_RECEIVE: /* drop receives */
6069 clear_flags |= FD_READ;
6070 break;
6071 case SD_SEND: /* drop sends */
6072 clear_flags |= FD_WRITE;
6073 break;
6074 case SD_BOTH: /* drop all */
6075 clear_flags |= FD_READ|FD_WRITE;
6076 /*fall through */
6077 default:
6078 clear_flags |= FD_WINE_LISTENING;
6081 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
6083 switch ( how )
6085 case SD_RECEIVE:
6086 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
6087 break;
6088 case SD_SEND:
6089 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
6090 break;
6091 case SD_BOTH:
6092 default:
6093 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
6094 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
6095 break;
6097 if (err) goto error;
6099 else /* non-overlapped mode */
6101 if ( shutdown( fd, how ) )
6103 err = wsaErrno();
6104 goto error;
6108 release_sock_fd( s, fd );
6109 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
6110 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
6111 return 0;
6113 error:
6114 release_sock_fd( s, fd );
6115 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
6116 SetLastError( err );
6117 return SOCKET_ERROR;
6120 /***********************************************************************
6121 * socket (WS2_32.23)
6123 SOCKET WINAPI WS_socket(int af, int type, int protocol)
6125 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
6127 return WSASocketW( af, type, protocol, NULL, 0,
6128 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
6132 /***********************************************************************
6133 * gethostbyaddr (WS2_32.51)
6135 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
6137 struct WS_hostent *retval = NULL;
6138 struct hostent* host;
6139 int unixtype = convert_af_w2u(type);
6140 const char *paddr = addr;
6141 unsigned long loopback;
6142 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6143 char *extrabuf;
6144 int ebufsize = 1024;
6145 struct hostent hostentry;
6146 int locerr = ENOBUFS;
6147 #endif
6149 /* convert back the magic loopback address if necessary */
6150 if (unixtype == AF_INET && len == 4 && !memcmp(addr, magic_loopback_addr, 4))
6152 loopback = htonl(INADDR_LOOPBACK);
6153 paddr = (char*) &loopback;
6156 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6157 host = NULL;
6158 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
6159 while(extrabuf) {
6160 int res = gethostbyaddr_r(paddr, len, unixtype,
6161 &hostentry, extrabuf, ebufsize, &host, &locerr);
6162 if (res != ERANGE) break;
6163 ebufsize *=2;
6164 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
6166 if (host) retval = WS_dup_he(host);
6167 else SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
6168 HeapFree(GetProcessHeap(),0,extrabuf);
6169 #else
6170 EnterCriticalSection( &csWSgetXXXbyYYY );
6171 host = gethostbyaddr(paddr, len, unixtype);
6172 if (host) retval = WS_dup_he(host);
6173 else SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
6174 LeaveCriticalSection( &csWSgetXXXbyYYY );
6175 #endif
6176 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
6177 return retval;
6180 /***********************************************************************
6181 * WS_compare_routes_by_metric_asc (INTERNAL)
6183 * Comparison function for qsort(), for sorting two routes (struct route)
6184 * by metric in ascending order.
6186 static int WS_compare_routes_by_metric_asc(const void *left, const void *right)
6188 const struct route *a = left, *b = right;
6189 if (a->default_route && b->default_route)
6190 return a->default_route - b->default_route;
6191 if (a->default_route && !b->default_route)
6192 return -1;
6193 if (b->default_route && !a->default_route)
6194 return 1;
6195 return a->metric - b->metric;
6198 /***********************************************************************
6199 * WS_get_local_ips (INTERNAL)
6201 * Returns the list of local IP addresses by going through the network
6202 * adapters and using the local routing table to sort the addresses
6203 * from highest routing priority to lowest routing priority. This
6204 * functionality is inferred from the description for obtaining local
6205 * IP addresses given in the Knowledge Base Article Q160215.
6207 * Please note that the returned hostent is only freed when the thread
6208 * closes and is replaced if another hostent is requested.
6210 static struct WS_hostent* WS_get_local_ips( char *hostname )
6212 int numroutes = 0, i, j, default_routes = 0;
6213 DWORD n;
6214 PIP_ADAPTER_INFO adapters = NULL, k;
6215 struct WS_hostent *hostlist = NULL;
6216 PMIB_IPFORWARDTABLE routes = NULL;
6217 struct route *route_addrs = NULL;
6218 DWORD adap_size, route_size;
6220 /* Obtain the size of the adapter list and routing table, also allocate memory */
6221 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
6222 return NULL;
6223 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
6224 return NULL;
6225 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
6226 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
6227 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
6228 if (adapters == NULL || routes == NULL || route_addrs == NULL)
6229 goto cleanup;
6230 /* Obtain the adapter list and the full routing table */
6231 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
6232 goto cleanup;
6233 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
6234 goto cleanup;
6235 /* Store the interface associated with each route */
6236 for (n = 0; n < routes->dwNumEntries; n++)
6238 IF_INDEX ifindex;
6239 DWORD ifmetric, ifdefault = 0;
6240 BOOL exists = FALSE;
6242 /* Check if this is a default route (there may be more than one) */
6243 if (!routes->table[n].dwForwardDest)
6244 ifdefault = ++default_routes;
6245 else if (routes->table[n].u1.ForwardType != MIB_IPROUTE_TYPE_DIRECT)
6246 continue;
6247 ifindex = routes->table[n].dwForwardIfIndex;
6248 ifmetric = routes->table[n].dwForwardMetric1;
6249 /* Only store the lowest valued metric for an interface */
6250 for (j = 0; j < numroutes; j++)
6252 if (route_addrs[j].interface == ifindex)
6254 if (route_addrs[j].metric > ifmetric)
6255 route_addrs[j].metric = ifmetric;
6256 exists = TRUE;
6259 if (exists)
6260 continue;
6261 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
6262 if (route_addrs == NULL)
6263 goto cleanup; /* Memory allocation error, fail gracefully */
6264 route_addrs[numroutes].interface = ifindex;
6265 route_addrs[numroutes].metric = ifmetric;
6266 route_addrs[numroutes].default_route = ifdefault;
6267 /* If no IP is found in the next step (for whatever reason)
6268 * then fall back to the magic loopback address.
6270 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
6271 numroutes++;
6273 if (numroutes == 0)
6274 goto cleanup; /* No routes, fall back to the Magic IP */
6275 /* Find the IP address associated with each found interface */
6276 for (i = 0; i < numroutes; i++)
6278 for (k = adapters; k != NULL; k = k->Next)
6280 char *ip = k->IpAddressList.IpAddress.String;
6282 if (route_addrs[i].interface == k->Index)
6283 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
6286 /* Allocate a hostent and enough memory for all the IPs,
6287 * including the NULL at the end of the list.
6289 hostlist = WS_create_he(hostname, 1, 0, numroutes+1, sizeof(struct in_addr));
6290 if (hostlist == NULL)
6291 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
6292 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
6293 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
6294 hostlist->h_addrtype = AF_INET;
6295 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
6296 /* Reorder the entries before placing them in the host list. Windows expects
6297 * the IP list in order from highest priority to lowest (the critical thing
6298 * is that most applications expect the first IP to be the default route).
6300 if (numroutes > 1)
6301 qsort(route_addrs, numroutes, sizeof(struct route), WS_compare_routes_by_metric_asc);
6303 for (i = 0; i < numroutes; i++)
6304 (*(struct in_addr *) hostlist->h_addr_list[i]) = route_addrs[i].addr;
6306 /* Cleanup all allocated memory except the address list,
6307 * the address list is used by the calling app.
6309 cleanup:
6310 HeapFree(GetProcessHeap(), 0, route_addrs);
6311 HeapFree(GetProcessHeap(), 0, adapters);
6312 HeapFree(GetProcessHeap(), 0, routes);
6313 return hostlist;
6316 /***********************************************************************
6317 * gethostbyname (WS2_32.52)
6319 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
6321 struct WS_hostent *retval = NULL;
6322 struct hostent* host;
6323 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6324 char *extrabuf;
6325 int ebufsize=1024;
6326 struct hostent hostentry;
6327 int locerr = ENOBUFS;
6328 #endif
6329 char hostname[100];
6330 if(!num_startup) {
6331 SetLastError(WSANOTINITIALISED);
6332 return NULL;
6334 if( gethostname( hostname, 100) == -1) {
6335 SetLastError(WSAENOBUFS); /* appropriate ? */
6336 return retval;
6338 if( !name || !name[0]) {
6339 name = hostname;
6341 /* If the hostname of the local machine is requested then return the
6342 * complete list of local IP addresses */
6343 if(strcmp(name, hostname) == 0)
6344 retval = WS_get_local_ips(hostname);
6345 /* If any other hostname was requested (or the routing table lookup failed)
6346 * then return the IP found by the host OS */
6347 if(retval == NULL)
6349 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6350 host = NULL;
6351 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
6352 while(extrabuf) {
6353 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
6354 if( res != ERANGE) break;
6355 ebufsize *=2;
6356 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
6358 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
6359 #else
6360 EnterCriticalSection( &csWSgetXXXbyYYY );
6361 host = gethostbyname(name);
6362 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
6363 #endif
6364 if (host) retval = WS_dup_he(host);
6365 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6366 HeapFree(GetProcessHeap(),0,extrabuf);
6367 #else
6368 LeaveCriticalSection( &csWSgetXXXbyYYY );
6369 #endif
6371 if (retval && retval->h_addr_list[0][0] == 127 &&
6372 strcmp(name, "localhost") != 0)
6374 /* hostname != "localhost" but has loopback address. replace by our
6375 * special address.*/
6376 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
6378 TRACE( "%s ret %p\n", debugstr_a(name), retval );
6379 return retval;
6383 /***********************************************************************
6384 * getprotobyname (WS2_32.53)
6386 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
6388 struct WS_protoent* retval = NULL;
6389 #ifdef HAVE_GETPROTOBYNAME
6390 struct protoent* proto;
6391 EnterCriticalSection( &csWSgetXXXbyYYY );
6392 if( (proto = getprotobyname(name)) != NULL )
6394 retval = WS_dup_pe(proto);
6396 else {
6397 MESSAGE("protocol %s not found; You might want to add "
6398 "this to /etc/protocols\n", debugstr_a(name) );
6399 SetLastError(WSANO_DATA);
6401 LeaveCriticalSection( &csWSgetXXXbyYYY );
6402 #endif
6403 TRACE( "%s ret %p\n", debugstr_a(name), retval );
6404 return retval;
6408 /***********************************************************************
6409 * getprotobynumber (WS2_32.54)
6411 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
6413 struct WS_protoent* retval = NULL;
6414 #ifdef HAVE_GETPROTOBYNUMBER
6415 struct protoent* proto;
6416 EnterCriticalSection( &csWSgetXXXbyYYY );
6417 if( (proto = getprotobynumber(number)) != NULL )
6419 retval = WS_dup_pe(proto);
6421 else {
6422 MESSAGE("protocol number %d not found; You might want to add "
6423 "this to /etc/protocols\n", number );
6424 SetLastError(WSANO_DATA);
6426 LeaveCriticalSection( &csWSgetXXXbyYYY );
6427 #endif
6428 TRACE("%i ret %p\n", number, retval);
6429 return retval;
6433 /***********************************************************************
6434 * getservbyname (WS2_32.55)
6436 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
6438 struct WS_servent* retval = NULL;
6439 struct servent* serv;
6440 char *name_str;
6441 char *proto_str = NULL;
6443 if (!(name_str = strdup_lower(name))) return NULL;
6445 if (proto && *proto)
6447 if (!(proto_str = strdup_lower(proto)))
6449 HeapFree( GetProcessHeap(), 0, name_str );
6450 return NULL;
6454 EnterCriticalSection( &csWSgetXXXbyYYY );
6455 serv = getservbyname(name_str, proto_str);
6456 if( serv != NULL )
6458 retval = WS_dup_se(serv);
6460 else SetLastError(WSANO_DATA);
6461 LeaveCriticalSection( &csWSgetXXXbyYYY );
6462 HeapFree( GetProcessHeap(), 0, proto_str );
6463 HeapFree( GetProcessHeap(), 0, name_str );
6464 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
6465 return retval;
6468 /***********************************************************************
6469 * freeaddrinfo (WS2_32.@)
6471 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
6473 while (res) {
6474 struct WS_addrinfo *next;
6476 HeapFree(GetProcessHeap(),0,res->ai_canonname);
6477 HeapFree(GetProcessHeap(),0,res->ai_addr);
6478 next = res->ai_next;
6479 HeapFree(GetProcessHeap(),0,res);
6480 res = next;
6484 /* helper functions for getaddrinfo()/getnameinfo() */
6485 static int convert_aiflag_w2u(int winflags) {
6486 unsigned int i;
6487 int unixflags = 0;
6489 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
6490 if (ws_aiflag_map[i][0] & winflags) {
6491 unixflags |= ws_aiflag_map[i][1];
6492 winflags &= ~ws_aiflag_map[i][0];
6494 if (winflags)
6495 FIXME("Unhandled windows AI_xxx flags 0x%x\n", winflags);
6496 return unixflags;
6499 static int convert_niflag_w2u(int winflags) {
6500 unsigned int i;
6501 int unixflags = 0;
6503 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
6504 if (ws_niflag_map[i][0] & winflags) {
6505 unixflags |= ws_niflag_map[i][1];
6506 winflags &= ~ws_niflag_map[i][0];
6508 if (winflags)
6509 FIXME("Unhandled windows NI_xxx flags 0x%x\n", winflags);
6510 return unixflags;
6513 static int convert_aiflag_u2w(int unixflags) {
6514 unsigned int i;
6515 int winflags = 0;
6517 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
6518 if (ws_aiflag_map[i][1] & unixflags) {
6519 winflags |= ws_aiflag_map[i][0];
6520 unixflags &= ~ws_aiflag_map[i][1];
6522 if (unixflags)
6523 WARN("Unhandled UNIX AI_xxx flags 0x%x\n", unixflags);
6524 return winflags;
6527 static int convert_eai_u2w(int unixret) {
6528 int i;
6530 if (!unixret) return 0;
6532 for (i=0;ws_eai_map[i][0];i++)
6533 if (ws_eai_map[i][1] == unixret)
6534 return ws_eai_map[i][0];
6536 if (unixret == EAI_SYSTEM)
6537 /* There are broken versions of glibc which return EAI_SYSTEM
6538 * and set errno to 0 instead of returning EAI_NONAME.
6540 return errno ? sock_get_error( errno ) : WS_EAI_NONAME;
6542 FIXME("Unhandled unix EAI_xxx ret %d\n", unixret);
6543 return unixret;
6546 static char *get_hostname(void)
6548 char *ret;
6549 DWORD size = 0;
6551 GetComputerNameExA( ComputerNamePhysicalDnsHostname, NULL, &size );
6552 if (GetLastError() != ERROR_MORE_DATA) return NULL;
6553 if (!(ret = HeapAlloc( GetProcessHeap(), 0, size ))) return NULL;
6554 if (!GetComputerNameExA( ComputerNamePhysicalDnsHostname, ret, &size ))
6556 HeapFree( GetProcessHeap(), 0, ret );
6557 return NULL;
6559 return ret;
6562 /***********************************************************************
6563 * getaddrinfo (WS2_32.@)
6565 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
6567 #ifdef HAVE_GETADDRINFO
6568 struct addrinfo *unixaires = NULL;
6569 int result;
6570 struct addrinfo unixhints, *punixhints = NULL;
6571 char *hostname;
6572 const char *node;
6574 *res = NULL;
6575 if (!nodename && !servname)
6577 SetLastError(WSAHOST_NOT_FOUND);
6578 return WSAHOST_NOT_FOUND;
6581 hostname = get_hostname();
6582 if (!hostname) return WSA_NOT_ENOUGH_MEMORY;
6584 if (!nodename)
6585 node = NULL;
6586 else if (!nodename[0])
6587 node = hostname;
6588 else
6589 node = nodename;
6591 /* servname tweak required by OSX and BSD kernels */
6592 if (servname && !servname[0]) servname = "0";
6594 if (hints) {
6595 punixhints = &unixhints;
6597 memset(&unixhints, 0, sizeof(unixhints));
6598 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
6600 /* zero is a wildcard, no need to convert */
6601 if (hints->ai_family)
6602 punixhints->ai_family = convert_af_w2u(hints->ai_family);
6603 if (hints->ai_socktype)
6604 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
6605 if (hints->ai_protocol)
6606 punixhints->ai_protocol = max(convert_proto_w2u(hints->ai_protocol), 0);
6608 if (punixhints->ai_socktype < 0)
6610 SetLastError(WSAESOCKTNOSUPPORT);
6611 HeapFree(GetProcessHeap(), 0, hostname);
6612 return SOCKET_ERROR;
6615 /* windows allows invalid combinations of socket type and protocol, unix does not.
6616 * fix the parameters here to make getaddrinfo call always work */
6617 if (punixhints->ai_protocol == IPPROTO_TCP &&
6618 punixhints->ai_socktype != SOCK_STREAM && punixhints->ai_socktype != SOCK_SEQPACKET)
6619 punixhints->ai_socktype = 0;
6621 else if (punixhints->ai_protocol == IPPROTO_UDP && punixhints->ai_socktype != SOCK_DGRAM)
6622 punixhints->ai_socktype = 0;
6624 else if (IS_IPX_PROTO(punixhints->ai_protocol) && punixhints->ai_socktype != SOCK_DGRAM)
6625 punixhints->ai_socktype = 0;
6627 else if (punixhints->ai_protocol == IPPROTO_IPV6)
6628 punixhints->ai_protocol = 0;
6631 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
6632 result = getaddrinfo(node, servname, punixhints, &unixaires);
6634 if (result && !strcmp(hostname, node))
6636 /* If it didn't work it means the host name IP is not in /etc/hosts, try again
6637 * by sending a NULL host and avoid sending a NULL servname too because that
6638 * is invalid */
6639 ERR_(winediag)("Failed to resolve your host name IP\n");
6640 result = getaddrinfo(NULL, servname ? servname : "0", punixhints, &unixaires);
6642 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
6643 HeapFree(GetProcessHeap(), 0, hostname);
6645 if (!result) {
6646 struct addrinfo *xuai = unixaires;
6647 struct WS_addrinfo **xai = res;
6649 *xai = NULL;
6650 while (xuai) {
6651 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
6652 SIZE_T len;
6654 if (!ai)
6655 goto outofmem;
6657 *xai = ai;xai = &ai->ai_next;
6658 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
6659 ai->ai_family = convert_af_u2w(xuai->ai_family);
6660 /* copy whatever was sent in the hints */
6661 if(hints) {
6662 ai->ai_socktype = hints->ai_socktype;
6663 ai->ai_protocol = hints->ai_protocol;
6664 } else {
6665 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
6666 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
6668 if (xuai->ai_canonname) {
6669 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
6670 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
6671 if (!ai->ai_canonname)
6672 goto outofmem;
6673 strcpy(ai->ai_canonname,xuai->ai_canonname);
6675 len = xuai->ai_addrlen;
6676 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
6677 if (!ai->ai_addr)
6678 goto outofmem;
6679 ai->ai_addrlen = len;
6680 do {
6681 int winlen = ai->ai_addrlen;
6683 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
6684 ai->ai_addrlen = winlen;
6685 break;
6687 len = 2*len;
6688 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
6689 if (!ai->ai_addr)
6690 goto outofmem;
6691 ai->ai_addrlen = len;
6692 } while (1);
6693 xuai = xuai->ai_next;
6695 freeaddrinfo(unixaires);
6697 if (TRACE_ON(winsock))
6699 struct WS_addrinfo *ai = *res;
6700 while (ai)
6702 TRACE("=> %p, flags %#x, family %d, type %d, protocol %d, len %ld, name %s, addr %s\n",
6703 ai, ai->ai_flags, ai->ai_family, ai->ai_socktype, ai->ai_protocol, ai->ai_addrlen,
6704 ai->ai_canonname, debugstr_sockaddr(ai->ai_addr));
6705 ai = ai->ai_next;
6708 } else
6709 result = convert_eai_u2w(result);
6711 SetLastError(result);
6712 return result;
6714 outofmem:
6715 if (*res) WS_freeaddrinfo(*res);
6716 if (unixaires) freeaddrinfo(unixaires);
6717 return WSA_NOT_ENOUGH_MEMORY;
6718 #else
6719 FIXME("getaddrinfo() failed, not found during buildtime.\n");
6720 return EAI_FAIL;
6721 #endif
6724 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
6726 struct WS_addrinfoW *ret;
6728 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
6729 ret->ai_flags = ai->ai_flags;
6730 ret->ai_family = ai->ai_family;
6731 ret->ai_socktype = ai->ai_socktype;
6732 ret->ai_protocol = ai->ai_protocol;
6733 ret->ai_addrlen = ai->ai_addrlen;
6734 ret->ai_canonname = NULL;
6735 ret->ai_addr = NULL;
6736 ret->ai_next = NULL;
6737 if (ai->ai_canonname)
6739 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
6740 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR))))
6742 HeapFree(GetProcessHeap(), 0, ret);
6743 return NULL;
6745 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
6747 if (ai->ai_addr)
6749 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, ai->ai_addrlen)))
6751 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
6752 HeapFree(GetProcessHeap(), 0, ret);
6753 return NULL;
6755 memcpy(ret->ai_addr, ai->ai_addr, ai->ai_addrlen);
6757 return ret;
6760 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
6762 struct WS_addrinfoW *ret, *infoW;
6764 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
6765 while (info->ai_next)
6767 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
6769 FreeAddrInfoW(ret);
6770 return NULL;
6772 infoW = infoW->ai_next;
6773 info = info->ai_next;
6775 return ret;
6778 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
6780 struct WS_addrinfo *ret;
6782 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
6783 ret->ai_flags = ai->ai_flags;
6784 ret->ai_family = ai->ai_family;
6785 ret->ai_socktype = ai->ai_socktype;
6786 ret->ai_protocol = ai->ai_protocol;
6787 ret->ai_addrlen = ai->ai_addrlen;
6788 ret->ai_canonname = NULL;
6789 ret->ai_addr = NULL;
6790 ret->ai_next = NULL;
6791 if (ai->ai_canonname)
6793 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
6794 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
6796 HeapFree(GetProcessHeap(), 0, ret);
6797 return NULL;
6799 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
6801 if (ai->ai_addr)
6803 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
6805 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
6806 HeapFree(GetProcessHeap(), 0, ret);
6807 return NULL;
6809 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
6811 return ret;
6814 /***********************************************************************
6815 * GetAddrInfoExW (WS2_32.@)
6817 int WINAPI GetAddrInfoExW(const WCHAR *name, const WCHAR *servname, DWORD namespace, GUID *namespace_id,
6818 const ADDRINFOEXW *hints, ADDRINFOEXW **result, struct timeval *timeout, OVERLAPPED *overlapped,
6819 LPLOOKUPSERVICE_COMPLETION_ROUTINE completion_routine, HANDLE *handle)
6821 FIXME("(%s %s %x %s %p %p %p %p %p %p)\n", debugstr_w(name), debugstr_w(servname), namespace,
6822 debugstr_guid(namespace_id), hints, result, timeout, overlapped, completion_routine, handle);
6823 return WSAHOST_NOT_FOUND;
6826 /***********************************************************************
6827 * GetAddrInfoW (WS2_32.@)
6829 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
6831 int ret = EAI_MEMORY, len, i;
6832 char *nodenameA = NULL, *servnameA = NULL;
6833 struct WS_addrinfo *resA, *hintsA = NULL;
6834 WCHAR *local_nodenameW = (WCHAR *)nodename;
6836 TRACE("nodename %s, servname %s, hints %p, result %p\n",
6837 debugstr_w(nodename), debugstr_w(servname), hints, res);
6839 *res = NULL;
6840 if (nodename)
6842 /* Is this an IDN? Most likely if any char is above the Ascii table, this
6843 * is the simplest validation possible, further validation will be done by
6844 * the native getaddrinfo() */
6845 for (i = 0; nodename[i]; i++)
6847 if (nodename[i] > 'z')
6848 break;
6850 if (nodename[i])
6852 if (hints && (hints->ai_flags & WS_AI_DISABLE_IDN_ENCODING))
6854 /* Name requires conversion but it was disabled */
6855 ret = WSAHOST_NOT_FOUND;
6856 WSASetLastError(ret);
6857 goto end;
6860 len = IdnToAscii(0, nodename, -1, NULL, 0);
6861 if (!len)
6863 ERR("Failed to convert %s to punycode\n", debugstr_w(nodename));
6864 ret = EAI_FAIL;
6865 goto end;
6867 if (!(local_nodenameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) goto end;
6868 IdnToAscii(0, nodename, -1, local_nodenameW, len);
6871 if (local_nodenameW)
6873 len = WideCharToMultiByte(CP_ACP, 0, local_nodenameW, -1, NULL, 0, NULL, NULL);
6874 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) goto end;
6875 WideCharToMultiByte(CP_ACP, 0, local_nodenameW, -1, nodenameA, len, NULL, NULL);
6877 if (servname)
6879 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
6880 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len))) goto end;
6881 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
6884 if (hints) hintsA = addrinfo_WtoA(hints);
6885 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
6886 WS_freeaddrinfo(hintsA);
6888 if (!ret)
6890 *res = addrinfo_list_AtoW(resA);
6891 WS_freeaddrinfo(resA);
6894 end:
6895 if (local_nodenameW != nodename)
6896 HeapFree(GetProcessHeap(), 0, local_nodenameW);
6897 HeapFree(GetProcessHeap(), 0, nodenameA);
6898 HeapFree(GetProcessHeap(), 0, servnameA);
6899 return ret;
6902 /***********************************************************************
6903 * FreeAddrInfoW (WS2_32.@)
6905 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
6907 while (ai)
6909 ADDRINFOW *next;
6910 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
6911 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
6912 next = ai->ai_next;
6913 HeapFree(GetProcessHeap(), 0, ai);
6914 ai = next;
6918 /***********************************************************************
6919 * FreeAddrInfoExW (WS2_32.@)
6921 void WINAPI FreeAddrInfoExW(ADDRINFOEXW *ai)
6923 FIXME("%p\n", ai);
6926 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
6927 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
6929 #ifdef HAVE_GETNAMEINFO
6930 int ret;
6931 union generic_unix_sockaddr sa_u;
6932 unsigned int size;
6934 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
6935 serv, servlen, flags);
6937 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
6938 if (!size)
6940 SetLastError(WSAEFAULT);
6941 return WSA_NOT_ENOUGH_MEMORY;
6943 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
6944 return convert_eai_u2w(ret);
6945 #else
6946 FIXME("getnameinfo() failed, not found during buildtime.\n");
6947 return EAI_FAIL;
6948 #endif
6951 int WINAPI GetNameInfoW(const SOCKADDR *sa, WS_socklen_t salen, PWCHAR host,
6952 DWORD hostlen, PWCHAR serv, DWORD servlen, INT flags)
6954 int ret;
6955 char *hostA = NULL, *servA = NULL;
6957 if (host && (!(hostA = HeapAlloc(GetProcessHeap(), 0, hostlen)))) return EAI_MEMORY;
6958 if (serv && (!(servA = HeapAlloc(GetProcessHeap(), 0, servlen))))
6960 HeapFree(GetProcessHeap(), 0, hostA);
6961 return EAI_MEMORY;
6964 ret = WS_getnameinfo(sa, salen, hostA, hostlen, servA, servlen, flags);
6965 if (!ret)
6967 if (host) MultiByteToWideChar(CP_ACP, 0, hostA, -1, host, hostlen);
6968 if (serv) MultiByteToWideChar(CP_ACP, 0, servA, -1, serv, servlen);
6971 HeapFree(GetProcessHeap(), 0, hostA);
6972 HeapFree(GetProcessHeap(), 0, servA);
6973 return ret;
6976 /***********************************************************************
6977 * getservbyport (WS2_32.56)
6979 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
6981 struct WS_servent* retval = NULL;
6982 #ifdef HAVE_GETSERVBYPORT
6983 struct servent* serv;
6984 char *proto_str = NULL;
6986 if (proto && *proto)
6988 if (!(proto_str = strdup_lower(proto))) return NULL;
6990 EnterCriticalSection( &csWSgetXXXbyYYY );
6991 if( (serv = getservbyport(port, proto_str)) != NULL ) {
6992 retval = WS_dup_se(serv);
6994 else SetLastError(WSANO_DATA);
6995 LeaveCriticalSection( &csWSgetXXXbyYYY );
6996 HeapFree( GetProcessHeap(), 0, proto_str );
6997 #endif
6998 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
6999 return retval;
7003 /***********************************************************************
7004 * gethostname (WS2_32.57)
7006 int WINAPI WS_gethostname(char *name, int namelen)
7008 char buf[256];
7009 int len;
7011 TRACE("name %p, len %d\n", name, namelen);
7013 if (!name)
7015 SetLastError(WSAEFAULT);
7016 return SOCKET_ERROR;
7019 if (gethostname(buf, sizeof(buf)) != 0)
7021 SetLastError(wsaErrno());
7022 return SOCKET_ERROR;
7025 TRACE("<- '%s'\n", buf);
7026 len = strlen(buf);
7027 if (len > 15)
7028 WARN("Windows supports NetBIOS name length up to 15 bytes!\n");
7029 if (namelen <= len)
7031 SetLastError(WSAEFAULT);
7032 WARN("<- not enough space for hostname, required %d, got %d!\n", len + 1, namelen);
7033 return SOCKET_ERROR;
7035 strcpy(name, buf);
7036 return 0;
7040 /* ------------------------------------- Windows sockets extensions -- *
7042 * ------------------------------------------------------------------- */
7044 /***********************************************************************
7045 * WSAEnumNetworkEvents (WS2_32.36)
7047 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
7049 int ret;
7050 int i;
7051 int errors[FD_MAX_EVENTS];
7053 TRACE("%04lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
7055 SERVER_START_REQ( get_socket_event )
7057 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
7058 req->service = TRUE;
7059 req->c_event = wine_server_obj_handle( hEvent );
7060 wine_server_set_reply( req, errors, sizeof(errors) );
7061 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
7063 SERVER_END_REQ;
7064 if (!ret)
7066 for (i = 0; i < FD_MAX_EVENTS; i++)
7067 lpEvent->iErrorCode[i] = NtStatusToWSAError(errors[i]);
7068 return 0;
7070 SetLastError(WSAEINVAL);
7071 return SOCKET_ERROR;
7074 /***********************************************************************
7075 * WSAEventSelect (WS2_32.39)
7077 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
7079 int ret;
7081 TRACE("%04lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
7083 SERVER_START_REQ( set_socket_event )
7085 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
7086 req->mask = lEvent;
7087 req->event = wine_server_obj_handle( hEvent );
7088 req->window = 0;
7089 req->msg = 0;
7090 ret = wine_server_call( req );
7092 SERVER_END_REQ;
7093 if (!ret) return 0;
7094 SetLastError(WSAEINVAL);
7095 return SOCKET_ERROR;
7098 /**********************************************************************
7099 * WSAGetOverlappedResult (WS2_32.40)
7101 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
7102 LPDWORD lpcbTransfer, BOOL fWait,
7103 LPDWORD lpdwFlags )
7105 NTSTATUS status;
7107 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
7108 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
7110 if ( lpOverlapped == NULL )
7112 ERR( "Invalid pointer\n" );
7113 SetLastError(WSA_INVALID_PARAMETER);
7114 return FALSE;
7117 status = lpOverlapped->Internal;
7118 if (status == STATUS_PENDING)
7120 if (!fWait)
7122 SetLastError( WSA_IO_INCOMPLETE );
7123 return FALSE;
7126 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
7127 INFINITE ) == WAIT_FAILED)
7128 return FALSE;
7129 status = lpOverlapped->Internal;
7132 if ( lpcbTransfer )
7133 *lpcbTransfer = lpOverlapped->InternalHigh;
7135 if ( lpdwFlags )
7136 *lpdwFlags = lpOverlapped->u.s.Offset;
7138 if (status) SetLastError( RtlNtStatusToDosError(status) );
7139 return !status;
7143 /***********************************************************************
7144 * WSAAsyncSelect (WS2_32.101)
7146 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
7148 int ret;
7150 TRACE("%04lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
7152 SERVER_START_REQ( set_socket_event )
7154 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
7155 req->mask = lEvent;
7156 req->event = 0;
7157 req->window = wine_server_user_handle( hWnd );
7158 req->msg = uMsg;
7159 ret = wine_server_call( req );
7161 SERVER_END_REQ;
7162 if (!ret) return 0;
7163 SetLastError(WSAEINVAL);
7164 return SOCKET_ERROR;
7167 /***********************************************************************
7168 * WSACreateEvent (WS2_32.31)
7171 WSAEVENT WINAPI WSACreateEvent(void)
7173 /* Create a manual-reset event, with initial state: unsignaled */
7174 TRACE("\n");
7176 return CreateEventW(NULL, TRUE, FALSE, NULL);
7179 /***********************************************************************
7180 * WSACloseEvent (WS2_32.29)
7183 BOOL WINAPI WSACloseEvent(WSAEVENT event)
7185 TRACE ("event=%p\n", event);
7187 return CloseHandle(event);
7190 /***********************************************************************
7191 * WSASocketA (WS2_32.78)
7194 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
7195 LPWSAPROTOCOL_INFOA lpProtocolInfo,
7196 GROUP g, DWORD dwFlags)
7198 INT len;
7199 WSAPROTOCOL_INFOW info;
7201 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
7202 af, type, protocol, lpProtocolInfo, g, dwFlags);
7204 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
7206 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
7207 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
7208 info.szProtocol, WSAPROTOCOL_LEN + 1);
7210 if (!len)
7212 SetLastError(WSAEINVAL);
7213 return SOCKET_ERROR;
7216 return WSASocketW(af, type, protocol, &info, g, dwFlags);
7219 /***********************************************************************
7220 * WSASocketW (WS2_32.79)
7223 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
7224 LPWSAPROTOCOL_INFOW lpProtocolInfo,
7225 GROUP g, DWORD dwFlags)
7227 SOCKET ret;
7228 DWORD err;
7229 int unixaf, unixtype, ipxptype = -1;
7232 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
7233 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
7236 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
7237 af, type, protocol, lpProtocolInfo, g, dwFlags );
7239 if (!num_startup)
7241 err = WSANOTINITIALISED;
7242 goto done;
7245 /* hack for WSADuplicateSocket */
7246 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
7247 ret = lpProtocolInfo->dwServiceFlags3;
7248 TRACE("\tgot duplicate %04lx\n", ret);
7249 return ret;
7252 if (lpProtocolInfo)
7254 if (af == FROM_PROTOCOL_INFO || !af)
7255 af = lpProtocolInfo->iAddressFamily;
7256 if (type == FROM_PROTOCOL_INFO || !type)
7257 type = lpProtocolInfo->iSocketType;
7258 if (protocol == FROM_PROTOCOL_INFO || !protocol)
7259 protocol = lpProtocolInfo->iProtocol;
7262 if (!type && (af || protocol))
7264 int autoproto = protocol;
7265 WSAPROTOCOL_INFOW infow;
7267 /* default to the first valid protocol */
7268 if (!autoproto)
7269 autoproto = valid_protocols[0];
7270 else if(IS_IPX_PROTO(autoproto))
7271 autoproto = WS_NSPROTO_IPX;
7273 if (WS_EnterSingleProtocolW(autoproto, &infow))
7275 type = infow.iSocketType;
7277 /* after win2003 it's no longer possible to pass AF_UNSPEC
7278 using the protocol info struct */
7279 if (!lpProtocolInfo && af == WS_AF_UNSPEC)
7280 af = infow.iAddressFamily;
7285 Windows has an extension to the IPX protocol that allows one to create sockets
7286 and set the IPX packet type at the same time, to do that a caller will use
7287 a protocol like NSPROTO_IPX + <PACKET TYPE>
7289 if (IS_IPX_PROTO(protocol))
7290 ipxptype = protocol - WS_NSPROTO_IPX;
7292 /* convert the socket family, type and protocol */
7293 unixaf = convert_af_w2u(af);
7294 unixtype = convert_socktype_w2u(type);
7295 protocol = convert_proto_w2u(protocol);
7296 if (unixaf == AF_UNSPEC) unixaf = -1;
7298 /* filter invalid parameters */
7299 if (protocol < 0)
7301 /* the type could not be converted */
7302 if (type && unixtype < 0)
7304 err = WSAESOCKTNOSUPPORT;
7305 goto done;
7308 err = WSAEPROTONOSUPPORT;
7309 goto done;
7311 if (unixaf < 0)
7313 /* both family and protocol can't be invalid */
7314 if (protocol <= 0)
7316 err = WSAEINVAL;
7317 goto done;
7320 /* family could not be converted and neither socket type */
7321 if (unixtype < 0 && af >= 0)
7324 err = WSAESOCKTNOSUPPORT;
7325 goto done;
7328 err = WSAEAFNOSUPPORT;
7329 goto done;
7332 SERVER_START_REQ( create_socket )
7334 req->family = unixaf;
7335 req->type = unixtype;
7336 req->protocol = protocol;
7337 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
7338 req->attributes = (dwFlags & WSA_FLAG_NO_HANDLE_INHERIT) ? 0 : OBJ_INHERIT;
7339 req->flags = dwFlags & ~WSA_FLAG_NO_HANDLE_INHERIT;
7340 set_error( wine_server_call( req ) );
7341 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
7343 SERVER_END_REQ;
7344 if (ret)
7346 TRACE("\tcreated %04lx\n", ret );
7347 if (ipxptype > 0)
7348 set_ipx_packettype(ret, ipxptype);
7350 /* ensure IP_DONTFRAGMENT is disabled, in Linux the global default can be enabled */
7351 if (unixaf == AF_INET || unixaf == AF_INET6)
7352 set_dont_fragment(ret, unixaf == AF_INET6 ? IPPROTO_IPV6 : IPPROTO_IP, FALSE);
7354 #ifdef IPV6_V6ONLY
7355 if (unixaf == AF_INET6)
7357 int fd = get_sock_fd(ret, 0, NULL);
7358 if (fd != -1)
7360 /* IPV6_V6ONLY is set by default on Windows */
7361 int enable = 1;
7362 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)))
7363 WARN("\tsetting IPV6_V6ONLY failed - errno = %i\n", errno);
7364 release_sock_fd(ret, fd);
7367 #endif
7368 return ret;
7371 err = GetLastError();
7372 if (err == WSAEACCES) /* raw socket denied */
7374 if (type == SOCK_RAW)
7375 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
7376 else
7377 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
7379 else
7381 /* invalid combination of valid parameters, like SOCK_STREAM + IPPROTO_UDP */
7382 if (err == WSAEINVAL)
7383 err = WSAESOCKTNOSUPPORT;
7384 else if (err == WSAEOPNOTSUPP)
7385 err = WSAEPROTONOSUPPORT;
7388 done:
7389 WARN("\t\tfailed, error %d!\n", err);
7390 SetLastError(err);
7391 return INVALID_SOCKET;
7394 /***********************************************************************
7395 * WSAJoinLeaf (WS2_32.58)
7398 SOCKET WINAPI WSAJoinLeaf(
7399 SOCKET s,
7400 const struct WS_sockaddr *addr,
7401 int addrlen,
7402 LPWSABUF lpCallerData,
7403 LPWSABUF lpCalleeData,
7404 LPQOS lpSQOS,
7405 LPQOS lpGQOS,
7406 DWORD dwFlags)
7408 FIXME("stub.\n");
7409 return INVALID_SOCKET;
7412 /***********************************************************************
7413 * __WSAFDIsSet (WS2_32.151)
7415 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
7417 int i = set->fd_count, ret = 0;
7419 while (i--)
7420 if (set->fd_array[i] == s)
7422 ret = 1;
7423 break;
7426 TRACE("(socket %04lx, fd_set %p, count %i) <- %d\n", s, set, set->fd_count, ret);
7427 return ret;
7430 /***********************************************************************
7431 * WSAIsBlocking (WS2_32.114)
7433 BOOL WINAPI WSAIsBlocking(void)
7435 /* By default WinSock should set all its sockets to non-blocking mode
7436 * and poll in PeekMessage loop when processing "blocking" ones. This
7437 * function is supposed to tell if the program is in this loop. Our
7438 * blocking calls are truly blocking so we always return FALSE.
7440 * Note: It is allowed to call this function without prior WSAStartup().
7443 TRACE("\n");
7444 return FALSE;
7447 /***********************************************************************
7448 * WSACancelBlockingCall (WS2_32.113)
7450 INT WINAPI WSACancelBlockingCall(void)
7452 TRACE("\n");
7453 return 0;
7456 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
7458 FIXME("How was this called?\n");
7459 return x();
7463 /***********************************************************************
7464 * WSASetBlockingHook (WS2_32.109)
7466 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
7468 FARPROC prev = blocking_hook;
7469 blocking_hook = lpBlockFunc;
7470 TRACE("hook %p\n", lpBlockFunc);
7471 return prev;
7475 /***********************************************************************
7476 * WSAUnhookBlockingHook (WS2_32.110)
7478 INT WINAPI WSAUnhookBlockingHook(void)
7480 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
7481 return 0;
7485 /* ----------------------------------- end of API stuff */
7487 /* ----------------------------------- helper functions -
7489 * TODO: Merge WS_dup_..() stuff into one function that
7490 * would operate with a generic structure containing internal
7491 * pointers (via a template of some kind).
7494 static int list_size(char** l, int item_size)
7496 int i,j = 0;
7497 if(l)
7498 { for(i=0;l[i];i++)
7499 j += (item_size) ? item_size : strlen(l[i]) + 1;
7500 j += (i + 1) * sizeof(char*); }
7501 return j;
7504 static int list_dup(char** l_src, char** l_to, int item_size)
7506 char *p;
7507 int i;
7509 for (i = 0; l_src[i]; i++) ;
7510 p = (char *)(l_to + i + 1);
7511 for (i = 0; l_src[i]; i++)
7513 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
7514 memcpy(p, l_src[i], count);
7515 l_to[i] = p;
7516 p += count;
7518 l_to[i] = NULL;
7519 return p - (char *)l_to;
7522 /* ----- hostent */
7524 /* create a hostent entry
7526 * Creates the entry with enough memory for the name, aliases
7527 * addresses, and the address pointers. Also copies the name
7528 * and sets up all the pointers.
7530 * NOTE: The alias and address lists must be allocated with room
7531 * for the NULL item terminating the list. This is true even if
7532 * the list has no items ("aliases" and "addresses" must be
7533 * at least "1", a truly empty list is invalid).
7535 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length)
7537 struct WS_hostent *p_to;
7538 char *p;
7539 int size = (sizeof(struct WS_hostent) +
7540 strlen(name) + 1 +
7541 sizeof(char *) * aliases +
7542 aliases_size +
7543 sizeof(char *) * addresses +
7544 address_length * (addresses - 1)), i;
7546 if (!(p_to = check_buffer_he(size))) return NULL;
7547 memset(p_to, 0, size);
7549 /* Use the memory in the same way winsock does.
7550 * First set the pointer for aliases, second set the pointers for addresses.
7551 * Third fill the addresses indexes, fourth jump aliases names size.
7552 * Fifth fill the hostname.
7553 * NOTE: This method is valid for OS version's >= XP.
7555 p = (char *)(p_to + 1);
7556 p_to->h_aliases = (char **)p;
7557 p += sizeof(char *)*aliases;
7559 p_to->h_addr_list = (char **)p;
7560 p += sizeof(char *)*addresses;
7562 for (i = 0, addresses--; i < addresses; i++, p += address_length)
7563 p_to->h_addr_list[i] = p;
7565 /* NOTE: h_aliases must be filled in manually because we don't know each string
7566 * size, leave these pointers NULL (already set to NULL by memset earlier).
7568 p += aliases_size;
7570 p_to->h_name = p;
7571 strcpy(p, name);
7573 return p_to;
7576 /* duplicate hostent entry
7577 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
7578 * Ditto for protoent and servent.
7580 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
7582 int i, addresses = 0, alias_size = 0;
7583 struct WS_hostent *p_to;
7584 char *p;
7586 for( i = 0; p_he->h_aliases[i]; i++) alias_size += strlen(p_he->h_aliases[i]) + 1;
7587 while (p_he->h_addr_list[addresses]) addresses++;
7589 p_to = WS_create_he(p_he->h_name, i + 1, alias_size, addresses + 1, p_he->h_length);
7591 if (!p_to) return NULL;
7592 p_to->h_addrtype = convert_af_u2w(p_he->h_addrtype);
7593 p_to->h_length = p_he->h_length;
7595 for(i = 0, p = p_to->h_addr_list[0]; p_he->h_addr_list[i]; i++, p += p_to->h_length)
7596 memcpy(p, p_he->h_addr_list[i], p_to->h_length);
7598 /* Fill the aliases after the IP data */
7599 for(i = 0; p_he->h_aliases[i]; i++)
7601 p_to->h_aliases[i] = p;
7602 strcpy(p, p_he->h_aliases[i]);
7603 p += strlen(p) + 1;
7606 return p_to;
7609 /* ----- protoent */
7611 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
7613 char *p;
7614 struct WS_protoent *p_to;
7616 int size = (sizeof(*p_pe) +
7617 strlen(p_pe->p_name) + 1 +
7618 list_size(p_pe->p_aliases, 0));
7620 if (!(p_to = check_buffer_pe(size))) return NULL;
7621 p_to->p_proto = p_pe->p_proto;
7623 p = (char *)(p_to + 1);
7624 p_to->p_name = p;
7625 strcpy(p, p_pe->p_name);
7626 p += strlen(p) + 1;
7628 p_to->p_aliases = (char **)p;
7629 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
7630 return p_to;
7633 /* ----- servent */
7635 static struct WS_servent *WS_dup_se(const struct servent* p_se)
7637 char *p;
7638 struct WS_servent *p_to;
7640 int size = (sizeof(*p_se) +
7641 strlen(p_se->s_proto) + 1 +
7642 strlen(p_se->s_name) + 1 +
7643 list_size(p_se->s_aliases, 0));
7645 if (!(p_to = check_buffer_se(size))) return NULL;
7646 p_to->s_port = p_se->s_port;
7648 p = (char *)(p_to + 1);
7649 p_to->s_name = p;
7650 strcpy(p, p_se->s_name);
7651 p += strlen(p) + 1;
7653 p_to->s_proto = p;
7654 strcpy(p, p_se->s_proto);
7655 p += strlen(p) + 1;
7657 p_to->s_aliases = (char **)p;
7658 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
7659 return p_to;
7663 /***********************************************************************
7664 * WSARecv (WS2_32.67)
7666 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
7667 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
7668 LPWSAOVERLAPPED lpOverlapped,
7669 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
7671 return WS2_recv_base(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
7672 NULL, NULL, lpOverlapped, lpCompletionRoutine, NULL);
7675 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
7676 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
7677 struct WS_sockaddr *lpFrom,
7678 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
7679 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
7680 LPWSABUF lpControlBuffer )
7682 unsigned int i, options;
7683 int n, fd, err, overlapped, flags;
7684 struct ws2_async *wsa = NULL, localwsa;
7685 BOOL is_blocking;
7686 DWORD timeout_start = GetTickCount();
7687 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
7689 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
7690 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
7691 (lpFromlen ? *lpFromlen : -1),
7692 lpOverlapped, lpCompletionRoutine);
7694 fd = get_sock_fd( s, FILE_READ_DATA, &options );
7695 TRACE( "fd=%d, options=%x\n", fd, options );
7697 if (fd == -1) return SOCKET_ERROR;
7699 if (*lpFlags & WS_MSG_OOB)
7701 /* It's invalid to receive OOB data from an OOBINLINED socket
7702 * as OOB data is turned into normal data. */
7703 i = sizeof(n);
7704 if (!getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, (char*) &n, &i) && n)
7706 err = WSAEINVAL;
7707 goto error;
7711 overlapped = (lpOverlapped || lpCompletionRoutine) &&
7712 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
7713 if (overlapped || dwBufferCount > 1)
7715 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[dwBufferCount]))))
7717 err = WSAEFAULT;
7718 goto error;
7721 else
7722 wsa = &localwsa;
7724 wsa->hSocket = SOCKET2HANDLE(s);
7725 wsa->flags = *lpFlags;
7726 wsa->lpFlags = lpFlags;
7727 wsa->addr = lpFrom;
7728 wsa->addrlen.ptr = lpFromlen;
7729 wsa->control = lpControlBuffer;
7730 wsa->n_iovecs = dwBufferCount;
7731 wsa->first_iovec = 0;
7732 for (i = 0; i < dwBufferCount; i++)
7734 /* check buffer first to trigger write watches */
7735 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
7737 err = WSAEFAULT;
7738 goto error;
7740 wsa->iovec[i].iov_base = lpBuffers[i].buf;
7741 wsa->iovec[i].iov_len = lpBuffers[i].len;
7744 flags = convert_flags(wsa->flags);
7745 for (;;)
7747 n = WS2_recv( fd, wsa, flags );
7748 if (n == -1)
7750 /* Unix-like systems return EINVAL when attempting to read OOB data from
7751 * an empty socket buffer, convert that to a Windows expected return. */
7752 if ((flags & MSG_OOB) && errno == EINVAL)
7753 errno = EWOULDBLOCK;
7755 if (errno != EAGAIN)
7757 int loc_errno = errno;
7758 err = wsaErrno();
7759 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
7760 goto error;
7763 else if (lpNumberOfBytesRecvd) *lpNumberOfBytesRecvd = n;
7765 if (overlapped)
7767 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
7769 wsa->user_overlapped = lpOverlapped;
7770 wsa->completion_func = lpCompletionRoutine;
7771 release_sock_fd( s, fd );
7773 if (n == -1)
7775 iosb->u.Status = STATUS_PENDING;
7776 iosb->Information = 0;
7778 if (wsa->completion_func)
7779 err = register_async( ASYNC_TYPE_READ, wsa->hSocket, WS2_async_recv, wsa, NULL,
7780 ws2_async_apc, wsa, iosb );
7781 else
7782 err = register_async( ASYNC_TYPE_READ, wsa->hSocket, WS2_async_recv, wsa, lpOverlapped->hEvent,
7783 NULL, (void *)cvalue, iosb );
7785 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
7786 SetLastError(NtStatusToWSAError( err ));
7787 return SOCKET_ERROR;
7790 iosb->u.Status = STATUS_SUCCESS;
7791 iosb->Information = n;
7792 if (!wsa->completion_func)
7794 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
7795 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
7796 HeapFree( GetProcessHeap(), 0, wsa );
7798 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
7799 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
7800 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7801 return 0;
7804 if (n != -1) break;
7806 if ((err = _is_blocking( s, &is_blocking )))
7808 err = NtStatusToWSAError( err );
7809 goto error;
7812 if ( is_blocking )
7814 struct pollfd pfd;
7815 int poll_timeout = -1;
7816 INT64 timeout = get_rcvsnd_timeo(fd, TRUE);
7818 if (timeout)
7820 timeout -= GetTickCount() - timeout_start;
7821 if (timeout < 0) poll_timeout = 0;
7822 else poll_timeout = timeout <= INT_MAX ? timeout : INT_MAX;
7825 pfd.fd = fd;
7826 pfd.events = POLLIN;
7827 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
7829 if (!poll_timeout || !poll( &pfd, 1, poll_timeout ))
7831 err = WSAETIMEDOUT;
7832 /* a timeout is not fatal */
7833 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7834 goto error;
7837 else
7839 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7840 err = WSAEWOULDBLOCK;
7841 goto error;
7845 TRACE(" -> %i bytes\n", n);
7846 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
7847 release_sock_fd( s, fd );
7848 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7849 SetLastError(ERROR_SUCCESS);
7851 return 0;
7853 error:
7854 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
7855 release_sock_fd( s, fd );
7856 WARN(" -> ERROR %d\n", err);
7857 SetLastError( err );
7858 return SOCKET_ERROR;
7861 /***********************************************************************
7862 * WSARecvFrom (WS2_32.69)
7864 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
7865 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
7866 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
7867 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
7870 return WS2_recv_base( s, lpBuffers, dwBufferCount,
7871 lpNumberOfBytesRecvd, lpFlags,
7872 lpFrom, lpFromlen,
7873 lpOverlapped, lpCompletionRoutine, NULL );
7876 /***********************************************************************
7877 * WSCInstallProvider (WS2_32.88)
7879 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
7880 LPCWSTR lpszProviderDllPath,
7881 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
7882 DWORD dwNumberOfEntries,
7883 LPINT lpErrno )
7885 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
7886 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
7887 dwNumberOfEntries, lpErrno);
7888 *lpErrno = 0;
7889 return 0;
7893 /***********************************************************************
7894 * WSCDeinstallProvider (WS2_32.83)
7896 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
7898 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
7899 *lpErrno = 0;
7900 return 0;
7904 /***********************************************************************
7905 * WSAAccept (WS2_32.26)
7907 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
7908 LPCONDITIONPROC lpfnCondition, DWORD_PTR dwCallbackData)
7911 int ret = 0, size;
7912 WSABUF CallerId, CallerData, CalleeId, CalleeData;
7913 /* QOS SQOS, GQOS; */
7914 GROUP g;
7915 SOCKET cs;
7916 SOCKADDR src_addr, dst_addr;
7918 TRACE("socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
7919 s, addr, addrlen, lpfnCondition, dwCallbackData);
7921 cs = WS_accept(s, addr, addrlen);
7922 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
7923 if (!lpfnCondition) return cs;
7925 if (addr && addrlen)
7927 CallerId.buf = (char *)addr;
7928 CallerId.len = *addrlen;
7930 else
7932 size = sizeof(src_addr);
7933 WS_getpeername(cs, &src_addr, &size);
7934 CallerId.buf = (char *)&src_addr;
7935 CallerId.len = size;
7937 CallerData.buf = NULL;
7938 CallerData.len = 0;
7940 size = sizeof(dst_addr);
7941 WS_getsockname(cs, &dst_addr, &size);
7943 CalleeId.buf = (char *)&dst_addr;
7944 CalleeId.len = sizeof(dst_addr);
7946 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
7947 &CalleeId, &CalleeData, &g, dwCallbackData);
7949 switch (ret)
7951 case CF_ACCEPT:
7952 return cs;
7953 case CF_DEFER:
7954 SERVER_START_REQ( set_socket_deferred )
7956 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
7957 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
7958 if ( !wine_server_call_err ( req ) )
7960 SetLastError( WSATRY_AGAIN );
7961 WS_closesocket( cs );
7964 SERVER_END_REQ;
7965 return SOCKET_ERROR;
7966 case CF_REJECT:
7967 WS_closesocket(cs);
7968 SetLastError(WSAECONNREFUSED);
7969 return SOCKET_ERROR;
7970 default:
7971 FIXME("Unknown return type from Condition function\n");
7972 SetLastError(WSAENOTSOCK);
7973 return SOCKET_ERROR;
7977 /***********************************************************************
7978 * WSADuplicateSocketA (WS2_32.32)
7980 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
7982 return WS_DuplicateSocket(FALSE, s, dwProcessId, (LPWSAPROTOCOL_INFOW) lpProtocolInfo);
7985 /***********************************************************************
7986 * WSADuplicateSocketW (WS2_32.33)
7988 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
7990 return WS_DuplicateSocket(TRUE, s, dwProcessId, lpProtocolInfo);
7993 /***********************************************************************
7994 * WSAInstallServiceClassA (WS2_32.48)
7996 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
7998 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
7999 SetLastError(WSAEACCES);
8000 return SOCKET_ERROR;
8003 /***********************************************************************
8004 * WSAInstallServiceClassW (WS2_32.49)
8006 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
8008 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
8009 SetLastError(WSAEACCES);
8010 return SOCKET_ERROR;
8013 /***********************************************************************
8014 * WSARemoveServiceClass (WS2_32.70)
8016 int WINAPI WSARemoveServiceClass(LPGUID info)
8018 FIXME("Request to remove service %s\n", debugstr_guid(info));
8019 SetLastError(WSATYPE_NOT_FOUND);
8020 return SOCKET_ERROR;
8023 /***********************************************************************
8024 * inet_ntop (WS2_32.@)
8026 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
8028 #ifdef HAVE_INET_NTOP
8029 struct WS_in6_addr *in6;
8030 struct WS_in_addr *in;
8031 PCSTR pdst;
8033 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
8034 if (!buffer)
8036 SetLastError( STATUS_INVALID_PARAMETER );
8037 return NULL;
8040 switch (family)
8042 case WS_AF_INET:
8044 in = addr;
8045 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
8046 break;
8048 case WS_AF_INET6:
8050 in6 = addr;
8051 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
8052 break;
8054 default:
8055 SetLastError( WSAEAFNOSUPPORT );
8056 return NULL;
8059 if (!pdst) SetLastError( STATUS_INVALID_PARAMETER );
8060 return pdst;
8061 #else
8062 FIXME( "not supported on this platform\n" );
8063 SetLastError( WSAEAFNOSUPPORT );
8064 return NULL;
8065 #endif
8068 /***********************************************************************
8069 * inet_pton (WS2_32.@)
8071 INT WINAPI WS_inet_pton( INT family, PCSTR addr, PVOID buffer)
8073 #ifdef HAVE_INET_PTON
8074 int unixaf, ret;
8076 TRACE("family %d, addr %s, buffer (%p)\n", family, debugstr_a(addr), buffer);
8078 if (!addr || !buffer)
8080 SetLastError(WSAEFAULT);
8081 return SOCKET_ERROR;
8084 unixaf = convert_af_w2u(family);
8085 if (unixaf != AF_INET && unixaf != AF_INET6)
8087 SetLastError(WSAEAFNOSUPPORT);
8088 return SOCKET_ERROR;
8091 ret = inet_pton(unixaf, addr, buffer);
8092 if (ret == -1) SetLastError(wsaErrno());
8093 return ret;
8094 #else
8095 FIXME( "not supported on this platform\n" );
8096 SetLastError( WSAEAFNOSUPPORT );
8097 return SOCKET_ERROR;
8098 #endif
8101 /***********************************************************************
8102 * InetPtonW (WS2_32.@)
8104 INT WINAPI InetPtonW(INT family, PCWSTR addr, PVOID buffer)
8106 char *addrA;
8107 int len;
8108 INT ret;
8110 TRACE("family %d, addr %s, buffer (%p)\n", family, debugstr_w(addr), buffer);
8112 if (!addr)
8114 SetLastError(WSAEFAULT);
8115 return SOCKET_ERROR;
8118 len = WideCharToMultiByte(CP_ACP, 0, addr, -1, NULL, 0, NULL, NULL);
8119 if (!(addrA = HeapAlloc(GetProcessHeap(), 0, len)))
8121 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8122 return SOCKET_ERROR;
8124 WideCharToMultiByte(CP_ACP, 0, addr, -1, addrA, len, NULL, NULL);
8126 ret = WS_inet_pton(family, addrA, buffer);
8128 HeapFree(GetProcessHeap(), 0, addrA);
8129 return ret;
8132 /***********************************************************************
8133 * InetNtopW (WS2_32.@)
8135 PCWSTR WINAPI InetNtopW(INT family, PVOID addr, PWSTR buffer, SIZE_T len)
8137 char bufferA[WS_INET6_ADDRSTRLEN];
8138 PWSTR ret = NULL;
8140 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
8142 if (WS_inet_ntop(family, addr, bufferA, sizeof(bufferA)))
8144 if (MultiByteToWideChar(CP_ACP, 0, bufferA, -1, buffer, len))
8145 ret = buffer;
8146 else
8147 SetLastError(ERROR_INVALID_PARAMETER);
8149 return ret;
8152 /***********************************************************************
8153 * WSAStringToAddressA (WS2_32.80)
8155 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
8156 INT AddressFamily,
8157 LPWSAPROTOCOL_INFOA lpProtocolInfo,
8158 LPSOCKADDR lpAddress,
8159 LPINT lpAddressLength)
8161 INT res=0;
8162 LPSTR workBuffer=NULL,ptrPort;
8164 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
8165 lpProtocolInfo, lpAddress, lpAddressLength );
8167 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
8169 if (!AddressString)
8171 SetLastError(WSAEINVAL);
8172 return SOCKET_ERROR;
8175 if (lpProtocolInfo)
8176 FIXME("ProtocolInfo not implemented.\n");
8178 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
8179 strlen(AddressString) + 1);
8180 if (!workBuffer)
8182 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8183 return SOCKET_ERROR;
8186 strcpy(workBuffer, AddressString);
8188 switch(AddressFamily)
8190 case WS_AF_INET:
8192 struct in_addr inetaddr;
8194 /* If lpAddressLength is too small, tell caller the size we need */
8195 if (*lpAddressLength < sizeof(SOCKADDR_IN))
8197 *lpAddressLength = sizeof(SOCKADDR_IN);
8198 res = WSAEFAULT;
8199 break;
8201 *lpAddressLength = sizeof(SOCKADDR_IN);
8202 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
8204 ((LPSOCKADDR_IN)lpAddress)->sin_family = WS_AF_INET;
8206 ptrPort = strchr(workBuffer, ':');
8207 if(ptrPort)
8209 /* User may have entered an IPv6 and asked to parse as IPv4 */
8210 if(strchr(ptrPort + 1, ':'))
8212 res = WSAEINVAL;
8213 break;
8215 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
8216 *ptrPort = '\0';
8219 if(inet_aton(workBuffer, &inetaddr) > 0)
8221 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
8222 res = 0;
8224 else
8225 res = WSAEINVAL;
8227 break;
8229 case WS_AF_INET6:
8231 struct in6_addr inetaddr;
8232 char *ptrAddr = workBuffer;
8234 /* If lpAddressLength is too small, tell caller the size we need */
8235 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
8237 *lpAddressLength = sizeof(SOCKADDR_IN6);
8238 res = WSAEFAULT;
8239 break;
8241 #ifdef HAVE_INET_PTON
8242 *lpAddressLength = sizeof(SOCKADDR_IN6);
8243 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
8245 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
8247 /* Valid IPv6 addresses can also be surrounded by [ ], and in this case
8248 * a port number may follow after like in [fd12:3456:7890::1]:12345
8249 * We need to cut the brackets and find the port if any. */
8251 if(*workBuffer == '[')
8253 ptrPort = strchr(workBuffer, ']');
8254 if (!ptrPort)
8256 SetLastError(WSAEINVAL);
8257 return SOCKET_ERROR;
8260 if (ptrPort[1] == ':')
8261 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort + 2));
8263 *ptrPort = '\0';
8264 ptrAddr = workBuffer + 1;
8267 if(inet_pton(AF_INET6, ptrAddr, &inetaddr) > 0)
8269 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
8270 sizeof(struct in6_addr));
8271 res = 0;
8273 else
8274 #endif /* HAVE_INET_PTON */
8275 res = WSAEINVAL;
8277 break;
8279 default:
8280 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
8281 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
8282 res = WSAEINVAL;
8285 HeapFree(GetProcessHeap(), 0, workBuffer);
8287 if (!res) return 0;
8288 SetLastError(res);
8289 return SOCKET_ERROR;
8292 /***********************************************************************
8293 * WSAStringToAddressW (WS2_32.81)
8295 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
8296 * If this should be the case, it would be required to map these digits
8297 * to Unicode digits (0-9) using FoldString first.
8299 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
8300 INT AddressFamily,
8301 LPWSAPROTOCOL_INFOW lpProtocolInfo,
8302 LPSOCKADDR lpAddress,
8303 LPINT lpAddressLength)
8305 INT sBuffer,res=0;
8306 LPSTR workBuffer=NULL;
8307 WSAPROTOCOL_INFOA infoA;
8308 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
8310 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
8311 lpAddress, lpAddressLength );
8313 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
8315 /* if ProtocolInfo is available - convert to ANSI variant */
8316 if (lpProtocolInfo)
8318 lpProtoInfoA = &infoA;
8319 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
8321 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
8322 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
8324 SetLastError(WSAEINVAL);
8325 return SOCKET_ERROR;
8329 if (AddressString)
8331 /* Translate AddressString to ANSI code page - assumes that only
8332 standard digits 0-9 are used with this API call */
8333 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
8334 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
8336 if (workBuffer)
8338 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
8339 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
8340 lpAddress,lpAddressLength);
8341 HeapFree( GetProcessHeap(), 0, workBuffer );
8342 return res;
8344 else
8345 res = WSA_NOT_ENOUGH_MEMORY;
8347 else
8348 res = WSAEINVAL;
8350 SetLastError(res);
8351 return SOCKET_ERROR;
8354 /***********************************************************************
8355 * WSAAddressToStringA (WS2_32.27)
8357 * See WSAAddressToStringW
8359 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
8360 LPWSAPROTOCOL_INFOA info, LPSTR string,
8361 LPDWORD lenstr )
8363 DWORD size;
8364 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
8365 CHAR *p;
8367 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
8369 if (!sockaddr) return SOCKET_ERROR;
8370 if (!string || !lenstr) return SOCKET_ERROR;
8372 switch(sockaddr->sa_family)
8374 case WS_AF_INET:
8376 unsigned int long_ip = ntohl(((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr);
8377 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
8378 sprintf( buffer, "%u.%u.%u.%u:%u",
8379 (long_ip >> 24) & 0xff,
8380 (long_ip >> 16) & 0xff,
8381 (long_ip >> 8) & 0xff,
8382 long_ip & 0xff,
8383 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
8385 p = strchr( buffer, ':' );
8386 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
8387 break;
8389 case WS_AF_INET6:
8391 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
8392 size_t slen;
8394 buffer[0] = 0;
8395 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
8396 if ((sockaddr6->sin6_port))
8397 strcpy(buffer, "[");
8398 slen = strlen(buffer);
8399 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, &buffer[slen], sizeof(buffer) - slen))
8401 SetLastError(WSAEINVAL);
8402 return SOCKET_ERROR;
8404 if ((sockaddr6->sin6_scope_id))
8405 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
8406 if ((sockaddr6->sin6_port))
8407 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
8408 break;
8411 default:
8412 SetLastError(WSAEINVAL);
8413 return SOCKET_ERROR;
8416 size = strlen( buffer ) + 1;
8418 if (*lenstr < size)
8420 *lenstr = size;
8421 SetLastError(WSAEFAULT);
8422 return SOCKET_ERROR;
8425 TRACE("=> %s,%u bytes\n", debugstr_a(buffer), size);
8426 *lenstr = size;
8427 strcpy( string, buffer );
8428 return 0;
8431 /***********************************************************************
8432 * WSAAddressToStringW (WS2_32.28)
8434 * Convert a sockaddr address into a readable address string.
8436 * PARAMS
8437 * sockaddr [I] Pointer to a sockaddr structure.
8438 * len [I] Size of the sockaddr structure.
8439 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
8440 * string [I/O] Pointer to a buffer to receive the address string.
8441 * lenstr [I/O] Size of the receive buffer in WCHARs.
8443 * RETURNS
8444 * Success: 0
8445 * Failure: SOCKET_ERROR
8447 * NOTES
8448 * The 'info' parameter is ignored.
8450 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
8451 LPWSAPROTOCOL_INFOW info, LPWSTR string,
8452 LPDWORD lenstr )
8454 INT ret;
8455 DWORD size;
8456 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
8457 CHAR bufAddr[54];
8459 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
8461 size = *lenstr;
8462 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
8464 if (ret) return ret;
8466 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
8468 if (*lenstr < size)
8470 *lenstr = size;
8471 SetLastError(WSAEFAULT);
8472 return SOCKET_ERROR;
8475 TRACE("=> %s,%u bytes\n", debugstr_w(buffer), size);
8476 *lenstr = size;
8477 lstrcpyW( string, buffer );
8478 return 0;
8481 /***********************************************************************
8482 * WSAEnumNameSpaceProvidersA (WS2_32.34)
8484 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
8486 FIXME( "(%p %p) Stub!\n", len, buffer );
8487 return 0;
8490 /***********************************************************************
8491 * WSAEnumNameSpaceProvidersW (WS2_32.35)
8493 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
8495 FIXME( "(%p %p) Stub!\n", len, buffer );
8496 return 0;
8499 /***********************************************************************
8500 * WSAGetQOSByName (WS2_32.41)
8502 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
8504 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
8505 return FALSE;
8508 /***********************************************************************
8509 * WSAGetServiceClassInfoA (WS2_32.42)
8511 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
8512 LPWSASERVICECLASSINFOA info )
8514 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
8515 len, info );
8516 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8517 return SOCKET_ERROR;
8520 /***********************************************************************
8521 * WSAGetServiceClassInfoW (WS2_32.43)
8523 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
8524 LPWSASERVICECLASSINFOW info )
8526 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
8527 len, info );
8528 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8529 return SOCKET_ERROR;
8532 /***********************************************************************
8533 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
8535 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
8537 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
8538 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8539 return SOCKET_ERROR;
8542 /***********************************************************************
8543 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
8545 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
8547 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
8548 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8549 return SOCKET_ERROR;
8552 /***********************************************************************
8553 * WSALookupServiceBeginA (WS2_32.59)
8555 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
8556 DWORD dwControlFlags,
8557 LPHANDLE lphLookup)
8559 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
8560 lphLookup);
8561 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8562 return SOCKET_ERROR;
8565 /***********************************************************************
8566 * WSALookupServiceBeginW (WS2_32.60)
8568 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
8569 DWORD dwControlFlags,
8570 LPHANDLE lphLookup)
8572 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
8573 lphLookup);
8574 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8575 return SOCKET_ERROR;
8578 /***********************************************************************
8579 * WSALookupServiceEnd (WS2_32.61)
8581 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
8583 FIXME("(%p) Stub!\n", lookup );
8584 return 0;
8587 /***********************************************************************
8588 * WSALookupServiceNextA (WS2_32.62)
8590 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
8592 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
8593 SetLastError(WSA_E_NO_MORE);
8594 return SOCKET_ERROR;
8597 /***********************************************************************
8598 * WSALookupServiceNextW (WS2_32.63)
8600 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
8602 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
8603 SetLastError(WSA_E_NO_MORE);
8604 return SOCKET_ERROR;
8607 /***********************************************************************
8608 * WSANtohl (WS2_32.64)
8610 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
8612 TRACE( "(%04lx 0x%08x %p)\n", s, netlong, lphostlong );
8614 if (!lphostlong) return WSAEFAULT;
8616 *lphostlong = ntohl( netlong );
8617 return 0;
8620 /***********************************************************************
8621 * WSANtohs (WS2_32.65)
8623 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
8625 TRACE( "(%04lx 0x%08x %p)\n", s, netshort, lphostshort );
8627 if (!lphostshort) return WSAEFAULT;
8629 *lphostshort = ntohs( netshort );
8630 return 0;
8633 /***********************************************************************
8634 * WSAProviderConfigChange (WS2_32.66)
8636 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
8637 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
8639 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
8640 return SOCKET_ERROR;
8643 /***********************************************************************
8644 * WSARecvDisconnect (WS2_32.68)
8646 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
8648 TRACE( "(%04lx %p)\n", s, disconnectdata );
8650 return WS_shutdown( s, SD_RECEIVE );
8653 /***********************************************************************
8654 * WSASetServiceA (WS2_32.76)
8656 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
8658 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
8659 return 0;
8662 /***********************************************************************
8663 * WSASetServiceW (WS2_32.77)
8665 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
8667 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
8668 return 0;
8671 /***********************************************************************
8672 * WSCEnableNSProvider (WS2_32.84)
8674 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
8676 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
8677 return 0;
8680 /***********************************************************************
8681 * WSCGetProviderPath (WS2_32.86)
8683 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
8685 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
8687 if (!errcode || !provider || !len) return WSAEFAULT;
8689 *errcode = WSAEINVAL;
8690 return SOCKET_ERROR;
8693 /***********************************************************************
8694 * WSCInstallNameSpace (WS2_32.87)
8696 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
8697 DWORD version, LPGUID provider )
8699 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
8700 namespace, version, debugstr_guid(provider) );
8701 return 0;
8704 /***********************************************************************
8705 * WSCUnInstallNameSpace (WS2_32.89)
8707 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
8709 FIXME("(%s) Stub!\n", debugstr_guid(lpProviderId));
8710 return NO_ERROR;
8713 /***********************************************************************
8714 * WSCWriteProviderOrder (WS2_32.91)
8716 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
8718 FIXME("(%p 0x%08x) Stub!\n", entry, number);
8719 return 0;
8722 /***********************************************************************
8723 * WSANSPIoctl (WS2_32.91)
8725 INT WINAPI WSANSPIoctl( HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer,
8726 DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer,
8727 LPDWORD lpcbBytesReturned, LPWSACOMPLETION lpCompletion )
8729 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup, dwControlCode,
8730 lpvInBuffer, cbInBuffer, lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpCompletion);
8731 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8732 return SOCKET_ERROR;
8735 /*****************************************************************************
8736 * WSAEnumProtocolsA [WS2_32.@]
8738 * see function WSAEnumProtocolsW
8740 INT WINAPI WSAEnumProtocolsA( LPINT protocols, LPWSAPROTOCOL_INFOA buffer, LPDWORD len )
8742 return WS_EnumProtocols( FALSE, protocols, (LPWSAPROTOCOL_INFOW) buffer, len);
8745 /*****************************************************************************
8746 * WSAEnumProtocolsW [WS2_32.@]
8748 * Retrieves information about specified set of active network protocols.
8750 * PARAMS
8751 * protocols [I] Pointer to null-terminated array of protocol id's. NULL
8752 * retrieves information on all available protocols.
8753 * buffer [I] Pointer to a buffer to be filled with WSAPROTOCOL_INFO
8754 * structures.
8755 * len [I/O] Pointer to a variable specifying buffer size. On output
8756 * the variable holds the number of bytes needed when the
8757 * specified size is too small.
8759 * RETURNS
8760 * Success: number of WSAPROTOCOL_INFO structures in buffer.
8761 * Failure: SOCKET_ERROR
8763 * NOTES
8764 * NT4SP5 does not return SPX if protocols == NULL
8766 * BUGS
8767 * - NT4SP5 returns in addition these list of NETBIOS protocols
8768 * (address family 17), each entry two times one for socket type 2 and 5
8770 * iProtocol szProtocol
8771 * 0x80000000 \Device\NwlnkNb
8772 * 0xfffffffa \Device\NetBT_CBENT7
8773 * 0xfffffffb \Device\Nbf_CBENT7
8774 * 0xfffffffc \Device\NetBT_NdisWan5
8775 * 0xfffffffd \Device\NetBT_El9202
8776 * 0xfffffffe \Device\Nbf_El9202
8777 * 0xffffffff \Device\Nbf_NdisWan4
8779 * - there is no check that the operating system supports the returned
8780 * protocols
8782 INT WINAPI WSAEnumProtocolsW( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
8784 return WS_EnumProtocols( TRUE, protocols, buffer, len);
8787 /*****************************************************************************
8788 * WSCEnumProtocols [WS2_32.@]
8790 * PARAMS
8791 * protocols [I] Null-terminated array of iProtocol values.
8792 * buffer [O] Buffer of WSAPROTOCOL_INFOW structures.
8793 * len [I/O] Size of buffer on input/output.
8794 * errno [O] Error code.
8796 * RETURNS
8797 * Success: number of protocols to be reported on.
8798 * Failure: SOCKET_ERROR. error is in errno.
8800 * BUGS
8801 * Doesn't supply info on layered protocols.
8804 INT WINAPI WSCEnumProtocols( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len, LPINT err )
8806 INT ret = WSAEnumProtocolsW( protocols, buffer, len );
8808 if (ret == SOCKET_ERROR) *err = WSAENOBUFS;
8810 return ret;