ws2_32: Add stub for TransmitFile.
[wine.git] / dlls / ws2_32 / socket.c
blob4edb5796413751b34af7c72f6b54295ef3051c93
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 * TransmitFile
2730 static BOOL WINAPI WS2_TransmitFile( SOCKET s, HANDLE h, DWORD file_bytes, DWORD bytes_per_send,
2731 LPOVERLAPPED overlapped, LPTRANSMIT_FILE_BUFFERS buffers,
2732 DWORD flags )
2734 FIXME("(%lx, %p, %d, %d, %p, %p, %d): stub !\n", s, h, file_bytes, bytes_per_send, overlapped,
2735 buffers, flags );
2736 WSASetLastError( WSAEOPNOTSUPP );
2737 return FALSE;
2740 /***********************************************************************
2741 * GetAcceptExSockaddrs
2743 static void WINAPI WS2_GetAcceptExSockaddrs(PVOID buffer, DWORD data_size, DWORD local_size, DWORD remote_size,
2744 struct WS_sockaddr **local_addr, LPINT local_addr_len,
2745 struct WS_sockaddr **remote_addr, LPINT remote_addr_len)
2747 char *cbuf = buffer;
2748 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer, data_size, local_size, remote_size, local_addr,
2749 local_addr_len, remote_addr, remote_addr_len );
2750 cbuf += data_size;
2752 *local_addr_len = *(int *) cbuf;
2753 *local_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2755 cbuf += local_size;
2757 *remote_addr_len = *(int *) cbuf;
2758 *remote_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2761 /***********************************************************************
2762 * WSASendMsg
2764 int WINAPI WSASendMsg( SOCKET s, LPWSAMSG msg, DWORD dwFlags, LPDWORD lpNumberOfBytesSent,
2765 LPWSAOVERLAPPED lpOverlapped,
2766 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
2768 if (!msg)
2770 SetLastError( WSAEFAULT );
2771 return SOCKET_ERROR;
2774 return WS2_sendto( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesSent,
2775 dwFlags, msg->name, msg->namelen,
2776 lpOverlapped, lpCompletionRoutine );
2779 /***********************************************************************
2780 * WSARecvMsg
2782 * Perform a receive operation that is capable of returning message
2783 * control headers. It is important to note that the WSAMSG parameter
2784 * must remain valid throughout the operation, even when an overlapped
2785 * receive is performed.
2787 static int WINAPI WS2_WSARecvMsg( SOCKET s, LPWSAMSG msg, LPDWORD lpNumberOfBytesRecvd,
2788 LPWSAOVERLAPPED lpOverlapped,
2789 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2791 if (!msg)
2793 SetLastError( WSAEFAULT );
2794 return SOCKET_ERROR;
2797 return WS2_recv_base( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesRecvd,
2798 &msg->dwFlags, msg->name, &msg->namelen,
2799 lpOverlapped, lpCompletionRoutine, &msg->Control );
2802 /***********************************************************************
2803 * interface_bind (INTERNAL)
2805 * Take bind() calls on any name corresponding to a local network adapter and restrict the given socket to
2806 * operating only on the specified interface. This restriction consists of two components:
2807 * 1) An outgoing packet restriction suggesting the egress interface for all packets.
2808 * 2) An incoming packet restriction dropping packets not meant for the interface.
2809 * If the function succeeds in placing these restrictions (returns TRUE) then the name for the bind() may
2810 * safely be changed to INADDR_ANY, permitting the transmission and receipt of broadcast packets on the
2811 * socket. This behavior is only relevant to UDP sockets and is needed for applications that expect to be able
2812 * to receive broadcast packets on a socket that is bound to a specific network interface.
2814 static BOOL interface_bind( SOCKET s, int fd, struct sockaddr *addr )
2816 struct sockaddr_in *in_sock = (struct sockaddr_in *) addr;
2817 in_addr_t bind_addr = in_sock->sin_addr.s_addr;
2818 PIP_ADAPTER_INFO adapters = NULL, adapter;
2819 BOOL ret = FALSE;
2820 DWORD adap_size;
2821 int enable = 1;
2823 if (bind_addr == htonl(INADDR_ANY) || bind_addr == htonl(INADDR_LOOPBACK))
2824 return FALSE; /* Not binding to a network adapter, special interface binding unnecessary. */
2825 if (_get_fd_type(fd) != SOCK_DGRAM)
2826 return FALSE; /* Special interface binding is only necessary for UDP datagrams. */
2827 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
2828 goto cleanup;
2829 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
2830 if (adapters == NULL || GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
2831 goto cleanup;
2832 /* Search the IPv4 adapter list for the appropriate binding interface */
2833 for (adapter = adapters; adapter != NULL; adapter = adapter->Next)
2835 in_addr_t adapter_addr = (in_addr_t) inet_addr(adapter->IpAddressList.IpAddress.String);
2837 if (bind_addr == adapter_addr)
2839 #if defined(IP_BOUND_IF)
2840 /* IP_BOUND_IF sets both the incoming and outgoing restriction at once */
2841 if (setsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &adapter->Index, sizeof(adapter->Index)) != 0)
2842 goto cleanup;
2843 ret = TRUE;
2844 #elif defined(LINUX_BOUND_IF)
2845 in_addr_t ifindex = (in_addr_t) htonl(adapter->Index);
2846 struct interface_filter specific_interface_filter;
2847 struct sock_fprog filter_prog;
2849 if (setsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex, sizeof(ifindex)) != 0)
2850 goto cleanup; /* Failed to suggest egress interface */
2851 specific_interface_filter = generic_interface_filter;
2852 specific_interface_filter.iface_rule.k = adapter->Index;
2853 specific_interface_filter.ip_rule.k = htonl(adapter_addr);
2854 filter_prog.len = sizeof(generic_interface_filter)/sizeof(struct sock_filter);
2855 filter_prog.filter = (struct sock_filter *) &specific_interface_filter;
2856 if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog, sizeof(filter_prog)) != 0)
2857 goto cleanup; /* Failed to specify incoming packet filter */
2858 ret = TRUE;
2859 #else
2860 FIXME("Broadcast packets on interface-bound sockets are not currently supported on this platform, "
2861 "receiving broadcast packets will not work on socket %04lx.\n", s);
2862 #endif
2863 break;
2866 /* Will soon be switching to INADDR_ANY: permit address reuse */
2867 if (ret && setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) == 0)
2868 TRACE("Socket %04lx bound to interface index %d\n", s, adapter->Index);
2869 else
2870 ret = FALSE;
2872 cleanup:
2873 if(!ret)
2874 ERR("Failed to bind to interface, receiving broadcast packets will not work on socket %04lx.\n", s);
2875 HeapFree(GetProcessHeap(), 0, adapters);
2876 return ret;
2879 /***********************************************************************
2880 * bind (WS2_32.2)
2882 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
2884 int fd = get_sock_fd( s, 0, NULL );
2885 int res = SOCKET_ERROR;
2887 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2889 if (fd != -1)
2891 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
2893 SetLastError(WSAEAFNOSUPPORT);
2895 else
2897 union generic_unix_sockaddr uaddr;
2898 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2899 if (!uaddrlen)
2901 SetLastError(WSAEFAULT);
2903 else
2905 #ifdef IPV6_V6ONLY
2906 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
2907 if (name->sa_family == WS_AF_INET6 &&
2908 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
2910 int enable = 1;
2911 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
2913 release_sock_fd( s, fd );
2914 SetLastError(WSAEAFNOSUPPORT);
2915 return SOCKET_ERROR;
2918 #endif
2919 if (name->sa_family == WS_AF_INET)
2921 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2922 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2924 /* Trying to bind to the default host interface, using
2925 * INADDR_ANY instead*/
2926 WARN("Trying to bind to magic IP address, using "
2927 "INADDR_ANY instead.\n");
2928 in4->sin_addr.s_addr = htonl(INADDR_ANY);
2930 else if (interface_bind(s, fd, &uaddr.addr))
2931 in4->sin_addr.s_addr = htonl(INADDR_ANY);
2933 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
2935 int loc_errno = errno;
2936 WARN("\tfailure - errno = %i\n", errno);
2937 errno = loc_errno;
2938 switch (errno)
2940 case EADDRNOTAVAIL:
2941 SetLastError(WSAEINVAL);
2942 break;
2943 case EADDRINUSE:
2945 int optval = 0;
2946 socklen_t optlen = sizeof(optval);
2947 /* Windows >= 2003 will return different results depending on
2948 * SO_REUSEADDR, WSAEACCES may be returned representing that
2949 * the socket hijacking protection prevented the bind */
2950 if (!getsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&optval, &optlen) && optval)
2952 SetLastError(WSAEACCES);
2953 break;
2955 /* fall through */
2957 default:
2958 SetLastError(wsaErrno());
2959 break;
2962 else
2964 res=0; /* success */
2968 release_sock_fd( s, fd );
2970 return res;
2973 /***********************************************************************
2974 * closesocket (WS2_32.3)
2976 int WINAPI WS_closesocket(SOCKET s)
2978 int res = SOCKET_ERROR, fd;
2979 if (num_startup)
2981 fd = get_sock_fd(s, FILE_READ_DATA, NULL);
2982 if (fd >= 0)
2984 release_sock_fd(s, fd);
2985 if (CloseHandle(SOCKET2HANDLE(s)))
2986 res = 0;
2988 else
2989 SetLastError(WSAENOTSOCK);
2991 else
2992 SetLastError(WSANOTINITIALISED);
2993 TRACE("(socket %04lx) -> %d\n", s, res);
2994 return res;
2997 static int do_connect(int fd, const struct WS_sockaddr* name, int namelen)
2999 union generic_unix_sockaddr uaddr;
3000 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
3002 if (!uaddrlen)
3003 return WSAEFAULT;
3005 if (name->sa_family == WS_AF_INET)
3007 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
3008 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
3010 /* Trying to connect to magic replace-loopback address,
3011 * assuming we really want to connect to localhost */
3012 TRACE("Trying to connect to magic IP address, using "
3013 "INADDR_LOOPBACK instead.\n");
3014 in4->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
3018 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
3019 return 0;
3021 return wsaErrno();
3024 /***********************************************************************
3025 * connect (WS2_32.4)
3027 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
3029 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
3031 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
3033 if (fd != -1)
3035 NTSTATUS status;
3036 BOOL is_blocking;
3037 int ret = do_connect(fd, name, namelen);
3038 if (ret == 0)
3039 goto connect_success;
3041 if (ret == WSAEINPROGRESS)
3043 /* tell wineserver that a connection is in progress */
3044 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3045 FD_CONNECT,
3046 FD_WINE_CONNECTED|FD_WINE_LISTENING);
3047 status = _is_blocking( s, &is_blocking );
3048 if (status)
3050 release_sock_fd( s, fd );
3051 set_error( status );
3052 return SOCKET_ERROR;
3054 if (is_blocking)
3056 int result;
3057 /* block here */
3058 do_block(fd, POLLIN | POLLOUT, -1);
3059 _sync_sock_state(s); /* let wineserver notice connection */
3060 /* retrieve any error codes from it */
3061 result = _get_sock_error(s, FD_CONNECT_BIT);
3062 if (result)
3063 SetLastError(NtStatusToWSAError(result));
3064 else
3066 goto connect_success;
3069 else
3071 SetLastError(WSAEWOULDBLOCK);
3074 else
3076 SetLastError(ret);
3078 release_sock_fd( s, fd );
3080 return SOCKET_ERROR;
3082 connect_success:
3083 release_sock_fd( s, fd );
3084 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3085 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
3086 FD_CONNECT|FD_WINE_LISTENING);
3087 TRACE("\tconnected %04lx\n", s);
3088 return 0;
3091 /***********************************************************************
3092 * WSAConnect (WS2_32.30)
3094 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
3095 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
3096 LPQOS lpSQOS, LPQOS lpGQOS )
3098 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
3099 FIXME("unsupported parameters!\n");
3100 return WS_connect( s, name, namelen );
3103 /***********************************************************************
3104 * ConnectEx
3106 static BOOL WINAPI WS2_ConnectEx(SOCKET s, const struct WS_sockaddr* name, int namelen,
3107 PVOID sendBuf, DWORD sendBufLen, LPDWORD sent, LPOVERLAPPED ov)
3109 int fd, ret, status;
3111 if (!ov)
3113 SetLastError( ERROR_INVALID_PARAMETER );
3114 return FALSE;
3117 fd = get_sock_fd( s, FILE_READ_DATA, NULL );
3118 if (fd == -1)
3120 SetLastError( WSAENOTSOCK );
3121 return FALSE;
3124 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
3125 s, name, debugstr_sockaddr(name), namelen, sendBuf, sendBufLen, ov);
3127 ret = is_fd_bound(fd, NULL, NULL);
3128 if (ret <= 0)
3130 SetLastError(ret == -1 ? wsaErrno() : WSAEINVAL);
3131 release_sock_fd( s, fd );
3132 return FALSE;
3135 ret = do_connect(fd, name, namelen);
3136 if (ret == 0)
3138 WSABUF wsabuf;
3140 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3141 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
3142 FD_CONNECT|FD_WINE_LISTENING);
3144 wsabuf.len = sendBufLen;
3145 wsabuf.buf = (char*) sendBuf;
3147 /* WSASend takes care of completion if need be */
3148 if (WSASend(s, &wsabuf, sendBuf ? 1 : 0, sent, 0, ov, NULL) != SOCKET_ERROR)
3149 goto connection_success;
3151 else if (ret == WSAEINPROGRESS)
3153 struct ws2_async *wsa;
3154 ULONG_PTR cvalue = (((ULONG_PTR)ov->hEvent & 1) == 0) ? (ULONG_PTR)ov : 0;
3156 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3157 FD_CONNECT,
3158 FD_WINE_CONNECTED|FD_WINE_LISTENING);
3160 /* Indirectly call WSASend */
3161 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof( struct ws2_async, iovec[1] ))))
3163 SetLastError(WSAEFAULT);
3165 else
3167 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)ov;
3168 iosb->u.Status = STATUS_PENDING;
3169 iosb->Information = 0;
3171 wsa->hSocket = SOCKET2HANDLE(s);
3172 wsa->addr = NULL;
3173 wsa->addrlen.val = 0;
3174 wsa->flags = 0;
3175 wsa->lpFlags = &wsa->flags;
3176 wsa->control = NULL;
3177 wsa->n_iovecs = sendBuf ? 1 : 0;
3178 wsa->first_iovec = 0;
3179 wsa->completion_func = NULL;
3180 wsa->iovec[0].iov_base = sendBuf;
3181 wsa->iovec[0].iov_len = sendBufLen;
3183 SERVER_START_REQ( register_async )
3185 req->type = ASYNC_TYPE_WRITE;
3186 req->async.handle = wine_server_obj_handle( wsa->hSocket );
3187 req->async.callback = wine_server_client_ptr( WS2_async_send );
3188 req->async.iosb = wine_server_client_ptr( iosb );
3189 req->async.arg = wine_server_client_ptr( wsa );
3190 req->async.event = wine_server_obj_handle( ov->hEvent );
3191 req->async.cvalue = cvalue;
3192 status = wine_server_call( req );
3194 SERVER_END_REQ;
3196 if (status != STATUS_PENDING) HeapFree(GetProcessHeap(), 0, wsa);
3198 /* If the connect already failed */
3199 if (status == STATUS_PIPE_DISCONNECTED)
3200 status = _get_sock_error(s, FD_CONNECT_BIT);
3201 SetLastError( NtStatusToWSAError(status) );
3204 else
3206 SetLastError(ret);
3209 release_sock_fd( s, fd );
3210 return FALSE;
3212 connection_success:
3213 release_sock_fd( s, fd );
3214 return TRUE;
3218 /***********************************************************************
3219 * getpeername (WS2_32.5)
3221 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
3223 int fd;
3224 int res;
3226 TRACE("socket %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
3228 fd = get_sock_fd( s, 0, NULL );
3229 res = SOCKET_ERROR;
3231 if (fd != -1)
3233 union generic_unix_sockaddr uaddr;
3234 socklen_t uaddrlen = sizeof(uaddr);
3236 if (getpeername(fd, &uaddr.addr, &uaddrlen) == 0)
3238 if (!name || !namelen)
3239 SetLastError(WSAEFAULT);
3240 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3241 /* The buffer was too small */
3242 SetLastError(WSAEFAULT);
3243 else
3245 res = 0;
3246 TRACE("=> %s\n", debugstr_sockaddr(name));
3249 else
3250 SetLastError(wsaErrno());
3251 release_sock_fd( s, fd );
3253 return res;
3256 /* When binding to an UDP address with filter support the getsockname call on the socket
3257 * will always return 0.0.0.0 instead of the filtered interface address. This function
3258 * checks if the socket is interface-bound on UDP and return the correct address.
3259 * This is required because applications often do a bind() with port zero followed by a
3260 * getsockname() to retrieve the port and address acquired.
3262 static void interface_bind_check(int fd, struct sockaddr_in *addr)
3264 #if !defined(IP_BOUND_IF) && !defined(LINUX_BOUND_IF)
3265 return;
3266 #else
3267 int ifindex;
3268 socklen_t len;
3270 /* Check for IPv4, address 0.0.0.0 and UDP socket */
3271 if (addr->sin_family != AF_INET || addr->sin_addr.s_addr != 0)
3272 return;
3273 if (_get_fd_type(fd) != SOCK_DGRAM)
3274 return;
3276 ifindex = -1;
3277 len = sizeof(ifindex);
3278 #if defined(IP_BOUND_IF)
3279 getsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &ifindex, &len);
3280 #elif defined(LINUX_BOUND_IF)
3281 getsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex, &len);
3282 if (ifindex > 0) ifindex = ntohl(ifindex);
3283 #endif
3284 if (ifindex > 0)
3286 PIP_ADAPTER_INFO adapters, adapter;
3287 DWORD adap_size;
3289 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
3290 return;
3291 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
3292 if (adapters && GetAdaptersInfo(adapters, &adap_size) == NO_ERROR)
3294 /* Search the IPv4 adapter list for the appropriate bound interface */
3295 for (adapter = adapters; adapter != NULL; adapter = adapter->Next)
3297 in_addr_t adapter_addr;
3298 if (adapter->Index != ifindex) continue;
3300 adapter_addr = inet_addr(adapter->IpAddressList.IpAddress.String);
3301 addr->sin_addr.s_addr = adapter_addr;
3302 TRACE("reporting interface address from adapter %d\n", ifindex);
3303 break;
3306 HeapFree(GetProcessHeap(), 0, adapters);
3308 #endif
3311 /***********************************************************************
3312 * getsockname (WS2_32.6)
3314 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
3316 int fd;
3317 int res;
3319 TRACE("socket %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
3321 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
3322 if( (name == NULL) || (namelen == NULL) )
3324 SetLastError( WSAEFAULT );
3325 return SOCKET_ERROR;
3328 fd = get_sock_fd( s, 0, NULL );
3329 res = SOCKET_ERROR;
3331 if (fd != -1)
3333 union generic_unix_sockaddr uaddr;
3334 socklen_t uaddrlen;
3335 int bound = is_fd_bound(fd, &uaddr, &uaddrlen);
3337 if (bound <= 0)
3339 SetLastError(bound == -1 ? wsaErrno() : WSAEINVAL);
3341 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3343 /* The buffer was too small */
3344 SetLastError(WSAEFAULT);
3346 else
3348 interface_bind_check(fd, (struct sockaddr_in*) &uaddr);
3349 if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3351 /* The buffer was too small */
3352 SetLastError(WSAEFAULT);
3354 else
3356 res = 0;
3357 TRACE("=> %s\n", debugstr_sockaddr(name));
3360 release_sock_fd( s, fd );
3362 return res;
3365 /***********************************************************************
3366 * getsockopt (WS2_32.7)
3368 INT WINAPI WS_getsockopt(SOCKET s, INT level,
3369 INT optname, char *optval, INT *optlen)
3371 int fd;
3372 INT ret = 0;
3374 TRACE("(socket %04lx, %s, optval %s, optlen %p (%d))\n", s,
3375 debugstr_sockopt(level, optname), debugstr_optval(optval, 0),
3376 optlen, optlen ? *optlen : 0);
3378 switch(level)
3380 case WS_SOL_SOCKET:
3382 switch(optname)
3384 /* Handle common cases. The special cases are below, sorted
3385 * alphabetically */
3386 case WS_SO_BROADCAST:
3387 case WS_SO_DEBUG:
3388 case WS_SO_KEEPALIVE:
3389 case WS_SO_OOBINLINE:
3390 case WS_SO_RCVBUF:
3391 case WS_SO_REUSEADDR:
3392 case WS_SO_SNDBUF:
3393 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3394 return SOCKET_ERROR;
3395 convert_sockopt(&level, &optname);
3396 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3398 SetLastError(wsaErrno());
3399 ret = SOCKET_ERROR;
3401 release_sock_fd( s, fd );
3402 return ret;
3403 case WS_SO_ACCEPTCONN:
3404 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3405 return SOCKET_ERROR;
3406 if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, optval, (socklen_t *)optlen) != 0 )
3408 SetLastError(wsaErrno());
3409 ret = SOCKET_ERROR;
3411 else
3413 /* BSD returns != 0 while Windows return exact == 1 */
3414 if (*(int *)optval) *(int *)optval = 1;
3416 release_sock_fd( s, fd );
3417 return ret;
3418 case WS_SO_BSP_STATE:
3420 int req_size, addr_size;
3421 WSAPROTOCOL_INFOW infow;
3422 CSADDR_INFO *csinfo;
3424 ret = ws_protocol_info(s, TRUE, &infow, &addr_size);
3425 if (ret)
3427 if (infow.iAddressFamily == WS_AF_INET)
3428 addr_size = sizeof(struct sockaddr_in);
3429 else if (infow.iAddressFamily == WS_AF_INET6)
3430 addr_size = sizeof(struct sockaddr_in6);
3431 else
3433 FIXME("Family %d is unsupported for SO_BSP_STATE\n", infow.iAddressFamily);
3434 SetLastError(WSAEAFNOSUPPORT);
3435 return SOCKET_ERROR;
3438 req_size = sizeof(CSADDR_INFO) + addr_size * 2;
3439 if (*optlen < req_size)
3441 ret = 0;
3442 SetLastError(WSAEFAULT);
3444 else
3446 union generic_unix_sockaddr uaddr;
3447 socklen_t uaddrlen;
3449 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3450 return SOCKET_ERROR;
3452 csinfo = (CSADDR_INFO*) optval;
3454 /* Check if the sock is bound */
3455 if (is_fd_bound(fd, &uaddr, &uaddrlen) == 1)
3457 csinfo->LocalAddr.lpSockaddr =
3458 (LPSOCKADDR) (optval + sizeof(CSADDR_INFO));
3459 ws_sockaddr_u2ws(&uaddr.addr, csinfo->LocalAddr.lpSockaddr, &addr_size);
3460 csinfo->LocalAddr.iSockaddrLength = addr_size;
3462 else
3464 csinfo->LocalAddr.lpSockaddr = NULL;
3465 csinfo->LocalAddr.iSockaddrLength = 0;
3468 /* Check if the sock is connected */
3469 if (!getpeername(fd, &uaddr.addr, &uaddrlen) &&
3470 is_sockaddr_bound(&uaddr.addr, uaddrlen))
3472 csinfo->RemoteAddr.lpSockaddr =
3473 (LPSOCKADDR) (optval + sizeof(CSADDR_INFO) + addr_size);
3474 ws_sockaddr_u2ws(&uaddr.addr, csinfo->RemoteAddr.lpSockaddr, &addr_size);
3475 csinfo->RemoteAddr.iSockaddrLength = addr_size;
3477 else
3479 csinfo->RemoteAddr.lpSockaddr = NULL;
3480 csinfo->RemoteAddr.iSockaddrLength = 0;
3483 csinfo->iSocketType = infow.iSocketType;
3484 csinfo->iProtocol = infow.iProtocol;
3485 release_sock_fd( s, fd );
3488 return ret ? 0 : SOCKET_ERROR;
3490 case WS_SO_DONTLINGER:
3492 struct linger lingval;
3493 socklen_t len = sizeof(struct linger);
3495 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
3497 SetLastError(WSAEFAULT);
3498 return SOCKET_ERROR;
3500 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3501 return SOCKET_ERROR;
3503 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
3505 SetLastError(wsaErrno());
3506 ret = SOCKET_ERROR;
3508 else
3510 *(BOOL *)optval = !lingval.l_onoff;
3511 *optlen = sizeof(BOOL);
3514 release_sock_fd( s, fd );
3515 return ret;
3518 case WS_SO_CONNECT_TIME:
3520 static int pretendtime = 0;
3521 struct WS_sockaddr addr;
3522 int len = sizeof(addr);
3524 if (!optlen || *optlen < sizeof(DWORD) || !optval)
3526 SetLastError(WSAEFAULT);
3527 return SOCKET_ERROR;
3529 if (WS_getpeername(s, &addr, &len) == SOCKET_ERROR)
3530 *(DWORD *)optval = ~0u;
3531 else
3533 if (!pretendtime) FIXME("WS_SO_CONNECT_TIME - faking results\n");
3534 *(DWORD *)optval = pretendtime++;
3536 *optlen = sizeof(DWORD);
3537 return ret;
3539 /* As mentioned in setsockopt, Windows ignores this, so we
3540 * always return true here */
3541 case WS_SO_DONTROUTE:
3542 if (!optlen || *optlen < sizeof(BOOL) || !optval)
3544 SetLastError(WSAEFAULT);
3545 return SOCKET_ERROR;
3547 *(BOOL *)optval = TRUE;
3548 *optlen = sizeof(BOOL);
3549 return 0;
3551 case WS_SO_ERROR:
3553 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3554 return SOCKET_ERROR;
3555 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, optval, (socklen_t *)optlen) != 0 )
3557 SetLastError(wsaErrno());
3558 ret = SOCKET_ERROR;
3560 release_sock_fd( s, fd );
3562 /* The wineserver may have swallowed the error before us */
3563 if (!ret && *(int*) optval == 0)
3565 int i, events[FD_MAX_EVENTS];
3566 _get_sock_errors(s, events);
3567 for (i = 0; i < FD_MAX_EVENTS; i++)
3569 if(events[i])
3571 events[i] = NtStatusToWSAError(events[i]);
3572 TRACE("returning SO_ERROR %d from wine server\n", events[i]);
3573 *(int*) optval = events[i];
3574 break;
3578 return ret;
3581 case WS_SO_LINGER:
3583 struct linger lingval;
3584 socklen_t len = sizeof(struct linger);
3586 /* struct linger and LINGER have different sizes */
3587 if (!optlen || *optlen < sizeof(LINGER) || !optval)
3589 SetLastError(WSAEFAULT);
3590 return SOCKET_ERROR;
3592 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3593 return SOCKET_ERROR;
3595 if (_get_fd_type(fd) == SOCK_DGRAM)
3597 SetLastError(WSAENOPROTOOPT);
3598 ret = SOCKET_ERROR;
3600 else if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0)
3602 SetLastError(wsaErrno());
3603 ret = SOCKET_ERROR;
3605 else
3607 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
3608 ((LINGER *)optval)->l_linger = lingval.l_linger;
3609 *optlen = sizeof(struct linger);
3612 release_sock_fd( s, fd );
3613 return ret;
3616 case WS_SO_MAX_MSG_SIZE:
3617 if (!optlen || *optlen < sizeof(int) || !optval)
3619 SetLastError(WSAEFAULT);
3620 return SOCKET_ERROR;
3622 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
3623 *(int *)optval = 65507;
3624 *optlen = sizeof(int);
3625 return 0;
3627 /* SO_OPENTYPE does not require a valid socket handle. */
3628 case WS_SO_OPENTYPE:
3629 if (!optlen || *optlen < sizeof(int) || !optval)
3631 SetLastError(WSAEFAULT);
3632 return SOCKET_ERROR;
3634 *(int *)optval = get_per_thread_data()->opentype;
3635 *optlen = sizeof(int);
3636 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
3637 return 0;
3638 case WS_SO_PROTOCOL_INFOA:
3639 case WS_SO_PROTOCOL_INFOW:
3641 int size;
3642 WSAPROTOCOL_INFOW infow;
3644 ret = ws_protocol_info(s, optname == WS_SO_PROTOCOL_INFOW, &infow, &size);
3645 if (ret)
3647 if (!optlen || !optval || *optlen < size)
3649 if(optlen) *optlen = size;
3650 ret = 0;
3651 SetLastError(WSAEFAULT);
3653 else
3654 memcpy(optval, &infow, size);
3656 return ret ? 0 : SOCKET_ERROR;
3658 case WS_SO_RCVTIMEO:
3659 case WS_SO_SNDTIMEO:
3661 INT64 timeout;
3663 if (!optlen || *optlen < sizeof(int)|| !optval)
3665 SetLastError(WSAEFAULT);
3666 return SOCKET_ERROR;
3668 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3669 return SOCKET_ERROR;
3671 timeout = get_rcvsnd_timeo(fd, optname == WS_SO_RCVTIMEO);
3672 *(int *)optval = timeout <= UINT_MAX ? timeout : UINT_MAX;
3674 release_sock_fd( s, fd );
3675 return ret;
3677 case WS_SO_TYPE:
3679 int sock_type;
3680 if (!optlen || *optlen < sizeof(int) || !optval)
3682 SetLastError(WSAEFAULT);
3683 return SOCKET_ERROR;
3685 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3686 return SOCKET_ERROR;
3688 sock_type = _get_fd_type(fd);
3689 if (sock_type == -1)
3691 SetLastError(wsaErrno());
3692 ret = SOCKET_ERROR;
3694 else
3695 (*(int *)optval) = convert_socktype_u2w(sock_type);
3697 release_sock_fd( s, fd );
3698 return ret;
3700 default:
3701 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
3702 SetLastError(WSAENOPROTOOPT);
3703 return SOCKET_ERROR;
3704 } /* end switch(optname) */
3705 }/* end case WS_SOL_SOCKET */
3706 #ifdef HAS_IPX
3707 case WS_NSPROTO_IPX:
3709 struct WS_sockaddr_ipx addr;
3710 IPX_ADDRESS_DATA *data;
3711 int namelen;
3712 switch(optname)
3714 case WS_IPX_PTYPE:
3715 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3716 #ifdef SOL_IPX
3717 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (socklen_t *)optlen) == -1)
3719 ret = SOCKET_ERROR;
3721 #else
3723 struct ipx val;
3724 socklen_t len=sizeof(struct ipx);
3725 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
3726 ret = SOCKET_ERROR;
3727 else
3728 *optval = (int)val.ipx_pt;
3730 #endif
3731 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
3732 release_sock_fd( s, fd );
3733 return ret;
3735 case WS_IPX_ADDRESS:
3737 * On a Win2000 system with one network card there are usually
3738 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
3739 * Using this call you can then retrieve info about this all.
3740 * In case of Linux it is a bit different. Usually you have
3741 * only "one" device active and further it is not possible to
3742 * query things like the linkspeed.
3744 FIXME("IPX_ADDRESS\n");
3745 namelen = sizeof(struct WS_sockaddr_ipx);
3746 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
3747 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
3749 data = (IPX_ADDRESS_DATA*)optval;
3750 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
3751 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
3752 data->adapternum = 0;
3753 data->wan = FALSE; /* We are not on a wan for now .. */
3754 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
3755 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
3756 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
3757 * note 1MB = 1000kB in this case */
3758 return 0;
3760 case WS_IPX_MAX_ADAPTER_NUM:
3761 FIXME("IPX_MAX_ADAPTER_NUM\n");
3762 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
3763 return 0;
3765 default:
3766 FIXME("IPX optname:%x\n", optname);
3767 return SOCKET_ERROR;
3768 }/* end switch(optname) */
3769 } /* end case WS_NSPROTO_IPX */
3770 #endif
3772 #ifdef HAS_IRDA
3773 #define MAX_IRDA_DEVICES 10
3775 case WS_SOL_IRLMP:
3776 switch(optname)
3778 case WS_IRLMP_ENUMDEVICES:
3780 char buf[sizeof(struct irda_device_list) +
3781 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
3782 int res;
3783 socklen_t len = sizeof(buf);
3785 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3786 return SOCKET_ERROR;
3787 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
3788 release_sock_fd( s, fd );
3789 if (res < 0)
3791 SetLastError(wsaErrno());
3792 return SOCKET_ERROR;
3794 else
3796 struct irda_device_list *src = (struct irda_device_list *)buf;
3797 DEVICELIST *dst = (DEVICELIST *)optval;
3798 INT needed = sizeof(DEVICELIST);
3799 unsigned int i;
3801 if (src->len > 0)
3802 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
3803 if (*optlen < needed)
3805 SetLastError(WSAEFAULT);
3806 return SOCKET_ERROR;
3808 *optlen = needed;
3809 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
3810 dst->numDevice = src->len;
3811 for (i = 0; i < src->len; i++)
3813 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
3814 src->dev[i].saddr, src->dev[i].daddr,
3815 src->dev[i].info, src->dev[i].hints[0],
3816 src->dev[i].hints[1]);
3817 memcpy( dst->Device[i].irdaDeviceID,
3818 &src->dev[i].daddr,
3819 sizeof(dst->Device[i].irdaDeviceID) ) ;
3820 memcpy( dst->Device[i].irdaDeviceName,
3821 src->dev[i].info,
3822 sizeof(dst->Device[i].irdaDeviceName) ) ;
3823 memcpy( &dst->Device[i].irdaDeviceHints1,
3824 &src->dev[i].hints[0],
3825 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
3826 memcpy( &dst->Device[i].irdaDeviceHints2,
3827 &src->dev[i].hints[1],
3828 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
3829 dst->Device[i].irdaCharSet = src->dev[i].charset;
3831 return 0;
3834 default:
3835 FIXME("IrDA optname:0x%x\n", optname);
3836 return SOCKET_ERROR;
3838 break; /* case WS_SOL_IRLMP */
3839 #undef MAX_IRDA_DEVICES
3840 #endif
3842 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3843 case WS_IPPROTO_TCP:
3844 switch(optname)
3846 case WS_TCP_NODELAY:
3847 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3848 return SOCKET_ERROR;
3849 convert_sockopt(&level, &optname);
3850 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3852 SetLastError(wsaErrno());
3853 ret = SOCKET_ERROR;
3855 release_sock_fd( s, fd );
3856 return ret;
3858 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
3859 return SOCKET_ERROR;
3861 case WS_IPPROTO_IP:
3862 switch(optname)
3864 case WS_IP_ADD_MEMBERSHIP:
3865 case WS_IP_DROP_MEMBERSHIP:
3866 #ifdef IP_HDRINCL
3867 case WS_IP_HDRINCL:
3868 #endif
3869 case WS_IP_MULTICAST_IF:
3870 case WS_IP_MULTICAST_LOOP:
3871 case WS_IP_MULTICAST_TTL:
3872 case WS_IP_OPTIONS:
3873 #ifdef IP_PKTINFO
3874 case WS_IP_PKTINFO:
3875 #endif
3876 case WS_IP_TOS:
3877 case WS_IP_TTL:
3878 #ifdef IP_UNICAST_IF
3879 case WS_IP_UNICAST_IF:
3880 #endif
3881 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3882 return SOCKET_ERROR;
3883 convert_sockopt(&level, &optname);
3884 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3886 SetLastError(wsaErrno());
3887 ret = SOCKET_ERROR;
3889 release_sock_fd( s, fd );
3890 return ret;
3891 case WS_IP_DONTFRAGMENT:
3892 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
3893 *(BOOL*)optval = FALSE;
3894 return 0;
3896 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
3897 return SOCKET_ERROR;
3899 case WS_IPPROTO_IPV6:
3900 switch(optname)
3902 #ifdef IPV6_ADD_MEMBERSHIP
3903 case WS_IPV6_ADD_MEMBERSHIP:
3904 #endif
3905 #ifdef IPV6_DROP_MEMBERSHIP
3906 case WS_IPV6_DROP_MEMBERSHIP:
3907 #endif
3908 case WS_IPV6_MULTICAST_IF:
3909 case WS_IPV6_MULTICAST_HOPS:
3910 case WS_IPV6_MULTICAST_LOOP:
3911 case WS_IPV6_UNICAST_HOPS:
3912 case WS_IPV6_V6ONLY:
3913 #ifdef IPV6_UNICAST_IF
3914 case WS_IPV6_UNICAST_IF:
3915 #endif
3916 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3917 return SOCKET_ERROR;
3918 convert_sockopt(&level, &optname);
3919 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3921 SetLastError(wsaErrno());
3922 ret = SOCKET_ERROR;
3924 release_sock_fd( s, fd );
3925 return ret;
3926 case WS_IPV6_DONTFRAG:
3927 FIXME("WS_IPV6_DONTFRAG is always false!\n");
3928 *(BOOL*)optval = FALSE;
3929 return 0;
3931 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
3932 return SOCKET_ERROR;
3934 default:
3935 WARN("Unknown level: 0x%08x\n", level);
3936 SetLastError(WSAEINVAL);
3937 return SOCKET_ERROR;
3938 } /* end switch(level) */
3941 /***********************************************************************
3942 * htonl (WS2_32.8)
3944 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
3946 return htonl(hostlong);
3950 /***********************************************************************
3951 * htons (WS2_32.9)
3953 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
3955 return htons(hostshort);
3958 /***********************************************************************
3959 * WSAHtonl (WS2_32.46)
3960 * From MSDN description of error codes, this function should also
3961 * check if WinSock has been initialized and the socket is a valid
3962 * socket. But why? This function only translates a host byte order
3963 * u_long into a network byte order u_long...
3965 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
3967 if (lpnetlong)
3969 *lpnetlong = htonl(hostlong);
3970 return 0;
3972 SetLastError(WSAEFAULT);
3973 return SOCKET_ERROR;
3976 /***********************************************************************
3977 * WSAHtons (WS2_32.47)
3978 * From MSDN description of error codes, this function should also
3979 * check if WinSock has been initialized and the socket is a valid
3980 * socket. But why? This function only translates a host byte order
3981 * u_short into a network byte order u_short...
3983 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
3986 if (lpnetshort)
3988 *lpnetshort = htons(hostshort);
3989 return 0;
3991 SetLastError(WSAEFAULT);
3992 return SOCKET_ERROR;
3996 /***********************************************************************
3997 * inet_addr (WS2_32.11)
3999 WS_u_long WINAPI WS_inet_addr(const char *cp)
4001 if (!cp) return INADDR_NONE;
4002 return inet_addr(cp);
4006 /***********************************************************************
4007 * ntohl (WS2_32.14)
4009 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
4011 return ntohl(netlong);
4015 /***********************************************************************
4016 * ntohs (WS2_32.15)
4018 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
4020 return ntohs(netshort);
4024 /***********************************************************************
4025 * inet_ntoa (WS2_32.12)
4027 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
4029 struct per_thread_data *data = get_per_thread_data();
4031 sprintf( data->ntoa_buffer, "%u.%u.%u.%u",
4032 (unsigned int)(ntohl( in.WS_s_addr ) >> 24 & 0xff),
4033 (unsigned int)(ntohl( in.WS_s_addr ) >> 16 & 0xff),
4034 (unsigned int)(ntohl( in.WS_s_addr ) >> 8 & 0xff),
4035 (unsigned int)(ntohl( in.WS_s_addr ) & 0xff) );
4037 return data->ntoa_buffer;
4040 static const char *debugstr_wsaioctl(DWORD ioctl)
4042 const char *buf_type, *family;
4044 switch(ioctl & 0x18000000)
4046 case WS_IOC_WS2:
4047 family = "IOC_WS2";
4048 break;
4049 case WS_IOC_PROTOCOL:
4050 family = "IOC_PROTOCOL";
4051 break;
4052 case WS_IOC_VENDOR:
4053 family = "IOC_VENDOR";
4054 break;
4055 default: /* WS_IOC_UNIX */
4057 BYTE size = (ioctl >> 16) & WS_IOCPARM_MASK;
4058 char x = (ioctl & 0xff00) >> 8;
4059 BYTE y = ioctl & 0xff;
4060 char args[14];
4062 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
4064 case WS_IOC_VOID:
4065 buf_type = "_IO";
4066 sprintf(args, "%d, %d", x, y);
4067 break;
4068 case WS_IOC_IN:
4069 buf_type = "_IOW";
4070 sprintf(args, "'%c', %d, %d", x, y, size);
4071 break;
4072 case WS_IOC_OUT:
4073 buf_type = "_IOR";
4074 sprintf(args, "'%c', %d, %d", x, y, size);
4075 break;
4076 default:
4077 buf_type = "?";
4078 sprintf(args, "'%c', %d, %d", x, y, size);
4079 break;
4081 return wine_dbg_sprintf("%s(%s)", buf_type, args);
4085 /* We are different from WS_IOC_UNIX. */
4086 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
4088 case WS_IOC_VOID:
4089 buf_type = "_WSAIO";
4090 break;
4091 case WS_IOC_INOUT:
4092 buf_type = "_WSAIORW";
4093 break;
4094 case WS_IOC_IN:
4095 buf_type = "_WSAIOW";
4096 break;
4097 case WS_IOC_OUT:
4098 buf_type = "_WSAIOR";
4099 break;
4100 default:
4101 buf_type = "?";
4102 break;
4105 return wine_dbg_sprintf("%s(%s, %d)", buf_type, family,
4106 (USHORT)(ioctl & 0xffff));
4109 /* do an ioctl call through the server */
4110 static DWORD server_ioctl_sock( SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size,
4111 LPVOID out_buff, DWORD out_size, LPDWORD ret_size,
4112 LPWSAOVERLAPPED overlapped,
4113 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
4115 HANDLE event = overlapped ? overlapped->hEvent : 0;
4116 HANDLE handle = SOCKET2HANDLE( s );
4117 struct ws2_async *wsa;
4118 NTSTATUS status;
4119 PIO_STATUS_BLOCK io;
4121 if (!(wsa = (struct ws2_async *)alloc_async_io( sizeof(*wsa) )))
4122 return WSA_NOT_ENOUGH_MEMORY;
4123 wsa->hSocket = handle;
4124 wsa->user_overlapped = overlapped;
4125 wsa->completion_func = completion;
4126 io = (overlapped ? (PIO_STATUS_BLOCK)overlapped : &wsa->local_iosb);
4128 status = NtDeviceIoControlFile( handle, event, ws2_async_apc, wsa, io, code,
4129 in_buff, in_size, out_buff, out_size );
4130 if (status == STATUS_NOT_SUPPORTED)
4132 FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
4133 code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
4135 else if (status == STATUS_SUCCESS)
4136 *ret_size = io->Information; /* "Information" is the size written to the output buffer */
4138 if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, wsa );
4140 return NtStatusToWSAError( status );
4143 /**********************************************************************
4144 * WSAIoctl (WS2_32.50)
4147 INT WINAPI WSAIoctl(SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size, LPVOID out_buff,
4148 DWORD out_size, LPDWORD ret_size, LPWSAOVERLAPPED overlapped,
4149 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
4151 int fd;
4152 DWORD status = 0, total = 0;
4154 TRACE("%04lx, %s, %p, %d, %p, %d, %p, %p, %p\n",
4155 s, debugstr_wsaioctl(code), in_buff, in_size, out_buff, out_size, ret_size, overlapped, completion);
4157 switch (code)
4159 case WS_FIONBIO:
4160 if (in_size != sizeof(WS_u_long) || IS_INTRESOURCE(in_buff))
4162 SetLastError(WSAEFAULT);
4163 return SOCKET_ERROR;
4165 TRACE("-> FIONBIO (%x)\n", *(WS_u_long*)in_buff);
4166 if (_get_sock_mask(s))
4168 /* AsyncSelect()'ed sockets are always nonblocking */
4169 if (!*(WS_u_long *)in_buff) status = WSAEINVAL;
4170 break;
4172 if (*(WS_u_long *)in_buff)
4173 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
4174 else
4175 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
4176 break;
4178 case WS_FIONREAD:
4180 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
4182 SetLastError(WSAEFAULT);
4183 return SOCKET_ERROR;
4185 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
4186 if (ioctl(fd, FIONREAD, out_buff ) == -1)
4187 status = wsaErrno();
4188 release_sock_fd( s, fd );
4189 break;
4192 case WS_SIOCATMARK:
4194 unsigned int oob = 0, atmark = 0;
4195 socklen_t oobsize = sizeof(int);
4196 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
4198 SetLastError(WSAEFAULT);
4199 return SOCKET_ERROR;
4201 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
4202 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
4203 if ((getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &oob, &oobsize ) == -1)
4204 || (!oob && ioctl(fd, SIOCATMARK, &atmark ) == -1))
4205 status = wsaErrno();
4206 else
4208 /* The SIOCATMARK value read from ioctl() is reversed
4209 * because BSD returns TRUE if it's in the OOB mark
4210 * while Windows returns TRUE if there are NO OOB bytes.
4212 (*(WS_u_long *) out_buff) = oob || !atmark;
4215 release_sock_fd( s, fd );
4216 break;
4219 case WS_FIOASYNC:
4220 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
4221 SetLastError(WSAEINVAL);
4222 return SOCKET_ERROR;
4224 case WS_SIO_GET_INTERFACE_LIST:
4226 INTERFACE_INFO* intArray = out_buff;
4227 DWORD size, numInt = 0, apiReturn;
4229 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
4231 if (!out_buff || !ret_size)
4233 SetLastError(WSAEFAULT);
4234 return SOCKET_ERROR;
4237 fd = get_sock_fd( s, 0, NULL );
4238 if (fd == -1) return SOCKET_ERROR;
4240 apiReturn = GetAdaptersInfo(NULL, &size);
4241 if (apiReturn == ERROR_BUFFER_OVERFLOW)
4243 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
4245 if (table)
4247 if (GetAdaptersInfo(table, &size) == NO_ERROR)
4249 PIP_ADAPTER_INFO ptr;
4251 for (ptr = table, numInt = 0; ptr; ptr = ptr->Next)
4253 unsigned int addr, mask, bcast;
4254 struct ifreq ifInfo;
4256 /* Skip interfaces without an IPv4 address. */
4257 if (ptr->IpAddressList.IpAddress.String[0] == '\0')
4258 continue;
4260 if ((numInt + 1)*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > out_size)
4262 WARN("Buffer too small = %u, out_size = %u\n", numInt + 1, out_size);
4263 status = WSAEFAULT;
4264 break;
4267 /* Socket Status Flags */
4268 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
4269 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
4271 ERR("Error obtaining status flags for socket!\n");
4272 status = WSAEINVAL;
4273 break;
4275 else
4277 /* set flags; the values of IFF_* are not the same
4278 under Linux and Windows, therefore must generate
4279 new flags */
4280 intArray->iiFlags = 0;
4281 if (ifInfo.ifr_flags & IFF_BROADCAST)
4282 intArray->iiFlags |= WS_IFF_BROADCAST;
4283 #ifdef IFF_POINTOPOINT
4284 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
4285 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
4286 #endif
4287 if (ifInfo.ifr_flags & IFF_LOOPBACK)
4288 intArray->iiFlags |= WS_IFF_LOOPBACK;
4289 if (ifInfo.ifr_flags & IFF_UP)
4290 intArray->iiFlags |= WS_IFF_UP;
4291 if (ifInfo.ifr_flags & IFF_MULTICAST)
4292 intArray->iiFlags |= WS_IFF_MULTICAST;
4295 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
4296 mask = inet_addr(ptr->IpAddressList.IpMask.String);
4297 bcast = addr | ~mask;
4298 intArray->iiAddress.AddressIn.sin_family = AF_INET;
4299 intArray->iiAddress.AddressIn.sin_port = 0;
4300 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
4301 addr;
4302 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
4303 intArray->iiNetmask.AddressIn.sin_port = 0;
4304 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
4305 mask;
4306 intArray->iiBroadcastAddress.AddressIn.sin_family =
4307 AF_INET;
4308 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
4309 intArray->iiBroadcastAddress.AddressIn.sin_addr.
4310 WS_s_addr = bcast;
4311 intArray++;
4312 numInt++;
4315 else
4317 ERR("Unable to get interface table!\n");
4318 status = WSAEINVAL;
4320 HeapFree(GetProcessHeap(),0,table);
4322 else status = WSAEINVAL;
4324 else if (apiReturn != ERROR_NO_DATA)
4326 ERR("Unable to get interface table!\n");
4327 status = WSAEINVAL;
4329 /* Calculate the size of the array being returned */
4330 total = sizeof(INTERFACE_INFO) * numInt;
4331 release_sock_fd( s, fd );
4332 break;
4335 case WS_SIO_ADDRESS_LIST_QUERY:
4337 DWORD size;
4339 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
4341 if (!ret_size)
4343 SetLastError(WSAEFAULT);
4344 return SOCKET_ERROR;
4347 if (out_size && out_size < FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[0]))
4349 *ret_size = 0;
4350 SetLastError(WSAEINVAL);
4351 return SOCKET_ERROR;
4354 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
4356 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
4357 SOCKET_ADDRESS_LIST *sa_list;
4358 SOCKADDR_IN *sockaddr;
4359 SOCKET_ADDRESS *sa;
4360 unsigned int i;
4361 DWORD num;
4363 if (!table || GetAdaptersInfo(table, &size))
4365 HeapFree(GetProcessHeap(), 0, table);
4366 status = WSAEINVAL;
4367 break;
4370 for (p = table, num = 0; p; p = p->Next)
4371 if (p->IpAddressList.IpAddress.String[0]) num++;
4373 total = FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[num]) + num * sizeof(*sockaddr);
4374 if (total > out_size || !out_buff)
4376 *ret_size = total;
4377 HeapFree(GetProcessHeap(), 0, table);
4378 status = WSAEFAULT;
4379 break;
4382 sa_list = out_buff;
4383 sa = sa_list->Address;
4384 sockaddr = (SOCKADDR_IN *)&sa[num];
4385 sa_list->iAddressCount = num;
4387 for (p = table, i = 0; p; p = p->Next)
4389 if (!p->IpAddressList.IpAddress.String[0]) continue;
4391 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
4392 sa[i].iSockaddrLength = sizeof(SOCKADDR);
4394 sockaddr[i].sin_family = AF_INET;
4395 sockaddr[i].sin_port = 0;
4396 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
4397 i++;
4400 HeapFree(GetProcessHeap(), 0, table);
4402 else
4404 WARN("unable to get IP address list\n");
4405 status = WSAEINVAL;
4407 break;
4410 case WS_SIO_FLUSH:
4411 FIXME("SIO_FLUSH: stub.\n");
4412 break;
4414 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
4416 static const GUID connectex_guid = WSAID_CONNECTEX;
4417 static const GUID disconnectex_guid = WSAID_DISCONNECTEX;
4418 static const GUID acceptex_guid = WSAID_ACCEPTEX;
4419 static const GUID getaccepexsockaddrs_guid = WSAID_GETACCEPTEXSOCKADDRS;
4420 static const GUID transmitfile_guid = WSAID_TRANSMITFILE;
4421 static const GUID transmitpackets_guid = WSAID_TRANSMITPACKETS;
4422 static const GUID wsarecvmsg_guid = WSAID_WSARECVMSG;
4423 static const GUID wsasendmsg_guid = WSAID_WSASENDMSG;
4425 if ( IsEqualGUID(&connectex_guid, in_buff) )
4427 *(LPFN_CONNECTEX *)out_buff = WS2_ConnectEx;
4428 break;
4430 else if ( IsEqualGUID(&disconnectex_guid, in_buff) )
4432 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented DisconnectEx\n");
4434 else if ( IsEqualGUID(&acceptex_guid, in_buff) )
4436 *(LPFN_ACCEPTEX *)out_buff = WS2_AcceptEx;
4437 break;
4439 else if ( IsEqualGUID(&getaccepexsockaddrs_guid, in_buff) )
4441 *(LPFN_GETACCEPTEXSOCKADDRS *)out_buff = WS2_GetAcceptExSockaddrs;
4442 break;
4444 else if ( IsEqualGUID(&transmitfile_guid, in_buff) )
4446 *(LPFN_TRANSMITFILE *)out_buff = WS2_TransmitFile;
4447 break;
4449 else if ( IsEqualGUID(&transmitpackets_guid, in_buff) )
4451 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitPackets\n");
4453 else if ( IsEqualGUID(&wsarecvmsg_guid, in_buff) )
4455 *(LPFN_WSARECVMSG *)out_buff = WS2_WSARecvMsg;
4456 break;
4458 else if ( IsEqualGUID(&wsasendmsg_guid, in_buff) )
4460 *(LPFN_WSASENDMSG *)out_buff = WSASendMsg;
4461 break;
4463 else
4464 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff));
4466 status = WSAEOPNOTSUPP;
4467 break;
4469 case WS_SIO_KEEPALIVE_VALS:
4471 struct tcp_keepalive *k;
4472 int keepalive, keepidle, keepintvl;
4474 if (!in_buff || in_size < sizeof(struct tcp_keepalive))
4476 SetLastError(WSAEFAULT);
4477 return SOCKET_ERROR;
4480 k = in_buff;
4481 keepalive = k->onoff ? 1 : 0;
4482 keepidle = max( 1, (k->keepalivetime + 500) / 1000 );
4483 keepintvl = max( 1, (k->keepaliveinterval + 500) / 1000 );
4485 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
4487 fd = get_sock_fd(s, 0, NULL);
4488 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
4489 status = WSAEINVAL;
4490 #if defined(TCP_KEEPIDLE) || defined(TCP_KEEPINTVL)
4491 /* these values need to be set only if SO_KEEPALIVE is enabled */
4492 else if(keepalive)
4494 #ifndef TCP_KEEPIDLE
4495 FIXME("ignoring keepalive timeout\n");
4496 #else
4497 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
4498 status = WSAEINVAL;
4499 else
4500 #endif
4501 #ifdef TCP_KEEPINTVL
4502 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
4503 status = WSAEINVAL;
4504 #else
4505 FIXME("ignoring keepalive interval\n");
4506 #endif
4508 #else
4509 else
4510 FIXME("ignoring keepalive interval and timeout\n");
4511 #endif
4512 release_sock_fd(s, fd);
4513 break;
4515 case WS_SIO_ROUTING_INTERFACE_QUERY:
4517 struct WS_sockaddr *daddr = (struct WS_sockaddr *)in_buff;
4518 struct WS_sockaddr_in *daddr_in = (struct WS_sockaddr_in *)daddr;
4519 struct WS_sockaddr_in *saddr_in = out_buff;
4520 MIB_IPFORWARDROW row;
4521 PMIB_IPADDRTABLE ipAddrTable = NULL;
4522 DWORD size, i, found_index;
4524 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
4526 if (!in_buff || in_size < sizeof(struct WS_sockaddr) ||
4527 !out_buff || out_size < sizeof(struct WS_sockaddr_in) || !ret_size)
4529 SetLastError(WSAEFAULT);
4530 return SOCKET_ERROR;
4532 if (daddr->sa_family != AF_INET)
4534 FIXME("unsupported address family %d\n", daddr->sa_family);
4535 status = WSAEAFNOSUPPORT;
4536 break;
4538 if (GetBestRoute(daddr_in->sin_addr.S_un.S_addr, 0, &row) != NOERROR ||
4539 GetIpAddrTable(NULL, &size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
4541 status = WSAEFAULT;
4542 break;
4544 ipAddrTable = HeapAlloc(GetProcessHeap(), 0, size);
4545 if (GetIpAddrTable(ipAddrTable, &size, FALSE))
4547 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4548 status = WSAEFAULT;
4549 break;
4551 for (i = 0, found_index = ipAddrTable->dwNumEntries;
4552 i < ipAddrTable->dwNumEntries; i++)
4554 if (ipAddrTable->table[i].dwIndex == row.dwForwardIfIndex)
4555 found_index = i;
4557 if (found_index == ipAddrTable->dwNumEntries)
4559 ERR("no matching IP address for interface %d\n",
4560 row.dwForwardIfIndex);
4561 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4562 status = WSAEFAULT;
4563 break;
4565 saddr_in->sin_family = AF_INET;
4566 saddr_in->sin_addr.S_un.S_addr = ipAddrTable->table[found_index].dwAddr;
4567 saddr_in->sin_port = 0;
4568 total = sizeof(struct WS_sockaddr_in);
4569 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4570 break;
4572 case WS_SIO_SET_COMPATIBILITY_MODE:
4573 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
4574 status = WSAEOPNOTSUPP;
4575 break;
4576 case WS_SIO_UDP_CONNRESET:
4577 FIXME("WS_SIO_UDP_CONNRESET stub\n");
4578 break;
4579 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
4580 SetLastError(WSAEOPNOTSUPP);
4581 return SOCKET_ERROR;
4582 default:
4583 status = WSAEOPNOTSUPP;
4584 break;
4587 if (status == WSAEOPNOTSUPP)
4589 status = server_ioctl_sock(s, code, in_buff, in_size, out_buff, out_size, &total,
4590 overlapped, completion);
4591 if (status != WSAEOPNOTSUPP)
4593 if (status == 0 || status == WSA_IO_PENDING)
4594 TRACE("-> %s request\n", debugstr_wsaioctl(code));
4595 else
4596 ERR("-> %s request failed with status 0x%x\n", debugstr_wsaioctl(code), status);
4598 /* overlapped and completion operations will be handled by the server */
4599 completion = NULL;
4600 overlapped = NULL;
4602 else
4603 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code));
4606 if (completion)
4608 FIXME( "completion routine %p not supported\n", completion );
4610 else if (overlapped)
4612 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
4613 overlapped->Internal = status;
4614 overlapped->InternalHigh = total;
4615 if (overlapped->hEvent) NtSetEvent( overlapped->hEvent, NULL );
4616 if (cvalue) WS_AddCompletion( HANDLE2SOCKET(s), cvalue, status, total );
4619 if (!status)
4621 if (ret_size) *ret_size = total;
4622 return 0;
4624 SetLastError( status );
4625 return SOCKET_ERROR;
4629 /***********************************************************************
4630 * ioctlsocket (WS2_32.10)
4632 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
4634 DWORD ret_size;
4635 return WSAIoctl( s, cmd, argp, sizeof(WS_u_long), argp, sizeof(WS_u_long), &ret_size, NULL, NULL );
4638 /***********************************************************************
4639 * listen (WS2_32.13)
4641 int WINAPI WS_listen(SOCKET s, int backlog)
4643 int fd = get_sock_fd( s, FILE_READ_DATA, NULL ), ret = SOCKET_ERROR;
4645 TRACE("socket %04lx, backlog %d\n", s, backlog);
4646 if (fd != -1)
4648 int bound = is_fd_bound(fd, NULL, NULL);
4650 if (bound <= 0)
4652 SetLastError(bound == -1 ? wsaErrno() : WSAEINVAL);
4654 else if (listen(fd, backlog) == 0)
4656 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
4657 FD_WINE_LISTENING,
4658 FD_CONNECT|FD_WINE_CONNECTED);
4659 ret = 0;
4661 else
4662 SetLastError(wsaErrno());
4663 release_sock_fd( s, fd );
4665 else
4666 SetLastError(WSAENOTSOCK);
4667 return ret;
4670 /***********************************************************************
4671 * recv (WS2_32.16)
4673 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
4675 DWORD n, dwFlags = flags;
4676 WSABUF wsabuf;
4678 wsabuf.len = len;
4679 wsabuf.buf = buf;
4681 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
4682 return SOCKET_ERROR;
4683 else
4684 return n;
4687 /***********************************************************************
4688 * recvfrom (WS2_32.17)
4690 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
4691 struct WS_sockaddr *from, int *fromlen)
4693 DWORD n, dwFlags = flags;
4694 WSABUF wsabuf;
4696 wsabuf.len = len;
4697 wsabuf.buf = buf;
4699 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL, NULL) == SOCKET_ERROR )
4700 return SOCKET_ERROR;
4701 else
4702 return n;
4705 /* allocate a poll array for the corresponding fd sets */
4706 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
4707 const WS_fd_set *exceptfds, int *count_ptr )
4709 unsigned int i, j = 0, count = 0;
4710 struct pollfd *fds;
4712 if (readfds) count += readfds->fd_count;
4713 if (writefds) count += writefds->fd_count;
4714 if (exceptfds) count += exceptfds->fd_count;
4715 *count_ptr = count;
4716 if (!count)
4718 SetLastError(WSAEINVAL);
4719 return NULL;
4721 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0]))))
4723 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
4724 return NULL;
4726 if (readfds)
4727 for (i = 0; i < readfds->fd_count; i++, j++)
4729 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
4730 if (fds[j].fd == -1) goto failed;
4731 fds[j].revents = 0;
4732 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1)
4734 fds[j].events = POLLIN;
4736 else
4738 release_sock_fd( readfds->fd_array[i], fds[j].fd );
4739 fds[j].fd = -1;
4740 fds[j].events = 0;
4743 if (writefds)
4744 for (i = 0; i < writefds->fd_count; i++, j++)
4746 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
4747 if (fds[j].fd == -1) goto failed;
4748 fds[j].revents = 0;
4749 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1 ||
4750 _get_fd_type(fds[j].fd) == SOCK_DGRAM)
4752 fds[j].events = POLLOUT;
4754 else
4756 release_sock_fd( writefds->fd_array[i], fds[j].fd );
4757 fds[j].fd = -1;
4758 fds[j].events = 0;
4761 if (exceptfds)
4762 for (i = 0; i < exceptfds->fd_count; i++, j++)
4764 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
4765 if (fds[j].fd == -1) goto failed;
4766 fds[j].revents = 0;
4767 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1)
4769 int oob_inlined = 0;
4770 socklen_t olen = sizeof(oob_inlined);
4772 fds[j].events = POLLHUP;
4774 /* Check if we need to test for urgent data or not */
4775 getsockopt(fds[j].fd, SOL_SOCKET, SO_OOBINLINE, (char*) &oob_inlined, &olen);
4776 if (!oob_inlined)
4777 fds[j].events |= POLLPRI;
4779 else
4781 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
4782 fds[j].fd = -1;
4783 fds[j].events = 0;
4786 return fds;
4788 failed:
4789 count = j;
4790 j = 0;
4791 if (readfds)
4792 for (i = 0; i < readfds->fd_count && j < count; i++, j++)
4793 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
4794 if (writefds)
4795 for (i = 0; i < writefds->fd_count && j < count; i++, j++)
4796 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
4797 if (exceptfds)
4798 for (i = 0; i < exceptfds->fd_count && j < count; i++, j++)
4799 if (fds[j].fd != -1) release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
4800 HeapFree( GetProcessHeap(), 0, fds );
4801 return NULL;
4804 /* release the file descriptor obtained in fd_sets_to_poll */
4805 /* must be called with the original fd_set arrays, before calling get_poll_results */
4806 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
4807 const WS_fd_set *exceptfds, struct pollfd *fds )
4809 unsigned int i, j = 0;
4811 if (readfds)
4813 for (i = 0; i < readfds->fd_count; i++, j++)
4814 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
4816 if (writefds)
4818 for (i = 0; i < writefds->fd_count; i++, j++)
4819 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
4821 if (exceptfds)
4823 for (i = 0; i < exceptfds->fd_count; i++, j++)
4825 if (fds[j].fd == -1) continue;
4826 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
4827 if (fds[j].revents & POLLHUP)
4829 int fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
4830 if (fd != -1)
4831 release_sock_fd( exceptfds->fd_array[i], fd );
4832 else
4833 fds[j].revents = 0;
4839 static int do_poll(struct pollfd *pollfds, int count, int timeout)
4841 struct timeval tv1, tv2;
4842 int ret, torig = timeout;
4844 if (timeout > 0) gettimeofday( &tv1, 0 );
4846 while ((ret = poll( pollfds, count, timeout )) < 0)
4848 if (errno != EINTR) break;
4849 if (timeout < 0) continue;
4850 if (timeout == 0) return 0;
4852 gettimeofday( &tv2, 0 );
4854 tv2.tv_sec -= tv1.tv_sec;
4855 tv2.tv_usec -= tv1.tv_usec;
4856 if (tv2.tv_usec < 0)
4858 tv2.tv_usec += 1000000;
4859 tv2.tv_sec -= 1;
4862 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
4863 if (timeout <= 0) return 0;
4865 return ret;
4868 /* map the poll results back into the Windows fd sets */
4869 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
4870 const struct pollfd *fds )
4872 const struct pollfd *poll_writefds = fds + (readfds ? readfds->fd_count : 0);
4873 const struct pollfd *poll_exceptfds = poll_writefds + (writefds ? writefds->fd_count : 0);
4874 unsigned int i, k, total = 0;
4876 if (readfds)
4878 for (i = k = 0; i < readfds->fd_count; i++)
4880 if (fds[i].revents ||
4881 (readfds == writefds && (poll_writefds[i].revents & POLLOUT) && !(poll_writefds[i].revents & POLLHUP)) ||
4882 (readfds == exceptfds && poll_exceptfds[i].revents))
4883 readfds->fd_array[k++] = readfds->fd_array[i];
4885 readfds->fd_count = k;
4886 total += k;
4888 if (writefds && writefds != readfds)
4890 for (i = k = 0; i < writefds->fd_count; i++)
4892 if (((poll_writefds[i].revents & POLLOUT) && !(poll_writefds[i].revents & POLLHUP)) ||
4893 (writefds == exceptfds && poll_exceptfds[i].revents))
4894 writefds->fd_array[k++] = writefds->fd_array[i];
4896 writefds->fd_count = k;
4897 total += k;
4899 if (exceptfds && exceptfds != readfds && exceptfds != writefds)
4901 for (i = k = 0; i < exceptfds->fd_count; i++)
4902 if (poll_exceptfds[i].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
4903 exceptfds->fd_count = k;
4904 total += k;
4906 return total;
4909 /***********************************************************************
4910 * select (WS2_32.18)
4912 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
4913 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
4914 const struct WS_timeval* ws_timeout)
4916 struct pollfd *pollfds;
4917 int count, ret, timeout = -1;
4919 TRACE("read %p, write %p, excp %p timeout %p\n",
4920 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
4922 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )))
4923 return SOCKET_ERROR;
4925 if (ws_timeout)
4926 timeout = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
4928 ret = do_poll(pollfds, count, timeout);
4929 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
4931 if (ret == -1) SetLastError(wsaErrno());
4932 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
4933 HeapFree( GetProcessHeap(), 0, pollfds );
4934 return ret;
4937 /* helper to send completion messages for client-only i/o operation case */
4938 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
4939 ULONG Information )
4941 SERVER_START_REQ( add_fd_completion )
4943 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
4944 req->cvalue = CompletionValue;
4945 req->status = CompletionStatus;
4946 req->information = Information;
4947 wine_server_call( req );
4949 SERVER_END_REQ;
4953 /***********************************************************************
4954 * send (WS2_32.19)
4956 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
4958 DWORD n;
4959 WSABUF wsabuf;
4961 wsabuf.len = len;
4962 wsabuf.buf = (char*) buf;
4964 if ( WS2_sendto( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
4965 return SOCKET_ERROR;
4966 else
4967 return n;
4970 /***********************************************************************
4971 * WSASend (WS2_32.72)
4973 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4974 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4975 LPWSAOVERLAPPED lpOverlapped,
4976 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4978 return WS2_sendto( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
4979 NULL, 0, lpOverlapped, lpCompletionRoutine );
4982 /***********************************************************************
4983 * WSASendDisconnect (WS2_32.73)
4985 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
4987 return WS_shutdown( s, SD_SEND );
4991 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4992 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4993 const struct WS_sockaddr *to, int tolen,
4994 LPWSAOVERLAPPED lpOverlapped,
4995 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4997 unsigned int i, options;
4998 int n, fd, err, overlapped, flags;
4999 struct ws2_async *wsa = NULL, localwsa;
5000 int totalLength = 0;
5001 DWORD bytes_sent;
5002 BOOL is_blocking;
5004 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
5005 s, lpBuffers, dwBufferCount, dwFlags,
5006 to, tolen, lpOverlapped, lpCompletionRoutine);
5008 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
5009 TRACE( "fd=%d, options=%x\n", fd, options );
5011 if ( fd == -1 ) return SOCKET_ERROR;
5013 if (!lpOverlapped && !lpNumberOfBytesSent)
5015 err = WSAEFAULT;
5016 goto error;
5019 overlapped = (lpOverlapped || lpCompletionRoutine) &&
5020 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
5021 if (overlapped || dwBufferCount > 1)
5023 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[dwBufferCount]))))
5025 err = WSAEFAULT;
5026 goto error;
5029 else
5030 wsa = &localwsa;
5032 wsa->hSocket = SOCKET2HANDLE(s);
5033 wsa->addr = (struct WS_sockaddr *)to;
5034 wsa->addrlen.val = tolen;
5035 wsa->flags = dwFlags;
5036 wsa->lpFlags = &wsa->flags;
5037 wsa->control = NULL;
5038 wsa->n_iovecs = dwBufferCount;
5039 wsa->first_iovec = 0;
5040 for ( i = 0; i < dwBufferCount; i++ )
5042 wsa->iovec[i].iov_base = lpBuffers[i].buf;
5043 wsa->iovec[i].iov_len = lpBuffers[i].len;
5044 totalLength += lpBuffers[i].len;
5047 flags = convert_flags(dwFlags);
5048 n = WS2_send( fd, wsa, flags );
5049 if (n == -1 && errno != EAGAIN)
5051 err = wsaErrno();
5052 goto error;
5055 if (overlapped)
5057 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
5058 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
5060 wsa->user_overlapped = lpOverlapped;
5061 wsa->completion_func = lpCompletionRoutine;
5062 release_sock_fd( s, fd );
5064 if (n == -1 || n < totalLength)
5066 iosb->u.Status = STATUS_PENDING;
5067 iosb->Information = n == -1 ? 0 : n;
5069 SERVER_START_REQ( register_async )
5071 req->type = ASYNC_TYPE_WRITE;
5072 req->async.handle = wine_server_obj_handle( wsa->hSocket );
5073 req->async.callback = wine_server_client_ptr( WS2_async_send );
5074 req->async.iosb = wine_server_client_ptr( iosb );
5075 req->async.arg = wine_server_client_ptr( wsa );
5076 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
5077 req->async.cvalue = cvalue;
5078 err = wine_server_call( req );
5080 SERVER_END_REQ;
5082 /* Enable the event only after starting the async. The server will deliver it as soon as
5083 the async is done. */
5084 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
5086 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
5087 SetLastError(NtStatusToWSAError( err ));
5088 return SOCKET_ERROR;
5091 iosb->u.Status = STATUS_SUCCESS;
5092 iosb->Information = n;
5093 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = n;
5094 if (!wsa->completion_func)
5096 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
5097 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
5098 HeapFree( GetProcessHeap(), 0, wsa );
5100 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
5101 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
5102 SetLastError(ERROR_SUCCESS);
5103 return 0;
5106 if ((err = _is_blocking( s, &is_blocking )))
5108 err = NtStatusToWSAError( err );
5109 goto error;
5112 if ( is_blocking )
5114 /* On a blocking non-overlapped stream socket,
5115 * sending blocks until the entire buffer is sent. */
5116 DWORD timeout_start = GetTickCount();
5118 bytes_sent = n == -1 ? 0 : n;
5120 while (wsa->first_iovec < wsa->n_iovecs)
5122 struct pollfd pfd;
5123 int poll_timeout = -1;
5124 INT64 timeout = get_rcvsnd_timeo(fd, FALSE);
5126 if (timeout)
5128 timeout -= GetTickCount() - timeout_start;
5129 if (timeout < 0) poll_timeout = 0;
5130 else poll_timeout = timeout <= INT_MAX ? timeout : INT_MAX;
5133 pfd.fd = fd;
5134 pfd.events = POLLOUT;
5136 if (!poll_timeout || !poll( &pfd, 1, poll_timeout ))
5138 err = WSAETIMEDOUT;
5139 goto error; /* msdn says a timeout in send is fatal */
5142 n = WS2_send( fd, wsa, flags );
5143 if (n == -1 && errno != EAGAIN)
5145 err = wsaErrno();
5146 goto error;
5149 if (n >= 0)
5150 bytes_sent += n;
5153 else /* non-blocking */
5155 if (n < totalLength)
5156 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
5157 if (n == -1)
5159 err = WSAEWOULDBLOCK;
5160 goto error;
5162 bytes_sent = n;
5165 TRACE(" -> %i bytes\n", bytes_sent);
5167 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = bytes_sent;
5168 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
5169 release_sock_fd( s, fd );
5170 SetLastError(ERROR_SUCCESS);
5171 return 0;
5173 error:
5174 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
5175 release_sock_fd( s, fd );
5176 WARN(" -> ERROR %d\n", err);
5177 SetLastError(err);
5178 return SOCKET_ERROR;
5181 /***********************************************************************
5182 * WSASendTo (WS2_32.74)
5184 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5185 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
5186 const struct WS_sockaddr *to, int tolen,
5187 LPWSAOVERLAPPED lpOverlapped,
5188 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5190 return WS2_sendto( s, lpBuffers, dwBufferCount,
5191 lpNumberOfBytesSent, dwFlags,
5192 to, tolen,
5193 lpOverlapped, lpCompletionRoutine );
5196 /***********************************************************************
5197 * sendto (WS2_32.20)
5199 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
5200 const struct WS_sockaddr *to, int tolen)
5202 DWORD n;
5203 WSABUF wsabuf;
5205 wsabuf.len = len;
5206 wsabuf.buf = (char*) buf;
5208 if ( WS2_sendto(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
5209 return SOCKET_ERROR;
5210 else
5211 return n;
5214 /***********************************************************************
5215 * setsockopt (WS2_32.21)
5217 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
5218 const char *optval, int optlen)
5220 int fd;
5221 int woptval;
5222 struct linger linger;
5223 struct timeval tval;
5225 TRACE("(socket %04lx, %s, optval %s, optlen %d)\n", s,
5226 debugstr_sockopt(level, optname), debugstr_optval(optval, optlen),
5227 optlen);
5229 /* some broken apps pass the value directly instead of a pointer to it */
5230 if(optlen && IS_INTRESOURCE(optval))
5232 SetLastError(WSAEFAULT);
5233 return SOCKET_ERROR;
5236 switch(level)
5238 case WS_SOL_SOCKET:
5239 switch(optname)
5241 /* Some options need some conversion before they can be sent to
5242 * setsockopt. The conversions are done here, then they will fall through
5243 * to the general case. Special options that are not passed to
5244 * setsockopt follow below that.*/
5246 case WS_SO_DONTLINGER:
5247 if (!optval)
5249 SetLastError(WSAEFAULT);
5250 return SOCKET_ERROR;
5252 linger.l_onoff = *(const int*)optval == 0;
5253 linger.l_linger = 0;
5254 level = SOL_SOCKET;
5255 optname = SO_LINGER;
5256 optval = (char*)&linger;
5257 optlen = sizeof(struct linger);
5258 break;
5260 case WS_SO_LINGER:
5261 if (!optval)
5263 SetLastError(WSAEFAULT);
5264 return SOCKET_ERROR;
5266 linger.l_onoff = ((LINGER*)optval)->l_onoff;
5267 linger.l_linger = ((LINGER*)optval)->l_linger;
5268 level = SOL_SOCKET;
5269 optname = SO_LINGER;
5270 optval = (char*)&linger;
5271 optlen = sizeof(struct linger);
5272 break;
5274 case WS_SO_RCVBUF:
5275 if (*(const int*)optval < 2048)
5277 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
5278 return 0;
5280 /* Fall through */
5282 /* The options listed here don't need any special handling. Thanks to
5283 * the conversion happening above, options from there will fall through
5284 * to this, too.*/
5285 case WS_SO_ACCEPTCONN:
5286 case WS_SO_BROADCAST:
5287 case WS_SO_ERROR:
5288 case WS_SO_KEEPALIVE:
5289 case WS_SO_OOBINLINE:
5290 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
5291 * however, using it the BSD way fixes bug 8513 and seems to be what
5292 * most programmers assume, anyway */
5293 case WS_SO_REUSEADDR:
5294 case WS_SO_SNDBUF:
5295 case WS_SO_TYPE:
5296 convert_sockopt(&level, &optname);
5297 break;
5299 /* SO_DEBUG is a privileged operation, ignore it. */
5300 case WS_SO_DEBUG:
5301 TRACE("Ignoring SO_DEBUG\n");
5302 return 0;
5304 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
5305 * socket. According to MSDN, this option is silently ignored.*/
5306 case WS_SO_DONTROUTE:
5307 TRACE("Ignoring SO_DONTROUTE\n");
5308 return 0;
5310 /* Stops two sockets from being bound to the same port. Always happens
5311 * on unix systems, so just drop it. */
5312 case WS_SO_EXCLUSIVEADDRUSE:
5313 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
5314 return 0;
5316 /* After a ConnectEx call succeeds, the socket can't be used with half of the
5317 * normal winsock functions on windows. We don't have that problem. */
5318 case WS_SO_UPDATE_CONNECT_CONTEXT:
5319 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
5320 return 0;
5322 /* After a AcceptEx call succeeds, the socket can't be used with half of the
5323 * normal winsock functions on windows. We don't have that problem. */
5324 case WS_SO_UPDATE_ACCEPT_CONTEXT:
5325 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
5326 return 0;
5328 /* SO_OPENTYPE does not require a valid socket handle. */
5329 case WS_SO_OPENTYPE:
5330 if (!optlen || optlen < sizeof(int) || !optval)
5332 SetLastError(WSAEFAULT);
5333 return SOCKET_ERROR;
5335 get_per_thread_data()->opentype = *(const int *)optval;
5336 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
5337 return 0;
5339 #ifdef SO_RCVTIMEO
5340 case WS_SO_RCVTIMEO:
5341 #endif
5342 #ifdef SO_SNDTIMEO
5343 case WS_SO_SNDTIMEO:
5344 #endif
5345 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
5346 if (optval && optlen == sizeof(UINT32)) {
5347 /* WinSock passes milliseconds instead of struct timeval */
5348 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
5349 tval.tv_sec = *(const UINT32*)optval / 1000;
5350 /* min of 500 milliseconds */
5351 if (tval.tv_sec == 0 && tval.tv_usec && tval.tv_usec < 500000)
5352 tval.tv_usec = 500000;
5353 optlen = sizeof(struct timeval);
5354 optval = (char*)&tval;
5355 } else if (optlen == sizeof(struct timeval)) {
5356 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
5357 } else {
5358 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
5359 return 0;
5361 convert_sockopt(&level, &optname);
5362 break;
5363 #endif
5365 default:
5366 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
5367 SetLastError(WSAENOPROTOOPT);
5368 return SOCKET_ERROR;
5370 break; /* case WS_SOL_SOCKET */
5372 #ifdef HAS_IPX
5373 case WS_NSPROTO_IPX:
5374 switch(optname)
5376 case WS_IPX_PTYPE:
5377 return set_ipx_packettype(s, *(int*)optval);
5379 case WS_IPX_FILTERPTYPE:
5380 /* Sets the receive filter packet type, at the moment we don't support it */
5381 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
5382 /* Returning 0 is better for now than returning a SOCKET_ERROR */
5383 return 0;
5385 default:
5386 FIXME("opt_name:%x\n", optname);
5387 return SOCKET_ERROR;
5389 break; /* case WS_NSPROTO_IPX */
5390 #endif
5392 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
5393 case WS_IPPROTO_TCP:
5394 switch(optname)
5396 case WS_TCP_NODELAY:
5397 convert_sockopt(&level, &optname);
5398 break;
5399 default:
5400 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
5401 return SOCKET_ERROR;
5403 break;
5405 case WS_IPPROTO_IP:
5406 switch(optname)
5408 case WS_IP_ADD_MEMBERSHIP:
5409 case WS_IP_DROP_MEMBERSHIP:
5410 #ifdef IP_HDRINCL
5411 case WS_IP_HDRINCL:
5412 #endif
5413 case WS_IP_MULTICAST_IF:
5414 case WS_IP_MULTICAST_LOOP:
5415 case WS_IP_MULTICAST_TTL:
5416 case WS_IP_OPTIONS:
5417 #ifdef IP_PKTINFO
5418 case WS_IP_PKTINFO:
5419 #endif
5420 case WS_IP_TOS:
5421 case WS_IP_TTL:
5422 #ifdef IP_UNICAST_IF
5423 case WS_IP_UNICAST_IF:
5424 #endif
5425 convert_sockopt(&level, &optname);
5426 break;
5427 case WS_IP_DONTFRAGMENT:
5428 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
5429 return 0;
5430 default:
5431 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
5432 return SOCKET_ERROR;
5434 break;
5436 case WS_IPPROTO_IPV6:
5437 switch(optname)
5439 #ifdef IPV6_ADD_MEMBERSHIP
5440 case WS_IPV6_ADD_MEMBERSHIP:
5441 #endif
5442 #ifdef IPV6_DROP_MEMBERSHIP
5443 case WS_IPV6_DROP_MEMBERSHIP:
5444 #endif
5445 case WS_IPV6_MULTICAST_IF:
5446 case WS_IPV6_MULTICAST_HOPS:
5447 case WS_IPV6_MULTICAST_LOOP:
5448 case WS_IPV6_UNICAST_HOPS:
5449 case WS_IPV6_V6ONLY:
5450 #ifdef IPV6_UNICAST_IF
5451 case WS_IPV6_UNICAST_IF:
5452 #endif
5453 convert_sockopt(&level, &optname);
5454 break;
5455 case WS_IPV6_DONTFRAG:
5456 FIXME("IPV6_DONTFRAG is silently ignored!\n");
5457 return 0;
5458 case WS_IPV6_PROTECTION_LEVEL:
5459 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
5460 return 0;
5461 default:
5462 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
5463 return SOCKET_ERROR;
5465 break;
5467 default:
5468 WARN("Unknown level: 0x%08x\n", level);
5469 SetLastError(WSAEINVAL);
5470 return SOCKET_ERROR;
5471 } /* end switch(level) */
5473 /* avoid endianness issues if argument is a 16-bit int */
5474 if (optval && optlen < sizeof(int))
5476 woptval= *((const INT16 *) optval);
5477 optval= (char*) &woptval;
5478 woptval&= (1 << optlen * 8) - 1;
5479 optlen=sizeof(int);
5481 fd = get_sock_fd( s, 0, NULL );
5482 if (fd == -1) return SOCKET_ERROR;
5484 if (setsockopt(fd, level, optname, optval, optlen) == 0)
5486 #ifdef __APPLE__
5487 if (level == SOL_SOCKET && optname == SO_REUSEADDR &&
5488 setsockopt(fd, level, SO_REUSEPORT, optval, optlen) != 0)
5490 SetLastError(wsaErrno());
5491 release_sock_fd( s, fd );
5492 return SOCKET_ERROR;
5494 #endif
5495 release_sock_fd( s, fd );
5496 return 0;
5498 TRACE("Setting socket error, %d\n", wsaErrno());
5499 SetLastError(wsaErrno());
5500 release_sock_fd( s, fd );
5502 return SOCKET_ERROR;
5505 /***********************************************************************
5506 * shutdown (WS2_32.22)
5508 int WINAPI WS_shutdown(SOCKET s, int how)
5510 int fd, err = WSAENOTSOCK;
5511 unsigned int options = 0, clear_flags = 0;
5513 fd = get_sock_fd( s, 0, &options );
5514 TRACE("socket %04lx, how 0x%x, options 0x%x\n", s, how, options );
5516 if (fd == -1)
5517 return SOCKET_ERROR;
5519 switch( how )
5521 case SD_RECEIVE: /* drop receives */
5522 clear_flags |= FD_READ;
5523 break;
5524 case SD_SEND: /* drop sends */
5525 clear_flags |= FD_WRITE;
5526 break;
5527 case SD_BOTH: /* drop all */
5528 clear_flags |= FD_READ|FD_WRITE;
5529 /*fall through */
5530 default:
5531 clear_flags |= FD_WINE_LISTENING;
5534 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
5536 switch ( how )
5538 case SD_RECEIVE:
5539 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
5540 break;
5541 case SD_SEND:
5542 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
5543 break;
5544 case SD_BOTH:
5545 default:
5546 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
5547 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
5548 break;
5550 if (err) goto error;
5552 else /* non-overlapped mode */
5554 if ( shutdown( fd, how ) )
5556 err = wsaErrno();
5557 goto error;
5561 release_sock_fd( s, fd );
5562 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
5563 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
5564 return 0;
5566 error:
5567 release_sock_fd( s, fd );
5568 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
5569 SetLastError( err );
5570 return SOCKET_ERROR;
5573 /***********************************************************************
5574 * socket (WS2_32.23)
5576 SOCKET WINAPI WS_socket(int af, int type, int protocol)
5578 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
5580 return WSASocketW( af, type, protocol, NULL, 0,
5581 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
5585 /***********************************************************************
5586 * gethostbyaddr (WS2_32.51)
5588 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
5590 struct WS_hostent *retval = NULL;
5591 struct hostent* host;
5592 int unixtype = convert_af_w2u(type);
5593 const char *paddr = addr;
5594 unsigned long loopback;
5595 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5596 char *extrabuf;
5597 int ebufsize = 1024;
5598 struct hostent hostentry;
5599 int locerr = ENOBUFS;
5600 #endif
5602 /* convert back the magic loopback address if necessary */
5603 if (unixtype == AF_INET && len == 4 && !memcmp(addr, magic_loopback_addr, 4))
5605 loopback = htonl(INADDR_LOOPBACK);
5606 paddr = (char*) &loopback;
5609 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5610 host = NULL;
5611 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
5612 while(extrabuf) {
5613 int res = gethostbyaddr_r(paddr, len, unixtype,
5614 &hostentry, extrabuf, ebufsize, &host, &locerr);
5615 if (res != ERANGE) break;
5616 ebufsize *=2;
5617 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
5619 if (host) retval = WS_dup_he(host);
5620 else SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
5621 HeapFree(GetProcessHeap(),0,extrabuf);
5622 #else
5623 EnterCriticalSection( &csWSgetXXXbyYYY );
5624 host = gethostbyaddr(paddr, len, unixtype);
5625 if (host) retval = WS_dup_he(host);
5626 else SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
5627 LeaveCriticalSection( &csWSgetXXXbyYYY );
5628 #endif
5629 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
5630 return retval;
5633 /***********************************************************************
5634 * WS_compare_routes_by_metric_asc (INTERNAL)
5636 * Comparison function for qsort(), for sorting two routes (struct route)
5637 * by metric in ascending order.
5639 static int WS_compare_routes_by_metric_asc(const void *left, const void *right)
5641 return ((const struct route*)left)->metric - ((const struct route*)right)->metric;
5644 /***********************************************************************
5645 * WS_get_local_ips (INTERNAL)
5647 * Returns the list of local IP addresses by going through the network
5648 * adapters and using the local routing table to sort the addresses
5649 * from highest routing priority to lowest routing priority. This
5650 * functionality is inferred from the description for obtaining local
5651 * IP addresses given in the Knowledge Base Article Q160215.
5653 * Please note that the returned hostent is only freed when the thread
5654 * closes and is replaced if another hostent is requested.
5656 static struct WS_hostent* WS_get_local_ips( char *hostname )
5658 int numroutes = 0, i, j;
5659 DWORD n;
5660 PIP_ADAPTER_INFO adapters = NULL, k;
5661 struct WS_hostent *hostlist = NULL;
5662 PMIB_IPFORWARDTABLE routes = NULL;
5663 struct route *route_addrs = NULL;
5664 DWORD adap_size, route_size;
5666 /* Obtain the size of the adapter list and routing table, also allocate memory */
5667 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
5668 return NULL;
5669 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
5670 return NULL;
5671 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
5672 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
5673 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
5674 if (adapters == NULL || routes == NULL || route_addrs == NULL)
5675 goto cleanup;
5676 /* Obtain the adapter list and the full routing table */
5677 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
5678 goto cleanup;
5679 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
5680 goto cleanup;
5681 /* Store the interface associated with each route */
5682 for (n = 0; n < routes->dwNumEntries; n++)
5684 IF_INDEX ifindex;
5685 DWORD ifmetric;
5686 BOOL exists = FALSE;
5688 if (routes->table[n].u1.ForwardType != MIB_IPROUTE_TYPE_DIRECT)
5689 continue;
5690 ifindex = routes->table[n].dwForwardIfIndex;
5691 ifmetric = routes->table[n].dwForwardMetric1;
5692 /* Only store the lowest valued metric for an interface */
5693 for (j = 0; j < numroutes; j++)
5695 if (route_addrs[j].interface == ifindex)
5697 if (route_addrs[j].metric > ifmetric)
5698 route_addrs[j].metric = ifmetric;
5699 exists = TRUE;
5702 if (exists)
5703 continue;
5704 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
5705 if (route_addrs == NULL)
5706 goto cleanup; /* Memory allocation error, fail gracefully */
5707 route_addrs[numroutes].interface = ifindex;
5708 route_addrs[numroutes].metric = ifmetric;
5709 /* If no IP is found in the next step (for whatever reason)
5710 * then fall back to the magic loopback address.
5712 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
5713 numroutes++;
5715 if (numroutes == 0)
5716 goto cleanup; /* No routes, fall back to the Magic IP */
5717 /* Find the IP address associated with each found interface */
5718 for (i = 0; i < numroutes; i++)
5720 for (k = adapters; k != NULL; k = k->Next)
5722 char *ip = k->IpAddressList.IpAddress.String;
5724 if (route_addrs[i].interface == k->Index)
5725 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
5728 /* Allocate a hostent and enough memory for all the IPs,
5729 * including the NULL at the end of the list.
5731 hostlist = WS_create_he(hostname, 1, 0, numroutes+1, sizeof(struct in_addr));
5732 if (hostlist == NULL)
5733 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
5734 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
5735 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
5736 hostlist->h_addrtype = AF_INET;
5737 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
5738 /* Reorder the entries before placing them in the host list. Windows expects
5739 * the IP list in order from highest priority to lowest (the critical thing
5740 * is that most applications expect the first IP to be the default route).
5742 if (numroutes > 1)
5743 qsort(route_addrs, numroutes, sizeof(struct route), WS_compare_routes_by_metric_asc);
5745 for (i = 0; i < numroutes; i++)
5746 (*(struct in_addr *) hostlist->h_addr_list[i]) = route_addrs[i].addr;
5748 /* Cleanup all allocated memory except the address list,
5749 * the address list is used by the calling app.
5751 cleanup:
5752 HeapFree(GetProcessHeap(), 0, route_addrs);
5753 HeapFree(GetProcessHeap(), 0, adapters);
5754 HeapFree(GetProcessHeap(), 0, routes);
5755 return hostlist;
5758 /***********************************************************************
5759 * gethostbyname (WS2_32.52)
5761 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
5763 struct WS_hostent *retval = NULL;
5764 struct hostent* host;
5765 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5766 char *extrabuf;
5767 int ebufsize=1024;
5768 struct hostent hostentry;
5769 int locerr = ENOBUFS;
5770 #endif
5771 char hostname[100];
5772 if(!num_startup) {
5773 SetLastError(WSANOTINITIALISED);
5774 return NULL;
5776 if( gethostname( hostname, 100) == -1) {
5777 SetLastError(WSAENOBUFS); /* appropriate ? */
5778 return retval;
5780 if( !name || !name[0]) {
5781 name = hostname;
5783 /* If the hostname of the local machine is requested then return the
5784 * complete list of local IP addresses */
5785 if(strcmp(name, hostname) == 0)
5786 retval = WS_get_local_ips(hostname);
5787 /* If any other hostname was requested (or the routing table lookup failed)
5788 * then return the IP found by the host OS */
5789 if(retval == NULL)
5791 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5792 host = NULL;
5793 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
5794 while(extrabuf) {
5795 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
5796 if( res != ERANGE) break;
5797 ebufsize *=2;
5798 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
5800 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
5801 #else
5802 EnterCriticalSection( &csWSgetXXXbyYYY );
5803 host = gethostbyname(name);
5804 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
5805 #endif
5806 if (host) retval = WS_dup_he(host);
5807 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5808 HeapFree(GetProcessHeap(),0,extrabuf);
5809 #else
5810 LeaveCriticalSection( &csWSgetXXXbyYYY );
5811 #endif
5813 if (retval && retval->h_addr_list[0][0] == 127 &&
5814 strcmp(name, "localhost") != 0)
5816 /* hostname != "localhost" but has loopback address. replace by our
5817 * special address.*/
5818 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
5820 TRACE( "%s ret %p\n", debugstr_a(name), retval );
5821 return retval;
5825 /***********************************************************************
5826 * getprotobyname (WS2_32.53)
5828 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
5830 struct WS_protoent* retval = NULL;
5831 #ifdef HAVE_GETPROTOBYNAME
5832 struct protoent* proto;
5833 EnterCriticalSection( &csWSgetXXXbyYYY );
5834 if( (proto = getprotobyname(name)) != NULL )
5836 retval = WS_dup_pe(proto);
5838 else {
5839 MESSAGE("protocol %s not found; You might want to add "
5840 "this to /etc/protocols\n", debugstr_a(name) );
5841 SetLastError(WSANO_DATA);
5843 LeaveCriticalSection( &csWSgetXXXbyYYY );
5844 #endif
5845 TRACE( "%s ret %p\n", debugstr_a(name), retval );
5846 return retval;
5850 /***********************************************************************
5851 * getprotobynumber (WS2_32.54)
5853 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
5855 struct WS_protoent* retval = NULL;
5856 #ifdef HAVE_GETPROTOBYNUMBER
5857 struct protoent* proto;
5858 EnterCriticalSection( &csWSgetXXXbyYYY );
5859 if( (proto = getprotobynumber(number)) != NULL )
5861 retval = WS_dup_pe(proto);
5863 else {
5864 MESSAGE("protocol number %d not found; You might want to add "
5865 "this to /etc/protocols\n", number );
5866 SetLastError(WSANO_DATA);
5868 LeaveCriticalSection( &csWSgetXXXbyYYY );
5869 #endif
5870 TRACE("%i ret %p\n", number, retval);
5871 return retval;
5875 /***********************************************************************
5876 * getservbyname (WS2_32.55)
5878 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
5880 struct WS_servent* retval = NULL;
5881 struct servent* serv;
5882 char *name_str;
5883 char *proto_str = NULL;
5885 if (!(name_str = strdup_lower(name))) return NULL;
5887 if (proto && *proto)
5889 if (!(proto_str = strdup_lower(proto)))
5891 HeapFree( GetProcessHeap(), 0, name_str );
5892 return NULL;
5896 EnterCriticalSection( &csWSgetXXXbyYYY );
5897 serv = getservbyname(name_str, proto_str);
5898 if( serv != NULL )
5900 retval = WS_dup_se(serv);
5902 else SetLastError(WSANO_DATA);
5903 LeaveCriticalSection( &csWSgetXXXbyYYY );
5904 HeapFree( GetProcessHeap(), 0, proto_str );
5905 HeapFree( GetProcessHeap(), 0, name_str );
5906 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
5907 return retval;
5910 /***********************************************************************
5911 * freeaddrinfo (WS2_32.@)
5913 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
5915 while (res) {
5916 struct WS_addrinfo *next;
5918 HeapFree(GetProcessHeap(),0,res->ai_canonname);
5919 HeapFree(GetProcessHeap(),0,res->ai_addr);
5920 next = res->ai_next;
5921 HeapFree(GetProcessHeap(),0,res);
5922 res = next;
5926 /* helper functions for getaddrinfo()/getnameinfo() */
5927 static int convert_aiflag_w2u(int winflags) {
5928 unsigned int i;
5929 int unixflags = 0;
5931 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
5932 if (ws_aiflag_map[i][0] & winflags) {
5933 unixflags |= ws_aiflag_map[i][1];
5934 winflags &= ~ws_aiflag_map[i][0];
5936 if (winflags)
5937 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
5938 return unixflags;
5941 static int convert_niflag_w2u(int winflags) {
5942 unsigned int i;
5943 int unixflags = 0;
5945 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
5946 if (ws_niflag_map[i][0] & winflags) {
5947 unixflags |= ws_niflag_map[i][1];
5948 winflags &= ~ws_niflag_map[i][0];
5950 if (winflags)
5951 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
5952 return unixflags;
5955 static int convert_aiflag_u2w(int unixflags) {
5956 unsigned int i;
5957 int winflags = 0;
5959 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
5960 if (ws_aiflag_map[i][1] & unixflags) {
5961 winflags |= ws_aiflag_map[i][0];
5962 unixflags &= ~ws_aiflag_map[i][1];
5964 if (unixflags) /* will warn usually */
5965 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
5966 return winflags;
5969 static int convert_eai_u2w(int unixret) {
5970 int i;
5972 if (!unixret) return 0;
5974 for (i=0;ws_eai_map[i][0];i++)
5975 if (ws_eai_map[i][1] == unixret)
5976 return ws_eai_map[i][0];
5978 if (unixret == EAI_SYSTEM)
5979 /* There are broken versions of glibc which return EAI_SYSTEM
5980 * and set errno to 0 instead of returning EAI_NONAME.
5982 return errno ? sock_get_error( errno ) : WS_EAI_NONAME;
5984 FIXME("Unhandled unix EAI_xxx ret %d\n", unixret);
5985 return unixret;
5988 static char *get_hostname(void)
5990 char *ret;
5991 DWORD size = 0;
5993 GetComputerNameExA( ComputerNamePhysicalDnsHostname, NULL, &size );
5994 if (GetLastError() != ERROR_MORE_DATA) return NULL;
5995 if (!(ret = HeapAlloc( GetProcessHeap(), 0, size ))) return NULL;
5996 if (!GetComputerNameExA( ComputerNamePhysicalDnsHostname, ret, &size ))
5998 HeapFree( GetProcessHeap(), 0, ret );
5999 return NULL;
6001 return ret;
6004 /***********************************************************************
6005 * getaddrinfo (WS2_32.@)
6007 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
6009 #ifdef HAVE_GETADDRINFO
6010 struct addrinfo *unixaires = NULL;
6011 int result;
6012 struct addrinfo unixhints, *punixhints = NULL;
6013 char *hostname;
6014 const char *node;
6016 *res = NULL;
6017 if (!nodename && !servname)
6019 SetLastError(WSAHOST_NOT_FOUND);
6020 return WSAHOST_NOT_FOUND;
6023 hostname = get_hostname();
6024 if (!hostname) return WSA_NOT_ENOUGH_MEMORY;
6026 if (!nodename)
6027 node = NULL;
6028 else if (!nodename[0])
6029 node = hostname;
6030 else
6031 node = nodename;
6033 /* servname tweak required by OSX and BSD kernels */
6034 if (servname && !servname[0]) servname = "0";
6036 if (hints) {
6037 punixhints = &unixhints;
6039 memset(&unixhints, 0, sizeof(unixhints));
6040 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
6042 /* zero is a wildcard, no need to convert */
6043 if (hints->ai_family)
6044 punixhints->ai_family = convert_af_w2u(hints->ai_family);
6045 if (hints->ai_socktype)
6046 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
6047 if (hints->ai_protocol)
6048 punixhints->ai_protocol = max(convert_proto_w2u(hints->ai_protocol), 0);
6050 if (punixhints->ai_socktype < 0)
6052 SetLastError(WSAESOCKTNOSUPPORT);
6053 HeapFree(GetProcessHeap(), 0, hostname);
6054 return SOCKET_ERROR;
6057 /* windows allows invalid combinations of socket type and protocol, unix does not.
6058 * fix the parameters here to make getaddrinfo call always work */
6059 if (punixhints->ai_protocol == IPPROTO_TCP &&
6060 punixhints->ai_socktype != SOCK_STREAM && punixhints->ai_socktype != SOCK_SEQPACKET)
6061 punixhints->ai_socktype = 0;
6063 else if (punixhints->ai_protocol == IPPROTO_UDP && punixhints->ai_socktype != SOCK_DGRAM)
6064 punixhints->ai_socktype = 0;
6066 else if (IS_IPX_PROTO(punixhints->ai_protocol) && punixhints->ai_socktype != SOCK_DGRAM)
6067 punixhints->ai_socktype = 0;
6070 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
6071 result = getaddrinfo(node, servname, punixhints, &unixaires);
6073 if (result && !strcmp(hostname, node))
6075 /* If it didn't work it means the host name IP is not in /etc/hosts, try again
6076 * by sending a NULL host and avoid sending a NULL servname too because that
6077 * is invalid */
6078 ERR_(winediag)("Failed to resolve your host name IP\n");
6079 result = getaddrinfo(NULL, servname ? servname : "0", punixhints, &unixaires);
6081 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
6082 HeapFree(GetProcessHeap(), 0, hostname);
6084 if (!result) {
6085 struct addrinfo *xuai = unixaires;
6086 struct WS_addrinfo **xai = res;
6088 *xai = NULL;
6089 while (xuai) {
6090 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
6091 SIZE_T len;
6093 if (!ai)
6094 goto outofmem;
6096 *xai = ai;xai = &ai->ai_next;
6097 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
6098 ai->ai_family = convert_af_u2w(xuai->ai_family);
6099 /* copy whatever was sent in the hints */
6100 if(hints) {
6101 ai->ai_socktype = hints->ai_socktype;
6102 ai->ai_protocol = hints->ai_protocol;
6103 } else {
6104 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
6105 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
6107 if (xuai->ai_canonname) {
6108 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
6109 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
6110 if (!ai->ai_canonname)
6111 goto outofmem;
6112 strcpy(ai->ai_canonname,xuai->ai_canonname);
6114 len = xuai->ai_addrlen;
6115 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
6116 if (!ai->ai_addr)
6117 goto outofmem;
6118 ai->ai_addrlen = len;
6119 do {
6120 int winlen = ai->ai_addrlen;
6122 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
6123 ai->ai_addrlen = winlen;
6124 break;
6126 len = 2*len;
6127 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
6128 if (!ai->ai_addr)
6129 goto outofmem;
6130 ai->ai_addrlen = len;
6131 } while (1);
6132 xuai = xuai->ai_next;
6134 freeaddrinfo(unixaires);
6136 if (TRACE_ON(winsock))
6138 struct WS_addrinfo *ai = *res;
6139 while (ai)
6141 TRACE("=> %p, flags %#x, family %d, type %d, protocol %d, len %ld, name %s, addr %s\n",
6142 ai, ai->ai_flags, ai->ai_family, ai->ai_socktype, ai->ai_protocol, ai->ai_addrlen,
6143 ai->ai_canonname, debugstr_sockaddr(ai->ai_addr));
6144 ai = ai->ai_next;
6147 } else
6148 result = convert_eai_u2w(result);
6150 SetLastError(result);
6151 return result;
6153 outofmem:
6154 if (*res) WS_freeaddrinfo(*res);
6155 if (unixaires) freeaddrinfo(unixaires);
6156 return WSA_NOT_ENOUGH_MEMORY;
6157 #else
6158 FIXME("getaddrinfo() failed, not found during buildtime.\n");
6159 return EAI_FAIL;
6160 #endif
6163 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
6165 struct WS_addrinfoW *ret;
6167 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
6168 ret->ai_flags = ai->ai_flags;
6169 ret->ai_family = ai->ai_family;
6170 ret->ai_socktype = ai->ai_socktype;
6171 ret->ai_protocol = ai->ai_protocol;
6172 ret->ai_addrlen = ai->ai_addrlen;
6173 ret->ai_canonname = NULL;
6174 ret->ai_addr = NULL;
6175 ret->ai_next = NULL;
6176 if (ai->ai_canonname)
6178 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
6179 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR))))
6181 HeapFree(GetProcessHeap(), 0, ret);
6182 return NULL;
6184 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
6186 if (ai->ai_addr)
6188 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, ai->ai_addrlen)))
6190 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
6191 HeapFree(GetProcessHeap(), 0, ret);
6192 return NULL;
6194 memcpy(ret->ai_addr, ai->ai_addr, ai->ai_addrlen);
6196 return ret;
6199 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
6201 struct WS_addrinfoW *ret, *infoW;
6203 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
6204 while (info->ai_next)
6206 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
6208 FreeAddrInfoW(ret);
6209 return NULL;
6211 infoW = infoW->ai_next;
6212 info = info->ai_next;
6214 return ret;
6217 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
6219 struct WS_addrinfo *ret;
6221 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
6222 ret->ai_flags = ai->ai_flags;
6223 ret->ai_family = ai->ai_family;
6224 ret->ai_socktype = ai->ai_socktype;
6225 ret->ai_protocol = ai->ai_protocol;
6226 ret->ai_addrlen = ai->ai_addrlen;
6227 ret->ai_canonname = NULL;
6228 ret->ai_addr = NULL;
6229 ret->ai_next = NULL;
6230 if (ai->ai_canonname)
6232 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
6233 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
6235 HeapFree(GetProcessHeap(), 0, ret);
6236 return NULL;
6238 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
6240 if (ai->ai_addr)
6242 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
6244 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
6245 HeapFree(GetProcessHeap(), 0, ret);
6246 return NULL;
6248 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
6250 return ret;
6253 /***********************************************************************
6254 * GetAddrInfoW (WS2_32.@)
6256 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
6258 int ret, len;
6259 char *nodenameA = NULL, *servnameA = NULL;
6260 struct WS_addrinfo *resA, *hintsA = NULL;
6262 *res = NULL;
6263 if (nodename)
6265 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
6266 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
6267 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
6269 if (servname)
6271 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
6272 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
6274 HeapFree(GetProcessHeap(), 0, nodenameA);
6275 return EAI_MEMORY;
6277 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
6280 if (hints) hintsA = addrinfo_WtoA(hints);
6281 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
6282 WS_freeaddrinfo(hintsA);
6284 if (!ret)
6286 *res = addrinfo_list_AtoW(resA);
6287 WS_freeaddrinfo(resA);
6290 HeapFree(GetProcessHeap(), 0, nodenameA);
6291 HeapFree(GetProcessHeap(), 0, servnameA);
6292 return ret;
6295 /***********************************************************************
6296 * FreeAddrInfoW (WS2_32.@)
6298 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
6300 while (ai)
6302 ADDRINFOW *next;
6303 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
6304 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
6305 next = ai->ai_next;
6306 HeapFree(GetProcessHeap(), 0, ai);
6307 ai = next;
6311 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
6312 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
6314 #ifdef HAVE_GETNAMEINFO
6315 int ret;
6316 union generic_unix_sockaddr sa_u;
6317 unsigned int size;
6319 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
6320 serv, servlen, flags);
6322 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
6323 if (!size)
6325 SetLastError(WSAEFAULT);
6326 return WSA_NOT_ENOUGH_MEMORY;
6328 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
6329 return convert_eai_u2w(ret);
6330 #else
6331 FIXME("getnameinfo() failed, not found during buildtime.\n");
6332 return EAI_FAIL;
6333 #endif
6336 int WINAPI GetNameInfoW(const SOCKADDR *sa, WS_socklen_t salen, PWCHAR host,
6337 DWORD hostlen, PWCHAR serv, DWORD servlen, INT flags)
6339 int ret;
6340 char *hostA = NULL, *servA = NULL;
6342 if (host && (!(hostA = HeapAlloc(GetProcessHeap(), 0, hostlen)))) return EAI_MEMORY;
6343 if (serv && (!(servA = HeapAlloc(GetProcessHeap(), 0, servlen))))
6345 HeapFree(GetProcessHeap(), 0, hostA);
6346 return EAI_MEMORY;
6349 ret = WS_getnameinfo(sa, salen, hostA, hostlen, servA, servlen, flags);
6350 if (!ret)
6352 if (host) MultiByteToWideChar(CP_ACP, 0, hostA, -1, host, hostlen);
6353 if (serv) MultiByteToWideChar(CP_ACP, 0, servA, -1, serv, servlen);
6356 HeapFree(GetProcessHeap(), 0, hostA);
6357 HeapFree(GetProcessHeap(), 0, servA);
6358 return ret;
6361 /***********************************************************************
6362 * getservbyport (WS2_32.56)
6364 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
6366 struct WS_servent* retval = NULL;
6367 #ifdef HAVE_GETSERVBYPORT
6368 struct servent* serv;
6369 char *proto_str = NULL;
6371 if (proto && *proto)
6373 if (!(proto_str = strdup_lower(proto))) return NULL;
6375 EnterCriticalSection( &csWSgetXXXbyYYY );
6376 if( (serv = getservbyport(port, proto_str)) != NULL ) {
6377 retval = WS_dup_se(serv);
6379 else SetLastError(WSANO_DATA);
6380 LeaveCriticalSection( &csWSgetXXXbyYYY );
6381 HeapFree( GetProcessHeap(), 0, proto_str );
6382 #endif
6383 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
6384 return retval;
6388 /***********************************************************************
6389 * gethostname (WS2_32.57)
6391 int WINAPI WS_gethostname(char *name, int namelen)
6393 char buf[256];
6394 int len;
6396 TRACE("name %p, len %d\n", name, namelen);
6398 if (!name)
6400 SetLastError(WSAEFAULT);
6401 return SOCKET_ERROR;
6404 if (gethostname(buf, sizeof(buf)) != 0)
6406 SetLastError(wsaErrno());
6407 return SOCKET_ERROR;
6410 TRACE("<- '%s'\n", buf);
6411 len = strlen(buf);
6412 if (len > 15)
6413 WARN("Windows supports NetBIOS name length up to 15 bytes!\n");
6414 if (namelen <= len)
6416 SetLastError(WSAEFAULT);
6417 WARN("<- not enough space for hostname, required %d, got %d!\n", len + 1, namelen);
6418 return SOCKET_ERROR;
6420 strcpy(name, buf);
6421 return 0;
6425 /* ------------------------------------- Windows sockets extensions -- *
6427 * ------------------------------------------------------------------- */
6429 /***********************************************************************
6430 * WSAEnumNetworkEvents (WS2_32.36)
6432 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
6434 int ret;
6435 int i;
6436 int errors[FD_MAX_EVENTS];
6438 TRACE("%04lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
6440 SERVER_START_REQ( get_socket_event )
6442 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6443 req->service = TRUE;
6444 req->c_event = wine_server_obj_handle( hEvent );
6445 wine_server_set_reply( req, errors, sizeof(errors) );
6446 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
6448 SERVER_END_REQ;
6449 if (!ret)
6451 for (i = 0; i < FD_MAX_EVENTS; i++)
6452 lpEvent->iErrorCode[i] = NtStatusToWSAError(errors[i]);
6453 return 0;
6455 SetLastError(WSAEINVAL);
6456 return SOCKET_ERROR;
6459 /***********************************************************************
6460 * WSAEventSelect (WS2_32.39)
6462 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
6464 int ret;
6466 TRACE("%04lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
6468 SERVER_START_REQ( set_socket_event )
6470 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6471 req->mask = lEvent;
6472 req->event = wine_server_obj_handle( hEvent );
6473 req->window = 0;
6474 req->msg = 0;
6475 ret = wine_server_call( req );
6477 SERVER_END_REQ;
6478 if (!ret) return 0;
6479 SetLastError(WSAEINVAL);
6480 return SOCKET_ERROR;
6483 /**********************************************************************
6484 * WSAGetOverlappedResult (WS2_32.40)
6486 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
6487 LPDWORD lpcbTransfer, BOOL fWait,
6488 LPDWORD lpdwFlags )
6490 NTSTATUS status;
6492 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
6493 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
6495 if ( lpOverlapped == NULL )
6497 ERR( "Invalid pointer\n" );
6498 SetLastError(WSA_INVALID_PARAMETER);
6499 return FALSE;
6502 status = lpOverlapped->Internal;
6503 if (status == STATUS_PENDING)
6505 if (!fWait)
6507 SetLastError( WSA_IO_INCOMPLETE );
6508 return FALSE;
6511 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
6512 INFINITE ) == WAIT_FAILED)
6513 return FALSE;
6514 status = lpOverlapped->Internal;
6517 if ( lpcbTransfer )
6518 *lpcbTransfer = lpOverlapped->InternalHigh;
6520 if ( lpdwFlags )
6521 *lpdwFlags = lpOverlapped->u.s.Offset;
6523 if (status) SetLastError( RtlNtStatusToDosError(status) );
6524 return !status;
6528 /***********************************************************************
6529 * WSAAsyncSelect (WS2_32.101)
6531 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
6533 int ret;
6535 TRACE("%04lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
6537 SERVER_START_REQ( set_socket_event )
6539 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6540 req->mask = lEvent;
6541 req->event = 0;
6542 req->window = wine_server_user_handle( hWnd );
6543 req->msg = uMsg;
6544 ret = wine_server_call( req );
6546 SERVER_END_REQ;
6547 if (!ret) return 0;
6548 SetLastError(WSAEINVAL);
6549 return SOCKET_ERROR;
6552 /***********************************************************************
6553 * WSACreateEvent (WS2_32.31)
6556 WSAEVENT WINAPI WSACreateEvent(void)
6558 /* Create a manual-reset event, with initial state: unsignaled */
6559 TRACE("\n");
6561 return CreateEventW(NULL, TRUE, FALSE, NULL);
6564 /***********************************************************************
6565 * WSACloseEvent (WS2_32.29)
6568 BOOL WINAPI WSACloseEvent(WSAEVENT event)
6570 TRACE ("event=%p\n", event);
6572 return CloseHandle(event);
6575 /***********************************************************************
6576 * WSASocketA (WS2_32.78)
6579 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
6580 LPWSAPROTOCOL_INFOA lpProtocolInfo,
6581 GROUP g, DWORD dwFlags)
6583 INT len;
6584 WSAPROTOCOL_INFOW info;
6586 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
6587 af, type, protocol, lpProtocolInfo, g, dwFlags);
6589 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
6591 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
6592 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
6593 info.szProtocol, WSAPROTOCOL_LEN + 1);
6595 if (!len)
6597 SetLastError(WSAEINVAL);
6598 return SOCKET_ERROR;
6601 return WSASocketW(af, type, protocol, &info, g, dwFlags);
6604 /***********************************************************************
6605 * WSASocketW (WS2_32.79)
6608 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
6609 LPWSAPROTOCOL_INFOW lpProtocolInfo,
6610 GROUP g, DWORD dwFlags)
6612 SOCKET ret;
6613 DWORD err;
6614 int unixaf, unixtype, ipxptype = -1;
6617 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
6618 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
6621 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
6622 af, type, protocol, lpProtocolInfo, g, dwFlags );
6624 if (!num_startup)
6626 err = WSANOTINITIALISED;
6627 goto done;
6630 /* hack for WSADuplicateSocket */
6631 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
6632 ret = lpProtocolInfo->dwServiceFlags3;
6633 TRACE("\tgot duplicate %04lx\n", ret);
6634 return ret;
6637 if (lpProtocolInfo)
6639 if (af == FROM_PROTOCOL_INFO || !af)
6640 af = lpProtocolInfo->iAddressFamily;
6641 if (type == FROM_PROTOCOL_INFO || !type)
6642 type = lpProtocolInfo->iSocketType;
6643 if (protocol == FROM_PROTOCOL_INFO || !protocol)
6644 protocol = lpProtocolInfo->iProtocol;
6647 if (!type && (af || protocol))
6649 int autoproto = protocol;
6650 WSAPROTOCOL_INFOW infow;
6652 /* default to the first valid protocol */
6653 if (!autoproto)
6654 autoproto = valid_protocols[0];
6655 else if(IS_IPX_PROTO(autoproto))
6656 autoproto = WS_NSPROTO_IPX;
6658 if (WS_EnterSingleProtocolW(autoproto, &infow))
6660 type = infow.iSocketType;
6662 /* after win2003 it's no longer possible to pass AF_UNSPEC
6663 using the protocol info struct */
6664 if (!lpProtocolInfo && af == WS_AF_UNSPEC)
6665 af = infow.iAddressFamily;
6670 Windows has an extension to the IPX protocol that allows one to create sockets
6671 and set the IPX packet type at the same time, to do that a caller will use
6672 a protocol like NSPROTO_IPX + <PACKET TYPE>
6674 if (IS_IPX_PROTO(protocol))
6675 ipxptype = protocol - WS_NSPROTO_IPX;
6677 /* convert the socket family, type and protocol */
6678 unixaf = convert_af_w2u(af);
6679 unixtype = convert_socktype_w2u(type);
6680 protocol = convert_proto_w2u(protocol);
6681 if (unixaf == AF_UNSPEC) unixaf = -1;
6683 /* filter invalid parameters */
6684 if (protocol < 0)
6686 /* the type could not be converted */
6687 if (type && unixtype < 0)
6689 err = WSAESOCKTNOSUPPORT;
6690 goto done;
6693 err = WSAEPROTONOSUPPORT;
6694 goto done;
6696 if (unixaf < 0)
6698 /* both family and protocol can't be invalid */
6699 if (protocol <= 0)
6701 err = WSAEINVAL;
6702 goto done;
6705 /* family could not be converted and neither socket type */
6706 if (unixtype < 0 && af >= 0)
6709 err = WSAESOCKTNOSUPPORT;
6710 goto done;
6713 err = WSAEAFNOSUPPORT;
6714 goto done;
6717 SERVER_START_REQ( create_socket )
6719 req->family = unixaf;
6720 req->type = unixtype;
6721 req->protocol = protocol;
6722 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
6723 req->attributes = (dwFlags & WSA_FLAG_NO_HANDLE_INHERIT) ? 0 : OBJ_INHERIT;
6724 req->flags = dwFlags & ~WSA_FLAG_NO_HANDLE_INHERIT;
6725 set_error( wine_server_call( req ) );
6726 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
6728 SERVER_END_REQ;
6729 if (ret)
6731 TRACE("\tcreated %04lx\n", ret );
6732 if (ipxptype > 0)
6733 set_ipx_packettype(ret, ipxptype);
6734 return ret;
6737 err = GetLastError();
6738 if (err == WSAEACCES) /* raw socket denied */
6740 if (type == SOCK_RAW)
6741 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
6742 else
6743 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
6745 else
6747 /* invalid combination of valid parameters, like SOCK_STREAM + IPPROTO_UDP */
6748 if (err == WSAEINVAL)
6749 err = WSAESOCKTNOSUPPORT;
6750 else if (err == WSAEOPNOTSUPP)
6751 err = WSAEPROTONOSUPPORT;
6754 done:
6755 WARN("\t\tfailed, error %d!\n", err);
6756 SetLastError(err);
6757 return INVALID_SOCKET;
6760 /***********************************************************************
6761 * WSAJoinLeaf (WS2_32.58)
6764 SOCKET WINAPI WSAJoinLeaf(
6765 SOCKET s,
6766 const struct WS_sockaddr *addr,
6767 int addrlen,
6768 LPWSABUF lpCallerData,
6769 LPWSABUF lpCalleeData,
6770 LPQOS lpSQOS,
6771 LPQOS lpGQOS,
6772 DWORD dwFlags)
6774 FIXME("stub.\n");
6775 return INVALID_SOCKET;
6778 /***********************************************************************
6779 * __WSAFDIsSet (WS2_32.151)
6781 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
6783 int i = set->fd_count, ret = 0;
6785 while (i--)
6786 if (set->fd_array[i] == s)
6788 ret = 1;
6789 break;
6792 TRACE("(socket %04lx, fd_set %p, count %i) <- %d\n", s, set, set->fd_count, ret);
6793 return ret;
6796 /***********************************************************************
6797 * WSAIsBlocking (WS2_32.114)
6799 BOOL WINAPI WSAIsBlocking(void)
6801 /* By default WinSock should set all its sockets to non-blocking mode
6802 * and poll in PeekMessage loop when processing "blocking" ones. This
6803 * function is supposed to tell if the program is in this loop. Our
6804 * blocking calls are truly blocking so we always return FALSE.
6806 * Note: It is allowed to call this function without prior WSAStartup().
6809 TRACE("\n");
6810 return FALSE;
6813 /***********************************************************************
6814 * WSACancelBlockingCall (WS2_32.113)
6816 INT WINAPI WSACancelBlockingCall(void)
6818 TRACE("\n");
6819 return 0;
6822 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
6824 FIXME("How was this called?\n");
6825 return x();
6829 /***********************************************************************
6830 * WSASetBlockingHook (WS2_32.109)
6832 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
6834 FARPROC prev = blocking_hook;
6835 blocking_hook = lpBlockFunc;
6836 TRACE("hook %p\n", lpBlockFunc);
6837 return prev;
6841 /***********************************************************************
6842 * WSAUnhookBlockingHook (WS2_32.110)
6844 INT WINAPI WSAUnhookBlockingHook(void)
6846 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
6847 return 0;
6851 /* ----------------------------------- end of API stuff */
6853 /* ----------------------------------- helper functions -
6855 * TODO: Merge WS_dup_..() stuff into one function that
6856 * would operate with a generic structure containing internal
6857 * pointers (via a template of some kind).
6860 static int list_size(char** l, int item_size)
6862 int i,j = 0;
6863 if(l)
6864 { for(i=0;l[i];i++)
6865 j += (item_size) ? item_size : strlen(l[i]) + 1;
6866 j += (i + 1) * sizeof(char*); }
6867 return j;
6870 static int list_dup(char** l_src, char** l_to, int item_size)
6872 char *p;
6873 int i;
6875 for (i = 0; l_src[i]; i++) ;
6876 p = (char *)(l_to + i + 1);
6877 for (i = 0; l_src[i]; i++)
6879 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
6880 memcpy(p, l_src[i], count);
6881 l_to[i] = p;
6882 p += count;
6884 l_to[i] = NULL;
6885 return p - (char *)l_to;
6888 /* ----- hostent */
6890 /* create a hostent entry
6892 * Creates the entry with enough memory for the name, aliases
6893 * addresses, and the address pointers. Also copies the name
6894 * and sets up all the pointers.
6896 * NOTE: The alias and address lists must be allocated with room
6897 * for the NULL item terminating the list. This is true even if
6898 * the list has no items ("aliases" and "addresses" must be
6899 * at least "1", a truly empty list is invalid).
6901 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length)
6903 struct WS_hostent *p_to;
6904 char *p;
6905 int size = (sizeof(struct WS_hostent) +
6906 strlen(name) + 1 +
6907 sizeof(char *) * aliases +
6908 aliases_size +
6909 sizeof(char *) * addresses +
6910 address_length * (addresses - 1)), i;
6912 if (!(p_to = check_buffer_he(size))) return NULL;
6913 memset(p_to, 0, size);
6915 /* Use the memory in the same way winsock does.
6916 * First set the pointer for aliases, second set the pointers for addresses.
6917 * Third fill the addresses indexes, fourth jump aliases names size.
6918 * Fifth fill the hostname.
6919 * NOTE: This method is valid for OS version's >= XP.
6921 p = (char *)(p_to + 1);
6922 p_to->h_aliases = (char **)p;
6923 p += sizeof(char *)*aliases;
6925 p_to->h_addr_list = (char **)p;
6926 p += sizeof(char *)*addresses;
6928 for (i = 0, addresses--; i < addresses; i++, p += address_length)
6929 p_to->h_addr_list[i] = p;
6931 /* NOTE: h_aliases must be filled in manually because we don't know each string
6932 * size, leave these pointers NULL (already set to NULL by memset earlier).
6934 p += aliases_size;
6936 p_to->h_name = p;
6937 strcpy(p, name);
6939 return p_to;
6942 /* duplicate hostent entry
6943 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
6944 * Ditto for protoent and servent.
6946 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
6948 int i, addresses = 0, alias_size = 0;
6949 struct WS_hostent *p_to;
6950 char *p;
6952 for( i = 0; p_he->h_aliases[i]; i++) alias_size += strlen(p_he->h_aliases[i]) + 1;
6953 while (p_he->h_addr_list[addresses]) addresses++;
6955 p_to = WS_create_he(p_he->h_name, i + 1, alias_size, addresses + 1, p_he->h_length);
6957 if (!p_to) return NULL;
6958 p_to->h_addrtype = convert_af_u2w(p_he->h_addrtype);
6959 p_to->h_length = p_he->h_length;
6961 for(i = 0, p = p_to->h_addr_list[0]; p_he->h_addr_list[i]; i++, p += p_to->h_length)
6962 memcpy(p, p_he->h_addr_list[i], p_to->h_length);
6964 /* Fill the aliases after the IP data */
6965 for(i = 0; p_he->h_aliases[i]; i++)
6967 p_to->h_aliases[i] = p;
6968 strcpy(p, p_he->h_aliases[i]);
6969 p += strlen(p) + 1;
6972 return p_to;
6975 /* ----- protoent */
6977 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
6979 char *p;
6980 struct WS_protoent *p_to;
6982 int size = (sizeof(*p_pe) +
6983 strlen(p_pe->p_name) + 1 +
6984 list_size(p_pe->p_aliases, 0));
6986 if (!(p_to = check_buffer_pe(size))) return NULL;
6987 p_to->p_proto = p_pe->p_proto;
6989 p = (char *)(p_to + 1);
6990 p_to->p_name = p;
6991 strcpy(p, p_pe->p_name);
6992 p += strlen(p) + 1;
6994 p_to->p_aliases = (char **)p;
6995 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
6996 return p_to;
6999 /* ----- servent */
7001 static struct WS_servent *WS_dup_se(const struct servent* p_se)
7003 char *p;
7004 struct WS_servent *p_to;
7006 int size = (sizeof(*p_se) +
7007 strlen(p_se->s_proto) + 1 +
7008 strlen(p_se->s_name) + 1 +
7009 list_size(p_se->s_aliases, 0));
7011 if (!(p_to = check_buffer_se(size))) return NULL;
7012 p_to->s_port = p_se->s_port;
7014 p = (char *)(p_to + 1);
7015 p_to->s_name = p;
7016 strcpy(p, p_se->s_name);
7017 p += strlen(p) + 1;
7019 p_to->s_proto = p;
7020 strcpy(p, p_se->s_proto);
7021 p += strlen(p) + 1;
7023 p_to->s_aliases = (char **)p;
7024 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
7025 return p_to;
7029 /***********************************************************************
7030 * WSARecv (WS2_32.67)
7032 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
7033 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
7034 LPWSAOVERLAPPED lpOverlapped,
7035 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
7037 return WS2_recv_base(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
7038 NULL, NULL, lpOverlapped, lpCompletionRoutine, NULL);
7041 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
7042 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
7043 struct WS_sockaddr *lpFrom,
7044 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
7045 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
7046 LPWSABUF lpControlBuffer )
7048 unsigned int i, options;
7049 int n, fd, err, overlapped, flags;
7050 struct ws2_async *wsa = NULL, localwsa;
7051 BOOL is_blocking;
7052 DWORD timeout_start = GetTickCount();
7053 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
7055 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
7056 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
7057 (lpFromlen ? *lpFromlen : -1),
7058 lpOverlapped, lpCompletionRoutine);
7060 fd = get_sock_fd( s, FILE_READ_DATA, &options );
7061 TRACE( "fd=%d, options=%x\n", fd, options );
7063 if (fd == -1) return SOCKET_ERROR;
7065 if (*lpFlags & WS_MSG_OOB)
7067 /* It's invalid to receive OOB data from an OOBINLINED socket
7068 * as OOB data is turned into normal data. */
7069 i = sizeof(n);
7070 if (!getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, (char*) &n, &i) && n)
7072 err = WSAEINVAL;
7073 goto error;
7077 overlapped = (lpOverlapped || lpCompletionRoutine) &&
7078 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
7079 if (overlapped || dwBufferCount > 1)
7081 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[dwBufferCount]))))
7083 err = WSAEFAULT;
7084 goto error;
7087 else
7088 wsa = &localwsa;
7090 wsa->hSocket = SOCKET2HANDLE(s);
7091 wsa->flags = *lpFlags;
7092 wsa->lpFlags = lpFlags;
7093 wsa->addr = lpFrom;
7094 wsa->addrlen.ptr = lpFromlen;
7095 wsa->control = lpControlBuffer;
7096 wsa->n_iovecs = dwBufferCount;
7097 wsa->first_iovec = 0;
7098 for (i = 0; i < dwBufferCount; i++)
7100 /* check buffer first to trigger write watches */
7101 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
7103 err = WSAEFAULT;
7104 goto error;
7106 wsa->iovec[i].iov_base = lpBuffers[i].buf;
7107 wsa->iovec[i].iov_len = lpBuffers[i].len;
7110 flags = convert_flags(wsa->flags);
7111 for (;;)
7113 n = WS2_recv( fd, wsa, flags );
7114 if (n == -1)
7116 /* Unix-like systems return EINVAL when attempting to read OOB data from
7117 * an empty socket buffer, convert that to a Windows expected return. */
7118 if ((flags & MSG_OOB) && errno == EINVAL)
7119 errno = EWOULDBLOCK;
7121 if (errno != EAGAIN)
7123 int loc_errno = errno;
7124 err = wsaErrno();
7125 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
7126 goto error;
7129 else if (lpNumberOfBytesRecvd) *lpNumberOfBytesRecvd = n;
7131 if (overlapped)
7133 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
7135 wsa->user_overlapped = lpOverlapped;
7136 wsa->completion_func = lpCompletionRoutine;
7137 release_sock_fd( s, fd );
7139 if (n == -1)
7141 iosb->u.Status = STATUS_PENDING;
7142 iosb->Information = 0;
7144 SERVER_START_REQ( register_async )
7146 req->type = ASYNC_TYPE_READ;
7147 req->async.handle = wine_server_obj_handle( wsa->hSocket );
7148 req->async.callback = wine_server_client_ptr( WS2_async_recv );
7149 req->async.iosb = wine_server_client_ptr( iosb );
7150 req->async.arg = wine_server_client_ptr( wsa );
7151 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
7152 req->async.cvalue = cvalue;
7153 err = wine_server_call( req );
7155 SERVER_END_REQ;
7157 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
7158 SetLastError(NtStatusToWSAError( err ));
7159 return SOCKET_ERROR;
7162 iosb->u.Status = STATUS_SUCCESS;
7163 iosb->Information = n;
7164 if (!wsa->completion_func)
7166 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
7167 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
7168 HeapFree( GetProcessHeap(), 0, wsa );
7170 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
7171 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
7172 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7173 return 0;
7176 if (n != -1) break;
7178 if ((err = _is_blocking( s, &is_blocking )))
7180 err = NtStatusToWSAError( err );
7181 goto error;
7184 if ( is_blocking )
7186 struct pollfd pfd;
7187 int poll_timeout = -1;
7188 INT64 timeout = get_rcvsnd_timeo(fd, TRUE);
7190 if (timeout)
7192 timeout -= GetTickCount() - timeout_start;
7193 if (timeout < 0) poll_timeout = 0;
7194 else poll_timeout = timeout <= INT_MAX ? timeout : INT_MAX;
7197 pfd.fd = fd;
7198 pfd.events = POLLIN;
7199 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
7201 if (!poll_timeout || !poll( &pfd, 1, poll_timeout ))
7203 err = WSAETIMEDOUT;
7204 /* a timeout is not fatal */
7205 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7206 goto error;
7209 else
7211 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7212 err = WSAEWOULDBLOCK;
7213 goto error;
7217 TRACE(" -> %i bytes\n", n);
7218 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
7219 release_sock_fd( s, fd );
7220 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7221 SetLastError(ERROR_SUCCESS);
7223 return 0;
7225 error:
7226 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
7227 release_sock_fd( s, fd );
7228 WARN(" -> ERROR %d\n", err);
7229 SetLastError( err );
7230 return SOCKET_ERROR;
7233 /***********************************************************************
7234 * WSARecvFrom (WS2_32.69)
7236 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
7237 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
7238 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
7239 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
7242 return WS2_recv_base( s, lpBuffers, dwBufferCount,
7243 lpNumberOfBytesRecvd, lpFlags,
7244 lpFrom, lpFromlen,
7245 lpOverlapped, lpCompletionRoutine, NULL );
7248 /***********************************************************************
7249 * WSCInstallProvider (WS2_32.88)
7251 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
7252 LPCWSTR lpszProviderDllPath,
7253 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
7254 DWORD dwNumberOfEntries,
7255 LPINT lpErrno )
7257 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
7258 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
7259 dwNumberOfEntries, lpErrno);
7260 *lpErrno = 0;
7261 return 0;
7265 /***********************************************************************
7266 * WSCDeinstallProvider (WS2_32.83)
7268 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
7270 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
7271 *lpErrno = 0;
7272 return 0;
7276 /***********************************************************************
7277 * WSAAccept (WS2_32.26)
7279 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
7280 LPCONDITIONPROC lpfnCondition, DWORD_PTR dwCallbackData)
7283 int ret = 0, size;
7284 WSABUF CallerId, CallerData, CalleeId, CalleeData;
7285 /* QOS SQOS, GQOS; */
7286 GROUP g;
7287 SOCKET cs;
7288 SOCKADDR src_addr, dst_addr;
7290 TRACE("socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
7291 s, addr, addrlen, lpfnCondition, dwCallbackData);
7293 cs = WS_accept(s, addr, addrlen);
7294 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
7295 if (!lpfnCondition) return cs;
7297 if (addr && addrlen)
7299 CallerId.buf = (char *)addr;
7300 CallerId.len = *addrlen;
7302 else
7304 size = sizeof(src_addr);
7305 WS_getpeername(cs, &src_addr, &size);
7306 CallerId.buf = (char *)&src_addr;
7307 CallerId.len = size;
7309 CallerData.buf = NULL;
7310 CallerData.len = 0;
7312 size = sizeof(dst_addr);
7313 WS_getsockname(cs, &dst_addr, &size);
7315 CalleeId.buf = (char *)&dst_addr;
7316 CalleeId.len = sizeof(dst_addr);
7318 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
7319 &CalleeId, &CalleeData, &g, dwCallbackData);
7321 switch (ret)
7323 case CF_ACCEPT:
7324 return cs;
7325 case CF_DEFER:
7326 SERVER_START_REQ( set_socket_deferred )
7328 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
7329 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
7330 if ( !wine_server_call_err ( req ) )
7332 SetLastError( WSATRY_AGAIN );
7333 WS_closesocket( cs );
7336 SERVER_END_REQ;
7337 return SOCKET_ERROR;
7338 case CF_REJECT:
7339 WS_closesocket(cs);
7340 SetLastError(WSAECONNREFUSED);
7341 return SOCKET_ERROR;
7342 default:
7343 FIXME("Unknown return type from Condition function\n");
7344 SetLastError(WSAENOTSOCK);
7345 return SOCKET_ERROR;
7349 /***********************************************************************
7350 * WSADuplicateSocketA (WS2_32.32)
7352 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
7354 return WS_DuplicateSocket(FALSE, s, dwProcessId, (LPWSAPROTOCOL_INFOW) lpProtocolInfo);
7357 /***********************************************************************
7358 * WSADuplicateSocketW (WS2_32.33)
7360 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
7362 return WS_DuplicateSocket(TRUE, s, dwProcessId, lpProtocolInfo);
7365 /***********************************************************************
7366 * WSAInstallServiceClassA (WS2_32.48)
7368 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
7370 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
7371 SetLastError(WSAEACCES);
7372 return SOCKET_ERROR;
7375 /***********************************************************************
7376 * WSAInstallServiceClassW (WS2_32.49)
7378 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
7380 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
7381 SetLastError(WSAEACCES);
7382 return SOCKET_ERROR;
7385 /***********************************************************************
7386 * WSARemoveServiceClass (WS2_32.70)
7388 int WINAPI WSARemoveServiceClass(LPGUID info)
7390 FIXME("Request to remove service %p\n",info);
7391 SetLastError(WSATYPE_NOT_FOUND);
7392 return SOCKET_ERROR;
7395 /***********************************************************************
7396 * inet_ntop (WS2_32.@)
7398 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
7400 #ifdef HAVE_INET_NTOP
7401 struct WS_in6_addr *in6;
7402 struct WS_in_addr *in;
7403 PCSTR pdst;
7405 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
7406 if (!buffer)
7408 SetLastError( STATUS_INVALID_PARAMETER );
7409 return NULL;
7412 switch (family)
7414 case WS_AF_INET:
7416 in = addr;
7417 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
7418 break;
7420 case WS_AF_INET6:
7422 in6 = addr;
7423 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
7424 break;
7426 default:
7427 SetLastError( WSAEAFNOSUPPORT );
7428 return NULL;
7431 if (!pdst) SetLastError( STATUS_INVALID_PARAMETER );
7432 return pdst;
7433 #else
7434 FIXME( "not supported on this platform\n" );
7435 SetLastError( WSAEAFNOSUPPORT );
7436 return NULL;
7437 #endif
7440 /***********************************************************************
7441 * inet_pton (WS2_32.@)
7443 INT WINAPI WS_inet_pton( INT family, PCSTR addr, PVOID buffer)
7445 #ifdef HAVE_INET_PTON
7446 int unixaf, ret;
7448 TRACE("family %d, addr %s, buffer (%p)\n", family, debugstr_a(addr), buffer);
7450 if (!addr || !buffer)
7452 SetLastError(WSAEFAULT);
7453 return SOCKET_ERROR;
7456 unixaf = convert_af_w2u(family);
7457 if (unixaf != AF_INET && unixaf != AF_INET6)
7459 SetLastError(WSAEAFNOSUPPORT);
7460 return SOCKET_ERROR;
7463 ret = inet_pton(unixaf, addr, buffer);
7464 if (ret == -1) SetLastError(wsaErrno());
7465 return ret;
7466 #else
7467 FIXME( "not supported on this platform\n" );
7468 SetLastError( WSAEAFNOSUPPORT );
7469 return SOCKET_ERROR;
7470 #endif
7473 /***********************************************************************
7474 * InetPtonW (WS2_32.@)
7476 INT WINAPI InetPtonW(INT family, PCWSTR addr, PVOID buffer)
7478 char *addrA;
7479 int len;
7480 INT ret;
7482 TRACE("family %d, addr %s, buffer (%p)\n", family, debugstr_w(addr), buffer);
7484 if (!addr)
7486 SetLastError(WSAEFAULT);
7487 return SOCKET_ERROR;
7490 len = WideCharToMultiByte(CP_ACP, 0, addr, -1, NULL, 0, NULL, NULL);
7491 if (!(addrA = HeapAlloc(GetProcessHeap(), 0, len)))
7493 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7494 return SOCKET_ERROR;
7496 WideCharToMultiByte(CP_ACP, 0, addr, -1, addrA, len, NULL, NULL);
7498 ret = WS_inet_pton(family, addrA, buffer);
7500 HeapFree(GetProcessHeap(), 0, addrA);
7501 return ret;
7504 /***********************************************************************
7505 * WSAStringToAddressA (WS2_32.80)
7507 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
7508 INT AddressFamily,
7509 LPWSAPROTOCOL_INFOA lpProtocolInfo,
7510 LPSOCKADDR lpAddress,
7511 LPINT lpAddressLength)
7513 INT res=0;
7514 LPSTR workBuffer=NULL,ptrPort;
7516 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
7517 lpProtocolInfo, lpAddress, lpAddressLength );
7519 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
7521 if (!AddressString)
7523 SetLastError(WSAEINVAL);
7524 return SOCKET_ERROR;
7527 if (lpProtocolInfo)
7528 FIXME("ProtocolInfo not implemented.\n");
7530 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
7531 strlen(AddressString) + 1);
7532 if (!workBuffer)
7534 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7535 return SOCKET_ERROR;
7538 strcpy(workBuffer, AddressString);
7540 switch(AddressFamily)
7542 case WS_AF_INET:
7544 struct in_addr inetaddr;
7546 /* If lpAddressLength is too small, tell caller the size we need */
7547 if (*lpAddressLength < sizeof(SOCKADDR_IN))
7549 *lpAddressLength = sizeof(SOCKADDR_IN);
7550 res = WSAEFAULT;
7551 break;
7553 *lpAddressLength = sizeof(SOCKADDR_IN);
7554 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
7556 ((LPSOCKADDR_IN)lpAddress)->sin_family = WS_AF_INET;
7558 ptrPort = strchr(workBuffer, ':');
7559 if(ptrPort)
7561 /* User may have entered an IPv6 and asked to parse as IPv4 */
7562 if(strchr(ptrPort + 1, ':'))
7564 res = WSAEINVAL;
7565 break;
7567 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
7568 *ptrPort = '\0';
7570 else
7572 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
7575 if(inet_aton(workBuffer, &inetaddr) > 0)
7577 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
7578 res = 0;
7580 else
7581 res = WSAEINVAL;
7583 break;
7586 case WS_AF_INET6:
7588 struct in6_addr inetaddr;
7589 /* If lpAddressLength is too small, tell caller the size we need */
7590 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
7592 *lpAddressLength = sizeof(SOCKADDR_IN6);
7593 res = WSAEFAULT;
7594 break;
7596 #ifdef HAVE_INET_PTON
7597 *lpAddressLength = sizeof(SOCKADDR_IN6);
7598 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
7600 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
7602 /* This one is a bit tricky. An IPv6 address contains colons, so the
7603 * check from IPv4 doesn't work like that. However, IPv6 addresses that
7604 * contain a port are written with braces like [fd12:3456:7890::1]:12345
7605 * so what we will do is to look for ']', check if the next char is a
7606 * colon, and if it is, parse the port as in IPv4. */
7608 ptrPort = strchr(workBuffer, ']');
7609 if(ptrPort && *(++ptrPort) == ':')
7611 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort+1));
7612 *ptrPort = '\0';
7614 else
7616 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
7619 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
7621 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
7622 sizeof(struct in6_addr));
7623 res = 0;
7625 else
7626 #endif /* HAVE_INET_PTON */
7627 res = WSAEINVAL;
7629 break;
7631 default:
7632 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
7633 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
7634 res = WSAEINVAL;
7637 HeapFree(GetProcessHeap(), 0, workBuffer);
7639 if (!res) return 0;
7640 SetLastError(res);
7641 return SOCKET_ERROR;
7644 /***********************************************************************
7645 * WSAStringToAddressW (WS2_32.81)
7647 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
7648 * If this should be the case, it would be required to map these digits
7649 * to Unicode digits (0-9) using FoldString first.
7651 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
7652 INT AddressFamily,
7653 LPWSAPROTOCOL_INFOW lpProtocolInfo,
7654 LPSOCKADDR lpAddress,
7655 LPINT lpAddressLength)
7657 INT sBuffer,res=0;
7658 LPSTR workBuffer=NULL;
7659 WSAPROTOCOL_INFOA infoA;
7660 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
7662 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
7663 lpAddress, lpAddressLength );
7665 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
7667 /* if ProtocolInfo is available - convert to ANSI variant */
7668 if (lpProtocolInfo)
7670 lpProtoInfoA = &infoA;
7671 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
7673 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
7674 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
7676 SetLastError(WSAEINVAL);
7677 return SOCKET_ERROR;
7681 if (AddressString)
7683 /* Translate AddressString to ANSI code page - assumes that only
7684 standard digits 0-9 are used with this API call */
7685 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
7686 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
7688 if (workBuffer)
7690 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
7691 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
7692 lpAddress,lpAddressLength);
7693 HeapFree( GetProcessHeap(), 0, workBuffer );
7694 return res;
7696 else
7697 res = WSA_NOT_ENOUGH_MEMORY;
7699 else
7700 res = WSAEINVAL;
7702 SetLastError(res);
7703 return SOCKET_ERROR;
7706 /***********************************************************************
7707 * WSAAddressToStringA (WS2_32.27)
7709 * See WSAAddressToStringW
7711 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
7712 LPWSAPROTOCOL_INFOA info, LPSTR string,
7713 LPDWORD lenstr )
7715 DWORD size;
7716 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
7717 CHAR *p;
7719 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
7721 if (!sockaddr) return SOCKET_ERROR;
7722 if (!string || !lenstr) return SOCKET_ERROR;
7724 switch(sockaddr->sa_family)
7726 case WS_AF_INET:
7727 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
7728 sprintf( buffer, "%u.%u.%u.%u:%u",
7729 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
7730 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
7731 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
7732 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
7733 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
7735 p = strchr( buffer, ':' );
7736 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
7737 break;
7739 case WS_AF_INET6:
7741 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
7742 size_t slen;
7744 buffer[0] = 0;
7745 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
7746 if ((sockaddr6->sin6_port))
7747 strcpy(buffer, "[");
7748 slen = strlen(buffer);
7749 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, &buffer[slen], sizeof(buffer) - slen))
7751 SetLastError(WSAEINVAL);
7752 return SOCKET_ERROR;
7754 if ((sockaddr6->sin6_scope_id))
7755 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
7756 if ((sockaddr6->sin6_port))
7757 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
7758 break;
7761 default:
7762 SetLastError(WSAEINVAL);
7763 return SOCKET_ERROR;
7766 size = strlen( buffer ) + 1;
7768 if (*lenstr < size)
7770 *lenstr = size;
7771 SetLastError(WSAEFAULT);
7772 return SOCKET_ERROR;
7775 TRACE("=> %s,%u bytes\n", debugstr_a(buffer), size);
7776 *lenstr = size;
7777 strcpy( string, buffer );
7778 return 0;
7781 /***********************************************************************
7782 * WSAAddressToStringW (WS2_32.28)
7784 * Convert a sockaddr address into a readable address string.
7786 * PARAMS
7787 * sockaddr [I] Pointer to a sockaddr structure.
7788 * len [I] Size of the sockaddr structure.
7789 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
7790 * string [I/O] Pointer to a buffer to receive the address string.
7791 * lenstr [I/O] Size of the receive buffer in WCHARs.
7793 * RETURNS
7794 * Success: 0
7795 * Failure: SOCKET_ERROR
7797 * NOTES
7798 * The 'info' parameter is ignored.
7800 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
7801 LPWSAPROTOCOL_INFOW info, LPWSTR string,
7802 LPDWORD lenstr )
7804 INT ret;
7805 DWORD size;
7806 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
7807 CHAR bufAddr[54];
7809 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
7811 size = *lenstr;
7812 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
7814 if (ret) return ret;
7816 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
7818 if (*lenstr < size)
7820 *lenstr = size;
7821 SetLastError(WSAEFAULT);
7822 return SOCKET_ERROR;
7825 TRACE("=> %s,%u bytes\n", debugstr_w(buffer), size);
7826 *lenstr = size;
7827 lstrcpyW( string, buffer );
7828 return 0;
7831 /***********************************************************************
7832 * WSAEnumNameSpaceProvidersA (WS2_32.34)
7834 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
7836 FIXME( "(%p %p) Stub!\n", len, buffer );
7837 return 0;
7840 /***********************************************************************
7841 * WSAEnumNameSpaceProvidersW (WS2_32.35)
7843 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
7845 FIXME( "(%p %p) Stub!\n", len, buffer );
7846 return 0;
7849 /***********************************************************************
7850 * WSAGetQOSByName (WS2_32.41)
7852 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
7854 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
7855 return FALSE;
7858 /***********************************************************************
7859 * WSAGetServiceClassInfoA (WS2_32.42)
7861 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
7862 LPWSASERVICECLASSINFOA info )
7864 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
7865 len, info );
7866 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7867 return SOCKET_ERROR;
7870 /***********************************************************************
7871 * WSAGetServiceClassInfoW (WS2_32.43)
7873 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
7874 LPWSASERVICECLASSINFOW info )
7876 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
7877 len, info );
7878 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7879 return SOCKET_ERROR;
7882 /***********************************************************************
7883 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
7885 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
7887 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
7888 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7889 return SOCKET_ERROR;
7892 /***********************************************************************
7893 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
7895 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
7897 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
7898 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7899 return SOCKET_ERROR;
7902 /***********************************************************************
7903 * WSALookupServiceBeginA (WS2_32.59)
7905 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
7906 DWORD dwControlFlags,
7907 LPHANDLE lphLookup)
7909 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
7910 lphLookup);
7911 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7912 return SOCKET_ERROR;
7915 /***********************************************************************
7916 * WSALookupServiceBeginW (WS2_32.60)
7918 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
7919 DWORD dwControlFlags,
7920 LPHANDLE lphLookup)
7922 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
7923 lphLookup);
7924 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7925 return SOCKET_ERROR;
7928 /***********************************************************************
7929 * WSALookupServiceEnd (WS2_32.61)
7931 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
7933 FIXME("(%p) Stub!\n", lookup );
7934 return 0;
7937 /***********************************************************************
7938 * WSALookupServiceNextA (WS2_32.62)
7940 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
7942 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
7943 SetLastError(WSA_E_NO_MORE);
7944 return SOCKET_ERROR;
7947 /***********************************************************************
7948 * WSALookupServiceNextW (WS2_32.63)
7950 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
7952 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
7953 SetLastError(WSA_E_NO_MORE);
7954 return SOCKET_ERROR;
7957 /***********************************************************************
7958 * WSANtohl (WS2_32.64)
7960 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
7962 TRACE( "(%04lx 0x%08x %p)\n", s, netlong, lphostlong );
7964 if (!lphostlong) return WSAEFAULT;
7966 *lphostlong = ntohl( netlong );
7967 return 0;
7970 /***********************************************************************
7971 * WSANtohs (WS2_32.65)
7973 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
7975 TRACE( "(%04lx 0x%08x %p)\n", s, netshort, lphostshort );
7977 if (!lphostshort) return WSAEFAULT;
7979 *lphostshort = ntohs( netshort );
7980 return 0;
7983 /***********************************************************************
7984 * WSAProviderConfigChange (WS2_32.66)
7986 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
7987 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
7989 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
7990 return SOCKET_ERROR;
7993 /***********************************************************************
7994 * WSARecvDisconnect (WS2_32.68)
7996 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
7998 TRACE( "(%04lx %p)\n", s, disconnectdata );
8000 return WS_shutdown( s, SD_RECEIVE );
8003 /***********************************************************************
8004 * WSASetServiceA (WS2_32.76)
8006 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
8008 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
8009 return 0;
8012 /***********************************************************************
8013 * WSASetServiceW (WS2_32.77)
8015 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
8017 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
8018 return 0;
8021 /***********************************************************************
8022 * WSCEnableNSProvider (WS2_32.84)
8024 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
8026 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
8027 return 0;
8030 /***********************************************************************
8031 * WSCGetProviderPath (WS2_32.86)
8033 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
8035 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
8037 if (!errcode || !provider || !len) return WSAEFAULT;
8039 *errcode = WSAEINVAL;
8040 return SOCKET_ERROR;
8043 /***********************************************************************
8044 * WSCInstallNameSpace (WS2_32.87)
8046 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
8047 DWORD version, LPGUID provider )
8049 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
8050 namespace, version, debugstr_guid(provider) );
8051 return 0;
8054 /***********************************************************************
8055 * WSCUnInstallNameSpace (WS2_32.89)
8057 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
8059 FIXME("(%p) Stub!\n", lpProviderId);
8060 return NO_ERROR;
8063 /***********************************************************************
8064 * WSCWriteProviderOrder (WS2_32.91)
8066 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
8068 FIXME("(%p 0x%08x) Stub!\n", entry, number);
8069 return 0;
8072 /***********************************************************************
8073 * WSANSPIoctl (WS2_32.91)
8075 INT WINAPI WSANSPIoctl( HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer,
8076 DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer,
8077 LPDWORD lpcbBytesReturned, LPWSACOMPLETION lpCompletion )
8079 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup, dwControlCode,
8080 lpvInBuffer, cbInBuffer, lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpCompletion);
8081 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8082 return SOCKET_ERROR;
8085 /*****************************************************************************
8086 * WSAEnumProtocolsA [WS2_32.@]
8088 * see function WSAEnumProtocolsW
8090 INT WINAPI WSAEnumProtocolsA( LPINT protocols, LPWSAPROTOCOL_INFOA buffer, LPDWORD len )
8092 return WS_EnumProtocols( FALSE, protocols, (LPWSAPROTOCOL_INFOW) buffer, len);
8095 /*****************************************************************************
8096 * WSAEnumProtocolsW [WS2_32.@]
8098 * Retrieves information about specified set of active network protocols.
8100 * PARAMS
8101 * protocols [I] Pointer to null-terminated array of protocol id's. NULL
8102 * retrieves information on all available protocols.
8103 * buffer [I] Pointer to a buffer to be filled with WSAPROTOCOL_INFO
8104 * structures.
8105 * len [I/O] Pointer to a variable specifying buffer size. On output
8106 * the variable holds the number of bytes needed when the
8107 * specified size is too small.
8109 * RETURNS
8110 * Success: number of WSAPROTOCOL_INFO structures in buffer.
8111 * Failure: SOCKET_ERROR
8113 * NOTES
8114 * NT4SP5 does not return SPX if protocols == NULL
8116 * BUGS
8117 * - NT4SP5 returns in addition these list of NETBIOS protocols
8118 * (address family 17), each entry two times one for socket type 2 and 5
8120 * iProtocol szProtocol
8121 * 0x80000000 \Device\NwlnkNb
8122 * 0xfffffffa \Device\NetBT_CBENT7
8123 * 0xfffffffb \Device\Nbf_CBENT7
8124 * 0xfffffffc \Device\NetBT_NdisWan5
8125 * 0xfffffffd \Device\NetBT_El9202
8126 * 0xfffffffe \Device\Nbf_El9202
8127 * 0xffffffff \Device\Nbf_NdisWan4
8129 * - there is no check that the operating system supports the returned
8130 * protocols
8132 INT WINAPI WSAEnumProtocolsW( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
8134 return WS_EnumProtocols( TRUE, protocols, buffer, len);
8137 /*****************************************************************************
8138 * WSCEnumProtocols [WS2_32.@]
8140 * PARAMS
8141 * protocols [I] Null-terminated array of iProtocol values.
8142 * buffer [O] Buffer of WSAPROTOCOL_INFOW structures.
8143 * len [I/O] Size of buffer on input/output.
8144 * errno [O] Error code.
8146 * RETURNS
8147 * Success: number of protocols to be reported on.
8148 * Failure: SOCKET_ERROR. error is in errno.
8150 * BUGS
8151 * Doesn't supply info on layered protocols.
8154 INT WINAPI WSCEnumProtocols( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len, LPINT err )
8156 INT ret = WSAEnumProtocolsW( protocols, buffer, len );
8158 if (ret == SOCKET_ERROR) *err = WSAENOBUFS;
8160 return ret;