ws2_32: Implement InetPtonW function.
[wine/multimedia.git] / dlls / ws2_32 / socket.c
blob5098f851dd980ccafbf7479cb05b1be1e65b7c4a
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 WINE_DEFAULT_DEBUG_CHANNEL(winsock);
181 WINE_DECLARE_DEBUG_CHANNEL(winediag);
183 /* names of the protocols */
184 static const WCHAR NameIpxW[] = {'I', 'P', 'X', '\0'};
185 static const WCHAR NameSpxW[] = {'S', 'P', 'X', '\0'};
186 static const WCHAR NameSpxIIW[] = {'S', 'P', 'X', ' ', 'I', 'I', '\0'};
187 static const WCHAR NameTcpW[] = {'T', 'C', 'P', '/', 'I', 'P', '\0'};
188 static const WCHAR NameUdpW[] = {'U', 'D', 'P', '/', 'I', 'P', '\0'};
190 /* Taken from Win2k */
191 static const GUID ProviderIdIP = { 0xe70f1aa0, 0xab8b, 0x11cf,
192 { 0x8c, 0xa3, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
193 static const GUID ProviderIdIPX = { 0x11058240, 0xbe47, 0x11cf,
194 { 0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
195 static const GUID ProviderIdSPX = { 0x11058241, 0xbe47, 0x11cf,
196 { 0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
198 static const INT valid_protocols[] =
200 WS_IPPROTO_TCP,
201 WS_IPPROTO_UDP,
202 WS_NSPROTO_IPX,
203 WS_NSPROTO_SPX,
204 WS_NSPROTO_SPXII,
208 #define IS_IPX_PROTO(X) ((X) >= WS_NSPROTO_IPX && (X) <= WS_NSPROTO_IPX + 255)
210 #if defined(IP_UNICAST_IF) && defined(SO_ATTACH_FILTER)
211 # define LINUX_BOUND_IF
212 struct interface_filter {
213 struct sock_filter iface_memaddr;
214 struct sock_filter iface_rule;
215 struct sock_filter ip_memaddr;
216 struct sock_filter ip_rule;
217 struct sock_filter return_keep;
218 struct sock_filter return_dump;
220 # define FILTER_JUMP_DUMP(here) (u_char)(offsetof(struct interface_filter, return_dump) \
221 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
222 /sizeof(struct sock_filter)
223 # define FILTER_JUMP_KEEP(here) (u_char)(offsetof(struct interface_filter, return_keep) \
224 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
225 /sizeof(struct sock_filter)
226 # define FILTER_JUMP_NEXT() (u_char)(0)
227 # define SKF_NET_DESTIP 16 /* offset in the network header to the destination IP */
228 static struct interface_filter generic_interface_filter = {
229 /* This filter rule allows incoming packets on the specified interface, which works for all
230 * remotely generated packets and for locally generated broadcast packets. */
231 BPF_STMT(BPF_LD+BPF_W+BPF_ABS, SKF_AD_OFF+SKF_AD_IFINDEX),
232 BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0xdeadbeef, FILTER_JUMP_KEEP(iface_rule), FILTER_JUMP_NEXT()),
233 /* This rule allows locally generated packets targeted at the specific IP address of the chosen
234 * adapter (local packets not destined for the broadcast address do not have IFINDEX set) */
235 BPF_STMT(BPF_LD+BPF_W+BPF_ABS, SKF_NET_OFF+SKF_NET_DESTIP),
236 BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0xdeadbeef, FILTER_JUMP_KEEP(ip_rule), FILTER_JUMP_DUMP(ip_rule)),
237 BPF_STMT(BPF_RET+BPF_K, (u_int)-1), /* keep packet */
238 BPF_STMT(BPF_RET+BPF_K, 0) /* dump packet */
240 #endif /* LINUX_BOUND_IF */
243 * The actual definition of WSASendTo, wrapped in a different function name
244 * so that internal calls from ws2_32 itself will not trigger programs like
245 * Garena, which hooks WSASendTo/WSARecvFrom calls.
247 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
248 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
249 const struct WS_sockaddr *to, int tolen,
250 LPWSAOVERLAPPED lpOverlapped,
251 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine );
254 * Internal fundamental receive function, essentially WSARecvFrom with an
255 * additional parameter to support message control headers.
257 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
258 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
259 struct WS_sockaddr *lpFrom,
260 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
261 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
262 LPWSABUF lpControlBuffer );
264 /* critical section to protect some non-reentrant net function */
265 static CRITICAL_SECTION csWSgetXXXbyYYY;
266 static CRITICAL_SECTION_DEBUG critsect_debug =
268 0, 0, &csWSgetXXXbyYYY,
269 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
270 0, 0, { (DWORD_PTR)(__FILE__ ": csWSgetXXXbyYYY") }
272 static CRITICAL_SECTION csWSgetXXXbyYYY = { &critsect_debug, -1, 0, 0, 0, 0 };
274 union generic_unix_sockaddr
276 struct sockaddr addr;
277 char data[128]; /* should be big enough for all families */
280 static inline const char *debugstr_sockaddr( const struct WS_sockaddr *a )
282 if (!a) return "(nil)";
283 switch (a->sa_family)
285 case WS_AF_INET:
287 char buf[16];
288 const char *p;
289 struct WS_sockaddr_in *sin = (struct WS_sockaddr_in *)a;
291 p = WS_inet_ntop( WS_AF_INET, &sin->sin_addr, buf, sizeof(buf) );
292 if (!p)
293 p = "(unknown IPv4 address)";
295 return wine_dbg_sprintf("{ family AF_INET, address %s, port %d }",
296 p, ntohs(sin->sin_port));
298 case WS_AF_INET6:
300 char buf[46];
301 const char *p;
302 struct WS_sockaddr_in6 *sin = (struct WS_sockaddr_in6 *)a;
304 p = WS_inet_ntop( WS_AF_INET6, &sin->sin6_addr, buf, sizeof(buf) );
305 if (!p)
306 p = "(unknown IPv6 address)";
307 return wine_dbg_sprintf("{ family AF_INET6, address %s, port %d }",
308 p, ntohs(sin->sin6_port));
310 case WS_AF_IPX:
312 int i;
313 char netnum[16], nodenum[16];
314 struct WS_sockaddr_ipx *sin = (struct WS_sockaddr_ipx *)a;
316 for (i = 0;i < 4; i++) sprintf(netnum + i * 2, "%02X", (unsigned char) sin->sa_netnum[i]);
317 for (i = 0;i < 6; i++) sprintf(nodenum + i * 2, "%02X", (unsigned char) sin->sa_nodenum[i]);
319 return wine_dbg_sprintf("{ family AF_IPX, address %s.%s, ipx socket %d }",
320 netnum, nodenum, sin->sa_socket);
322 case WS_AF_IRDA:
324 DWORD addr;
326 memcpy( &addr, ((const SOCKADDR_IRDA *)a)->irdaDeviceID, sizeof(addr) );
327 addr = ntohl( addr );
328 return wine_dbg_sprintf("{ family AF_IRDA, addr %08x, name %s }",
329 addr,
330 ((const SOCKADDR_IRDA *)a)->irdaServiceName);
332 default:
333 return wine_dbg_sprintf("{ family %d }", a->sa_family);
337 static inline const char *debugstr_sockopt(int level, int optname)
339 const char *stropt = NULL, *strlevel = NULL;
341 #define DEBUG_SOCKLEVEL(x) case (x): strlevel = #x
342 #define DEBUG_SOCKOPT(x) case (x): stropt = #x; break
344 switch(level)
346 DEBUG_SOCKLEVEL(WS_SOL_SOCKET);
347 switch(optname)
349 DEBUG_SOCKOPT(WS_SO_ACCEPTCONN);
350 DEBUG_SOCKOPT(WS_SO_BROADCAST);
351 DEBUG_SOCKOPT(WS_SO_BSP_STATE);
352 DEBUG_SOCKOPT(WS_SO_CONDITIONAL_ACCEPT);
353 DEBUG_SOCKOPT(WS_SO_CONNECT_TIME);
354 DEBUG_SOCKOPT(WS_SO_DEBUG);
355 DEBUG_SOCKOPT(WS_SO_DONTLINGER);
356 DEBUG_SOCKOPT(WS_SO_DONTROUTE);
357 DEBUG_SOCKOPT(WS_SO_ERROR);
358 DEBUG_SOCKOPT(WS_SO_EXCLUSIVEADDRUSE);
359 DEBUG_SOCKOPT(WS_SO_GROUP_ID);
360 DEBUG_SOCKOPT(WS_SO_GROUP_PRIORITY);
361 DEBUG_SOCKOPT(WS_SO_KEEPALIVE);
362 DEBUG_SOCKOPT(WS_SO_LINGER);
363 DEBUG_SOCKOPT(WS_SO_MAX_MSG_SIZE);
364 DEBUG_SOCKOPT(WS_SO_OOBINLINE);
365 DEBUG_SOCKOPT(WS_SO_OPENTYPE);
366 DEBUG_SOCKOPT(WS_SO_PROTOCOL_INFOA);
367 DEBUG_SOCKOPT(WS_SO_PROTOCOL_INFOW);
368 DEBUG_SOCKOPT(WS_SO_RCVBUF);
369 DEBUG_SOCKOPT(WS_SO_RCVTIMEO);
370 DEBUG_SOCKOPT(WS_SO_REUSEADDR);
371 DEBUG_SOCKOPT(WS_SO_SNDBUF);
372 DEBUG_SOCKOPT(WS_SO_SNDTIMEO);
373 DEBUG_SOCKOPT(WS_SO_TYPE);
375 break;
377 DEBUG_SOCKLEVEL(WS_NSPROTO_IPX);
378 switch(optname)
380 DEBUG_SOCKOPT(WS_IPX_PTYPE);
381 DEBUG_SOCKOPT(WS_IPX_FILTERPTYPE);
382 DEBUG_SOCKOPT(WS_IPX_DSTYPE);
383 DEBUG_SOCKOPT(WS_IPX_RECVHDR);
384 DEBUG_SOCKOPT(WS_IPX_MAXSIZE);
385 DEBUG_SOCKOPT(WS_IPX_ADDRESS);
386 DEBUG_SOCKOPT(WS_IPX_MAX_ADAPTER_NUM);
388 break;
390 DEBUG_SOCKLEVEL(WS_SOL_IRLMP);
391 switch(optname)
393 DEBUG_SOCKOPT(WS_IRLMP_ENUMDEVICES);
395 break;
397 DEBUG_SOCKLEVEL(WS_IPPROTO_TCP);
398 switch(optname)
400 DEBUG_SOCKOPT(WS_TCP_BSDURGENT);
401 DEBUG_SOCKOPT(WS_TCP_EXPEDITED_1122);
402 DEBUG_SOCKOPT(WS_TCP_NODELAY);
404 break;
406 DEBUG_SOCKLEVEL(WS_IPPROTO_IP);
407 switch(optname)
409 DEBUG_SOCKOPT(WS_IP_ADD_MEMBERSHIP);
410 DEBUG_SOCKOPT(WS_IP_DROP_MEMBERSHIP);
411 DEBUG_SOCKOPT(WS_IP_HDRINCL);
412 DEBUG_SOCKOPT(WS_IP_MULTICAST_IF);
413 DEBUG_SOCKOPT(WS_IP_MULTICAST_LOOP);
414 DEBUG_SOCKOPT(WS_IP_MULTICAST_TTL);
415 DEBUG_SOCKOPT(WS_IP_OPTIONS);
416 DEBUG_SOCKOPT(WS_IP_PKTINFO);
417 DEBUG_SOCKOPT(WS_IP_TOS);
418 DEBUG_SOCKOPT(WS_IP_TTL);
419 DEBUG_SOCKOPT(WS_IP_UNICAST_IF);
420 DEBUG_SOCKOPT(WS_IP_DONTFRAGMENT);
422 break;
424 DEBUG_SOCKLEVEL(WS_IPPROTO_IPV6);
425 switch(optname)
427 DEBUG_SOCKOPT(WS_IPV6_ADD_MEMBERSHIP);
428 DEBUG_SOCKOPT(WS_IPV6_DROP_MEMBERSHIP);
429 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_IF);
430 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_HOPS);
431 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_LOOP);
432 DEBUG_SOCKOPT(WS_IPV6_UNICAST_HOPS);
433 DEBUG_SOCKOPT(WS_IPV6_V6ONLY);
434 DEBUG_SOCKOPT(WS_IPV6_UNICAST_IF);
435 DEBUG_SOCKOPT(WS_IPV6_DONTFRAG);
437 break;
439 #undef DEBUG_SOCKLEVEL
440 #undef DEBUG_SOCKOPT
442 if (!strlevel)
443 strlevel = wine_dbg_sprintf("WS_0x%x", level);
444 if (!stropt)
445 stropt = wine_dbg_sprintf("WS_0x%x", optname);
447 return wine_dbg_sprintf("level %s, name %s", strlevel + 3, stropt + 3);
450 static inline const char *debugstr_optval(const char *optval, int optlenval)
452 if (optval && !IS_INTRESOURCE(optval) && optlenval >= 1 && optlenval <= sizeof(DWORD))
454 DWORD value = 0;
455 memcpy(&value, optval, optlenval);
456 return wine_dbg_sprintf("%p (%u)", optval, value);
458 return wine_dbg_sprintf("%p", optval);
461 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
462 #define SOCKET2HANDLE(s) ((HANDLE)(s))
463 #define HANDLE2SOCKET(h) ((SOCKET)(h))
465 /****************************************************************
466 * Async IO declarations
467 ****************************************************************/
469 struct ws2_async_io
471 struct ws2_async_io *next;
474 struct ws2_async_shutdown
476 struct ws2_async_io io;
477 HANDLE hSocket;
478 IO_STATUS_BLOCK iosb;
479 int type;
482 struct ws2_async
484 struct ws2_async_io io;
485 HANDLE hSocket;
486 LPWSAOVERLAPPED user_overlapped;
487 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
488 IO_STATUS_BLOCK local_iosb;
489 struct WS_sockaddr *addr;
490 union
492 int val; /* for send operations */
493 int *ptr; /* for recv operations */
494 } addrlen;
495 DWORD flags;
496 DWORD *lpFlags;
497 WSABUF *control;
498 unsigned int n_iovecs;
499 unsigned int first_iovec;
500 struct iovec iovec[1];
503 struct ws2_accept_async
505 struct ws2_async_io io;
506 HANDLE listen_socket;
507 HANDLE accept_socket;
508 LPOVERLAPPED user_overlapped;
509 ULONG_PTR cvalue;
510 PVOID buf; /* buffer to write data to */
511 int data_len;
512 int local_len;
513 int remote_len;
514 struct ws2_async *read;
517 static struct ws2_async_io *async_io_freelist;
519 static void release_async_io( struct ws2_async_io *io )
521 for (;;)
523 struct ws2_async_io *next = async_io_freelist;
524 io->next = next;
525 if (InterlockedCompareExchangePointer( (void **)&async_io_freelist, io, next ) == next) return;
529 static struct ws2_async_io *alloc_async_io( DWORD size )
531 /* first free remaining previous fileinfos */
533 struct ws2_async_io *io = InterlockedExchangePointer( (void **)&async_io_freelist, NULL );
535 while (io)
537 struct ws2_async_io *next = io->next;
538 HeapFree( GetProcessHeap(), 0, io );
539 io = next;
542 return HeapAlloc( GetProcessHeap(), 0, size );
545 /****************************************************************/
547 /* ----------------------------------- internal data */
549 /* ws_... struct conversion flags */
551 typedef struct /* WSAAsyncSelect() control struct */
553 HANDLE service, event, sock;
554 HWND hWnd;
555 UINT uMsg;
556 LONG lEvent;
557 } ws_select_info;
559 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
560 #define WS_MAX_UDP_DATAGRAM 1024
561 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
563 /* hostent's, servent's and protent's are stored in one buffer per thread,
564 * as documented on MSDN for the functions that return any of the buffers */
565 struct per_thread_data
567 int opentype;
568 struct WS_hostent *he_buffer;
569 struct WS_servent *se_buffer;
570 struct WS_protoent *pe_buffer;
571 int he_len;
572 int se_len;
573 int pe_len;
574 char ntoa_buffer[16]; /* 4*3 digits + 3 '.' + 1 '\0' */
577 /* internal: routing description information */
578 struct route {
579 struct in_addr addr;
580 IF_INDEX interface;
581 DWORD metric;
584 static INT num_startup; /* reference counter */
585 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
587 /* function prototypes */
588 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length);
589 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
590 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
591 static struct WS_servent *WS_dup_se(const struct servent* p_se);
592 static int ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size);
594 int WSAIOCTL_GetInterfaceCount(void);
595 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
597 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus, ULONG Information );
599 #define MAP_OPTION(opt) { WS_##opt, opt }
601 static const int ws_flags_map[][2] =
603 MAP_OPTION( MSG_OOB ),
604 MAP_OPTION( MSG_PEEK ),
605 MAP_OPTION( MSG_DONTROUTE ),
606 MAP_OPTION( MSG_WAITALL ),
609 static const int ws_sock_map[][2] =
611 MAP_OPTION( SO_DEBUG ),
612 MAP_OPTION( SO_ACCEPTCONN ),
613 MAP_OPTION( SO_REUSEADDR ),
614 MAP_OPTION( SO_KEEPALIVE ),
615 MAP_OPTION( SO_DONTROUTE ),
616 MAP_OPTION( SO_BROADCAST ),
617 MAP_OPTION( SO_LINGER ),
618 MAP_OPTION( SO_OOBINLINE ),
619 MAP_OPTION( SO_SNDBUF ),
620 MAP_OPTION( SO_RCVBUF ),
621 MAP_OPTION( SO_ERROR ),
622 MAP_OPTION( SO_TYPE ),
623 #ifdef SO_RCVTIMEO
624 MAP_OPTION( SO_RCVTIMEO ),
625 #endif
626 #ifdef SO_SNDTIMEO
627 MAP_OPTION( SO_SNDTIMEO ),
628 #endif
631 static const int ws_tcp_map[][2] =
633 #ifdef TCP_NODELAY
634 MAP_OPTION( TCP_NODELAY ),
635 #endif
638 static const int ws_ip_map[][2] =
640 MAP_OPTION( IP_MULTICAST_IF ),
641 MAP_OPTION( IP_MULTICAST_TTL ),
642 MAP_OPTION( IP_MULTICAST_LOOP ),
643 MAP_OPTION( IP_ADD_MEMBERSHIP ),
644 MAP_OPTION( IP_DROP_MEMBERSHIP ),
645 MAP_OPTION( IP_OPTIONS ),
646 #ifdef IP_HDRINCL
647 MAP_OPTION( IP_HDRINCL ),
648 #endif
649 MAP_OPTION( IP_TOS ),
650 MAP_OPTION( IP_TTL ),
651 #ifdef IP_PKTINFO
652 MAP_OPTION( IP_PKTINFO ),
653 #endif
654 #ifdef IP_UNICAST_IF
655 MAP_OPTION( IP_UNICAST_IF ),
656 #endif
659 static const int ws_ipv6_map[][2] =
661 #ifdef IPV6_ADD_MEMBERSHIP
662 MAP_OPTION( IPV6_ADD_MEMBERSHIP ),
663 #endif
664 #ifdef IPV6_DROP_MEMBERSHIP
665 MAP_OPTION( IPV6_DROP_MEMBERSHIP ),
666 #endif
667 MAP_OPTION( IPV6_MULTICAST_IF ),
668 MAP_OPTION( IPV6_MULTICAST_HOPS ),
669 MAP_OPTION( IPV6_MULTICAST_LOOP ),
670 MAP_OPTION( IPV6_UNICAST_HOPS ),
671 MAP_OPTION( IPV6_V6ONLY ),
672 #ifdef IPV6_UNICAST_IF
673 MAP_OPTION( IPV6_UNICAST_IF ),
674 #endif
677 static const int ws_af_map[][2] =
679 MAP_OPTION( AF_UNSPEC ),
680 MAP_OPTION( AF_INET ),
681 MAP_OPTION( AF_INET6 ),
682 #ifdef HAS_IPX
683 MAP_OPTION( AF_IPX ),
684 #endif
685 #ifdef AF_IRDA
686 MAP_OPTION( AF_IRDA ),
687 #endif
688 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
691 static const int ws_socktype_map[][2] =
693 MAP_OPTION( SOCK_DGRAM ),
694 MAP_OPTION( SOCK_STREAM ),
695 MAP_OPTION( SOCK_RAW ),
696 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
699 static const int ws_proto_map[][2] =
701 MAP_OPTION( IPPROTO_IP ),
702 MAP_OPTION( IPPROTO_TCP ),
703 MAP_OPTION( IPPROTO_UDP ),
704 MAP_OPTION( IPPROTO_IPV6 ),
705 MAP_OPTION( IPPROTO_ICMP ),
706 MAP_OPTION( IPPROTO_IGMP ),
707 MAP_OPTION( IPPROTO_RAW ),
708 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
711 static const int ws_aiflag_map[][2] =
713 MAP_OPTION( AI_PASSIVE ),
714 MAP_OPTION( AI_CANONNAME ),
715 MAP_OPTION( AI_NUMERICHOST ),
716 #ifdef AI_NUMERICSERV
717 MAP_OPTION( AI_NUMERICSERV ),
718 #endif
719 #ifdef AI_V4MAPPED
720 MAP_OPTION( AI_V4MAPPED ),
721 #endif
722 MAP_OPTION( AI_ADDRCONFIG ),
725 static const int ws_niflag_map[][2] =
727 MAP_OPTION( NI_NOFQDN ),
728 MAP_OPTION( NI_NUMERICHOST ),
729 MAP_OPTION( NI_NAMEREQD ),
730 MAP_OPTION( NI_NUMERICSERV ),
731 MAP_OPTION( NI_DGRAM ),
734 static const int ws_eai_map[][2] =
736 MAP_OPTION( EAI_AGAIN ),
737 MAP_OPTION( EAI_BADFLAGS ),
738 MAP_OPTION( EAI_FAIL ),
739 MAP_OPTION( EAI_FAMILY ),
740 MAP_OPTION( EAI_MEMORY ),
741 /* Note: EAI_NODATA is deprecated, but still
742 * used by Windows and Linux... We map the newer
743 * EAI_NONAME to EAI_NODATA for now until Windows
744 * changes too.
746 #ifdef EAI_NODATA
747 MAP_OPTION( EAI_NODATA ),
748 #endif
749 #ifdef EAI_NONAME
750 { WS_EAI_NODATA, EAI_NONAME },
751 #endif
753 MAP_OPTION( EAI_SERVICE ),
754 MAP_OPTION( EAI_SOCKTYPE ),
755 { 0, 0 }
758 static const char magic_loopback_addr[] = {127, 12, 34, 56};
760 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
761 #ifdef IP_PKTINFO
762 static inline WSACMSGHDR *fill_control_message(int level, int type, WSACMSGHDR *current, ULONG *maxsize, void *data, int len)
764 ULONG msgsize = sizeof(WSACMSGHDR) + WSA_CMSG_ALIGN(len);
765 char *ptr = (char *) current + sizeof(WSACMSGHDR);
767 /* Make sure there is at least enough room for this entry */
768 if (msgsize > *maxsize)
769 return NULL;
770 *maxsize -= msgsize;
771 /* Fill in the entry */
772 current->cmsg_len = sizeof(WSACMSGHDR) + len;
773 current->cmsg_level = level;
774 current->cmsg_type = type;
775 memcpy(ptr, data, len);
776 /* Return the pointer to where next entry should go */
777 return (WSACMSGHDR *) (ptr + WSA_CMSG_ALIGN(len));
779 #endif /* IP_PKTINFO */
781 static inline int convert_control_headers(struct msghdr *hdr, WSABUF *control)
783 #ifdef IP_PKTINFO
784 WSACMSGHDR *cmsg_win = (WSACMSGHDR *) control->buf, *ptr;
785 ULONG ctlsize = control->len;
786 struct cmsghdr *cmsg_unix;
788 ptr = cmsg_win;
789 /* Loop over all the headers, converting as appropriate */
790 for (cmsg_unix = CMSG_FIRSTHDR(hdr); cmsg_unix != NULL; cmsg_unix = CMSG_NXTHDR(hdr, cmsg_unix))
792 switch(cmsg_unix->cmsg_level)
794 case IPPROTO_IP:
795 switch(cmsg_unix->cmsg_type)
797 case IP_PKTINFO:
799 /* Convert the Unix IP_PKTINFO structure to the Windows version */
800 struct in_pktinfo *data_unix = (struct in_pktinfo *) CMSG_DATA(cmsg_unix);
801 struct WS_in_pktinfo data_win;
803 memcpy(&data_win.ipi_addr,&data_unix->ipi_addr.s_addr,4); /* 4 bytes = 32 address bits */
804 data_win.ipi_ifindex = data_unix->ipi_ifindex;
805 ptr = fill_control_message(WS_IPPROTO_IP, WS_IP_PKTINFO, ptr, &ctlsize,
806 (void*)&data_win, sizeof(data_win));
807 if (!ptr) goto error;
808 } break;
809 default:
810 FIXME("Unhandled IPPROTO_IP message header type %d\n", cmsg_unix->cmsg_type);
811 break;
813 break;
814 default:
815 FIXME("Unhandled message header level %d\n", cmsg_unix->cmsg_level);
816 break;
820 error:
821 /* Set the length of the returned control headers */
822 control->len = (ptr == NULL ? 0 : (char*)ptr - (char*)cmsg_win);
823 return (ptr != NULL);
824 #else /* IP_PKTINFO */
825 control->len = 0;
826 return 1;
827 #endif /* IP_PKTINFO */
829 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
831 /* ----------------------------------- error handling */
833 static NTSTATUS sock_get_ntstatus( int err )
835 switch ( err )
837 case EBADF: return STATUS_INVALID_HANDLE;
838 case EBUSY: return STATUS_DEVICE_BUSY;
839 case EPERM:
840 case EACCES: return STATUS_ACCESS_DENIED;
841 case EFAULT: return STATUS_NO_MEMORY;
842 case EINVAL: return STATUS_INVALID_PARAMETER;
843 case ENFILE:
844 case EMFILE: return STATUS_TOO_MANY_OPENED_FILES;
845 case EWOULDBLOCK: return STATUS_CANT_WAIT;
846 case EINPROGRESS: return STATUS_PENDING;
847 case EALREADY: return STATUS_NETWORK_BUSY;
848 case ENOTSOCK: return STATUS_OBJECT_TYPE_MISMATCH;
849 case EDESTADDRREQ: return STATUS_INVALID_PARAMETER;
850 case EMSGSIZE: return STATUS_BUFFER_OVERFLOW;
851 case EPROTONOSUPPORT:
852 case ESOCKTNOSUPPORT:
853 case EPFNOSUPPORT:
854 case EAFNOSUPPORT:
855 case EPROTOTYPE: return STATUS_NOT_SUPPORTED;
856 case ENOPROTOOPT: return STATUS_INVALID_PARAMETER;
857 case EOPNOTSUPP: return STATUS_NOT_SUPPORTED;
858 case EADDRINUSE: return STATUS_ADDRESS_ALREADY_ASSOCIATED;
859 case EADDRNOTAVAIL: return STATUS_INVALID_PARAMETER;
860 case ECONNREFUSED: return STATUS_CONNECTION_REFUSED;
861 case ESHUTDOWN: return STATUS_PIPE_DISCONNECTED;
862 case ENOTCONN: return STATUS_CONNECTION_DISCONNECTED;
863 case ETIMEDOUT: return STATUS_IO_TIMEOUT;
864 case ENETUNREACH: return STATUS_NETWORK_UNREACHABLE;
865 case ENETDOWN: return STATUS_NETWORK_BUSY;
866 case EPIPE:
867 case ECONNRESET: return STATUS_CONNECTION_RESET;
868 case ECONNABORTED: return STATUS_CONNECTION_ABORTED;
870 case 0: return STATUS_SUCCESS;
871 default:
872 WARN("Unknown errno %d!\n", err);
873 return STATUS_UNSUCCESSFUL;
877 static UINT sock_get_error( int err )
879 switch(err)
881 case EINTR: return WSAEINTR;
882 case EPERM:
883 case EACCES: return WSAEACCES;
884 case EFAULT: return WSAEFAULT;
885 case EINVAL: return WSAEINVAL;
886 case EMFILE: return WSAEMFILE;
887 case EWOULDBLOCK: return WSAEWOULDBLOCK;
888 case EINPROGRESS: return WSAEINPROGRESS;
889 case EALREADY: return WSAEALREADY;
890 case EBADF:
891 case ENOTSOCK: return WSAENOTSOCK;
892 case EDESTADDRREQ: return WSAEDESTADDRREQ;
893 case EMSGSIZE: return WSAEMSGSIZE;
894 case EPROTOTYPE: return WSAEPROTOTYPE;
895 case ENOPROTOOPT: return WSAENOPROTOOPT;
896 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
897 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
898 case EOPNOTSUPP: return WSAEOPNOTSUPP;
899 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
900 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
901 case EADDRINUSE: return WSAEADDRINUSE;
902 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
903 case ENETDOWN: return WSAENETDOWN;
904 case ENETUNREACH: return WSAENETUNREACH;
905 case ENETRESET: return WSAENETRESET;
906 case ECONNABORTED: return WSAECONNABORTED;
907 case EPIPE:
908 case ECONNRESET: return WSAECONNRESET;
909 case ENOBUFS: return WSAENOBUFS;
910 case EISCONN: return WSAEISCONN;
911 case ENOTCONN: return WSAENOTCONN;
912 case ESHUTDOWN: return WSAESHUTDOWN;
913 case ETOOMANYREFS: return WSAETOOMANYREFS;
914 case ETIMEDOUT: return WSAETIMEDOUT;
915 case ECONNREFUSED: return WSAECONNREFUSED;
916 case ELOOP: return WSAELOOP;
917 case ENAMETOOLONG: return WSAENAMETOOLONG;
918 case EHOSTDOWN: return WSAEHOSTDOWN;
919 case EHOSTUNREACH: return WSAEHOSTUNREACH;
920 case ENOTEMPTY: return WSAENOTEMPTY;
921 #ifdef EPROCLIM
922 case EPROCLIM: return WSAEPROCLIM;
923 #endif
924 #ifdef EUSERS
925 case EUSERS: return WSAEUSERS;
926 #endif
927 #ifdef EDQUOT
928 case EDQUOT: return WSAEDQUOT;
929 #endif
930 #ifdef ESTALE
931 case ESTALE: return WSAESTALE;
932 #endif
933 #ifdef EREMOTE
934 case EREMOTE: return WSAEREMOTE;
935 #endif
937 /* just in case we ever get here and there are no problems */
938 case 0: return 0;
939 default:
940 WARN("Unknown errno %d!\n", err);
941 return WSAEOPNOTSUPP;
945 static UINT wsaErrno(void)
947 int loc_errno = errno;
948 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
950 return sock_get_error( loc_errno );
953 /* most ws2 overlapped functions return an ntstatus-based error code */
954 static NTSTATUS wsaErrStatus(void)
956 int loc_errno = errno;
957 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
959 return sock_get_ntstatus(loc_errno);
962 static UINT wsaHerrno(int loc_errno)
964 WARN("h_errno %d.\n", loc_errno);
966 switch(loc_errno)
968 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
969 case TRY_AGAIN: return WSATRY_AGAIN;
970 case NO_RECOVERY: return WSANO_RECOVERY;
971 case NO_DATA: return WSANO_DATA;
972 case ENOBUFS: return WSAENOBUFS;
974 case 0: return 0;
975 default:
976 WARN("Unknown h_errno %d!\n", loc_errno);
977 return WSAEOPNOTSUPP;
981 static inline DWORD NtStatusToWSAError( const DWORD status )
983 /* We only need to cover the status codes set by server async request handling */
984 DWORD wserr;
985 switch ( status )
987 case STATUS_SUCCESS: wserr = 0; break;
988 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
989 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
990 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
991 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
992 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
993 case STATUS_NETWORK_BUSY: wserr = WSAEALREADY; break;
994 case STATUS_NETWORK_UNREACHABLE: wserr = WSAENETUNREACH; break;
995 case STATUS_CONNECTION_REFUSED: wserr = WSAECONNREFUSED; break;
996 case STATUS_CONNECTION_DISCONNECTED: wserr = WSAENOTCONN; break;
997 case STATUS_CONNECTION_RESET: wserr = WSAECONNRESET; break;
998 case STATUS_CONNECTION_ABORTED: wserr = WSAECONNABORTED; break;
999 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
1000 case STATUS_ADDRESS_ALREADY_ASSOCIATED: wserr = WSAEADDRINUSE; break;
1001 case STATUS_IO_TIMEOUT:
1002 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
1003 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
1004 case STATUS_ACCESS_DENIED: wserr = WSAEACCES; break;
1005 case STATUS_TOO_MANY_OPENED_FILES: wserr = WSAEMFILE; break;
1006 case STATUS_CANT_WAIT: wserr = WSAEWOULDBLOCK; break;
1007 case STATUS_BUFFER_OVERFLOW: wserr = WSAEMSGSIZE; break;
1008 case STATUS_NOT_SUPPORTED: wserr = WSAEOPNOTSUPP; break;
1009 case STATUS_HOST_UNREACHABLE: wserr = WSAEHOSTUNREACH; break;
1011 default:
1012 wserr = RtlNtStatusToDosError( status );
1013 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
1015 return wserr;
1018 /* set last error code from NT status without mapping WSA errors */
1019 static inline unsigned int set_error( unsigned int err )
1021 if (err)
1023 err = NtStatusToWSAError( err );
1024 SetLastError( err );
1026 return err;
1029 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
1031 int fd;
1032 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
1033 return -1;
1034 return fd;
1037 static inline void release_sock_fd( SOCKET s, int fd )
1039 wine_server_release_fd( SOCKET2HANDLE(s), fd );
1042 static void _enable_event( HANDLE s, unsigned int event,
1043 unsigned int sstate, unsigned int cstate )
1045 SERVER_START_REQ( enable_socket_event )
1047 req->handle = wine_server_obj_handle( s );
1048 req->mask = event;
1049 req->sstate = sstate;
1050 req->cstate = cstate;
1051 wine_server_call( req );
1053 SERVER_END_REQ;
1056 static NTSTATUS _is_blocking(SOCKET s, BOOL *ret)
1058 NTSTATUS status;
1059 SERVER_START_REQ( get_socket_event )
1061 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1062 req->service = FALSE;
1063 req->c_event = 0;
1064 status = wine_server_call( req );
1065 *ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
1067 SERVER_END_REQ;
1068 return status;
1071 static unsigned int _get_sock_mask(SOCKET s)
1073 unsigned int ret;
1074 SERVER_START_REQ( get_socket_event )
1076 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1077 req->service = FALSE;
1078 req->c_event = 0;
1079 wine_server_call( req );
1080 ret = reply->mask;
1082 SERVER_END_REQ;
1083 return ret;
1086 static void _sync_sock_state(SOCKET s)
1088 BOOL dummy;
1089 /* do a dummy wineserver request in order to let
1090 the wineserver run through its select loop once */
1091 (void)_is_blocking(s, &dummy);
1094 static void _get_sock_errors(SOCKET s, int *events)
1096 SERVER_START_REQ( get_socket_event )
1098 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1099 req->service = FALSE;
1100 req->c_event = 0;
1101 wine_server_set_reply( req, events, sizeof(int) * FD_MAX_EVENTS );
1102 wine_server_call( req );
1104 SERVER_END_REQ;
1107 static int _get_sock_error(SOCKET s, unsigned int bit)
1109 int events[FD_MAX_EVENTS];
1110 _get_sock_errors(s, events);
1111 return events[bit];
1114 static int _get_fd_type(int fd)
1116 int sock_type = -1;
1117 socklen_t optlen = sizeof(sock_type);
1118 getsockopt(fd, SOL_SOCKET, SO_TYPE, (char*) &sock_type, &optlen);
1119 return sock_type;
1122 static struct per_thread_data *get_per_thread_data(void)
1124 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
1125 /* lazy initialization */
1126 if (!ptb)
1128 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
1129 NtCurrentTeb()->WinSockData = ptb;
1131 return ptb;
1134 static void free_per_thread_data(void)
1136 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
1138 if (!ptb) return;
1140 /* delete scratch buffers */
1141 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1142 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1143 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1144 ptb->he_buffer = NULL;
1145 ptb->se_buffer = NULL;
1146 ptb->pe_buffer = NULL;
1148 HeapFree( GetProcessHeap(), 0, ptb );
1149 NtCurrentTeb()->WinSockData = NULL;
1152 /***********************************************************************
1153 * DllMain (WS2_32.init)
1155 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
1157 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
1158 switch (fdwReason) {
1159 case DLL_PROCESS_ATTACH:
1160 break;
1161 case DLL_PROCESS_DETACH:
1162 if (fImpLoad) break;
1163 free_per_thread_data();
1164 DeleteCriticalSection(&csWSgetXXXbyYYY);
1165 break;
1166 case DLL_THREAD_DETACH:
1167 free_per_thread_data();
1168 break;
1170 return TRUE;
1173 /***********************************************************************
1174 * convert_flags()
1176 * Converts send/recv flags from Windows format.
1177 * Return the converted flag bits, unsupported flags remain unchanged.
1179 static int convert_flags(int flags)
1181 int i, out;
1182 if (!flags) return 0;
1184 for (out = i = 0; flags && i < sizeof(ws_flags_map) / sizeof(ws_flags_map[0]); i++)
1186 if (ws_flags_map[i][0] & flags)
1188 out |= ws_flags_map[i][1];
1189 flags &= ~ws_flags_map[i][0];
1192 if (flags)
1194 FIXME("Unknown send/recv flags 0x%x, using anyway...\n", flags);
1195 out |= flags;
1197 return out;
1200 /***********************************************************************
1201 * convert_sockopt()
1203 * Converts socket flags from Windows format.
1204 * Return 1 if converted, 0 if not (error).
1206 static int convert_sockopt(INT *level, INT *optname)
1208 unsigned int i;
1209 switch (*level)
1211 case WS_SOL_SOCKET:
1212 *level = SOL_SOCKET;
1213 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
1214 if( ws_sock_map[i][0] == *optname )
1216 *optname = ws_sock_map[i][1];
1217 return 1;
1220 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
1221 break;
1222 case WS_IPPROTO_TCP:
1223 *level = IPPROTO_TCP;
1224 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
1225 if ( ws_tcp_map[i][0] == *optname )
1227 *optname = ws_tcp_map[i][1];
1228 return 1;
1231 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
1232 break;
1233 case WS_IPPROTO_IP:
1234 *level = IPPROTO_IP;
1235 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
1236 if (ws_ip_map[i][0] == *optname )
1238 *optname = ws_ip_map[i][1];
1239 return 1;
1242 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
1243 break;
1244 case WS_IPPROTO_IPV6:
1245 *level = IPPROTO_IPV6;
1246 for(i=0; i<sizeof(ws_ipv6_map)/sizeof(ws_ipv6_map[0]); i++) {
1247 if (ws_ipv6_map[i][0] == *optname )
1249 *optname = ws_ipv6_map[i][1];
1250 return 1;
1253 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname);
1254 break;
1255 default: FIXME("Unimplemented or unknown socket level\n");
1257 return 0;
1260 /* ----------------------------------- Per-thread info (or per-process?) */
1262 static char *strdup_lower(const char *str)
1264 int i;
1265 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
1267 if (ret)
1269 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
1270 ret[i] = 0;
1272 else SetLastError(WSAENOBUFS);
1273 return ret;
1276 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
1277 * from an fd and return the value converted to milli seconds
1278 * or 0 if there is an infinite time out */
1279 static inline INT64 get_rcvsnd_timeo( int fd, BOOL is_recv)
1281 struct timeval tv;
1282 socklen_t len = sizeof(tv);
1283 int optname, res;
1285 if (is_recv)
1286 #ifdef SO_RCVTIMEO
1287 optname = SO_RCVTIMEO;
1288 #else
1289 return 0;
1290 #endif
1291 else
1292 #ifdef SO_SNDTIMEO
1293 optname = SO_SNDTIMEO;
1294 #else
1295 return 0;
1296 #endif
1298 res = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
1299 if (res < 0)
1300 return 0;
1301 return (UINT64)tv.tv_sec * 1000 + tv.tv_usec / 1000;
1304 /* utility: given an fd, will block until one of the events occurs */
1305 static inline int do_block( int fd, int events, int timeout )
1307 struct pollfd pfd;
1308 int ret;
1310 pfd.fd = fd;
1311 pfd.events = events;
1313 while ((ret = poll(&pfd, 1, timeout)) < 0)
1315 if (errno != EINTR)
1316 return -1;
1318 if( ret == 0 )
1319 return 0;
1320 return pfd.revents;
1323 static int
1324 convert_af_w2u(int windowsaf) {
1325 unsigned int i;
1327 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1328 if (ws_af_map[i][0] == windowsaf)
1329 return ws_af_map[i][1];
1330 FIXME("unhandled Windows address family %d\n", windowsaf);
1331 return -1;
1334 static int
1335 convert_af_u2w(int unixaf) {
1336 unsigned int i;
1338 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1339 if (ws_af_map[i][1] == unixaf)
1340 return ws_af_map[i][0];
1341 FIXME("unhandled UNIX address family %d\n", unixaf);
1342 return -1;
1345 static int
1346 convert_proto_w2u(int windowsproto) {
1347 unsigned int i;
1349 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1350 if (ws_proto_map[i][0] == windowsproto)
1351 return ws_proto_map[i][1];
1353 /* check for extended IPX */
1354 if (IS_IPX_PROTO(windowsproto))
1355 return windowsproto;
1357 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
1358 return -1;
1361 static int
1362 convert_proto_u2w(int unixproto) {
1363 unsigned int i;
1365 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1366 if (ws_proto_map[i][1] == unixproto)
1367 return ws_proto_map[i][0];
1369 /* if value is inside IPX range just return it - the kernel simply
1370 * echoes the value used in the socket() function */
1371 if (IS_IPX_PROTO(unixproto))
1372 return unixproto;
1374 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
1375 return -1;
1378 static int
1379 convert_socktype_w2u(int windowssocktype) {
1380 unsigned int i;
1382 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1383 if (ws_socktype_map[i][0] == windowssocktype)
1384 return ws_socktype_map[i][1];
1385 FIXME("unhandled Windows socket type %d\n", windowssocktype);
1386 return -1;
1389 static int
1390 convert_socktype_u2w(int unixsocktype) {
1391 unsigned int i;
1393 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1394 if (ws_socktype_map[i][1] == unixsocktype)
1395 return ws_socktype_map[i][0];
1396 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
1397 return -1;
1400 static int set_ipx_packettype(int sock, int ptype)
1402 #ifdef HAS_IPX
1403 int fd = get_sock_fd( sock, 0, NULL ), ret = 0;
1404 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", ptype, fd);
1406 if (fd == -1) return SOCKET_ERROR;
1408 /* We try to set the ipx type on ipx socket level. */
1409 #ifdef SOL_IPX
1410 if(setsockopt(fd, SOL_IPX, IPX_TYPE, &ptype, sizeof(ptype)) == -1)
1412 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
1413 ret = SOCKET_ERROR;
1415 #else
1417 struct ipx val;
1418 /* Should we retrieve val using a getsockopt call and then
1419 * set the modified one? */
1420 val.ipx_pt = ptype;
1421 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
1423 #endif
1424 release_sock_fd( sock, fd );
1425 return ret;
1426 #else
1427 WARN("IPX support is not enabled, can't set packet type\n");
1428 return SOCKET_ERROR;
1429 #endif
1432 /* ----------------------------------- API -----
1434 * Init / cleanup / error checking.
1437 /***********************************************************************
1438 * WSAStartup (WS2_32.115)
1440 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
1442 TRACE("verReq=%x\n", wVersionRequested);
1444 if (LOBYTE(wVersionRequested) < 1)
1445 return WSAVERNOTSUPPORTED;
1447 if (!lpWSAData) return WSAEINVAL;
1449 num_startup++;
1451 /* that's the whole of the negotiation for now */
1452 lpWSAData->wVersion = wVersionRequested;
1453 /* return winsock information */
1454 lpWSAData->wHighVersion = 0x0202;
1455 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
1456 strcpy(lpWSAData->szSystemStatus, "Running" );
1457 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
1458 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
1459 /* don't do anything with lpWSAData->lpVendorInfo */
1460 /* (some apps don't allocate the space for this field) */
1462 TRACE("succeeded starts: %d\n", num_startup);
1463 return 0;
1467 /***********************************************************************
1468 * WSACleanup (WS2_32.116)
1470 INT WINAPI WSACleanup(void)
1472 if (num_startup) {
1473 num_startup--;
1474 TRACE("pending cleanups: %d\n", num_startup);
1475 return 0;
1477 SetLastError(WSANOTINITIALISED);
1478 return SOCKET_ERROR;
1482 /***********************************************************************
1483 * WSAGetLastError (WS2_32.111)
1485 INT WINAPI WSAGetLastError(void)
1487 return GetLastError();
1490 /***********************************************************************
1491 * WSASetLastError (WS2_32.112)
1493 void WINAPI WSASetLastError(INT iError) {
1494 SetLastError(iError);
1497 static struct WS_hostent *check_buffer_he(int size)
1499 struct per_thread_data * ptb = get_per_thread_data();
1500 if (ptb->he_buffer)
1502 if (ptb->he_len >= size ) return ptb->he_buffer;
1503 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1505 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
1506 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
1507 return ptb->he_buffer;
1510 static struct WS_servent *check_buffer_se(int size)
1512 struct per_thread_data * ptb = get_per_thread_data();
1513 if (ptb->se_buffer)
1515 if (ptb->se_len >= size ) return ptb->se_buffer;
1516 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1518 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
1519 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
1520 return ptb->se_buffer;
1523 static struct WS_protoent *check_buffer_pe(int size)
1525 struct per_thread_data * ptb = get_per_thread_data();
1526 if (ptb->pe_buffer)
1528 if (ptb->pe_len >= size ) return ptb->pe_buffer;
1529 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1531 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
1532 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
1533 return ptb->pe_buffer;
1536 /* ----------------------------------- i/o APIs */
1538 static inline BOOL supported_pf(int pf)
1540 switch (pf)
1542 case WS_AF_INET:
1543 case WS_AF_INET6:
1544 return TRUE;
1545 #ifdef HAS_IPX
1546 case WS_AF_IPX:
1547 return TRUE;
1548 #endif
1549 #ifdef HAS_IRDA
1550 case WS_AF_IRDA:
1551 return TRUE;
1552 #endif
1553 default:
1554 return FALSE;
1558 static inline BOOL supported_protocol(int protocol)
1560 int i;
1561 for (i = 0; i < sizeof(valid_protocols) / sizeof(valid_protocols[0]); i++)
1562 if (protocol == valid_protocols[i])
1563 return TRUE;
1564 return FALSE;
1567 /**********************************************************************/
1569 /* Returns the length of the converted address if successful, 0 if it was too small to
1570 * start with.
1572 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
1573 union generic_unix_sockaddr *uaddr)
1575 unsigned int uaddrlen = 0;
1577 switch (wsaddr->sa_family)
1579 #ifdef HAS_IPX
1580 case WS_AF_IPX:
1582 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
1583 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
1585 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
1586 return 0;
1588 uaddrlen = sizeof(struct sockaddr_ipx);
1589 memset( uaddr, 0, uaddrlen );
1590 uipx->sipx_family=AF_IPX;
1591 uipx->sipx_port=wsipx->sa_socket;
1592 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1593 * in one go
1595 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
1596 #ifdef IPX_FRAME_NONE
1597 uipx->sipx_type=IPX_FRAME_NONE;
1598 #endif
1599 break;
1601 #endif
1602 case WS_AF_INET6: {
1603 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
1604 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
1606 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1607 * scope_id, one without.
1609 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
1610 uaddrlen = sizeof(struct sockaddr_in6);
1611 memset( uaddr, 0, uaddrlen );
1612 uin6->sin6_family = AF_INET6;
1613 uin6->sin6_port = win6->sin6_port;
1614 uin6->sin6_flowinfo = win6->sin6_flowinfo;
1615 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1616 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
1617 #endif
1618 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
1619 break;
1621 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
1622 return 0;
1624 case WS_AF_INET: {
1625 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
1626 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
1628 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
1629 return 0;
1630 uaddrlen = sizeof(struct sockaddr_in);
1631 memset( uaddr, 0, uaddrlen );
1632 uin->sin_family = AF_INET;
1633 uin->sin_port = win->sin_port;
1634 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
1635 break;
1637 #ifdef HAS_IRDA
1638 case WS_AF_IRDA: {
1639 struct sockaddr_irda *uin = (struct sockaddr_irda *)uaddr;
1640 const SOCKADDR_IRDA *win = (const SOCKADDR_IRDA *)wsaddr;
1642 if (wsaddrlen < sizeof(SOCKADDR_IRDA))
1643 return 0;
1644 uaddrlen = sizeof(struct sockaddr_irda);
1645 memset( uaddr, 0, uaddrlen );
1646 uin->sir_family = AF_IRDA;
1647 if (!strncmp( win->irdaServiceName, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1649 unsigned int lsap_sel = 0;
1651 sscanf( win->irdaServiceName, "LSAP-SEL%u", &lsap_sel );
1652 uin->sir_lsap_sel = lsap_sel;
1654 else
1656 uin->sir_lsap_sel = LSAP_ANY;
1657 memcpy( uin->sir_name, win->irdaServiceName, 25 );
1659 memcpy( &uin->sir_addr, win->irdaDeviceID, sizeof(uin->sir_addr) );
1660 break;
1662 #endif
1663 case WS_AF_UNSPEC: {
1664 /* Try to determine the needed space by the passed windows sockaddr space */
1665 switch (wsaddrlen) {
1666 default: /* likely an ipv4 address */
1667 case sizeof(struct WS_sockaddr_in):
1668 uaddrlen = sizeof(struct sockaddr_in);
1669 break;
1670 #ifdef HAS_IPX
1671 case sizeof(struct WS_sockaddr_ipx):
1672 uaddrlen = sizeof(struct sockaddr_ipx);
1673 break;
1674 #endif
1675 #ifdef HAS_IRDA
1676 case sizeof(SOCKADDR_IRDA):
1677 uaddrlen = sizeof(struct sockaddr_irda);
1678 break;
1679 #endif
1680 case sizeof(struct WS_sockaddr_in6):
1681 case sizeof(struct WS_sockaddr_in6_old):
1682 uaddrlen = sizeof(struct sockaddr_in6);
1683 break;
1685 memset( uaddr, 0, uaddrlen );
1686 break;
1688 default:
1689 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
1690 return 0;
1692 return uaddrlen;
1695 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
1697 switch (uaddr->sa_family)
1699 #ifdef HAS_IPX
1700 case AF_IPX:
1702 static const struct sockaddr_ipx emptyAddr;
1703 struct sockaddr_ipx *ipx = (struct sockaddr_ipx*) uaddr;
1704 return ipx->sipx_port
1705 || memcmp(&ipx->sipx_network, &emptyAddr.sipx_network, sizeof(emptyAddr.sipx_network))
1706 || memcmp(&ipx->sipx_node, &emptyAddr.sipx_node, sizeof(emptyAddr.sipx_node));
1708 #endif
1709 case AF_INET6:
1711 static const struct sockaddr_in6 emptyAddr;
1712 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
1713 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
1715 case AF_INET:
1717 static const struct sockaddr_in emptyAddr;
1718 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
1719 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
1721 case AF_UNSPEC:
1722 return FALSE;
1723 default:
1724 FIXME("unknown address family %d\n", uaddr->sa_family);
1725 return TRUE;
1729 /* Returns -1 if getsockname fails, 0 if not bound, 1 otherwise */
1730 static int is_fd_bound(int fd, union generic_unix_sockaddr *uaddr, socklen_t *uaddrlen)
1732 union generic_unix_sockaddr inaddr;
1733 socklen_t inlen;
1734 int res;
1736 if (!uaddr) uaddr = &inaddr;
1737 if (!uaddrlen) uaddrlen = &inlen;
1739 *uaddrlen = sizeof(inaddr);
1740 res = getsockname(fd, &uaddr->addr, uaddrlen);
1741 if (!res) res = is_sockaddr_bound(&uaddr->addr, *uaddrlen);
1742 return res;
1745 /* Returns 0 if successful, -1 if the buffer is too small */
1746 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
1748 int res;
1750 switch(uaddr->sa_family)
1752 #ifdef HAS_IPX
1753 case AF_IPX:
1755 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
1756 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
1758 res=-1;
1759 switch (*wsaddrlen) /* how much can we copy? */
1761 default:
1762 res=0; /* enough */
1763 *wsaddrlen = sizeof(*wsipx);
1764 wsipx->sa_socket=uipx->sipx_port;
1765 /* fall through */
1766 case 13:
1767 case 12:
1768 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
1769 /* fall through */
1770 case 11:
1771 case 10:
1772 case 9:
1773 case 8:
1774 case 7:
1775 case 6:
1776 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1777 /* fall through */
1778 case 5:
1779 case 4:
1780 case 3:
1781 case 2:
1782 wsipx->sa_family=WS_AF_IPX;
1783 /* fall through */
1784 case 1:
1785 case 0:
1786 /* way too small */
1787 break;
1790 break;
1791 #endif
1792 #ifdef HAS_IRDA
1793 case AF_IRDA: {
1794 const struct sockaddr_irda *uin = (const struct sockaddr_irda *)uaddr;
1795 SOCKADDR_IRDA *win = (SOCKADDR_IRDA *)wsaddr;
1797 if (*wsaddrlen < sizeof(SOCKADDR_IRDA))
1798 return -1;
1799 win->irdaAddressFamily = WS_AF_IRDA;
1800 memcpy( win->irdaDeviceID, &uin->sir_addr, sizeof(win->irdaDeviceID) );
1801 if (uin->sir_lsap_sel != LSAP_ANY)
1802 sprintf( win->irdaServiceName, "LSAP-SEL%u", uin->sir_lsap_sel );
1803 else
1804 memcpy( win->irdaServiceName, uin->sir_name,
1805 sizeof(win->irdaServiceName) );
1806 return 0;
1808 #endif
1809 case AF_INET6: {
1810 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1811 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1813 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1814 return -1;
1815 win6old->sin6_family = WS_AF_INET6;
1816 win6old->sin6_port = uin6->sin6_port;
1817 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1818 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1819 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1820 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1821 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1822 win6->sin6_scope_id = uin6->sin6_scope_id;
1823 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1825 else
1826 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1827 #else
1828 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1829 #endif
1830 return 0;
1832 case AF_INET: {
1833 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1834 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1836 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1837 return -1;
1838 win->sin_family = WS_AF_INET;
1839 win->sin_port = uin->sin_port;
1840 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1841 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1842 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1843 return 0;
1845 case AF_UNSPEC: {
1846 memset(wsaddr,0,*wsaddrlen);
1847 return 0;
1849 default:
1850 FIXME("Unknown address family %d\n", uaddr->sa_family);
1851 return -1;
1853 return res;
1856 static INT WS_DuplicateSocket(BOOL unicode, SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo)
1858 HANDLE hProcess;
1859 int size;
1860 WSAPROTOCOL_INFOW infow;
1862 TRACE("(unicode %d, socket %04lx, processid %x, buffer %p)\n",
1863 unicode, s, dwProcessId, lpProtocolInfo);
1865 if (!ws_protocol_info(s, unicode, &infow, &size))
1866 return SOCKET_ERROR;
1868 if (!(hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId)))
1870 SetLastError(WSAEINVAL);
1871 return SOCKET_ERROR;
1874 if (!lpProtocolInfo)
1876 CloseHandle(hProcess);
1877 SetLastError(WSAEFAULT);
1878 return SOCKET_ERROR;
1881 /* I don't know what the real Windoze does next, this is a hack */
1882 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
1883 * the target use the global duplicate, or we could copy a reference to us to the structure
1884 * and let the target duplicate it from us, but let's do it as simple as possible */
1885 memcpy(lpProtocolInfo, &infow, size);
1886 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
1887 hProcess, (LPHANDLE)&lpProtocolInfo->dwServiceFlags3,
1888 0, FALSE, DUPLICATE_SAME_ACCESS);
1889 CloseHandle(hProcess);
1890 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
1891 return 0;
1894 /*****************************************************************************
1895 * WS_EnterSingleProtocolW [internal]
1897 * enters the protocol information of one given protocol into the given
1898 * buffer.
1900 * RETURNS
1901 * TRUE if a protocol was entered into the buffer.
1903 * BUGS
1904 * - only implemented for IPX, SPX, SPXII, TCP, UDP
1905 * - there is no check that the operating system supports the returned
1906 * protocols
1908 static BOOL WS_EnterSingleProtocolW( INT protocol, WSAPROTOCOL_INFOW* info )
1910 memset( info, 0, sizeof(WSAPROTOCOL_INFOW) );
1911 info->iProtocol = protocol;
1913 switch (protocol)
1915 case WS_IPPROTO_TCP:
1916 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_EXPEDITED_DATA |
1917 XP1_GRACEFUL_CLOSE | XP1_GUARANTEED_ORDER |
1918 XP1_GUARANTEED_DELIVERY;
1919 info->ProviderId = ProviderIdIP;
1920 info->dwCatalogEntryId = 0x3e9;
1921 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1922 info->ProtocolChain.ChainLen = 1;
1923 info->iVersion = 2;
1924 info->iAddressFamily = WS_AF_INET;
1925 info->iMaxSockAddr = 0x10;
1926 info->iMinSockAddr = 0x10;
1927 info->iSocketType = WS_SOCK_STREAM;
1928 strcpyW( info->szProtocol, NameTcpW );
1929 break;
1931 case WS_IPPROTO_UDP:
1932 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_SUPPORT_BROADCAST |
1933 XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED |
1934 XP1_CONNECTIONLESS;
1935 info->ProviderId = ProviderIdIP;
1936 info->dwCatalogEntryId = 0x3ea;
1937 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1938 info->ProtocolChain.ChainLen = 1;
1939 info->iVersion = 2;
1940 info->iAddressFamily = WS_AF_INET;
1941 info->iMaxSockAddr = 0x10;
1942 info->iMinSockAddr = 0x10;
1943 info->iSocketType = WS_SOCK_DGRAM;
1944 info->dwMessageSize = 0xffbb;
1945 strcpyW( info->szProtocol, NameUdpW );
1946 break;
1948 case WS_NSPROTO_IPX:
1949 info->dwServiceFlags1 = XP1_PARTIAL_MESSAGE | XP1_SUPPORT_BROADCAST |
1950 XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED |
1951 XP1_CONNECTIONLESS;
1952 info->ProviderId = ProviderIdIPX;
1953 info->dwCatalogEntryId = 0x406;
1954 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1955 info->ProtocolChain.ChainLen = 1;
1956 info->iVersion = 2;
1957 info->iAddressFamily = WS_AF_IPX;
1958 info->iMaxSockAddr = 0x10;
1959 info->iMinSockAddr = 0x0e;
1960 info->iSocketType = WS_SOCK_DGRAM;
1961 info->iProtocolMaxOffset = 0xff;
1962 info->dwMessageSize = 0x240;
1963 strcpyW( info->szProtocol, NameIpxW );
1964 break;
1966 case WS_NSPROTO_SPX:
1967 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_PSEUDO_STREAM |
1968 XP1_MESSAGE_ORIENTED | XP1_GUARANTEED_ORDER |
1969 XP1_GUARANTEED_DELIVERY;
1970 info->ProviderId = ProviderIdSPX;
1971 info->dwCatalogEntryId = 0x407;
1972 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1973 info->ProtocolChain.ChainLen = 1;
1974 info->iVersion = 2;
1975 info->iAddressFamily = WS_AF_IPX;
1976 info->iMaxSockAddr = 0x10;
1977 info->iMinSockAddr = 0x0e;
1978 info->iSocketType = WS_SOCK_SEQPACKET;
1979 info->dwMessageSize = 0xffffffff;
1980 strcpyW( info->szProtocol, NameSpxW );
1981 break;
1983 case WS_NSPROTO_SPXII:
1984 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_GRACEFUL_CLOSE |
1985 XP1_PSEUDO_STREAM | XP1_MESSAGE_ORIENTED |
1986 XP1_GUARANTEED_ORDER | XP1_GUARANTEED_DELIVERY;
1987 info->ProviderId = ProviderIdSPX;
1988 info->dwCatalogEntryId = 0x409;
1989 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1990 info->ProtocolChain.ChainLen = 1;
1991 info->iVersion = 2;
1992 info->iAddressFamily = WS_AF_IPX;
1993 info->iMaxSockAddr = 0x10;
1994 info->iMinSockAddr = 0x0e;
1995 info->iSocketType = WS_SOCK_SEQPACKET;
1996 info->dwMessageSize = 0xffffffff;
1997 strcpyW( info->szProtocol, NameSpxIIW );
1998 break;
2000 default:
2001 FIXME("unknown Protocol <0x%08x>\n", protocol);
2002 return FALSE;
2004 return TRUE;
2007 /*****************************************************************************
2008 * WS_EnterSingleProtocolA [internal]
2010 * see function WS_EnterSingleProtocolW
2013 static BOOL WS_EnterSingleProtocolA( INT protocol, WSAPROTOCOL_INFOA* info )
2015 WSAPROTOCOL_INFOW infow;
2016 INT ret;
2017 memset( info, 0, sizeof(WSAPROTOCOL_INFOA) );
2019 ret = WS_EnterSingleProtocolW( protocol, &infow );
2020 if (ret)
2022 /* convert the structure from W to A */
2023 memcpy( info, &infow, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
2024 WideCharToMultiByte( CP_ACP, 0, infow.szProtocol, -1,
2025 info->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL );
2028 return ret;
2031 static INT WS_EnumProtocols( BOOL unicode, const INT *protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
2033 INT i = 0, items = 0;
2034 DWORD size = 0;
2035 union _info
2037 LPWSAPROTOCOL_INFOA a;
2038 LPWSAPROTOCOL_INFOW w;
2039 } info;
2040 info.w = buffer;
2042 if (!protocols) protocols = valid_protocols;
2044 while (protocols[i])
2046 if(supported_protocol(protocols[i++]))
2047 items++;
2050 size = items * (unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA));
2052 TRACE("unicode %d, protocols %p, buffer %p, length %p %d, items %d, required %d\n",
2053 unicode, protocols, buffer, len, len ? *len : 0, items, size);
2055 if (*len < size || !buffer)
2057 *len = size;
2058 SetLastError(WSAENOBUFS);
2059 return SOCKET_ERROR;
2062 for (i = items = 0; protocols[i]; i++)
2064 if (!supported_protocol(protocols[i])) continue;
2065 if (unicode)
2067 if (WS_EnterSingleProtocolW( protocols[i], &info.w[items] ))
2068 items++;
2070 else
2072 if (WS_EnterSingleProtocolA( protocols[i], &info.a[items] ))
2073 items++;
2076 return items;
2079 static BOOL ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size)
2081 NTSTATUS status;
2083 *size = unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA);
2084 memset(buffer, 0, *size);
2086 SERVER_START_REQ( get_socket_info )
2088 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
2089 status = wine_server_call( req );
2090 if (!status)
2092 buffer->iAddressFamily = convert_af_u2w(reply->family);
2093 buffer->iSocketType = convert_socktype_u2w(reply->type);
2094 buffer->iProtocol = convert_proto_u2w(reply->protocol);
2097 SERVER_END_REQ;
2099 if (status)
2101 unsigned int err = NtStatusToWSAError( status );
2102 SetLastError( err == WSAEBADF ? WSAENOTSOCK : err );
2103 return FALSE;
2106 if (unicode)
2107 WS_EnterSingleProtocolW( buffer->iProtocol, buffer);
2108 else
2109 WS_EnterSingleProtocolA( buffer->iProtocol, (WSAPROTOCOL_INFOA *)buffer);
2111 return TRUE;
2114 /**************************************************************************
2115 * Functions for handling overlapped I/O
2116 **************************************************************************/
2118 /* user APC called upon async completion */
2119 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
2121 struct ws2_async *wsa = arg;
2123 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
2124 iosb->Information, wsa->user_overlapped,
2125 wsa->flags );
2126 release_async_io( &wsa->io );
2129 /***********************************************************************
2130 * WS2_recv (INTERNAL)
2132 * Workhorse for both synchronous and asynchronous recv() operations.
2134 static int WS2_recv( int fd, struct ws2_async *wsa, int flags )
2136 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2137 char pktbuf[512];
2138 #endif
2139 struct msghdr hdr;
2140 union generic_unix_sockaddr unix_sockaddr;
2141 int n;
2143 hdr.msg_name = NULL;
2145 if (wsa->addr)
2147 hdr.msg_namelen = sizeof(unix_sockaddr);
2148 hdr.msg_name = &unix_sockaddr;
2150 else
2151 hdr.msg_namelen = 0;
2153 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
2154 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
2155 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2156 hdr.msg_accrights = NULL;
2157 hdr.msg_accrightslen = 0;
2158 #else
2159 hdr.msg_control = pktbuf;
2160 hdr.msg_controllen = sizeof(pktbuf);
2161 hdr.msg_flags = 0;
2162 #endif
2164 while ((n = recvmsg(fd, &hdr, flags)) == -1)
2166 if (errno != EINTR)
2167 return -1;
2170 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2171 if (wsa->control)
2173 ERR("Message control headers cannot be properly supported on this system.\n");
2174 wsa->control->len = 0;
2176 #else
2177 if (wsa->control && !convert_control_headers(&hdr, wsa->control))
2179 WARN("Application passed insufficient room for control headers.\n");
2180 *wsa->lpFlags |= WS_MSG_CTRUNC;
2181 errno = EMSGSIZE;
2182 return -1;
2184 #endif
2186 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
2187 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
2189 * quoting linux 2.6 net/ipv4/tcp.c:
2190 * "According to UNIX98, msg_name/msg_namelen are ignored
2191 * on connected socket. I was just happy when found this 8) --ANK"
2193 * likewise MSDN says that lpFrom and lpFromlen are ignored for
2194 * connection-oriented sockets, so don't try to update lpFrom.
2196 if (wsa->addr && hdr.msg_namelen)
2197 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
2199 return n;
2202 /***********************************************************************
2203 * WS2_async_recv (INTERNAL)
2205 * Handler for overlapped recv() operations.
2207 static NTSTATUS WS2_async_recv( void *user, IO_STATUS_BLOCK *iosb,
2208 NTSTATUS status, void **apc, void **arg )
2210 struct ws2_async *wsa = user;
2211 int result = 0, fd;
2213 switch (status)
2215 case STATUS_ALERTED:
2216 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
2217 break;
2219 result = WS2_recv( fd, wsa, convert_flags(wsa->flags) );
2220 wine_server_release_fd( wsa->hSocket, fd );
2221 if (result >= 0)
2223 status = STATUS_SUCCESS;
2224 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
2226 else
2228 if (errno == EAGAIN)
2230 status = STATUS_PENDING;
2231 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
2233 else
2235 result = 0;
2236 status = wsaErrStatus();
2239 break;
2241 if (status != STATUS_PENDING)
2243 iosb->u.Status = status;
2244 iosb->Information = result;
2245 if (wsa->completion_func)
2247 *apc = ws2_async_apc;
2248 *arg = wsa;
2250 else
2251 release_async_io( &wsa->io );
2253 return status;
2256 /***********************************************************************
2257 * WS2_async_accept_recv (INTERNAL)
2259 * This function is used to finish the read part of an accept request. It is
2260 * needed to place the completion on the correct socket (listener).
2262 static NTSTATUS WS2_async_accept_recv( void *user, IO_STATUS_BLOCK *iosb,
2263 NTSTATUS status, void **apc, void **arg )
2265 void *junk;
2266 struct ws2_accept_async *wsa = user;
2268 status = WS2_async_recv( wsa->read, iosb, status, &junk, &junk );
2269 if (status == STATUS_PENDING)
2270 return status;
2272 if (wsa->cvalue)
2273 WS_AddCompletion( HANDLE2SOCKET(wsa->listen_socket), wsa->cvalue, iosb->u.Status, iosb->Information );
2275 release_async_io( &wsa->io );
2276 return status;
2279 /***********************************************************************
2280 * WS2_async_accept (INTERNAL)
2282 * This is the function called to satisfy the AcceptEx callback
2284 static NTSTATUS WS2_async_accept( void *user, IO_STATUS_BLOCK *iosb,
2285 NTSTATUS status, void **apc, void **arg )
2287 struct ws2_accept_async *wsa = user;
2288 int len;
2289 char *addr;
2291 TRACE("status: 0x%x listen: %p, accept: %p\n", status, wsa->listen_socket, wsa->accept_socket);
2293 if (status == STATUS_ALERTED)
2295 SERVER_START_REQ( accept_into_socket )
2297 req->lhandle = wine_server_obj_handle( wsa->listen_socket );
2298 req->ahandle = wine_server_obj_handle( wsa->accept_socket );
2299 status = wine_server_call( req );
2301 SERVER_END_REQ;
2303 if (status == STATUS_CANT_WAIT)
2304 return STATUS_PENDING;
2306 if (status == STATUS_INVALID_HANDLE)
2308 FIXME("AcceptEx accepting socket closed but request was not cancelled\n");
2309 status = STATUS_CANCELLED;
2312 else if (status == STATUS_HANDLES_CLOSED)
2313 status = STATUS_CANCELLED; /* strange windows behavior */
2315 if (status != STATUS_SUCCESS)
2316 goto finish;
2318 /* WS2 Spec says size param is extra 16 bytes long...what do we put in it? */
2319 addr = ((char *)wsa->buf) + wsa->data_len;
2320 len = wsa->local_len - sizeof(int);
2321 WS_getsockname(HANDLE2SOCKET(wsa->accept_socket),
2322 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
2323 *(int *)addr = len;
2325 addr += wsa->local_len;
2326 len = wsa->remote_len - sizeof(int);
2327 WS_getpeername(HANDLE2SOCKET(wsa->accept_socket),
2328 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
2329 *(int *)addr = len;
2331 if (!wsa->read)
2332 goto finish;
2334 SERVER_START_REQ( register_async )
2336 req->type = ASYNC_TYPE_READ;
2337 req->async.handle = wine_server_obj_handle( wsa->accept_socket );
2338 req->async.event = wine_server_obj_handle( wsa->user_overlapped->hEvent );
2339 req->async.callback = wine_server_client_ptr( WS2_async_accept_recv );
2340 req->async.iosb = wine_server_client_ptr( iosb );
2341 req->async.arg = wine_server_client_ptr( wsa );
2342 status = wine_server_call( req );
2344 SERVER_END_REQ;
2346 if (status != STATUS_PENDING)
2347 goto finish;
2349 /* The APC has finished but no completion should be sent for the operation yet, additional processing
2350 * needs to be performed by WS2_async_accept_recv() first. */
2351 return STATUS_MORE_PROCESSING_REQUIRED;
2353 finish:
2354 iosb->u.Status = status;
2355 iosb->Information = 0;
2357 if (wsa->read) release_async_io( &wsa->read->io );
2358 release_async_io( &wsa->io );
2359 return status;
2362 /***********************************************************************
2363 * WS2_send (INTERNAL)
2365 * Workhorse for both synchronous and asynchronous send() operations.
2367 static int WS2_send( int fd, struct ws2_async *wsa, int flags )
2369 struct msghdr hdr;
2370 union generic_unix_sockaddr unix_addr;
2371 int n, ret;
2373 hdr.msg_name = NULL;
2374 hdr.msg_namelen = 0;
2376 if (wsa->addr)
2378 hdr.msg_name = &unix_addr;
2379 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
2380 if ( !hdr.msg_namelen )
2382 errno = EFAULT;
2383 return -1;
2386 #if defined(HAS_IPX) && defined(SOL_IPX)
2387 if(wsa->addr->sa_family == WS_AF_IPX)
2389 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
2390 int val=0;
2391 socklen_t len = sizeof(int);
2393 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
2394 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
2395 * the packet type and then we can retrieve it using getsockopt. After that we can set the
2396 * ipx type in the sockaddr_opx structure with the stored value.
2398 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
2399 uipx->sipx_type = val;
2401 #endif
2404 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
2405 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
2406 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2407 hdr.msg_accrights = NULL;
2408 hdr.msg_accrightslen = 0;
2409 #else
2410 hdr.msg_control = NULL;
2411 hdr.msg_controllen = 0;
2412 hdr.msg_flags = 0;
2413 #endif
2415 while ((ret = sendmsg(fd, &hdr, flags)) == -1)
2417 if (errno != EINTR)
2418 return -1;
2421 n = ret;
2422 while (wsa->first_iovec < wsa->n_iovecs && wsa->iovec[wsa->first_iovec].iov_len <= n)
2423 n -= wsa->iovec[wsa->first_iovec++].iov_len;
2424 if (wsa->first_iovec < wsa->n_iovecs)
2426 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
2427 wsa->iovec[wsa->first_iovec].iov_len -= n;
2429 return ret;
2432 /***********************************************************************
2433 * WS2_async_send (INTERNAL)
2435 * Handler for overlapped send() operations.
2437 static NTSTATUS WS2_async_send( void *user, IO_STATUS_BLOCK *iosb,
2438 NTSTATUS status, void **apc, void **arg )
2440 struct ws2_async *wsa = user;
2441 int result = 0, fd;
2443 switch (status)
2445 case STATUS_ALERTED:
2446 if ( wsa->n_iovecs <= wsa->first_iovec )
2448 /* Nothing to do */
2449 status = STATUS_SUCCESS;
2450 break;
2452 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
2453 break;
2455 /* check to see if the data is ready (non-blocking) */
2456 result = WS2_send( fd, wsa, convert_flags(wsa->flags) );
2457 wine_server_release_fd( wsa->hSocket, fd );
2459 if (result >= 0)
2461 if (wsa->first_iovec < wsa->n_iovecs)
2462 status = STATUS_PENDING;
2463 else
2464 status = STATUS_SUCCESS;
2466 iosb->Information += result;
2468 else if (errno == EAGAIN)
2470 status = STATUS_PENDING;
2472 else
2474 status = wsaErrStatus();
2476 break;
2478 if (status != STATUS_PENDING)
2480 iosb->u.Status = status;
2481 if (wsa->completion_func)
2483 *apc = ws2_async_apc;
2484 *arg = wsa;
2486 else
2487 release_async_io( &wsa->io );
2489 return status;
2492 /***********************************************************************
2493 * WS2_async_shutdown (INTERNAL)
2495 * Handler for shutdown() operations on overlapped sockets.
2497 static NTSTATUS WS2_async_shutdown( void *user, IO_STATUS_BLOCK *iosb,
2498 NTSTATUS status, void **apc, void **arg )
2500 struct ws2_async_shutdown *wsa = user;
2501 int fd, err = 1;
2503 switch (status)
2505 case STATUS_ALERTED:
2506 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
2507 break;
2509 switch ( wsa->type )
2511 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
2512 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
2514 status = err ? wsaErrStatus() : STATUS_SUCCESS;
2515 wine_server_release_fd( wsa->hSocket, fd );
2516 break;
2518 iosb->u.Status = status;
2519 iosb->Information = 0;
2520 release_async_io( &wsa->io );
2521 return status;
2524 /***********************************************************************
2525 * WS2_register_async_shutdown (INTERNAL)
2527 * Helper function for WS_shutdown() on overlapped sockets.
2529 static int WS2_register_async_shutdown( SOCKET s, int type )
2531 struct ws2_async_shutdown *wsa;
2532 NTSTATUS status;
2534 TRACE("socket %04lx type %d\n", s, type);
2536 wsa = (struct ws2_async_shutdown *)alloc_async_io( sizeof(*wsa) );
2537 if ( !wsa )
2538 return WSAEFAULT;
2540 wsa->hSocket = SOCKET2HANDLE(s);
2541 wsa->type = type;
2543 SERVER_START_REQ( register_async )
2545 req->type = type;
2546 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2547 req->async.callback = wine_server_client_ptr( WS2_async_shutdown );
2548 req->async.iosb = wine_server_client_ptr( &wsa->iosb );
2549 req->async.arg = wine_server_client_ptr( wsa );
2550 req->async.cvalue = 0;
2551 status = wine_server_call( req );
2553 SERVER_END_REQ;
2555 if (status != STATUS_PENDING)
2557 HeapFree( GetProcessHeap(), 0, wsa );
2558 return NtStatusToWSAError( status );
2560 return 0;
2563 /***********************************************************************
2564 * accept (WS2_32.1)
2566 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr, int *addrlen32)
2568 NTSTATUS status;
2569 SOCKET as;
2570 BOOL is_blocking;
2572 TRACE("socket %04lx\n", s );
2573 status = _is_blocking(s, &is_blocking);
2574 if (status)
2576 set_error(status);
2577 return INVALID_SOCKET;
2580 do {
2581 /* try accepting first (if there is a deferred connection) */
2582 SERVER_START_REQ( accept_socket )
2584 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
2585 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
2586 req->attributes = OBJ_INHERIT;
2587 status = wine_server_call( req );
2588 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
2590 SERVER_END_REQ;
2591 if (!status)
2593 if (addr && WS_getpeername(as, addr, addrlen32))
2595 WS_closesocket(as);
2596 return SOCKET_ERROR;
2598 TRACE("\taccepted %04lx\n", as);
2599 return as;
2601 if (is_blocking && status == STATUS_CANT_WAIT)
2603 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2604 /* block here */
2605 do_block(fd, POLLIN, -1);
2606 _sync_sock_state(s); /* let wineserver notice connection */
2607 release_sock_fd( s, fd );
2609 } while (is_blocking && status == STATUS_CANT_WAIT);
2611 set_error(status);
2612 return INVALID_SOCKET;
2615 /***********************************************************************
2616 * AcceptEx
2618 static BOOL WINAPI WS2_AcceptEx(SOCKET listener, SOCKET acceptor, PVOID dest, DWORD dest_len,
2619 DWORD local_addr_len, DWORD rem_addr_len, LPDWORD received,
2620 LPOVERLAPPED overlapped)
2622 DWORD status;
2623 struct ws2_accept_async *wsa;
2624 int fd;
2626 TRACE("(%04lx, %04lx, %p, %d, %d, %d, %p, %p)\n", listener, acceptor, dest, dest_len, local_addr_len,
2627 rem_addr_len, received, overlapped);
2629 if (!dest)
2631 SetLastError(WSAEINVAL);
2632 return FALSE;
2635 if (!overlapped)
2637 SetLastError(WSA_INVALID_PARAMETER);
2638 return FALSE;
2641 if (!rem_addr_len)
2643 SetLastError(WSAEFAULT);
2644 return FALSE;
2647 fd = get_sock_fd( listener, FILE_READ_DATA, NULL );
2648 if (fd == -1)
2650 SetLastError(WSAENOTSOCK);
2651 return FALSE;
2653 release_sock_fd( listener, fd );
2655 fd = get_sock_fd( acceptor, FILE_READ_DATA, NULL );
2656 if (fd == -1)
2658 SetLastError(WSAENOTSOCK);
2659 return FALSE;
2661 release_sock_fd( acceptor, fd );
2663 wsa = (struct ws2_accept_async *)alloc_async_io( sizeof(*wsa) );
2664 if(!wsa)
2666 SetLastError(WSAEFAULT);
2667 return FALSE;
2670 wsa->listen_socket = SOCKET2HANDLE(listener);
2671 wsa->accept_socket = SOCKET2HANDLE(acceptor);
2672 wsa->user_overlapped = overlapped;
2673 wsa->cvalue = !((ULONG_PTR)overlapped->hEvent & 1) ? (ULONG_PTR)overlapped : 0;
2674 wsa->buf = dest;
2675 wsa->data_len = dest_len;
2676 wsa->local_len = local_addr_len;
2677 wsa->remote_len = rem_addr_len;
2678 wsa->read = NULL;
2680 if (wsa->data_len)
2682 /* set up a read request if we need it */
2683 wsa->read = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[1]) );
2684 if (!wsa->read)
2686 HeapFree( GetProcessHeap(), 0, wsa );
2687 SetLastError(WSAEFAULT);
2688 return FALSE;
2691 wsa->read->hSocket = wsa->accept_socket;
2692 wsa->read->flags = 0;
2693 wsa->read->lpFlags = &wsa->read->flags;
2694 wsa->read->addr = NULL;
2695 wsa->read->addrlen.ptr = NULL;
2696 wsa->read->control = NULL;
2697 wsa->read->n_iovecs = 1;
2698 wsa->read->first_iovec = 0;
2699 wsa->read->completion_func = NULL;
2700 wsa->read->iovec[0].iov_base = wsa->buf;
2701 wsa->read->iovec[0].iov_len = wsa->data_len;
2704 SERVER_START_REQ( register_async )
2706 req->type = ASYNC_TYPE_READ;
2707 req->async.handle = wine_server_obj_handle( SOCKET2HANDLE(listener) );
2708 req->async.event = wine_server_obj_handle( overlapped->hEvent );
2709 req->async.callback = wine_server_client_ptr( WS2_async_accept );
2710 req->async.iosb = wine_server_client_ptr( overlapped );
2711 req->async.arg = wine_server_client_ptr( wsa );
2712 req->async.cvalue = wsa->cvalue;
2713 status = wine_server_call( req );
2715 SERVER_END_REQ;
2717 if(status != STATUS_PENDING)
2719 HeapFree( GetProcessHeap(), 0, wsa->read );
2720 HeapFree( GetProcessHeap(), 0, wsa );
2723 SetLastError( NtStatusToWSAError(status) );
2724 return FALSE;
2727 /***********************************************************************
2728 * GetAcceptExSockaddrs
2730 static void WINAPI WS2_GetAcceptExSockaddrs(PVOID buffer, DWORD data_size, DWORD local_size, DWORD remote_size,
2731 struct WS_sockaddr **local_addr, LPINT local_addr_len,
2732 struct WS_sockaddr **remote_addr, LPINT remote_addr_len)
2734 char *cbuf = buffer;
2735 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer, data_size, local_size, remote_size, local_addr,
2736 local_addr_len, remote_addr, remote_addr_len );
2737 cbuf += data_size;
2739 *local_addr_len = *(int *) cbuf;
2740 *local_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2742 cbuf += local_size;
2744 *remote_addr_len = *(int *) cbuf;
2745 *remote_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2748 /***********************************************************************
2749 * WSASendMsg
2751 int WINAPI WSASendMsg( SOCKET s, LPWSAMSG msg, DWORD dwFlags, LPDWORD lpNumberOfBytesSent,
2752 LPWSAOVERLAPPED lpOverlapped,
2753 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
2755 if (!msg)
2757 SetLastError( WSAEFAULT );
2758 return SOCKET_ERROR;
2761 return WS2_sendto( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesSent,
2762 dwFlags, msg->name, msg->namelen,
2763 lpOverlapped, lpCompletionRoutine );
2766 /***********************************************************************
2767 * WSARecvMsg
2769 * Perform a receive operation that is capable of returning message
2770 * control headers. It is important to note that the WSAMSG parameter
2771 * must remain valid throughout the operation, even when an overlapped
2772 * receive is performed.
2774 static int WINAPI WS2_WSARecvMsg( SOCKET s, LPWSAMSG msg, LPDWORD lpNumberOfBytesRecvd,
2775 LPWSAOVERLAPPED lpOverlapped,
2776 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2778 if (!msg)
2780 SetLastError( WSAEFAULT );
2781 return SOCKET_ERROR;
2784 return WS2_recv_base( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesRecvd,
2785 &msg->dwFlags, msg->name, &msg->namelen,
2786 lpOverlapped, lpCompletionRoutine, &msg->Control );
2789 /***********************************************************************
2790 * interface_bind (INTERNAL)
2792 * Take bind() calls on any name corresponding to a local network adapter and restrict the given socket to
2793 * operating only on the specified interface. This restriction consists of two components:
2794 * 1) An outgoing packet restriction suggesting the egress interface for all packets.
2795 * 2) An incoming packet restriction dropping packets not meant for the interface.
2796 * If the function succeeds in placing these restrictions (returns TRUE) then the name for the bind() may
2797 * safely be changed to INADDR_ANY, permitting the transmission and receipt of broadcast packets on the
2798 * socket. This behavior is only relevant to UDP sockets and is needed for applications that expect to be able
2799 * to receive broadcast packets on a socket that is bound to a specific network interface.
2801 static BOOL interface_bind( SOCKET s, int fd, struct sockaddr *addr )
2803 struct sockaddr_in *in_sock = (struct sockaddr_in *) addr;
2804 in_addr_t bind_addr = in_sock->sin_addr.s_addr;
2805 PIP_ADAPTER_INFO adapters = NULL, adapter;
2806 BOOL ret = FALSE;
2807 DWORD adap_size;
2808 int enable = 1;
2810 if (bind_addr == htonl(INADDR_ANY) || bind_addr == htonl(INADDR_LOOPBACK))
2811 return FALSE; /* Not binding to a network adapter, special interface binding unnecessary. */
2812 if (_get_fd_type(fd) != SOCK_DGRAM)
2813 return FALSE; /* Special interface binding is only necessary for UDP datagrams. */
2814 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
2815 goto cleanup;
2816 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
2817 if (adapters == NULL || GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
2818 goto cleanup;
2819 /* Search the IPv4 adapter list for the appropriate binding interface */
2820 for (adapter = adapters; adapter != NULL; adapter = adapter->Next)
2822 in_addr_t adapter_addr = (in_addr_t) inet_addr(adapter->IpAddressList.IpAddress.String);
2824 if (bind_addr == adapter_addr)
2826 #if defined(IP_BOUND_IF)
2827 /* IP_BOUND_IF sets both the incoming and outgoing restriction at once */
2828 if (setsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &adapter->Index, sizeof(adapter->Index)) != 0)
2829 goto cleanup;
2830 ret = TRUE;
2831 #elif defined(LINUX_BOUND_IF)
2832 in_addr_t ifindex = (in_addr_t) htonl(adapter->Index);
2833 struct interface_filter specific_interface_filter;
2834 struct sock_fprog filter_prog;
2836 if (setsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex, sizeof(ifindex)) != 0)
2837 goto cleanup; /* Failed to suggest egress interface */
2838 specific_interface_filter = generic_interface_filter;
2839 specific_interface_filter.iface_rule.k = adapter->Index;
2840 specific_interface_filter.ip_rule.k = htonl(adapter_addr);
2841 filter_prog.len = sizeof(generic_interface_filter)/sizeof(struct sock_filter);
2842 filter_prog.filter = (struct sock_filter *) &specific_interface_filter;
2843 if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog, sizeof(filter_prog)) != 0)
2844 goto cleanup; /* Failed to specify incoming packet filter */
2845 ret = TRUE;
2846 #else
2847 FIXME("Broadcast packets on interface-bound sockets are not currently supported on this platform, "
2848 "receiving broadcast packets will not work on socket %04lx.\n", s);
2849 #endif
2850 break;
2853 /* Will soon be switching to INADDR_ANY: permit address reuse */
2854 if (ret && setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) == 0)
2855 TRACE("Socket %04lx bound to interface index %d\n", s, adapter->Index);
2856 else
2857 ret = FALSE;
2859 cleanup:
2860 if(!ret)
2861 ERR("Failed to bind to interface, receiving broadcast packets will not work on socket %04lx.\n", s);
2862 HeapFree(GetProcessHeap(), 0, adapters);
2863 return ret;
2866 /***********************************************************************
2867 * bind (WS2_32.2)
2869 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
2871 int fd = get_sock_fd( s, 0, NULL );
2872 int res = SOCKET_ERROR;
2874 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2876 if (fd != -1)
2878 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
2880 SetLastError(WSAEAFNOSUPPORT);
2882 else
2884 union generic_unix_sockaddr uaddr;
2885 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2886 if (!uaddrlen)
2888 SetLastError(WSAEFAULT);
2890 else
2892 #ifdef IPV6_V6ONLY
2893 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
2894 if (name->sa_family == WS_AF_INET6 &&
2895 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
2897 int enable = 1;
2898 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
2900 release_sock_fd( s, fd );
2901 SetLastError(WSAEAFNOSUPPORT);
2902 return SOCKET_ERROR;
2905 #endif
2906 if (name->sa_family == WS_AF_INET)
2908 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2909 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2911 /* Trying to bind to the default host interface, using
2912 * INADDR_ANY instead*/
2913 WARN("Trying to bind to magic IP address, using "
2914 "INADDR_ANY instead.\n");
2915 in4->sin_addr.s_addr = htonl(INADDR_ANY);
2917 else if (interface_bind(s, fd, &uaddr.addr))
2918 in4->sin_addr.s_addr = htonl(INADDR_ANY);
2920 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
2922 int loc_errno = errno;
2923 WARN("\tfailure - errno = %i\n", errno);
2924 errno = loc_errno;
2925 switch (errno)
2927 case EADDRNOTAVAIL:
2928 SetLastError(WSAEINVAL);
2929 break;
2930 case EADDRINUSE:
2932 int optval = 0;
2933 socklen_t optlen = sizeof(optval);
2934 /* Windows >= 2003 will return different results depending on
2935 * SO_REUSEADDR, WSAEACCES may be returned representing that
2936 * the socket hijacking protection prevented the bind */
2937 if (!getsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&optval, &optlen) && optval)
2939 SetLastError(WSAEACCES);
2940 break;
2942 /* fall through */
2944 default:
2945 SetLastError(wsaErrno());
2946 break;
2949 else
2951 res=0; /* success */
2955 release_sock_fd( s, fd );
2957 return res;
2960 /***********************************************************************
2961 * closesocket (WS2_32.3)
2963 int WINAPI WS_closesocket(SOCKET s)
2965 int res = SOCKET_ERROR, fd;
2966 if (num_startup)
2968 fd = get_sock_fd(s, FILE_READ_DATA, NULL);
2969 if (fd >= 0)
2971 release_sock_fd(s, fd);
2972 if (CloseHandle(SOCKET2HANDLE(s)))
2973 res = 0;
2975 else
2976 SetLastError(WSAENOTSOCK);
2978 else
2979 SetLastError(WSANOTINITIALISED);
2980 TRACE("(socket %04lx) -> %d\n", s, res);
2981 return res;
2984 static int do_connect(int fd, const struct WS_sockaddr* name, int namelen)
2986 union generic_unix_sockaddr uaddr;
2987 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2989 if (!uaddrlen)
2990 return WSAEFAULT;
2992 if (name->sa_family == WS_AF_INET)
2994 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2995 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2997 /* Trying to connect to magic replace-loopback address,
2998 * assuming we really want to connect to localhost */
2999 TRACE("Trying to connect to magic IP address, using "
3000 "INADDR_LOOPBACK instead.\n");
3001 in4->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
3005 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
3006 return 0;
3008 return wsaErrno();
3011 /***********************************************************************
3012 * connect (WS2_32.4)
3014 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
3016 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
3018 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
3020 if (fd != -1)
3022 NTSTATUS status;
3023 BOOL is_blocking;
3024 int ret = do_connect(fd, name, namelen);
3025 if (ret == 0)
3026 goto connect_success;
3028 if (ret == WSAEINPROGRESS)
3030 /* tell wineserver that a connection is in progress */
3031 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3032 FD_CONNECT,
3033 FD_WINE_CONNECTED|FD_WINE_LISTENING);
3034 status = _is_blocking( s, &is_blocking );
3035 if (status)
3037 release_sock_fd( s, fd );
3038 set_error( status );
3039 return SOCKET_ERROR;
3041 if (is_blocking)
3043 int result;
3044 /* block here */
3045 do_block(fd, POLLIN | POLLOUT, -1);
3046 _sync_sock_state(s); /* let wineserver notice connection */
3047 /* retrieve any error codes from it */
3048 result = _get_sock_error(s, FD_CONNECT_BIT);
3049 if (result)
3050 SetLastError(NtStatusToWSAError(result));
3051 else
3053 goto connect_success;
3056 else
3058 SetLastError(WSAEWOULDBLOCK);
3061 else
3063 SetLastError(ret);
3065 release_sock_fd( s, fd );
3067 return SOCKET_ERROR;
3069 connect_success:
3070 release_sock_fd( s, fd );
3071 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3072 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
3073 FD_CONNECT|FD_WINE_LISTENING);
3074 TRACE("\tconnected %04lx\n", s);
3075 return 0;
3078 /***********************************************************************
3079 * WSAConnect (WS2_32.30)
3081 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
3082 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
3083 LPQOS lpSQOS, LPQOS lpGQOS )
3085 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
3086 FIXME("unsupported parameters!\n");
3087 return WS_connect( s, name, namelen );
3090 /***********************************************************************
3091 * ConnectEx
3093 static BOOL WINAPI WS2_ConnectEx(SOCKET s, const struct WS_sockaddr* name, int namelen,
3094 PVOID sendBuf, DWORD sendBufLen, LPDWORD sent, LPOVERLAPPED ov)
3096 int fd, ret, status;
3098 if (!ov)
3100 SetLastError( ERROR_INVALID_PARAMETER );
3101 return FALSE;
3104 fd = get_sock_fd( s, FILE_READ_DATA, NULL );
3105 if (fd == -1)
3107 SetLastError( WSAENOTSOCK );
3108 return FALSE;
3111 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
3112 s, name, debugstr_sockaddr(name), namelen, sendBuf, sendBufLen, ov);
3114 ret = is_fd_bound(fd, NULL, NULL);
3115 if (ret <= 0)
3117 SetLastError(ret == -1 ? wsaErrno() : WSAEINVAL);
3118 release_sock_fd( s, fd );
3119 return FALSE;
3122 ret = do_connect(fd, name, namelen);
3123 if (ret == 0)
3125 WSABUF wsabuf;
3127 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3128 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
3129 FD_CONNECT|FD_WINE_LISTENING);
3131 wsabuf.len = sendBufLen;
3132 wsabuf.buf = (char*) sendBuf;
3134 /* WSASend takes care of completion if need be */
3135 if (WSASend(s, &wsabuf, sendBuf ? 1 : 0, sent, 0, ov, NULL) != SOCKET_ERROR)
3136 goto connection_success;
3138 else if (ret == WSAEINPROGRESS)
3140 struct ws2_async *wsa;
3141 ULONG_PTR cvalue = (((ULONG_PTR)ov->hEvent & 1) == 0) ? (ULONG_PTR)ov : 0;
3143 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3144 FD_CONNECT,
3145 FD_WINE_CONNECTED|FD_WINE_LISTENING);
3147 /* Indirectly call WSASend */
3148 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof( struct ws2_async, iovec[1] ))))
3150 SetLastError(WSAEFAULT);
3152 else
3154 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)ov;
3155 iosb->u.Status = STATUS_PENDING;
3156 iosb->Information = 0;
3158 wsa->hSocket = SOCKET2HANDLE(s);
3159 wsa->addr = NULL;
3160 wsa->addrlen.val = 0;
3161 wsa->flags = 0;
3162 wsa->lpFlags = &wsa->flags;
3163 wsa->control = NULL;
3164 wsa->n_iovecs = sendBuf ? 1 : 0;
3165 wsa->first_iovec = 0;
3166 wsa->completion_func = NULL;
3167 wsa->iovec[0].iov_base = sendBuf;
3168 wsa->iovec[0].iov_len = sendBufLen;
3170 SERVER_START_REQ( register_async )
3172 req->type = ASYNC_TYPE_WRITE;
3173 req->async.handle = wine_server_obj_handle( wsa->hSocket );
3174 req->async.callback = wine_server_client_ptr( WS2_async_send );
3175 req->async.iosb = wine_server_client_ptr( iosb );
3176 req->async.arg = wine_server_client_ptr( wsa );
3177 req->async.event = wine_server_obj_handle( ov->hEvent );
3178 req->async.cvalue = cvalue;
3179 status = wine_server_call( req );
3181 SERVER_END_REQ;
3183 if (status != STATUS_PENDING) HeapFree(GetProcessHeap(), 0, wsa);
3185 /* If the connect already failed */
3186 if (status == STATUS_PIPE_DISCONNECTED)
3187 status = _get_sock_error(s, FD_CONNECT_BIT);
3188 SetLastError( NtStatusToWSAError(status) );
3191 else
3193 SetLastError(ret);
3196 release_sock_fd( s, fd );
3197 return FALSE;
3199 connection_success:
3200 release_sock_fd( s, fd );
3201 return TRUE;
3205 /***********************************************************************
3206 * getpeername (WS2_32.5)
3208 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
3210 int fd;
3211 int res;
3213 TRACE("socket %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
3215 fd = get_sock_fd( s, 0, NULL );
3216 res = SOCKET_ERROR;
3218 if (fd != -1)
3220 union generic_unix_sockaddr uaddr;
3221 socklen_t uaddrlen = sizeof(uaddr);
3223 if (getpeername(fd, &uaddr.addr, &uaddrlen) == 0)
3225 if (!name || !namelen)
3226 SetLastError(WSAEFAULT);
3227 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3228 /* The buffer was too small */
3229 SetLastError(WSAEFAULT);
3230 else
3232 res = 0;
3233 TRACE("=> %s\n", debugstr_sockaddr(name));
3236 else
3237 SetLastError(wsaErrno());
3238 release_sock_fd( s, fd );
3240 return res;
3243 /* When binding to an UDP address with filter support the getsockname call on the socket
3244 * will always return 0.0.0.0 instead of the filtered interface address. This function
3245 * checks if the socket is interface-bound on UDP and return the correct address.
3246 * This is required because applications often do a bind() with port zero followed by a
3247 * getsockname() to retrieve the port and address acquired.
3249 static void interface_bind_check(int fd, struct sockaddr_in *addr)
3251 #if !defined(IP_BOUND_IF) && !defined(LINUX_BOUND_IF)
3252 return;
3253 #else
3254 int ifindex;
3255 socklen_t len;
3257 /* Check for IPv4, address 0.0.0.0 and UDP socket */
3258 if (addr->sin_family != AF_INET || addr->sin_addr.s_addr != 0)
3259 return;
3260 if (_get_fd_type(fd) != SOCK_DGRAM)
3261 return;
3263 ifindex = -1;
3264 len = sizeof(ifindex);
3265 #if defined(IP_BOUND_IF)
3266 getsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &ifindex, &len);
3267 #elif defined(LINUX_BOUND_IF)
3268 getsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex, &len);
3269 if (ifindex > 0) ifindex = ntohl(ifindex);
3270 #endif
3271 if (ifindex > 0)
3273 PIP_ADAPTER_INFO adapters, adapter;
3274 DWORD adap_size;
3276 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
3277 return;
3278 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
3279 if (adapters && GetAdaptersInfo(adapters, &adap_size) == NO_ERROR)
3281 /* Search the IPv4 adapter list for the appropriate bound interface */
3282 for (adapter = adapters; adapter != NULL; adapter = adapter->Next)
3284 in_addr_t adapter_addr;
3285 if (adapter->Index != ifindex) continue;
3287 adapter_addr = inet_addr(adapter->IpAddressList.IpAddress.String);
3288 addr->sin_addr.s_addr = adapter_addr;
3289 TRACE("reporting interface address from adapter %d\n", ifindex);
3290 break;
3293 HeapFree(GetProcessHeap(), 0, adapters);
3295 #endif
3298 /***********************************************************************
3299 * getsockname (WS2_32.6)
3301 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
3303 int fd;
3304 int res;
3306 TRACE("socket %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
3308 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
3309 if( (name == NULL) || (namelen == NULL) )
3311 SetLastError( WSAEFAULT );
3312 return SOCKET_ERROR;
3315 fd = get_sock_fd( s, 0, NULL );
3316 res = SOCKET_ERROR;
3318 if (fd != -1)
3320 union generic_unix_sockaddr uaddr;
3321 socklen_t uaddrlen;
3322 int bound = is_fd_bound(fd, &uaddr, &uaddrlen);
3324 if (bound <= 0)
3326 SetLastError(bound == -1 ? wsaErrno() : WSAEINVAL);
3328 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3330 /* The buffer was too small */
3331 SetLastError(WSAEFAULT);
3333 else
3335 interface_bind_check(fd, (struct sockaddr_in*) &uaddr);
3336 if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3338 /* The buffer was too small */
3339 SetLastError(WSAEFAULT);
3341 else
3343 res = 0;
3344 TRACE("=> %s\n", debugstr_sockaddr(name));
3347 release_sock_fd( s, fd );
3349 return res;
3352 /***********************************************************************
3353 * getsockopt (WS2_32.7)
3355 INT WINAPI WS_getsockopt(SOCKET s, INT level,
3356 INT optname, char *optval, INT *optlen)
3358 int fd;
3359 INT ret = 0;
3361 TRACE("(socket %04lx, %s, optval %s, optlen %p (%d))\n", s,
3362 debugstr_sockopt(level, optname), debugstr_optval(optval, 0),
3363 optlen, optlen ? *optlen : 0);
3365 switch(level)
3367 case WS_SOL_SOCKET:
3369 switch(optname)
3371 /* Handle common cases. The special cases are below, sorted
3372 * alphabetically */
3373 case WS_SO_BROADCAST:
3374 case WS_SO_DEBUG:
3375 case WS_SO_KEEPALIVE:
3376 case WS_SO_OOBINLINE:
3377 case WS_SO_RCVBUF:
3378 case WS_SO_REUSEADDR:
3379 case WS_SO_SNDBUF:
3380 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3381 return SOCKET_ERROR;
3382 convert_sockopt(&level, &optname);
3383 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3385 SetLastError(wsaErrno());
3386 ret = SOCKET_ERROR;
3388 release_sock_fd( s, fd );
3389 return ret;
3390 case WS_SO_ACCEPTCONN:
3391 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3392 return SOCKET_ERROR;
3393 if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, optval, (socklen_t *)optlen) != 0 )
3395 SetLastError(wsaErrno());
3396 ret = SOCKET_ERROR;
3398 else
3400 /* BSD returns != 0 while Windows return exact == 1 */
3401 if (*(int *)optval) *(int *)optval = 1;
3403 release_sock_fd( s, fd );
3404 return ret;
3405 case WS_SO_BSP_STATE:
3407 int req_size, addr_size;
3408 WSAPROTOCOL_INFOW infow;
3409 CSADDR_INFO *csinfo;
3411 ret = ws_protocol_info(s, TRUE, &infow, &addr_size);
3412 if (ret)
3414 if (infow.iAddressFamily == WS_AF_INET)
3415 addr_size = sizeof(struct sockaddr_in);
3416 else if (infow.iAddressFamily == WS_AF_INET6)
3417 addr_size = sizeof(struct sockaddr_in6);
3418 else
3420 FIXME("Family %d is unsupported for SO_BSP_STATE\n", infow.iAddressFamily);
3421 SetLastError(WSAEAFNOSUPPORT);
3422 return SOCKET_ERROR;
3425 req_size = sizeof(CSADDR_INFO) + addr_size * 2;
3426 if (*optlen < req_size)
3428 ret = 0;
3429 SetLastError(WSAEFAULT);
3431 else
3433 union generic_unix_sockaddr uaddr;
3434 socklen_t uaddrlen;
3436 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3437 return SOCKET_ERROR;
3439 csinfo = (CSADDR_INFO*) optval;
3441 /* Check if the sock is bound */
3442 if (is_fd_bound(fd, &uaddr, &uaddrlen) == 1)
3444 csinfo->LocalAddr.lpSockaddr =
3445 (LPSOCKADDR) (optval + sizeof(CSADDR_INFO));
3446 ws_sockaddr_u2ws(&uaddr.addr, csinfo->LocalAddr.lpSockaddr, &addr_size);
3447 csinfo->LocalAddr.iSockaddrLength = addr_size;
3449 else
3451 csinfo->LocalAddr.lpSockaddr = NULL;
3452 csinfo->LocalAddr.iSockaddrLength = 0;
3455 /* Check if the sock is connected */
3456 if (!getpeername(fd, &uaddr.addr, &uaddrlen) &&
3457 is_sockaddr_bound(&uaddr.addr, uaddrlen))
3459 csinfo->RemoteAddr.lpSockaddr =
3460 (LPSOCKADDR) (optval + sizeof(CSADDR_INFO) + addr_size);
3461 ws_sockaddr_u2ws(&uaddr.addr, csinfo->RemoteAddr.lpSockaddr, &addr_size);
3462 csinfo->RemoteAddr.iSockaddrLength = addr_size;
3464 else
3466 csinfo->RemoteAddr.lpSockaddr = NULL;
3467 csinfo->RemoteAddr.iSockaddrLength = 0;
3470 csinfo->iSocketType = infow.iSocketType;
3471 csinfo->iProtocol = infow.iProtocol;
3472 release_sock_fd( s, fd );
3475 return ret ? 0 : SOCKET_ERROR;
3477 case WS_SO_DONTLINGER:
3479 struct linger lingval;
3480 socklen_t len = sizeof(struct linger);
3482 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
3484 SetLastError(WSAEFAULT);
3485 return SOCKET_ERROR;
3487 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3488 return SOCKET_ERROR;
3490 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
3492 SetLastError(wsaErrno());
3493 ret = SOCKET_ERROR;
3495 else
3497 *(BOOL *)optval = !lingval.l_onoff;
3498 *optlen = sizeof(BOOL);
3501 release_sock_fd( s, fd );
3502 return ret;
3505 case WS_SO_CONNECT_TIME:
3507 static int pretendtime = 0;
3508 struct WS_sockaddr addr;
3509 int len = sizeof(addr);
3511 if (!optlen || *optlen < sizeof(DWORD) || !optval)
3513 SetLastError(WSAEFAULT);
3514 return SOCKET_ERROR;
3516 if (WS_getpeername(s, &addr, &len) == SOCKET_ERROR)
3517 *(DWORD *)optval = ~0u;
3518 else
3520 if (!pretendtime) FIXME("WS_SO_CONNECT_TIME - faking results\n");
3521 *(DWORD *)optval = pretendtime++;
3523 *optlen = sizeof(DWORD);
3524 return ret;
3526 /* As mentioned in setsockopt, Windows ignores this, so we
3527 * always return true here */
3528 case WS_SO_DONTROUTE:
3529 if (!optlen || *optlen < sizeof(BOOL) || !optval)
3531 SetLastError(WSAEFAULT);
3532 return SOCKET_ERROR;
3534 *(BOOL *)optval = TRUE;
3535 *optlen = sizeof(BOOL);
3536 return 0;
3538 case WS_SO_ERROR:
3540 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3541 return SOCKET_ERROR;
3542 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, optval, (socklen_t *)optlen) != 0 )
3544 SetLastError(wsaErrno());
3545 ret = SOCKET_ERROR;
3547 release_sock_fd( s, fd );
3549 /* The wineserver may have swallowed the error before us */
3550 if (!ret && *(int*) optval == 0)
3552 int i, events[FD_MAX_EVENTS];
3553 _get_sock_errors(s, events);
3554 for (i = 0; i < FD_MAX_EVENTS; i++)
3556 if(events[i])
3558 events[i] = NtStatusToWSAError(events[i]);
3559 TRACE("returning SO_ERROR %d from wine server\n", events[i]);
3560 *(int*) optval = events[i];
3561 break;
3565 return ret;
3568 case WS_SO_LINGER:
3570 struct linger lingval;
3571 socklen_t len = sizeof(struct linger);
3573 /* struct linger and LINGER have different sizes */
3574 if (!optlen || *optlen < sizeof(LINGER) || !optval)
3576 SetLastError(WSAEFAULT);
3577 return SOCKET_ERROR;
3579 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3580 return SOCKET_ERROR;
3582 if (_get_fd_type(fd) == SOCK_DGRAM)
3584 SetLastError(WSAENOPROTOOPT);
3585 ret = SOCKET_ERROR;
3587 else if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0)
3589 SetLastError(wsaErrno());
3590 ret = SOCKET_ERROR;
3592 else
3594 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
3595 ((LINGER *)optval)->l_linger = lingval.l_linger;
3596 *optlen = sizeof(struct linger);
3599 release_sock_fd( s, fd );
3600 return ret;
3603 case WS_SO_MAX_MSG_SIZE:
3604 if (!optlen || *optlen < sizeof(int) || !optval)
3606 SetLastError(WSAEFAULT);
3607 return SOCKET_ERROR;
3609 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
3610 *(int *)optval = 65507;
3611 *optlen = sizeof(int);
3612 return 0;
3614 /* SO_OPENTYPE does not require a valid socket handle. */
3615 case WS_SO_OPENTYPE:
3616 if (!optlen || *optlen < sizeof(int) || !optval)
3618 SetLastError(WSAEFAULT);
3619 return SOCKET_ERROR;
3621 *(int *)optval = get_per_thread_data()->opentype;
3622 *optlen = sizeof(int);
3623 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
3624 return 0;
3625 case WS_SO_PROTOCOL_INFOA:
3626 case WS_SO_PROTOCOL_INFOW:
3628 int size;
3629 WSAPROTOCOL_INFOW infow;
3631 ret = ws_protocol_info(s, optname == WS_SO_PROTOCOL_INFOW, &infow, &size);
3632 if (ret)
3634 if (!optlen || !optval || *optlen < size)
3636 if(optlen) *optlen = size;
3637 ret = 0;
3638 SetLastError(WSAEFAULT);
3640 else
3641 memcpy(optval, &infow, size);
3643 return ret ? 0 : SOCKET_ERROR;
3645 case WS_SO_RCVTIMEO:
3646 case WS_SO_SNDTIMEO:
3648 INT64 timeout;
3650 if (!optlen || *optlen < sizeof(int)|| !optval)
3652 SetLastError(WSAEFAULT);
3653 return SOCKET_ERROR;
3655 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3656 return SOCKET_ERROR;
3658 timeout = get_rcvsnd_timeo(fd, optname == WS_SO_RCVTIMEO);
3659 *(int *)optval = timeout <= UINT_MAX ? timeout : UINT_MAX;
3661 release_sock_fd( s, fd );
3662 return ret;
3664 case WS_SO_TYPE:
3666 int sock_type;
3667 if (!optlen || *optlen < sizeof(int) || !optval)
3669 SetLastError(WSAEFAULT);
3670 return SOCKET_ERROR;
3672 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3673 return SOCKET_ERROR;
3675 sock_type = _get_fd_type(fd);
3676 if (sock_type == -1)
3678 SetLastError(wsaErrno());
3679 ret = SOCKET_ERROR;
3681 else
3682 (*(int *)optval) = convert_socktype_u2w(sock_type);
3684 release_sock_fd( s, fd );
3685 return ret;
3687 default:
3688 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
3689 SetLastError(WSAENOPROTOOPT);
3690 return SOCKET_ERROR;
3691 } /* end switch(optname) */
3692 }/* end case WS_SOL_SOCKET */
3693 #ifdef HAS_IPX
3694 case WS_NSPROTO_IPX:
3696 struct WS_sockaddr_ipx addr;
3697 IPX_ADDRESS_DATA *data;
3698 int namelen;
3699 switch(optname)
3701 case WS_IPX_PTYPE:
3702 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3703 #ifdef SOL_IPX
3704 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (socklen_t *)optlen) == -1)
3706 ret = SOCKET_ERROR;
3708 #else
3710 struct ipx val;
3711 socklen_t len=sizeof(struct ipx);
3712 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
3713 ret = SOCKET_ERROR;
3714 else
3715 *optval = (int)val.ipx_pt;
3717 #endif
3718 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
3719 release_sock_fd( s, fd );
3720 return ret;
3722 case WS_IPX_ADDRESS:
3724 * On a Win2000 system with one network card there are usually
3725 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
3726 * Using this call you can then retrieve info about this all.
3727 * In case of Linux it is a bit different. Usually you have
3728 * only "one" device active and further it is not possible to
3729 * query things like the linkspeed.
3731 FIXME("IPX_ADDRESS\n");
3732 namelen = sizeof(struct WS_sockaddr_ipx);
3733 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
3734 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
3736 data = (IPX_ADDRESS_DATA*)optval;
3737 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
3738 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
3739 data->adapternum = 0;
3740 data->wan = FALSE; /* We are not on a wan for now .. */
3741 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
3742 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
3743 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
3744 * note 1MB = 1000kB in this case */
3745 return 0;
3747 case WS_IPX_MAX_ADAPTER_NUM:
3748 FIXME("IPX_MAX_ADAPTER_NUM\n");
3749 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
3750 return 0;
3752 default:
3753 FIXME("IPX optname:%x\n", optname);
3754 return SOCKET_ERROR;
3755 }/* end switch(optname) */
3756 } /* end case WS_NSPROTO_IPX */
3757 #endif
3759 #ifdef HAS_IRDA
3760 #define MAX_IRDA_DEVICES 10
3762 case WS_SOL_IRLMP:
3763 switch(optname)
3765 case WS_IRLMP_ENUMDEVICES:
3767 char buf[sizeof(struct irda_device_list) +
3768 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
3769 int res;
3770 socklen_t len = sizeof(buf);
3772 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3773 return SOCKET_ERROR;
3774 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
3775 release_sock_fd( s, fd );
3776 if (res < 0)
3778 SetLastError(wsaErrno());
3779 return SOCKET_ERROR;
3781 else
3783 struct irda_device_list *src = (struct irda_device_list *)buf;
3784 DEVICELIST *dst = (DEVICELIST *)optval;
3785 INT needed = sizeof(DEVICELIST);
3786 unsigned int i;
3788 if (src->len > 0)
3789 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
3790 if (*optlen < needed)
3792 SetLastError(WSAEFAULT);
3793 return SOCKET_ERROR;
3795 *optlen = needed;
3796 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
3797 dst->numDevice = src->len;
3798 for (i = 0; i < src->len; i++)
3800 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
3801 src->dev[i].saddr, src->dev[i].daddr,
3802 src->dev[i].info, src->dev[i].hints[0],
3803 src->dev[i].hints[1]);
3804 memcpy( dst->Device[i].irdaDeviceID,
3805 &src->dev[i].daddr,
3806 sizeof(dst->Device[i].irdaDeviceID) ) ;
3807 memcpy( dst->Device[i].irdaDeviceName,
3808 src->dev[i].info,
3809 sizeof(dst->Device[i].irdaDeviceName) ) ;
3810 memcpy( &dst->Device[i].irdaDeviceHints1,
3811 &src->dev[i].hints[0],
3812 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
3813 memcpy( &dst->Device[i].irdaDeviceHints2,
3814 &src->dev[i].hints[1],
3815 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
3816 dst->Device[i].irdaCharSet = src->dev[i].charset;
3818 return 0;
3821 default:
3822 FIXME("IrDA optname:0x%x\n", optname);
3823 return SOCKET_ERROR;
3825 break; /* case WS_SOL_IRLMP */
3826 #undef MAX_IRDA_DEVICES
3827 #endif
3829 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3830 case WS_IPPROTO_TCP:
3831 switch(optname)
3833 case WS_TCP_NODELAY:
3834 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3835 return SOCKET_ERROR;
3836 convert_sockopt(&level, &optname);
3837 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3839 SetLastError(wsaErrno());
3840 ret = SOCKET_ERROR;
3842 release_sock_fd( s, fd );
3843 return ret;
3845 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
3846 return SOCKET_ERROR;
3848 case WS_IPPROTO_IP:
3849 switch(optname)
3851 case WS_IP_ADD_MEMBERSHIP:
3852 case WS_IP_DROP_MEMBERSHIP:
3853 #ifdef IP_HDRINCL
3854 case WS_IP_HDRINCL:
3855 #endif
3856 case WS_IP_MULTICAST_IF:
3857 case WS_IP_MULTICAST_LOOP:
3858 case WS_IP_MULTICAST_TTL:
3859 case WS_IP_OPTIONS:
3860 #ifdef IP_PKTINFO
3861 case WS_IP_PKTINFO:
3862 #endif
3863 case WS_IP_TOS:
3864 case WS_IP_TTL:
3865 #ifdef IP_UNICAST_IF
3866 case WS_IP_UNICAST_IF:
3867 #endif
3868 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3869 return SOCKET_ERROR;
3870 convert_sockopt(&level, &optname);
3871 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3873 SetLastError(wsaErrno());
3874 ret = SOCKET_ERROR;
3876 release_sock_fd( s, fd );
3877 return ret;
3878 case WS_IP_DONTFRAGMENT:
3879 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
3880 *(BOOL*)optval = FALSE;
3881 return 0;
3883 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
3884 return SOCKET_ERROR;
3886 case WS_IPPROTO_IPV6:
3887 switch(optname)
3889 #ifdef IPV6_ADD_MEMBERSHIP
3890 case WS_IPV6_ADD_MEMBERSHIP:
3891 #endif
3892 #ifdef IPV6_DROP_MEMBERSHIP
3893 case WS_IPV6_DROP_MEMBERSHIP:
3894 #endif
3895 case WS_IPV6_MULTICAST_IF:
3896 case WS_IPV6_MULTICAST_HOPS:
3897 case WS_IPV6_MULTICAST_LOOP:
3898 case WS_IPV6_UNICAST_HOPS:
3899 case WS_IPV6_V6ONLY:
3900 #ifdef IPV6_UNICAST_IF
3901 case WS_IPV6_UNICAST_IF:
3902 #endif
3903 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3904 return SOCKET_ERROR;
3905 convert_sockopt(&level, &optname);
3906 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3908 SetLastError(wsaErrno());
3909 ret = SOCKET_ERROR;
3911 release_sock_fd( s, fd );
3912 return ret;
3913 case WS_IPV6_DONTFRAG:
3914 FIXME("WS_IPV6_DONTFRAG is always false!\n");
3915 *(BOOL*)optval = FALSE;
3916 return 0;
3918 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
3919 return SOCKET_ERROR;
3921 default:
3922 WARN("Unknown level: 0x%08x\n", level);
3923 SetLastError(WSAEINVAL);
3924 return SOCKET_ERROR;
3925 } /* end switch(level) */
3928 /***********************************************************************
3929 * htonl (WS2_32.8)
3931 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
3933 return htonl(hostlong);
3937 /***********************************************************************
3938 * htons (WS2_32.9)
3940 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
3942 return htons(hostshort);
3945 /***********************************************************************
3946 * WSAHtonl (WS2_32.46)
3947 * From MSDN description of error codes, this function should also
3948 * check if WinSock has been initialized and the socket is a valid
3949 * socket. But why? This function only translates a host byte order
3950 * u_long into a network byte order u_long...
3952 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
3954 if (lpnetlong)
3956 *lpnetlong = htonl(hostlong);
3957 return 0;
3959 SetLastError(WSAEFAULT);
3960 return SOCKET_ERROR;
3963 /***********************************************************************
3964 * WSAHtons (WS2_32.47)
3965 * From MSDN description of error codes, this function should also
3966 * check if WinSock has been initialized and the socket is a valid
3967 * socket. But why? This function only translates a host byte order
3968 * u_short into a network byte order u_short...
3970 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
3973 if (lpnetshort)
3975 *lpnetshort = htons(hostshort);
3976 return 0;
3978 SetLastError(WSAEFAULT);
3979 return SOCKET_ERROR;
3983 /***********************************************************************
3984 * inet_addr (WS2_32.11)
3986 WS_u_long WINAPI WS_inet_addr(const char *cp)
3988 if (!cp) return INADDR_NONE;
3989 return inet_addr(cp);
3993 /***********************************************************************
3994 * ntohl (WS2_32.14)
3996 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
3998 return ntohl(netlong);
4002 /***********************************************************************
4003 * ntohs (WS2_32.15)
4005 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
4007 return ntohs(netshort);
4011 /***********************************************************************
4012 * inet_ntoa (WS2_32.12)
4014 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
4016 struct per_thread_data *data = get_per_thread_data();
4018 sprintf( data->ntoa_buffer, "%u.%u.%u.%u",
4019 (unsigned int)(ntohl( in.WS_s_addr ) >> 24 & 0xff),
4020 (unsigned int)(ntohl( in.WS_s_addr ) >> 16 & 0xff),
4021 (unsigned int)(ntohl( in.WS_s_addr ) >> 8 & 0xff),
4022 (unsigned int)(ntohl( in.WS_s_addr ) & 0xff) );
4024 return data->ntoa_buffer;
4027 static const char *debugstr_wsaioctl(DWORD ioctl)
4029 const char *buf_type, *family;
4031 switch(ioctl & 0x18000000)
4033 case WS_IOC_WS2:
4034 family = "IOC_WS2";
4035 break;
4036 case WS_IOC_PROTOCOL:
4037 family = "IOC_PROTOCOL";
4038 break;
4039 case WS_IOC_VENDOR:
4040 family = "IOC_VENDOR";
4041 break;
4042 default: /* WS_IOC_UNIX */
4044 BYTE size = (ioctl >> 16) & WS_IOCPARM_MASK;
4045 char x = (ioctl & 0xff00) >> 8;
4046 BYTE y = ioctl & 0xff;
4047 char args[14];
4049 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
4051 case WS_IOC_VOID:
4052 buf_type = "_IO";
4053 sprintf(args, "%d, %d", x, y);
4054 break;
4055 case WS_IOC_IN:
4056 buf_type = "_IOW";
4057 sprintf(args, "'%c', %d, %d", x, y, size);
4058 break;
4059 case WS_IOC_OUT:
4060 buf_type = "_IOR";
4061 sprintf(args, "'%c', %d, %d", x, y, size);
4062 break;
4063 default:
4064 buf_type = "?";
4065 sprintf(args, "'%c', %d, %d", x, y, size);
4066 break;
4068 return wine_dbg_sprintf("%s(%s)", buf_type, args);
4072 /* We are different from WS_IOC_UNIX. */
4073 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
4075 case WS_IOC_VOID:
4076 buf_type = "_WSAIO";
4077 break;
4078 case WS_IOC_INOUT:
4079 buf_type = "_WSAIORW";
4080 break;
4081 case WS_IOC_IN:
4082 buf_type = "_WSAIOW";
4083 break;
4084 case WS_IOC_OUT:
4085 buf_type = "_WSAIOR";
4086 break;
4087 default:
4088 buf_type = "?";
4089 break;
4092 return wine_dbg_sprintf("%s(%s, %d)", buf_type, family,
4093 (USHORT)(ioctl & 0xffff));
4096 /* do an ioctl call through the server */
4097 static DWORD server_ioctl_sock( SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size,
4098 LPVOID out_buff, DWORD out_size, LPDWORD ret_size,
4099 LPWSAOVERLAPPED overlapped,
4100 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
4102 HANDLE event = overlapped ? overlapped->hEvent : 0;
4103 HANDLE handle = SOCKET2HANDLE( s );
4104 struct ws2_async *wsa;
4105 NTSTATUS status;
4106 PIO_STATUS_BLOCK io;
4108 if (!(wsa = (struct ws2_async *)alloc_async_io( sizeof(*wsa) )))
4109 return WSA_NOT_ENOUGH_MEMORY;
4110 wsa->hSocket = handle;
4111 wsa->user_overlapped = overlapped;
4112 wsa->completion_func = completion;
4113 io = (overlapped ? (PIO_STATUS_BLOCK)overlapped : &wsa->local_iosb);
4115 status = NtDeviceIoControlFile( handle, event, ws2_async_apc, wsa, io, code,
4116 in_buff, in_size, out_buff, out_size );
4117 if (status == STATUS_NOT_SUPPORTED)
4119 FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
4120 code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
4122 else if (status == STATUS_SUCCESS)
4123 *ret_size = io->Information; /* "Information" is the size written to the output buffer */
4125 if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, wsa );
4127 return NtStatusToWSAError( status );
4130 /**********************************************************************
4131 * WSAIoctl (WS2_32.50)
4134 INT WINAPI WSAIoctl(SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size, LPVOID out_buff,
4135 DWORD out_size, LPDWORD ret_size, LPWSAOVERLAPPED overlapped,
4136 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
4138 int fd;
4139 DWORD status = 0, total = 0;
4141 TRACE("%04lx, %s, %p, %d, %p, %d, %p, %p, %p\n",
4142 s, debugstr_wsaioctl(code), in_buff, in_size, out_buff, out_size, ret_size, overlapped, completion);
4144 switch (code)
4146 case WS_FIONBIO:
4147 if (in_size != sizeof(WS_u_long) || IS_INTRESOURCE(in_buff))
4149 SetLastError(WSAEFAULT);
4150 return SOCKET_ERROR;
4152 TRACE("-> FIONBIO (%x)\n", *(WS_u_long*)in_buff);
4153 if (_get_sock_mask(s))
4155 /* AsyncSelect()'ed sockets are always nonblocking */
4156 if (!*(WS_u_long *)in_buff) status = WSAEINVAL;
4157 break;
4159 if (*(WS_u_long *)in_buff)
4160 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
4161 else
4162 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
4163 break;
4165 case WS_FIONREAD:
4167 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
4169 SetLastError(WSAEFAULT);
4170 return SOCKET_ERROR;
4172 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
4173 if (ioctl(fd, FIONREAD, out_buff ) == -1)
4174 status = wsaErrno();
4175 release_sock_fd( s, fd );
4176 break;
4179 case WS_SIOCATMARK:
4181 unsigned int oob = 0, atmark = 0;
4182 socklen_t oobsize = sizeof(int);
4183 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
4185 SetLastError(WSAEFAULT);
4186 return SOCKET_ERROR;
4188 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
4189 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
4190 if ((getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &oob, &oobsize ) == -1)
4191 || (!oob && ioctl(fd, SIOCATMARK, &atmark ) == -1))
4192 status = wsaErrno();
4193 else
4195 /* The SIOCATMARK value read from ioctl() is reversed
4196 * because BSD returns TRUE if it's in the OOB mark
4197 * while Windows returns TRUE if there are NO OOB bytes.
4199 (*(WS_u_long *) out_buff) = oob || !atmark;
4202 release_sock_fd( s, fd );
4203 break;
4206 case WS_FIOASYNC:
4207 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
4208 SetLastError(WSAEINVAL);
4209 return SOCKET_ERROR;
4211 case WS_SIO_GET_INTERFACE_LIST:
4213 INTERFACE_INFO* intArray = out_buff;
4214 DWORD size, numInt = 0, apiReturn;
4216 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
4218 if (!out_buff || !ret_size)
4220 SetLastError(WSAEFAULT);
4221 return SOCKET_ERROR;
4224 fd = get_sock_fd( s, 0, NULL );
4225 if (fd == -1) return SOCKET_ERROR;
4227 apiReturn = GetAdaptersInfo(NULL, &size);
4228 if (apiReturn == ERROR_BUFFER_OVERFLOW)
4230 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
4232 if (table)
4234 if (GetAdaptersInfo(table, &size) == NO_ERROR)
4236 PIP_ADAPTER_INFO ptr;
4238 for (ptr = table, numInt = 0; ptr; ptr = ptr->Next)
4240 unsigned int addr, mask, bcast;
4241 struct ifreq ifInfo;
4243 /* Skip interfaces without an IPv4 address. */
4244 if (ptr->IpAddressList.IpAddress.String[0] == '\0')
4245 continue;
4247 if ((numInt + 1)*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > out_size)
4249 WARN("Buffer too small = %u, out_size = %u\n", numInt + 1, out_size);
4250 status = WSAEFAULT;
4251 break;
4254 /* Socket Status Flags */
4255 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
4256 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
4258 ERR("Error obtaining status flags for socket!\n");
4259 status = WSAEINVAL;
4260 break;
4262 else
4264 /* set flags; the values of IFF_* are not the same
4265 under Linux and Windows, therefore must generate
4266 new flags */
4267 intArray->iiFlags = 0;
4268 if (ifInfo.ifr_flags & IFF_BROADCAST)
4269 intArray->iiFlags |= WS_IFF_BROADCAST;
4270 #ifdef IFF_POINTOPOINT
4271 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
4272 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
4273 #endif
4274 if (ifInfo.ifr_flags & IFF_LOOPBACK)
4275 intArray->iiFlags |= WS_IFF_LOOPBACK;
4276 if (ifInfo.ifr_flags & IFF_UP)
4277 intArray->iiFlags |= WS_IFF_UP;
4278 if (ifInfo.ifr_flags & IFF_MULTICAST)
4279 intArray->iiFlags |= WS_IFF_MULTICAST;
4282 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
4283 mask = inet_addr(ptr->IpAddressList.IpMask.String);
4284 bcast = addr | ~mask;
4285 intArray->iiAddress.AddressIn.sin_family = AF_INET;
4286 intArray->iiAddress.AddressIn.sin_port = 0;
4287 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
4288 addr;
4289 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
4290 intArray->iiNetmask.AddressIn.sin_port = 0;
4291 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
4292 mask;
4293 intArray->iiBroadcastAddress.AddressIn.sin_family =
4294 AF_INET;
4295 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
4296 intArray->iiBroadcastAddress.AddressIn.sin_addr.
4297 WS_s_addr = bcast;
4298 intArray++;
4299 numInt++;
4302 else
4304 ERR("Unable to get interface table!\n");
4305 status = WSAEINVAL;
4307 HeapFree(GetProcessHeap(),0,table);
4309 else status = WSAEINVAL;
4311 else if (apiReturn != ERROR_NO_DATA)
4313 ERR("Unable to get interface table!\n");
4314 status = WSAEINVAL;
4316 /* Calculate the size of the array being returned */
4317 total = sizeof(INTERFACE_INFO) * numInt;
4318 release_sock_fd( s, fd );
4319 break;
4322 case WS_SIO_ADDRESS_LIST_QUERY:
4324 DWORD size;
4326 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
4328 if (!ret_size)
4330 SetLastError(WSAEFAULT);
4331 return SOCKET_ERROR;
4334 if (out_size && out_size < FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[0]))
4336 *ret_size = 0;
4337 SetLastError(WSAEINVAL);
4338 return SOCKET_ERROR;
4341 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
4343 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
4344 SOCKET_ADDRESS_LIST *sa_list;
4345 SOCKADDR_IN *sockaddr;
4346 SOCKET_ADDRESS *sa;
4347 unsigned int i;
4348 DWORD num;
4350 if (!table || GetAdaptersInfo(table, &size))
4352 HeapFree(GetProcessHeap(), 0, table);
4353 status = WSAEINVAL;
4354 break;
4357 for (p = table, num = 0; p; p = p->Next)
4358 if (p->IpAddressList.IpAddress.String[0]) num++;
4360 total = FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[num]) + num * sizeof(*sockaddr);
4361 if (total > out_size || !out_buff)
4363 *ret_size = total;
4364 HeapFree(GetProcessHeap(), 0, table);
4365 status = WSAEFAULT;
4366 break;
4369 sa_list = out_buff;
4370 sa = sa_list->Address;
4371 sockaddr = (SOCKADDR_IN *)&sa[num];
4372 sa_list->iAddressCount = num;
4374 for (p = table, i = 0; p; p = p->Next)
4376 if (!p->IpAddressList.IpAddress.String[0]) continue;
4378 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
4379 sa[i].iSockaddrLength = sizeof(SOCKADDR);
4381 sockaddr[i].sin_family = AF_INET;
4382 sockaddr[i].sin_port = 0;
4383 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
4384 i++;
4387 HeapFree(GetProcessHeap(), 0, table);
4389 else
4391 WARN("unable to get IP address list\n");
4392 status = WSAEINVAL;
4394 break;
4397 case WS_SIO_FLUSH:
4398 FIXME("SIO_FLUSH: stub.\n");
4399 break;
4401 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
4403 static const GUID connectex_guid = WSAID_CONNECTEX;
4404 static const GUID disconnectex_guid = WSAID_DISCONNECTEX;
4405 static const GUID acceptex_guid = WSAID_ACCEPTEX;
4406 static const GUID getaccepexsockaddrs_guid = WSAID_GETACCEPTEXSOCKADDRS;
4407 static const GUID transmitfile_guid = WSAID_TRANSMITFILE;
4408 static const GUID transmitpackets_guid = WSAID_TRANSMITPACKETS;
4409 static const GUID wsarecvmsg_guid = WSAID_WSARECVMSG;
4410 static const GUID wsasendmsg_guid = WSAID_WSASENDMSG;
4412 if ( IsEqualGUID(&connectex_guid, in_buff) )
4414 *(LPFN_CONNECTEX *)out_buff = WS2_ConnectEx;
4415 break;
4417 else if ( IsEqualGUID(&disconnectex_guid, in_buff) )
4419 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented DisconnectEx\n");
4421 else if ( IsEqualGUID(&acceptex_guid, in_buff) )
4423 *(LPFN_ACCEPTEX *)out_buff = WS2_AcceptEx;
4424 break;
4426 else if ( IsEqualGUID(&getaccepexsockaddrs_guid, in_buff) )
4428 *(LPFN_GETACCEPTEXSOCKADDRS *)out_buff = WS2_GetAcceptExSockaddrs;
4429 break;
4431 else if ( IsEqualGUID(&transmitfile_guid, in_buff) )
4433 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitFile\n");
4435 else if ( IsEqualGUID(&transmitpackets_guid, in_buff) )
4437 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitPackets\n");
4439 else if ( IsEqualGUID(&wsarecvmsg_guid, in_buff) )
4441 *(LPFN_WSARECVMSG *)out_buff = WS2_WSARecvMsg;
4442 break;
4444 else if ( IsEqualGUID(&wsasendmsg_guid, in_buff) )
4446 *(LPFN_WSASENDMSG *)out_buff = WSASendMsg;
4447 break;
4449 else
4450 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff));
4452 status = WSAEOPNOTSUPP;
4453 break;
4455 case WS_SIO_KEEPALIVE_VALS:
4457 struct tcp_keepalive *k;
4458 int keepalive, keepidle, keepintvl;
4460 if (!in_buff || in_size < sizeof(struct tcp_keepalive))
4462 SetLastError(WSAEFAULT);
4463 return SOCKET_ERROR;
4466 k = in_buff;
4467 keepalive = k->onoff ? 1 : 0;
4468 keepidle = max( 1, (k->keepalivetime + 500) / 1000 );
4469 keepintvl = max( 1, (k->keepaliveinterval + 500) / 1000 );
4471 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
4473 fd = get_sock_fd(s, 0, NULL);
4474 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
4475 status = WSAEINVAL;
4476 #if defined(TCP_KEEPIDLE) || defined(TCP_KEEPINTVL)
4477 /* these values need to be set only if SO_KEEPALIVE is enabled */
4478 else if(keepalive)
4480 #ifndef TCP_KEEPIDLE
4481 FIXME("ignoring keepalive timeout\n");
4482 #else
4483 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
4484 status = WSAEINVAL;
4485 else
4486 #endif
4487 #ifdef TCP_KEEPINTVL
4488 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
4489 status = WSAEINVAL;
4490 #else
4491 FIXME("ignoring keepalive interval\n");
4492 #endif
4494 #else
4495 else
4496 FIXME("ignoring keepalive interval and timeout\n");
4497 #endif
4498 release_sock_fd(s, fd);
4499 break;
4501 case WS_SIO_ROUTING_INTERFACE_QUERY:
4503 struct WS_sockaddr *daddr = (struct WS_sockaddr *)in_buff;
4504 struct WS_sockaddr_in *daddr_in = (struct WS_sockaddr_in *)daddr;
4505 struct WS_sockaddr_in *saddr_in = out_buff;
4506 MIB_IPFORWARDROW row;
4507 PMIB_IPADDRTABLE ipAddrTable = NULL;
4508 DWORD size, i, found_index;
4510 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
4512 if (!in_buff || in_size < sizeof(struct WS_sockaddr) ||
4513 !out_buff || out_size < sizeof(struct WS_sockaddr_in) || !ret_size)
4515 SetLastError(WSAEFAULT);
4516 return SOCKET_ERROR;
4518 if (daddr->sa_family != AF_INET)
4520 FIXME("unsupported address family %d\n", daddr->sa_family);
4521 status = WSAEAFNOSUPPORT;
4522 break;
4524 if (GetBestRoute(daddr_in->sin_addr.S_un.S_addr, 0, &row) != NOERROR ||
4525 GetIpAddrTable(NULL, &size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
4527 status = WSAEFAULT;
4528 break;
4530 ipAddrTable = HeapAlloc(GetProcessHeap(), 0, size);
4531 if (GetIpAddrTable(ipAddrTable, &size, FALSE))
4533 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4534 status = WSAEFAULT;
4535 break;
4537 for (i = 0, found_index = ipAddrTable->dwNumEntries;
4538 i < ipAddrTable->dwNumEntries; i++)
4540 if (ipAddrTable->table[i].dwIndex == row.dwForwardIfIndex)
4541 found_index = i;
4543 if (found_index == ipAddrTable->dwNumEntries)
4545 ERR("no matching IP address for interface %d\n",
4546 row.dwForwardIfIndex);
4547 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4548 status = WSAEFAULT;
4549 break;
4551 saddr_in->sin_family = AF_INET;
4552 saddr_in->sin_addr.S_un.S_addr = ipAddrTable->table[found_index].dwAddr;
4553 saddr_in->sin_port = 0;
4554 total = sizeof(struct WS_sockaddr_in);
4555 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4556 break;
4558 case WS_SIO_SET_COMPATIBILITY_MODE:
4559 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
4560 status = WSAEOPNOTSUPP;
4561 break;
4562 case WS_SIO_UDP_CONNRESET:
4563 FIXME("WS_SIO_UDP_CONNRESET stub\n");
4564 break;
4565 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
4566 SetLastError(WSAEOPNOTSUPP);
4567 return SOCKET_ERROR;
4568 default:
4569 status = WSAEOPNOTSUPP;
4570 break;
4573 if (status == WSAEOPNOTSUPP)
4575 status = server_ioctl_sock(s, code, in_buff, in_size, out_buff, out_size, &total,
4576 overlapped, completion);
4577 if (status != WSAEOPNOTSUPP)
4579 if (status == 0 || status == WSA_IO_PENDING)
4580 TRACE("-> %s request\n", debugstr_wsaioctl(code));
4581 else
4582 ERR("-> %s request failed with status 0x%x\n", debugstr_wsaioctl(code), status);
4584 /* overlapped and completion operations will be handled by the server */
4585 completion = NULL;
4586 overlapped = NULL;
4588 else
4589 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code));
4592 if (completion)
4594 FIXME( "completion routine %p not supported\n", completion );
4596 else if (overlapped)
4598 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
4599 overlapped->Internal = status;
4600 overlapped->InternalHigh = total;
4601 if (overlapped->hEvent) NtSetEvent( overlapped->hEvent, NULL );
4602 if (cvalue) WS_AddCompletion( HANDLE2SOCKET(s), cvalue, status, total );
4605 if (!status)
4607 if (ret_size) *ret_size = total;
4608 return 0;
4610 SetLastError( status );
4611 return SOCKET_ERROR;
4615 /***********************************************************************
4616 * ioctlsocket (WS2_32.10)
4618 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
4620 DWORD ret_size;
4621 return WSAIoctl( s, cmd, argp, sizeof(WS_u_long), argp, sizeof(WS_u_long), &ret_size, NULL, NULL );
4624 /***********************************************************************
4625 * listen (WS2_32.13)
4627 int WINAPI WS_listen(SOCKET s, int backlog)
4629 int fd = get_sock_fd( s, FILE_READ_DATA, NULL ), ret = SOCKET_ERROR;
4631 TRACE("socket %04lx, backlog %d\n", s, backlog);
4632 if (fd != -1)
4634 int bound = is_fd_bound(fd, NULL, NULL);
4636 if (bound <= 0)
4638 SetLastError(bound == -1 ? wsaErrno() : WSAEINVAL);
4640 else if (listen(fd, backlog) == 0)
4642 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
4643 FD_WINE_LISTENING,
4644 FD_CONNECT|FD_WINE_CONNECTED);
4645 ret = 0;
4647 else
4648 SetLastError(wsaErrno());
4649 release_sock_fd( s, fd );
4651 else
4652 SetLastError(WSAENOTSOCK);
4653 return ret;
4656 /***********************************************************************
4657 * recv (WS2_32.16)
4659 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
4661 DWORD n, dwFlags = flags;
4662 WSABUF wsabuf;
4664 wsabuf.len = len;
4665 wsabuf.buf = buf;
4667 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
4668 return SOCKET_ERROR;
4669 else
4670 return n;
4673 /***********************************************************************
4674 * recvfrom (WS2_32.17)
4676 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
4677 struct WS_sockaddr *from, int *fromlen)
4679 DWORD n, dwFlags = flags;
4680 WSABUF wsabuf;
4682 wsabuf.len = len;
4683 wsabuf.buf = buf;
4685 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL, NULL) == SOCKET_ERROR )
4686 return SOCKET_ERROR;
4687 else
4688 return n;
4691 /* allocate a poll array for the corresponding fd sets */
4692 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
4693 const WS_fd_set *exceptfds, int *count_ptr )
4695 unsigned int i, j = 0, count = 0;
4696 struct pollfd *fds;
4698 if (readfds) count += readfds->fd_count;
4699 if (writefds) count += writefds->fd_count;
4700 if (exceptfds) count += exceptfds->fd_count;
4701 *count_ptr = count;
4702 if (!count)
4704 SetLastError(WSAEINVAL);
4705 return NULL;
4707 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0]))))
4709 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
4710 return NULL;
4712 if (readfds)
4713 for (i = 0; i < readfds->fd_count; i++, j++)
4715 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
4716 if (fds[j].fd == -1) goto failed;
4717 fds[j].revents = 0;
4718 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1)
4720 fds[j].events = POLLIN;
4722 else
4724 release_sock_fd( readfds->fd_array[i], fds[j].fd );
4725 fds[j].fd = -1;
4726 fds[j].events = 0;
4729 if (writefds)
4730 for (i = 0; i < writefds->fd_count; i++, j++)
4732 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
4733 if (fds[j].fd == -1) goto failed;
4734 fds[j].revents = 0;
4735 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1 ||
4736 _get_fd_type(fds[j].fd) == SOCK_DGRAM)
4738 fds[j].events = POLLOUT;
4740 else
4742 release_sock_fd( writefds->fd_array[i], fds[j].fd );
4743 fds[j].fd = -1;
4744 fds[j].events = 0;
4747 if (exceptfds)
4748 for (i = 0; i < exceptfds->fd_count; i++, j++)
4750 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
4751 if (fds[j].fd == -1) goto failed;
4752 fds[j].revents = 0;
4753 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1)
4755 int oob_inlined = 0;
4756 socklen_t olen = sizeof(oob_inlined);
4758 fds[j].events = POLLHUP;
4760 /* Check if we need to test for urgent data or not */
4761 getsockopt(fds[j].fd, SOL_SOCKET, SO_OOBINLINE, (char*) &oob_inlined, &olen);
4762 if (!oob_inlined)
4763 fds[j].events |= POLLPRI;
4765 else
4767 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
4768 fds[j].fd = -1;
4769 fds[j].events = 0;
4772 return fds;
4774 failed:
4775 count = j;
4776 j = 0;
4777 if (readfds)
4778 for (i = 0; i < readfds->fd_count && j < count; i++, j++)
4779 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
4780 if (writefds)
4781 for (i = 0; i < writefds->fd_count && j < count; i++, j++)
4782 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
4783 if (exceptfds)
4784 for (i = 0; i < exceptfds->fd_count && j < count; i++, j++)
4785 if (fds[j].fd != -1) release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
4786 HeapFree( GetProcessHeap(), 0, fds );
4787 return NULL;
4790 /* release the file descriptor obtained in fd_sets_to_poll */
4791 /* must be called with the original fd_set arrays, before calling get_poll_results */
4792 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
4793 const WS_fd_set *exceptfds, struct pollfd *fds )
4795 unsigned int i, j = 0;
4797 if (readfds)
4799 for (i = 0; i < readfds->fd_count; i++, j++)
4800 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
4802 if (writefds)
4804 for (i = 0; i < writefds->fd_count; i++, j++)
4805 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
4807 if (exceptfds)
4809 for (i = 0; i < exceptfds->fd_count; i++, j++)
4811 if (fds[j].fd == -1) continue;
4812 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
4813 if (fds[j].revents & POLLHUP)
4815 int fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
4816 if (fd != -1)
4817 release_sock_fd( exceptfds->fd_array[i], fd );
4818 else
4819 fds[j].revents = 0;
4825 static int do_poll(struct pollfd *pollfds, int count, int timeout)
4827 struct timeval tv1, tv2;
4828 int ret, torig = timeout;
4830 if (timeout > 0) gettimeofday( &tv1, 0 );
4832 while ((ret = poll( pollfds, count, timeout )) < 0)
4834 if (errno != EINTR) break;
4835 if (timeout < 0) continue;
4836 if (timeout == 0) return 0;
4838 gettimeofday( &tv2, 0 );
4840 tv2.tv_sec -= tv1.tv_sec;
4841 tv2.tv_usec -= tv1.tv_usec;
4842 if (tv2.tv_usec < 0)
4844 tv2.tv_usec += 1000000;
4845 tv2.tv_sec -= 1;
4848 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
4849 if (timeout <= 0) return 0;
4851 return ret;
4854 /* map the poll results back into the Windows fd sets */
4855 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
4856 const struct pollfd *fds )
4858 const struct pollfd *poll_writefds = fds + (readfds ? readfds->fd_count : 0);
4859 const struct pollfd *poll_exceptfds = poll_writefds + (writefds ? writefds->fd_count : 0);
4860 unsigned int i, k, total = 0;
4862 if (readfds)
4864 for (i = k = 0; i < readfds->fd_count; i++)
4866 if (fds[i].revents ||
4867 (readfds == writefds && (poll_writefds[i].revents & POLLOUT) && !(poll_writefds[i].revents & POLLHUP)) ||
4868 (readfds == exceptfds && poll_exceptfds[i].revents))
4869 readfds->fd_array[k++] = readfds->fd_array[i];
4871 readfds->fd_count = k;
4872 total += k;
4874 if (writefds && writefds != readfds)
4876 for (i = k = 0; i < writefds->fd_count; i++)
4878 if (((poll_writefds[i].revents & POLLOUT) && !(poll_writefds[i].revents & POLLHUP)) ||
4879 (writefds == exceptfds && poll_exceptfds[i].revents))
4880 writefds->fd_array[k++] = writefds->fd_array[i];
4882 writefds->fd_count = k;
4883 total += k;
4885 if (exceptfds && exceptfds != readfds && exceptfds != writefds)
4887 for (i = k = 0; i < exceptfds->fd_count; i++)
4888 if (poll_exceptfds[i].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
4889 exceptfds->fd_count = k;
4890 total += k;
4892 return total;
4895 /***********************************************************************
4896 * select (WS2_32.18)
4898 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
4899 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
4900 const struct WS_timeval* ws_timeout)
4902 struct pollfd *pollfds;
4903 int count, ret, timeout = -1;
4905 TRACE("read %p, write %p, excp %p timeout %p\n",
4906 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
4908 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )))
4909 return SOCKET_ERROR;
4911 if (ws_timeout)
4912 timeout = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
4914 ret = do_poll(pollfds, count, timeout);
4915 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
4917 if (ret == -1) SetLastError(wsaErrno());
4918 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
4919 HeapFree( GetProcessHeap(), 0, pollfds );
4920 return ret;
4923 /* helper to send completion messages for client-only i/o operation case */
4924 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
4925 ULONG Information )
4927 SERVER_START_REQ( add_fd_completion )
4929 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
4930 req->cvalue = CompletionValue;
4931 req->status = CompletionStatus;
4932 req->information = Information;
4933 wine_server_call( req );
4935 SERVER_END_REQ;
4939 /***********************************************************************
4940 * send (WS2_32.19)
4942 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
4944 DWORD n;
4945 WSABUF wsabuf;
4947 wsabuf.len = len;
4948 wsabuf.buf = (char*) buf;
4950 if ( WS2_sendto( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
4951 return SOCKET_ERROR;
4952 else
4953 return n;
4956 /***********************************************************************
4957 * WSASend (WS2_32.72)
4959 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4960 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4961 LPWSAOVERLAPPED lpOverlapped,
4962 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4964 return WS2_sendto( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
4965 NULL, 0, lpOverlapped, lpCompletionRoutine );
4968 /***********************************************************************
4969 * WSASendDisconnect (WS2_32.73)
4971 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
4973 return WS_shutdown( s, SD_SEND );
4977 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4978 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4979 const struct WS_sockaddr *to, int tolen,
4980 LPWSAOVERLAPPED lpOverlapped,
4981 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4983 unsigned int i, options;
4984 int n, fd, err, overlapped, flags;
4985 struct ws2_async *wsa = NULL, localwsa;
4986 int totalLength = 0;
4987 DWORD bytes_sent;
4988 BOOL is_blocking;
4990 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
4991 s, lpBuffers, dwBufferCount, dwFlags,
4992 to, tolen, lpOverlapped, lpCompletionRoutine);
4994 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
4995 TRACE( "fd=%d, options=%x\n", fd, options );
4997 if ( fd == -1 ) return SOCKET_ERROR;
4999 if (!lpOverlapped && !lpNumberOfBytesSent)
5001 err = WSAEFAULT;
5002 goto error;
5005 overlapped = (lpOverlapped || lpCompletionRoutine) &&
5006 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
5007 if (overlapped || dwBufferCount > 1)
5009 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[dwBufferCount]))))
5011 err = WSAEFAULT;
5012 goto error;
5015 else
5016 wsa = &localwsa;
5018 wsa->hSocket = SOCKET2HANDLE(s);
5019 wsa->addr = (struct WS_sockaddr *)to;
5020 wsa->addrlen.val = tolen;
5021 wsa->flags = dwFlags;
5022 wsa->lpFlags = &wsa->flags;
5023 wsa->control = NULL;
5024 wsa->n_iovecs = dwBufferCount;
5025 wsa->first_iovec = 0;
5026 for ( i = 0; i < dwBufferCount; i++ )
5028 wsa->iovec[i].iov_base = lpBuffers[i].buf;
5029 wsa->iovec[i].iov_len = lpBuffers[i].len;
5030 totalLength += lpBuffers[i].len;
5033 flags = convert_flags(dwFlags);
5034 n = WS2_send( fd, wsa, flags );
5035 if (n == -1 && errno != EAGAIN)
5037 err = wsaErrno();
5038 goto error;
5041 if (overlapped)
5043 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
5044 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
5046 wsa->user_overlapped = lpOverlapped;
5047 wsa->completion_func = lpCompletionRoutine;
5048 release_sock_fd( s, fd );
5050 if (n == -1 || n < totalLength)
5052 iosb->u.Status = STATUS_PENDING;
5053 iosb->Information = n == -1 ? 0 : n;
5055 SERVER_START_REQ( register_async )
5057 req->type = ASYNC_TYPE_WRITE;
5058 req->async.handle = wine_server_obj_handle( wsa->hSocket );
5059 req->async.callback = wine_server_client_ptr( WS2_async_send );
5060 req->async.iosb = wine_server_client_ptr( iosb );
5061 req->async.arg = wine_server_client_ptr( wsa );
5062 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
5063 req->async.cvalue = cvalue;
5064 err = wine_server_call( req );
5066 SERVER_END_REQ;
5068 /* Enable the event only after starting the async. The server will deliver it as soon as
5069 the async is done. */
5070 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
5072 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
5073 SetLastError(NtStatusToWSAError( err ));
5074 return SOCKET_ERROR;
5077 iosb->u.Status = STATUS_SUCCESS;
5078 iosb->Information = n;
5079 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = n;
5080 if (!wsa->completion_func)
5082 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
5083 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
5084 HeapFree( GetProcessHeap(), 0, wsa );
5086 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
5087 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
5088 SetLastError(ERROR_SUCCESS);
5089 return 0;
5092 if ((err = _is_blocking( s, &is_blocking )))
5094 err = NtStatusToWSAError( err );
5095 goto error;
5098 if ( is_blocking )
5100 /* On a blocking non-overlapped stream socket,
5101 * sending blocks until the entire buffer is sent. */
5102 DWORD timeout_start = GetTickCount();
5104 bytes_sent = n == -1 ? 0 : n;
5106 while (wsa->first_iovec < wsa->n_iovecs)
5108 struct pollfd pfd;
5109 int poll_timeout = -1;
5110 INT64 timeout = get_rcvsnd_timeo(fd, FALSE);
5112 if (timeout)
5114 timeout -= GetTickCount() - timeout_start;
5115 if (timeout < 0) poll_timeout = 0;
5116 else poll_timeout = timeout <= INT_MAX ? timeout : INT_MAX;
5119 pfd.fd = fd;
5120 pfd.events = POLLOUT;
5122 if (!poll_timeout || !poll( &pfd, 1, poll_timeout ))
5124 err = WSAETIMEDOUT;
5125 goto error; /* msdn says a timeout in send is fatal */
5128 n = WS2_send( fd, wsa, flags );
5129 if (n == -1 && errno != EAGAIN)
5131 err = wsaErrno();
5132 goto error;
5135 if (n >= 0)
5136 bytes_sent += n;
5139 else /* non-blocking */
5141 if (n < totalLength)
5142 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
5143 if (n == -1)
5145 err = WSAEWOULDBLOCK;
5146 goto error;
5148 bytes_sent = n;
5151 TRACE(" -> %i bytes\n", bytes_sent);
5153 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = bytes_sent;
5154 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
5155 release_sock_fd( s, fd );
5156 SetLastError(ERROR_SUCCESS);
5157 return 0;
5159 error:
5160 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
5161 release_sock_fd( s, fd );
5162 WARN(" -> ERROR %d\n", err);
5163 SetLastError(err);
5164 return SOCKET_ERROR;
5167 /***********************************************************************
5168 * WSASendTo (WS2_32.74)
5170 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5171 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
5172 const struct WS_sockaddr *to, int tolen,
5173 LPWSAOVERLAPPED lpOverlapped,
5174 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5176 return WS2_sendto( s, lpBuffers, dwBufferCount,
5177 lpNumberOfBytesSent, dwFlags,
5178 to, tolen,
5179 lpOverlapped, lpCompletionRoutine );
5182 /***********************************************************************
5183 * sendto (WS2_32.20)
5185 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
5186 const struct WS_sockaddr *to, int tolen)
5188 DWORD n;
5189 WSABUF wsabuf;
5191 wsabuf.len = len;
5192 wsabuf.buf = (char*) buf;
5194 if ( WS2_sendto(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
5195 return SOCKET_ERROR;
5196 else
5197 return n;
5200 /***********************************************************************
5201 * setsockopt (WS2_32.21)
5203 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
5204 const char *optval, int optlen)
5206 int fd;
5207 int woptval;
5208 struct linger linger;
5209 struct timeval tval;
5211 TRACE("(socket %04lx, %s, optval %s, optlen %d)\n", s,
5212 debugstr_sockopt(level, optname), debugstr_optval(optval, optlen),
5213 optlen);
5215 /* some broken apps pass the value directly instead of a pointer to it */
5216 if(optlen && IS_INTRESOURCE(optval))
5218 SetLastError(WSAEFAULT);
5219 return SOCKET_ERROR;
5222 switch(level)
5224 case WS_SOL_SOCKET:
5225 switch(optname)
5227 /* Some options need some conversion before they can be sent to
5228 * setsockopt. The conversions are done here, then they will fall through
5229 * to the general case. Special options that are not passed to
5230 * setsockopt follow below that.*/
5232 case WS_SO_DONTLINGER:
5233 if (!optval)
5235 SetLastError(WSAEFAULT);
5236 return SOCKET_ERROR;
5238 linger.l_onoff = *(const int*)optval == 0;
5239 linger.l_linger = 0;
5240 level = SOL_SOCKET;
5241 optname = SO_LINGER;
5242 optval = (char*)&linger;
5243 optlen = sizeof(struct linger);
5244 break;
5246 case WS_SO_LINGER:
5247 if (!optval)
5249 SetLastError(WSAEFAULT);
5250 return SOCKET_ERROR;
5252 linger.l_onoff = ((LINGER*)optval)->l_onoff;
5253 linger.l_linger = ((LINGER*)optval)->l_linger;
5254 level = SOL_SOCKET;
5255 optname = SO_LINGER;
5256 optval = (char*)&linger;
5257 optlen = sizeof(struct linger);
5258 break;
5260 case WS_SO_RCVBUF:
5261 if (*(const int*)optval < 2048)
5263 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
5264 return 0;
5266 /* Fall through */
5268 /* The options listed here don't need any special handling. Thanks to
5269 * the conversion happening above, options from there will fall through
5270 * to this, too.*/
5271 case WS_SO_ACCEPTCONN:
5272 case WS_SO_BROADCAST:
5273 case WS_SO_ERROR:
5274 case WS_SO_KEEPALIVE:
5275 case WS_SO_OOBINLINE:
5276 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
5277 * however, using it the BSD way fixes bug 8513 and seems to be what
5278 * most programmers assume, anyway */
5279 case WS_SO_REUSEADDR:
5280 case WS_SO_SNDBUF:
5281 case WS_SO_TYPE:
5282 convert_sockopt(&level, &optname);
5283 break;
5285 /* SO_DEBUG is a privileged operation, ignore it. */
5286 case WS_SO_DEBUG:
5287 TRACE("Ignoring SO_DEBUG\n");
5288 return 0;
5290 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
5291 * socket. According to MSDN, this option is silently ignored.*/
5292 case WS_SO_DONTROUTE:
5293 TRACE("Ignoring SO_DONTROUTE\n");
5294 return 0;
5296 /* Stops two sockets from being bound to the same port. Always happens
5297 * on unix systems, so just drop it. */
5298 case WS_SO_EXCLUSIVEADDRUSE:
5299 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
5300 return 0;
5302 /* After a ConnectEx call succeeds, the socket can't be used with half of the
5303 * normal winsock functions on windows. We don't have that problem. */
5304 case WS_SO_UPDATE_CONNECT_CONTEXT:
5305 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
5306 return 0;
5308 /* After a AcceptEx call succeeds, the socket can't be used with half of the
5309 * normal winsock functions on windows. We don't have that problem. */
5310 case WS_SO_UPDATE_ACCEPT_CONTEXT:
5311 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
5312 return 0;
5314 /* SO_OPENTYPE does not require a valid socket handle. */
5315 case WS_SO_OPENTYPE:
5316 if (!optlen || optlen < sizeof(int) || !optval)
5318 SetLastError(WSAEFAULT);
5319 return SOCKET_ERROR;
5321 get_per_thread_data()->opentype = *(const int *)optval;
5322 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
5323 return 0;
5325 #ifdef SO_RCVTIMEO
5326 case WS_SO_RCVTIMEO:
5327 #endif
5328 #ifdef SO_SNDTIMEO
5329 case WS_SO_SNDTIMEO:
5330 #endif
5331 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
5332 if (optval && optlen == sizeof(UINT32)) {
5333 /* WinSock passes milliseconds instead of struct timeval */
5334 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
5335 tval.tv_sec = *(const UINT32*)optval / 1000;
5336 /* min of 500 milliseconds */
5337 if (tval.tv_sec == 0 && tval.tv_usec && tval.tv_usec < 500000)
5338 tval.tv_usec = 500000;
5339 optlen = sizeof(struct timeval);
5340 optval = (char*)&tval;
5341 } else if (optlen == sizeof(struct timeval)) {
5342 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
5343 } else {
5344 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
5345 return 0;
5347 convert_sockopt(&level, &optname);
5348 break;
5349 #endif
5351 default:
5352 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
5353 SetLastError(WSAENOPROTOOPT);
5354 return SOCKET_ERROR;
5356 break; /* case WS_SOL_SOCKET */
5358 #ifdef HAS_IPX
5359 case WS_NSPROTO_IPX:
5360 switch(optname)
5362 case WS_IPX_PTYPE:
5363 return set_ipx_packettype(s, *(int*)optval);
5365 case WS_IPX_FILTERPTYPE:
5366 /* Sets the receive filter packet type, at the moment we don't support it */
5367 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
5368 /* Returning 0 is better for now than returning a SOCKET_ERROR */
5369 return 0;
5371 default:
5372 FIXME("opt_name:%x\n", optname);
5373 return SOCKET_ERROR;
5375 break; /* case WS_NSPROTO_IPX */
5376 #endif
5378 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
5379 case WS_IPPROTO_TCP:
5380 switch(optname)
5382 case WS_TCP_NODELAY:
5383 convert_sockopt(&level, &optname);
5384 break;
5385 default:
5386 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
5387 return SOCKET_ERROR;
5389 break;
5391 case WS_IPPROTO_IP:
5392 switch(optname)
5394 case WS_IP_ADD_MEMBERSHIP:
5395 case WS_IP_DROP_MEMBERSHIP:
5396 #ifdef IP_HDRINCL
5397 case WS_IP_HDRINCL:
5398 #endif
5399 case WS_IP_MULTICAST_IF:
5400 case WS_IP_MULTICAST_LOOP:
5401 case WS_IP_MULTICAST_TTL:
5402 case WS_IP_OPTIONS:
5403 #ifdef IP_PKTINFO
5404 case WS_IP_PKTINFO:
5405 #endif
5406 case WS_IP_TOS:
5407 case WS_IP_TTL:
5408 #ifdef IP_UNICAST_IF
5409 case WS_IP_UNICAST_IF:
5410 #endif
5411 convert_sockopt(&level, &optname);
5412 break;
5413 case WS_IP_DONTFRAGMENT:
5414 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
5415 return 0;
5416 default:
5417 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
5418 return SOCKET_ERROR;
5420 break;
5422 case WS_IPPROTO_IPV6:
5423 switch(optname)
5425 #ifdef IPV6_ADD_MEMBERSHIP
5426 case WS_IPV6_ADD_MEMBERSHIP:
5427 #endif
5428 #ifdef IPV6_DROP_MEMBERSHIP
5429 case WS_IPV6_DROP_MEMBERSHIP:
5430 #endif
5431 case WS_IPV6_MULTICAST_IF:
5432 case WS_IPV6_MULTICAST_HOPS:
5433 case WS_IPV6_MULTICAST_LOOP:
5434 case WS_IPV6_UNICAST_HOPS:
5435 case WS_IPV6_V6ONLY:
5436 #ifdef IPV6_UNICAST_IF
5437 case WS_IPV6_UNICAST_IF:
5438 #endif
5439 convert_sockopt(&level, &optname);
5440 break;
5441 case WS_IPV6_DONTFRAG:
5442 FIXME("IPV6_DONTFRAG is silently ignored!\n");
5443 return 0;
5444 case WS_IPV6_PROTECTION_LEVEL:
5445 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
5446 return 0;
5447 default:
5448 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
5449 return SOCKET_ERROR;
5451 break;
5453 default:
5454 WARN("Unknown level: 0x%08x\n", level);
5455 SetLastError(WSAEINVAL);
5456 return SOCKET_ERROR;
5457 } /* end switch(level) */
5459 /* avoid endianness issues if argument is a 16-bit int */
5460 if (optval && optlen < sizeof(int))
5462 woptval= *((const INT16 *) optval);
5463 optval= (char*) &woptval;
5464 woptval&= (1 << optlen * 8) - 1;
5465 optlen=sizeof(int);
5467 fd = get_sock_fd( s, 0, NULL );
5468 if (fd == -1) return SOCKET_ERROR;
5470 if (setsockopt(fd, level, optname, optval, optlen) == 0)
5472 #ifdef __APPLE__
5473 if (level == SOL_SOCKET && optname == SO_REUSEADDR &&
5474 setsockopt(fd, level, SO_REUSEPORT, optval, optlen) != 0)
5476 SetLastError(wsaErrno());
5477 release_sock_fd( s, fd );
5478 return SOCKET_ERROR;
5480 #endif
5481 release_sock_fd( s, fd );
5482 return 0;
5484 TRACE("Setting socket error, %d\n", wsaErrno());
5485 SetLastError(wsaErrno());
5486 release_sock_fd( s, fd );
5488 return SOCKET_ERROR;
5491 /***********************************************************************
5492 * shutdown (WS2_32.22)
5494 int WINAPI WS_shutdown(SOCKET s, int how)
5496 int fd, err = WSAENOTSOCK;
5497 unsigned int options = 0, clear_flags = 0;
5499 fd = get_sock_fd( s, 0, &options );
5500 TRACE("socket %04lx, how 0x%x, options 0x%x\n", s, how, options );
5502 if (fd == -1)
5503 return SOCKET_ERROR;
5505 switch( how )
5507 case SD_RECEIVE: /* drop receives */
5508 clear_flags |= FD_READ;
5509 break;
5510 case SD_SEND: /* drop sends */
5511 clear_flags |= FD_WRITE;
5512 break;
5513 case SD_BOTH: /* drop all */
5514 clear_flags |= FD_READ|FD_WRITE;
5515 /*fall through */
5516 default:
5517 clear_flags |= FD_WINE_LISTENING;
5520 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
5522 switch ( how )
5524 case SD_RECEIVE:
5525 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
5526 break;
5527 case SD_SEND:
5528 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
5529 break;
5530 case SD_BOTH:
5531 default:
5532 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
5533 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
5534 break;
5536 if (err) goto error;
5538 else /* non-overlapped mode */
5540 if ( shutdown( fd, how ) )
5542 err = wsaErrno();
5543 goto error;
5547 release_sock_fd( s, fd );
5548 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
5549 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
5550 return 0;
5552 error:
5553 release_sock_fd( s, fd );
5554 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
5555 SetLastError( err );
5556 return SOCKET_ERROR;
5559 /***********************************************************************
5560 * socket (WS2_32.23)
5562 SOCKET WINAPI WS_socket(int af, int type, int protocol)
5564 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
5566 return WSASocketW( af, type, protocol, NULL, 0,
5567 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
5571 /***********************************************************************
5572 * gethostbyaddr (WS2_32.51)
5574 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
5576 struct WS_hostent *retval = NULL;
5577 struct hostent* host;
5578 int unixtype = convert_af_w2u(type);
5579 const char *paddr = addr;
5580 unsigned long loopback;
5581 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5582 char *extrabuf;
5583 int ebufsize = 1024;
5584 struct hostent hostentry;
5585 int locerr = ENOBUFS;
5586 #endif
5588 /* convert back the magic loopback address if necessary */
5589 if (unixtype == AF_INET && len == 4 && !memcmp(addr, magic_loopback_addr, 4))
5591 loopback = htonl(INADDR_LOOPBACK);
5592 paddr = (char*) &loopback;
5595 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5596 host = NULL;
5597 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
5598 while(extrabuf) {
5599 int res = gethostbyaddr_r(paddr, len, unixtype,
5600 &hostentry, extrabuf, ebufsize, &host, &locerr);
5601 if (res != ERANGE) break;
5602 ebufsize *=2;
5603 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
5605 if (host) retval = WS_dup_he(host);
5606 else SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
5607 HeapFree(GetProcessHeap(),0,extrabuf);
5608 #else
5609 EnterCriticalSection( &csWSgetXXXbyYYY );
5610 host = gethostbyaddr(paddr, len, unixtype);
5611 if (host) retval = WS_dup_he(host);
5612 else SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
5613 LeaveCriticalSection( &csWSgetXXXbyYYY );
5614 #endif
5615 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
5616 return retval;
5619 /***********************************************************************
5620 * WS_compare_routes_by_metric_asc (INTERNAL)
5622 * Comparison function for qsort(), for sorting two routes (struct route)
5623 * by metric in ascending order.
5625 static int WS_compare_routes_by_metric_asc(const void *left, const void *right)
5627 return ((const struct route*)left)->metric - ((const struct route*)right)->metric;
5630 /***********************************************************************
5631 * WS_get_local_ips (INTERNAL)
5633 * Returns the list of local IP addresses by going through the network
5634 * adapters and using the local routing table to sort the addresses
5635 * from highest routing priority to lowest routing priority. This
5636 * functionality is inferred from the description for obtaining local
5637 * IP addresses given in the Knowledge Base Article Q160215.
5639 * Please note that the returned hostent is only freed when the thread
5640 * closes and is replaced if another hostent is requested.
5642 static struct WS_hostent* WS_get_local_ips( char *hostname )
5644 int numroutes = 0, i, j;
5645 DWORD n;
5646 PIP_ADAPTER_INFO adapters = NULL, k;
5647 struct WS_hostent *hostlist = NULL;
5648 PMIB_IPFORWARDTABLE routes = NULL;
5649 struct route *route_addrs = NULL;
5650 DWORD adap_size, route_size;
5652 /* Obtain the size of the adapter list and routing table, also allocate memory */
5653 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
5654 return NULL;
5655 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
5656 return NULL;
5657 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
5658 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
5659 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
5660 if (adapters == NULL || routes == NULL || route_addrs == NULL)
5661 goto cleanup;
5662 /* Obtain the adapter list and the full routing table */
5663 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
5664 goto cleanup;
5665 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
5666 goto cleanup;
5667 /* Store the interface associated with each route */
5668 for (n = 0; n < routes->dwNumEntries; n++)
5670 IF_INDEX ifindex;
5671 DWORD ifmetric;
5672 BOOL exists = FALSE;
5674 if (routes->table[n].u1.ForwardType != MIB_IPROUTE_TYPE_DIRECT)
5675 continue;
5676 ifindex = routes->table[n].dwForwardIfIndex;
5677 ifmetric = routes->table[n].dwForwardMetric1;
5678 /* Only store the lowest valued metric for an interface */
5679 for (j = 0; j < numroutes; j++)
5681 if (route_addrs[j].interface == ifindex)
5683 if (route_addrs[j].metric > ifmetric)
5684 route_addrs[j].metric = ifmetric;
5685 exists = TRUE;
5688 if (exists)
5689 continue;
5690 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
5691 if (route_addrs == NULL)
5692 goto cleanup; /* Memory allocation error, fail gracefully */
5693 route_addrs[numroutes].interface = ifindex;
5694 route_addrs[numroutes].metric = ifmetric;
5695 /* If no IP is found in the next step (for whatever reason)
5696 * then fall back to the magic loopback address.
5698 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
5699 numroutes++;
5701 if (numroutes == 0)
5702 goto cleanup; /* No routes, fall back to the Magic IP */
5703 /* Find the IP address associated with each found interface */
5704 for (i = 0; i < numroutes; i++)
5706 for (k = adapters; k != NULL; k = k->Next)
5708 char *ip = k->IpAddressList.IpAddress.String;
5710 if (route_addrs[i].interface == k->Index)
5711 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
5714 /* Allocate a hostent and enough memory for all the IPs,
5715 * including the NULL at the end of the list.
5717 hostlist = WS_create_he(hostname, 1, 0, numroutes+1, sizeof(struct in_addr));
5718 if (hostlist == NULL)
5719 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
5720 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
5721 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
5722 hostlist->h_addrtype = AF_INET;
5723 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
5724 /* Reorder the entries before placing them in the host list. Windows expects
5725 * the IP list in order from highest priority to lowest (the critical thing
5726 * is that most applications expect the first IP to be the default route).
5728 if (numroutes > 1)
5729 qsort(route_addrs, numroutes, sizeof(struct route), WS_compare_routes_by_metric_asc);
5731 for (i = 0; i < numroutes; i++)
5732 (*(struct in_addr *) hostlist->h_addr_list[i]) = route_addrs[i].addr;
5734 /* Cleanup all allocated memory except the address list,
5735 * the address list is used by the calling app.
5737 cleanup:
5738 HeapFree(GetProcessHeap(), 0, route_addrs);
5739 HeapFree(GetProcessHeap(), 0, adapters);
5740 HeapFree(GetProcessHeap(), 0, routes);
5741 return hostlist;
5744 /***********************************************************************
5745 * gethostbyname (WS2_32.52)
5747 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
5749 struct WS_hostent *retval = NULL;
5750 struct hostent* host;
5751 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5752 char *extrabuf;
5753 int ebufsize=1024;
5754 struct hostent hostentry;
5755 int locerr = ENOBUFS;
5756 #endif
5757 char hostname[100];
5758 if(!num_startup) {
5759 SetLastError(WSANOTINITIALISED);
5760 return NULL;
5762 if( gethostname( hostname, 100) == -1) {
5763 SetLastError(WSAENOBUFS); /* appropriate ? */
5764 return retval;
5766 if( !name || !name[0]) {
5767 name = hostname;
5769 /* If the hostname of the local machine is requested then return the
5770 * complete list of local IP addresses */
5771 if(strcmp(name, hostname) == 0)
5772 retval = WS_get_local_ips(hostname);
5773 /* If any other hostname was requested (or the routing table lookup failed)
5774 * then return the IP found by the host OS */
5775 if(retval == NULL)
5777 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5778 host = NULL;
5779 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
5780 while(extrabuf) {
5781 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
5782 if( res != ERANGE) break;
5783 ebufsize *=2;
5784 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
5786 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
5787 #else
5788 EnterCriticalSection( &csWSgetXXXbyYYY );
5789 host = gethostbyname(name);
5790 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
5791 #endif
5792 if (host) retval = WS_dup_he(host);
5793 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5794 HeapFree(GetProcessHeap(),0,extrabuf);
5795 #else
5796 LeaveCriticalSection( &csWSgetXXXbyYYY );
5797 #endif
5799 if (retval && retval->h_addr_list[0][0] == 127 &&
5800 strcmp(name, "localhost") != 0)
5802 /* hostname != "localhost" but has loopback address. replace by our
5803 * special address.*/
5804 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
5806 TRACE( "%s ret %p\n", debugstr_a(name), retval );
5807 return retval;
5811 /***********************************************************************
5812 * getprotobyname (WS2_32.53)
5814 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
5816 struct WS_protoent* retval = NULL;
5817 #ifdef HAVE_GETPROTOBYNAME
5818 struct protoent* proto;
5819 EnterCriticalSection( &csWSgetXXXbyYYY );
5820 if( (proto = getprotobyname(name)) != NULL )
5822 retval = WS_dup_pe(proto);
5824 else {
5825 MESSAGE("protocol %s not found; You might want to add "
5826 "this to /etc/protocols\n", debugstr_a(name) );
5827 SetLastError(WSANO_DATA);
5829 LeaveCriticalSection( &csWSgetXXXbyYYY );
5830 #endif
5831 TRACE( "%s ret %p\n", debugstr_a(name), retval );
5832 return retval;
5836 /***********************************************************************
5837 * getprotobynumber (WS2_32.54)
5839 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
5841 struct WS_protoent* retval = NULL;
5842 #ifdef HAVE_GETPROTOBYNUMBER
5843 struct protoent* proto;
5844 EnterCriticalSection( &csWSgetXXXbyYYY );
5845 if( (proto = getprotobynumber(number)) != NULL )
5847 retval = WS_dup_pe(proto);
5849 else {
5850 MESSAGE("protocol number %d not found; You might want to add "
5851 "this to /etc/protocols\n", number );
5852 SetLastError(WSANO_DATA);
5854 LeaveCriticalSection( &csWSgetXXXbyYYY );
5855 #endif
5856 TRACE("%i ret %p\n", number, retval);
5857 return retval;
5861 /***********************************************************************
5862 * getservbyname (WS2_32.55)
5864 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
5866 struct WS_servent* retval = NULL;
5867 struct servent* serv;
5868 char *name_str;
5869 char *proto_str = NULL;
5871 if (!(name_str = strdup_lower(name))) return NULL;
5873 if (proto && *proto)
5875 if (!(proto_str = strdup_lower(proto)))
5877 HeapFree( GetProcessHeap(), 0, name_str );
5878 return NULL;
5882 EnterCriticalSection( &csWSgetXXXbyYYY );
5883 serv = getservbyname(name_str, proto_str);
5884 if( serv != NULL )
5886 retval = WS_dup_se(serv);
5888 else SetLastError(WSANO_DATA);
5889 LeaveCriticalSection( &csWSgetXXXbyYYY );
5890 HeapFree( GetProcessHeap(), 0, proto_str );
5891 HeapFree( GetProcessHeap(), 0, name_str );
5892 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
5893 return retval;
5896 /***********************************************************************
5897 * freeaddrinfo (WS2_32.@)
5899 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
5901 while (res) {
5902 struct WS_addrinfo *next;
5904 HeapFree(GetProcessHeap(),0,res->ai_canonname);
5905 HeapFree(GetProcessHeap(),0,res->ai_addr);
5906 next = res->ai_next;
5907 HeapFree(GetProcessHeap(),0,res);
5908 res = next;
5912 /* helper functions for getaddrinfo()/getnameinfo() */
5913 static int convert_aiflag_w2u(int winflags) {
5914 unsigned int i;
5915 int unixflags = 0;
5917 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
5918 if (ws_aiflag_map[i][0] & winflags) {
5919 unixflags |= ws_aiflag_map[i][1];
5920 winflags &= ~ws_aiflag_map[i][0];
5922 if (winflags)
5923 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
5924 return unixflags;
5927 static int convert_niflag_w2u(int winflags) {
5928 unsigned int i;
5929 int unixflags = 0;
5931 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
5932 if (ws_niflag_map[i][0] & winflags) {
5933 unixflags |= ws_niflag_map[i][1];
5934 winflags &= ~ws_niflag_map[i][0];
5936 if (winflags)
5937 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
5938 return unixflags;
5941 static int convert_aiflag_u2w(int unixflags) {
5942 unsigned int i;
5943 int winflags = 0;
5945 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
5946 if (ws_aiflag_map[i][1] & unixflags) {
5947 winflags |= ws_aiflag_map[i][0];
5948 unixflags &= ~ws_aiflag_map[i][1];
5950 if (unixflags) /* will warn usually */
5951 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
5952 return winflags;
5955 static int convert_eai_u2w(int unixret) {
5956 int i;
5958 if (!unixret) return 0;
5960 for (i=0;ws_eai_map[i][0];i++)
5961 if (ws_eai_map[i][1] == unixret)
5962 return ws_eai_map[i][0];
5964 if (unixret == EAI_SYSTEM)
5965 /* There are broken versions of glibc which return EAI_SYSTEM
5966 * and set errno to 0 instead of returning EAI_NONAME.
5968 return errno ? sock_get_error( errno ) : WS_EAI_NONAME;
5970 FIXME("Unhandled unix EAI_xxx ret %d\n", unixret);
5971 return unixret;
5974 static char *get_hostname(void)
5976 char *ret;
5977 DWORD size = 0;
5979 GetComputerNameExA( ComputerNamePhysicalDnsHostname, NULL, &size );
5980 if (GetLastError() != ERROR_MORE_DATA) return NULL;
5981 if (!(ret = HeapAlloc( GetProcessHeap(), 0, size ))) return NULL;
5982 if (!GetComputerNameExA( ComputerNamePhysicalDnsHostname, ret, &size ))
5984 HeapFree( GetProcessHeap(), 0, ret );
5985 return NULL;
5987 return ret;
5990 /***********************************************************************
5991 * getaddrinfo (WS2_32.@)
5993 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
5995 #ifdef HAVE_GETADDRINFO
5996 struct addrinfo *unixaires = NULL;
5997 int result;
5998 struct addrinfo unixhints, *punixhints = NULL;
5999 char *hostname;
6000 const char *node;
6002 *res = NULL;
6003 if (!nodename && !servname)
6005 SetLastError(WSAHOST_NOT_FOUND);
6006 return WSAHOST_NOT_FOUND;
6009 hostname = get_hostname();
6010 if (!hostname) return WSA_NOT_ENOUGH_MEMORY;
6012 if (!nodename)
6013 node = NULL;
6014 else if (!nodename[0])
6015 node = hostname;
6016 else
6017 node = nodename;
6019 /* servname tweak required by OSX and BSD kernels */
6020 if (servname && !servname[0]) servname = "0";
6022 if (hints) {
6023 punixhints = &unixhints;
6025 memset(&unixhints, 0, sizeof(unixhints));
6026 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
6028 /* zero is a wildcard, no need to convert */
6029 if (hints->ai_family)
6030 punixhints->ai_family = convert_af_w2u(hints->ai_family);
6031 if (hints->ai_socktype)
6032 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
6033 if (hints->ai_protocol)
6034 punixhints->ai_protocol = max(convert_proto_w2u(hints->ai_protocol), 0);
6036 if (punixhints->ai_socktype < 0)
6038 SetLastError(WSAESOCKTNOSUPPORT);
6039 HeapFree(GetProcessHeap(), 0, hostname);
6040 return SOCKET_ERROR;
6043 /* windows allows invalid combinations of socket type and protocol, unix does not.
6044 * fix the parameters here to make getaddrinfo call always work */
6045 if (punixhints->ai_protocol == IPPROTO_TCP &&
6046 punixhints->ai_socktype != SOCK_STREAM && punixhints->ai_socktype != SOCK_SEQPACKET)
6047 punixhints->ai_socktype = 0;
6049 else if (punixhints->ai_protocol == IPPROTO_UDP && punixhints->ai_socktype != SOCK_DGRAM)
6050 punixhints->ai_socktype = 0;
6052 else if (IS_IPX_PROTO(punixhints->ai_protocol) && punixhints->ai_socktype != SOCK_DGRAM)
6053 punixhints->ai_socktype = 0;
6056 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
6057 result = getaddrinfo(node, servname, punixhints, &unixaires);
6059 if (result && !strcmp(hostname, node))
6061 /* If it didn't work it means the host name IP is not in /etc/hosts, try again
6062 * by sending a NULL host and avoid sending a NULL servname too because that
6063 * is invalid */
6064 ERR_(winediag)("Failed to resolve your host name IP\n");
6065 result = getaddrinfo(NULL, servname ? servname : "0", punixhints, &unixaires);
6067 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
6068 HeapFree(GetProcessHeap(), 0, hostname);
6070 if (!result) {
6071 struct addrinfo *xuai = unixaires;
6072 struct WS_addrinfo **xai = res;
6074 *xai = NULL;
6075 while (xuai) {
6076 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
6077 SIZE_T len;
6079 if (!ai)
6080 goto outofmem;
6082 *xai = ai;xai = &ai->ai_next;
6083 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
6084 ai->ai_family = convert_af_u2w(xuai->ai_family);
6085 /* copy whatever was sent in the hints */
6086 if(hints) {
6087 ai->ai_socktype = hints->ai_socktype;
6088 ai->ai_protocol = hints->ai_protocol;
6089 } else {
6090 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
6091 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
6093 if (xuai->ai_canonname) {
6094 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
6095 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
6096 if (!ai->ai_canonname)
6097 goto outofmem;
6098 strcpy(ai->ai_canonname,xuai->ai_canonname);
6100 len = xuai->ai_addrlen;
6101 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
6102 if (!ai->ai_addr)
6103 goto outofmem;
6104 ai->ai_addrlen = len;
6105 do {
6106 int winlen = ai->ai_addrlen;
6108 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
6109 ai->ai_addrlen = winlen;
6110 break;
6112 len = 2*len;
6113 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
6114 if (!ai->ai_addr)
6115 goto outofmem;
6116 ai->ai_addrlen = len;
6117 } while (1);
6118 xuai = xuai->ai_next;
6120 freeaddrinfo(unixaires);
6122 if (TRACE_ON(winsock))
6124 struct WS_addrinfo *ai = *res;
6125 while (ai)
6127 TRACE("=> %p, flags %#x, family %d, type %d, protocol %d, len %ld, name %s, addr %s\n",
6128 ai, ai->ai_flags, ai->ai_family, ai->ai_socktype, ai->ai_protocol, ai->ai_addrlen,
6129 ai->ai_canonname, debugstr_sockaddr(ai->ai_addr));
6130 ai = ai->ai_next;
6133 } else
6134 result = convert_eai_u2w(result);
6136 SetLastError(result);
6137 return result;
6139 outofmem:
6140 if (*res) WS_freeaddrinfo(*res);
6141 if (unixaires) freeaddrinfo(unixaires);
6142 return WSA_NOT_ENOUGH_MEMORY;
6143 #else
6144 FIXME("getaddrinfo() failed, not found during buildtime.\n");
6145 return EAI_FAIL;
6146 #endif
6149 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
6151 struct WS_addrinfoW *ret;
6153 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
6154 ret->ai_flags = ai->ai_flags;
6155 ret->ai_family = ai->ai_family;
6156 ret->ai_socktype = ai->ai_socktype;
6157 ret->ai_protocol = ai->ai_protocol;
6158 ret->ai_addrlen = ai->ai_addrlen;
6159 ret->ai_canonname = NULL;
6160 ret->ai_addr = NULL;
6161 ret->ai_next = NULL;
6162 if (ai->ai_canonname)
6164 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
6165 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR))))
6167 HeapFree(GetProcessHeap(), 0, ret);
6168 return NULL;
6170 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
6172 if (ai->ai_addr)
6174 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, ai->ai_addrlen)))
6176 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
6177 HeapFree(GetProcessHeap(), 0, ret);
6178 return NULL;
6180 memcpy(ret->ai_addr, ai->ai_addr, ai->ai_addrlen);
6182 return ret;
6185 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
6187 struct WS_addrinfoW *ret, *infoW;
6189 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
6190 while (info->ai_next)
6192 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
6194 FreeAddrInfoW(ret);
6195 return NULL;
6197 infoW = infoW->ai_next;
6198 info = info->ai_next;
6200 return ret;
6203 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
6205 struct WS_addrinfo *ret;
6207 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
6208 ret->ai_flags = ai->ai_flags;
6209 ret->ai_family = ai->ai_family;
6210 ret->ai_socktype = ai->ai_socktype;
6211 ret->ai_protocol = ai->ai_protocol;
6212 ret->ai_addrlen = ai->ai_addrlen;
6213 ret->ai_canonname = NULL;
6214 ret->ai_addr = NULL;
6215 ret->ai_next = NULL;
6216 if (ai->ai_canonname)
6218 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
6219 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
6221 HeapFree(GetProcessHeap(), 0, ret);
6222 return NULL;
6224 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
6226 if (ai->ai_addr)
6228 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
6230 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
6231 HeapFree(GetProcessHeap(), 0, ret);
6232 return NULL;
6234 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
6236 return ret;
6239 /***********************************************************************
6240 * GetAddrInfoW (WS2_32.@)
6242 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
6244 int ret, len;
6245 char *nodenameA = NULL, *servnameA = NULL;
6246 struct WS_addrinfo *resA, *hintsA = NULL;
6248 *res = NULL;
6249 if (nodename)
6251 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
6252 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
6253 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
6255 if (servname)
6257 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
6258 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
6260 HeapFree(GetProcessHeap(), 0, nodenameA);
6261 return EAI_MEMORY;
6263 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
6266 if (hints) hintsA = addrinfo_WtoA(hints);
6267 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
6268 WS_freeaddrinfo(hintsA);
6270 if (!ret)
6272 *res = addrinfo_list_AtoW(resA);
6273 WS_freeaddrinfo(resA);
6276 HeapFree(GetProcessHeap(), 0, nodenameA);
6277 HeapFree(GetProcessHeap(), 0, servnameA);
6278 return ret;
6281 /***********************************************************************
6282 * FreeAddrInfoW (WS2_32.@)
6284 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
6286 while (ai)
6288 ADDRINFOW *next;
6289 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
6290 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
6291 next = ai->ai_next;
6292 HeapFree(GetProcessHeap(), 0, ai);
6293 ai = next;
6297 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
6298 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
6300 #ifdef HAVE_GETNAMEINFO
6301 int ret;
6302 union generic_unix_sockaddr sa_u;
6303 unsigned int size;
6305 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
6306 serv, servlen, flags);
6308 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
6309 if (!size)
6311 SetLastError(WSAEFAULT);
6312 return WSA_NOT_ENOUGH_MEMORY;
6314 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
6315 return convert_eai_u2w(ret);
6316 #else
6317 FIXME("getnameinfo() failed, not found during buildtime.\n");
6318 return EAI_FAIL;
6319 #endif
6322 int WINAPI GetNameInfoW(const SOCKADDR *sa, WS_socklen_t salen, PWCHAR host,
6323 DWORD hostlen, PWCHAR serv, DWORD servlen, INT flags)
6325 int ret;
6326 char *hostA = NULL, *servA = NULL;
6328 if (host && (!(hostA = HeapAlloc(GetProcessHeap(), 0, hostlen)))) return EAI_MEMORY;
6329 if (serv && (!(servA = HeapAlloc(GetProcessHeap(), 0, servlen))))
6331 HeapFree(GetProcessHeap(), 0, hostA);
6332 return EAI_MEMORY;
6335 ret = WS_getnameinfo(sa, salen, hostA, hostlen, servA, servlen, flags);
6336 if (!ret)
6338 if (host) MultiByteToWideChar(CP_ACP, 0, hostA, -1, host, hostlen);
6339 if (serv) MultiByteToWideChar(CP_ACP, 0, servA, -1, serv, servlen);
6342 HeapFree(GetProcessHeap(), 0, hostA);
6343 HeapFree(GetProcessHeap(), 0, servA);
6344 return ret;
6347 /***********************************************************************
6348 * getservbyport (WS2_32.56)
6350 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
6352 struct WS_servent* retval = NULL;
6353 #ifdef HAVE_GETSERVBYPORT
6354 struct servent* serv;
6355 char *proto_str = NULL;
6357 if (proto && *proto)
6359 if (!(proto_str = strdup_lower(proto))) return NULL;
6361 EnterCriticalSection( &csWSgetXXXbyYYY );
6362 if( (serv = getservbyport(port, proto_str)) != NULL ) {
6363 retval = WS_dup_se(serv);
6365 else SetLastError(WSANO_DATA);
6366 LeaveCriticalSection( &csWSgetXXXbyYYY );
6367 HeapFree( GetProcessHeap(), 0, proto_str );
6368 #endif
6369 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
6370 return retval;
6374 /***********************************************************************
6375 * gethostname (WS2_32.57)
6377 int WINAPI WS_gethostname(char *name, int namelen)
6379 char buf[256];
6380 int len;
6382 TRACE("name %p, len %d\n", name, namelen);
6384 if (!name)
6386 SetLastError(WSAEFAULT);
6387 return SOCKET_ERROR;
6390 if (gethostname(buf, sizeof(buf)) != 0)
6392 SetLastError(wsaErrno());
6393 return SOCKET_ERROR;
6396 TRACE("<- '%s'\n", buf);
6397 len = strlen(buf);
6398 if (len > 15)
6399 WARN("Windows supports NetBIOS name length up to 15 bytes!\n");
6400 if (namelen <= len)
6402 SetLastError(WSAEFAULT);
6403 WARN("<- not enough space for hostname, required %d, got %d!\n", len + 1, namelen);
6404 return SOCKET_ERROR;
6406 strcpy(name, buf);
6407 return 0;
6411 /* ------------------------------------- Windows sockets extensions -- *
6413 * ------------------------------------------------------------------- */
6415 /***********************************************************************
6416 * WSAEnumNetworkEvents (WS2_32.36)
6418 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
6420 int ret;
6421 int i;
6422 int errors[FD_MAX_EVENTS];
6424 TRACE("%04lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
6426 SERVER_START_REQ( get_socket_event )
6428 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6429 req->service = TRUE;
6430 req->c_event = wine_server_obj_handle( hEvent );
6431 wine_server_set_reply( req, errors, sizeof(errors) );
6432 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
6434 SERVER_END_REQ;
6435 if (!ret)
6437 for (i = 0; i < FD_MAX_EVENTS; i++)
6438 lpEvent->iErrorCode[i] = NtStatusToWSAError(errors[i]);
6439 return 0;
6441 SetLastError(WSAEINVAL);
6442 return SOCKET_ERROR;
6445 /***********************************************************************
6446 * WSAEventSelect (WS2_32.39)
6448 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
6450 int ret;
6452 TRACE("%04lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
6454 SERVER_START_REQ( set_socket_event )
6456 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6457 req->mask = lEvent;
6458 req->event = wine_server_obj_handle( hEvent );
6459 req->window = 0;
6460 req->msg = 0;
6461 ret = wine_server_call( req );
6463 SERVER_END_REQ;
6464 if (!ret) return 0;
6465 SetLastError(WSAEINVAL);
6466 return SOCKET_ERROR;
6469 /**********************************************************************
6470 * WSAGetOverlappedResult (WS2_32.40)
6472 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
6473 LPDWORD lpcbTransfer, BOOL fWait,
6474 LPDWORD lpdwFlags )
6476 NTSTATUS status;
6478 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
6479 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
6481 if ( lpOverlapped == NULL )
6483 ERR( "Invalid pointer\n" );
6484 SetLastError(WSA_INVALID_PARAMETER);
6485 return FALSE;
6488 status = lpOverlapped->Internal;
6489 if (status == STATUS_PENDING)
6491 if (!fWait)
6493 SetLastError( WSA_IO_INCOMPLETE );
6494 return FALSE;
6497 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
6498 INFINITE ) == WAIT_FAILED)
6499 return FALSE;
6500 status = lpOverlapped->Internal;
6503 if ( lpcbTransfer )
6504 *lpcbTransfer = lpOverlapped->InternalHigh;
6506 if ( lpdwFlags )
6507 *lpdwFlags = lpOverlapped->u.s.Offset;
6509 if (status) SetLastError( RtlNtStatusToDosError(status) );
6510 return !status;
6514 /***********************************************************************
6515 * WSAAsyncSelect (WS2_32.101)
6517 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
6519 int ret;
6521 TRACE("%04lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
6523 SERVER_START_REQ( set_socket_event )
6525 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6526 req->mask = lEvent;
6527 req->event = 0;
6528 req->window = wine_server_user_handle( hWnd );
6529 req->msg = uMsg;
6530 ret = wine_server_call( req );
6532 SERVER_END_REQ;
6533 if (!ret) return 0;
6534 SetLastError(WSAEINVAL);
6535 return SOCKET_ERROR;
6538 /***********************************************************************
6539 * WSACreateEvent (WS2_32.31)
6542 WSAEVENT WINAPI WSACreateEvent(void)
6544 /* Create a manual-reset event, with initial state: unsignaled */
6545 TRACE("\n");
6547 return CreateEventW(NULL, TRUE, FALSE, NULL);
6550 /***********************************************************************
6551 * WSACloseEvent (WS2_32.29)
6554 BOOL WINAPI WSACloseEvent(WSAEVENT event)
6556 TRACE ("event=%p\n", event);
6558 return CloseHandle(event);
6561 /***********************************************************************
6562 * WSASocketA (WS2_32.78)
6565 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
6566 LPWSAPROTOCOL_INFOA lpProtocolInfo,
6567 GROUP g, DWORD dwFlags)
6569 INT len;
6570 WSAPROTOCOL_INFOW info;
6572 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
6573 af, type, protocol, lpProtocolInfo, g, dwFlags);
6575 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
6577 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
6578 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
6579 info.szProtocol, WSAPROTOCOL_LEN + 1);
6581 if (!len)
6583 SetLastError(WSAEINVAL);
6584 return SOCKET_ERROR;
6587 return WSASocketW(af, type, protocol, &info, g, dwFlags);
6590 /***********************************************************************
6591 * WSASocketW (WS2_32.79)
6594 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
6595 LPWSAPROTOCOL_INFOW lpProtocolInfo,
6596 GROUP g, DWORD dwFlags)
6598 SOCKET ret;
6599 DWORD err;
6600 int unixaf, unixtype, ipxptype = -1;
6603 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
6604 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
6607 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
6608 af, type, protocol, lpProtocolInfo, g, dwFlags );
6610 if (!num_startup)
6612 err = WSANOTINITIALISED;
6613 goto done;
6616 /* hack for WSADuplicateSocket */
6617 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
6618 ret = lpProtocolInfo->dwServiceFlags3;
6619 TRACE("\tgot duplicate %04lx\n", ret);
6620 return ret;
6623 if (lpProtocolInfo)
6625 if (af == FROM_PROTOCOL_INFO || !af)
6626 af = lpProtocolInfo->iAddressFamily;
6627 if (type == FROM_PROTOCOL_INFO || !type)
6628 type = lpProtocolInfo->iSocketType;
6629 if (protocol == FROM_PROTOCOL_INFO || !protocol)
6630 protocol = lpProtocolInfo->iProtocol;
6633 if (!type && (af || protocol))
6635 int autoproto = protocol;
6636 WSAPROTOCOL_INFOW infow;
6638 /* default to the first valid protocol */
6639 if (!autoproto)
6640 autoproto = valid_protocols[0];
6641 else if(IS_IPX_PROTO(autoproto))
6642 autoproto = WS_NSPROTO_IPX;
6644 if (WS_EnterSingleProtocolW(autoproto, &infow))
6646 type = infow.iSocketType;
6648 /* after win2003 it's no longer possible to pass AF_UNSPEC
6649 using the protocol info struct */
6650 if (!lpProtocolInfo && af == WS_AF_UNSPEC)
6651 af = infow.iAddressFamily;
6656 Windows has an extension to the IPX protocol that allows one to create sockets
6657 and set the IPX packet type at the same time, to do that a caller will use
6658 a protocol like NSPROTO_IPX + <PACKET TYPE>
6660 if (IS_IPX_PROTO(protocol))
6661 ipxptype = protocol - WS_NSPROTO_IPX;
6663 /* convert the socket family, type and protocol */
6664 unixaf = convert_af_w2u(af);
6665 unixtype = convert_socktype_w2u(type);
6666 protocol = convert_proto_w2u(protocol);
6667 if (unixaf == AF_UNSPEC) unixaf = -1;
6669 /* filter invalid parameters */
6670 if (protocol < 0)
6672 /* the type could not be converted */
6673 if (type && unixtype < 0)
6675 err = WSAESOCKTNOSUPPORT;
6676 goto done;
6679 err = WSAEPROTONOSUPPORT;
6680 goto done;
6682 if (unixaf < 0)
6684 /* both family and protocol can't be invalid */
6685 if (protocol <= 0)
6687 err = WSAEINVAL;
6688 goto done;
6691 /* family could not be converted and neither socket type */
6692 if (unixtype < 0 && af >= 0)
6695 err = WSAESOCKTNOSUPPORT;
6696 goto done;
6699 err = WSAEAFNOSUPPORT;
6700 goto done;
6703 SERVER_START_REQ( create_socket )
6705 req->family = unixaf;
6706 req->type = unixtype;
6707 req->protocol = protocol;
6708 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
6709 req->attributes = (dwFlags & WSA_FLAG_NO_HANDLE_INHERIT) ? 0 : OBJ_INHERIT;
6710 req->flags = dwFlags & ~WSA_FLAG_NO_HANDLE_INHERIT;
6711 set_error( wine_server_call( req ) );
6712 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
6714 SERVER_END_REQ;
6715 if (ret)
6717 TRACE("\tcreated %04lx\n", ret );
6718 if (ipxptype > 0)
6719 set_ipx_packettype(ret, ipxptype);
6720 return ret;
6723 err = GetLastError();
6724 if (err == WSAEACCES) /* raw socket denied */
6726 if (type == SOCK_RAW)
6727 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
6728 else
6729 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
6731 else
6733 /* invalid combination of valid parameters, like SOCK_STREAM + IPPROTO_UDP */
6734 if (err == WSAEINVAL)
6735 err = WSAESOCKTNOSUPPORT;
6736 else if (err == WSAEOPNOTSUPP)
6737 err = WSAEPROTONOSUPPORT;
6740 done:
6741 WARN("\t\tfailed, error %d!\n", err);
6742 SetLastError(err);
6743 return INVALID_SOCKET;
6746 /***********************************************************************
6747 * WSAJoinLeaf (WS2_32.58)
6750 SOCKET WINAPI WSAJoinLeaf(
6751 SOCKET s,
6752 const struct WS_sockaddr *addr,
6753 int addrlen,
6754 LPWSABUF lpCallerData,
6755 LPWSABUF lpCalleeData,
6756 LPQOS lpSQOS,
6757 LPQOS lpGQOS,
6758 DWORD dwFlags)
6760 FIXME("stub.\n");
6761 return INVALID_SOCKET;
6764 /***********************************************************************
6765 * __WSAFDIsSet (WS2_32.151)
6767 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
6769 int i = set->fd_count, ret = 0;
6771 while (i--)
6772 if (set->fd_array[i] == s)
6774 ret = 1;
6775 break;
6778 TRACE("(socket %04lx, fd_set %p, count %i) <- %d\n", s, set, set->fd_count, ret);
6779 return ret;
6782 /***********************************************************************
6783 * WSAIsBlocking (WS2_32.114)
6785 BOOL WINAPI WSAIsBlocking(void)
6787 /* By default WinSock should set all its sockets to non-blocking mode
6788 * and poll in PeekMessage loop when processing "blocking" ones. This
6789 * function is supposed to tell if the program is in this loop. Our
6790 * blocking calls are truly blocking so we always return FALSE.
6792 * Note: It is allowed to call this function without prior WSAStartup().
6795 TRACE("\n");
6796 return FALSE;
6799 /***********************************************************************
6800 * WSACancelBlockingCall (WS2_32.113)
6802 INT WINAPI WSACancelBlockingCall(void)
6804 TRACE("\n");
6805 return 0;
6808 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
6810 FIXME("How was this called?\n");
6811 return x();
6815 /***********************************************************************
6816 * WSASetBlockingHook (WS2_32.109)
6818 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
6820 FARPROC prev = blocking_hook;
6821 blocking_hook = lpBlockFunc;
6822 TRACE("hook %p\n", lpBlockFunc);
6823 return prev;
6827 /***********************************************************************
6828 * WSAUnhookBlockingHook (WS2_32.110)
6830 INT WINAPI WSAUnhookBlockingHook(void)
6832 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
6833 return 0;
6837 /* ----------------------------------- end of API stuff */
6839 /* ----------------------------------- helper functions -
6841 * TODO: Merge WS_dup_..() stuff into one function that
6842 * would operate with a generic structure containing internal
6843 * pointers (via a template of some kind).
6846 static int list_size(char** l, int item_size)
6848 int i,j = 0;
6849 if(l)
6850 { for(i=0;l[i];i++)
6851 j += (item_size) ? item_size : strlen(l[i]) + 1;
6852 j += (i + 1) * sizeof(char*); }
6853 return j;
6856 static int list_dup(char** l_src, char** l_to, int item_size)
6858 char *p;
6859 int i;
6861 for (i = 0; l_src[i]; i++) ;
6862 p = (char *)(l_to + i + 1);
6863 for (i = 0; l_src[i]; i++)
6865 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
6866 memcpy(p, l_src[i], count);
6867 l_to[i] = p;
6868 p += count;
6870 l_to[i] = NULL;
6871 return p - (char *)l_to;
6874 /* ----- hostent */
6876 /* create a hostent entry
6878 * Creates the entry with enough memory for the name, aliases
6879 * addresses, and the address pointers. Also copies the name
6880 * and sets up all the pointers.
6882 * NOTE: The alias and address lists must be allocated with room
6883 * for the NULL item terminating the list. This is true even if
6884 * the list has no items ("aliases" and "addresses" must be
6885 * at least "1", a truly empty list is invalid).
6887 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length)
6889 struct WS_hostent *p_to;
6890 char *p;
6891 int size = (sizeof(struct WS_hostent) +
6892 strlen(name) + 1 +
6893 sizeof(char *) * aliases +
6894 aliases_size +
6895 sizeof(char *) * addresses +
6896 address_length * (addresses - 1)), i;
6898 if (!(p_to = check_buffer_he(size))) return NULL;
6899 memset(p_to, 0, size);
6901 /* Use the memory in the same way winsock does.
6902 * First set the pointer for aliases, second set the pointers for addresses.
6903 * Third fill the addresses indexes, fourth jump aliases names size.
6904 * Fifth fill the hostname.
6905 * NOTE: This method is valid for OS version's >= XP.
6907 p = (char *)(p_to + 1);
6908 p_to->h_aliases = (char **)p;
6909 p += sizeof(char *)*aliases;
6911 p_to->h_addr_list = (char **)p;
6912 p += sizeof(char *)*addresses;
6914 for (i = 0, addresses--; i < addresses; i++, p += address_length)
6915 p_to->h_addr_list[i] = p;
6917 /* NOTE: h_aliases must be filled in manually because we don't know each string
6918 * size, leave these pointers NULL (already set to NULL by memset earlier).
6920 p += aliases_size;
6922 p_to->h_name = p;
6923 strcpy(p, name);
6925 return p_to;
6928 /* duplicate hostent entry
6929 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
6930 * Ditto for protoent and servent.
6932 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
6934 int i, addresses = 0, alias_size = 0;
6935 struct WS_hostent *p_to;
6936 char *p;
6938 for( i = 0; p_he->h_aliases[i]; i++) alias_size += strlen(p_he->h_aliases[i]) + 1;
6939 while (p_he->h_addr_list[addresses]) addresses++;
6941 p_to = WS_create_he(p_he->h_name, i + 1, alias_size, addresses + 1, p_he->h_length);
6943 if (!p_to) return NULL;
6944 p_to->h_addrtype = convert_af_u2w(p_he->h_addrtype);
6945 p_to->h_length = p_he->h_length;
6947 for(i = 0, p = p_to->h_addr_list[0]; p_he->h_addr_list[i]; i++, p += p_to->h_length)
6948 memcpy(p, p_he->h_addr_list[i], p_to->h_length);
6950 /* Fill the aliases after the IP data */
6951 for(i = 0; p_he->h_aliases[i]; i++)
6953 p_to->h_aliases[i] = p;
6954 strcpy(p, p_he->h_aliases[i]);
6955 p += strlen(p) + 1;
6958 return p_to;
6961 /* ----- protoent */
6963 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
6965 char *p;
6966 struct WS_protoent *p_to;
6968 int size = (sizeof(*p_pe) +
6969 strlen(p_pe->p_name) + 1 +
6970 list_size(p_pe->p_aliases, 0));
6972 if (!(p_to = check_buffer_pe(size))) return NULL;
6973 p_to->p_proto = p_pe->p_proto;
6975 p = (char *)(p_to + 1);
6976 p_to->p_name = p;
6977 strcpy(p, p_pe->p_name);
6978 p += strlen(p) + 1;
6980 p_to->p_aliases = (char **)p;
6981 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
6982 return p_to;
6985 /* ----- servent */
6987 static struct WS_servent *WS_dup_se(const struct servent* p_se)
6989 char *p;
6990 struct WS_servent *p_to;
6992 int size = (sizeof(*p_se) +
6993 strlen(p_se->s_proto) + 1 +
6994 strlen(p_se->s_name) + 1 +
6995 list_size(p_se->s_aliases, 0));
6997 if (!(p_to = check_buffer_se(size))) return NULL;
6998 p_to->s_port = p_se->s_port;
7000 p = (char *)(p_to + 1);
7001 p_to->s_name = p;
7002 strcpy(p, p_se->s_name);
7003 p += strlen(p) + 1;
7005 p_to->s_proto = p;
7006 strcpy(p, p_se->s_proto);
7007 p += strlen(p) + 1;
7009 p_to->s_aliases = (char **)p;
7010 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
7011 return p_to;
7015 /***********************************************************************
7016 * WSARecv (WS2_32.67)
7018 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
7019 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
7020 LPWSAOVERLAPPED lpOverlapped,
7021 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
7023 return WS2_recv_base(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
7024 NULL, NULL, lpOverlapped, lpCompletionRoutine, NULL);
7027 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
7028 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
7029 struct WS_sockaddr *lpFrom,
7030 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
7031 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
7032 LPWSABUF lpControlBuffer )
7034 unsigned int i, options;
7035 int n, fd, err, overlapped, flags;
7036 struct ws2_async *wsa = NULL, localwsa;
7037 BOOL is_blocking;
7038 DWORD timeout_start = GetTickCount();
7039 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
7041 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
7042 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
7043 (lpFromlen ? *lpFromlen : -1),
7044 lpOverlapped, lpCompletionRoutine);
7046 fd = get_sock_fd( s, FILE_READ_DATA, &options );
7047 TRACE( "fd=%d, options=%x\n", fd, options );
7049 if (fd == -1) return SOCKET_ERROR;
7051 if (*lpFlags & WS_MSG_OOB)
7053 /* It's invalid to receive OOB data from an OOBINLINED socket
7054 * as OOB data is turned into normal data. */
7055 i = sizeof(n);
7056 if (!getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, (char*) &n, &i) && n)
7058 err = WSAEINVAL;
7059 goto error;
7063 overlapped = (lpOverlapped || lpCompletionRoutine) &&
7064 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
7065 if (overlapped || dwBufferCount > 1)
7067 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[dwBufferCount]))))
7069 err = WSAEFAULT;
7070 goto error;
7073 else
7074 wsa = &localwsa;
7076 wsa->hSocket = SOCKET2HANDLE(s);
7077 wsa->flags = *lpFlags;
7078 wsa->lpFlags = lpFlags;
7079 wsa->addr = lpFrom;
7080 wsa->addrlen.ptr = lpFromlen;
7081 wsa->control = lpControlBuffer;
7082 wsa->n_iovecs = dwBufferCount;
7083 wsa->first_iovec = 0;
7084 for (i = 0; i < dwBufferCount; i++)
7086 /* check buffer first to trigger write watches */
7087 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
7089 err = WSAEFAULT;
7090 goto error;
7092 wsa->iovec[i].iov_base = lpBuffers[i].buf;
7093 wsa->iovec[i].iov_len = lpBuffers[i].len;
7096 flags = convert_flags(wsa->flags);
7097 for (;;)
7099 n = WS2_recv( fd, wsa, flags );
7100 if (n == -1)
7102 /* Unix-like systems return EINVAL when attempting to read OOB data from
7103 * an empty socket buffer, convert that to a Windows expected return. */
7104 if ((flags & MSG_OOB) && errno == EINVAL)
7105 errno = EWOULDBLOCK;
7107 if (errno != EAGAIN)
7109 int loc_errno = errno;
7110 err = wsaErrno();
7111 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
7112 goto error;
7115 else if (lpNumberOfBytesRecvd) *lpNumberOfBytesRecvd = n;
7117 if (overlapped)
7119 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
7121 wsa->user_overlapped = lpOverlapped;
7122 wsa->completion_func = lpCompletionRoutine;
7123 release_sock_fd( s, fd );
7125 if (n == -1)
7127 iosb->u.Status = STATUS_PENDING;
7128 iosb->Information = 0;
7130 SERVER_START_REQ( register_async )
7132 req->type = ASYNC_TYPE_READ;
7133 req->async.handle = wine_server_obj_handle( wsa->hSocket );
7134 req->async.callback = wine_server_client_ptr( WS2_async_recv );
7135 req->async.iosb = wine_server_client_ptr( iosb );
7136 req->async.arg = wine_server_client_ptr( wsa );
7137 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
7138 req->async.cvalue = cvalue;
7139 err = wine_server_call( req );
7141 SERVER_END_REQ;
7143 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
7144 SetLastError(NtStatusToWSAError( err ));
7145 return SOCKET_ERROR;
7148 iosb->u.Status = STATUS_SUCCESS;
7149 iosb->Information = n;
7150 if (!wsa->completion_func)
7152 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
7153 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
7154 HeapFree( GetProcessHeap(), 0, wsa );
7156 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
7157 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
7158 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7159 return 0;
7162 if (n != -1) break;
7164 if ((err = _is_blocking( s, &is_blocking )))
7166 err = NtStatusToWSAError( err );
7167 goto error;
7170 if ( is_blocking )
7172 struct pollfd pfd;
7173 int poll_timeout = -1;
7174 INT64 timeout = get_rcvsnd_timeo(fd, TRUE);
7176 if (timeout)
7178 timeout -= GetTickCount() - timeout_start;
7179 if (timeout < 0) poll_timeout = 0;
7180 else poll_timeout = timeout <= INT_MAX ? timeout : INT_MAX;
7183 pfd.fd = fd;
7184 pfd.events = POLLIN;
7185 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
7187 if (!poll_timeout || !poll( &pfd, 1, poll_timeout ))
7189 err = WSAETIMEDOUT;
7190 /* a timeout is not fatal */
7191 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7192 goto error;
7195 else
7197 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7198 err = WSAEWOULDBLOCK;
7199 goto error;
7203 TRACE(" -> %i bytes\n", n);
7204 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
7205 release_sock_fd( s, fd );
7206 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7207 SetLastError(ERROR_SUCCESS);
7209 return 0;
7211 error:
7212 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
7213 release_sock_fd( s, fd );
7214 WARN(" -> ERROR %d\n", err);
7215 SetLastError( err );
7216 return SOCKET_ERROR;
7219 /***********************************************************************
7220 * WSARecvFrom (WS2_32.69)
7222 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
7223 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
7224 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
7225 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
7228 return WS2_recv_base( s, lpBuffers, dwBufferCount,
7229 lpNumberOfBytesRecvd, lpFlags,
7230 lpFrom, lpFromlen,
7231 lpOverlapped, lpCompletionRoutine, NULL );
7234 /***********************************************************************
7235 * WSCInstallProvider (WS2_32.88)
7237 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
7238 LPCWSTR lpszProviderDllPath,
7239 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
7240 DWORD dwNumberOfEntries,
7241 LPINT lpErrno )
7243 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
7244 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
7245 dwNumberOfEntries, lpErrno);
7246 *lpErrno = 0;
7247 return 0;
7251 /***********************************************************************
7252 * WSCDeinstallProvider (WS2_32.83)
7254 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
7256 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
7257 *lpErrno = 0;
7258 return 0;
7262 /***********************************************************************
7263 * WSAAccept (WS2_32.26)
7265 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
7266 LPCONDITIONPROC lpfnCondition, DWORD_PTR dwCallbackData)
7269 int ret = 0, size;
7270 WSABUF CallerId, CallerData, CalleeId, CalleeData;
7271 /* QOS SQOS, GQOS; */
7272 GROUP g;
7273 SOCKET cs;
7274 SOCKADDR src_addr, dst_addr;
7276 TRACE("socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
7277 s, addr, addrlen, lpfnCondition, dwCallbackData);
7279 cs = WS_accept(s, addr, addrlen);
7280 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
7281 if (!lpfnCondition) return cs;
7283 if (addr && addrlen)
7285 CallerId.buf = (char *)addr;
7286 CallerId.len = *addrlen;
7288 else
7290 size = sizeof(src_addr);
7291 WS_getpeername(cs, &src_addr, &size);
7292 CallerId.buf = (char *)&src_addr;
7293 CallerId.len = size;
7295 CallerData.buf = NULL;
7296 CallerData.len = 0;
7298 size = sizeof(dst_addr);
7299 WS_getsockname(cs, &dst_addr, &size);
7301 CalleeId.buf = (char *)&dst_addr;
7302 CalleeId.len = sizeof(dst_addr);
7304 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
7305 &CalleeId, &CalleeData, &g, dwCallbackData);
7307 switch (ret)
7309 case CF_ACCEPT:
7310 return cs;
7311 case CF_DEFER:
7312 SERVER_START_REQ( set_socket_deferred )
7314 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
7315 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
7316 if ( !wine_server_call_err ( req ) )
7318 SetLastError( WSATRY_AGAIN );
7319 WS_closesocket( cs );
7322 SERVER_END_REQ;
7323 return SOCKET_ERROR;
7324 case CF_REJECT:
7325 WS_closesocket(cs);
7326 SetLastError(WSAECONNREFUSED);
7327 return SOCKET_ERROR;
7328 default:
7329 FIXME("Unknown return type from Condition function\n");
7330 SetLastError(WSAENOTSOCK);
7331 return SOCKET_ERROR;
7335 /***********************************************************************
7336 * WSADuplicateSocketA (WS2_32.32)
7338 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
7340 return WS_DuplicateSocket(FALSE, s, dwProcessId, (LPWSAPROTOCOL_INFOW) lpProtocolInfo);
7343 /***********************************************************************
7344 * WSADuplicateSocketW (WS2_32.33)
7346 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
7348 return WS_DuplicateSocket(TRUE, s, dwProcessId, lpProtocolInfo);
7351 /***********************************************************************
7352 * WSAInstallServiceClassA (WS2_32.48)
7354 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
7356 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
7357 SetLastError(WSAEACCES);
7358 return SOCKET_ERROR;
7361 /***********************************************************************
7362 * WSAInstallServiceClassW (WS2_32.49)
7364 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
7366 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
7367 SetLastError(WSAEACCES);
7368 return SOCKET_ERROR;
7371 /***********************************************************************
7372 * WSARemoveServiceClass (WS2_32.70)
7374 int WINAPI WSARemoveServiceClass(LPGUID info)
7376 FIXME("Request to remove service %p\n",info);
7377 SetLastError(WSATYPE_NOT_FOUND);
7378 return SOCKET_ERROR;
7381 /***********************************************************************
7382 * inet_ntop (WS2_32.@)
7384 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
7386 #ifdef HAVE_INET_NTOP
7387 struct WS_in6_addr *in6;
7388 struct WS_in_addr *in;
7389 PCSTR pdst;
7391 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
7392 if (!buffer)
7394 SetLastError( STATUS_INVALID_PARAMETER );
7395 return NULL;
7398 switch (family)
7400 case WS_AF_INET:
7402 in = addr;
7403 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
7404 break;
7406 case WS_AF_INET6:
7408 in6 = addr;
7409 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
7410 break;
7412 default:
7413 SetLastError( WSAEAFNOSUPPORT );
7414 return NULL;
7417 if (!pdst) SetLastError( STATUS_INVALID_PARAMETER );
7418 return pdst;
7419 #else
7420 FIXME( "not supported on this platform\n" );
7421 SetLastError( WSAEAFNOSUPPORT );
7422 return NULL;
7423 #endif
7426 /***********************************************************************
7427 * inet_pton (WS2_32.@)
7429 INT WINAPI WS_inet_pton( INT family, PCSTR addr, PVOID buffer)
7431 #ifdef HAVE_INET_PTON
7432 int unixaf, ret;
7434 TRACE("family %d, addr %s, buffer (%p)\n", family, debugstr_a(addr), buffer);
7436 if (!addr || !buffer)
7438 SetLastError(WSAEFAULT);
7439 return SOCKET_ERROR;
7442 unixaf = convert_af_w2u(family);
7443 if (unixaf != AF_INET && unixaf != AF_INET6)
7445 SetLastError(WSAEAFNOSUPPORT);
7446 return SOCKET_ERROR;
7449 ret = inet_pton(unixaf, addr, buffer);
7450 if (ret == -1) SetLastError(wsaErrno());
7451 return ret;
7452 #else
7453 FIXME( "not supported on this platform\n" );
7454 SetLastError( WSAEAFNOSUPPORT );
7455 return SOCKET_ERROR;
7456 #endif
7459 /***********************************************************************
7460 * InetPtonW (WS2_32.@)
7462 INT WINAPI InetPtonW(INT family, PCWSTR addr, PVOID buffer)
7464 char *addrA;
7465 int len;
7466 INT ret;
7468 TRACE("family %d, addr %s, buffer (%p)\n", family, debugstr_w(addr), buffer);
7470 if (!addr)
7472 SetLastError(WSAEFAULT);
7473 return SOCKET_ERROR;
7476 len = WideCharToMultiByte(CP_ACP, 0, addr, -1, NULL, 0, NULL, NULL);
7477 if (!(addrA = HeapAlloc(GetProcessHeap(), 0, len)))
7479 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7480 return SOCKET_ERROR;
7482 WideCharToMultiByte(CP_ACP, 0, addr, -1, addrA, len, NULL, NULL);
7484 ret = WS_inet_pton(family, addrA, buffer);
7486 HeapFree(GetProcessHeap(), 0, addrA);
7487 return ret;
7490 /***********************************************************************
7491 * WSAStringToAddressA (WS2_32.80)
7493 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
7494 INT AddressFamily,
7495 LPWSAPROTOCOL_INFOA lpProtocolInfo,
7496 LPSOCKADDR lpAddress,
7497 LPINT lpAddressLength)
7499 INT res=0;
7500 LPSTR workBuffer=NULL,ptrPort;
7502 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
7503 lpProtocolInfo, lpAddress, lpAddressLength );
7505 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
7507 if (!AddressString)
7509 SetLastError(WSAEINVAL);
7510 return SOCKET_ERROR;
7513 if (lpProtocolInfo)
7514 FIXME("ProtocolInfo not implemented.\n");
7516 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
7517 strlen(AddressString) + 1);
7518 if (!workBuffer)
7520 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7521 return SOCKET_ERROR;
7524 strcpy(workBuffer, AddressString);
7526 switch(AddressFamily)
7528 case WS_AF_INET:
7530 struct in_addr inetaddr;
7532 /* If lpAddressLength is too small, tell caller the size we need */
7533 if (*lpAddressLength < sizeof(SOCKADDR_IN))
7535 *lpAddressLength = sizeof(SOCKADDR_IN);
7536 res = WSAEFAULT;
7537 break;
7539 *lpAddressLength = sizeof(SOCKADDR_IN);
7540 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
7542 ((LPSOCKADDR_IN)lpAddress)->sin_family = WS_AF_INET;
7544 ptrPort = strchr(workBuffer, ':');
7545 if(ptrPort)
7547 /* User may have entered an IPv6 and asked to parse as IPv4 */
7548 if(strchr(ptrPort + 1, ':'))
7550 res = WSAEINVAL;
7551 break;
7553 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
7554 *ptrPort = '\0';
7556 else
7558 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
7561 if(inet_aton(workBuffer, &inetaddr) > 0)
7563 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
7564 res = 0;
7566 else
7567 res = WSAEINVAL;
7569 break;
7572 case WS_AF_INET6:
7574 struct in6_addr inetaddr;
7575 /* If lpAddressLength is too small, tell caller the size we need */
7576 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
7578 *lpAddressLength = sizeof(SOCKADDR_IN6);
7579 res = WSAEFAULT;
7580 break;
7582 #ifdef HAVE_INET_PTON
7583 *lpAddressLength = sizeof(SOCKADDR_IN6);
7584 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
7586 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
7588 /* This one is a bit tricky. An IPv6 address contains colons, so the
7589 * check from IPv4 doesn't work like that. However, IPv6 addresses that
7590 * contain a port are written with braces like [fd12:3456:7890::1]:12345
7591 * so what we will do is to look for ']', check if the next char is a
7592 * colon, and if it is, parse the port as in IPv4. */
7594 ptrPort = strchr(workBuffer, ']');
7595 if(ptrPort && *(++ptrPort) == ':')
7597 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort+1));
7598 *ptrPort = '\0';
7600 else
7602 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
7605 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
7607 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
7608 sizeof(struct in6_addr));
7609 res = 0;
7611 else
7612 #endif /* HAVE_INET_PTON */
7613 res = WSAEINVAL;
7615 break;
7617 default:
7618 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
7619 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
7620 res = WSAEINVAL;
7623 HeapFree(GetProcessHeap(), 0, workBuffer);
7625 if (!res) return 0;
7626 SetLastError(res);
7627 return SOCKET_ERROR;
7630 /***********************************************************************
7631 * WSAStringToAddressW (WS2_32.81)
7633 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
7634 * If this should be the case, it would be required to map these digits
7635 * to Unicode digits (0-9) using FoldString first.
7637 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
7638 INT AddressFamily,
7639 LPWSAPROTOCOL_INFOW lpProtocolInfo,
7640 LPSOCKADDR lpAddress,
7641 LPINT lpAddressLength)
7643 INT sBuffer,res=0;
7644 LPSTR workBuffer=NULL;
7645 WSAPROTOCOL_INFOA infoA;
7646 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
7648 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
7649 lpAddress, lpAddressLength );
7651 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
7653 /* if ProtocolInfo is available - convert to ANSI variant */
7654 if (lpProtocolInfo)
7656 lpProtoInfoA = &infoA;
7657 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
7659 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
7660 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
7662 SetLastError(WSAEINVAL);
7663 return SOCKET_ERROR;
7667 if (AddressString)
7669 /* Translate AddressString to ANSI code page - assumes that only
7670 standard digits 0-9 are used with this API call */
7671 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
7672 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
7674 if (workBuffer)
7676 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
7677 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
7678 lpAddress,lpAddressLength);
7679 HeapFree( GetProcessHeap(), 0, workBuffer );
7680 return res;
7682 else
7683 res = WSA_NOT_ENOUGH_MEMORY;
7685 else
7686 res = WSAEINVAL;
7688 SetLastError(res);
7689 return SOCKET_ERROR;
7692 /***********************************************************************
7693 * WSAAddressToStringA (WS2_32.27)
7695 * See WSAAddressToStringW
7697 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
7698 LPWSAPROTOCOL_INFOA info, LPSTR string,
7699 LPDWORD lenstr )
7701 DWORD size;
7702 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
7703 CHAR *p;
7705 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
7707 if (!sockaddr) return SOCKET_ERROR;
7708 if (!string || !lenstr) return SOCKET_ERROR;
7710 switch(sockaddr->sa_family)
7712 case WS_AF_INET:
7713 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
7714 sprintf( buffer, "%u.%u.%u.%u:%u",
7715 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
7716 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
7717 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
7718 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
7719 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
7721 p = strchr( buffer, ':' );
7722 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
7723 break;
7725 case WS_AF_INET6:
7727 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
7728 size_t slen;
7730 buffer[0] = 0;
7731 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
7732 if ((sockaddr6->sin6_port))
7733 strcpy(buffer, "[");
7734 slen = strlen(buffer);
7735 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, &buffer[slen], sizeof(buffer) - slen))
7737 SetLastError(WSAEINVAL);
7738 return SOCKET_ERROR;
7740 if ((sockaddr6->sin6_scope_id))
7741 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
7742 if ((sockaddr6->sin6_port))
7743 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
7744 break;
7747 default:
7748 SetLastError(WSAEINVAL);
7749 return SOCKET_ERROR;
7752 size = strlen( buffer ) + 1;
7754 if (*lenstr < size)
7756 *lenstr = size;
7757 SetLastError(WSAEFAULT);
7758 return SOCKET_ERROR;
7761 TRACE("=> %s,%u bytes\n", debugstr_a(buffer), size);
7762 *lenstr = size;
7763 strcpy( string, buffer );
7764 return 0;
7767 /***********************************************************************
7768 * WSAAddressToStringW (WS2_32.28)
7770 * Convert a sockaddr address into a readable address string.
7772 * PARAMS
7773 * sockaddr [I] Pointer to a sockaddr structure.
7774 * len [I] Size of the sockaddr structure.
7775 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
7776 * string [I/O] Pointer to a buffer to receive the address string.
7777 * lenstr [I/O] Size of the receive buffer in WCHARs.
7779 * RETURNS
7780 * Success: 0
7781 * Failure: SOCKET_ERROR
7783 * NOTES
7784 * The 'info' parameter is ignored.
7786 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
7787 LPWSAPROTOCOL_INFOW info, LPWSTR string,
7788 LPDWORD lenstr )
7790 INT ret;
7791 DWORD size;
7792 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
7793 CHAR bufAddr[54];
7795 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
7797 size = *lenstr;
7798 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
7800 if (ret) return ret;
7802 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
7804 if (*lenstr < size)
7806 *lenstr = size;
7807 SetLastError(WSAEFAULT);
7808 return SOCKET_ERROR;
7811 TRACE("=> %s,%u bytes\n", debugstr_w(buffer), size);
7812 *lenstr = size;
7813 lstrcpyW( string, buffer );
7814 return 0;
7817 /***********************************************************************
7818 * WSAEnumNameSpaceProvidersA (WS2_32.34)
7820 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
7822 FIXME( "(%p %p) Stub!\n", len, buffer );
7823 return 0;
7826 /***********************************************************************
7827 * WSAEnumNameSpaceProvidersW (WS2_32.35)
7829 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
7831 FIXME( "(%p %p) Stub!\n", len, buffer );
7832 return 0;
7835 /***********************************************************************
7836 * WSAGetQOSByName (WS2_32.41)
7838 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
7840 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
7841 return FALSE;
7844 /***********************************************************************
7845 * WSAGetServiceClassInfoA (WS2_32.42)
7847 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
7848 LPWSASERVICECLASSINFOA info )
7850 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
7851 len, info );
7852 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7853 return SOCKET_ERROR;
7856 /***********************************************************************
7857 * WSAGetServiceClassInfoW (WS2_32.43)
7859 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
7860 LPWSASERVICECLASSINFOW info )
7862 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
7863 len, info );
7864 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7865 return SOCKET_ERROR;
7868 /***********************************************************************
7869 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
7871 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
7873 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
7874 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7875 return SOCKET_ERROR;
7878 /***********************************************************************
7879 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
7881 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
7883 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
7884 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7885 return SOCKET_ERROR;
7888 /***********************************************************************
7889 * WSALookupServiceBeginA (WS2_32.59)
7891 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
7892 DWORD dwControlFlags,
7893 LPHANDLE lphLookup)
7895 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
7896 lphLookup);
7897 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7898 return SOCKET_ERROR;
7901 /***********************************************************************
7902 * WSALookupServiceBeginW (WS2_32.60)
7904 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
7905 DWORD dwControlFlags,
7906 LPHANDLE lphLookup)
7908 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
7909 lphLookup);
7910 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7911 return SOCKET_ERROR;
7914 /***********************************************************************
7915 * WSALookupServiceEnd (WS2_32.61)
7917 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
7919 FIXME("(%p) Stub!\n", lookup );
7920 return 0;
7923 /***********************************************************************
7924 * WSALookupServiceNextA (WS2_32.62)
7926 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
7928 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
7929 SetLastError(WSA_E_NO_MORE);
7930 return SOCKET_ERROR;
7933 /***********************************************************************
7934 * WSALookupServiceNextW (WS2_32.63)
7936 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
7938 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
7939 SetLastError(WSA_E_NO_MORE);
7940 return SOCKET_ERROR;
7943 /***********************************************************************
7944 * WSANtohl (WS2_32.64)
7946 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
7948 TRACE( "(%04lx 0x%08x %p)\n", s, netlong, lphostlong );
7950 if (!lphostlong) return WSAEFAULT;
7952 *lphostlong = ntohl( netlong );
7953 return 0;
7956 /***********************************************************************
7957 * WSANtohs (WS2_32.65)
7959 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
7961 TRACE( "(%04lx 0x%08x %p)\n", s, netshort, lphostshort );
7963 if (!lphostshort) return WSAEFAULT;
7965 *lphostshort = ntohs( netshort );
7966 return 0;
7969 /***********************************************************************
7970 * WSAProviderConfigChange (WS2_32.66)
7972 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
7973 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
7975 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
7976 return SOCKET_ERROR;
7979 /***********************************************************************
7980 * WSARecvDisconnect (WS2_32.68)
7982 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
7984 TRACE( "(%04lx %p)\n", s, disconnectdata );
7986 return WS_shutdown( s, SD_RECEIVE );
7989 /***********************************************************************
7990 * WSASetServiceA (WS2_32.76)
7992 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
7994 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
7995 return 0;
7998 /***********************************************************************
7999 * WSASetServiceW (WS2_32.77)
8001 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
8003 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
8004 return 0;
8007 /***********************************************************************
8008 * WSCEnableNSProvider (WS2_32.84)
8010 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
8012 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
8013 return 0;
8016 /***********************************************************************
8017 * WSCGetProviderPath (WS2_32.86)
8019 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
8021 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
8023 if (!errcode || !provider || !len) return WSAEFAULT;
8025 *errcode = WSAEINVAL;
8026 return SOCKET_ERROR;
8029 /***********************************************************************
8030 * WSCInstallNameSpace (WS2_32.87)
8032 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
8033 DWORD version, LPGUID provider )
8035 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
8036 namespace, version, debugstr_guid(provider) );
8037 return 0;
8040 /***********************************************************************
8041 * WSCUnInstallNameSpace (WS2_32.89)
8043 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
8045 FIXME("(%p) Stub!\n", lpProviderId);
8046 return NO_ERROR;
8049 /***********************************************************************
8050 * WSCWriteProviderOrder (WS2_32.91)
8052 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
8054 FIXME("(%p 0x%08x) Stub!\n", entry, number);
8055 return 0;
8058 /***********************************************************************
8059 * WSANSPIoctl (WS2_32.91)
8061 INT WINAPI WSANSPIoctl( HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer,
8062 DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer,
8063 LPDWORD lpcbBytesReturned, LPWSACOMPLETION lpCompletion )
8065 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup, dwControlCode,
8066 lpvInBuffer, cbInBuffer, lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpCompletion);
8067 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8068 return SOCKET_ERROR;
8071 /*****************************************************************************
8072 * WSAEnumProtocolsA [WS2_32.@]
8074 * see function WSAEnumProtocolsW
8076 INT WINAPI WSAEnumProtocolsA( LPINT protocols, LPWSAPROTOCOL_INFOA buffer, LPDWORD len )
8078 return WS_EnumProtocols( FALSE, protocols, (LPWSAPROTOCOL_INFOW) buffer, len);
8081 /*****************************************************************************
8082 * WSAEnumProtocolsW [WS2_32.@]
8084 * Retrieves information about specified set of active network protocols.
8086 * PARAMS
8087 * protocols [I] Pointer to null-terminated array of protocol id's. NULL
8088 * retrieves information on all available protocols.
8089 * buffer [I] Pointer to a buffer to be filled with WSAPROTOCOL_INFO
8090 * structures.
8091 * len [I/O] Pointer to a variable specifying buffer size. On output
8092 * the variable holds the number of bytes needed when the
8093 * specified size is too small.
8095 * RETURNS
8096 * Success: number of WSAPROTOCOL_INFO structures in buffer.
8097 * Failure: SOCKET_ERROR
8099 * NOTES
8100 * NT4SP5 does not return SPX if protocols == NULL
8102 * BUGS
8103 * - NT4SP5 returns in addition these list of NETBIOS protocols
8104 * (address family 17), each entry two times one for socket type 2 and 5
8106 * iProtocol szProtocol
8107 * 0x80000000 \Device\NwlnkNb
8108 * 0xfffffffa \Device\NetBT_CBENT7
8109 * 0xfffffffb \Device\Nbf_CBENT7
8110 * 0xfffffffc \Device\NetBT_NdisWan5
8111 * 0xfffffffd \Device\NetBT_El9202
8112 * 0xfffffffe \Device\Nbf_El9202
8113 * 0xffffffff \Device\Nbf_NdisWan4
8115 * - there is no check that the operating system supports the returned
8116 * protocols
8118 INT WINAPI WSAEnumProtocolsW( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
8120 return WS_EnumProtocols( TRUE, protocols, buffer, len);
8123 /*****************************************************************************
8124 * WSCEnumProtocols [WS2_32.@]
8126 * PARAMS
8127 * protocols [I] Null-terminated array of iProtocol values.
8128 * buffer [O] Buffer of WSAPROTOCOL_INFOW structures.
8129 * len [I/O] Size of buffer on input/output.
8130 * errno [O] Error code.
8132 * RETURNS
8133 * Success: number of protocols to be reported on.
8134 * Failure: SOCKET_ERROR. error is in errno.
8136 * BUGS
8137 * Doesn't supply info on layered protocols.
8140 INT WINAPI WSCEnumProtocols( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len, LPINT err )
8142 INT ret = WSAEnumProtocolsW( protocols, buffer, len );
8144 if (ret == SOCKET_ERROR) *err = WSAENOBUFS;
8146 return ret;