regedit: Output an error message and exit with error code zero instead of calling...
[wine.git] / dlls / ws2_32 / socket.c
blob3f4691f02b781785c96550409b5dd9ad669667bf
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 typedef NTSTATUS async_callback_t( void *user, IO_STATUS_BLOCK *io, NTSTATUS status );
475 struct ws2_async_io
477 async_callback_t *callback; /* must be the first field */
478 struct ws2_async_io *next;
481 struct ws2_async_shutdown
483 struct ws2_async_io io;
484 HANDLE hSocket;
485 IO_STATUS_BLOCK iosb;
486 int type;
489 struct ws2_async
491 struct ws2_async_io io;
492 HANDLE hSocket;
493 LPWSAOVERLAPPED user_overlapped;
494 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
495 IO_STATUS_BLOCK local_iosb;
496 struct WS_sockaddr *addr;
497 union
499 int val; /* for send operations */
500 int *ptr; /* for recv operations */
501 } addrlen;
502 DWORD flags;
503 DWORD *lpFlags;
504 WSABUF *control;
505 unsigned int n_iovecs;
506 unsigned int first_iovec;
507 struct iovec iovec[1];
510 struct ws2_accept_async
512 struct ws2_async_io io;
513 HANDLE listen_socket;
514 HANDLE accept_socket;
515 LPOVERLAPPED user_overlapped;
516 ULONG_PTR cvalue;
517 PVOID buf; /* buffer to write data to */
518 int data_len;
519 int local_len;
520 int remote_len;
521 struct ws2_async *read;
524 struct ws2_transmitfile_async
526 struct ws2_async_io io;
527 char *buffer;
528 HANDLE file;
529 DWORD file_read;
530 DWORD file_bytes;
531 DWORD bytes_per_send;
532 TRANSMIT_FILE_BUFFERS buffers;
533 DWORD flags;
534 LARGE_INTEGER offset;
535 struct ws2_async write;
538 static struct ws2_async_io *async_io_freelist;
540 static void release_async_io( struct ws2_async_io *io )
542 for (;;)
544 struct ws2_async_io *next = async_io_freelist;
545 io->next = next;
546 if (InterlockedCompareExchangePointer( (void **)&async_io_freelist, io, next ) == next) return;
550 static struct ws2_async_io *alloc_async_io( DWORD size, async_callback_t callback )
552 /* first free remaining previous fileinfos */
554 struct ws2_async_io *io = InterlockedExchangePointer( (void **)&async_io_freelist, NULL );
556 while (io)
558 struct ws2_async_io *next = io->next;
559 HeapFree( GetProcessHeap(), 0, io );
560 io = next;
563 io = HeapAlloc( GetProcessHeap(), 0, size );
564 if (io) io->callback = callback;
565 return io;
568 static NTSTATUS register_async( int type, HANDLE handle, struct ws2_async_io *async, HANDLE event,
569 PIO_APC_ROUTINE apc, void *apc_context, IO_STATUS_BLOCK *io )
571 NTSTATUS status;
573 SERVER_START_REQ( register_async )
575 req->type = type;
576 req->async.handle = wine_server_obj_handle( handle );
577 req->async.user = wine_server_client_ptr( async );
578 req->async.iosb = wine_server_client_ptr( io );
579 req->async.event = wine_server_obj_handle( event );
580 req->async.apc = wine_server_client_ptr( apc );
581 req->async.apc_context = wine_server_client_ptr( apc_context );
582 status = wine_server_call( req );
584 SERVER_END_REQ;
586 return status;
589 /****************************************************************/
591 /* ----------------------------------- internal data */
593 /* ws_... struct conversion flags */
595 typedef struct /* WSAAsyncSelect() control struct */
597 HANDLE service, event, sock;
598 HWND hWnd;
599 UINT uMsg;
600 LONG lEvent;
601 } ws_select_info;
603 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
604 #define WS_MAX_UDP_DATAGRAM 1024
605 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
607 /* hostent's, servent's and protent's are stored in one buffer per thread,
608 * as documented on MSDN for the functions that return any of the buffers */
609 struct per_thread_data
611 int opentype;
612 struct WS_hostent *he_buffer;
613 struct WS_servent *se_buffer;
614 struct WS_protoent *pe_buffer;
615 struct pollfd *fd_cache;
616 unsigned int fd_count;
617 int he_len;
618 int se_len;
619 int pe_len;
620 char ntoa_buffer[16]; /* 4*3 digits + 3 '.' + 1 '\0' */
623 /* internal: routing description information */
624 struct route {
625 struct in_addr addr;
626 IF_INDEX interface;
627 DWORD metric, default_route;
630 static INT num_startup; /* reference counter */
631 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
633 /* function prototypes */
634 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length);
635 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
636 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
637 static struct WS_servent *WS_dup_se(const struct servent* p_se);
638 static int ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size);
640 int WSAIOCTL_GetInterfaceCount(void);
641 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
643 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus, ULONG Information );
645 #define MAP_OPTION(opt) { WS_##opt, opt }
647 static const int ws_flags_map[][2] =
649 MAP_OPTION( MSG_OOB ),
650 MAP_OPTION( MSG_PEEK ),
651 MAP_OPTION( MSG_DONTROUTE ),
652 MAP_OPTION( MSG_WAITALL ),
653 { WS_MSG_PARTIAL, 0 },
656 static const int ws_sock_map[][2] =
658 MAP_OPTION( SO_DEBUG ),
659 MAP_OPTION( SO_ACCEPTCONN ),
660 MAP_OPTION( SO_REUSEADDR ),
661 MAP_OPTION( SO_KEEPALIVE ),
662 MAP_OPTION( SO_DONTROUTE ),
663 MAP_OPTION( SO_BROADCAST ),
664 MAP_OPTION( SO_LINGER ),
665 MAP_OPTION( SO_OOBINLINE ),
666 MAP_OPTION( SO_SNDBUF ),
667 MAP_OPTION( SO_RCVBUF ),
668 MAP_OPTION( SO_ERROR ),
669 MAP_OPTION( SO_TYPE ),
670 #ifdef SO_RCVTIMEO
671 MAP_OPTION( SO_RCVTIMEO ),
672 #endif
673 #ifdef SO_SNDTIMEO
674 MAP_OPTION( SO_SNDTIMEO ),
675 #endif
678 static const int ws_tcp_map[][2] =
680 #ifdef TCP_NODELAY
681 MAP_OPTION( TCP_NODELAY ),
682 #endif
685 static const int ws_ip_map[][2] =
687 MAP_OPTION( IP_MULTICAST_IF ),
688 MAP_OPTION( IP_MULTICAST_TTL ),
689 MAP_OPTION( IP_MULTICAST_LOOP ),
690 MAP_OPTION( IP_ADD_MEMBERSHIP ),
691 MAP_OPTION( IP_DROP_MEMBERSHIP ),
692 MAP_OPTION( IP_OPTIONS ),
693 #ifdef IP_HDRINCL
694 MAP_OPTION( IP_HDRINCL ),
695 #endif
696 MAP_OPTION( IP_TOS ),
697 MAP_OPTION( IP_TTL ),
698 #ifdef IP_PKTINFO
699 MAP_OPTION( IP_PKTINFO ),
700 #endif
701 #ifdef IP_UNICAST_IF
702 MAP_OPTION( IP_UNICAST_IF ),
703 #endif
706 static const int ws_ipv6_map[][2] =
708 #ifdef IPV6_ADD_MEMBERSHIP
709 MAP_OPTION( IPV6_ADD_MEMBERSHIP ),
710 #endif
711 #ifdef IPV6_DROP_MEMBERSHIP
712 MAP_OPTION( IPV6_DROP_MEMBERSHIP ),
713 #endif
714 MAP_OPTION( IPV6_MULTICAST_IF ),
715 MAP_OPTION( IPV6_MULTICAST_HOPS ),
716 MAP_OPTION( IPV6_MULTICAST_LOOP ),
717 MAP_OPTION( IPV6_UNICAST_HOPS ),
718 MAP_OPTION( IPV6_V6ONLY ),
719 #ifdef IPV6_UNICAST_IF
720 MAP_OPTION( IPV6_UNICAST_IF ),
721 #endif
724 static const int ws_af_map[][2] =
726 MAP_OPTION( AF_UNSPEC ),
727 MAP_OPTION( AF_INET ),
728 MAP_OPTION( AF_INET6 ),
729 #ifdef HAS_IPX
730 MAP_OPTION( AF_IPX ),
731 #endif
732 #ifdef AF_IRDA
733 MAP_OPTION( AF_IRDA ),
734 #endif
735 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
738 static const int ws_socktype_map[][2] =
740 MAP_OPTION( SOCK_DGRAM ),
741 MAP_OPTION( SOCK_STREAM ),
742 MAP_OPTION( SOCK_RAW ),
743 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
746 static const int ws_proto_map[][2] =
748 MAP_OPTION( IPPROTO_IP ),
749 MAP_OPTION( IPPROTO_TCP ),
750 MAP_OPTION( IPPROTO_UDP ),
751 MAP_OPTION( IPPROTO_IPV6 ),
752 MAP_OPTION( IPPROTO_ICMP ),
753 MAP_OPTION( IPPROTO_IGMP ),
754 MAP_OPTION( IPPROTO_RAW ),
755 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
758 static const int ws_aiflag_map[][2] =
760 MAP_OPTION( AI_PASSIVE ),
761 MAP_OPTION( AI_CANONNAME ),
762 MAP_OPTION( AI_NUMERICHOST ),
763 #ifdef AI_NUMERICSERV
764 MAP_OPTION( AI_NUMERICSERV ),
765 #endif
766 #ifdef AI_V4MAPPED
767 MAP_OPTION( AI_V4MAPPED ),
768 #endif
769 MAP_OPTION( AI_ADDRCONFIG ),
772 static const int ws_niflag_map[][2] =
774 MAP_OPTION( NI_NOFQDN ),
775 MAP_OPTION( NI_NUMERICHOST ),
776 MAP_OPTION( NI_NAMEREQD ),
777 MAP_OPTION( NI_NUMERICSERV ),
778 MAP_OPTION( NI_DGRAM ),
781 static const int ws_eai_map[][2] =
783 MAP_OPTION( EAI_AGAIN ),
784 MAP_OPTION( EAI_BADFLAGS ),
785 MAP_OPTION( EAI_FAIL ),
786 MAP_OPTION( EAI_FAMILY ),
787 MAP_OPTION( EAI_MEMORY ),
788 /* Note: EAI_NODATA is deprecated, but still
789 * used by Windows and Linux... We map the newer
790 * EAI_NONAME to EAI_NODATA for now until Windows
791 * changes too.
793 #ifdef EAI_NODATA
794 MAP_OPTION( EAI_NODATA ),
795 #endif
796 #ifdef EAI_NONAME
797 { WS_EAI_NODATA, EAI_NONAME },
798 #endif
800 MAP_OPTION( EAI_SERVICE ),
801 MAP_OPTION( EAI_SOCKTYPE ),
802 { 0, 0 }
805 static const int ws_poll_map[][2] =
807 MAP_OPTION( POLLERR ),
808 MAP_OPTION( POLLHUP ),
809 MAP_OPTION( POLLNVAL ),
810 MAP_OPTION( POLLWRNORM ),
811 MAP_OPTION( POLLWRBAND ),
812 MAP_OPTION( POLLRDNORM ),
813 { WS_POLLRDBAND, POLLPRI }
816 static const char magic_loopback_addr[] = {127, 12, 34, 56};
818 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
819 #ifdef IP_PKTINFO
820 static inline WSACMSGHDR *fill_control_message(int level, int type, WSACMSGHDR *current, ULONG *maxsize, void *data, int len)
822 ULONG msgsize = sizeof(WSACMSGHDR) + WSA_CMSG_ALIGN(len);
823 char *ptr = (char *) current + sizeof(WSACMSGHDR);
825 /* Make sure there is at least enough room for this entry */
826 if (msgsize > *maxsize)
827 return NULL;
828 *maxsize -= msgsize;
829 /* Fill in the entry */
830 current->cmsg_len = sizeof(WSACMSGHDR) + len;
831 current->cmsg_level = level;
832 current->cmsg_type = type;
833 memcpy(ptr, data, len);
834 /* Return the pointer to where next entry should go */
835 return (WSACMSGHDR *) (ptr + WSA_CMSG_ALIGN(len));
837 #endif /* IP_PKTINFO */
839 static inline int convert_control_headers(struct msghdr *hdr, WSABUF *control)
841 #ifdef IP_PKTINFO
842 WSACMSGHDR *cmsg_win = (WSACMSGHDR *) control->buf, *ptr;
843 ULONG ctlsize = control->len;
844 struct cmsghdr *cmsg_unix;
846 ptr = cmsg_win;
847 /* Loop over all the headers, converting as appropriate */
848 for (cmsg_unix = CMSG_FIRSTHDR(hdr); cmsg_unix != NULL; cmsg_unix = CMSG_NXTHDR(hdr, cmsg_unix))
850 switch(cmsg_unix->cmsg_level)
852 case IPPROTO_IP:
853 switch(cmsg_unix->cmsg_type)
855 case IP_PKTINFO:
857 /* Convert the Unix IP_PKTINFO structure to the Windows version */
858 struct in_pktinfo *data_unix = (struct in_pktinfo *) CMSG_DATA(cmsg_unix);
859 struct WS_in_pktinfo data_win;
861 memcpy(&data_win.ipi_addr,&data_unix->ipi_addr.s_addr,4); /* 4 bytes = 32 address bits */
862 data_win.ipi_ifindex = data_unix->ipi_ifindex;
863 ptr = fill_control_message(WS_IPPROTO_IP, WS_IP_PKTINFO, ptr, &ctlsize,
864 (void*)&data_win, sizeof(data_win));
865 if (!ptr) goto error;
866 } break;
867 default:
868 FIXME("Unhandled IPPROTO_IP message header type %d\n", cmsg_unix->cmsg_type);
869 break;
871 break;
872 default:
873 FIXME("Unhandled message header level %d\n", cmsg_unix->cmsg_level);
874 break;
878 error:
879 /* Set the length of the returned control headers */
880 control->len = (ptr == NULL ? 0 : (char*)ptr - (char*)cmsg_win);
881 return (ptr != NULL);
882 #else /* IP_PKTINFO */
883 control->len = 0;
884 return 1;
885 #endif /* IP_PKTINFO */
887 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
889 /* ----------------------------------- error handling */
891 static NTSTATUS sock_get_ntstatus( int err )
893 switch ( err )
895 case EBADF: return STATUS_INVALID_HANDLE;
896 case EBUSY: return STATUS_DEVICE_BUSY;
897 case EPERM:
898 case EACCES: return STATUS_ACCESS_DENIED;
899 case EFAULT: return STATUS_NO_MEMORY;
900 case EINVAL: return STATUS_INVALID_PARAMETER;
901 case ENFILE:
902 case EMFILE: return STATUS_TOO_MANY_OPENED_FILES;
903 case EWOULDBLOCK: return STATUS_CANT_WAIT;
904 case EINPROGRESS: return STATUS_PENDING;
905 case EALREADY: return STATUS_NETWORK_BUSY;
906 case ENOTSOCK: return STATUS_OBJECT_TYPE_MISMATCH;
907 case EDESTADDRREQ: return STATUS_INVALID_PARAMETER;
908 case EMSGSIZE: return STATUS_BUFFER_OVERFLOW;
909 case EPROTONOSUPPORT:
910 case ESOCKTNOSUPPORT:
911 case EPFNOSUPPORT:
912 case EAFNOSUPPORT:
913 case EPROTOTYPE: return STATUS_NOT_SUPPORTED;
914 case ENOPROTOOPT: return STATUS_INVALID_PARAMETER;
915 case EOPNOTSUPP: return STATUS_NOT_SUPPORTED;
916 case EADDRINUSE: return STATUS_ADDRESS_ALREADY_ASSOCIATED;
917 case EADDRNOTAVAIL: return STATUS_INVALID_PARAMETER;
918 case ECONNREFUSED: return STATUS_CONNECTION_REFUSED;
919 case ESHUTDOWN: return STATUS_PIPE_DISCONNECTED;
920 case ENOTCONN: return STATUS_CONNECTION_DISCONNECTED;
921 case ETIMEDOUT: return STATUS_IO_TIMEOUT;
922 case ENETUNREACH: return STATUS_NETWORK_UNREACHABLE;
923 case ENETDOWN: return STATUS_NETWORK_BUSY;
924 case EPIPE:
925 case ECONNRESET: return STATUS_CONNECTION_RESET;
926 case ECONNABORTED: return STATUS_CONNECTION_ABORTED;
928 case 0: return STATUS_SUCCESS;
929 default:
930 WARN("Unknown errno %d!\n", err);
931 return STATUS_UNSUCCESSFUL;
935 static UINT sock_get_error( int err )
937 switch(err)
939 case EINTR: return WSAEINTR;
940 case EPERM:
941 case EACCES: return WSAEACCES;
942 case EFAULT: return WSAEFAULT;
943 case EINVAL: return WSAEINVAL;
944 case EMFILE: return WSAEMFILE;
945 case EWOULDBLOCK: return WSAEWOULDBLOCK;
946 case EINPROGRESS: return WSAEINPROGRESS;
947 case EALREADY: return WSAEALREADY;
948 case EBADF:
949 case ENOTSOCK: return WSAENOTSOCK;
950 case EDESTADDRREQ: return WSAEDESTADDRREQ;
951 case EMSGSIZE: return WSAEMSGSIZE;
952 case EPROTOTYPE: return WSAEPROTOTYPE;
953 case ENOPROTOOPT: return WSAENOPROTOOPT;
954 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
955 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
956 case EOPNOTSUPP: return WSAEOPNOTSUPP;
957 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
958 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
959 case EADDRINUSE: return WSAEADDRINUSE;
960 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
961 case ENETDOWN: return WSAENETDOWN;
962 case ENETUNREACH: return WSAENETUNREACH;
963 case ENETRESET: return WSAENETRESET;
964 case ECONNABORTED: return WSAECONNABORTED;
965 case EPIPE:
966 case ECONNRESET: return WSAECONNRESET;
967 case ENOBUFS: return WSAENOBUFS;
968 case EISCONN: return WSAEISCONN;
969 case ENOTCONN: return WSAENOTCONN;
970 case ESHUTDOWN: return WSAESHUTDOWN;
971 case ETOOMANYREFS: return WSAETOOMANYREFS;
972 case ETIMEDOUT: return WSAETIMEDOUT;
973 case ECONNREFUSED: return WSAECONNREFUSED;
974 case ELOOP: return WSAELOOP;
975 case ENAMETOOLONG: return WSAENAMETOOLONG;
976 case EHOSTDOWN: return WSAEHOSTDOWN;
977 case EHOSTUNREACH: return WSAEHOSTUNREACH;
978 case ENOTEMPTY: return WSAENOTEMPTY;
979 #ifdef EPROCLIM
980 case EPROCLIM: return WSAEPROCLIM;
981 #endif
982 #ifdef EUSERS
983 case EUSERS: return WSAEUSERS;
984 #endif
985 #ifdef EDQUOT
986 case EDQUOT: return WSAEDQUOT;
987 #endif
988 #ifdef ESTALE
989 case ESTALE: return WSAESTALE;
990 #endif
991 #ifdef EREMOTE
992 case EREMOTE: return WSAEREMOTE;
993 #endif
995 /* just in case we ever get here and there are no problems */
996 case 0: return 0;
997 default:
998 WARN("Unknown errno %d!\n", err);
999 return WSAEOPNOTSUPP;
1003 static UINT wsaErrno(void)
1005 int loc_errno = errno;
1006 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
1008 return sock_get_error( loc_errno );
1011 /* most ws2 overlapped functions return an ntstatus-based error code */
1012 static NTSTATUS wsaErrStatus(void)
1014 int loc_errno = errno;
1015 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
1017 return sock_get_ntstatus(loc_errno);
1020 static UINT wsaHerrno(int loc_errno)
1022 WARN("h_errno %d.\n", loc_errno);
1024 switch(loc_errno)
1026 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
1027 case TRY_AGAIN: return WSATRY_AGAIN;
1028 case NO_RECOVERY: return WSANO_RECOVERY;
1029 case NO_DATA: return WSANO_DATA;
1030 case ENOBUFS: return WSAENOBUFS;
1032 case 0: return 0;
1033 default:
1034 WARN("Unknown h_errno %d!\n", loc_errno);
1035 return WSAEOPNOTSUPP;
1039 static inline DWORD NtStatusToWSAError( const DWORD status )
1041 /* We only need to cover the status codes set by server async request handling */
1042 DWORD wserr;
1043 switch ( status )
1045 case STATUS_SUCCESS: wserr = 0; break;
1046 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
1047 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
1048 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
1049 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
1050 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
1051 case STATUS_NETWORK_BUSY: wserr = WSAEALREADY; break;
1052 case STATUS_NETWORK_UNREACHABLE: wserr = WSAENETUNREACH; break;
1053 case STATUS_CONNECTION_REFUSED: wserr = WSAECONNREFUSED; break;
1054 case STATUS_CONNECTION_DISCONNECTED: wserr = WSAENOTCONN; break;
1055 case STATUS_CONNECTION_RESET: wserr = WSAECONNRESET; break;
1056 case STATUS_CONNECTION_ABORTED: wserr = WSAECONNABORTED; break;
1057 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
1058 case STATUS_ADDRESS_ALREADY_ASSOCIATED: wserr = WSAEADDRINUSE; break;
1059 case STATUS_IO_TIMEOUT:
1060 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
1061 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
1062 case STATUS_ACCESS_DENIED: wserr = WSAEACCES; break;
1063 case STATUS_TOO_MANY_OPENED_FILES: wserr = WSAEMFILE; break;
1064 case STATUS_CANT_WAIT: wserr = WSAEWOULDBLOCK; break;
1065 case STATUS_BUFFER_OVERFLOW: wserr = WSAEMSGSIZE; break;
1066 case STATUS_NOT_SUPPORTED: wserr = WSAEOPNOTSUPP; break;
1067 case STATUS_HOST_UNREACHABLE: wserr = WSAEHOSTUNREACH; break;
1069 default:
1070 wserr = RtlNtStatusToDosError( status );
1071 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
1073 return wserr;
1076 /* set last error code from NT status without mapping WSA errors */
1077 static inline unsigned int set_error( unsigned int err )
1079 if (err)
1081 err = NtStatusToWSAError( err );
1082 SetLastError( err );
1084 return err;
1087 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
1089 int fd;
1090 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
1091 return -1;
1092 return fd;
1095 static inline void release_sock_fd( SOCKET s, int fd )
1097 wine_server_release_fd( SOCKET2HANDLE(s), fd );
1100 static void _enable_event( HANDLE s, unsigned int event,
1101 unsigned int sstate, unsigned int cstate )
1103 SERVER_START_REQ( enable_socket_event )
1105 req->handle = wine_server_obj_handle( s );
1106 req->mask = event;
1107 req->sstate = sstate;
1108 req->cstate = cstate;
1109 wine_server_call( req );
1111 SERVER_END_REQ;
1114 static NTSTATUS _is_blocking(SOCKET s, BOOL *ret)
1116 NTSTATUS status;
1117 SERVER_START_REQ( get_socket_event )
1119 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1120 req->service = FALSE;
1121 req->c_event = 0;
1122 status = wine_server_call( req );
1123 *ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
1125 SERVER_END_REQ;
1126 return status;
1129 static unsigned int _get_sock_mask(SOCKET s)
1131 unsigned int ret;
1132 SERVER_START_REQ( get_socket_event )
1134 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1135 req->service = FALSE;
1136 req->c_event = 0;
1137 wine_server_call( req );
1138 ret = reply->mask;
1140 SERVER_END_REQ;
1141 return ret;
1144 static void _sync_sock_state(SOCKET s)
1146 BOOL dummy;
1147 /* do a dummy wineserver request in order to let
1148 the wineserver run through its select loop once */
1149 (void)_is_blocking(s, &dummy);
1152 static void _get_sock_errors(SOCKET s, int *events)
1154 SERVER_START_REQ( get_socket_event )
1156 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1157 req->service = FALSE;
1158 req->c_event = 0;
1159 wine_server_set_reply( req, events, sizeof(int) * FD_MAX_EVENTS );
1160 wine_server_call( req );
1162 SERVER_END_REQ;
1165 static int _get_sock_error(SOCKET s, unsigned int bit)
1167 int events[FD_MAX_EVENTS];
1168 _get_sock_errors(s, events);
1169 return events[bit];
1172 static int _get_fd_type(int fd)
1174 int sock_type = -1;
1175 socklen_t optlen = sizeof(sock_type);
1176 getsockopt(fd, SOL_SOCKET, SO_TYPE, (char*) &sock_type, &optlen);
1177 return sock_type;
1180 static BOOL set_dont_fragment(SOCKET s, int level, BOOL value)
1182 int fd, optname;
1184 if (level == IPPROTO_IP)
1186 #ifdef IP_DONTFRAG
1187 optname = IP_DONTFRAG;
1188 #elif defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DO) && defined(IP_PMTUDISC_DONT)
1189 optname = IP_MTU_DISCOVER;
1190 value = value ? IP_PMTUDISC_DO : IP_PMTUDISC_DONT;
1191 #else
1192 static int once;
1193 if (!once++)
1194 FIXME("IP_DONTFRAGMENT for IPv4 not supported in this platform\n");
1195 return TRUE; /* fake success */
1196 #endif
1198 else
1200 #ifdef IPV6_DONTFRAG
1201 optname = IPV6_DONTFRAG;
1202 #elif defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DO) && defined(IPV6_PMTUDISC_DONT)
1203 optname = IPV6_MTU_DISCOVER;
1204 value = value ? IPV6_PMTUDISC_DO : IPV6_PMTUDISC_DONT;
1205 #else
1206 static int once;
1207 if (!once++)
1208 FIXME("IP_DONTFRAGMENT for IPv6 not supported in this platform\n");
1209 return TRUE; /* fake success */
1210 #endif
1213 fd = get_sock_fd(s, 0, NULL);
1214 if (fd == -1) return FALSE;
1216 if (!setsockopt(fd, level, optname, &value, sizeof(value)))
1217 value = TRUE;
1218 else
1220 WSASetLastError(wsaErrno());
1221 value = FALSE;
1224 release_sock_fd(s, fd);
1225 return value;
1228 static BOOL get_dont_fragment(SOCKET s, int level, BOOL *out)
1230 int fd, optname, value, not_expected;
1231 socklen_t optlen = sizeof(value);
1233 if (level == IPPROTO_IP)
1235 #ifdef IP_DONTFRAG
1236 optname = IP_DONTFRAG;
1237 not_expected = 0;
1238 #elif defined(IP_MTU_DISCOVER) && defined(IP_PMTUDISC_DONT)
1239 optname = IP_MTU_DISCOVER;
1240 not_expected = IP_PMTUDISC_DONT;
1241 #else
1242 static int once;
1243 if (!once++)
1244 FIXME("IP_DONTFRAGMENT for IPv4 not supported in this platform\n");
1245 return TRUE; /* fake success */
1246 #endif
1248 else
1250 #ifdef IPV6_DONTFRAG
1251 optname = IPV6_DONTFRAG;
1252 not_expected = 0;
1253 #elif defined(IPV6_MTU_DISCOVER) && defined(IPV6_PMTUDISC_DONT)
1254 optname = IPV6_MTU_DISCOVER;
1255 not_expected = IPV6_PMTUDISC_DONT;
1256 #else
1257 static int once;
1258 if (!once++)
1259 FIXME("IP_DONTFRAGMENT for IPv6 not supported in this platform\n");
1260 return TRUE; /* fake success */
1261 #endif
1264 fd = get_sock_fd(s, 0, NULL);
1265 if (fd == -1) return FALSE;
1267 if (!getsockopt(fd, level, optname, &value, &optlen))
1269 *out = value != not_expected;
1270 value = TRUE;
1272 else
1274 WSASetLastError(wsaErrno());
1275 value = FALSE;
1278 release_sock_fd(s, fd);
1279 return value;
1282 static struct per_thread_data *get_per_thread_data(void)
1284 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
1285 /* lazy initialization */
1286 if (!ptb)
1288 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
1289 NtCurrentTeb()->WinSockData = ptb;
1291 return ptb;
1294 static void free_per_thread_data(void)
1296 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
1298 if (!ptb) return;
1300 /* delete scratch buffers */
1301 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1302 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1303 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1304 HeapFree( GetProcessHeap(), 0, ptb->fd_cache );
1306 HeapFree( GetProcessHeap(), 0, ptb );
1307 NtCurrentTeb()->WinSockData = NULL;
1310 /***********************************************************************
1311 * DllMain (WS2_32.init)
1313 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
1315 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
1316 switch (fdwReason) {
1317 case DLL_PROCESS_ATTACH:
1318 break;
1319 case DLL_PROCESS_DETACH:
1320 if (fImpLoad) break;
1321 free_per_thread_data();
1322 DeleteCriticalSection(&csWSgetXXXbyYYY);
1323 break;
1324 case DLL_THREAD_DETACH:
1325 free_per_thread_data();
1326 break;
1328 return TRUE;
1331 /***********************************************************************
1332 * convert_flags()
1334 * Converts send/recv flags from Windows format.
1335 * Return the converted flag bits, unsupported flags remain unchanged.
1337 static int convert_flags(int flags)
1339 int i, out;
1340 if (!flags) return 0;
1342 for (out = i = 0; flags && i < sizeof(ws_flags_map) / sizeof(ws_flags_map[0]); i++)
1344 if (ws_flags_map[i][0] & flags)
1346 out |= ws_flags_map[i][1];
1347 flags &= ~ws_flags_map[i][0];
1350 if (flags)
1352 FIXME("Unknown send/recv flags 0x%x, using anyway...\n", flags);
1353 out |= flags;
1355 return out;
1358 /***********************************************************************
1359 * convert_sockopt()
1361 * Converts socket flags from Windows format.
1362 * Return 1 if converted, 0 if not (error).
1364 static int convert_sockopt(INT *level, INT *optname)
1366 unsigned int i;
1367 switch (*level)
1369 case WS_SOL_SOCKET:
1370 *level = SOL_SOCKET;
1371 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
1372 if( ws_sock_map[i][0] == *optname )
1374 *optname = ws_sock_map[i][1];
1375 return 1;
1378 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
1379 break;
1380 case WS_IPPROTO_TCP:
1381 *level = IPPROTO_TCP;
1382 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
1383 if ( ws_tcp_map[i][0] == *optname )
1385 *optname = ws_tcp_map[i][1];
1386 return 1;
1389 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
1390 break;
1391 case WS_IPPROTO_IP:
1392 *level = IPPROTO_IP;
1393 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
1394 if (ws_ip_map[i][0] == *optname )
1396 *optname = ws_ip_map[i][1];
1397 return 1;
1400 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
1401 break;
1402 case WS_IPPROTO_IPV6:
1403 *level = IPPROTO_IPV6;
1404 for(i=0; i<sizeof(ws_ipv6_map)/sizeof(ws_ipv6_map[0]); i++) {
1405 if (ws_ipv6_map[i][0] == *optname )
1407 *optname = ws_ipv6_map[i][1];
1408 return 1;
1411 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname);
1412 break;
1413 default: FIXME("Unimplemented or unknown socket level\n");
1415 return 0;
1418 /* ----------------------------------- Per-thread info (or per-process?) */
1420 static char *strdup_lower(const char *str)
1422 int i;
1423 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
1425 if (ret)
1427 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
1428 ret[i] = 0;
1430 else SetLastError(WSAENOBUFS);
1431 return ret;
1434 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
1435 * from an fd and return the value converted to milli seconds
1436 * or 0 if there is an infinite time out */
1437 static inline INT64 get_rcvsnd_timeo( int fd, BOOL is_recv)
1439 struct timeval tv;
1440 socklen_t len = sizeof(tv);
1441 int optname, res;
1443 if (is_recv)
1444 #ifdef SO_RCVTIMEO
1445 optname = SO_RCVTIMEO;
1446 #else
1447 return 0;
1448 #endif
1449 else
1450 #ifdef SO_SNDTIMEO
1451 optname = SO_SNDTIMEO;
1452 #else
1453 return 0;
1454 #endif
1456 res = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
1457 if (res < 0)
1458 return 0;
1459 return (UINT64)tv.tv_sec * 1000 + tv.tv_usec / 1000;
1462 /* utility: given an fd, will block until one of the events occurs */
1463 static inline int do_block( int fd, int events, int timeout )
1465 struct pollfd pfd;
1466 int ret;
1468 pfd.fd = fd;
1469 pfd.events = events;
1471 while ((ret = poll(&pfd, 1, timeout)) < 0)
1473 if (errno != EINTR)
1474 return -1;
1476 if( ret == 0 )
1477 return 0;
1478 return pfd.revents;
1481 static int
1482 convert_af_w2u(int windowsaf) {
1483 unsigned int i;
1485 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1486 if (ws_af_map[i][0] == windowsaf)
1487 return ws_af_map[i][1];
1488 FIXME("unhandled Windows address family %d\n", windowsaf);
1489 return -1;
1492 static int
1493 convert_af_u2w(int unixaf) {
1494 unsigned int i;
1496 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1497 if (ws_af_map[i][1] == unixaf)
1498 return ws_af_map[i][0];
1499 FIXME("unhandled UNIX address family %d\n", unixaf);
1500 return -1;
1503 static int
1504 convert_proto_w2u(int windowsproto) {
1505 unsigned int i;
1507 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1508 if (ws_proto_map[i][0] == windowsproto)
1509 return ws_proto_map[i][1];
1511 /* check for extended IPX */
1512 if (IS_IPX_PROTO(windowsproto))
1513 return windowsproto;
1515 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
1516 return -1;
1519 static int
1520 convert_proto_u2w(int unixproto) {
1521 unsigned int i;
1523 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1524 if (ws_proto_map[i][1] == unixproto)
1525 return ws_proto_map[i][0];
1527 /* if value is inside IPX range just return it - the kernel simply
1528 * echoes the value used in the socket() function */
1529 if (IS_IPX_PROTO(unixproto))
1530 return unixproto;
1532 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
1533 return -1;
1536 static int
1537 convert_socktype_w2u(int windowssocktype) {
1538 unsigned int i;
1540 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1541 if (ws_socktype_map[i][0] == windowssocktype)
1542 return ws_socktype_map[i][1];
1543 FIXME("unhandled Windows socket type %d\n", windowssocktype);
1544 return -1;
1547 static int
1548 convert_socktype_u2w(int unixsocktype) {
1549 unsigned int i;
1551 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1552 if (ws_socktype_map[i][1] == unixsocktype)
1553 return ws_socktype_map[i][0];
1554 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
1555 return -1;
1558 static int convert_poll_w2u(int events)
1560 int i, ret;
1561 for (i = ret = 0; events && i < sizeof(ws_poll_map) / sizeof(ws_poll_map[0]); i++)
1563 if (ws_poll_map[i][0] & events)
1565 ret |= ws_poll_map[i][1];
1566 events &= ~ws_poll_map[i][0];
1570 if (events)
1571 FIXME("Unsupported WSAPoll() flags 0x%x\n", events);
1572 return ret;
1575 static int convert_poll_u2w(int events)
1577 int i, ret;
1578 for (i = ret = 0; events && i < sizeof(ws_poll_map) / sizeof(ws_poll_map[0]); i++)
1580 if (ws_poll_map[i][1] & events)
1582 ret |= ws_poll_map[i][0];
1583 events &= ~ws_poll_map[i][1];
1587 if (events)
1588 FIXME("Unsupported poll() flags 0x%x\n", events);
1589 return ret;
1592 static int set_ipx_packettype(int sock, int ptype)
1594 #ifdef HAS_IPX
1595 int fd = get_sock_fd( sock, 0, NULL ), ret = 0;
1596 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", ptype, fd);
1598 if (fd == -1) return SOCKET_ERROR;
1600 /* We try to set the ipx type on ipx socket level. */
1601 #ifdef SOL_IPX
1602 if(setsockopt(fd, SOL_IPX, IPX_TYPE, &ptype, sizeof(ptype)) == -1)
1604 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
1605 ret = SOCKET_ERROR;
1607 #else
1609 struct ipx val;
1610 /* Should we retrieve val using a getsockopt call and then
1611 * set the modified one? */
1612 val.ipx_pt = ptype;
1613 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
1615 #endif
1616 release_sock_fd( sock, fd );
1617 return ret;
1618 #else
1619 WARN("IPX support is not enabled, can't set packet type\n");
1620 return SOCKET_ERROR;
1621 #endif
1624 /* ----------------------------------- API -----
1626 * Init / cleanup / error checking.
1629 /***********************************************************************
1630 * WSAStartup (WS2_32.115)
1632 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
1634 TRACE("verReq=%x\n", wVersionRequested);
1636 if (LOBYTE(wVersionRequested) < 1)
1637 return WSAVERNOTSUPPORTED;
1639 if (!lpWSAData) return WSAEINVAL;
1641 num_startup++;
1643 /* that's the whole of the negotiation for now */
1644 lpWSAData->wVersion = wVersionRequested;
1645 /* return winsock information */
1646 lpWSAData->wHighVersion = 0x0202;
1647 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
1648 strcpy(lpWSAData->szSystemStatus, "Running" );
1649 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
1650 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
1651 /* don't do anything with lpWSAData->lpVendorInfo */
1652 /* (some apps don't allocate the space for this field) */
1654 TRACE("succeeded starts: %d\n", num_startup);
1655 return 0;
1659 /***********************************************************************
1660 * WSACleanup (WS2_32.116)
1662 INT WINAPI WSACleanup(void)
1664 if (num_startup) {
1665 num_startup--;
1666 TRACE("pending cleanups: %d\n", num_startup);
1667 return 0;
1669 SetLastError(WSANOTINITIALISED);
1670 return SOCKET_ERROR;
1674 /***********************************************************************
1675 * WSAGetLastError (WS2_32.111)
1677 INT WINAPI WSAGetLastError(void)
1679 return GetLastError();
1682 /***********************************************************************
1683 * WSASetLastError (WS2_32.112)
1685 void WINAPI WSASetLastError(INT iError) {
1686 SetLastError(iError);
1689 static struct WS_hostent *check_buffer_he(int size)
1691 struct per_thread_data * ptb = get_per_thread_data();
1692 if (ptb->he_buffer)
1694 if (ptb->he_len >= size ) return ptb->he_buffer;
1695 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1697 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
1698 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
1699 return ptb->he_buffer;
1702 static struct WS_servent *check_buffer_se(int size)
1704 struct per_thread_data * ptb = get_per_thread_data();
1705 if (ptb->se_buffer)
1707 if (ptb->se_len >= size ) return ptb->se_buffer;
1708 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1710 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
1711 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
1712 return ptb->se_buffer;
1715 static struct WS_protoent *check_buffer_pe(int size)
1717 struct per_thread_data * ptb = get_per_thread_data();
1718 if (ptb->pe_buffer)
1720 if (ptb->pe_len >= size ) return ptb->pe_buffer;
1721 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1723 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
1724 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
1725 return ptb->pe_buffer;
1728 /* ----------------------------------- i/o APIs */
1730 static inline BOOL supported_pf(int pf)
1732 switch (pf)
1734 case WS_AF_INET:
1735 case WS_AF_INET6:
1736 return TRUE;
1737 #ifdef HAS_IPX
1738 case WS_AF_IPX:
1739 return TRUE;
1740 #endif
1741 #ifdef HAS_IRDA
1742 case WS_AF_IRDA:
1743 return TRUE;
1744 #endif
1745 default:
1746 return FALSE;
1750 static inline BOOL supported_protocol(int protocol)
1752 int i;
1753 for (i = 0; i < sizeof(valid_protocols) / sizeof(valid_protocols[0]); i++)
1754 if (protocol == valid_protocols[i])
1755 return TRUE;
1756 return FALSE;
1759 /**********************************************************************/
1761 /* Returns the length of the converted address if successful, 0 if it was too
1762 * small to start with or unknown family or invalid address buffer.
1764 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
1765 union generic_unix_sockaddr *uaddr)
1767 unsigned int uaddrlen = 0;
1769 if (!wsaddr)
1770 return 0;
1772 switch (wsaddr->sa_family)
1774 #ifdef HAS_IPX
1775 case WS_AF_IPX:
1777 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
1778 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
1780 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
1781 return 0;
1783 uaddrlen = sizeof(struct sockaddr_ipx);
1784 memset( uaddr, 0, uaddrlen );
1785 uipx->sipx_family=AF_IPX;
1786 uipx->sipx_port=wsipx->sa_socket;
1787 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1788 * in one go
1790 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
1791 #ifdef IPX_FRAME_NONE
1792 uipx->sipx_type=IPX_FRAME_NONE;
1793 #endif
1794 break;
1796 #endif
1797 case WS_AF_INET6: {
1798 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
1799 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
1801 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1802 * scope_id, one without.
1804 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
1805 uaddrlen = sizeof(struct sockaddr_in6);
1806 memset( uaddr, 0, uaddrlen );
1807 uin6->sin6_family = AF_INET6;
1808 uin6->sin6_port = win6->sin6_port;
1809 uin6->sin6_flowinfo = win6->sin6_flowinfo;
1810 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1811 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
1812 #endif
1813 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
1814 break;
1816 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
1817 return 0;
1819 case WS_AF_INET: {
1820 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
1821 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
1823 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
1824 return 0;
1825 uaddrlen = sizeof(struct sockaddr_in);
1826 memset( uaddr, 0, uaddrlen );
1827 uin->sin_family = AF_INET;
1828 uin->sin_port = win->sin_port;
1829 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
1830 break;
1832 #ifdef HAS_IRDA
1833 case WS_AF_IRDA: {
1834 struct sockaddr_irda *uin = (struct sockaddr_irda *)uaddr;
1835 const SOCKADDR_IRDA *win = (const SOCKADDR_IRDA *)wsaddr;
1837 if (wsaddrlen < sizeof(SOCKADDR_IRDA))
1838 return 0;
1839 uaddrlen = sizeof(struct sockaddr_irda);
1840 memset( uaddr, 0, uaddrlen );
1841 uin->sir_family = AF_IRDA;
1842 if (!strncmp( win->irdaServiceName, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1844 unsigned int lsap_sel = 0;
1846 sscanf( win->irdaServiceName, "LSAP-SEL%u", &lsap_sel );
1847 uin->sir_lsap_sel = lsap_sel;
1849 else
1851 uin->sir_lsap_sel = LSAP_ANY;
1852 memcpy( uin->sir_name, win->irdaServiceName, 25 );
1854 memcpy( &uin->sir_addr, win->irdaDeviceID, sizeof(uin->sir_addr) );
1855 break;
1857 #endif
1858 case WS_AF_UNSPEC: {
1859 /* Try to determine the needed space by the passed windows sockaddr space */
1860 switch (wsaddrlen) {
1861 default: /* likely an ipv4 address */
1862 case sizeof(struct WS_sockaddr_in):
1863 uaddrlen = sizeof(struct sockaddr_in);
1864 break;
1865 #ifdef HAS_IPX
1866 case sizeof(struct WS_sockaddr_ipx):
1867 uaddrlen = sizeof(struct sockaddr_ipx);
1868 break;
1869 #endif
1870 #ifdef HAS_IRDA
1871 case sizeof(SOCKADDR_IRDA):
1872 uaddrlen = sizeof(struct sockaddr_irda);
1873 break;
1874 #endif
1875 case sizeof(struct WS_sockaddr_in6):
1876 case sizeof(struct WS_sockaddr_in6_old):
1877 uaddrlen = sizeof(struct sockaddr_in6);
1878 break;
1880 memset( uaddr, 0, uaddrlen );
1881 break;
1883 default:
1884 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
1885 return 0;
1887 return uaddrlen;
1890 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
1892 switch (uaddr->sa_family)
1894 #ifdef HAS_IPX
1895 case AF_IPX:
1897 static const struct sockaddr_ipx emptyAddr;
1898 struct sockaddr_ipx *ipx = (struct sockaddr_ipx*) uaddr;
1899 return ipx->sipx_port
1900 || memcmp(&ipx->sipx_network, &emptyAddr.sipx_network, sizeof(emptyAddr.sipx_network))
1901 || memcmp(&ipx->sipx_node, &emptyAddr.sipx_node, sizeof(emptyAddr.sipx_node));
1903 #endif
1904 case AF_INET6:
1906 static const struct sockaddr_in6 emptyAddr;
1907 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
1908 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
1910 case AF_INET:
1912 static const struct sockaddr_in emptyAddr;
1913 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
1914 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
1916 case AF_UNSPEC:
1917 return FALSE;
1918 default:
1919 FIXME("unknown address family %d\n", uaddr->sa_family);
1920 return TRUE;
1924 /* Returns -1 if getsockname fails, 0 if not bound, 1 otherwise */
1925 static int is_fd_bound(int fd, union generic_unix_sockaddr *uaddr, socklen_t *uaddrlen)
1927 union generic_unix_sockaddr inaddr;
1928 socklen_t inlen;
1929 int res;
1931 if (!uaddr) uaddr = &inaddr;
1932 if (!uaddrlen) uaddrlen = &inlen;
1934 *uaddrlen = sizeof(inaddr);
1935 res = getsockname(fd, &uaddr->addr, uaddrlen);
1936 if (!res) res = is_sockaddr_bound(&uaddr->addr, *uaddrlen);
1937 return res;
1940 /* Returns 0 if successful, -1 if the buffer is too small */
1941 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
1943 int res;
1945 switch(uaddr->sa_family)
1947 #ifdef HAS_IPX
1948 case AF_IPX:
1950 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
1951 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
1953 res=-1;
1954 switch (*wsaddrlen) /* how much can we copy? */
1956 default:
1957 res=0; /* enough */
1958 *wsaddrlen = sizeof(*wsipx);
1959 wsipx->sa_socket=uipx->sipx_port;
1960 /* fall through */
1961 case 13:
1962 case 12:
1963 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
1964 /* fall through */
1965 case 11:
1966 case 10:
1967 case 9:
1968 case 8:
1969 case 7:
1970 case 6:
1971 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1972 /* fall through */
1973 case 5:
1974 case 4:
1975 case 3:
1976 case 2:
1977 wsipx->sa_family=WS_AF_IPX;
1978 /* fall through */
1979 case 1:
1980 case 0:
1981 /* way too small */
1982 break;
1985 break;
1986 #endif
1987 #ifdef HAS_IRDA
1988 case AF_IRDA: {
1989 const struct sockaddr_irda *uin = (const struct sockaddr_irda *)uaddr;
1990 SOCKADDR_IRDA *win = (SOCKADDR_IRDA *)wsaddr;
1992 if (*wsaddrlen < sizeof(SOCKADDR_IRDA))
1993 return -1;
1994 win->irdaAddressFamily = WS_AF_IRDA;
1995 memcpy( win->irdaDeviceID, &uin->sir_addr, sizeof(win->irdaDeviceID) );
1996 if (uin->sir_lsap_sel != LSAP_ANY)
1997 sprintf( win->irdaServiceName, "LSAP-SEL%u", uin->sir_lsap_sel );
1998 else
1999 memcpy( win->irdaServiceName, uin->sir_name,
2000 sizeof(win->irdaServiceName) );
2001 return 0;
2003 #endif
2004 case AF_INET6: {
2005 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
2006 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
2008 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
2009 return -1;
2010 win6old->sin6_family = WS_AF_INET6;
2011 win6old->sin6_port = uin6->sin6_port;
2012 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
2013 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
2014 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
2015 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
2016 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
2017 win6->sin6_scope_id = uin6->sin6_scope_id;
2018 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
2020 else
2021 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
2022 #else
2023 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
2024 #endif
2025 return 0;
2027 case AF_INET: {
2028 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
2029 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
2031 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
2032 return -1;
2033 win->sin_family = WS_AF_INET;
2034 win->sin_port = uin->sin_port;
2035 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
2036 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
2037 *wsaddrlen = sizeof(struct WS_sockaddr_in);
2038 return 0;
2040 case AF_UNSPEC: {
2041 memset(wsaddr,0,*wsaddrlen);
2042 return 0;
2044 default:
2045 FIXME("Unknown address family %d\n", uaddr->sa_family);
2046 return -1;
2048 return res;
2051 static INT WS_DuplicateSocket(BOOL unicode, SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo)
2053 HANDLE hProcess;
2054 int size;
2055 WSAPROTOCOL_INFOW infow;
2057 TRACE("(unicode %d, socket %04lx, processid %x, buffer %p)\n",
2058 unicode, s, dwProcessId, lpProtocolInfo);
2060 if (!ws_protocol_info(s, unicode, &infow, &size))
2061 return SOCKET_ERROR;
2063 if (!(hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId)))
2065 SetLastError(WSAEINVAL);
2066 return SOCKET_ERROR;
2069 if (!lpProtocolInfo)
2071 CloseHandle(hProcess);
2072 SetLastError(WSAEFAULT);
2073 return SOCKET_ERROR;
2076 /* I don't know what the real Windoze does next, this is a hack */
2077 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
2078 * the target use the global duplicate, or we could copy a reference to us to the structure
2079 * and let the target duplicate it from us, but let's do it as simple as possible */
2080 memcpy(lpProtocolInfo, &infow, size);
2081 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
2082 hProcess, (LPHANDLE)&lpProtocolInfo->dwServiceFlags3,
2083 0, FALSE, DUPLICATE_SAME_ACCESS);
2084 CloseHandle(hProcess);
2085 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
2086 return 0;
2089 /*****************************************************************************
2090 * WS_EnterSingleProtocolW [internal]
2092 * enters the protocol information of one given protocol into the given
2093 * buffer.
2095 * RETURNS
2096 * TRUE if a protocol was entered into the buffer.
2098 * BUGS
2099 * - only implemented for IPX, SPX, SPXII, TCP, UDP
2100 * - there is no check that the operating system supports the returned
2101 * protocols
2103 static BOOL WS_EnterSingleProtocolW( INT protocol, WSAPROTOCOL_INFOW* info )
2105 memset( info, 0, sizeof(WSAPROTOCOL_INFOW) );
2106 info->iProtocol = protocol;
2108 switch (protocol)
2110 case WS_IPPROTO_TCP:
2111 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_EXPEDITED_DATA |
2112 XP1_GRACEFUL_CLOSE | XP1_GUARANTEED_ORDER |
2113 XP1_GUARANTEED_DELIVERY;
2114 info->ProviderId = ProviderIdIP;
2115 info->dwCatalogEntryId = 0x3e9;
2116 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
2117 info->ProtocolChain.ChainLen = 1;
2118 info->iVersion = 2;
2119 info->iAddressFamily = WS_AF_INET;
2120 info->iMaxSockAddr = 0x10;
2121 info->iMinSockAddr = 0x10;
2122 info->iSocketType = WS_SOCK_STREAM;
2123 strcpyW( info->szProtocol, NameTcpW );
2124 break;
2126 case WS_IPPROTO_UDP:
2127 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_SUPPORT_BROADCAST |
2128 XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED |
2129 XP1_CONNECTIONLESS;
2130 info->ProviderId = ProviderIdIP;
2131 info->dwCatalogEntryId = 0x3ea;
2132 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
2133 info->ProtocolChain.ChainLen = 1;
2134 info->iVersion = 2;
2135 info->iAddressFamily = WS_AF_INET;
2136 info->iMaxSockAddr = 0x10;
2137 info->iMinSockAddr = 0x10;
2138 info->iSocketType = WS_SOCK_DGRAM;
2139 info->dwMessageSize = 0xffbb;
2140 strcpyW( info->szProtocol, NameUdpW );
2141 break;
2143 case WS_NSPROTO_IPX:
2144 info->dwServiceFlags1 = XP1_PARTIAL_MESSAGE | XP1_SUPPORT_BROADCAST |
2145 XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED |
2146 XP1_CONNECTIONLESS;
2147 info->ProviderId = ProviderIdIPX;
2148 info->dwCatalogEntryId = 0x406;
2149 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
2150 info->ProtocolChain.ChainLen = 1;
2151 info->iVersion = 2;
2152 info->iAddressFamily = WS_AF_IPX;
2153 info->iMaxSockAddr = 0x10;
2154 info->iMinSockAddr = 0x0e;
2155 info->iSocketType = WS_SOCK_DGRAM;
2156 info->iProtocolMaxOffset = 0xff;
2157 info->dwMessageSize = 0x240;
2158 strcpyW( info->szProtocol, NameIpxW );
2159 break;
2161 case WS_NSPROTO_SPX:
2162 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_PSEUDO_STREAM |
2163 XP1_MESSAGE_ORIENTED | XP1_GUARANTEED_ORDER |
2164 XP1_GUARANTEED_DELIVERY;
2165 info->ProviderId = ProviderIdSPX;
2166 info->dwCatalogEntryId = 0x407;
2167 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
2168 info->ProtocolChain.ChainLen = 1;
2169 info->iVersion = 2;
2170 info->iAddressFamily = WS_AF_IPX;
2171 info->iMaxSockAddr = 0x10;
2172 info->iMinSockAddr = 0x0e;
2173 info->iSocketType = WS_SOCK_SEQPACKET;
2174 info->dwMessageSize = 0xffffffff;
2175 strcpyW( info->szProtocol, NameSpxW );
2176 break;
2178 case WS_NSPROTO_SPXII:
2179 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_GRACEFUL_CLOSE |
2180 XP1_PSEUDO_STREAM | XP1_MESSAGE_ORIENTED |
2181 XP1_GUARANTEED_ORDER | XP1_GUARANTEED_DELIVERY;
2182 info->ProviderId = ProviderIdSPX;
2183 info->dwCatalogEntryId = 0x409;
2184 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
2185 info->ProtocolChain.ChainLen = 1;
2186 info->iVersion = 2;
2187 info->iAddressFamily = WS_AF_IPX;
2188 info->iMaxSockAddr = 0x10;
2189 info->iMinSockAddr = 0x0e;
2190 info->iSocketType = WS_SOCK_SEQPACKET;
2191 info->dwMessageSize = 0xffffffff;
2192 strcpyW( info->szProtocol, NameSpxIIW );
2193 break;
2195 default:
2196 FIXME("unknown Protocol <0x%08x>\n", protocol);
2197 return FALSE;
2199 return TRUE;
2202 /*****************************************************************************
2203 * WS_EnterSingleProtocolA [internal]
2205 * see function WS_EnterSingleProtocolW
2208 static BOOL WS_EnterSingleProtocolA( INT protocol, WSAPROTOCOL_INFOA* info )
2210 WSAPROTOCOL_INFOW infow;
2211 INT ret;
2212 memset( info, 0, sizeof(WSAPROTOCOL_INFOA) );
2214 ret = WS_EnterSingleProtocolW( protocol, &infow );
2215 if (ret)
2217 /* convert the structure from W to A */
2218 memcpy( info, &infow, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
2219 WideCharToMultiByte( CP_ACP, 0, infow.szProtocol, -1,
2220 info->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL );
2223 return ret;
2226 static INT WS_EnumProtocols( BOOL unicode, const INT *protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
2228 INT i = 0, items = 0;
2229 DWORD size = 0;
2230 union _info
2232 LPWSAPROTOCOL_INFOA a;
2233 LPWSAPROTOCOL_INFOW w;
2234 } info;
2235 info.w = buffer;
2237 if (!protocols) protocols = valid_protocols;
2239 while (protocols[i])
2241 if(supported_protocol(protocols[i++]))
2242 items++;
2245 size = items * (unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA));
2247 TRACE("unicode %d, protocols %p, buffer %p, length %p %d, items %d, required %d\n",
2248 unicode, protocols, buffer, len, len ? *len : 0, items, size);
2250 if (*len < size || !buffer)
2252 *len = size;
2253 SetLastError(WSAENOBUFS);
2254 return SOCKET_ERROR;
2257 for (i = items = 0; protocols[i]; i++)
2259 if (!supported_protocol(protocols[i])) continue;
2260 if (unicode)
2262 if (WS_EnterSingleProtocolW( protocols[i], &info.w[items] ))
2263 items++;
2265 else
2267 if (WS_EnterSingleProtocolA( protocols[i], &info.a[items] ))
2268 items++;
2271 return items;
2274 static BOOL ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size)
2276 NTSTATUS status;
2278 *size = unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA);
2279 memset(buffer, 0, *size);
2281 SERVER_START_REQ( get_socket_info )
2283 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
2284 status = wine_server_call( req );
2285 if (!status)
2287 buffer->iAddressFamily = convert_af_u2w(reply->family);
2288 buffer->iSocketType = convert_socktype_u2w(reply->type);
2289 buffer->iProtocol = convert_proto_u2w(reply->protocol);
2292 SERVER_END_REQ;
2294 if (status)
2296 unsigned int err = NtStatusToWSAError( status );
2297 SetLastError( err == WSAEBADF ? WSAENOTSOCK : err );
2298 return FALSE;
2301 if (unicode)
2302 WS_EnterSingleProtocolW( buffer->iProtocol, buffer);
2303 else
2304 WS_EnterSingleProtocolA( buffer->iProtocol, (WSAPROTOCOL_INFOA *)buffer);
2306 return TRUE;
2309 /**************************************************************************
2310 * Functions for handling overlapped I/O
2311 **************************************************************************/
2313 /* user APC called upon async completion */
2314 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
2316 struct ws2_async *wsa = arg;
2318 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
2319 iosb->Information, wsa->user_overlapped,
2320 wsa->flags );
2321 release_async_io( &wsa->io );
2324 /***********************************************************************
2325 * WS2_recv (INTERNAL)
2327 * Workhorse for both synchronous and asynchronous recv() operations.
2329 static int WS2_recv( int fd, struct ws2_async *wsa, int flags )
2331 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2332 char pktbuf[512];
2333 #endif
2334 struct msghdr hdr;
2335 union generic_unix_sockaddr unix_sockaddr;
2336 int n;
2338 hdr.msg_name = NULL;
2340 if (wsa->addr)
2342 hdr.msg_namelen = sizeof(unix_sockaddr);
2343 hdr.msg_name = &unix_sockaddr;
2345 else
2346 hdr.msg_namelen = 0;
2348 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
2349 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
2350 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2351 hdr.msg_accrights = NULL;
2352 hdr.msg_accrightslen = 0;
2353 #else
2354 hdr.msg_control = pktbuf;
2355 hdr.msg_controllen = sizeof(pktbuf);
2356 hdr.msg_flags = 0;
2357 #endif
2359 while ((n = recvmsg(fd, &hdr, flags)) == -1)
2361 if (errno != EINTR)
2362 return -1;
2365 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2366 if (wsa->control)
2368 ERR("Message control headers cannot be properly supported on this system.\n");
2369 wsa->control->len = 0;
2371 #else
2372 if (wsa->control && !convert_control_headers(&hdr, wsa->control))
2374 WARN("Application passed insufficient room for control headers.\n");
2375 *wsa->lpFlags |= WS_MSG_CTRUNC;
2376 errno = EMSGSIZE;
2377 return -1;
2379 #endif
2381 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
2382 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
2384 * quoting linux 2.6 net/ipv4/tcp.c:
2385 * "According to UNIX98, msg_name/msg_namelen are ignored
2386 * on connected socket. I was just happy when found this 8) --ANK"
2388 * likewise MSDN says that lpFrom and lpFromlen are ignored for
2389 * connection-oriented sockets, so don't try to update lpFrom.
2391 if (wsa->addr && hdr.msg_namelen)
2392 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
2394 return n;
2397 /***********************************************************************
2398 * WS2_async_recv (INTERNAL)
2400 * Handler for overlapped recv() operations.
2402 static NTSTATUS WS2_async_recv( void *user, IO_STATUS_BLOCK *iosb, NTSTATUS status )
2404 struct ws2_async *wsa = user;
2405 int result = 0, fd;
2407 switch (status)
2409 case STATUS_ALERTED:
2410 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
2411 break;
2413 result = WS2_recv( fd, wsa, convert_flags(wsa->flags) );
2414 wine_server_release_fd( wsa->hSocket, fd );
2415 if (result >= 0)
2417 status = STATUS_SUCCESS;
2418 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
2420 else
2422 if (errno == EAGAIN)
2424 status = STATUS_PENDING;
2425 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
2427 else
2429 result = 0;
2430 status = wsaErrStatus();
2433 break;
2435 if (status != STATUS_PENDING)
2437 iosb->u.Status = status;
2438 iosb->Information = result;
2439 if (!wsa->completion_func)
2440 release_async_io( &wsa->io );
2442 return status;
2445 /***********************************************************************
2446 * WS2_async_accept_recv (INTERNAL)
2448 * This function is used to finish the read part of an accept request. It is
2449 * needed to place the completion on the correct socket (listener).
2451 static NTSTATUS WS2_async_accept_recv( void *user, IO_STATUS_BLOCK *iosb, NTSTATUS status )
2453 struct ws2_accept_async *wsa = user;
2455 status = WS2_async_recv( wsa->read, iosb, status );
2456 if (status == STATUS_PENDING)
2457 return status;
2459 if (wsa->cvalue)
2460 WS_AddCompletion( HANDLE2SOCKET(wsa->listen_socket), wsa->cvalue, iosb->u.Status, iosb->Information );
2462 release_async_io( &wsa->io );
2463 return status;
2466 /***********************************************************************
2467 * WS2_async_accept (INTERNAL)
2469 * This is the function called to satisfy the AcceptEx callback
2471 static NTSTATUS WS2_async_accept( void *user, IO_STATUS_BLOCK *iosb, NTSTATUS status )
2473 struct ws2_accept_async *wsa = user;
2474 int len;
2475 char *addr;
2477 TRACE("status: 0x%x listen: %p, accept: %p\n", status, wsa->listen_socket, wsa->accept_socket);
2479 if (status == STATUS_ALERTED)
2481 SERVER_START_REQ( accept_into_socket )
2483 req->lhandle = wine_server_obj_handle( wsa->listen_socket );
2484 req->ahandle = wine_server_obj_handle( wsa->accept_socket );
2485 status = wine_server_call( req );
2487 SERVER_END_REQ;
2489 if (status == STATUS_CANT_WAIT)
2490 return STATUS_PENDING;
2492 if (status == STATUS_INVALID_HANDLE)
2494 FIXME("AcceptEx accepting socket closed but request was not cancelled\n");
2495 status = STATUS_CANCELLED;
2498 else if (status == STATUS_HANDLES_CLOSED)
2499 status = STATUS_CANCELLED; /* strange windows behavior */
2501 if (status != STATUS_SUCCESS)
2502 goto finish;
2504 /* WS2 Spec says size param is extra 16 bytes long...what do we put in it? */
2505 addr = ((char *)wsa->buf) + wsa->data_len;
2506 len = wsa->local_len - sizeof(int);
2507 WS_getsockname(HANDLE2SOCKET(wsa->accept_socket),
2508 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
2509 *(int *)addr = len;
2511 addr += wsa->local_len;
2512 len = wsa->remote_len - sizeof(int);
2513 WS_getpeername(HANDLE2SOCKET(wsa->accept_socket),
2514 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
2515 *(int *)addr = len;
2517 if (!wsa->read)
2518 goto finish;
2520 wsa->io.callback = WS2_async_accept_recv;
2521 status = register_async( ASYNC_TYPE_READ, wsa->accept_socket, &wsa->io,
2522 wsa->user_overlapped->hEvent, NULL, NULL, iosb);
2524 if (status != STATUS_PENDING)
2525 goto finish;
2527 /* The APC has finished but no completion should be sent for the operation yet, additional processing
2528 * needs to be performed by WS2_async_accept_recv() first. */
2529 return STATUS_MORE_PROCESSING_REQUIRED;
2531 finish:
2532 iosb->u.Status = status;
2533 iosb->Information = 0;
2535 if (wsa->read) release_async_io( &wsa->read->io );
2536 release_async_io( &wsa->io );
2537 return status;
2540 /***********************************************************************
2541 * WS2_send (INTERNAL)
2543 * Workhorse for both synchronous and asynchronous send() operations.
2545 static int WS2_send( int fd, struct ws2_async *wsa, int flags )
2547 struct msghdr hdr;
2548 union generic_unix_sockaddr unix_addr;
2549 int n, ret;
2551 hdr.msg_name = NULL;
2552 hdr.msg_namelen = 0;
2554 if (wsa->addr)
2556 hdr.msg_name = &unix_addr;
2557 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
2558 if ( !hdr.msg_namelen )
2560 errno = EFAULT;
2561 return -1;
2564 #if defined(HAS_IPX) && defined(SOL_IPX)
2565 if(wsa->addr->sa_family == WS_AF_IPX)
2567 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
2568 int val=0;
2569 socklen_t len = sizeof(int);
2571 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
2572 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
2573 * the packet type and then we can retrieve it using getsockopt. After that we can set the
2574 * ipx type in the sockaddr_opx structure with the stored value.
2576 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
2577 uipx->sipx_type = val;
2579 #endif
2582 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
2583 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
2584 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2585 hdr.msg_accrights = NULL;
2586 hdr.msg_accrightslen = 0;
2587 #else
2588 hdr.msg_control = NULL;
2589 hdr.msg_controllen = 0;
2590 hdr.msg_flags = 0;
2591 #endif
2593 while ((ret = sendmsg(fd, &hdr, flags)) == -1)
2595 if (errno != EINTR)
2596 return -1;
2599 n = ret;
2600 while (wsa->first_iovec < wsa->n_iovecs && wsa->iovec[wsa->first_iovec].iov_len <= n)
2601 n -= wsa->iovec[wsa->first_iovec++].iov_len;
2602 if (wsa->first_iovec < wsa->n_iovecs)
2604 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
2605 wsa->iovec[wsa->first_iovec].iov_len -= n;
2607 return ret;
2610 /***********************************************************************
2611 * WS2_async_send (INTERNAL)
2613 * Handler for overlapped send() operations.
2615 static NTSTATUS WS2_async_send( void *user, IO_STATUS_BLOCK *iosb, NTSTATUS status )
2617 struct ws2_async *wsa = user;
2618 int result = 0, fd;
2620 switch (status)
2622 case STATUS_ALERTED:
2623 if ( wsa->n_iovecs <= wsa->first_iovec )
2625 /* Nothing to do */
2626 status = STATUS_SUCCESS;
2627 break;
2629 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
2630 break;
2632 /* check to see if the data is ready (non-blocking) */
2633 result = WS2_send( fd, wsa, convert_flags(wsa->flags) );
2634 wine_server_release_fd( wsa->hSocket, fd );
2636 if (result >= 0)
2638 if (wsa->first_iovec < wsa->n_iovecs)
2639 status = STATUS_PENDING;
2640 else
2641 status = STATUS_SUCCESS;
2643 iosb->Information += result;
2645 else if (errno == EAGAIN)
2647 status = STATUS_PENDING;
2649 else
2651 status = wsaErrStatus();
2653 break;
2655 if (status != STATUS_PENDING)
2657 iosb->u.Status = status;
2658 if (!wsa->completion_func)
2659 release_async_io( &wsa->io );
2661 return status;
2664 /***********************************************************************
2665 * WS2_async_shutdown (INTERNAL)
2667 * Handler for shutdown() operations on overlapped sockets.
2669 static NTSTATUS WS2_async_shutdown( void *user, IO_STATUS_BLOCK *iosb, NTSTATUS status )
2671 struct ws2_async_shutdown *wsa = user;
2672 int fd, err = 1;
2674 switch (status)
2676 case STATUS_ALERTED:
2677 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
2678 break;
2680 switch ( wsa->type )
2682 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
2683 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
2685 status = err ? wsaErrStatus() : STATUS_SUCCESS;
2686 wine_server_release_fd( wsa->hSocket, fd );
2687 break;
2689 iosb->u.Status = status;
2690 iosb->Information = 0;
2691 release_async_io( &wsa->io );
2692 return status;
2695 /***********************************************************************
2696 * WS2_register_async_shutdown (INTERNAL)
2698 * Helper function for WS_shutdown() on overlapped sockets.
2700 static int WS2_register_async_shutdown( SOCKET s, int type )
2702 struct ws2_async_shutdown *wsa;
2703 NTSTATUS status;
2705 TRACE("socket %04lx type %d\n", s, type);
2707 wsa = (struct ws2_async_shutdown *)alloc_async_io( sizeof(*wsa), WS2_async_shutdown );
2708 if ( !wsa )
2709 return WSAEFAULT;
2711 wsa->hSocket = SOCKET2HANDLE(s);
2712 wsa->type = type;
2714 status = register_async( type, wsa->hSocket, &wsa->io, 0, NULL, NULL, &wsa->iosb );
2715 if (status != STATUS_PENDING)
2717 HeapFree( GetProcessHeap(), 0, wsa );
2718 return NtStatusToWSAError( status );
2720 return 0;
2723 /***********************************************************************
2724 * accept (WS2_32.1)
2726 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr, int *addrlen32)
2728 NTSTATUS status;
2729 SOCKET as;
2730 BOOL is_blocking;
2732 TRACE("socket %04lx\n", s );
2733 status = _is_blocking(s, &is_blocking);
2734 if (status)
2735 goto error;
2737 do {
2738 /* try accepting first (if there is a deferred connection) */
2739 SERVER_START_REQ( accept_socket )
2741 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
2742 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
2743 req->attributes = OBJ_INHERIT;
2744 status = wine_server_call( req );
2745 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
2747 SERVER_END_REQ;
2748 if (!status)
2750 if (addr && addrlen32 && WS_getpeername(as, addr, addrlen32))
2752 WS_closesocket(as);
2753 return SOCKET_ERROR;
2755 TRACE("\taccepted %04lx\n", as);
2756 return as;
2758 if (is_blocking && status == STATUS_CANT_WAIT)
2760 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2761 /* block here */
2762 do_block(fd, POLLIN, -1);
2763 _sync_sock_state(s); /* let wineserver notice connection */
2764 release_sock_fd( s, fd );
2766 } while (is_blocking && status == STATUS_CANT_WAIT);
2768 error:
2769 set_error(status);
2770 WARN(" -> ERROR %d\n", GetLastError());
2771 return INVALID_SOCKET;
2774 /***********************************************************************
2775 * AcceptEx
2777 static BOOL WINAPI WS2_AcceptEx(SOCKET listener, SOCKET acceptor, PVOID dest, DWORD dest_len,
2778 DWORD local_addr_len, DWORD rem_addr_len, LPDWORD received,
2779 LPOVERLAPPED overlapped)
2781 DWORD status;
2782 struct ws2_accept_async *wsa;
2783 int fd;
2785 TRACE("(%04lx, %04lx, %p, %d, %d, %d, %p, %p)\n", listener, acceptor, dest, dest_len, local_addr_len,
2786 rem_addr_len, received, overlapped);
2788 if (!dest)
2790 SetLastError(WSAEINVAL);
2791 return FALSE;
2794 if (!overlapped)
2796 SetLastError(WSA_INVALID_PARAMETER);
2797 return FALSE;
2800 if (!rem_addr_len)
2802 SetLastError(WSAEFAULT);
2803 return FALSE;
2806 fd = get_sock_fd( listener, FILE_READ_DATA, NULL );
2807 if (fd == -1)
2809 SetLastError(WSAENOTSOCK);
2810 return FALSE;
2812 release_sock_fd( listener, fd );
2814 fd = get_sock_fd( acceptor, FILE_READ_DATA, NULL );
2815 if (fd == -1)
2817 SetLastError(WSAENOTSOCK);
2818 return FALSE;
2820 release_sock_fd( acceptor, fd );
2822 wsa = (struct ws2_accept_async *)alloc_async_io( sizeof(*wsa), WS2_async_accept );
2823 if(!wsa)
2825 SetLastError(WSAEFAULT);
2826 return FALSE;
2829 wsa->listen_socket = SOCKET2HANDLE(listener);
2830 wsa->accept_socket = SOCKET2HANDLE(acceptor);
2831 wsa->user_overlapped = overlapped;
2832 wsa->cvalue = !((ULONG_PTR)overlapped->hEvent & 1) ? (ULONG_PTR)overlapped : 0;
2833 wsa->buf = dest;
2834 wsa->data_len = dest_len;
2835 wsa->local_len = local_addr_len;
2836 wsa->remote_len = rem_addr_len;
2837 wsa->read = NULL;
2839 if (wsa->data_len)
2841 /* set up a read request if we need it */
2842 wsa->read = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[1]), WS2_async_accept_recv );
2843 if (!wsa->read)
2845 HeapFree( GetProcessHeap(), 0, wsa );
2846 SetLastError(WSAEFAULT);
2847 return FALSE;
2850 wsa->read->hSocket = wsa->accept_socket;
2851 wsa->read->flags = 0;
2852 wsa->read->lpFlags = &wsa->read->flags;
2853 wsa->read->addr = NULL;
2854 wsa->read->addrlen.ptr = NULL;
2855 wsa->read->control = NULL;
2856 wsa->read->n_iovecs = 1;
2857 wsa->read->first_iovec = 0;
2858 wsa->read->completion_func = NULL;
2859 wsa->read->iovec[0].iov_base = wsa->buf;
2860 wsa->read->iovec[0].iov_len = wsa->data_len;
2863 status = register_async( ASYNC_TYPE_READ, SOCKET2HANDLE(listener), &wsa->io,
2864 overlapped->hEvent, NULL, (void *)wsa->cvalue, (IO_STATUS_BLOCK *)overlapped );
2866 if(status != STATUS_PENDING)
2868 HeapFree( GetProcessHeap(), 0, wsa->read );
2869 HeapFree( GetProcessHeap(), 0, wsa );
2872 SetLastError( NtStatusToWSAError(status) );
2873 return FALSE;
2876 /***********************************************************************
2877 * WS2_ReadFile (INTERNAL)
2879 * Perform an APC-safe ReadFile operation
2881 static NTSTATUS WS2_ReadFile(HANDLE hFile, PIO_STATUS_BLOCK io_status, char* buffer, ULONG length,
2882 PLARGE_INTEGER offset)
2884 int result = -1, unix_handle;
2885 unsigned int options;
2886 NTSTATUS status;
2888 TRACE( "(%p,%p,0x%08x)\n", hFile, buffer,length );
2890 status = wine_server_handle_to_fd( hFile, FILE_READ_DATA, &unix_handle, &options );
2891 if (status) return status;
2893 while (result == -1)
2895 if (offset->QuadPart != FILE_USE_FILE_POINTER_POSITION)
2896 result = pread( unix_handle, buffer, length, offset->QuadPart );
2897 else
2898 result = read( unix_handle, buffer, length );
2899 if (errno != EINTR)
2900 break;
2903 if (!result)
2904 status = (length ? STATUS_END_OF_FILE : STATUS_SUCCESS);
2905 else if (result != -1)
2906 status = STATUS_SUCCESS;
2907 else if (errno != EAGAIN)
2908 status = wsaErrStatus();
2909 else
2910 status = STATUS_PENDING;
2912 wine_server_release_fd( hFile, unix_handle );
2913 TRACE("= 0x%08x (%d)\n", status, result);
2914 if (status == STATUS_SUCCESS || status == STATUS_END_OF_FILE)
2916 io_status->u.Status = status;
2917 io_status->Information = result;
2920 return status;
2923 /***********************************************************************
2924 * WS2_transmitfile_getbuffer (INTERNAL)
2926 * Pick the appropriate buffer for a TransmitFile send operation.
2928 static NTSTATUS WS2_transmitfile_getbuffer( int fd, struct ws2_transmitfile_async *wsa )
2930 /* send any incomplete writes from a previous iteration */
2931 if (wsa->write.first_iovec < wsa->write.n_iovecs)
2932 return STATUS_PENDING;
2934 /* process the header (if applicable) */
2935 if (wsa->buffers.Head)
2937 wsa->write.first_iovec = 0;
2938 wsa->write.n_iovecs = 1;
2939 wsa->write.iovec[0].iov_base = wsa->buffers.Head;
2940 wsa->write.iovec[0].iov_len = wsa->buffers.HeadLength;
2941 wsa->buffers.Head = NULL;
2942 return STATUS_PENDING;
2945 /* process the main file */
2946 if (wsa->file)
2948 DWORD bytes_per_send = wsa->bytes_per_send;
2949 IO_STATUS_BLOCK iosb;
2950 NTSTATUS status;
2952 iosb.Information = 0;
2953 /* when the size of the transfer is limited ensure that we don't go past that limit */
2954 if (wsa->file_bytes != 0)
2955 bytes_per_send = min(bytes_per_send, wsa->file_bytes - wsa->file_read);
2956 status = WS2_ReadFile( wsa->file, &iosb, wsa->buffer, bytes_per_send, &wsa->offset );
2957 if (wsa->offset.QuadPart != FILE_USE_FILE_POINTER_POSITION)
2958 wsa->offset.QuadPart += iosb.Information;
2959 if (status == STATUS_END_OF_FILE)
2960 wsa->file = NULL; /* continue on to the footer */
2961 else if (status != STATUS_SUCCESS)
2962 return status;
2963 else
2965 if (iosb.Information)
2967 wsa->write.first_iovec = 0;
2968 wsa->write.n_iovecs = 1;
2969 wsa->write.iovec[0].iov_base = wsa->buffer;
2970 wsa->write.iovec[0].iov_len = iosb.Information;
2971 wsa->file_read += iosb.Information;
2974 if (wsa->file_bytes != 0 && wsa->file_read >= wsa->file_bytes)
2975 wsa->file = NULL;
2977 return STATUS_PENDING;
2981 /* send the footer (if applicable) */
2982 if (wsa->buffers.Tail)
2984 wsa->write.first_iovec = 0;
2985 wsa->write.n_iovecs = 1;
2986 wsa->write.iovec[0].iov_base = wsa->buffers.Tail;
2987 wsa->write.iovec[0].iov_len = wsa->buffers.TailLength;
2988 wsa->buffers.Tail = NULL;
2989 return STATUS_PENDING;
2992 return STATUS_SUCCESS;
2995 /***********************************************************************
2996 * WS2_transmitfile_base (INTERNAL)
2998 * Shared implementation for both synchronous and asynchronous TransmitFile.
3000 static NTSTATUS WS2_transmitfile_base( int fd, struct ws2_transmitfile_async *wsa )
3002 NTSTATUS status;
3004 status = WS2_transmitfile_getbuffer( fd, wsa );
3005 if (status == STATUS_PENDING)
3007 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)wsa->write.user_overlapped;
3008 int n;
3010 n = WS2_send( fd, &wsa->write, convert_flags(wsa->write.flags) );
3011 if (n >= 0)
3013 if (iosb) iosb->Information += n;
3015 else if (errno != EAGAIN)
3016 return wsaErrStatus();
3019 return status;
3022 /***********************************************************************
3023 * WS2_async_transmitfile (INTERNAL)
3025 * Asynchronous callback for overlapped TransmitFile operations.
3027 static NTSTATUS WS2_async_transmitfile( void *user, IO_STATUS_BLOCK *iosb, NTSTATUS status )
3029 struct ws2_transmitfile_async *wsa = user;
3030 int fd;
3032 if (status == STATUS_ALERTED)
3034 if (!(status = wine_server_handle_to_fd( wsa->write.hSocket, FILE_WRITE_DATA, &fd, NULL )))
3036 status = WS2_transmitfile_base( fd, wsa );
3037 wine_server_release_fd( wsa->write.hSocket, fd );
3039 if (status == STATUS_PENDING)
3040 return status;
3043 iosb->u.Status = status;
3044 release_async_io( &wsa->io );
3045 return status;
3048 /***********************************************************************
3049 * TransmitFile
3051 static BOOL WINAPI WS2_TransmitFile( SOCKET s, HANDLE h, DWORD file_bytes, DWORD bytes_per_send,
3052 LPOVERLAPPED overlapped, LPTRANSMIT_FILE_BUFFERS buffers,
3053 DWORD flags )
3055 union generic_unix_sockaddr uaddr;
3056 socklen_t uaddrlen = sizeof(uaddr);
3057 struct ws2_transmitfile_async *wsa;
3058 NTSTATUS status;
3059 int fd;
3061 TRACE("(%lx, %p, %d, %d, %p, %p, %d)\n", s, h, file_bytes, bytes_per_send, overlapped,
3062 buffers, flags );
3064 fd = get_sock_fd( s, FILE_WRITE_DATA, NULL );
3065 if (fd == -1)
3067 WSASetLastError( WSAENOTSOCK );
3068 return FALSE;
3070 if (getpeername( fd, &uaddr.addr, &uaddrlen ) != 0)
3072 release_sock_fd( s, fd );
3073 WSASetLastError( WSAENOTCONN );
3074 return FALSE;
3076 if (flags)
3077 FIXME("Flags are not currently supported (0x%x).\n", flags);
3079 if (h && GetFileType( h ) != FILE_TYPE_DISK)
3081 FIXME("Non-disk file handles are not currently supported.\n");
3082 release_sock_fd( s, fd );
3083 WSASetLastError( WSAEOPNOTSUPP );
3084 return FALSE;
3087 /* set reasonable defaults when requested */
3088 if (!bytes_per_send)
3089 bytes_per_send = (1 << 16); /* Depends on OS version: PAGE_SIZE, 2*PAGE_SIZE, or 2^16 */
3091 if (!(wsa = (struct ws2_transmitfile_async *)alloc_async_io( sizeof(*wsa) + bytes_per_send,
3092 WS2_async_transmitfile )))
3094 release_sock_fd( s, fd );
3095 WSASetLastError( WSAEFAULT );
3096 return FALSE;
3098 if (buffers)
3099 wsa->buffers = *buffers;
3100 else
3101 memset(&wsa->buffers, 0x0, sizeof(wsa->buffers));
3102 wsa->buffer = (char *)(wsa + 1);
3103 wsa->file = h;
3104 wsa->file_read = 0;
3105 wsa->file_bytes = file_bytes;
3106 wsa->bytes_per_send = bytes_per_send;
3107 wsa->flags = flags;
3108 wsa->offset.QuadPart = FILE_USE_FILE_POINTER_POSITION;
3109 wsa->write.hSocket = SOCKET2HANDLE(s);
3110 wsa->write.addr = NULL;
3111 wsa->write.addrlen.val = 0;
3112 wsa->write.flags = 0;
3113 wsa->write.lpFlags = &wsa->flags;
3114 wsa->write.control = NULL;
3115 wsa->write.n_iovecs = 0;
3116 wsa->write.first_iovec = 0;
3117 wsa->write.user_overlapped = overlapped;
3118 if (overlapped)
3120 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)overlapped;
3121 int status;
3123 wsa->offset.u.LowPart = overlapped->u.s.Offset;
3124 wsa->offset.u.HighPart = overlapped->u.s.OffsetHigh;
3125 iosb->u.Status = STATUS_PENDING;
3126 iosb->Information = 0;
3127 status = register_async( ASYNC_TYPE_WRITE, SOCKET2HANDLE(s), &wsa->io,
3128 overlapped->hEvent, NULL, NULL, iosb );
3129 if(status != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
3130 release_sock_fd( s, fd );
3131 WSASetLastError( NtStatusToWSAError(status) );
3132 return FALSE;
3137 status = WS2_transmitfile_base( fd, wsa );
3138 if (status == STATUS_PENDING)
3140 /* block here */
3141 do_block(fd, POLLOUT, -1);
3142 _sync_sock_state(s); /* let wineserver notice connection */
3145 while (status == STATUS_PENDING);
3146 release_sock_fd( s, fd );
3148 if (status != STATUS_SUCCESS)
3149 WSASetLastError( NtStatusToWSAError(status) );
3150 HeapFree( GetProcessHeap(), 0, wsa );
3151 return (status == STATUS_SUCCESS);
3154 /***********************************************************************
3155 * GetAcceptExSockaddrs
3157 static void WINAPI WS2_GetAcceptExSockaddrs(PVOID buffer, DWORD data_size, DWORD local_size, DWORD remote_size,
3158 struct WS_sockaddr **local_addr, LPINT local_addr_len,
3159 struct WS_sockaddr **remote_addr, LPINT remote_addr_len)
3161 char *cbuf = buffer;
3162 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer, data_size, local_size, remote_size, local_addr,
3163 local_addr_len, remote_addr, remote_addr_len );
3164 cbuf += data_size;
3166 *local_addr_len = *(int *) cbuf;
3167 *local_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
3169 cbuf += local_size;
3171 *remote_addr_len = *(int *) cbuf;
3172 *remote_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
3175 /***********************************************************************
3176 * WSASendMsg
3178 int WINAPI WSASendMsg( SOCKET s, LPWSAMSG msg, DWORD dwFlags, LPDWORD lpNumberOfBytesSent,
3179 LPWSAOVERLAPPED lpOverlapped,
3180 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
3182 if (!msg)
3184 SetLastError( WSAEFAULT );
3185 return SOCKET_ERROR;
3188 return WS2_sendto( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesSent,
3189 dwFlags, msg->name, msg->namelen,
3190 lpOverlapped, lpCompletionRoutine );
3193 /***********************************************************************
3194 * WSARecvMsg
3196 * Perform a receive operation that is capable of returning message
3197 * control headers. It is important to note that the WSAMSG parameter
3198 * must remain valid throughout the operation, even when an overlapped
3199 * receive is performed.
3201 static int WINAPI WS2_WSARecvMsg( SOCKET s, LPWSAMSG msg, LPDWORD lpNumberOfBytesRecvd,
3202 LPWSAOVERLAPPED lpOverlapped,
3203 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3205 if (!msg)
3207 SetLastError( WSAEFAULT );
3208 return SOCKET_ERROR;
3211 return WS2_recv_base( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesRecvd,
3212 &msg->dwFlags, msg->name, &msg->namelen,
3213 lpOverlapped, lpCompletionRoutine, &msg->Control );
3216 /***********************************************************************
3217 * interface_bind (INTERNAL)
3219 * Take bind() calls on any name corresponding to a local network adapter and restrict the given socket to
3220 * operating only on the specified interface. This restriction consists of two components:
3221 * 1) An outgoing packet restriction suggesting the egress interface for all packets.
3222 * 2) An incoming packet restriction dropping packets not meant for the interface.
3223 * If the function succeeds in placing these restrictions (returns TRUE) then the name for the bind() may
3224 * safely be changed to INADDR_ANY, permitting the transmission and receipt of broadcast packets on the
3225 * socket. This behavior is only relevant to UDP sockets and is needed for applications that expect to be able
3226 * to receive broadcast packets on a socket that is bound to a specific network interface.
3228 static BOOL interface_bind( SOCKET s, int fd, struct sockaddr *addr )
3230 struct sockaddr_in *in_sock = (struct sockaddr_in *) addr;
3231 in_addr_t bind_addr = in_sock->sin_addr.s_addr;
3232 PIP_ADAPTER_INFO adapters = NULL, adapter;
3233 BOOL ret = FALSE;
3234 DWORD adap_size;
3235 int enable = 1;
3237 if (bind_addr == htonl(INADDR_ANY) || bind_addr == htonl(INADDR_LOOPBACK))
3238 return FALSE; /* Not binding to a network adapter, special interface binding unnecessary. */
3239 if (_get_fd_type(fd) != SOCK_DGRAM)
3240 return FALSE; /* Special interface binding is only necessary for UDP datagrams. */
3241 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
3242 goto cleanup;
3243 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
3244 if (adapters == NULL || GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
3245 goto cleanup;
3246 /* Search the IPv4 adapter list for the appropriate binding interface */
3247 for (adapter = adapters; adapter != NULL; adapter = adapter->Next)
3249 in_addr_t adapter_addr = (in_addr_t) inet_addr(adapter->IpAddressList.IpAddress.String);
3251 if (bind_addr == adapter_addr)
3253 #if defined(IP_BOUND_IF)
3254 /* IP_BOUND_IF sets both the incoming and outgoing restriction at once */
3255 if (setsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &adapter->Index, sizeof(adapter->Index)) != 0)
3256 goto cleanup;
3257 ret = TRUE;
3258 #elif defined(LINUX_BOUND_IF)
3259 in_addr_t ifindex = (in_addr_t) htonl(adapter->Index);
3260 struct interface_filter specific_interface_filter;
3261 struct sock_fprog filter_prog;
3263 if (setsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex, sizeof(ifindex)) != 0)
3264 goto cleanup; /* Failed to suggest egress interface */
3265 specific_interface_filter = generic_interface_filter;
3266 specific_interface_filter.iface_rule.k = adapter->Index;
3267 specific_interface_filter.ip_rule.k = htonl(adapter_addr);
3268 filter_prog.len = sizeof(generic_interface_filter)/sizeof(struct sock_filter);
3269 filter_prog.filter = (struct sock_filter *) &specific_interface_filter;
3270 if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog, sizeof(filter_prog)) != 0)
3271 goto cleanup; /* Failed to specify incoming packet filter */
3272 ret = TRUE;
3273 #else
3274 FIXME("Broadcast packets on interface-bound sockets are not currently supported on this platform, "
3275 "receiving broadcast packets will not work on socket %04lx.\n", s);
3276 #endif
3277 break;
3280 /* Will soon be switching to INADDR_ANY: permit address reuse */
3281 if (ret && setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) == 0)
3282 TRACE("Socket %04lx bound to interface index %d\n", s, adapter->Index);
3283 else
3284 ret = FALSE;
3286 cleanup:
3287 if(!ret)
3288 ERR("Failed to bind to interface, receiving broadcast packets will not work on socket %04lx.\n", s);
3289 HeapFree(GetProcessHeap(), 0, adapters);
3290 return ret;
3293 /***********************************************************************
3294 * bind (WS2_32.2)
3296 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
3298 int fd = get_sock_fd( s, 0, NULL );
3299 int res = SOCKET_ERROR;
3301 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
3303 if (fd != -1)
3305 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
3307 SetLastError(WSAEAFNOSUPPORT);
3309 else
3311 union generic_unix_sockaddr uaddr;
3312 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
3313 if (!uaddrlen)
3315 SetLastError(WSAEFAULT);
3317 else
3319 if (name->sa_family == WS_AF_INET)
3321 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
3322 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
3324 /* Trying to bind to the default host interface, using
3325 * INADDR_ANY instead*/
3326 WARN("Trying to bind to magic IP address, using "
3327 "INADDR_ANY instead.\n");
3328 in4->sin_addr.s_addr = htonl(INADDR_ANY);
3330 else if (interface_bind(s, fd, &uaddr.addr))
3331 in4->sin_addr.s_addr = htonl(INADDR_ANY);
3333 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
3335 int loc_errno = errno;
3336 WARN("\tfailure - errno = %i\n", errno);
3337 errno = loc_errno;
3338 switch (errno)
3340 case EADDRNOTAVAIL:
3341 SetLastError(WSAEINVAL);
3342 break;
3343 case EADDRINUSE:
3345 int optval = 0;
3346 socklen_t optlen = sizeof(optval);
3347 /* Windows >= 2003 will return different results depending on
3348 * SO_REUSEADDR, WSAEACCES may be returned representing that
3349 * the socket hijacking protection prevented the bind */
3350 if (!getsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&optval, &optlen) && optval)
3352 SetLastError(WSAEACCES);
3353 break;
3355 /* fall through */
3357 default:
3358 SetLastError(wsaErrno());
3359 break;
3362 else
3364 res=0; /* success */
3368 release_sock_fd( s, fd );
3370 return res;
3373 /***********************************************************************
3374 * closesocket (WS2_32.3)
3376 int WINAPI WS_closesocket(SOCKET s)
3378 int res = SOCKET_ERROR, fd;
3379 if (num_startup)
3381 fd = get_sock_fd(s, FILE_READ_DATA, NULL);
3382 if (fd >= 0)
3384 release_sock_fd(s, fd);
3385 if (CloseHandle(SOCKET2HANDLE(s)))
3386 res = 0;
3388 else
3389 SetLastError(WSAENOTSOCK);
3391 else
3392 SetLastError(WSANOTINITIALISED);
3393 TRACE("(socket %04lx) -> %d\n", s, res);
3394 return res;
3397 static int do_connect(int fd, const struct WS_sockaddr* name, int namelen)
3399 union generic_unix_sockaddr uaddr;
3400 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
3402 if (!uaddrlen)
3403 return WSAEFAULT;
3405 if (name->sa_family == WS_AF_INET)
3407 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
3408 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
3410 /* Trying to connect to magic replace-loopback address,
3411 * assuming we really want to connect to localhost */
3412 TRACE("Trying to connect to magic IP address, using "
3413 "INADDR_LOOPBACK instead.\n");
3414 in4->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
3418 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
3419 return 0;
3421 return wsaErrno();
3424 /***********************************************************************
3425 * connect (WS2_32.4)
3427 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
3429 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
3431 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
3433 if (fd != -1)
3435 NTSTATUS status;
3436 BOOL is_blocking;
3437 int ret = do_connect(fd, name, namelen);
3438 if (ret == 0)
3439 goto connect_success;
3441 if (ret == WSAEINPROGRESS)
3443 /* tell wineserver that a connection is in progress */
3444 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3445 FD_CONNECT,
3446 FD_WINE_CONNECTED|FD_WINE_LISTENING);
3447 status = _is_blocking( s, &is_blocking );
3448 if (status)
3450 release_sock_fd( s, fd );
3451 set_error( status );
3452 return SOCKET_ERROR;
3454 if (is_blocking)
3456 int result;
3457 /* block here */
3458 do_block(fd, POLLIN | POLLOUT, -1);
3459 _sync_sock_state(s); /* let wineserver notice connection */
3460 /* retrieve any error codes from it */
3461 result = _get_sock_error(s, FD_CONNECT_BIT);
3462 if (result)
3463 SetLastError(NtStatusToWSAError(result));
3464 else
3466 goto connect_success;
3469 else
3471 SetLastError(WSAEWOULDBLOCK);
3474 else
3476 SetLastError(ret);
3478 release_sock_fd( s, fd );
3480 return SOCKET_ERROR;
3482 connect_success:
3483 release_sock_fd( s, fd );
3484 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3485 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
3486 FD_CONNECT|FD_WINE_LISTENING);
3487 TRACE("\tconnected %04lx\n", s);
3488 return 0;
3491 /***********************************************************************
3492 * WSAConnect (WS2_32.30)
3494 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
3495 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
3496 LPQOS lpSQOS, LPQOS lpGQOS )
3498 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
3499 FIXME("unsupported parameters!\n");
3500 return WS_connect( s, name, namelen );
3503 /***********************************************************************
3504 * ConnectEx
3506 static BOOL WINAPI WS2_ConnectEx(SOCKET s, const struct WS_sockaddr* name, int namelen,
3507 PVOID sendBuf, DWORD sendBufLen, LPDWORD sent, LPOVERLAPPED ov)
3509 int fd, ret, status;
3511 if (!ov)
3513 SetLastError( ERROR_INVALID_PARAMETER );
3514 return FALSE;
3517 fd = get_sock_fd( s, FILE_READ_DATA, NULL );
3518 if (fd == -1)
3520 SetLastError( WSAENOTSOCK );
3521 return FALSE;
3524 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
3525 s, name, debugstr_sockaddr(name), namelen, sendBuf, sendBufLen, ov);
3527 ret = is_fd_bound(fd, NULL, NULL);
3528 if (ret <= 0)
3530 SetLastError(ret == -1 ? wsaErrno() : WSAEINVAL);
3531 release_sock_fd( s, fd );
3532 return FALSE;
3535 ret = do_connect(fd, name, namelen);
3536 if (ret == 0)
3538 WSABUF wsabuf;
3540 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3541 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
3542 FD_CONNECT|FD_WINE_LISTENING);
3544 wsabuf.len = sendBufLen;
3545 wsabuf.buf = (char*) sendBuf;
3547 /* WSASend takes care of completion if need be */
3548 if (WSASend(s, &wsabuf, sendBuf ? 1 : 0, sent, 0, ov, NULL) != SOCKET_ERROR)
3549 goto connection_success;
3551 else if (ret == WSAEINPROGRESS)
3553 struct ws2_async *wsa;
3554 ULONG_PTR cvalue = (((ULONG_PTR)ov->hEvent & 1) == 0) ? (ULONG_PTR)ov : 0;
3556 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3557 FD_CONNECT,
3558 FD_WINE_CONNECTED|FD_WINE_LISTENING);
3560 /* Indirectly call WSASend */
3561 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof( struct ws2_async, iovec[1] ), WS2_async_send )))
3563 SetLastError(WSAEFAULT);
3565 else
3567 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)ov;
3568 iosb->u.Status = STATUS_PENDING;
3569 iosb->Information = 0;
3571 wsa->hSocket = SOCKET2HANDLE(s);
3572 wsa->addr = NULL;
3573 wsa->addrlen.val = 0;
3574 wsa->flags = 0;
3575 wsa->lpFlags = &wsa->flags;
3576 wsa->control = NULL;
3577 wsa->n_iovecs = sendBuf ? 1 : 0;
3578 wsa->first_iovec = 0;
3579 wsa->completion_func = NULL;
3580 wsa->iovec[0].iov_base = sendBuf;
3581 wsa->iovec[0].iov_len = sendBufLen;
3583 status = register_async( ASYNC_TYPE_WRITE, wsa->hSocket, &wsa->io, ov->hEvent,
3584 NULL, (void *)cvalue, iosb );
3585 if (status != STATUS_PENDING) HeapFree(GetProcessHeap(), 0, wsa);
3587 /* If the connect already failed */
3588 if (status == STATUS_PIPE_DISCONNECTED)
3589 status = _get_sock_error(s, FD_CONNECT_BIT);
3590 SetLastError( NtStatusToWSAError(status) );
3593 else
3595 SetLastError(ret);
3598 release_sock_fd( s, fd );
3599 return FALSE;
3601 connection_success:
3602 release_sock_fd( s, fd );
3603 return TRUE;
3606 /***********************************************************************
3607 * DisconnectEx
3609 static BOOL WINAPI WS2_DisconnectEx( SOCKET s, LPOVERLAPPED ov, DWORD flags, DWORD reserved )
3611 TRACE( "socket %04lx, ov %p, flags 0x%x, reserved 0x%x\n", s, ov, flags, reserved );
3613 if (flags & TF_REUSE_SOCKET)
3614 FIXME( "Reusing socket not supported yet\n" );
3616 if (ov)
3618 ov->Internal = STATUS_PENDING;
3619 ov->InternalHigh = 0;
3622 return !WS_shutdown( s, SD_BOTH );
3625 /***********************************************************************
3626 * getpeername (WS2_32.5)
3628 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
3630 int fd;
3631 int res;
3633 TRACE("socket %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
3635 fd = get_sock_fd( s, 0, NULL );
3636 res = SOCKET_ERROR;
3638 if (fd != -1)
3640 union generic_unix_sockaddr uaddr;
3641 socklen_t uaddrlen = sizeof(uaddr);
3643 if (getpeername(fd, &uaddr.addr, &uaddrlen) == 0)
3645 if (!name || !namelen)
3646 SetLastError(WSAEFAULT);
3647 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3648 /* The buffer was too small */
3649 SetLastError(WSAEFAULT);
3650 else
3652 res = 0;
3653 TRACE("=> %s\n", debugstr_sockaddr(name));
3656 else
3657 SetLastError(wsaErrno());
3658 release_sock_fd( s, fd );
3660 return res;
3663 /* When binding to an UDP address with filter support the getsockname call on the socket
3664 * will always return 0.0.0.0 instead of the filtered interface address. This function
3665 * checks if the socket is interface-bound on UDP and return the correct address.
3666 * This is required because applications often do a bind() with port zero followed by a
3667 * getsockname() to retrieve the port and address acquired.
3669 static void interface_bind_check(int fd, struct sockaddr_in *addr)
3671 #if !defined(IP_BOUND_IF) && !defined(LINUX_BOUND_IF)
3672 return;
3673 #else
3674 unsigned int ifindex;
3675 int ret;
3676 socklen_t len;
3678 /* Check for IPv4, address 0.0.0.0 and UDP socket */
3679 if (addr->sin_family != AF_INET || addr->sin_addr.s_addr != 0)
3680 return;
3681 if (_get_fd_type(fd) != SOCK_DGRAM)
3682 return;
3684 len = sizeof(ifindex);
3685 #if defined(IP_BOUND_IF)
3686 ret = getsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &ifindex, &len);
3687 #elif defined(LINUX_BOUND_IF)
3688 ret = getsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex, &len);
3689 if (!ret) ifindex = ntohl(ifindex);
3690 #endif
3691 if (!ret)
3693 PIP_ADAPTER_INFO adapters, adapter;
3694 DWORD adap_size;
3696 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
3697 return;
3698 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
3699 if (adapters && GetAdaptersInfo(adapters, &adap_size) == NO_ERROR)
3701 /* Search the IPv4 adapter list for the appropriate bound interface */
3702 for (adapter = adapters; adapter != NULL; adapter = adapter->Next)
3704 in_addr_t adapter_addr;
3705 if (adapter->Index != ifindex) continue;
3707 adapter_addr = inet_addr(adapter->IpAddressList.IpAddress.String);
3708 addr->sin_addr.s_addr = adapter_addr;
3709 TRACE("reporting interface address from adapter %d\n", ifindex);
3710 break;
3713 HeapFree(GetProcessHeap(), 0, adapters);
3715 #endif
3718 /***********************************************************************
3719 * getsockname (WS2_32.6)
3721 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
3723 int fd;
3724 int res;
3726 TRACE("socket %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
3728 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
3729 if( (name == NULL) || (namelen == NULL) )
3731 SetLastError( WSAEFAULT );
3732 return SOCKET_ERROR;
3735 fd = get_sock_fd( s, 0, NULL );
3736 res = SOCKET_ERROR;
3738 if (fd != -1)
3740 union generic_unix_sockaddr uaddr;
3741 socklen_t uaddrlen;
3742 int bound = is_fd_bound(fd, &uaddr, &uaddrlen);
3744 if (bound <= 0)
3746 SetLastError(bound == -1 ? wsaErrno() : WSAEINVAL);
3748 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3750 /* The buffer was too small */
3751 SetLastError(WSAEFAULT);
3753 else
3755 interface_bind_check(fd, (struct sockaddr_in*) &uaddr);
3756 if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3758 /* The buffer was too small */
3759 SetLastError(WSAEFAULT);
3761 else
3763 res = 0;
3764 TRACE("=> %s\n", debugstr_sockaddr(name));
3767 release_sock_fd( s, fd );
3769 return res;
3772 /***********************************************************************
3773 * getsockopt (WS2_32.7)
3775 INT WINAPI WS_getsockopt(SOCKET s, INT level,
3776 INT optname, char *optval, INT *optlen)
3778 int fd;
3779 INT ret = 0;
3781 TRACE("(socket %04lx, %s, optval %s, optlen %p (%d))\n", s,
3782 debugstr_sockopt(level, optname), debugstr_optval(optval, 0),
3783 optlen, optlen ? *optlen : 0);
3785 switch(level)
3787 case WS_SOL_SOCKET:
3789 switch(optname)
3791 /* Handle common cases. The special cases are below, sorted
3792 * alphabetically */
3793 case WS_SO_BROADCAST:
3794 case WS_SO_DEBUG:
3795 case WS_SO_KEEPALIVE:
3796 case WS_SO_OOBINLINE:
3797 case WS_SO_RCVBUF:
3798 case WS_SO_REUSEADDR:
3799 case WS_SO_SNDBUF:
3800 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3801 return SOCKET_ERROR;
3802 convert_sockopt(&level, &optname);
3803 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3805 SetLastError(wsaErrno());
3806 ret = SOCKET_ERROR;
3808 release_sock_fd( s, fd );
3809 return ret;
3810 case WS_SO_ACCEPTCONN:
3811 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3812 return SOCKET_ERROR;
3813 if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, optval, (socklen_t *)optlen) != 0 )
3815 SetLastError(wsaErrno());
3816 ret = SOCKET_ERROR;
3818 else
3820 /* BSD returns != 0 while Windows return exact == 1 */
3821 if (*(int *)optval) *(int *)optval = 1;
3823 release_sock_fd( s, fd );
3824 return ret;
3825 case WS_SO_BSP_STATE:
3827 int req_size, addr_size;
3828 WSAPROTOCOL_INFOW infow;
3829 CSADDR_INFO *csinfo;
3831 ret = ws_protocol_info(s, TRUE, &infow, &addr_size);
3832 if (ret)
3834 if (infow.iAddressFamily == WS_AF_INET)
3835 addr_size = sizeof(struct sockaddr_in);
3836 else if (infow.iAddressFamily == WS_AF_INET6)
3837 addr_size = sizeof(struct sockaddr_in6);
3838 else
3840 FIXME("Family %d is unsupported for SO_BSP_STATE\n", infow.iAddressFamily);
3841 SetLastError(WSAEAFNOSUPPORT);
3842 return SOCKET_ERROR;
3845 req_size = sizeof(CSADDR_INFO) + addr_size * 2;
3846 if (*optlen < req_size)
3848 ret = 0;
3849 SetLastError(WSAEFAULT);
3851 else
3853 union generic_unix_sockaddr uaddr;
3854 socklen_t uaddrlen;
3856 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3857 return SOCKET_ERROR;
3859 csinfo = (CSADDR_INFO*) optval;
3861 /* Check if the sock is bound */
3862 if (is_fd_bound(fd, &uaddr, &uaddrlen) == 1)
3864 csinfo->LocalAddr.lpSockaddr =
3865 (LPSOCKADDR) (optval + sizeof(CSADDR_INFO));
3866 ws_sockaddr_u2ws(&uaddr.addr, csinfo->LocalAddr.lpSockaddr, &addr_size);
3867 csinfo->LocalAddr.iSockaddrLength = addr_size;
3869 else
3871 csinfo->LocalAddr.lpSockaddr = NULL;
3872 csinfo->LocalAddr.iSockaddrLength = 0;
3875 /* Check if the sock is connected */
3876 if (!getpeername(fd, &uaddr.addr, &uaddrlen) &&
3877 is_sockaddr_bound(&uaddr.addr, uaddrlen))
3879 csinfo->RemoteAddr.lpSockaddr =
3880 (LPSOCKADDR) (optval + sizeof(CSADDR_INFO) + addr_size);
3881 ws_sockaddr_u2ws(&uaddr.addr, csinfo->RemoteAddr.lpSockaddr, &addr_size);
3882 csinfo->RemoteAddr.iSockaddrLength = addr_size;
3884 else
3886 csinfo->RemoteAddr.lpSockaddr = NULL;
3887 csinfo->RemoteAddr.iSockaddrLength = 0;
3890 csinfo->iSocketType = infow.iSocketType;
3891 csinfo->iProtocol = infow.iProtocol;
3892 release_sock_fd( s, fd );
3895 return ret ? 0 : SOCKET_ERROR;
3897 case WS_SO_DONTLINGER:
3899 struct linger lingval;
3900 socklen_t len = sizeof(struct linger);
3902 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
3904 SetLastError(WSAEFAULT);
3905 return SOCKET_ERROR;
3907 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3908 return SOCKET_ERROR;
3910 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
3912 SetLastError(wsaErrno());
3913 ret = SOCKET_ERROR;
3915 else
3917 *(BOOL *)optval = !lingval.l_onoff;
3918 *optlen = sizeof(BOOL);
3921 release_sock_fd( s, fd );
3922 return ret;
3925 case WS_SO_CONNECT_TIME:
3927 static int pretendtime = 0;
3928 struct WS_sockaddr addr;
3929 int len = sizeof(addr);
3931 if (!optlen || *optlen < sizeof(DWORD) || !optval)
3933 SetLastError(WSAEFAULT);
3934 return SOCKET_ERROR;
3936 if (WS_getpeername(s, &addr, &len) == SOCKET_ERROR)
3937 *(DWORD *)optval = ~0u;
3938 else
3940 if (!pretendtime) FIXME("WS_SO_CONNECT_TIME - faking results\n");
3941 *(DWORD *)optval = pretendtime++;
3943 *optlen = sizeof(DWORD);
3944 return ret;
3946 /* As mentioned in setsockopt, Windows ignores this, so we
3947 * always return true here */
3948 case WS_SO_DONTROUTE:
3949 if (!optlen || *optlen < sizeof(BOOL) || !optval)
3951 SetLastError(WSAEFAULT);
3952 return SOCKET_ERROR;
3954 *(BOOL *)optval = TRUE;
3955 *optlen = sizeof(BOOL);
3956 return 0;
3958 case WS_SO_ERROR:
3960 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3961 return SOCKET_ERROR;
3962 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, optval, (socklen_t *)optlen) != 0 )
3964 SetLastError(wsaErrno());
3965 ret = SOCKET_ERROR;
3967 release_sock_fd( s, fd );
3969 /* The wineserver may have swallowed the error before us */
3970 if (!ret && *(int*) optval == 0)
3972 int i, events[FD_MAX_EVENTS];
3973 _get_sock_errors(s, events);
3974 for (i = 0; i < FD_MAX_EVENTS; i++)
3976 if(events[i])
3978 events[i] = NtStatusToWSAError(events[i]);
3979 TRACE("returning SO_ERROR %d from wine server\n", events[i]);
3980 *(int*) optval = events[i];
3981 break;
3985 return ret;
3988 case WS_SO_LINGER:
3990 struct linger lingval;
3991 socklen_t len = sizeof(struct linger);
3993 /* struct linger and LINGER have different sizes */
3994 if (!optlen || *optlen < sizeof(LINGER) || !optval)
3996 SetLastError(WSAEFAULT);
3997 return SOCKET_ERROR;
3999 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4000 return SOCKET_ERROR;
4002 if (_get_fd_type(fd) == SOCK_DGRAM)
4004 SetLastError(WSAENOPROTOOPT);
4005 ret = SOCKET_ERROR;
4007 else if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0)
4009 SetLastError(wsaErrno());
4010 ret = SOCKET_ERROR;
4012 else
4014 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
4015 ((LINGER *)optval)->l_linger = lingval.l_linger;
4016 *optlen = sizeof(struct linger);
4019 release_sock_fd( s, fd );
4020 return ret;
4023 case WS_SO_MAX_MSG_SIZE:
4024 if (!optlen || *optlen < sizeof(int) || !optval)
4026 SetLastError(WSAEFAULT);
4027 return SOCKET_ERROR;
4029 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
4030 *(int *)optval = 65507;
4031 *optlen = sizeof(int);
4032 return 0;
4034 /* SO_OPENTYPE does not require a valid socket handle. */
4035 case WS_SO_OPENTYPE:
4036 if (!optlen || *optlen < sizeof(int) || !optval)
4038 SetLastError(WSAEFAULT);
4039 return SOCKET_ERROR;
4041 *(int *)optval = get_per_thread_data()->opentype;
4042 *optlen = sizeof(int);
4043 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
4044 return 0;
4045 case WS_SO_PROTOCOL_INFOA:
4046 case WS_SO_PROTOCOL_INFOW:
4048 int size;
4049 WSAPROTOCOL_INFOW infow;
4051 ret = ws_protocol_info(s, optname == WS_SO_PROTOCOL_INFOW, &infow, &size);
4052 if (ret)
4054 if (!optlen || !optval || *optlen < size)
4056 if(optlen) *optlen = size;
4057 ret = 0;
4058 SetLastError(WSAEFAULT);
4060 else
4061 memcpy(optval, &infow, size);
4063 return ret ? 0 : SOCKET_ERROR;
4065 case WS_SO_RCVTIMEO:
4066 case WS_SO_SNDTIMEO:
4068 INT64 timeout;
4070 if (!optlen || *optlen < sizeof(int)|| !optval)
4072 SetLastError(WSAEFAULT);
4073 return SOCKET_ERROR;
4075 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4076 return SOCKET_ERROR;
4078 timeout = get_rcvsnd_timeo(fd, optname == WS_SO_RCVTIMEO);
4079 *(int *)optval = timeout <= UINT_MAX ? timeout : UINT_MAX;
4081 release_sock_fd( s, fd );
4082 return ret;
4084 case WS_SO_TYPE:
4086 int sock_type;
4087 if (!optlen || *optlen < sizeof(int) || !optval)
4089 SetLastError(WSAEFAULT);
4090 return SOCKET_ERROR;
4092 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4093 return SOCKET_ERROR;
4095 sock_type = _get_fd_type(fd);
4096 if (sock_type == -1)
4098 SetLastError(wsaErrno());
4099 ret = SOCKET_ERROR;
4101 else
4102 (*(int *)optval) = convert_socktype_u2w(sock_type);
4104 release_sock_fd( s, fd );
4105 return ret;
4107 default:
4108 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
4109 SetLastError(WSAENOPROTOOPT);
4110 return SOCKET_ERROR;
4111 } /* end switch(optname) */
4112 }/* end case WS_SOL_SOCKET */
4113 #ifdef HAS_IPX
4114 case WS_NSPROTO_IPX:
4116 struct WS_sockaddr_ipx addr;
4117 IPX_ADDRESS_DATA *data;
4118 int namelen;
4119 switch(optname)
4121 case WS_IPX_PTYPE:
4122 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
4123 #ifdef SOL_IPX
4124 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (socklen_t *)optlen) == -1)
4126 ret = SOCKET_ERROR;
4128 #else
4130 struct ipx val;
4131 socklen_t len=sizeof(struct ipx);
4132 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
4133 ret = SOCKET_ERROR;
4134 else
4135 *optval = (int)val.ipx_pt;
4137 #endif
4138 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
4139 release_sock_fd( s, fd );
4140 return ret;
4142 case WS_IPX_ADDRESS:
4144 * On a Win2000 system with one network card there are usually
4145 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
4146 * Using this call you can then retrieve info about this all.
4147 * In case of Linux it is a bit different. Usually you have
4148 * only "one" device active and further it is not possible to
4149 * query things like the linkspeed.
4151 FIXME("IPX_ADDRESS\n");
4152 namelen = sizeof(struct WS_sockaddr_ipx);
4153 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
4154 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
4156 data = (IPX_ADDRESS_DATA*)optval;
4157 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
4158 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
4159 data->adapternum = 0;
4160 data->wan = FALSE; /* We are not on a wan for now .. */
4161 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
4162 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
4163 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
4164 * note 1MB = 1000kB in this case */
4165 return 0;
4167 case WS_IPX_MAX_ADAPTER_NUM:
4168 FIXME("IPX_MAX_ADAPTER_NUM\n");
4169 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
4170 return 0;
4172 default:
4173 FIXME("IPX optname:%x\n", optname);
4174 return SOCKET_ERROR;
4175 }/* end switch(optname) */
4176 } /* end case WS_NSPROTO_IPX */
4177 #endif
4179 #ifdef HAS_IRDA
4180 #define MAX_IRDA_DEVICES 10
4182 case WS_SOL_IRLMP:
4183 switch(optname)
4185 case WS_IRLMP_ENUMDEVICES:
4187 char buf[sizeof(struct irda_device_list) +
4188 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
4189 int res;
4190 socklen_t len = sizeof(buf);
4192 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4193 return SOCKET_ERROR;
4194 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
4195 release_sock_fd( s, fd );
4196 if (res < 0)
4198 SetLastError(wsaErrno());
4199 return SOCKET_ERROR;
4201 else
4203 struct irda_device_list *src = (struct irda_device_list *)buf;
4204 DEVICELIST *dst = (DEVICELIST *)optval;
4205 INT needed = sizeof(DEVICELIST);
4206 unsigned int i;
4208 if (src->len > 0)
4209 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
4210 if (*optlen < needed)
4212 SetLastError(WSAEFAULT);
4213 return SOCKET_ERROR;
4215 *optlen = needed;
4216 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
4217 dst->numDevice = src->len;
4218 for (i = 0; i < src->len; i++)
4220 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
4221 src->dev[i].saddr, src->dev[i].daddr,
4222 src->dev[i].info, src->dev[i].hints[0],
4223 src->dev[i].hints[1]);
4224 memcpy( dst->Device[i].irdaDeviceID,
4225 &src->dev[i].daddr,
4226 sizeof(dst->Device[i].irdaDeviceID) ) ;
4227 memcpy( dst->Device[i].irdaDeviceName,
4228 src->dev[i].info,
4229 sizeof(dst->Device[i].irdaDeviceName) ) ;
4230 memcpy( &dst->Device[i].irdaDeviceHints1,
4231 &src->dev[i].hints[0],
4232 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
4233 memcpy( &dst->Device[i].irdaDeviceHints2,
4234 &src->dev[i].hints[1],
4235 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
4236 dst->Device[i].irdaCharSet = src->dev[i].charset;
4238 return 0;
4241 default:
4242 FIXME("IrDA optname:0x%x\n", optname);
4243 return SOCKET_ERROR;
4245 break; /* case WS_SOL_IRLMP */
4246 #undef MAX_IRDA_DEVICES
4247 #endif
4249 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
4250 case WS_IPPROTO_TCP:
4251 switch(optname)
4253 case WS_TCP_NODELAY:
4254 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4255 return SOCKET_ERROR;
4256 convert_sockopt(&level, &optname);
4257 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
4259 SetLastError(wsaErrno());
4260 ret = SOCKET_ERROR;
4262 release_sock_fd( s, fd );
4263 return ret;
4265 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
4266 return SOCKET_ERROR;
4268 case WS_IPPROTO_IP:
4269 switch(optname)
4271 case WS_IP_ADD_MEMBERSHIP:
4272 case WS_IP_DROP_MEMBERSHIP:
4273 #ifdef IP_HDRINCL
4274 case WS_IP_HDRINCL:
4275 #endif
4276 case WS_IP_MULTICAST_IF:
4277 case WS_IP_MULTICAST_LOOP:
4278 case WS_IP_MULTICAST_TTL:
4279 case WS_IP_OPTIONS:
4280 #ifdef IP_PKTINFO
4281 case WS_IP_PKTINFO:
4282 #endif
4283 case WS_IP_TOS:
4284 case WS_IP_TTL:
4285 #ifdef IP_UNICAST_IF
4286 case WS_IP_UNICAST_IF:
4287 #endif
4288 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4289 return SOCKET_ERROR;
4290 convert_sockopt(&level, &optname);
4291 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
4293 SetLastError(wsaErrno());
4294 ret = SOCKET_ERROR;
4296 release_sock_fd( s, fd );
4297 return ret;
4298 case WS_IP_DONTFRAGMENT:
4299 return get_dont_fragment(s, IPPROTO_IP, (BOOL *)optval) ? 0 : SOCKET_ERROR;
4301 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
4302 return SOCKET_ERROR;
4304 case WS_IPPROTO_IPV6:
4305 switch(optname)
4307 #ifdef IPV6_ADD_MEMBERSHIP
4308 case WS_IPV6_ADD_MEMBERSHIP:
4309 #endif
4310 #ifdef IPV6_DROP_MEMBERSHIP
4311 case WS_IPV6_DROP_MEMBERSHIP:
4312 #endif
4313 case WS_IPV6_MULTICAST_IF:
4314 case WS_IPV6_MULTICAST_HOPS:
4315 case WS_IPV6_MULTICAST_LOOP:
4316 case WS_IPV6_UNICAST_HOPS:
4317 case WS_IPV6_V6ONLY:
4318 #ifdef IPV6_UNICAST_IF
4319 case WS_IPV6_UNICAST_IF:
4320 #endif
4321 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
4322 return SOCKET_ERROR;
4323 convert_sockopt(&level, &optname);
4324 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
4326 SetLastError(wsaErrno());
4327 ret = SOCKET_ERROR;
4329 release_sock_fd( s, fd );
4330 return ret;
4331 case WS_IPV6_DONTFRAG:
4332 return get_dont_fragment(s, IPPROTO_IPV6, (BOOL *)optval) ? 0 : SOCKET_ERROR;
4334 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
4335 return SOCKET_ERROR;
4337 default:
4338 WARN("Unknown level: 0x%08x\n", level);
4339 SetLastError(WSAEINVAL);
4340 return SOCKET_ERROR;
4341 } /* end switch(level) */
4344 /***********************************************************************
4345 * htonl (WS2_32.8)
4347 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
4349 return htonl(hostlong);
4353 /***********************************************************************
4354 * htons (WS2_32.9)
4356 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
4358 return htons(hostshort);
4361 /***********************************************************************
4362 * WSAHtonl (WS2_32.46)
4363 * From MSDN description of error codes, this function should also
4364 * check if WinSock has been initialized and the socket is a valid
4365 * socket. But why? This function only translates a host byte order
4366 * u_long into a network byte order u_long...
4368 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
4370 if (lpnetlong)
4372 *lpnetlong = htonl(hostlong);
4373 return 0;
4375 SetLastError(WSAEFAULT);
4376 return SOCKET_ERROR;
4379 /***********************************************************************
4380 * WSAHtons (WS2_32.47)
4381 * From MSDN description of error codes, this function should also
4382 * check if WinSock has been initialized and the socket is a valid
4383 * socket. But why? This function only translates a host byte order
4384 * u_short into a network byte order u_short...
4386 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
4389 if (lpnetshort)
4391 *lpnetshort = htons(hostshort);
4392 return 0;
4394 SetLastError(WSAEFAULT);
4395 return SOCKET_ERROR;
4399 /***********************************************************************
4400 * inet_addr (WS2_32.11)
4402 WS_u_long WINAPI WS_inet_addr(const char *cp)
4404 if (!cp) return INADDR_NONE;
4405 return inet_addr(cp);
4409 /***********************************************************************
4410 * ntohl (WS2_32.14)
4412 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
4414 return ntohl(netlong);
4418 /***********************************************************************
4419 * ntohs (WS2_32.15)
4421 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
4423 return ntohs(netshort);
4427 /***********************************************************************
4428 * inet_ntoa (WS2_32.12)
4430 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
4432 unsigned int long_ip = ntohl(in.WS_s_addr);
4433 struct per_thread_data *data = get_per_thread_data();
4435 sprintf( data->ntoa_buffer, "%u.%u.%u.%u",
4436 (long_ip >> 24) & 0xff,
4437 (long_ip >> 16) & 0xff,
4438 (long_ip >> 8) & 0xff,
4439 long_ip & 0xff);
4441 return data->ntoa_buffer;
4444 static const char *debugstr_wsaioctl(DWORD code)
4446 const char *name = NULL, *buf_type, *family;
4448 #define IOCTL_NAME(x) case x: name = #x; break
4449 switch (code)
4451 IOCTL_NAME(WS_FIONBIO);
4452 IOCTL_NAME(WS_FIONREAD);
4453 IOCTL_NAME(WS_SIOCATMARK);
4454 /* IOCTL_NAME(WS_SIO_ACQUIRE_PORT_RESERVATION); */
4455 IOCTL_NAME(WS_SIO_ADDRESS_LIST_CHANGE);
4456 IOCTL_NAME(WS_SIO_ADDRESS_LIST_QUERY);
4457 IOCTL_NAME(WS_SIO_ASSOCIATE_HANDLE);
4458 /* IOCTL_NAME(WS_SIO_ASSOCIATE_PORT_RESERVATION);
4459 IOCTL_NAME(WS_SIO_BASE_HANDLE);
4460 IOCTL_NAME(WS_SIO_BSP_HANDLE);
4461 IOCTL_NAME(WS_SIO_BSP_HANDLE_SELECT);
4462 IOCTL_NAME(WS_SIO_BSP_HANDLE_POLL);
4463 IOCTL_NAME(WS_SIO_CHK_QOS); */
4464 IOCTL_NAME(WS_SIO_ENABLE_CIRCULAR_QUEUEING);
4465 IOCTL_NAME(WS_SIO_FIND_ROUTE);
4466 IOCTL_NAME(WS_SIO_FLUSH);
4467 IOCTL_NAME(WS_SIO_GET_BROADCAST_ADDRESS);
4468 IOCTL_NAME(WS_SIO_GET_EXTENSION_FUNCTION_POINTER);
4469 IOCTL_NAME(WS_SIO_GET_GROUP_QOS);
4470 IOCTL_NAME(WS_SIO_GET_INTERFACE_LIST);
4471 /* IOCTL_NAME(WS_SIO_GET_INTERFACE_LIST_EX); */
4472 IOCTL_NAME(WS_SIO_GET_QOS);
4473 /* IOCTL_NAME(WS_SIO_IDEAL_SEND_BACKLOG_CHANGE);
4474 IOCTL_NAME(WS_SIO_IDEAL_SEND_BACKLOG_QUERY); */
4475 IOCTL_NAME(WS_SIO_KEEPALIVE_VALS);
4476 IOCTL_NAME(WS_SIO_MULTIPOINT_LOOPBACK);
4477 IOCTL_NAME(WS_SIO_MULTICAST_SCOPE);
4478 /* IOCTL_NAME(WS_SIO_QUERY_RSS_SCALABILITY_INFO);
4479 IOCTL_NAME(WS_SIO_QUERY_WFP_ALE_ENDPOINT_HANDLE); */
4480 IOCTL_NAME(WS_SIO_RCVALL);
4481 IOCTL_NAME(WS_SIO_RCVALL_IGMPMCAST);
4482 IOCTL_NAME(WS_SIO_RCVALL_MCAST);
4483 /* IOCTL_NAME(WS_SIO_RELEASE_PORT_RESERVATION); */
4484 IOCTL_NAME(WS_SIO_ROUTING_INTERFACE_CHANGE);
4485 IOCTL_NAME(WS_SIO_ROUTING_INTERFACE_QUERY);
4486 IOCTL_NAME(WS_SIO_SET_COMPATIBILITY_MODE);
4487 IOCTL_NAME(WS_SIO_SET_GROUP_QOS);
4488 IOCTL_NAME(WS_SIO_SET_QOS);
4489 IOCTL_NAME(WS_SIO_TRANSLATE_HANDLE);
4490 IOCTL_NAME(WS_SIO_UDP_CONNRESET);
4492 #undef IOCTL_NAME
4494 if (name)
4495 return name + 3;
4497 /* If this is not a known code split its bits */
4498 switch(code & 0x18000000)
4500 case WS_IOC_WS2:
4501 family = "IOC_WS2";
4502 break;
4503 case WS_IOC_PROTOCOL:
4504 family = "IOC_PROTOCOL";
4505 break;
4506 case WS_IOC_VENDOR:
4507 family = "IOC_VENDOR";
4508 break;
4509 default: /* WS_IOC_UNIX */
4511 BYTE size = (code >> 16) & WS_IOCPARM_MASK;
4512 char x = (code & 0xff00) >> 8;
4513 BYTE y = code & 0xff;
4514 char args[14];
4516 switch (code & (WS_IOC_VOID|WS_IOC_INOUT))
4518 case WS_IOC_VOID:
4519 buf_type = "_IO";
4520 sprintf(args, "%d, %d", x, y);
4521 break;
4522 case WS_IOC_IN:
4523 buf_type = "_IOW";
4524 sprintf(args, "'%c', %d, %d", x, y, size);
4525 break;
4526 case WS_IOC_OUT:
4527 buf_type = "_IOR";
4528 sprintf(args, "'%c', %d, %d", x, y, size);
4529 break;
4530 default:
4531 buf_type = "?";
4532 sprintf(args, "'%c', %d, %d", x, y, size);
4533 break;
4535 return wine_dbg_sprintf("%s(%s)", buf_type, args);
4539 /* We are different from WS_IOC_UNIX. */
4540 switch (code & (WS_IOC_VOID|WS_IOC_INOUT))
4542 case WS_IOC_VOID:
4543 buf_type = "_WSAIO";
4544 break;
4545 case WS_IOC_INOUT:
4546 buf_type = "_WSAIORW";
4547 break;
4548 case WS_IOC_IN:
4549 buf_type = "_WSAIOW";
4550 break;
4551 case WS_IOC_OUT:
4552 buf_type = "_WSAIOR";
4553 break;
4554 default:
4555 buf_type = "?";
4556 break;
4559 return wine_dbg_sprintf("%s(%s, %d)", buf_type, family,
4560 (USHORT)(code & 0xffff));
4563 /* do an ioctl call through the server */
4564 static DWORD server_ioctl_sock( SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size,
4565 LPVOID out_buff, DWORD out_size, LPDWORD ret_size,
4566 LPWSAOVERLAPPED overlapped,
4567 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
4569 HANDLE event = overlapped ? overlapped->hEvent : 0;
4570 HANDLE handle = SOCKET2HANDLE( s );
4571 struct ws2_async *wsa = NULL;
4572 IO_STATUS_BLOCK *io = (PIO_STATUS_BLOCK)overlapped, iosb;
4573 void *cvalue = NULL;
4574 NTSTATUS status;
4576 if (completion)
4578 if (!(wsa = (struct ws2_async *)alloc_async_io( sizeof(*wsa), NULL )))
4579 return WSA_NOT_ENOUGH_MEMORY;
4580 wsa->hSocket = handle;
4581 wsa->user_overlapped = overlapped;
4582 wsa->completion_func = completion;
4583 if (!io) io = &wsa->local_iosb;
4584 cvalue = wsa;
4586 else if (!io)
4587 io = &iosb;
4588 else if (!((ULONG_PTR)overlapped->hEvent & 1))
4589 cvalue = overlapped;
4591 status = NtDeviceIoControlFile( handle, event, wsa ? ws2_async_apc : NULL, cvalue, io, code,
4592 in_buff, in_size, out_buff, out_size );
4593 if (status == STATUS_NOT_SUPPORTED)
4595 FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
4596 code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
4598 else if (status == STATUS_SUCCESS)
4599 *ret_size = io->Information; /* "Information" is the size written to the output buffer */
4601 if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, wsa );
4603 return NtStatusToWSAError( status );
4606 /**********************************************************************
4607 * WSAIoctl (WS2_32.50)
4610 INT WINAPI WSAIoctl(SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size, LPVOID out_buff,
4611 DWORD out_size, LPDWORD ret_size, LPWSAOVERLAPPED overlapped,
4612 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
4614 int fd;
4615 DWORD status = 0, total = 0;
4617 TRACE("%04lx, %s, %p, %d, %p, %d, %p, %p, %p\n",
4618 s, debugstr_wsaioctl(code), in_buff, in_size, out_buff, out_size, ret_size, overlapped, completion);
4620 switch (code)
4622 case WS_FIONBIO:
4623 if (in_size != sizeof(WS_u_long) || IS_INTRESOURCE(in_buff))
4625 SetLastError(WSAEFAULT);
4626 return SOCKET_ERROR;
4628 TRACE("-> FIONBIO (%x)\n", *(WS_u_long*)in_buff);
4629 if (_get_sock_mask(s))
4631 /* AsyncSelect()'ed sockets are always nonblocking */
4632 if (!*(WS_u_long *)in_buff) status = WSAEINVAL;
4633 break;
4635 if (*(WS_u_long *)in_buff)
4636 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
4637 else
4638 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
4639 break;
4641 case WS_FIONREAD:
4643 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
4645 SetLastError(WSAEFAULT);
4646 return SOCKET_ERROR;
4648 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
4649 if (ioctl(fd, FIONREAD, out_buff ) == -1)
4650 status = wsaErrno();
4651 release_sock_fd( s, fd );
4652 break;
4655 case WS_SIOCATMARK:
4657 unsigned int oob = 0, atmark = 0;
4658 socklen_t oobsize = sizeof(int);
4659 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
4661 SetLastError(WSAEFAULT);
4662 return SOCKET_ERROR;
4664 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
4665 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
4666 if ((getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &oob, &oobsize ) == -1)
4667 || (!oob && ioctl(fd, SIOCATMARK, &atmark ) == -1))
4668 status = wsaErrno();
4669 else
4671 /* The SIOCATMARK value read from ioctl() is reversed
4672 * because BSD returns TRUE if it's in the OOB mark
4673 * while Windows returns TRUE if there are NO OOB bytes.
4675 (*(WS_u_long *) out_buff) = oob || !atmark;
4678 release_sock_fd( s, fd );
4679 break;
4682 case WS_FIOASYNC:
4683 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
4684 SetLastError(WSAEINVAL);
4685 return SOCKET_ERROR;
4687 case WS_SIO_GET_INTERFACE_LIST:
4689 INTERFACE_INFO* intArray = out_buff;
4690 DWORD size, numInt = 0, apiReturn;
4692 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
4694 if (!out_buff || !ret_size)
4696 SetLastError(WSAEFAULT);
4697 return SOCKET_ERROR;
4700 fd = get_sock_fd( s, 0, NULL );
4701 if (fd == -1) return SOCKET_ERROR;
4703 apiReturn = GetAdaptersInfo(NULL, &size);
4704 if (apiReturn == ERROR_BUFFER_OVERFLOW)
4706 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
4708 if (table)
4710 if (GetAdaptersInfo(table, &size) == NO_ERROR)
4712 PIP_ADAPTER_INFO ptr;
4714 for (ptr = table, numInt = 0; ptr; ptr = ptr->Next)
4716 unsigned int addr, mask, bcast;
4717 struct ifreq ifInfo;
4719 /* Skip interfaces without an IPv4 address. */
4720 if (ptr->IpAddressList.IpAddress.String[0] == '\0')
4721 continue;
4723 if ((numInt + 1)*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > out_size)
4725 WARN("Buffer too small = %u, out_size = %u\n", numInt + 1, out_size);
4726 status = WSAEFAULT;
4727 break;
4730 /* Socket Status Flags */
4731 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
4732 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
4734 ERR("Error obtaining status flags for socket!\n");
4735 status = WSAEINVAL;
4736 break;
4738 else
4740 /* set flags; the values of IFF_* are not the same
4741 under Linux and Windows, therefore must generate
4742 new flags */
4743 intArray->iiFlags = 0;
4744 if (ifInfo.ifr_flags & IFF_BROADCAST)
4745 intArray->iiFlags |= WS_IFF_BROADCAST;
4746 #ifdef IFF_POINTOPOINT
4747 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
4748 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
4749 #endif
4750 if (ifInfo.ifr_flags & IFF_LOOPBACK)
4751 intArray->iiFlags |= WS_IFF_LOOPBACK;
4752 if (ifInfo.ifr_flags & IFF_UP)
4753 intArray->iiFlags |= WS_IFF_UP;
4754 if (ifInfo.ifr_flags & IFF_MULTICAST)
4755 intArray->iiFlags |= WS_IFF_MULTICAST;
4758 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
4759 mask = inet_addr(ptr->IpAddressList.IpMask.String);
4760 bcast = addr | ~mask;
4761 intArray->iiAddress.AddressIn.sin_family = WS_AF_INET;
4762 intArray->iiAddress.AddressIn.sin_port = 0;
4763 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr = addr;
4765 intArray->iiNetmask.AddressIn.sin_family = WS_AF_INET;
4766 intArray->iiNetmask.AddressIn.sin_port = 0;
4767 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr = mask;
4769 intArray->iiBroadcastAddress.AddressIn.sin_family = WS_AF_INET;
4770 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
4771 intArray->iiBroadcastAddress.AddressIn.sin_addr.WS_s_addr = bcast;
4772 intArray++;
4773 numInt++;
4776 else
4778 ERR("Unable to get interface table!\n");
4779 status = WSAEINVAL;
4781 HeapFree(GetProcessHeap(),0,table);
4783 else status = WSAEINVAL;
4785 else if (apiReturn != ERROR_NO_DATA)
4787 ERR("Unable to get interface table!\n");
4788 status = WSAEINVAL;
4790 /* Calculate the size of the array being returned */
4791 total = sizeof(INTERFACE_INFO) * numInt;
4792 release_sock_fd( s, fd );
4793 break;
4796 case WS_SIO_ADDRESS_LIST_QUERY:
4798 DWORD size;
4800 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
4802 if (!ret_size)
4804 SetLastError(WSAEFAULT);
4805 return SOCKET_ERROR;
4808 if (out_size && out_size < FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[0]))
4810 *ret_size = 0;
4811 SetLastError(WSAEINVAL);
4812 return SOCKET_ERROR;
4815 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
4817 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
4818 SOCKET_ADDRESS_LIST *sa_list;
4819 SOCKADDR_IN *sockaddr;
4820 SOCKET_ADDRESS *sa;
4821 unsigned int i;
4822 DWORD num;
4824 if (!table || GetAdaptersInfo(table, &size))
4826 HeapFree(GetProcessHeap(), 0, table);
4827 status = WSAEINVAL;
4828 break;
4831 for (p = table, num = 0; p; p = p->Next)
4832 if (p->IpAddressList.IpAddress.String[0]) num++;
4834 total = FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[num]) + num * sizeof(*sockaddr);
4835 if (total > out_size || !out_buff)
4837 *ret_size = total;
4838 HeapFree(GetProcessHeap(), 0, table);
4839 status = WSAEFAULT;
4840 break;
4843 sa_list = out_buff;
4844 sa = sa_list->Address;
4845 sockaddr = (SOCKADDR_IN *)&sa[num];
4846 sa_list->iAddressCount = num;
4848 for (p = table, i = 0; p; p = p->Next)
4850 if (!p->IpAddressList.IpAddress.String[0]) continue;
4852 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
4853 sa[i].iSockaddrLength = sizeof(SOCKADDR);
4855 sockaddr[i].sin_family = WS_AF_INET;
4856 sockaddr[i].sin_port = 0;
4857 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
4858 i++;
4861 HeapFree(GetProcessHeap(), 0, table);
4863 else
4865 WARN("unable to get IP address list\n");
4866 status = WSAEINVAL;
4868 break;
4871 case WS_SIO_FLUSH:
4872 FIXME("SIO_FLUSH: stub.\n");
4873 break;
4875 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
4877 #define EXTENSION_FUNCTION(x, y) { x, y, #y },
4878 static const struct
4880 GUID guid;
4881 void *func_ptr;
4882 const char *name;
4883 } guid_funcs[] = {
4884 EXTENSION_FUNCTION(WSAID_CONNECTEX, WS2_ConnectEx)
4885 EXTENSION_FUNCTION(WSAID_DISCONNECTEX, WS2_DisconnectEx)
4886 EXTENSION_FUNCTION(WSAID_ACCEPTEX, WS2_AcceptEx)
4887 EXTENSION_FUNCTION(WSAID_GETACCEPTEXSOCKADDRS, WS2_GetAcceptExSockaddrs)
4888 EXTENSION_FUNCTION(WSAID_TRANSMITFILE, WS2_TransmitFile)
4889 /* EXTENSION_FUNCTION(WSAID_TRANSMITPACKETS, WS2_TransmitPackets) */
4890 EXTENSION_FUNCTION(WSAID_WSARECVMSG, WS2_WSARecvMsg)
4891 EXTENSION_FUNCTION(WSAID_WSASENDMSG, WSASendMsg)
4893 #undef EXTENSION_FUNCTION
4894 BOOL found = FALSE;
4895 unsigned int i;
4897 for (i = 0; i < sizeof(guid_funcs) / sizeof(guid_funcs[0]); i++)
4899 if (IsEqualGUID(&guid_funcs[i].guid, in_buff))
4901 found = TRUE;
4902 break;
4906 if (found)
4908 TRACE("-> got %s\n", guid_funcs[i].name);
4909 *(void **)out_buff = guid_funcs[i].func_ptr;
4910 total = sizeof(void *);
4911 break;
4914 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff));
4915 status = WSAEOPNOTSUPP;
4916 break;
4918 case WS_SIO_KEEPALIVE_VALS:
4920 struct tcp_keepalive *k;
4921 int keepalive, keepidle, keepintvl;
4923 if (!in_buff || in_size < sizeof(struct tcp_keepalive))
4925 SetLastError(WSAEFAULT);
4926 return SOCKET_ERROR;
4929 k = in_buff;
4930 keepalive = k->onoff ? 1 : 0;
4931 keepidle = max( 1, (k->keepalivetime + 500) / 1000 );
4932 keepintvl = max( 1, (k->keepaliveinterval + 500) / 1000 );
4934 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
4936 fd = get_sock_fd(s, 0, NULL);
4937 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
4938 status = WSAEINVAL;
4939 #if defined(TCP_KEEPIDLE) || defined(TCP_KEEPINTVL)
4940 /* these values need to be set only if SO_KEEPALIVE is enabled */
4941 else if(keepalive)
4943 #ifndef TCP_KEEPIDLE
4944 FIXME("ignoring keepalive timeout\n");
4945 #else
4946 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
4947 status = WSAEINVAL;
4948 else
4949 #endif
4950 #ifdef TCP_KEEPINTVL
4951 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
4952 status = WSAEINVAL;
4953 #else
4954 FIXME("ignoring keepalive interval\n");
4955 #endif
4957 #else
4958 else
4959 FIXME("ignoring keepalive interval and timeout\n");
4960 #endif
4961 release_sock_fd(s, fd);
4962 break;
4964 case WS_SIO_ROUTING_INTERFACE_QUERY:
4966 struct WS_sockaddr *daddr = (struct WS_sockaddr *)in_buff;
4967 struct WS_sockaddr_in *daddr_in = (struct WS_sockaddr_in *)daddr;
4968 struct WS_sockaddr_in *saddr_in = out_buff;
4969 MIB_IPFORWARDROW row;
4970 PMIB_IPADDRTABLE ipAddrTable = NULL;
4971 DWORD size, i, found_index;
4973 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
4975 if (!in_buff || in_size < sizeof(struct WS_sockaddr) ||
4976 !out_buff || out_size < sizeof(struct WS_sockaddr_in) || !ret_size)
4978 SetLastError(WSAEFAULT);
4979 return SOCKET_ERROR;
4981 if (daddr->sa_family != WS_AF_INET)
4983 FIXME("unsupported address family %d\n", daddr->sa_family);
4984 status = WSAEAFNOSUPPORT;
4985 break;
4987 if (GetBestRoute(daddr_in->sin_addr.S_un.S_addr, 0, &row) != NOERROR ||
4988 GetIpAddrTable(NULL, &size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
4990 status = WSAEFAULT;
4991 break;
4993 ipAddrTable = HeapAlloc(GetProcessHeap(), 0, size);
4994 if (GetIpAddrTable(ipAddrTable, &size, FALSE))
4996 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4997 status = WSAEFAULT;
4998 break;
5000 for (i = 0, found_index = ipAddrTable->dwNumEntries;
5001 i < ipAddrTable->dwNumEntries; i++)
5003 if (ipAddrTable->table[i].dwIndex == row.dwForwardIfIndex)
5004 found_index = i;
5006 if (found_index == ipAddrTable->dwNumEntries)
5008 ERR("no matching IP address for interface %d\n",
5009 row.dwForwardIfIndex);
5010 HeapFree(GetProcessHeap(), 0, ipAddrTable);
5011 status = WSAEFAULT;
5012 break;
5014 saddr_in->sin_family = WS_AF_INET;
5015 saddr_in->sin_addr.S_un.S_addr = ipAddrTable->table[found_index].dwAddr;
5016 saddr_in->sin_port = 0;
5017 total = sizeof(struct WS_sockaddr_in);
5018 HeapFree(GetProcessHeap(), 0, ipAddrTable);
5019 break;
5021 case WS_SIO_SET_COMPATIBILITY_MODE:
5022 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
5023 status = WSAEOPNOTSUPP;
5024 break;
5025 case WS_SIO_UDP_CONNRESET:
5026 FIXME("WS_SIO_UDP_CONNRESET stub\n");
5027 break;
5028 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
5029 SetLastError(WSAEOPNOTSUPP);
5030 return SOCKET_ERROR;
5031 default:
5032 status = WSAEOPNOTSUPP;
5033 break;
5036 if (status == WSAEOPNOTSUPP)
5038 status = server_ioctl_sock(s, code, in_buff, in_size, out_buff, out_size, &total,
5039 overlapped, completion);
5040 if (status != WSAEOPNOTSUPP)
5042 if (status == 0 || status == WSA_IO_PENDING)
5043 TRACE("-> %s request\n", debugstr_wsaioctl(code));
5044 else
5045 ERR("-> %s request failed with status 0x%x\n", debugstr_wsaioctl(code), status);
5047 /* overlapped and completion operations will be handled by the server */
5048 completion = NULL;
5049 overlapped = NULL;
5051 else
5052 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code));
5055 if (completion)
5057 FIXME( "completion routine %p not supported\n", completion );
5059 else if (overlapped)
5061 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
5062 overlapped->Internal = status;
5063 overlapped->InternalHigh = total;
5064 if (overlapped->hEvent) NtSetEvent( overlapped->hEvent, NULL );
5065 if (cvalue) WS_AddCompletion( HANDLE2SOCKET(s), cvalue, status, total );
5068 if (!status)
5070 if (ret_size) *ret_size = total;
5071 return 0;
5073 SetLastError( status );
5074 return SOCKET_ERROR;
5078 /***********************************************************************
5079 * ioctlsocket (WS2_32.10)
5081 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
5083 DWORD ret_size;
5084 return WSAIoctl( s, cmd, argp, sizeof(WS_u_long), argp, sizeof(WS_u_long), &ret_size, NULL, NULL );
5087 /***********************************************************************
5088 * listen (WS2_32.13)
5090 int WINAPI WS_listen(SOCKET s, int backlog)
5092 int fd = get_sock_fd( s, FILE_READ_DATA, NULL ), ret = SOCKET_ERROR;
5094 TRACE("socket %04lx, backlog %d\n", s, backlog);
5095 if (fd != -1)
5097 int bound = is_fd_bound(fd, NULL, NULL);
5099 if (bound <= 0)
5101 SetLastError(bound == -1 ? wsaErrno() : WSAEINVAL);
5103 else if (listen(fd, backlog) == 0)
5105 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
5106 FD_WINE_LISTENING,
5107 FD_CONNECT|FD_WINE_CONNECTED);
5108 ret = 0;
5110 else
5111 SetLastError(wsaErrno());
5112 release_sock_fd( s, fd );
5114 else
5115 SetLastError(WSAENOTSOCK);
5116 return ret;
5119 /***********************************************************************
5120 * recv (WS2_32.16)
5122 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
5124 DWORD n, dwFlags = flags;
5125 WSABUF wsabuf;
5127 wsabuf.len = len;
5128 wsabuf.buf = buf;
5130 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
5131 return SOCKET_ERROR;
5132 else
5133 return n;
5136 /***********************************************************************
5137 * recvfrom (WS2_32.17)
5139 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
5140 struct WS_sockaddr *from, int *fromlen)
5142 DWORD n, dwFlags = flags;
5143 WSABUF wsabuf;
5145 wsabuf.len = len;
5146 wsabuf.buf = buf;
5148 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL, NULL) == SOCKET_ERROR )
5149 return SOCKET_ERROR;
5150 else
5151 return n;
5154 /* allocate a poll array for the corresponding fd sets */
5155 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
5156 const WS_fd_set *exceptfds, int *count_ptr )
5158 unsigned int i, j = 0, count = 0;
5159 struct pollfd *fds;
5160 struct per_thread_data *ptb = get_per_thread_data();
5162 if (readfds) count += readfds->fd_count;
5163 if (writefds) count += writefds->fd_count;
5164 if (exceptfds) count += exceptfds->fd_count;
5165 *count_ptr = count;
5166 if (!count)
5168 SetLastError(WSAEINVAL);
5169 return NULL;
5172 /* check if the cache can hold all descriptors, if not do the resizing */
5173 if (ptb->fd_count < count)
5175 if (!(fds = HeapAlloc(GetProcessHeap(), 0, count * sizeof(fds[0]))))
5177 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
5178 return NULL;
5180 HeapFree(GetProcessHeap(), 0, ptb->fd_cache);
5181 ptb->fd_cache = fds;
5182 ptb->fd_count = count;
5184 else
5185 fds = ptb->fd_cache;
5187 if (readfds)
5188 for (i = 0; i < readfds->fd_count; i++, j++)
5190 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
5191 if (fds[j].fd == -1) goto failed;
5192 fds[j].revents = 0;
5193 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1)
5195 fds[j].events = POLLIN;
5197 else
5199 release_sock_fd( readfds->fd_array[i], fds[j].fd );
5200 fds[j].fd = -1;
5201 fds[j].events = 0;
5204 if (writefds)
5205 for (i = 0; i < writefds->fd_count; i++, j++)
5207 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
5208 if (fds[j].fd == -1) goto failed;
5209 fds[j].revents = 0;
5210 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1 ||
5211 _get_fd_type(fds[j].fd) == SOCK_DGRAM)
5213 fds[j].events = POLLOUT;
5215 else
5217 release_sock_fd( writefds->fd_array[i], fds[j].fd );
5218 fds[j].fd = -1;
5219 fds[j].events = 0;
5222 if (exceptfds)
5223 for (i = 0; i < exceptfds->fd_count; i++, j++)
5225 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
5226 if (fds[j].fd == -1) goto failed;
5227 fds[j].revents = 0;
5228 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1)
5230 int oob_inlined = 0;
5231 socklen_t olen = sizeof(oob_inlined);
5233 fds[j].events = POLLHUP;
5235 /* Check if we need to test for urgent data or not */
5236 getsockopt(fds[j].fd, SOL_SOCKET, SO_OOBINLINE, (char*) &oob_inlined, &olen);
5237 if (!oob_inlined)
5238 fds[j].events |= POLLPRI;
5240 else
5242 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
5243 fds[j].fd = -1;
5244 fds[j].events = 0;
5247 return fds;
5249 failed:
5250 count = j;
5251 j = 0;
5252 if (readfds)
5253 for (i = 0; i < readfds->fd_count && j < count; i++, j++)
5254 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
5255 if (writefds)
5256 for (i = 0; i < writefds->fd_count && j < count; i++, j++)
5257 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
5258 if (exceptfds)
5259 for (i = 0; i < exceptfds->fd_count && j < count; i++, j++)
5260 if (fds[j].fd != -1) release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
5261 return NULL;
5264 /* release the file descriptor obtained in fd_sets_to_poll */
5265 /* must be called with the original fd_set arrays, before calling get_poll_results */
5266 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
5267 const WS_fd_set *exceptfds, struct pollfd *fds )
5269 unsigned int i, j = 0;
5271 if (readfds)
5273 for (i = 0; i < readfds->fd_count; i++, j++)
5274 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
5276 if (writefds)
5278 for (i = 0; i < writefds->fd_count; i++, j++)
5279 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
5281 if (exceptfds)
5283 for (i = 0; i < exceptfds->fd_count; i++, j++)
5285 if (fds[j].fd == -1) continue;
5286 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
5287 if (fds[j].revents & POLLHUP)
5289 int fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
5290 if (fd != -1)
5291 release_sock_fd( exceptfds->fd_array[i], fd );
5292 else
5293 fds[j].revents = 0;
5299 static int do_poll(struct pollfd *pollfds, int count, int timeout)
5301 struct timeval tv1, tv2;
5302 int ret, torig = timeout;
5304 if (timeout > 0) gettimeofday( &tv1, 0 );
5306 while ((ret = poll( pollfds, count, timeout )) < 0)
5308 if (errno != EINTR) break;
5309 if (timeout < 0) continue;
5310 if (timeout == 0) return 0;
5312 gettimeofday( &tv2, 0 );
5314 tv2.tv_sec -= tv1.tv_sec;
5315 tv2.tv_usec -= tv1.tv_usec;
5316 if (tv2.tv_usec < 0)
5318 tv2.tv_usec += 1000000;
5319 tv2.tv_sec -= 1;
5322 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
5323 if (timeout <= 0) return 0;
5325 return ret;
5328 /* map the poll results back into the Windows fd sets */
5329 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
5330 const struct pollfd *fds )
5332 const struct pollfd *poll_writefds = fds + (readfds ? readfds->fd_count : 0);
5333 const struct pollfd *poll_exceptfds = poll_writefds + (writefds ? writefds->fd_count : 0);
5334 unsigned int i, k, total = 0;
5336 if (readfds)
5338 for (i = k = 0; i < readfds->fd_count; i++)
5340 if (fds[i].revents ||
5341 (readfds == writefds && (poll_writefds[i].revents & POLLOUT) && !(poll_writefds[i].revents & POLLHUP)) ||
5342 (readfds == exceptfds && poll_exceptfds[i].revents))
5343 readfds->fd_array[k++] = readfds->fd_array[i];
5345 readfds->fd_count = k;
5346 total += k;
5348 if (writefds && writefds != readfds)
5350 for (i = k = 0; i < writefds->fd_count; i++)
5352 if (((poll_writefds[i].revents & POLLOUT) && !(poll_writefds[i].revents & POLLHUP)) ||
5353 (writefds == exceptfds && poll_exceptfds[i].revents))
5354 writefds->fd_array[k++] = writefds->fd_array[i];
5356 writefds->fd_count = k;
5357 total += k;
5359 if (exceptfds && exceptfds != readfds && exceptfds != writefds)
5361 for (i = k = 0; i < exceptfds->fd_count; i++)
5362 if (poll_exceptfds[i].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
5363 exceptfds->fd_count = k;
5364 total += k;
5366 return total;
5369 /***********************************************************************
5370 * select (WS2_32.18)
5372 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
5373 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
5374 const struct WS_timeval* ws_timeout)
5376 struct pollfd *pollfds;
5377 int count, ret, timeout = -1;
5379 TRACE("read %p, write %p, excp %p timeout %p\n",
5380 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
5382 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )))
5383 return SOCKET_ERROR;
5385 if (ws_timeout)
5386 timeout = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
5388 ret = do_poll(pollfds, count, timeout);
5389 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
5391 if (ret == -1) SetLastError(wsaErrno());
5392 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
5393 return ret;
5396 /***********************************************************************
5397 * WSAPoll
5399 int WINAPI WSAPoll(WSAPOLLFD *wfds, ULONG count, int timeout)
5401 int i, ret;
5402 struct pollfd *ufds;
5404 if (!count)
5406 SetLastError(WSAEINVAL);
5407 return SOCKET_ERROR;
5409 if (!wfds)
5411 SetLastError(WSAEFAULT);
5412 return SOCKET_ERROR;
5415 if (!(ufds = HeapAlloc(GetProcessHeap(), 0, count * sizeof(ufds[0]))))
5417 SetLastError(WSAENOBUFS);
5418 return SOCKET_ERROR;
5421 for (i = 0; i < count; i++)
5423 ufds[i].fd = get_sock_fd(wfds[i].fd, 0, NULL);
5424 ufds[i].events = convert_poll_w2u(wfds[i].events);
5425 ufds[i].revents = 0;
5428 ret = do_poll(ufds, count, timeout);
5430 for (i = 0; i < count; i++)
5432 if (ufds[i].fd != -1)
5434 release_sock_fd(wfds[i].fd, ufds[i].fd);
5435 if (ufds[i].revents & POLLHUP)
5437 /* Check if the socket still exists */
5438 int fd = get_sock_fd(wfds[i].fd, 0, NULL);
5439 if (fd != -1)
5441 wfds[i].revents = WS_POLLHUP;
5442 release_sock_fd(wfds[i].fd, fd);
5444 else
5445 wfds[i].revents = WS_POLLNVAL;
5447 else
5448 wfds[i].revents = convert_poll_u2w(ufds[i].revents);
5450 else
5451 wfds[i].revents = WS_POLLNVAL;
5454 HeapFree(GetProcessHeap(), 0, ufds);
5455 return ret;
5458 /* helper to send completion messages for client-only i/o operation case */
5459 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
5460 ULONG Information )
5462 SERVER_START_REQ( add_fd_completion )
5464 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
5465 req->cvalue = CompletionValue;
5466 req->status = CompletionStatus;
5467 req->information = Information;
5468 wine_server_call( req );
5470 SERVER_END_REQ;
5474 /***********************************************************************
5475 * send (WS2_32.19)
5477 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
5479 DWORD n;
5480 WSABUF wsabuf;
5482 wsabuf.len = len;
5483 wsabuf.buf = (char*) buf;
5485 if ( WS2_sendto( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
5486 return SOCKET_ERROR;
5487 else
5488 return n;
5491 /***********************************************************************
5492 * WSASend (WS2_32.72)
5494 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5495 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
5496 LPWSAOVERLAPPED lpOverlapped,
5497 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5499 return WS2_sendto( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
5500 NULL, 0, lpOverlapped, lpCompletionRoutine );
5503 /***********************************************************************
5504 * WSASendDisconnect (WS2_32.73)
5506 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
5508 return WS_shutdown( s, SD_SEND );
5512 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5513 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
5514 const struct WS_sockaddr *to, int tolen,
5515 LPWSAOVERLAPPED lpOverlapped,
5516 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5518 unsigned int i, options;
5519 int n, fd, err, overlapped, flags;
5520 struct ws2_async *wsa = NULL, localwsa;
5521 int totalLength = 0;
5522 DWORD bytes_sent;
5523 BOOL is_blocking;
5525 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
5526 s, lpBuffers, dwBufferCount, dwFlags,
5527 to, tolen, lpOverlapped, lpCompletionRoutine);
5529 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
5530 TRACE( "fd=%d, options=%x\n", fd, options );
5532 if ( fd == -1 ) return SOCKET_ERROR;
5534 if (!lpOverlapped && !lpNumberOfBytesSent)
5536 err = WSAEFAULT;
5537 goto error;
5540 overlapped = (lpOverlapped || lpCompletionRoutine) &&
5541 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
5542 if (overlapped || dwBufferCount > 1)
5544 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[dwBufferCount]),
5545 WS2_async_send )))
5547 err = WSAEFAULT;
5548 goto error;
5551 else
5552 wsa = &localwsa;
5554 wsa->hSocket = SOCKET2HANDLE(s);
5555 wsa->addr = (struct WS_sockaddr *)to;
5556 wsa->addrlen.val = tolen;
5557 wsa->flags = dwFlags;
5558 wsa->lpFlags = &wsa->flags;
5559 wsa->control = NULL;
5560 wsa->n_iovecs = dwBufferCount;
5561 wsa->first_iovec = 0;
5562 for ( i = 0; i < dwBufferCount; i++ )
5564 wsa->iovec[i].iov_base = lpBuffers[i].buf;
5565 wsa->iovec[i].iov_len = lpBuffers[i].len;
5566 totalLength += lpBuffers[i].len;
5569 flags = convert_flags(dwFlags);
5570 n = WS2_send( fd, wsa, flags );
5571 if (n == -1 && errno != EAGAIN)
5573 err = wsaErrno();
5574 goto error;
5577 if (overlapped)
5579 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
5580 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
5582 wsa->user_overlapped = lpOverlapped;
5583 wsa->completion_func = lpCompletionRoutine;
5584 release_sock_fd( s, fd );
5586 if (n == -1 || n < totalLength)
5588 iosb->u.Status = STATUS_PENDING;
5589 iosb->Information = n == -1 ? 0 : n;
5591 if (wsa->completion_func)
5592 err = register_async( ASYNC_TYPE_WRITE, wsa->hSocket, &wsa->io, NULL,
5593 ws2_async_apc, wsa, iosb );
5594 else
5595 err = register_async( ASYNC_TYPE_WRITE, wsa->hSocket, &wsa->io, lpOverlapped->hEvent,
5596 NULL, (void *)cvalue, iosb );
5598 /* Enable the event only after starting the async. The server will deliver it as soon as
5599 the async is done. */
5600 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
5602 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
5603 SetLastError(NtStatusToWSAError( err ));
5604 return SOCKET_ERROR;
5607 iosb->u.Status = STATUS_SUCCESS;
5608 iosb->Information = n;
5609 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = n;
5610 if (!wsa->completion_func)
5612 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
5613 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
5614 HeapFree( GetProcessHeap(), 0, wsa );
5616 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
5617 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
5618 SetLastError(ERROR_SUCCESS);
5619 return 0;
5622 if ((err = _is_blocking( s, &is_blocking )))
5624 err = NtStatusToWSAError( err );
5625 goto error;
5628 if ( is_blocking )
5630 /* On a blocking non-overlapped stream socket,
5631 * sending blocks until the entire buffer is sent. */
5632 DWORD timeout_start = GetTickCount();
5634 bytes_sent = n == -1 ? 0 : n;
5636 while (wsa->first_iovec < wsa->n_iovecs)
5638 struct pollfd pfd;
5639 int poll_timeout = -1;
5640 INT64 timeout = get_rcvsnd_timeo(fd, FALSE);
5642 if (timeout)
5644 timeout -= GetTickCount() - timeout_start;
5645 if (timeout < 0) poll_timeout = 0;
5646 else poll_timeout = timeout <= INT_MAX ? timeout : INT_MAX;
5649 pfd.fd = fd;
5650 pfd.events = POLLOUT;
5652 if (!poll_timeout || !poll( &pfd, 1, poll_timeout ))
5654 err = WSAETIMEDOUT;
5655 goto error; /* msdn says a timeout in send is fatal */
5658 n = WS2_send( fd, wsa, flags );
5659 if (n == -1 && errno != EAGAIN)
5661 err = wsaErrno();
5662 goto error;
5665 if (n >= 0)
5666 bytes_sent += n;
5669 else /* non-blocking */
5671 if (n < totalLength)
5672 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
5673 if (n == -1)
5675 err = WSAEWOULDBLOCK;
5676 goto error;
5678 bytes_sent = n;
5681 TRACE(" -> %i bytes\n", bytes_sent);
5683 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = bytes_sent;
5684 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
5685 release_sock_fd( s, fd );
5686 SetLastError(ERROR_SUCCESS);
5687 return 0;
5689 error:
5690 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
5691 release_sock_fd( s, fd );
5692 WARN(" -> ERROR %d\n", err);
5693 SetLastError(err);
5694 return SOCKET_ERROR;
5697 /***********************************************************************
5698 * WSASendTo (WS2_32.74)
5700 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5701 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
5702 const struct WS_sockaddr *to, int tolen,
5703 LPWSAOVERLAPPED lpOverlapped,
5704 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5706 return WS2_sendto( s, lpBuffers, dwBufferCount,
5707 lpNumberOfBytesSent, dwFlags,
5708 to, tolen,
5709 lpOverlapped, lpCompletionRoutine );
5712 /***********************************************************************
5713 * sendto (WS2_32.20)
5715 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
5716 const struct WS_sockaddr *to, int tolen)
5718 DWORD n;
5719 WSABUF wsabuf;
5721 wsabuf.len = len;
5722 wsabuf.buf = (char*) buf;
5724 if ( WS2_sendto(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
5725 return SOCKET_ERROR;
5726 else
5727 return n;
5730 /***********************************************************************
5731 * setsockopt (WS2_32.21)
5733 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
5734 const char *optval, int optlen)
5736 int fd;
5737 int woptval;
5738 struct linger linger;
5739 struct timeval tval;
5741 TRACE("(socket %04lx, %s, optval %s, optlen %d)\n", s,
5742 debugstr_sockopt(level, optname), debugstr_optval(optval, optlen),
5743 optlen);
5745 /* some broken apps pass the value directly instead of a pointer to it */
5746 if(optlen && IS_INTRESOURCE(optval))
5748 SetLastError(WSAEFAULT);
5749 return SOCKET_ERROR;
5752 switch(level)
5754 case WS_SOL_SOCKET:
5755 switch(optname)
5757 /* Some options need some conversion before they can be sent to
5758 * setsockopt. The conversions are done here, then they will fall through
5759 * to the general case. Special options that are not passed to
5760 * setsockopt follow below that.*/
5762 case WS_SO_DONTLINGER:
5763 if (!optval)
5765 SetLastError(WSAEFAULT);
5766 return SOCKET_ERROR;
5768 linger.l_onoff = *(const int*)optval == 0;
5769 linger.l_linger = 0;
5770 level = SOL_SOCKET;
5771 optname = SO_LINGER;
5772 optval = (char*)&linger;
5773 optlen = sizeof(struct linger);
5774 break;
5776 case WS_SO_LINGER:
5777 if (!optval)
5779 SetLastError(WSAEFAULT);
5780 return SOCKET_ERROR;
5782 linger.l_onoff = ((LINGER*)optval)->l_onoff;
5783 linger.l_linger = ((LINGER*)optval)->l_linger;
5784 level = SOL_SOCKET;
5785 optname = SO_LINGER;
5786 optval = (char*)&linger;
5787 optlen = sizeof(struct linger);
5788 break;
5790 case WS_SO_RCVBUF:
5791 if (*(const int*)optval < 2048)
5793 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
5794 return 0;
5796 /* Fall through */
5798 /* The options listed here don't need any special handling. Thanks to
5799 * the conversion happening above, options from there will fall through
5800 * to this, too.*/
5801 case WS_SO_ACCEPTCONN:
5802 case WS_SO_BROADCAST:
5803 case WS_SO_ERROR:
5804 case WS_SO_KEEPALIVE:
5805 case WS_SO_OOBINLINE:
5806 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
5807 * however, using it the BSD way fixes bug 8513 and seems to be what
5808 * most programmers assume, anyway */
5809 case WS_SO_REUSEADDR:
5810 case WS_SO_SNDBUF:
5811 case WS_SO_TYPE:
5812 convert_sockopt(&level, &optname);
5813 break;
5815 /* SO_DEBUG is a privileged operation, ignore it. */
5816 case WS_SO_DEBUG:
5817 TRACE("Ignoring SO_DEBUG\n");
5818 return 0;
5820 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
5821 * socket. According to MSDN, this option is silently ignored.*/
5822 case WS_SO_DONTROUTE:
5823 TRACE("Ignoring SO_DONTROUTE\n");
5824 return 0;
5826 /* Stops two sockets from being bound to the same port. Always happens
5827 * on unix systems, so just drop it. */
5828 case WS_SO_EXCLUSIVEADDRUSE:
5829 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
5830 return 0;
5832 /* After a ConnectEx call succeeds, the socket can't be used with half of the
5833 * normal winsock functions on windows. We don't have that problem. */
5834 case WS_SO_UPDATE_CONNECT_CONTEXT:
5835 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
5836 return 0;
5838 /* After a AcceptEx call succeeds, the socket can't be used with half of the
5839 * normal winsock functions on windows. We don't have that problem. */
5840 case WS_SO_UPDATE_ACCEPT_CONTEXT:
5841 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
5842 return 0;
5844 /* SO_OPENTYPE does not require a valid socket handle. */
5845 case WS_SO_OPENTYPE:
5846 if (!optlen || optlen < sizeof(int) || !optval)
5848 SetLastError(WSAEFAULT);
5849 return SOCKET_ERROR;
5851 get_per_thread_data()->opentype = *(const int *)optval;
5852 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
5853 return 0;
5855 #ifdef SO_RCVTIMEO
5856 case WS_SO_RCVTIMEO:
5857 #endif
5858 #ifdef SO_SNDTIMEO
5859 case WS_SO_SNDTIMEO:
5860 #endif
5861 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
5862 if (optval && optlen == sizeof(UINT32)) {
5863 /* WinSock passes milliseconds instead of struct timeval */
5864 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
5865 tval.tv_sec = *(const UINT32*)optval / 1000;
5866 /* min of 500 milliseconds */
5867 if (tval.tv_sec == 0 && tval.tv_usec && tval.tv_usec < 500000)
5868 tval.tv_usec = 500000;
5869 optlen = sizeof(struct timeval);
5870 optval = (char*)&tval;
5871 } else if (optlen == sizeof(struct timeval)) {
5872 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
5873 } else {
5874 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
5875 return 0;
5877 convert_sockopt(&level, &optname);
5878 break;
5879 #endif
5881 default:
5882 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
5883 SetLastError(WSAENOPROTOOPT);
5884 return SOCKET_ERROR;
5886 break; /* case WS_SOL_SOCKET */
5888 #ifdef HAS_IPX
5889 case WS_NSPROTO_IPX:
5890 switch(optname)
5892 case WS_IPX_PTYPE:
5893 return set_ipx_packettype(s, *(int*)optval);
5895 case WS_IPX_FILTERPTYPE:
5896 /* Sets the receive filter packet type, at the moment we don't support it */
5897 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
5898 /* Returning 0 is better for now than returning a SOCKET_ERROR */
5899 return 0;
5901 default:
5902 FIXME("opt_name:%x\n", optname);
5903 return SOCKET_ERROR;
5905 break; /* case WS_NSPROTO_IPX */
5906 #endif
5908 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
5909 case WS_IPPROTO_TCP:
5910 switch(optname)
5912 case WS_TCP_NODELAY:
5913 convert_sockopt(&level, &optname);
5914 break;
5915 default:
5916 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
5917 return SOCKET_ERROR;
5919 break;
5921 case WS_IPPROTO_IP:
5922 switch(optname)
5924 case WS_IP_ADD_MEMBERSHIP:
5925 case WS_IP_DROP_MEMBERSHIP:
5926 #ifdef IP_HDRINCL
5927 case WS_IP_HDRINCL:
5928 #endif
5929 case WS_IP_MULTICAST_IF:
5930 case WS_IP_MULTICAST_LOOP:
5931 case WS_IP_MULTICAST_TTL:
5932 case WS_IP_OPTIONS:
5933 #ifdef IP_PKTINFO
5934 case WS_IP_PKTINFO:
5935 #endif
5936 case WS_IP_TOS:
5937 case WS_IP_TTL:
5938 #ifdef IP_UNICAST_IF
5939 case WS_IP_UNICAST_IF:
5940 #endif
5941 convert_sockopt(&level, &optname);
5942 break;
5943 case WS_IP_DONTFRAGMENT:
5944 return set_dont_fragment(s, IPPROTO_IP, *(BOOL *)optval) ? 0 : SOCKET_ERROR;
5945 default:
5946 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
5947 return SOCKET_ERROR;
5949 break;
5951 case WS_IPPROTO_IPV6:
5952 switch(optname)
5954 #ifdef IPV6_ADD_MEMBERSHIP
5955 case WS_IPV6_ADD_MEMBERSHIP:
5956 #endif
5957 #ifdef IPV6_DROP_MEMBERSHIP
5958 case WS_IPV6_DROP_MEMBERSHIP:
5959 #endif
5960 case WS_IPV6_MULTICAST_IF:
5961 case WS_IPV6_MULTICAST_HOPS:
5962 case WS_IPV6_MULTICAST_LOOP:
5963 case WS_IPV6_UNICAST_HOPS:
5964 #ifdef IPV6_UNICAST_IF
5965 case WS_IPV6_UNICAST_IF:
5966 #endif
5967 convert_sockopt(&level, &optname);
5968 break;
5969 case WS_IPV6_DONTFRAG:
5970 return set_dont_fragment(s, IPPROTO_IPV6, *(BOOL *)optval) ? 0 : SOCKET_ERROR;
5971 case WS_IPV6_PROTECTION_LEVEL:
5972 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
5973 return 0;
5974 case WS_IPV6_V6ONLY:
5976 union generic_unix_sockaddr uaddr;
5977 socklen_t uaddrlen;
5978 int bound;
5980 fd = get_sock_fd( s, 0, NULL );
5981 if (fd == -1) return SOCKET_ERROR;
5983 bound = is_fd_bound(fd, &uaddr, &uaddrlen);
5984 release_sock_fd( s, fd );
5985 if (bound == 0 && uaddr.addr.sa_family == AF_INET)
5987 /* Changing IPV6_V6ONLY succeeds on AF_INET (IPv4) socket
5988 * on Windows (with IPv6 support) if the socket is unbound.
5989 * It is essentially a noop, though Windows does store the value
5991 WARN("Silently ignoring IPPROTO_IPV6+IPV6_V6ONLY on AF_INET socket\n");
5992 return 0;
5994 level = IPPROTO_IPV6;
5995 optname = IPV6_V6ONLY;
5996 break;
5998 default:
5999 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
6000 return SOCKET_ERROR;
6002 break;
6004 default:
6005 WARN("Unknown level: 0x%08x\n", level);
6006 SetLastError(WSAEINVAL);
6007 return SOCKET_ERROR;
6008 } /* end switch(level) */
6010 /* avoid endianness issues if argument is a 16-bit int */
6011 if (optval && optlen < sizeof(int))
6013 woptval= *((const INT16 *) optval);
6014 optval= (char*) &woptval;
6015 woptval&= (1 << optlen * 8) - 1;
6016 optlen=sizeof(int);
6018 fd = get_sock_fd( s, 0, NULL );
6019 if (fd == -1) return SOCKET_ERROR;
6021 if (setsockopt(fd, level, optname, optval, optlen) == 0)
6023 #ifdef __APPLE__
6024 if (level == SOL_SOCKET && optname == SO_REUSEADDR &&
6025 setsockopt(fd, level, SO_REUSEPORT, optval, optlen) != 0)
6027 SetLastError(wsaErrno());
6028 release_sock_fd( s, fd );
6029 return SOCKET_ERROR;
6031 #endif
6032 release_sock_fd( s, fd );
6033 return 0;
6035 TRACE("Setting socket error, %d\n", wsaErrno());
6036 SetLastError(wsaErrno());
6037 release_sock_fd( s, fd );
6039 return SOCKET_ERROR;
6042 /***********************************************************************
6043 * shutdown (WS2_32.22)
6045 int WINAPI WS_shutdown(SOCKET s, int how)
6047 int fd, err = WSAENOTSOCK;
6048 unsigned int options = 0, clear_flags = 0;
6050 fd = get_sock_fd( s, 0, &options );
6051 TRACE("socket %04lx, how 0x%x, options 0x%x\n", s, how, options );
6053 if (fd == -1)
6054 return SOCKET_ERROR;
6056 switch( how )
6058 case SD_RECEIVE: /* drop receives */
6059 clear_flags |= FD_READ;
6060 break;
6061 case SD_SEND: /* drop sends */
6062 clear_flags |= FD_WRITE;
6063 break;
6064 case SD_BOTH: /* drop all */
6065 clear_flags |= FD_READ|FD_WRITE;
6066 /*fall through */
6067 default:
6068 clear_flags |= FD_WINE_LISTENING;
6071 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
6073 switch ( how )
6075 case SD_RECEIVE:
6076 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
6077 break;
6078 case SD_SEND:
6079 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
6080 break;
6081 case SD_BOTH:
6082 default:
6083 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
6084 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
6085 break;
6087 if (err) goto error;
6089 else /* non-overlapped mode */
6091 if ( shutdown( fd, how ) )
6093 err = wsaErrno();
6094 goto error;
6098 release_sock_fd( s, fd );
6099 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
6100 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
6101 return 0;
6103 error:
6104 release_sock_fd( s, fd );
6105 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
6106 SetLastError( err );
6107 return SOCKET_ERROR;
6110 /***********************************************************************
6111 * socket (WS2_32.23)
6113 SOCKET WINAPI WS_socket(int af, int type, int protocol)
6115 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
6117 return WSASocketW( af, type, protocol, NULL, 0,
6118 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
6122 /***********************************************************************
6123 * gethostbyaddr (WS2_32.51)
6125 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
6127 struct WS_hostent *retval = NULL;
6128 struct hostent* host;
6129 int unixtype = convert_af_w2u(type);
6130 const char *paddr = addr;
6131 unsigned long loopback;
6132 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6133 char *extrabuf;
6134 int ebufsize = 1024;
6135 struct hostent hostentry;
6136 int locerr = ENOBUFS;
6137 #endif
6139 /* convert back the magic loopback address if necessary */
6140 if (unixtype == AF_INET && len == 4 && !memcmp(addr, magic_loopback_addr, 4))
6142 loopback = htonl(INADDR_LOOPBACK);
6143 paddr = (char*) &loopback;
6146 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6147 host = NULL;
6148 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
6149 while(extrabuf) {
6150 int res = gethostbyaddr_r(paddr, len, unixtype,
6151 &hostentry, extrabuf, ebufsize, &host, &locerr);
6152 if (res != ERANGE) break;
6153 ebufsize *=2;
6154 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
6156 if (host) retval = WS_dup_he(host);
6157 else SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
6158 HeapFree(GetProcessHeap(),0,extrabuf);
6159 #else
6160 EnterCriticalSection( &csWSgetXXXbyYYY );
6161 host = gethostbyaddr(paddr, len, unixtype);
6162 if (host) retval = WS_dup_he(host);
6163 else SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
6164 LeaveCriticalSection( &csWSgetXXXbyYYY );
6165 #endif
6166 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
6167 return retval;
6170 /***********************************************************************
6171 * WS_compare_routes_by_metric_asc (INTERNAL)
6173 * Comparison function for qsort(), for sorting two routes (struct route)
6174 * by metric in ascending order.
6176 static int WS_compare_routes_by_metric_asc(const void *left, const void *right)
6178 const struct route *a = left, *b = right;
6179 if (a->default_route && b->default_route)
6180 return a->default_route - b->default_route;
6181 if (a->default_route && !b->default_route)
6182 return -1;
6183 if (b->default_route && !a->default_route)
6184 return 1;
6185 return a->metric - b->metric;
6188 /***********************************************************************
6189 * WS_get_local_ips (INTERNAL)
6191 * Returns the list of local IP addresses by going through the network
6192 * adapters and using the local routing table to sort the addresses
6193 * from highest routing priority to lowest routing priority. This
6194 * functionality is inferred from the description for obtaining local
6195 * IP addresses given in the Knowledge Base Article Q160215.
6197 * Please note that the returned hostent is only freed when the thread
6198 * closes and is replaced if another hostent is requested.
6200 static struct WS_hostent* WS_get_local_ips( char *hostname )
6202 int numroutes = 0, i, j, default_routes = 0;
6203 DWORD n;
6204 PIP_ADAPTER_INFO adapters = NULL, k;
6205 struct WS_hostent *hostlist = NULL;
6206 PMIB_IPFORWARDTABLE routes = NULL;
6207 struct route *route_addrs = NULL;
6208 DWORD adap_size, route_size;
6210 /* Obtain the size of the adapter list and routing table, also allocate memory */
6211 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
6212 return NULL;
6213 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
6214 return NULL;
6215 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
6216 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
6217 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
6218 if (adapters == NULL || routes == NULL || route_addrs == NULL)
6219 goto cleanup;
6220 /* Obtain the adapter list and the full routing table */
6221 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
6222 goto cleanup;
6223 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
6224 goto cleanup;
6225 /* Store the interface associated with each route */
6226 for (n = 0; n < routes->dwNumEntries; n++)
6228 IF_INDEX ifindex;
6229 DWORD ifmetric, ifdefault = 0;
6230 BOOL exists = FALSE;
6232 /* Check if this is a default route (there may be more than one) */
6233 if (!routes->table[n].dwForwardDest)
6234 ifdefault = ++default_routes;
6235 else if (routes->table[n].u1.ForwardType != MIB_IPROUTE_TYPE_DIRECT)
6236 continue;
6237 ifindex = routes->table[n].dwForwardIfIndex;
6238 ifmetric = routes->table[n].dwForwardMetric1;
6239 /* Only store the lowest valued metric for an interface */
6240 for (j = 0; j < numroutes; j++)
6242 if (route_addrs[j].interface == ifindex)
6244 if (route_addrs[j].metric > ifmetric)
6245 route_addrs[j].metric = ifmetric;
6246 exists = TRUE;
6249 if (exists)
6250 continue;
6251 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
6252 if (route_addrs == NULL)
6253 goto cleanup; /* Memory allocation error, fail gracefully */
6254 route_addrs[numroutes].interface = ifindex;
6255 route_addrs[numroutes].metric = ifmetric;
6256 route_addrs[numroutes].default_route = ifdefault;
6257 /* If no IP is found in the next step (for whatever reason)
6258 * then fall back to the magic loopback address.
6260 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
6261 numroutes++;
6263 if (numroutes == 0)
6264 goto cleanup; /* No routes, fall back to the Magic IP */
6265 /* Find the IP address associated with each found interface */
6266 for (i = 0; i < numroutes; i++)
6268 for (k = adapters; k != NULL; k = k->Next)
6270 char *ip = k->IpAddressList.IpAddress.String;
6272 if (route_addrs[i].interface == k->Index)
6273 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
6276 /* Allocate a hostent and enough memory for all the IPs,
6277 * including the NULL at the end of the list.
6279 hostlist = WS_create_he(hostname, 1, 0, numroutes+1, sizeof(struct in_addr));
6280 if (hostlist == NULL)
6281 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
6282 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
6283 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
6284 hostlist->h_addrtype = AF_INET;
6285 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
6286 /* Reorder the entries before placing them in the host list. Windows expects
6287 * the IP list in order from highest priority to lowest (the critical thing
6288 * is that most applications expect the first IP to be the default route).
6290 if (numroutes > 1)
6291 qsort(route_addrs, numroutes, sizeof(struct route), WS_compare_routes_by_metric_asc);
6293 for (i = 0; i < numroutes; i++)
6294 (*(struct in_addr *) hostlist->h_addr_list[i]) = route_addrs[i].addr;
6296 /* Cleanup all allocated memory except the address list,
6297 * the address list is used by the calling app.
6299 cleanup:
6300 HeapFree(GetProcessHeap(), 0, route_addrs);
6301 HeapFree(GetProcessHeap(), 0, adapters);
6302 HeapFree(GetProcessHeap(), 0, routes);
6303 return hostlist;
6306 /***********************************************************************
6307 * gethostbyname (WS2_32.52)
6309 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
6311 struct WS_hostent *retval = NULL;
6312 struct hostent* host;
6313 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6314 char *extrabuf;
6315 int ebufsize=1024;
6316 struct hostent hostentry;
6317 int locerr = ENOBUFS;
6318 #endif
6319 char hostname[100];
6320 if(!num_startup) {
6321 SetLastError(WSANOTINITIALISED);
6322 return NULL;
6324 if( gethostname( hostname, 100) == -1) {
6325 SetLastError(WSAENOBUFS); /* appropriate ? */
6326 return retval;
6328 if( !name || !name[0]) {
6329 name = hostname;
6331 /* If the hostname of the local machine is requested then return the
6332 * complete list of local IP addresses */
6333 if(strcmp(name, hostname) == 0)
6334 retval = WS_get_local_ips(hostname);
6335 /* If any other hostname was requested (or the routing table lookup failed)
6336 * then return the IP found by the host OS */
6337 if(retval == NULL)
6339 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6340 host = NULL;
6341 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
6342 while(extrabuf) {
6343 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
6344 if( res != ERANGE) break;
6345 ebufsize *=2;
6346 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
6348 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
6349 #else
6350 EnterCriticalSection( &csWSgetXXXbyYYY );
6351 host = gethostbyname(name);
6352 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
6353 #endif
6354 if (host) retval = WS_dup_he(host);
6355 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
6356 HeapFree(GetProcessHeap(),0,extrabuf);
6357 #else
6358 LeaveCriticalSection( &csWSgetXXXbyYYY );
6359 #endif
6361 if (retval && retval->h_addr_list[0][0] == 127 &&
6362 strcmp(name, "localhost") != 0)
6364 /* hostname != "localhost" but has loopback address. replace by our
6365 * special address.*/
6366 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
6368 TRACE( "%s ret %p\n", debugstr_a(name), retval );
6369 return retval;
6373 /***********************************************************************
6374 * getprotobyname (WS2_32.53)
6376 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
6378 struct WS_protoent* retval = NULL;
6379 #ifdef HAVE_GETPROTOBYNAME
6380 struct protoent* proto;
6381 EnterCriticalSection( &csWSgetXXXbyYYY );
6382 if( (proto = getprotobyname(name)) != NULL )
6384 retval = WS_dup_pe(proto);
6386 else {
6387 MESSAGE("protocol %s not found; You might want to add "
6388 "this to /etc/protocols\n", debugstr_a(name) );
6389 SetLastError(WSANO_DATA);
6391 LeaveCriticalSection( &csWSgetXXXbyYYY );
6392 #endif
6393 TRACE( "%s ret %p\n", debugstr_a(name), retval );
6394 return retval;
6398 /***********************************************************************
6399 * getprotobynumber (WS2_32.54)
6401 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
6403 struct WS_protoent* retval = NULL;
6404 #ifdef HAVE_GETPROTOBYNUMBER
6405 struct protoent* proto;
6406 EnterCriticalSection( &csWSgetXXXbyYYY );
6407 if( (proto = getprotobynumber(number)) != NULL )
6409 retval = WS_dup_pe(proto);
6411 else {
6412 MESSAGE("protocol number %d not found; You might want to add "
6413 "this to /etc/protocols\n", number );
6414 SetLastError(WSANO_DATA);
6416 LeaveCriticalSection( &csWSgetXXXbyYYY );
6417 #endif
6418 TRACE("%i ret %p\n", number, retval);
6419 return retval;
6423 /***********************************************************************
6424 * getservbyname (WS2_32.55)
6426 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
6428 struct WS_servent* retval = NULL;
6429 struct servent* serv;
6430 char *name_str;
6431 char *proto_str = NULL;
6433 if (!(name_str = strdup_lower(name))) return NULL;
6435 if (proto && *proto)
6437 if (!(proto_str = strdup_lower(proto)))
6439 HeapFree( GetProcessHeap(), 0, name_str );
6440 return NULL;
6444 EnterCriticalSection( &csWSgetXXXbyYYY );
6445 serv = getservbyname(name_str, proto_str);
6446 if( serv != NULL )
6448 retval = WS_dup_se(serv);
6450 else SetLastError(WSANO_DATA);
6451 LeaveCriticalSection( &csWSgetXXXbyYYY );
6452 HeapFree( GetProcessHeap(), 0, proto_str );
6453 HeapFree( GetProcessHeap(), 0, name_str );
6454 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
6455 return retval;
6458 /***********************************************************************
6459 * freeaddrinfo (WS2_32.@)
6461 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
6463 while (res) {
6464 struct WS_addrinfo *next;
6466 HeapFree(GetProcessHeap(),0,res->ai_canonname);
6467 HeapFree(GetProcessHeap(),0,res->ai_addr);
6468 next = res->ai_next;
6469 HeapFree(GetProcessHeap(),0,res);
6470 res = next;
6474 /* helper functions for getaddrinfo()/getnameinfo() */
6475 static int convert_aiflag_w2u(int winflags) {
6476 unsigned int i;
6477 int unixflags = 0;
6479 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
6480 if (ws_aiflag_map[i][0] & winflags) {
6481 unixflags |= ws_aiflag_map[i][1];
6482 winflags &= ~ws_aiflag_map[i][0];
6484 if (winflags)
6485 FIXME("Unhandled windows AI_xxx flags 0x%x\n", winflags);
6486 return unixflags;
6489 static int convert_niflag_w2u(int winflags) {
6490 unsigned int i;
6491 int unixflags = 0;
6493 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
6494 if (ws_niflag_map[i][0] & winflags) {
6495 unixflags |= ws_niflag_map[i][1];
6496 winflags &= ~ws_niflag_map[i][0];
6498 if (winflags)
6499 FIXME("Unhandled windows NI_xxx flags 0x%x\n", winflags);
6500 return unixflags;
6503 static int convert_aiflag_u2w(int unixflags) {
6504 unsigned int i;
6505 int winflags = 0;
6507 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
6508 if (ws_aiflag_map[i][1] & unixflags) {
6509 winflags |= ws_aiflag_map[i][0];
6510 unixflags &= ~ws_aiflag_map[i][1];
6512 if (unixflags)
6513 WARN("Unhandled UNIX AI_xxx flags 0x%x\n", unixflags);
6514 return winflags;
6517 static int convert_eai_u2w(int unixret) {
6518 int i;
6520 if (!unixret) return 0;
6522 for (i=0;ws_eai_map[i][0];i++)
6523 if (ws_eai_map[i][1] == unixret)
6524 return ws_eai_map[i][0];
6526 if (unixret == EAI_SYSTEM)
6527 /* There are broken versions of glibc which return EAI_SYSTEM
6528 * and set errno to 0 instead of returning EAI_NONAME.
6530 return errno ? sock_get_error( errno ) : WS_EAI_NONAME;
6532 FIXME("Unhandled unix EAI_xxx ret %d\n", unixret);
6533 return unixret;
6536 static char *get_hostname(void)
6538 char *ret;
6539 DWORD size = 0;
6541 GetComputerNameExA( ComputerNamePhysicalDnsHostname, NULL, &size );
6542 if (GetLastError() != ERROR_MORE_DATA) return NULL;
6543 if (!(ret = HeapAlloc( GetProcessHeap(), 0, size ))) return NULL;
6544 if (!GetComputerNameExA( ComputerNamePhysicalDnsHostname, ret, &size ))
6546 HeapFree( GetProcessHeap(), 0, ret );
6547 return NULL;
6549 return ret;
6552 /***********************************************************************
6553 * getaddrinfo (WS2_32.@)
6555 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
6557 #ifdef HAVE_GETADDRINFO
6558 struct addrinfo *unixaires = NULL;
6559 int result;
6560 struct addrinfo unixhints, *punixhints = NULL;
6561 char *hostname, *nodeV6 = NULL;
6562 const char *node;
6564 *res = NULL;
6565 if (!nodename && !servname)
6567 SetLastError(WSAHOST_NOT_FOUND);
6568 return WSAHOST_NOT_FOUND;
6571 hostname = get_hostname();
6572 if (!hostname) return WSA_NOT_ENOUGH_MEMORY;
6574 if (!nodename)
6575 node = NULL;
6576 else if (!nodename[0])
6577 node = hostname;
6578 else
6580 node = nodename;
6582 /* Check for [ipv6] or [ipv6]:portnumber, which are supported by Windows */
6583 if (!hints || hints->ai_family == WS_AF_UNSPEC || hints->ai_family == WS_AF_INET6)
6585 char *close_bracket;
6587 if (node[0] == '[' && (close_bracket = strchr(node + 1, ']')))
6589 nodeV6 = HeapAlloc(GetProcessHeap(), 0, close_bracket - node);
6590 if (!nodeV6)
6592 HeapFree(GetProcessHeap(), 0, hostname);
6593 return WSA_NOT_ENOUGH_MEMORY;
6595 lstrcpynA(nodeV6, node + 1, close_bracket - node);
6596 node = nodeV6;
6601 /* servname tweak required by OSX and BSD kernels */
6602 if (servname && !servname[0]) servname = "0";
6604 if (hints) {
6605 punixhints = &unixhints;
6607 memset(&unixhints, 0, sizeof(unixhints));
6608 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
6610 /* zero is a wildcard, no need to convert */
6611 if (hints->ai_family)
6612 punixhints->ai_family = convert_af_w2u(hints->ai_family);
6613 if (hints->ai_socktype)
6614 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
6615 if (hints->ai_protocol)
6616 punixhints->ai_protocol = max(convert_proto_w2u(hints->ai_protocol), 0);
6618 if (punixhints->ai_socktype < 0)
6620 SetLastError(WSAESOCKTNOSUPPORT);
6621 HeapFree(GetProcessHeap(), 0, hostname);
6622 HeapFree(GetProcessHeap(), 0, nodeV6);
6623 return SOCKET_ERROR;
6626 /* windows allows invalid combinations of socket type and protocol, unix does not.
6627 * fix the parameters here to make getaddrinfo call always work */
6628 if (punixhints->ai_protocol == IPPROTO_TCP &&
6629 punixhints->ai_socktype != SOCK_STREAM && punixhints->ai_socktype != SOCK_SEQPACKET)
6630 punixhints->ai_socktype = 0;
6632 else if (punixhints->ai_protocol == IPPROTO_UDP && punixhints->ai_socktype != SOCK_DGRAM)
6633 punixhints->ai_socktype = 0;
6635 else if (IS_IPX_PROTO(punixhints->ai_protocol) && punixhints->ai_socktype != SOCK_DGRAM)
6636 punixhints->ai_socktype = 0;
6638 else if (punixhints->ai_protocol == IPPROTO_IPV6)
6639 punixhints->ai_protocol = 0;
6642 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
6643 result = getaddrinfo(node, servname, punixhints, &unixaires);
6645 if (result && (!hints || !(hints->ai_flags & WS_AI_NUMERICHOST)) && !strcmp(hostname, node))
6647 /* If it didn't work it means the host name IP is not in /etc/hosts, try again
6648 * by sending a NULL host and avoid sending a NULL servname too because that
6649 * is invalid */
6650 ERR_(winediag)("Failed to resolve your host name IP\n");
6651 result = getaddrinfo(NULL, servname ? servname : "0", punixhints, &unixaires);
6653 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
6654 HeapFree(GetProcessHeap(), 0, hostname);
6655 HeapFree(GetProcessHeap(), 0, nodeV6);
6657 if (!result) {
6658 struct addrinfo *xuai = unixaires;
6659 struct WS_addrinfo **xai = res;
6661 *xai = NULL;
6662 while (xuai) {
6663 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
6664 SIZE_T len;
6666 if (!ai)
6667 goto outofmem;
6669 *xai = ai;xai = &ai->ai_next;
6670 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
6671 ai->ai_family = convert_af_u2w(xuai->ai_family);
6672 /* copy whatever was sent in the hints */
6673 if(hints) {
6674 ai->ai_socktype = hints->ai_socktype;
6675 ai->ai_protocol = hints->ai_protocol;
6676 } else {
6677 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
6678 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
6680 if (xuai->ai_canonname) {
6681 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
6682 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
6683 if (!ai->ai_canonname)
6684 goto outofmem;
6685 strcpy(ai->ai_canonname,xuai->ai_canonname);
6687 len = xuai->ai_addrlen;
6688 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
6689 if (!ai->ai_addr)
6690 goto outofmem;
6691 ai->ai_addrlen = len;
6692 do {
6693 int winlen = ai->ai_addrlen;
6695 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
6696 ai->ai_addrlen = winlen;
6697 break;
6699 len = 2*len;
6700 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
6701 if (!ai->ai_addr)
6702 goto outofmem;
6703 ai->ai_addrlen = len;
6704 } while (1);
6705 xuai = xuai->ai_next;
6707 freeaddrinfo(unixaires);
6709 if (TRACE_ON(winsock))
6711 struct WS_addrinfo *ai = *res;
6712 while (ai)
6714 TRACE("=> %p, flags %#x, family %d, type %d, protocol %d, len %ld, name %s, addr %s\n",
6715 ai, ai->ai_flags, ai->ai_family, ai->ai_socktype, ai->ai_protocol, ai->ai_addrlen,
6716 ai->ai_canonname, debugstr_sockaddr(ai->ai_addr));
6717 ai = ai->ai_next;
6720 } else
6721 result = convert_eai_u2w(result);
6723 SetLastError(result);
6724 return result;
6726 outofmem:
6727 if (*res) WS_freeaddrinfo(*res);
6728 if (unixaires) freeaddrinfo(unixaires);
6729 return WSA_NOT_ENOUGH_MEMORY;
6730 #else
6731 FIXME("getaddrinfo() failed, not found during buildtime.\n");
6732 return EAI_FAIL;
6733 #endif
6736 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
6738 struct WS_addrinfoW *ret;
6740 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
6741 ret->ai_flags = ai->ai_flags;
6742 ret->ai_family = ai->ai_family;
6743 ret->ai_socktype = ai->ai_socktype;
6744 ret->ai_protocol = ai->ai_protocol;
6745 ret->ai_addrlen = ai->ai_addrlen;
6746 ret->ai_canonname = NULL;
6747 ret->ai_addr = NULL;
6748 ret->ai_next = NULL;
6749 if (ai->ai_canonname)
6751 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
6752 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR))))
6754 HeapFree(GetProcessHeap(), 0, ret);
6755 return NULL;
6757 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
6759 if (ai->ai_addr)
6761 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, ai->ai_addrlen)))
6763 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
6764 HeapFree(GetProcessHeap(), 0, ret);
6765 return NULL;
6767 memcpy(ret->ai_addr, ai->ai_addr, ai->ai_addrlen);
6769 return ret;
6772 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
6774 struct WS_addrinfoW *ret, *infoW;
6776 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
6777 while (info->ai_next)
6779 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
6781 FreeAddrInfoW(ret);
6782 return NULL;
6784 infoW = infoW->ai_next;
6785 info = info->ai_next;
6787 return ret;
6790 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
6792 struct WS_addrinfo *ret;
6794 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
6795 ret->ai_flags = ai->ai_flags;
6796 ret->ai_family = ai->ai_family;
6797 ret->ai_socktype = ai->ai_socktype;
6798 ret->ai_protocol = ai->ai_protocol;
6799 ret->ai_addrlen = ai->ai_addrlen;
6800 ret->ai_canonname = NULL;
6801 ret->ai_addr = NULL;
6802 ret->ai_next = NULL;
6803 if (ai->ai_canonname)
6805 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
6806 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
6808 HeapFree(GetProcessHeap(), 0, ret);
6809 return NULL;
6811 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
6813 if (ai->ai_addr)
6815 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
6817 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
6818 HeapFree(GetProcessHeap(), 0, ret);
6819 return NULL;
6821 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
6823 return ret;
6826 /***********************************************************************
6827 * GetAddrInfoExW (WS2_32.@)
6829 int WINAPI GetAddrInfoExW(const WCHAR *name, const WCHAR *servname, DWORD namespace, GUID *namespace_id,
6830 const ADDRINFOEXW *hints, ADDRINFOEXW **result, struct timeval *timeout, OVERLAPPED *overlapped,
6831 LPLOOKUPSERVICE_COMPLETION_ROUTINE completion_routine, HANDLE *handle)
6833 FIXME("(%s %s %x %s %p %p %p %p %p %p)\n", debugstr_w(name), debugstr_w(servname), namespace,
6834 debugstr_guid(namespace_id), hints, result, timeout, overlapped, completion_routine, handle);
6835 return WSAHOST_NOT_FOUND;
6838 /***********************************************************************
6839 * GetAddrInfoExCancel (WS2_32.@)
6841 int WINAPI GetAddrInfoExCancel(HANDLE *handle)
6843 FIXME("(%p)\n", handle);
6844 return WSA_INVALID_HANDLE;
6847 /***********************************************************************
6848 * GetAddrInfoW (WS2_32.@)
6850 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
6852 int ret = EAI_MEMORY, len, i;
6853 char *nodenameA = NULL, *servnameA = NULL;
6854 struct WS_addrinfo *resA, *hintsA = NULL;
6855 WCHAR *local_nodenameW = (WCHAR *)nodename;
6857 TRACE("nodename %s, servname %s, hints %p, result %p\n",
6858 debugstr_w(nodename), debugstr_w(servname), hints, res);
6860 *res = NULL;
6861 if (nodename)
6863 /* Is this an IDN? Most likely if any char is above the Ascii table, this
6864 * is the simplest validation possible, further validation will be done by
6865 * the native getaddrinfo() */
6866 for (i = 0; nodename[i]; i++)
6868 if (nodename[i] > 'z')
6869 break;
6871 if (nodename[i])
6873 if (hints && (hints->ai_flags & WS_AI_DISABLE_IDN_ENCODING))
6875 /* Name requires conversion but it was disabled */
6876 ret = WSAHOST_NOT_FOUND;
6877 WSASetLastError(ret);
6878 goto end;
6881 len = IdnToAscii(0, nodename, -1, NULL, 0);
6882 if (!len)
6884 ERR("Failed to convert %s to punycode\n", debugstr_w(nodename));
6885 ret = EAI_FAIL;
6886 goto end;
6888 if (!(local_nodenameW = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WCHAR)))) goto end;
6889 IdnToAscii(0, nodename, -1, local_nodenameW, len);
6892 if (local_nodenameW)
6894 len = WideCharToMultiByte(CP_ACP, 0, local_nodenameW, -1, NULL, 0, NULL, NULL);
6895 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) goto end;
6896 WideCharToMultiByte(CP_ACP, 0, local_nodenameW, -1, nodenameA, len, NULL, NULL);
6898 if (servname)
6900 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
6901 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len))) goto end;
6902 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
6905 if (hints) hintsA = addrinfo_WtoA(hints);
6906 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
6907 WS_freeaddrinfo(hintsA);
6909 if (!ret)
6911 *res = addrinfo_list_AtoW(resA);
6912 WS_freeaddrinfo(resA);
6915 end:
6916 if (local_nodenameW != nodename)
6917 HeapFree(GetProcessHeap(), 0, local_nodenameW);
6918 HeapFree(GetProcessHeap(), 0, nodenameA);
6919 HeapFree(GetProcessHeap(), 0, servnameA);
6920 return ret;
6923 /***********************************************************************
6924 * FreeAddrInfoW (WS2_32.@)
6926 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
6928 while (ai)
6930 ADDRINFOW *next;
6931 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
6932 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
6933 next = ai->ai_next;
6934 HeapFree(GetProcessHeap(), 0, ai);
6935 ai = next;
6939 /***********************************************************************
6940 * FreeAddrInfoExW (WS2_32.@)
6942 void WINAPI FreeAddrInfoExW(ADDRINFOEXW *ai)
6944 FIXME("%p\n", ai);
6947 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
6948 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
6950 #ifdef HAVE_GETNAMEINFO
6951 int ret;
6952 union generic_unix_sockaddr sa_u;
6953 unsigned int size;
6955 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
6956 serv, servlen, flags);
6958 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
6959 if (!size)
6961 SetLastError(WSAEFAULT);
6962 return WSA_NOT_ENOUGH_MEMORY;
6964 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
6965 return convert_eai_u2w(ret);
6966 #else
6967 FIXME("getnameinfo() failed, not found during buildtime.\n");
6968 return EAI_FAIL;
6969 #endif
6972 int WINAPI GetNameInfoW(const SOCKADDR *sa, WS_socklen_t salen, PWCHAR host,
6973 DWORD hostlen, PWCHAR serv, DWORD servlen, INT flags)
6975 int ret;
6976 char *hostA = NULL, *servA = NULL;
6978 if (host && (!(hostA = HeapAlloc(GetProcessHeap(), 0, hostlen)))) return EAI_MEMORY;
6979 if (serv && (!(servA = HeapAlloc(GetProcessHeap(), 0, servlen))))
6981 HeapFree(GetProcessHeap(), 0, hostA);
6982 return EAI_MEMORY;
6985 ret = WS_getnameinfo(sa, salen, hostA, hostlen, servA, servlen, flags);
6986 if (!ret)
6988 if (host) MultiByteToWideChar(CP_ACP, 0, hostA, -1, host, hostlen);
6989 if (serv) MultiByteToWideChar(CP_ACP, 0, servA, -1, serv, servlen);
6992 HeapFree(GetProcessHeap(), 0, hostA);
6993 HeapFree(GetProcessHeap(), 0, servA);
6994 return ret;
6997 /***********************************************************************
6998 * getservbyport (WS2_32.56)
7000 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
7002 struct WS_servent* retval = NULL;
7003 #ifdef HAVE_GETSERVBYPORT
7004 struct servent* serv;
7005 char *proto_str = NULL;
7007 if (proto && *proto)
7009 if (!(proto_str = strdup_lower(proto))) return NULL;
7011 EnterCriticalSection( &csWSgetXXXbyYYY );
7012 if( (serv = getservbyport(port, proto_str)) != NULL ) {
7013 retval = WS_dup_se(serv);
7015 else SetLastError(WSANO_DATA);
7016 LeaveCriticalSection( &csWSgetXXXbyYYY );
7017 HeapFree( GetProcessHeap(), 0, proto_str );
7018 #endif
7019 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
7020 return retval;
7024 /***********************************************************************
7025 * gethostname (WS2_32.57)
7027 int WINAPI WS_gethostname(char *name, int namelen)
7029 char buf[256];
7030 int len;
7032 TRACE("name %p, len %d\n", name, namelen);
7034 if (!name)
7036 SetLastError(WSAEFAULT);
7037 return SOCKET_ERROR;
7040 if (gethostname(buf, sizeof(buf)) != 0)
7042 SetLastError(wsaErrno());
7043 return SOCKET_ERROR;
7046 TRACE("<- '%s'\n", buf);
7047 len = strlen(buf);
7048 if (len > 15)
7049 WARN("Windows supports NetBIOS name length up to 15 bytes!\n");
7050 if (namelen <= len)
7052 SetLastError(WSAEFAULT);
7053 WARN("<- not enough space for hostname, required %d, got %d!\n", len + 1, namelen);
7054 return SOCKET_ERROR;
7056 strcpy(name, buf);
7057 return 0;
7061 /* ------------------------------------- Windows sockets extensions -- *
7063 * ------------------------------------------------------------------- */
7065 /***********************************************************************
7066 * WSAEnumNetworkEvents (WS2_32.36)
7068 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
7070 int ret;
7071 int i;
7072 int errors[FD_MAX_EVENTS];
7074 TRACE("%04lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
7076 SERVER_START_REQ( get_socket_event )
7078 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
7079 req->service = TRUE;
7080 req->c_event = wine_server_obj_handle( hEvent );
7081 wine_server_set_reply( req, errors, sizeof(errors) );
7082 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
7084 SERVER_END_REQ;
7085 if (!ret)
7087 for (i = 0; i < FD_MAX_EVENTS; i++)
7088 lpEvent->iErrorCode[i] = NtStatusToWSAError(errors[i]);
7089 return 0;
7091 SetLastError(WSAEINVAL);
7092 return SOCKET_ERROR;
7095 /***********************************************************************
7096 * WSAEventSelect (WS2_32.39)
7098 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
7100 int ret;
7102 TRACE("%04lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
7104 SERVER_START_REQ( set_socket_event )
7106 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
7107 req->mask = lEvent;
7108 req->event = wine_server_obj_handle( hEvent );
7109 req->window = 0;
7110 req->msg = 0;
7111 ret = wine_server_call( req );
7113 SERVER_END_REQ;
7114 if (!ret) return 0;
7115 SetLastError(WSAEINVAL);
7116 return SOCKET_ERROR;
7119 /**********************************************************************
7120 * WSAGetOverlappedResult (WS2_32.40)
7122 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
7123 LPDWORD lpcbTransfer, BOOL fWait,
7124 LPDWORD lpdwFlags )
7126 NTSTATUS status;
7128 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
7129 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
7131 if ( lpOverlapped == NULL )
7133 ERR( "Invalid pointer\n" );
7134 SetLastError(WSA_INVALID_PARAMETER);
7135 return FALSE;
7138 status = lpOverlapped->Internal;
7139 if (status == STATUS_PENDING)
7141 if (!fWait)
7143 SetLastError( WSA_IO_INCOMPLETE );
7144 return FALSE;
7147 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
7148 INFINITE ) == WAIT_FAILED)
7149 return FALSE;
7150 status = lpOverlapped->Internal;
7153 if ( lpcbTransfer )
7154 *lpcbTransfer = lpOverlapped->InternalHigh;
7156 if ( lpdwFlags )
7157 *lpdwFlags = lpOverlapped->u.s.Offset;
7159 if (status) SetLastError( RtlNtStatusToDosError(status) );
7160 return !status;
7164 /***********************************************************************
7165 * WSAAsyncSelect (WS2_32.101)
7167 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
7169 int ret;
7171 TRACE("%04lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
7173 SERVER_START_REQ( set_socket_event )
7175 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
7176 req->mask = lEvent;
7177 req->event = 0;
7178 req->window = wine_server_user_handle( hWnd );
7179 req->msg = uMsg;
7180 ret = wine_server_call( req );
7182 SERVER_END_REQ;
7183 if (!ret) return 0;
7184 SetLastError(WSAEINVAL);
7185 return SOCKET_ERROR;
7188 /***********************************************************************
7189 * WSACreateEvent (WS2_32.31)
7192 WSAEVENT WINAPI WSACreateEvent(void)
7194 /* Create a manual-reset event, with initial state: unsignaled */
7195 TRACE("\n");
7197 return CreateEventW(NULL, TRUE, FALSE, NULL);
7200 /***********************************************************************
7201 * WSACloseEvent (WS2_32.29)
7204 BOOL WINAPI WSACloseEvent(WSAEVENT event)
7206 TRACE ("event=%p\n", event);
7208 return CloseHandle(event);
7211 /***********************************************************************
7212 * WSASocketA (WS2_32.78)
7215 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
7216 LPWSAPROTOCOL_INFOA lpProtocolInfo,
7217 GROUP g, DWORD dwFlags)
7219 INT len;
7220 WSAPROTOCOL_INFOW info;
7222 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
7223 af, type, protocol, lpProtocolInfo, g, dwFlags);
7225 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
7227 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
7228 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
7229 info.szProtocol, WSAPROTOCOL_LEN + 1);
7231 if (!len)
7233 SetLastError(WSAEINVAL);
7234 return SOCKET_ERROR;
7237 return WSASocketW(af, type, protocol, &info, g, dwFlags);
7240 /***********************************************************************
7241 * WSASocketW (WS2_32.79)
7244 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
7245 LPWSAPROTOCOL_INFOW lpProtocolInfo,
7246 GROUP g, DWORD dwFlags)
7248 SOCKET ret;
7249 DWORD err;
7250 int unixaf, unixtype, ipxptype = -1;
7253 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
7254 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
7257 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
7258 af, type, protocol, lpProtocolInfo, g, dwFlags );
7260 if (!num_startup)
7262 err = WSANOTINITIALISED;
7263 goto done;
7266 /* hack for WSADuplicateSocket */
7267 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
7268 ret = lpProtocolInfo->dwServiceFlags3;
7269 TRACE("\tgot duplicate %04lx\n", ret);
7270 return ret;
7273 if (lpProtocolInfo)
7275 if (af == FROM_PROTOCOL_INFO || !af)
7276 af = lpProtocolInfo->iAddressFamily;
7277 if (type == FROM_PROTOCOL_INFO || !type)
7278 type = lpProtocolInfo->iSocketType;
7279 if (protocol == FROM_PROTOCOL_INFO || !protocol)
7280 protocol = lpProtocolInfo->iProtocol;
7283 if (!type && (af || protocol))
7285 int autoproto = protocol;
7286 WSAPROTOCOL_INFOW infow;
7288 /* default to the first valid protocol */
7289 if (!autoproto)
7290 autoproto = valid_protocols[0];
7291 else if(IS_IPX_PROTO(autoproto))
7292 autoproto = WS_NSPROTO_IPX;
7294 if (WS_EnterSingleProtocolW(autoproto, &infow))
7296 type = infow.iSocketType;
7298 /* after win2003 it's no longer possible to pass AF_UNSPEC
7299 using the protocol info struct */
7300 if (!lpProtocolInfo && af == WS_AF_UNSPEC)
7301 af = infow.iAddressFamily;
7306 Windows has an extension to the IPX protocol that allows one to create sockets
7307 and set the IPX packet type at the same time, to do that a caller will use
7308 a protocol like NSPROTO_IPX + <PACKET TYPE>
7310 if (IS_IPX_PROTO(protocol))
7311 ipxptype = protocol - WS_NSPROTO_IPX;
7313 /* convert the socket family, type and protocol */
7314 unixaf = convert_af_w2u(af);
7315 unixtype = convert_socktype_w2u(type);
7316 protocol = convert_proto_w2u(protocol);
7317 if (unixaf == AF_UNSPEC) unixaf = -1;
7319 /* filter invalid parameters */
7320 if (protocol < 0)
7322 /* the type could not be converted */
7323 if (type && unixtype < 0)
7325 err = WSAESOCKTNOSUPPORT;
7326 goto done;
7329 err = WSAEPROTONOSUPPORT;
7330 goto done;
7332 if (unixaf < 0)
7334 /* both family and protocol can't be invalid */
7335 if (protocol <= 0)
7337 err = WSAEINVAL;
7338 goto done;
7341 /* family could not be converted and neither socket type */
7342 if (unixtype < 0 && af >= 0)
7345 err = WSAESOCKTNOSUPPORT;
7346 goto done;
7349 err = WSAEAFNOSUPPORT;
7350 goto done;
7353 SERVER_START_REQ( create_socket )
7355 req->family = unixaf;
7356 req->type = unixtype;
7357 req->protocol = protocol;
7358 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
7359 req->attributes = (dwFlags & WSA_FLAG_NO_HANDLE_INHERIT) ? 0 : OBJ_INHERIT;
7360 req->flags = dwFlags & ~WSA_FLAG_NO_HANDLE_INHERIT;
7361 set_error( wine_server_call( req ) );
7362 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
7364 SERVER_END_REQ;
7365 if (ret)
7367 TRACE("\tcreated %04lx\n", ret );
7368 if (ipxptype > 0)
7369 set_ipx_packettype(ret, ipxptype);
7371 /* ensure IP_DONTFRAGMENT is disabled, in Linux the global default can be enabled */
7372 if (unixaf == AF_INET || unixaf == AF_INET6)
7373 set_dont_fragment(ret, unixaf == AF_INET6 ? IPPROTO_IPV6 : IPPROTO_IP, FALSE);
7375 #ifdef IPV6_V6ONLY
7376 if (unixaf == AF_INET6)
7378 int fd = get_sock_fd(ret, 0, NULL);
7379 if (fd != -1)
7381 /* IPV6_V6ONLY is set by default on Windows */
7382 int enable = 1;
7383 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)))
7384 WARN("\tsetting IPV6_V6ONLY failed - errno = %i\n", errno);
7385 release_sock_fd(ret, fd);
7388 #endif
7389 return ret;
7392 err = GetLastError();
7393 if (err == WSAEACCES) /* raw socket denied */
7395 if (type == SOCK_RAW)
7396 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
7397 else
7398 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
7400 else
7402 /* invalid combination of valid parameters, like SOCK_STREAM + IPPROTO_UDP */
7403 if (err == WSAEINVAL)
7404 err = WSAESOCKTNOSUPPORT;
7405 else if (err == WSAEOPNOTSUPP)
7406 err = WSAEPROTONOSUPPORT;
7409 done:
7410 WARN("\t\tfailed, error %d!\n", err);
7411 SetLastError(err);
7412 return INVALID_SOCKET;
7415 /***********************************************************************
7416 * WSAJoinLeaf (WS2_32.58)
7419 SOCKET WINAPI WSAJoinLeaf(
7420 SOCKET s,
7421 const struct WS_sockaddr *addr,
7422 int addrlen,
7423 LPWSABUF lpCallerData,
7424 LPWSABUF lpCalleeData,
7425 LPQOS lpSQOS,
7426 LPQOS lpGQOS,
7427 DWORD dwFlags)
7429 FIXME("stub.\n");
7430 return INVALID_SOCKET;
7433 /***********************************************************************
7434 * __WSAFDIsSet (WS2_32.151)
7436 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
7438 int i = set->fd_count, ret = 0;
7440 while (i--)
7441 if (set->fd_array[i] == s)
7443 ret = 1;
7444 break;
7447 TRACE("(socket %04lx, fd_set %p, count %i) <- %d\n", s, set, set->fd_count, ret);
7448 return ret;
7451 /***********************************************************************
7452 * WSAIsBlocking (WS2_32.114)
7454 BOOL WINAPI WSAIsBlocking(void)
7456 /* By default WinSock should set all its sockets to non-blocking mode
7457 * and poll in PeekMessage loop when processing "blocking" ones. This
7458 * function is supposed to tell if the program is in this loop. Our
7459 * blocking calls are truly blocking so we always return FALSE.
7461 * Note: It is allowed to call this function without prior WSAStartup().
7464 TRACE("\n");
7465 return FALSE;
7468 /***********************************************************************
7469 * WSACancelBlockingCall (WS2_32.113)
7471 INT WINAPI WSACancelBlockingCall(void)
7473 TRACE("\n");
7474 return 0;
7477 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
7479 FIXME("How was this called?\n");
7480 return x();
7484 /***********************************************************************
7485 * WSASetBlockingHook (WS2_32.109)
7487 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
7489 FARPROC prev = blocking_hook;
7490 blocking_hook = lpBlockFunc;
7491 TRACE("hook %p\n", lpBlockFunc);
7492 return prev;
7496 /***********************************************************************
7497 * WSAUnhookBlockingHook (WS2_32.110)
7499 INT WINAPI WSAUnhookBlockingHook(void)
7501 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
7502 return 0;
7506 /* ----------------------------------- end of API stuff */
7508 /* ----------------------------------- helper functions -
7510 * TODO: Merge WS_dup_..() stuff into one function that
7511 * would operate with a generic structure containing internal
7512 * pointers (via a template of some kind).
7515 static int list_size(char** l, int item_size)
7517 int i,j = 0;
7518 if(l)
7519 { for(i=0;l[i];i++)
7520 j += (item_size) ? item_size : strlen(l[i]) + 1;
7521 j += (i + 1) * sizeof(char*); }
7522 return j;
7525 static int list_dup(char** l_src, char** l_to, int item_size)
7527 char *p;
7528 int i;
7530 for (i = 0; l_src[i]; i++) ;
7531 p = (char *)(l_to + i + 1);
7532 for (i = 0; l_src[i]; i++)
7534 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
7535 memcpy(p, l_src[i], count);
7536 l_to[i] = p;
7537 p += count;
7539 l_to[i] = NULL;
7540 return p - (char *)l_to;
7543 /* ----- hostent */
7545 /* create a hostent entry
7547 * Creates the entry with enough memory for the name, aliases
7548 * addresses, and the address pointers. Also copies the name
7549 * and sets up all the pointers.
7551 * NOTE: The alias and address lists must be allocated with room
7552 * for the NULL item terminating the list. This is true even if
7553 * the list has no items ("aliases" and "addresses" must be
7554 * at least "1", a truly empty list is invalid).
7556 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length)
7558 struct WS_hostent *p_to;
7559 char *p;
7560 int size = (sizeof(struct WS_hostent) +
7561 strlen(name) + 1 +
7562 sizeof(char *) * aliases +
7563 aliases_size +
7564 sizeof(char *) * addresses +
7565 address_length * (addresses - 1)), i;
7567 if (!(p_to = check_buffer_he(size))) return NULL;
7568 memset(p_to, 0, size);
7570 /* Use the memory in the same way winsock does.
7571 * First set the pointer for aliases, second set the pointers for addresses.
7572 * Third fill the addresses indexes, fourth jump aliases names size.
7573 * Fifth fill the hostname.
7574 * NOTE: This method is valid for OS version's >= XP.
7576 p = (char *)(p_to + 1);
7577 p_to->h_aliases = (char **)p;
7578 p += sizeof(char *)*aliases;
7580 p_to->h_addr_list = (char **)p;
7581 p += sizeof(char *)*addresses;
7583 for (i = 0, addresses--; i < addresses; i++, p += address_length)
7584 p_to->h_addr_list[i] = p;
7586 /* NOTE: h_aliases must be filled in manually because we don't know each string
7587 * size, leave these pointers NULL (already set to NULL by memset earlier).
7589 p += aliases_size;
7591 p_to->h_name = p;
7592 strcpy(p, name);
7594 return p_to;
7597 /* duplicate hostent entry
7598 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
7599 * Ditto for protoent and servent.
7601 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
7603 int i, addresses = 0, alias_size = 0;
7604 struct WS_hostent *p_to;
7605 char *p;
7607 for( i = 0; p_he->h_aliases[i]; i++) alias_size += strlen(p_he->h_aliases[i]) + 1;
7608 while (p_he->h_addr_list[addresses]) addresses++;
7610 p_to = WS_create_he(p_he->h_name, i + 1, alias_size, addresses + 1, p_he->h_length);
7612 if (!p_to) return NULL;
7613 p_to->h_addrtype = convert_af_u2w(p_he->h_addrtype);
7614 p_to->h_length = p_he->h_length;
7616 for(i = 0, p = p_to->h_addr_list[0]; p_he->h_addr_list[i]; i++, p += p_to->h_length)
7617 memcpy(p, p_he->h_addr_list[i], p_to->h_length);
7619 /* Fill the aliases after the IP data */
7620 for(i = 0; p_he->h_aliases[i]; i++)
7622 p_to->h_aliases[i] = p;
7623 strcpy(p, p_he->h_aliases[i]);
7624 p += strlen(p) + 1;
7627 return p_to;
7630 /* ----- protoent */
7632 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
7634 char *p;
7635 struct WS_protoent *p_to;
7637 int size = (sizeof(*p_pe) +
7638 strlen(p_pe->p_name) + 1 +
7639 list_size(p_pe->p_aliases, 0));
7641 if (!(p_to = check_buffer_pe(size))) return NULL;
7642 p_to->p_proto = p_pe->p_proto;
7644 p = (char *)(p_to + 1);
7645 p_to->p_name = p;
7646 strcpy(p, p_pe->p_name);
7647 p += strlen(p) + 1;
7649 p_to->p_aliases = (char **)p;
7650 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
7651 return p_to;
7654 /* ----- servent */
7656 static struct WS_servent *WS_dup_se(const struct servent* p_se)
7658 char *p;
7659 struct WS_servent *p_to;
7661 int size = (sizeof(*p_se) +
7662 strlen(p_se->s_proto) + 1 +
7663 strlen(p_se->s_name) + 1 +
7664 list_size(p_se->s_aliases, 0));
7666 if (!(p_to = check_buffer_se(size))) return NULL;
7667 p_to->s_port = p_se->s_port;
7669 p = (char *)(p_to + 1);
7670 p_to->s_name = p;
7671 strcpy(p, p_se->s_name);
7672 p += strlen(p) + 1;
7674 p_to->s_proto = p;
7675 strcpy(p, p_se->s_proto);
7676 p += strlen(p) + 1;
7678 p_to->s_aliases = (char **)p;
7679 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
7680 return p_to;
7684 /***********************************************************************
7685 * WSARecv (WS2_32.67)
7687 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
7688 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
7689 LPWSAOVERLAPPED lpOverlapped,
7690 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
7692 return WS2_recv_base(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
7693 NULL, NULL, lpOverlapped, lpCompletionRoutine, NULL);
7696 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
7697 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
7698 struct WS_sockaddr *lpFrom,
7699 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
7700 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
7701 LPWSABUF lpControlBuffer )
7703 unsigned int i, options;
7704 int n, fd, err, overlapped, flags;
7705 struct ws2_async *wsa = NULL, localwsa;
7706 BOOL is_blocking;
7707 DWORD timeout_start = GetTickCount();
7708 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
7710 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
7711 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
7712 (lpFromlen ? *lpFromlen : -1),
7713 lpOverlapped, lpCompletionRoutine);
7715 fd = get_sock_fd( s, FILE_READ_DATA, &options );
7716 TRACE( "fd=%d, options=%x\n", fd, options );
7718 if (fd == -1) return SOCKET_ERROR;
7720 if (*lpFlags & WS_MSG_OOB)
7722 /* It's invalid to receive OOB data from an OOBINLINED socket
7723 * as OOB data is turned into normal data. */
7724 socklen_t len = sizeof(n);
7725 if (!getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, (char*) &n, &len) && n)
7727 err = WSAEINVAL;
7728 goto error;
7732 overlapped = (lpOverlapped || lpCompletionRoutine) &&
7733 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
7734 if (overlapped || dwBufferCount > 1)
7736 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[dwBufferCount]),
7737 WS2_async_recv )))
7739 err = WSAEFAULT;
7740 goto error;
7743 else
7744 wsa = &localwsa;
7746 wsa->hSocket = SOCKET2HANDLE(s);
7747 wsa->flags = *lpFlags;
7748 wsa->lpFlags = lpFlags;
7749 wsa->addr = lpFrom;
7750 wsa->addrlen.ptr = lpFromlen;
7751 wsa->control = lpControlBuffer;
7752 wsa->n_iovecs = dwBufferCount;
7753 wsa->first_iovec = 0;
7754 for (i = 0; i < dwBufferCount; i++)
7756 /* check buffer first to trigger write watches */
7757 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
7759 err = WSAEFAULT;
7760 goto error;
7762 wsa->iovec[i].iov_base = lpBuffers[i].buf;
7763 wsa->iovec[i].iov_len = lpBuffers[i].len;
7766 flags = convert_flags(wsa->flags);
7767 for (;;)
7769 n = WS2_recv( fd, wsa, flags );
7770 if (n == -1)
7772 /* Unix-like systems return EINVAL when attempting to read OOB data from
7773 * an empty socket buffer, convert that to a Windows expected return. */
7774 if ((flags & MSG_OOB) && errno == EINVAL)
7775 errno = EWOULDBLOCK;
7777 if (errno != EAGAIN)
7779 err = wsaErrno();
7780 goto error;
7783 else if (lpNumberOfBytesRecvd) *lpNumberOfBytesRecvd = n;
7785 if (overlapped)
7787 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
7789 wsa->user_overlapped = lpOverlapped;
7790 wsa->completion_func = lpCompletionRoutine;
7791 release_sock_fd( s, fd );
7793 if (n == -1)
7795 iosb->u.Status = STATUS_PENDING;
7796 iosb->Information = 0;
7798 if (wsa->completion_func)
7799 err = register_async( ASYNC_TYPE_READ, wsa->hSocket, &wsa->io, NULL,
7800 ws2_async_apc, wsa, iosb );
7801 else
7802 err = register_async( ASYNC_TYPE_READ, wsa->hSocket, &wsa->io, lpOverlapped->hEvent,
7803 NULL, (void *)cvalue, iosb );
7805 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
7806 SetLastError(NtStatusToWSAError( err ));
7807 return SOCKET_ERROR;
7810 iosb->u.Status = STATUS_SUCCESS;
7811 iosb->Information = n;
7812 if (!wsa->completion_func)
7814 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
7815 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
7816 HeapFree( GetProcessHeap(), 0, wsa );
7818 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
7819 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
7820 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7821 return 0;
7824 if (n != -1) break;
7826 if ((err = _is_blocking( s, &is_blocking )))
7828 err = NtStatusToWSAError( err );
7829 goto error;
7832 if ( is_blocking )
7834 struct pollfd pfd;
7835 int poll_timeout = -1;
7836 INT64 timeout = get_rcvsnd_timeo(fd, TRUE);
7838 if (timeout)
7840 timeout -= GetTickCount() - timeout_start;
7841 if (timeout < 0) poll_timeout = 0;
7842 else poll_timeout = timeout <= INT_MAX ? timeout : INT_MAX;
7845 pfd.fd = fd;
7846 pfd.events = POLLIN;
7847 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
7849 if (!poll_timeout || !poll( &pfd, 1, poll_timeout ))
7851 err = WSAETIMEDOUT;
7852 /* a timeout is not fatal */
7853 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7854 goto error;
7857 else
7859 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7860 err = WSAEWOULDBLOCK;
7861 goto error;
7865 TRACE(" -> %i bytes\n", n);
7866 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
7867 release_sock_fd( s, fd );
7868 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7869 SetLastError(ERROR_SUCCESS);
7871 return 0;
7873 error:
7874 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
7875 release_sock_fd( s, fd );
7876 WARN(" -> ERROR %d\n", err);
7877 SetLastError( err );
7878 return SOCKET_ERROR;
7881 /***********************************************************************
7882 * WSARecvFrom (WS2_32.69)
7884 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
7885 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
7886 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
7887 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
7890 return WS2_recv_base( s, lpBuffers, dwBufferCount,
7891 lpNumberOfBytesRecvd, lpFlags,
7892 lpFrom, lpFromlen,
7893 lpOverlapped, lpCompletionRoutine, NULL );
7896 /***********************************************************************
7897 * WSCInstallProvider (WS2_32.88)
7899 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
7900 LPCWSTR lpszProviderDllPath,
7901 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
7902 DWORD dwNumberOfEntries,
7903 LPINT lpErrno )
7905 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
7906 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
7907 dwNumberOfEntries, lpErrno);
7908 *lpErrno = 0;
7909 return 0;
7913 /***********************************************************************
7914 * WSCDeinstallProvider (WS2_32.83)
7916 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
7918 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
7919 *lpErrno = 0;
7920 return 0;
7924 /***********************************************************************
7925 * WSAAccept (WS2_32.26)
7927 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
7928 LPCONDITIONPROC lpfnCondition, DWORD_PTR dwCallbackData)
7931 int ret = 0, size;
7932 WSABUF CallerId, CallerData, CalleeId, CalleeData;
7933 /* QOS SQOS, GQOS; */
7934 GROUP g;
7935 SOCKET cs;
7936 SOCKADDR src_addr, dst_addr;
7938 TRACE("socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
7939 s, addr, addrlen, lpfnCondition, dwCallbackData);
7941 cs = WS_accept(s, addr, addrlen);
7942 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
7943 if (!lpfnCondition) return cs;
7945 if (addr && addrlen)
7947 CallerId.buf = (char *)addr;
7948 CallerId.len = *addrlen;
7950 else
7952 size = sizeof(src_addr);
7953 WS_getpeername(cs, &src_addr, &size);
7954 CallerId.buf = (char *)&src_addr;
7955 CallerId.len = size;
7957 CallerData.buf = NULL;
7958 CallerData.len = 0;
7960 size = sizeof(dst_addr);
7961 WS_getsockname(cs, &dst_addr, &size);
7963 CalleeId.buf = (char *)&dst_addr;
7964 CalleeId.len = sizeof(dst_addr);
7966 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
7967 &CalleeId, &CalleeData, &g, dwCallbackData);
7969 switch (ret)
7971 case CF_ACCEPT:
7972 return cs;
7973 case CF_DEFER:
7974 SERVER_START_REQ( set_socket_deferred )
7976 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
7977 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
7978 if ( !wine_server_call_err ( req ) )
7980 SetLastError( WSATRY_AGAIN );
7981 WS_closesocket( cs );
7984 SERVER_END_REQ;
7985 return SOCKET_ERROR;
7986 case CF_REJECT:
7987 WS_closesocket(cs);
7988 SetLastError(WSAECONNREFUSED);
7989 return SOCKET_ERROR;
7990 default:
7991 FIXME("Unknown return type from Condition function\n");
7992 SetLastError(WSAENOTSOCK);
7993 return SOCKET_ERROR;
7997 /***********************************************************************
7998 * WSADuplicateSocketA (WS2_32.32)
8000 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
8002 return WS_DuplicateSocket(FALSE, s, dwProcessId, (LPWSAPROTOCOL_INFOW) lpProtocolInfo);
8005 /***********************************************************************
8006 * WSADuplicateSocketW (WS2_32.33)
8008 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
8010 return WS_DuplicateSocket(TRUE, s, dwProcessId, lpProtocolInfo);
8013 /***********************************************************************
8014 * WSAInstallServiceClassA (WS2_32.48)
8016 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
8018 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
8019 SetLastError(WSAEACCES);
8020 return SOCKET_ERROR;
8023 /***********************************************************************
8024 * WSAInstallServiceClassW (WS2_32.49)
8026 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
8028 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
8029 SetLastError(WSAEACCES);
8030 return SOCKET_ERROR;
8033 /***********************************************************************
8034 * WSARemoveServiceClass (WS2_32.70)
8036 int WINAPI WSARemoveServiceClass(LPGUID info)
8038 FIXME("Request to remove service %s\n", debugstr_guid(info));
8039 SetLastError(WSATYPE_NOT_FOUND);
8040 return SOCKET_ERROR;
8043 /***********************************************************************
8044 * inet_ntop (WS2_32.@)
8046 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
8048 #ifdef HAVE_INET_NTOP
8049 struct WS_in6_addr *in6;
8050 struct WS_in_addr *in;
8051 PCSTR pdst;
8053 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
8054 if (!buffer)
8056 SetLastError( STATUS_INVALID_PARAMETER );
8057 return NULL;
8060 switch (family)
8062 case WS_AF_INET:
8064 in = addr;
8065 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
8066 break;
8068 case WS_AF_INET6:
8070 in6 = addr;
8071 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
8072 break;
8074 default:
8075 SetLastError( WSAEAFNOSUPPORT );
8076 return NULL;
8079 if (!pdst) SetLastError( STATUS_INVALID_PARAMETER );
8080 return pdst;
8081 #else
8082 FIXME( "not supported on this platform\n" );
8083 SetLastError( WSAEAFNOSUPPORT );
8084 return NULL;
8085 #endif
8088 /***********************************************************************
8089 * inet_pton (WS2_32.@)
8091 INT WINAPI WS_inet_pton( INT family, PCSTR addr, PVOID buffer)
8093 #ifdef HAVE_INET_PTON
8094 int unixaf, ret;
8096 TRACE("family %d, addr %s, buffer (%p)\n", family, debugstr_a(addr), buffer);
8098 if (!addr || !buffer)
8100 SetLastError(WSAEFAULT);
8101 return SOCKET_ERROR;
8104 unixaf = convert_af_w2u(family);
8105 if (unixaf != AF_INET && unixaf != AF_INET6)
8107 SetLastError(WSAEAFNOSUPPORT);
8108 return SOCKET_ERROR;
8111 ret = inet_pton(unixaf, addr, buffer);
8112 if (ret == -1) SetLastError(wsaErrno());
8113 return ret;
8114 #else
8115 FIXME( "not supported on this platform\n" );
8116 SetLastError( WSAEAFNOSUPPORT );
8117 return SOCKET_ERROR;
8118 #endif
8121 /***********************************************************************
8122 * InetPtonW (WS2_32.@)
8124 INT WINAPI InetPtonW(INT family, PCWSTR addr, PVOID buffer)
8126 char *addrA;
8127 int len;
8128 INT ret;
8130 TRACE("family %d, addr %s, buffer (%p)\n", family, debugstr_w(addr), buffer);
8132 if (!addr)
8134 SetLastError(WSAEFAULT);
8135 return SOCKET_ERROR;
8138 len = WideCharToMultiByte(CP_ACP, 0, addr, -1, NULL, 0, NULL, NULL);
8139 if (!(addrA = HeapAlloc(GetProcessHeap(), 0, len)))
8141 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8142 return SOCKET_ERROR;
8144 WideCharToMultiByte(CP_ACP, 0, addr, -1, addrA, len, NULL, NULL);
8146 ret = WS_inet_pton(family, addrA, buffer);
8148 HeapFree(GetProcessHeap(), 0, addrA);
8149 return ret;
8152 /***********************************************************************
8153 * InetNtopW (WS2_32.@)
8155 PCWSTR WINAPI InetNtopW(INT family, PVOID addr, PWSTR buffer, SIZE_T len)
8157 char bufferA[WS_INET6_ADDRSTRLEN];
8158 PWSTR ret = NULL;
8160 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
8162 if (WS_inet_ntop(family, addr, bufferA, sizeof(bufferA)))
8164 if (MultiByteToWideChar(CP_ACP, 0, bufferA, -1, buffer, len))
8165 ret = buffer;
8166 else
8167 SetLastError(ERROR_INVALID_PARAMETER);
8169 return ret;
8172 /***********************************************************************
8173 * WSAStringToAddressA (WS2_32.80)
8175 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
8176 INT AddressFamily,
8177 LPWSAPROTOCOL_INFOA lpProtocolInfo,
8178 LPSOCKADDR lpAddress,
8179 LPINT lpAddressLength)
8181 INT res=0;
8182 LPSTR workBuffer=NULL,ptrPort;
8184 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
8185 lpProtocolInfo, lpAddress, lpAddressLength );
8187 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
8189 if (!AddressString)
8191 SetLastError(WSAEINVAL);
8192 return SOCKET_ERROR;
8195 if (lpProtocolInfo)
8196 FIXME("ProtocolInfo not implemented.\n");
8198 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
8199 strlen(AddressString) + 1);
8200 if (!workBuffer)
8202 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8203 return SOCKET_ERROR;
8206 strcpy(workBuffer, AddressString);
8208 switch(AddressFamily)
8210 case WS_AF_INET:
8212 struct in_addr inetaddr;
8214 /* If lpAddressLength is too small, tell caller the size we need */
8215 if (*lpAddressLength < sizeof(SOCKADDR_IN))
8217 *lpAddressLength = sizeof(SOCKADDR_IN);
8218 res = WSAEFAULT;
8219 break;
8221 *lpAddressLength = sizeof(SOCKADDR_IN);
8222 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
8224 ((LPSOCKADDR_IN)lpAddress)->sin_family = WS_AF_INET;
8226 ptrPort = strchr(workBuffer, ':');
8227 if(ptrPort)
8229 /* User may have entered an IPv6 and asked to parse as IPv4 */
8230 if(strchr(ptrPort + 1, ':'))
8232 res = WSAEINVAL;
8233 break;
8235 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
8236 *ptrPort = '\0';
8239 if(inet_aton(workBuffer, &inetaddr) > 0)
8241 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
8242 res = 0;
8244 else
8245 res = WSAEINVAL;
8247 break;
8249 case WS_AF_INET6:
8251 struct in6_addr inetaddr;
8252 char *ptrAddr = workBuffer;
8254 /* If lpAddressLength is too small, tell caller the size we need */
8255 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
8257 *lpAddressLength = sizeof(SOCKADDR_IN6);
8258 res = WSAEFAULT;
8259 break;
8261 #ifdef HAVE_INET_PTON
8262 *lpAddressLength = sizeof(SOCKADDR_IN6);
8263 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
8265 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
8267 /* Valid IPv6 addresses can also be surrounded by [ ], and in this case
8268 * a port number may follow after like in [fd12:3456:7890::1]:12345
8269 * We need to cut the brackets and find the port if any. */
8271 if(*workBuffer == '[')
8273 ptrPort = strchr(workBuffer, ']');
8274 if (!ptrPort)
8276 SetLastError(WSAEINVAL);
8277 return SOCKET_ERROR;
8280 if (ptrPort[1] == ':')
8281 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort + 2));
8283 *ptrPort = '\0';
8284 ptrAddr = workBuffer + 1;
8287 if(inet_pton(AF_INET6, ptrAddr, &inetaddr) > 0)
8289 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
8290 sizeof(struct in6_addr));
8291 res = 0;
8293 else
8294 #endif /* HAVE_INET_PTON */
8295 res = WSAEINVAL;
8297 break;
8299 default:
8300 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
8301 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
8302 res = WSAEINVAL;
8305 HeapFree(GetProcessHeap(), 0, workBuffer);
8307 if (!res) return 0;
8308 SetLastError(res);
8309 return SOCKET_ERROR;
8312 /***********************************************************************
8313 * WSAStringToAddressW (WS2_32.81)
8315 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
8316 * If this should be the case, it would be required to map these digits
8317 * to Unicode digits (0-9) using FoldString first.
8319 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
8320 INT AddressFamily,
8321 LPWSAPROTOCOL_INFOW lpProtocolInfo,
8322 LPSOCKADDR lpAddress,
8323 LPINT lpAddressLength)
8325 INT sBuffer,res=0;
8326 LPSTR workBuffer=NULL;
8327 WSAPROTOCOL_INFOA infoA;
8328 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
8330 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
8331 lpAddress, lpAddressLength );
8333 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
8335 /* if ProtocolInfo is available - convert to ANSI variant */
8336 if (lpProtocolInfo)
8338 lpProtoInfoA = &infoA;
8339 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
8341 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
8342 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
8344 SetLastError(WSAEINVAL);
8345 return SOCKET_ERROR;
8349 if (AddressString)
8351 /* Translate AddressString to ANSI code page - assumes that only
8352 standard digits 0-9 are used with this API call */
8353 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
8354 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
8356 if (workBuffer)
8358 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
8359 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
8360 lpAddress,lpAddressLength);
8361 HeapFree( GetProcessHeap(), 0, workBuffer );
8362 return res;
8364 else
8365 res = WSA_NOT_ENOUGH_MEMORY;
8367 else
8368 res = WSAEINVAL;
8370 SetLastError(res);
8371 return SOCKET_ERROR;
8374 /***********************************************************************
8375 * WSAAddressToStringA (WS2_32.27)
8377 * See WSAAddressToStringW
8379 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
8380 LPWSAPROTOCOL_INFOA info, LPSTR string,
8381 LPDWORD lenstr )
8383 DWORD size;
8384 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
8385 CHAR *p;
8387 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
8389 if (!sockaddr) return SOCKET_ERROR;
8390 if (!string || !lenstr) return SOCKET_ERROR;
8392 switch(sockaddr->sa_family)
8394 case WS_AF_INET:
8396 unsigned int long_ip = ntohl(((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr);
8397 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
8398 sprintf( buffer, "%u.%u.%u.%u:%u",
8399 (long_ip >> 24) & 0xff,
8400 (long_ip >> 16) & 0xff,
8401 (long_ip >> 8) & 0xff,
8402 long_ip & 0xff,
8403 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
8405 p = strchr( buffer, ':' );
8406 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
8407 break;
8409 case WS_AF_INET6:
8411 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
8412 size_t slen;
8414 buffer[0] = 0;
8415 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
8416 if ((sockaddr6->sin6_port))
8417 strcpy(buffer, "[");
8418 slen = strlen(buffer);
8419 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, &buffer[slen], sizeof(buffer) - slen))
8421 SetLastError(WSAEINVAL);
8422 return SOCKET_ERROR;
8424 if ((sockaddr6->sin6_scope_id))
8425 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
8426 if ((sockaddr6->sin6_port))
8427 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
8428 break;
8431 default:
8432 SetLastError(WSAEINVAL);
8433 return SOCKET_ERROR;
8436 size = strlen( buffer ) + 1;
8438 if (*lenstr < size)
8440 *lenstr = size;
8441 SetLastError(WSAEFAULT);
8442 return SOCKET_ERROR;
8445 TRACE("=> %s,%u bytes\n", debugstr_a(buffer), size);
8446 *lenstr = size;
8447 strcpy( string, buffer );
8448 return 0;
8451 /***********************************************************************
8452 * WSAAddressToStringW (WS2_32.28)
8454 * Convert a sockaddr address into a readable address string.
8456 * PARAMS
8457 * sockaddr [I] Pointer to a sockaddr structure.
8458 * len [I] Size of the sockaddr structure.
8459 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
8460 * string [I/O] Pointer to a buffer to receive the address string.
8461 * lenstr [I/O] Size of the receive buffer in WCHARs.
8463 * RETURNS
8464 * Success: 0
8465 * Failure: SOCKET_ERROR
8467 * NOTES
8468 * The 'info' parameter is ignored.
8470 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
8471 LPWSAPROTOCOL_INFOW info, LPWSTR string,
8472 LPDWORD lenstr )
8474 INT ret;
8475 DWORD size;
8476 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
8477 CHAR bufAddr[54];
8479 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
8481 size = *lenstr;
8482 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
8484 if (ret) return ret;
8486 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
8488 if (*lenstr < size)
8490 *lenstr = size;
8491 SetLastError(WSAEFAULT);
8492 return SOCKET_ERROR;
8495 TRACE("=> %s,%u bytes\n", debugstr_w(buffer), size);
8496 *lenstr = size;
8497 lstrcpyW( string, buffer );
8498 return 0;
8501 /***********************************************************************
8502 * WSAEnumNameSpaceProvidersA (WS2_32.34)
8504 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
8506 FIXME( "(%p %p) Stub!\n", len, buffer );
8507 return 0;
8510 /***********************************************************************
8511 * WSAEnumNameSpaceProvidersW (WS2_32.35)
8513 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
8515 FIXME( "(%p %p) Stub!\n", len, buffer );
8516 return 0;
8519 /***********************************************************************
8520 * WSAGetQOSByName (WS2_32.41)
8522 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
8524 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
8525 return FALSE;
8528 /***********************************************************************
8529 * WSAGetServiceClassInfoA (WS2_32.42)
8531 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
8532 LPWSASERVICECLASSINFOA info )
8534 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
8535 len, info );
8536 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8537 return SOCKET_ERROR;
8540 /***********************************************************************
8541 * WSAGetServiceClassInfoW (WS2_32.43)
8543 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
8544 LPWSASERVICECLASSINFOW info )
8546 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
8547 len, info );
8548 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8549 return SOCKET_ERROR;
8552 /***********************************************************************
8553 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
8555 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
8557 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
8558 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8559 return SOCKET_ERROR;
8562 /***********************************************************************
8563 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
8565 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
8567 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
8568 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8569 return SOCKET_ERROR;
8572 /***********************************************************************
8573 * WSALookupServiceBeginA (WS2_32.59)
8575 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
8576 DWORD dwControlFlags,
8577 LPHANDLE lphLookup)
8579 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
8580 lphLookup);
8581 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8582 return SOCKET_ERROR;
8585 /***********************************************************************
8586 * WSALookupServiceBeginW (WS2_32.60)
8588 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
8589 DWORD dwControlFlags,
8590 LPHANDLE lphLookup)
8592 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
8593 lphLookup);
8594 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8595 return SOCKET_ERROR;
8598 /***********************************************************************
8599 * WSALookupServiceEnd (WS2_32.61)
8601 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
8603 FIXME("(%p) Stub!\n", lookup );
8604 return 0;
8607 /***********************************************************************
8608 * WSALookupServiceNextA (WS2_32.62)
8610 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
8612 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
8613 SetLastError(WSA_E_NO_MORE);
8614 return SOCKET_ERROR;
8617 /***********************************************************************
8618 * WSALookupServiceNextW (WS2_32.63)
8620 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
8622 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
8623 SetLastError(WSA_E_NO_MORE);
8624 return SOCKET_ERROR;
8627 /***********************************************************************
8628 * WSANtohl (WS2_32.64)
8630 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
8632 TRACE( "(%04lx 0x%08x %p)\n", s, netlong, lphostlong );
8634 if (!lphostlong) return WSAEFAULT;
8636 *lphostlong = ntohl( netlong );
8637 return 0;
8640 /***********************************************************************
8641 * WSANtohs (WS2_32.65)
8643 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
8645 TRACE( "(%04lx 0x%08x %p)\n", s, netshort, lphostshort );
8647 if (!lphostshort) return WSAEFAULT;
8649 *lphostshort = ntohs( netshort );
8650 return 0;
8653 /***********************************************************************
8654 * WSAProviderConfigChange (WS2_32.66)
8656 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
8657 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
8659 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
8660 return SOCKET_ERROR;
8663 /***********************************************************************
8664 * WSARecvDisconnect (WS2_32.68)
8666 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
8668 TRACE( "(%04lx %p)\n", s, disconnectdata );
8670 return WS_shutdown( s, SD_RECEIVE );
8673 /***********************************************************************
8674 * WSASetServiceA (WS2_32.76)
8676 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
8678 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
8679 return 0;
8682 /***********************************************************************
8683 * WSASetServiceW (WS2_32.77)
8685 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
8687 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
8688 return 0;
8691 /***********************************************************************
8692 * WSCEnableNSProvider (WS2_32.84)
8694 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
8696 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
8697 return 0;
8700 /***********************************************************************
8701 * WSCGetProviderPath (WS2_32.86)
8703 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
8705 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
8707 if (!errcode || !provider || !len) return WSAEFAULT;
8709 *errcode = WSAEINVAL;
8710 return SOCKET_ERROR;
8713 /***********************************************************************
8714 * WSCInstallNameSpace (WS2_32.87)
8716 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
8717 DWORD version, LPGUID provider )
8719 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
8720 namespace, version, debugstr_guid(provider) );
8721 return 0;
8724 /***********************************************************************
8725 * WSCUnInstallNameSpace (WS2_32.89)
8727 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
8729 FIXME("(%s) Stub!\n", debugstr_guid(lpProviderId));
8730 return NO_ERROR;
8733 /***********************************************************************
8734 * WSCWriteProviderOrder (WS2_32.91)
8736 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
8738 FIXME("(%p 0x%08x) Stub!\n", entry, number);
8739 return 0;
8742 /***********************************************************************
8743 * WSANSPIoctl (WS2_32.91)
8745 INT WINAPI WSANSPIoctl( HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer,
8746 DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer,
8747 LPDWORD lpcbBytesReturned, LPWSACOMPLETION lpCompletion )
8749 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup, dwControlCode,
8750 lpvInBuffer, cbInBuffer, lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpCompletion);
8751 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8752 return SOCKET_ERROR;
8755 /*****************************************************************************
8756 * WSAEnumProtocolsA [WS2_32.@]
8758 * see function WSAEnumProtocolsW
8760 INT WINAPI WSAEnumProtocolsA( LPINT protocols, LPWSAPROTOCOL_INFOA buffer, LPDWORD len )
8762 return WS_EnumProtocols( FALSE, protocols, (LPWSAPROTOCOL_INFOW) buffer, len);
8765 /*****************************************************************************
8766 * WSAEnumProtocolsW [WS2_32.@]
8768 * Retrieves information about specified set of active network protocols.
8770 * PARAMS
8771 * protocols [I] Pointer to null-terminated array of protocol id's. NULL
8772 * retrieves information on all available protocols.
8773 * buffer [I] Pointer to a buffer to be filled with WSAPROTOCOL_INFO
8774 * structures.
8775 * len [I/O] Pointer to a variable specifying buffer size. On output
8776 * the variable holds the number of bytes needed when the
8777 * specified size is too small.
8779 * RETURNS
8780 * Success: number of WSAPROTOCOL_INFO structures in buffer.
8781 * Failure: SOCKET_ERROR
8783 * NOTES
8784 * NT4SP5 does not return SPX if protocols == NULL
8786 * BUGS
8787 * - NT4SP5 returns in addition these list of NETBIOS protocols
8788 * (address family 17), each entry two times one for socket type 2 and 5
8790 * iProtocol szProtocol
8791 * 0x80000000 \Device\NwlnkNb
8792 * 0xfffffffa \Device\NetBT_CBENT7
8793 * 0xfffffffb \Device\Nbf_CBENT7
8794 * 0xfffffffc \Device\NetBT_NdisWan5
8795 * 0xfffffffd \Device\NetBT_El9202
8796 * 0xfffffffe \Device\Nbf_El9202
8797 * 0xffffffff \Device\Nbf_NdisWan4
8799 * - there is no check that the operating system supports the returned
8800 * protocols
8802 INT WINAPI WSAEnumProtocolsW( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
8804 return WS_EnumProtocols( TRUE, protocols, buffer, len);
8807 /*****************************************************************************
8808 * WSCEnumProtocols [WS2_32.@]
8810 * PARAMS
8811 * protocols [I] Null-terminated array of iProtocol values.
8812 * buffer [O] Buffer of WSAPROTOCOL_INFOW structures.
8813 * len [I/O] Size of buffer on input/output.
8814 * errno [O] Error code.
8816 * RETURNS
8817 * Success: number of protocols to be reported on.
8818 * Failure: SOCKET_ERROR. error is in errno.
8820 * BUGS
8821 * Doesn't supply info on layered protocols.
8824 INT WINAPI WSCEnumProtocols( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len, LPINT err )
8826 INT ret = WSAEnumProtocolsW( protocols, buffer, len );
8828 if (ret == SOCKET_ERROR) *err = WSAENOBUFS;
8830 return ret;