dbghelp: Parse the DWARF information in Mach-O modules.
[wine.git] / dlls / ws2_32 / socket.c
blob4fe3a0b2a94b7ea78b9bd27867171a671fc85bd5
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 WINE_DEFAULT_DEBUG_CHANNEL(winsock);
176 WINE_DECLARE_DEBUG_CHANNEL(winediag);
178 /* names of the protocols */
179 static const WCHAR NameIpxW[] = {'I', 'P', 'X', '\0'};
180 static const WCHAR NameSpxW[] = {'S', 'P', 'X', '\0'};
181 static const WCHAR NameSpxIIW[] = {'S', 'P', 'X', ' ', 'I', 'I', '\0'};
182 static const WCHAR NameTcpW[] = {'T', 'C', 'P', '/', 'I', 'P', '\0'};
183 static const WCHAR NameUdpW[] = {'U', 'D', 'P', '/', 'I', 'P', '\0'};
185 /* Taken from Win2k */
186 static const GUID ProviderIdIP = { 0xe70f1aa0, 0xab8b, 0x11cf,
187 { 0x8c, 0xa3, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
188 static const GUID ProviderIdIPX = { 0x11058240, 0xbe47, 0x11cf,
189 { 0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
190 static const GUID ProviderIdSPX = { 0x11058241, 0xbe47, 0x11cf,
191 { 0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
193 static const INT valid_protocols[] =
195 WS_IPPROTO_TCP,
196 WS_IPPROTO_UDP,
197 WS_NSPROTO_IPX,
198 WS_NSPROTO_SPX,
199 WS_NSPROTO_SPXII,
203 #define IS_IPX_PROTO(X) ((X) >= WS_NSPROTO_IPX && (X) <= WS_NSPROTO_IPX + 255)
205 #if defined(IP_UNICAST_IF) && defined(SO_ATTACH_FILTER)
206 # define LINUX_BOUND_IF
207 struct interface_filter {
208 struct sock_filter iface_memaddr;
209 struct sock_filter iface_rule;
210 struct sock_filter ip_memaddr;
211 struct sock_filter ip_rule;
212 struct sock_filter return_keep;
213 struct sock_filter return_dump;
215 # define FILTER_JUMP_DUMP(here) (u_char)(offsetof(struct interface_filter, return_dump) \
216 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
217 /sizeof(struct sock_filter)
218 # define FILTER_JUMP_KEEP(here) (u_char)(offsetof(struct interface_filter, return_keep) \
219 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
220 /sizeof(struct sock_filter)
221 # define FILTER_JUMP_NEXT() (u_char)(0)
222 # define SKF_NET_DESTIP 16 /* offset in the network header to the destination IP */
223 static struct interface_filter generic_interface_filter = {
224 /* This filter rule allows incoming packets on the specified interface, which works for all
225 * remotely generated packets and for locally generated broadcast packets. */
226 BPF_STMT(BPF_LD+BPF_W+BPF_ABS, SKF_AD_OFF+SKF_AD_IFINDEX),
227 BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0xdeadbeef, FILTER_JUMP_KEEP(iface_rule), FILTER_JUMP_NEXT()),
228 /* This rule allows locally generated packets targeted at the specific IP address of the chosen
229 * adapter (local packets not destined for the broadcast address do not have IFINDEX set) */
230 BPF_STMT(BPF_LD+BPF_W+BPF_ABS, SKF_NET_OFF+SKF_NET_DESTIP),
231 BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0xdeadbeef, FILTER_JUMP_KEEP(ip_rule), FILTER_JUMP_DUMP(ip_rule)),
232 BPF_STMT(BPF_RET+BPF_K, (u_int)-1), /* keep packet */
233 BPF_STMT(BPF_RET+BPF_K, 0) /* dump packet */
235 #endif /* LINUX_BOUND_IF */
238 * The actual definition of WSASendTo, wrapped in a different function name
239 * so that internal calls from ws2_32 itself will not trigger programs like
240 * Garena, which hooks WSASendTo/WSARecvFrom calls.
242 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
243 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
244 const struct WS_sockaddr *to, int tolen,
245 LPWSAOVERLAPPED lpOverlapped,
246 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine );
249 * Internal fundamental receive function, essentially WSARecvFrom with an
250 * additional parameter to support message control headers.
252 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
253 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
254 struct WS_sockaddr *lpFrom,
255 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
256 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
257 LPWSABUF lpControlBuffer );
259 /* critical section to protect some non-reentrant net function */
260 static CRITICAL_SECTION csWSgetXXXbyYYY;
261 static CRITICAL_SECTION_DEBUG critsect_debug =
263 0, 0, &csWSgetXXXbyYYY,
264 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
265 0, 0, { (DWORD_PTR)(__FILE__ ": csWSgetXXXbyYYY") }
267 static CRITICAL_SECTION csWSgetXXXbyYYY = { &critsect_debug, -1, 0, 0, 0, 0 };
269 union generic_unix_sockaddr
271 struct sockaddr addr;
272 char data[128]; /* should be big enough for all families */
275 static inline const char *debugstr_sockaddr( const struct WS_sockaddr *a )
277 if (!a) return "(nil)";
278 switch (a->sa_family)
280 case WS_AF_INET:
281 return wine_dbg_sprintf("{ family AF_INET, address %s, port %d }",
282 inet_ntoa(((const struct sockaddr_in *)a)->sin_addr),
283 ntohs(((const struct sockaddr_in *)a)->sin_port));
284 case WS_AF_INET6:
286 char buf[46];
287 const char *p;
288 struct WS_sockaddr_in6 *sin = (struct WS_sockaddr_in6 *)a;
290 p = WS_inet_ntop( WS_AF_INET6, &sin->sin6_addr, buf, sizeof(buf) );
291 if (!p)
292 p = "(unknown IPv6 address)";
293 return wine_dbg_sprintf("{ family AF_INET6, address %s, port %d }",
294 p, ntohs(sin->sin6_port));
296 case WS_AF_IPX:
298 int i;
299 char netnum[16], nodenum[16];
300 struct WS_sockaddr_ipx *sin = (struct WS_sockaddr_ipx *)a;
302 for (i = 0;i < 4; i++) sprintf(netnum + i * 2, "%02X", (unsigned char) sin->sa_netnum[i]);
303 for (i = 0;i < 6; i++) sprintf(nodenum + i * 2, "%02X", (unsigned char) sin->sa_nodenum[i]);
305 return wine_dbg_sprintf("{ family AF_IPX, address %s.%s, ipx socket %d }",
306 netnum, nodenum, sin->sa_socket);
308 case WS_AF_IRDA:
310 DWORD addr;
312 memcpy( &addr, ((const SOCKADDR_IRDA *)a)->irdaDeviceID, sizeof(addr) );
313 addr = ntohl( addr );
314 return wine_dbg_sprintf("{ family AF_IRDA, addr %08x, name %s }",
315 addr,
316 ((const SOCKADDR_IRDA *)a)->irdaServiceName);
318 default:
319 return wine_dbg_sprintf("{ family %d }", a->sa_family);
323 static inline const char *debugstr_sockopt(int level, int optname)
325 const char *stropt = NULL, *strlevel = NULL;
327 #define DEBUG_SOCKLEVEL(x) case (x): strlevel = #x
328 #define DEBUG_SOCKOPT(x) case (x): stropt = #x; break
330 switch(level)
332 DEBUG_SOCKLEVEL(WS_SOL_SOCKET);
333 switch(optname)
335 DEBUG_SOCKOPT(WS_SO_ACCEPTCONN);
336 DEBUG_SOCKOPT(WS_SO_BROADCAST);
337 DEBUG_SOCKOPT(WS_SO_BSP_STATE);
338 DEBUG_SOCKOPT(WS_SO_CONDITIONAL_ACCEPT);
339 DEBUG_SOCKOPT(WS_SO_CONNECT_TIME);
340 DEBUG_SOCKOPT(WS_SO_DEBUG);
341 DEBUG_SOCKOPT(WS_SO_DONTLINGER);
342 DEBUG_SOCKOPT(WS_SO_DONTROUTE);
343 DEBUG_SOCKOPT(WS_SO_ERROR);
344 DEBUG_SOCKOPT(WS_SO_EXCLUSIVEADDRUSE);
345 DEBUG_SOCKOPT(WS_SO_GROUP_ID);
346 DEBUG_SOCKOPT(WS_SO_GROUP_PRIORITY);
347 DEBUG_SOCKOPT(WS_SO_KEEPALIVE);
348 DEBUG_SOCKOPT(WS_SO_LINGER);
349 DEBUG_SOCKOPT(WS_SO_MAX_MSG_SIZE);
350 DEBUG_SOCKOPT(WS_SO_OOBINLINE);
351 DEBUG_SOCKOPT(WS_SO_OPENTYPE);
352 DEBUG_SOCKOPT(WS_SO_PROTOCOL_INFOA);
353 DEBUG_SOCKOPT(WS_SO_PROTOCOL_INFOW);
354 DEBUG_SOCKOPT(WS_SO_RCVBUF);
355 DEBUG_SOCKOPT(WS_SO_RCVTIMEO);
356 DEBUG_SOCKOPT(WS_SO_REUSEADDR);
357 DEBUG_SOCKOPT(WS_SO_SNDBUF);
358 DEBUG_SOCKOPT(WS_SO_SNDTIMEO);
359 DEBUG_SOCKOPT(WS_SO_TYPE);
361 break;
363 DEBUG_SOCKLEVEL(WS_NSPROTO_IPX);
364 switch(optname)
366 DEBUG_SOCKOPT(WS_IPX_PTYPE);
367 DEBUG_SOCKOPT(WS_IPX_FILTERPTYPE);
368 DEBUG_SOCKOPT(WS_IPX_DSTYPE);
369 DEBUG_SOCKOPT(WS_IPX_RECVHDR);
370 DEBUG_SOCKOPT(WS_IPX_MAXSIZE);
371 DEBUG_SOCKOPT(WS_IPX_ADDRESS);
372 DEBUG_SOCKOPT(WS_IPX_MAX_ADAPTER_NUM);
374 break;
376 DEBUG_SOCKLEVEL(WS_SOL_IRLMP);
377 switch(optname)
379 DEBUG_SOCKOPT(WS_IRLMP_ENUMDEVICES);
381 break;
383 DEBUG_SOCKLEVEL(WS_IPPROTO_TCP);
384 switch(optname)
386 DEBUG_SOCKOPT(WS_TCP_BSDURGENT);
387 DEBUG_SOCKOPT(WS_TCP_EXPEDITED_1122);
388 DEBUG_SOCKOPT(WS_TCP_NODELAY);
390 break;
392 DEBUG_SOCKLEVEL(WS_IPPROTO_IP);
393 switch(optname)
395 DEBUG_SOCKOPT(WS_IP_ADD_MEMBERSHIP);
396 DEBUG_SOCKOPT(WS_IP_DROP_MEMBERSHIP);
397 DEBUG_SOCKOPT(WS_IP_HDRINCL);
398 DEBUG_SOCKOPT(WS_IP_MULTICAST_IF);
399 DEBUG_SOCKOPT(WS_IP_MULTICAST_LOOP);
400 DEBUG_SOCKOPT(WS_IP_MULTICAST_TTL);
401 DEBUG_SOCKOPT(WS_IP_OPTIONS);
402 DEBUG_SOCKOPT(WS_IP_PKTINFO);
403 DEBUG_SOCKOPT(WS_IP_TOS);
404 DEBUG_SOCKOPT(WS_IP_TTL);
405 DEBUG_SOCKOPT(WS_IP_UNICAST_IF);
406 DEBUG_SOCKOPT(WS_IP_DONTFRAGMENT);
408 break;
410 DEBUG_SOCKLEVEL(WS_IPPROTO_IPV6);
411 switch(optname)
413 DEBUG_SOCKOPT(WS_IPV6_ADD_MEMBERSHIP);
414 DEBUG_SOCKOPT(WS_IPV6_DROP_MEMBERSHIP);
415 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_IF);
416 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_HOPS);
417 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_LOOP);
418 DEBUG_SOCKOPT(WS_IPV6_UNICAST_HOPS);
419 DEBUG_SOCKOPT(WS_IPV6_V6ONLY);
420 DEBUG_SOCKOPT(WS_IPV6_UNICAST_IF);
421 DEBUG_SOCKOPT(WS_IPV6_DONTFRAG);
423 break;
425 #undef DEBUG_SOCKLEVEL
426 #undef DEBUG_SOCKOPT
428 if (!strlevel)
429 strlevel = wine_dbg_sprintf("WS_0x%x", level);
430 if (!stropt)
431 stropt = wine_dbg_sprintf("WS_0x%x", optname);
433 return wine_dbg_sprintf("level %s, name %s", strlevel + 3, stropt + 3);
436 static inline const char *debugstr_optval(const char *optval, int optlenval)
438 if (optval && !IS_INTRESOURCE(optval) && optlenval >= 1 && optlenval <= sizeof(DWORD))
440 DWORD value = 0;
441 memcpy(&value, optval, optlenval);
442 return wine_dbg_sprintf("%p (%u)", optval, value);
444 return wine_dbg_sprintf("%p", optval);
447 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
448 #define SOCKET2HANDLE(s) ((HANDLE)(s))
449 #define HANDLE2SOCKET(h) ((SOCKET)(h))
451 /****************************************************************
452 * Async IO declarations
453 ****************************************************************/
455 struct ws2_async_io
457 struct ws2_async_io *next;
460 struct ws2_async_shutdown
462 struct ws2_async_io io;
463 HANDLE hSocket;
464 IO_STATUS_BLOCK iosb;
465 int type;
468 struct ws2_async
470 struct ws2_async_io io;
471 HANDLE hSocket;
472 LPWSAOVERLAPPED user_overlapped;
473 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
474 IO_STATUS_BLOCK local_iosb;
475 struct WS_sockaddr *addr;
476 union
478 int val; /* for send operations */
479 int *ptr; /* for recv operations */
480 } addrlen;
481 DWORD flags;
482 DWORD *lpFlags;
483 WSABUF *control;
484 unsigned int n_iovecs;
485 unsigned int first_iovec;
486 struct iovec iovec[1];
489 struct ws2_accept_async
491 struct ws2_async_io io;
492 HANDLE listen_socket;
493 HANDLE accept_socket;
494 LPOVERLAPPED user_overlapped;
495 ULONG_PTR cvalue;
496 PVOID buf; /* buffer to write data to */
497 int data_len;
498 int local_len;
499 int remote_len;
500 struct ws2_async *read;
503 static struct ws2_async_io *async_io_freelist;
505 static void release_async_io( struct ws2_async_io *io )
507 for (;;)
509 struct ws2_async_io *next = async_io_freelist;
510 io->next = next;
511 if (InterlockedCompareExchangePointer( (void **)&async_io_freelist, io, next ) == next) return;
515 static struct ws2_async_io *alloc_async_io( DWORD size )
517 /* first free remaining previous fileinfos */
519 struct ws2_async_io *io = InterlockedExchangePointer( (void **)&async_io_freelist, NULL );
521 while (io)
523 struct ws2_async_io *next = io->next;
524 HeapFree( GetProcessHeap(), 0, io );
525 io = next;
528 return HeapAlloc( GetProcessHeap(), 0, size );
531 /****************************************************************/
533 /* ----------------------------------- internal data */
535 /* ws_... struct conversion flags */
537 typedef struct /* WSAAsyncSelect() control struct */
539 HANDLE service, event, sock;
540 HWND hWnd;
541 UINT uMsg;
542 LONG lEvent;
543 } ws_select_info;
545 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
546 #define WS_MAX_UDP_DATAGRAM 1024
547 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
549 /* hostent's, servent's and protent's are stored in one buffer per thread,
550 * as documented on MSDN for the functions that return any of the buffers */
551 struct per_thread_data
553 int opentype;
554 struct WS_hostent *he_buffer;
555 struct WS_servent *se_buffer;
556 struct WS_protoent *pe_buffer;
557 int he_len;
558 int se_len;
559 int pe_len;
560 char ntoa_buffer[16]; /* 4*3 digits + 3 '.' + 1 '\0' */
563 /* internal: routing description information */
564 struct route {
565 struct in_addr addr;
566 IF_INDEX interface;
567 DWORD metric;
570 static INT num_startup; /* reference counter */
571 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
573 /* function prototypes */
574 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length);
575 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
576 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
577 static struct WS_servent *WS_dup_se(const struct servent* p_se);
578 static int ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size);
580 int WSAIOCTL_GetInterfaceCount(void);
581 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
583 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus, ULONG Information );
585 #define MAP_OPTION(opt) { WS_##opt, opt }
587 static const int ws_flags_map[][2] =
589 MAP_OPTION( MSG_OOB ),
590 MAP_OPTION( MSG_PEEK ),
591 MAP_OPTION( MSG_DONTROUTE ),
592 MAP_OPTION( MSG_WAITALL ),
595 static const int ws_sock_map[][2] =
597 MAP_OPTION( SO_DEBUG ),
598 MAP_OPTION( SO_ACCEPTCONN ),
599 MAP_OPTION( SO_REUSEADDR ),
600 MAP_OPTION( SO_KEEPALIVE ),
601 MAP_OPTION( SO_DONTROUTE ),
602 MAP_OPTION( SO_BROADCAST ),
603 MAP_OPTION( SO_LINGER ),
604 MAP_OPTION( SO_OOBINLINE ),
605 MAP_OPTION( SO_SNDBUF ),
606 MAP_OPTION( SO_RCVBUF ),
607 MAP_OPTION( SO_ERROR ),
608 MAP_OPTION( SO_TYPE ),
609 #ifdef SO_RCVTIMEO
610 MAP_OPTION( SO_RCVTIMEO ),
611 #endif
612 #ifdef SO_SNDTIMEO
613 MAP_OPTION( SO_SNDTIMEO ),
614 #endif
617 static const int ws_tcp_map[][2] =
619 #ifdef TCP_NODELAY
620 MAP_OPTION( TCP_NODELAY ),
621 #endif
624 static const int ws_ip_map[][2] =
626 MAP_OPTION( IP_MULTICAST_IF ),
627 MAP_OPTION( IP_MULTICAST_TTL ),
628 MAP_OPTION( IP_MULTICAST_LOOP ),
629 MAP_OPTION( IP_ADD_MEMBERSHIP ),
630 MAP_OPTION( IP_DROP_MEMBERSHIP ),
631 MAP_OPTION( IP_OPTIONS ),
632 #ifdef IP_HDRINCL
633 MAP_OPTION( IP_HDRINCL ),
634 #endif
635 MAP_OPTION( IP_TOS ),
636 MAP_OPTION( IP_TTL ),
637 #ifdef IP_PKTINFO
638 MAP_OPTION( IP_PKTINFO ),
639 #endif
640 #ifdef IP_UNICAST_IF
641 MAP_OPTION( IP_UNICAST_IF ),
642 #endif
645 static const int ws_ipv6_map[][2] =
647 #ifdef IPV6_ADD_MEMBERSHIP
648 MAP_OPTION( IPV6_ADD_MEMBERSHIP ),
649 #endif
650 #ifdef IPV6_DROP_MEMBERSHIP
651 MAP_OPTION( IPV6_DROP_MEMBERSHIP ),
652 #endif
653 MAP_OPTION( IPV6_MULTICAST_IF ),
654 MAP_OPTION( IPV6_MULTICAST_HOPS ),
655 MAP_OPTION( IPV6_MULTICAST_LOOP ),
656 MAP_OPTION( IPV6_UNICAST_HOPS ),
657 MAP_OPTION( IPV6_V6ONLY ),
658 #ifdef IPV6_UNICAST_IF
659 MAP_OPTION( IPV6_UNICAST_IF ),
660 #endif
663 static const int ws_af_map[][2] =
665 MAP_OPTION( AF_UNSPEC ),
666 MAP_OPTION( AF_INET ),
667 MAP_OPTION( AF_INET6 ),
668 #ifdef HAS_IPX
669 MAP_OPTION( AF_IPX ),
670 #endif
671 #ifdef AF_IRDA
672 MAP_OPTION( AF_IRDA ),
673 #endif
674 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
677 static const int ws_socktype_map[][2] =
679 MAP_OPTION( SOCK_DGRAM ),
680 MAP_OPTION( SOCK_STREAM ),
681 MAP_OPTION( SOCK_RAW ),
682 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
685 static const int ws_proto_map[][2] =
687 MAP_OPTION( IPPROTO_IP ),
688 MAP_OPTION( IPPROTO_TCP ),
689 MAP_OPTION( IPPROTO_UDP ),
690 MAP_OPTION( IPPROTO_ICMP ),
691 MAP_OPTION( IPPROTO_IGMP ),
692 MAP_OPTION( IPPROTO_RAW ),
693 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
696 static const int ws_aiflag_map[][2] =
698 MAP_OPTION( AI_PASSIVE ),
699 MAP_OPTION( AI_CANONNAME ),
700 MAP_OPTION( AI_NUMERICHOST ),
701 #ifdef AI_NUMERICSERV
702 MAP_OPTION( AI_NUMERICSERV ),
703 #endif
704 #ifdef AI_V4MAPPED
705 MAP_OPTION( AI_V4MAPPED ),
706 #endif
707 MAP_OPTION( AI_ADDRCONFIG ),
710 static const int ws_niflag_map[][2] =
712 MAP_OPTION( NI_NOFQDN ),
713 MAP_OPTION( NI_NUMERICHOST ),
714 MAP_OPTION( NI_NAMEREQD ),
715 MAP_OPTION( NI_NUMERICSERV ),
716 MAP_OPTION( NI_DGRAM ),
719 static const int ws_eai_map[][2] =
721 MAP_OPTION( EAI_AGAIN ),
722 MAP_OPTION( EAI_BADFLAGS ),
723 MAP_OPTION( EAI_FAIL ),
724 MAP_OPTION( EAI_FAMILY ),
725 MAP_OPTION( EAI_MEMORY ),
726 /* Note: EAI_NODATA is deprecated, but still
727 * used by Windows and Linux... We map the newer
728 * EAI_NONAME to EAI_NODATA for now until Windows
729 * changes too.
731 #ifdef EAI_NODATA
732 MAP_OPTION( EAI_NODATA ),
733 #endif
734 #ifdef EAI_NONAME
735 { WS_EAI_NODATA, EAI_NONAME },
736 #endif
738 MAP_OPTION( EAI_SERVICE ),
739 MAP_OPTION( EAI_SOCKTYPE ),
740 { 0, 0 }
743 static const char magic_loopback_addr[] = {127, 12, 34, 56};
745 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
746 #ifdef IP_PKTINFO
747 static inline WSACMSGHDR *fill_control_message(int level, int type, WSACMSGHDR *current, ULONG *maxsize, void *data, int len)
749 ULONG msgsize = sizeof(WSACMSGHDR) + WSA_CMSG_ALIGN(len);
750 char *ptr = (char *) current + sizeof(WSACMSGHDR);
752 /* Make sure there is at least enough room for this entry */
753 if (msgsize > *maxsize)
754 return NULL;
755 *maxsize -= msgsize;
756 /* Fill in the entry */
757 current->cmsg_len = sizeof(WSACMSGHDR) + len;
758 current->cmsg_level = level;
759 current->cmsg_type = type;
760 memcpy(ptr, data, len);
761 /* Return the pointer to where next entry should go */
762 return (WSACMSGHDR *) (ptr + WSA_CMSG_ALIGN(len));
764 #endif /* IP_PKTINFO */
766 static inline int convert_control_headers(struct msghdr *hdr, WSABUF *control)
768 #ifdef IP_PKTINFO
769 WSACMSGHDR *cmsg_win = (WSACMSGHDR *) control->buf, *ptr;
770 ULONG ctlsize = control->len;
771 struct cmsghdr *cmsg_unix;
773 ptr = cmsg_win;
774 /* Loop over all the headers, converting as appropriate */
775 for (cmsg_unix = CMSG_FIRSTHDR(hdr); cmsg_unix != NULL; cmsg_unix = CMSG_NXTHDR(hdr, cmsg_unix))
777 switch(cmsg_unix->cmsg_level)
779 case IPPROTO_IP:
780 switch(cmsg_unix->cmsg_type)
782 case IP_PKTINFO:
784 /* Convert the Unix IP_PKTINFO structure to the Windows version */
785 struct in_pktinfo *data_unix = (struct in_pktinfo *) CMSG_DATA(cmsg_unix);
786 struct WS_in_pktinfo data_win;
788 memcpy(&data_win.ipi_addr,&data_unix->ipi_addr.s_addr,4); /* 4 bytes = 32 address bits */
789 data_win.ipi_ifindex = data_unix->ipi_ifindex;
790 ptr = fill_control_message(WS_IPPROTO_IP, WS_IP_PKTINFO, ptr, &ctlsize,
791 (void*)&data_win, sizeof(data_win));
792 if (!ptr) goto error;
793 } break;
794 default:
795 FIXME("Unhandled IPPROTO_IP message header type %d\n", cmsg_unix->cmsg_type);
796 break;
798 break;
799 default:
800 FIXME("Unhandled message header level %d\n", cmsg_unix->cmsg_level);
801 break;
805 error:
806 /* Set the length of the returned control headers */
807 control->len = (ptr == NULL ? 0 : (char*)ptr - (char*)cmsg_win);
808 return (ptr != NULL);
809 #else /* IP_PKTINFO */
810 control->len = 0;
811 return 1;
812 #endif /* IP_PKTINFO */
814 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
816 /* ----------------------------------- error handling */
818 static NTSTATUS sock_get_ntstatus( int err )
820 switch ( err )
822 case EBADF: return STATUS_INVALID_HANDLE;
823 case EBUSY: return STATUS_DEVICE_BUSY;
824 case EPERM:
825 case EACCES: return STATUS_ACCESS_DENIED;
826 case EFAULT: return STATUS_NO_MEMORY;
827 case EINVAL: return STATUS_INVALID_PARAMETER;
828 case ENFILE:
829 case EMFILE: return STATUS_TOO_MANY_OPENED_FILES;
830 case EWOULDBLOCK: return STATUS_CANT_WAIT;
831 case EINPROGRESS: return STATUS_PENDING;
832 case EALREADY: return STATUS_NETWORK_BUSY;
833 case ENOTSOCK: return STATUS_OBJECT_TYPE_MISMATCH;
834 case EDESTADDRREQ: return STATUS_INVALID_PARAMETER;
835 case EMSGSIZE: return STATUS_BUFFER_OVERFLOW;
836 case EPROTONOSUPPORT:
837 case ESOCKTNOSUPPORT:
838 case EPFNOSUPPORT:
839 case EAFNOSUPPORT:
840 case EPROTOTYPE: return STATUS_NOT_SUPPORTED;
841 case ENOPROTOOPT: return STATUS_INVALID_PARAMETER;
842 case EOPNOTSUPP: return STATUS_NOT_SUPPORTED;
843 case EADDRINUSE: return STATUS_ADDRESS_ALREADY_ASSOCIATED;
844 case EADDRNOTAVAIL: return STATUS_INVALID_PARAMETER;
845 case ECONNREFUSED: return STATUS_CONNECTION_REFUSED;
846 case ESHUTDOWN: return STATUS_PIPE_DISCONNECTED;
847 case ENOTCONN: return STATUS_CONNECTION_DISCONNECTED;
848 case ETIMEDOUT: return STATUS_IO_TIMEOUT;
849 case ENETUNREACH: return STATUS_NETWORK_UNREACHABLE;
850 case ENETDOWN: return STATUS_NETWORK_BUSY;
851 case EPIPE:
852 case ECONNRESET: return STATUS_CONNECTION_RESET;
853 case ECONNABORTED: return STATUS_CONNECTION_ABORTED;
855 case 0: return STATUS_SUCCESS;
856 default:
857 WARN("Unknown errno %d!\n", err);
858 return STATUS_UNSUCCESSFUL;
862 static UINT sock_get_error( int err )
864 switch(err)
866 case EINTR: return WSAEINTR;
867 case EPERM:
868 case EACCES: return WSAEACCES;
869 case EFAULT: return WSAEFAULT;
870 case EINVAL: return WSAEINVAL;
871 case EMFILE: return WSAEMFILE;
872 case EWOULDBLOCK: return WSAEWOULDBLOCK;
873 case EINPROGRESS: return WSAEINPROGRESS;
874 case EALREADY: return WSAEALREADY;
875 case EBADF:
876 case ENOTSOCK: return WSAENOTSOCK;
877 case EDESTADDRREQ: return WSAEDESTADDRREQ;
878 case EMSGSIZE: return WSAEMSGSIZE;
879 case EPROTOTYPE: return WSAEPROTOTYPE;
880 case ENOPROTOOPT: return WSAENOPROTOOPT;
881 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
882 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
883 case EOPNOTSUPP: return WSAEOPNOTSUPP;
884 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
885 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
886 case EADDRINUSE: return WSAEADDRINUSE;
887 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
888 case ENETDOWN: return WSAENETDOWN;
889 case ENETUNREACH: return WSAENETUNREACH;
890 case ENETRESET: return WSAENETRESET;
891 case ECONNABORTED: return WSAECONNABORTED;
892 case EPIPE:
893 case ECONNRESET: return WSAECONNRESET;
894 case ENOBUFS: return WSAENOBUFS;
895 case EISCONN: return WSAEISCONN;
896 case ENOTCONN: return WSAENOTCONN;
897 case ESHUTDOWN: return WSAESHUTDOWN;
898 case ETOOMANYREFS: return WSAETOOMANYREFS;
899 case ETIMEDOUT: return WSAETIMEDOUT;
900 case ECONNREFUSED: return WSAECONNREFUSED;
901 case ELOOP: return WSAELOOP;
902 case ENAMETOOLONG: return WSAENAMETOOLONG;
903 case EHOSTDOWN: return WSAEHOSTDOWN;
904 case EHOSTUNREACH: return WSAEHOSTUNREACH;
905 case ENOTEMPTY: return WSAENOTEMPTY;
906 #ifdef EPROCLIM
907 case EPROCLIM: return WSAEPROCLIM;
908 #endif
909 #ifdef EUSERS
910 case EUSERS: return WSAEUSERS;
911 #endif
912 #ifdef EDQUOT
913 case EDQUOT: return WSAEDQUOT;
914 #endif
915 #ifdef ESTALE
916 case ESTALE: return WSAESTALE;
917 #endif
918 #ifdef EREMOTE
919 case EREMOTE: return WSAEREMOTE;
920 #endif
922 /* just in case we ever get here and there are no problems */
923 case 0: return 0;
924 default:
925 WARN("Unknown errno %d!\n", err);
926 return WSAEOPNOTSUPP;
930 static UINT wsaErrno(void)
932 int loc_errno = errno;
933 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
935 return sock_get_error( loc_errno );
938 /* most ws2 overlapped functions return an ntstatus-based error code */
939 static NTSTATUS wsaErrStatus(void)
941 int loc_errno = errno;
942 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
944 return sock_get_ntstatus(loc_errno);
947 static UINT wsaHerrno(int loc_errno)
949 WARN("h_errno %d.\n", loc_errno);
951 switch(loc_errno)
953 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
954 case TRY_AGAIN: return WSATRY_AGAIN;
955 case NO_RECOVERY: return WSANO_RECOVERY;
956 case NO_DATA: return WSANO_DATA;
957 case ENOBUFS: return WSAENOBUFS;
959 case 0: return 0;
960 default:
961 WARN("Unknown h_errno %d!\n", loc_errno);
962 return WSAEOPNOTSUPP;
966 static inline DWORD NtStatusToWSAError( const DWORD status )
968 /* We only need to cover the status codes set by server async request handling */
969 DWORD wserr;
970 switch ( status )
972 case STATUS_SUCCESS: wserr = 0; break;
973 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
974 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
975 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
976 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
977 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
978 case STATUS_NETWORK_BUSY: wserr = WSAEALREADY; break;
979 case STATUS_NETWORK_UNREACHABLE: wserr = WSAENETUNREACH; break;
980 case STATUS_CONNECTION_REFUSED: wserr = WSAECONNREFUSED; break;
981 case STATUS_CONNECTION_DISCONNECTED: wserr = WSAENOTCONN; break;
982 case STATUS_CONNECTION_RESET: wserr = WSAECONNRESET; break;
983 case STATUS_CONNECTION_ABORTED: wserr = WSAECONNABORTED; break;
984 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
985 case STATUS_ADDRESS_ALREADY_ASSOCIATED: wserr = WSAEADDRINUSE; break;
986 case STATUS_IO_TIMEOUT:
987 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
988 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
989 case STATUS_ACCESS_DENIED: wserr = WSAEACCES; break;
990 case STATUS_TOO_MANY_OPENED_FILES: wserr = WSAEMFILE; break;
991 case STATUS_CANT_WAIT: wserr = WSAEWOULDBLOCK; break;
992 case STATUS_BUFFER_OVERFLOW: wserr = WSAEMSGSIZE; break;
993 case STATUS_NOT_SUPPORTED: wserr = WSAEOPNOTSUPP; break;
994 case STATUS_HOST_UNREACHABLE: wserr = WSAEHOSTUNREACH; break;
996 default:
997 wserr = RtlNtStatusToDosError( status );
998 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
1000 return wserr;
1003 /* set last error code from NT status without mapping WSA errors */
1004 static inline unsigned int set_error( unsigned int err )
1006 if (err)
1008 err = NtStatusToWSAError( err );
1009 SetLastError( err );
1011 return err;
1014 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
1016 int fd;
1017 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
1018 return -1;
1019 return fd;
1022 static inline void release_sock_fd( SOCKET s, int fd )
1024 wine_server_release_fd( SOCKET2HANDLE(s), fd );
1027 static void _enable_event( HANDLE s, unsigned int event,
1028 unsigned int sstate, unsigned int cstate )
1030 SERVER_START_REQ( enable_socket_event )
1032 req->handle = wine_server_obj_handle( s );
1033 req->mask = event;
1034 req->sstate = sstate;
1035 req->cstate = cstate;
1036 wine_server_call( req );
1038 SERVER_END_REQ;
1041 static NTSTATUS _is_blocking(SOCKET s, BOOL *ret)
1043 NTSTATUS status;
1044 SERVER_START_REQ( get_socket_event )
1046 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1047 req->service = FALSE;
1048 req->c_event = 0;
1049 status = wine_server_call( req );
1050 *ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
1052 SERVER_END_REQ;
1053 return status;
1056 static unsigned int _get_sock_mask(SOCKET s)
1058 unsigned int ret;
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 wine_server_call( req );
1065 ret = reply->mask;
1067 SERVER_END_REQ;
1068 return ret;
1071 static void _sync_sock_state(SOCKET s)
1073 BOOL dummy;
1074 /* do a dummy wineserver request in order to let
1075 the wineserver run through its select loop once */
1076 (void)_is_blocking(s, &dummy);
1079 static void _get_sock_errors(SOCKET s, int *events)
1081 SERVER_START_REQ( get_socket_event )
1083 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1084 req->service = FALSE;
1085 req->c_event = 0;
1086 wine_server_set_reply( req, events, sizeof(int) * FD_MAX_EVENTS );
1087 wine_server_call( req );
1089 SERVER_END_REQ;
1092 static int _get_sock_error(SOCKET s, unsigned int bit)
1094 int events[FD_MAX_EVENTS];
1095 _get_sock_errors(s, events);
1096 return events[bit];
1099 static int _get_fd_type(int fd)
1101 int sock_type = -1;
1102 socklen_t optlen = sizeof(sock_type);
1103 getsockopt(fd, SOL_SOCKET, SO_TYPE, (char*) &sock_type, &optlen);
1104 return sock_type;
1107 static struct per_thread_data *get_per_thread_data(void)
1109 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
1110 /* lazy initialization */
1111 if (!ptb)
1113 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
1114 NtCurrentTeb()->WinSockData = ptb;
1116 return ptb;
1119 static void free_per_thread_data(void)
1121 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
1123 if (!ptb) return;
1125 /* delete scratch buffers */
1126 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1127 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1128 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1129 ptb->he_buffer = NULL;
1130 ptb->se_buffer = NULL;
1131 ptb->pe_buffer = NULL;
1133 HeapFree( GetProcessHeap(), 0, ptb );
1134 NtCurrentTeb()->WinSockData = NULL;
1137 /***********************************************************************
1138 * DllMain (WS2_32.init)
1140 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
1142 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
1143 switch (fdwReason) {
1144 case DLL_PROCESS_ATTACH:
1145 break;
1146 case DLL_PROCESS_DETACH:
1147 if (fImpLoad) break;
1148 free_per_thread_data();
1149 DeleteCriticalSection(&csWSgetXXXbyYYY);
1150 break;
1151 case DLL_THREAD_DETACH:
1152 free_per_thread_data();
1153 break;
1155 return TRUE;
1158 /***********************************************************************
1159 * convert_flags()
1161 * Converts send/recv flags from Windows format.
1162 * Return the converted flag bits, unsupported flags remain unchanged.
1164 static int convert_flags(int flags)
1166 int i, out;
1167 if (!flags) return 0;
1169 for (out = i = 0; flags && i < sizeof(ws_flags_map) / sizeof(ws_flags_map[0]); i++)
1171 if (ws_flags_map[i][0] & flags)
1173 out |= ws_flags_map[i][1];
1174 flags &= ~ws_flags_map[i][0];
1177 if (flags)
1179 FIXME("Unknown send/recv flags 0x%x, using anyway...\n", flags);
1180 out |= flags;
1182 return out;
1185 /***********************************************************************
1186 * convert_sockopt()
1188 * Converts socket flags from Windows format.
1189 * Return 1 if converted, 0 if not (error).
1191 static int convert_sockopt(INT *level, INT *optname)
1193 unsigned int i;
1194 switch (*level)
1196 case WS_SOL_SOCKET:
1197 *level = SOL_SOCKET;
1198 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
1199 if( ws_sock_map[i][0] == *optname )
1201 *optname = ws_sock_map[i][1];
1202 return 1;
1205 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
1206 break;
1207 case WS_IPPROTO_TCP:
1208 *level = IPPROTO_TCP;
1209 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
1210 if ( ws_tcp_map[i][0] == *optname )
1212 *optname = ws_tcp_map[i][1];
1213 return 1;
1216 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
1217 break;
1218 case WS_IPPROTO_IP:
1219 *level = IPPROTO_IP;
1220 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
1221 if (ws_ip_map[i][0] == *optname )
1223 *optname = ws_ip_map[i][1];
1224 return 1;
1227 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
1228 break;
1229 case WS_IPPROTO_IPV6:
1230 *level = IPPROTO_IPV6;
1231 for(i=0; i<sizeof(ws_ipv6_map)/sizeof(ws_ipv6_map[0]); i++) {
1232 if (ws_ipv6_map[i][0] == *optname )
1234 *optname = ws_ipv6_map[i][1];
1235 return 1;
1238 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname);
1239 break;
1240 default: FIXME("Unimplemented or unknown socket level\n");
1242 return 0;
1245 /* ----------------------------------- Per-thread info (or per-process?) */
1247 static char *strdup_lower(const char *str)
1249 int i;
1250 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
1252 if (ret)
1254 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
1255 ret[i] = 0;
1257 else SetLastError(WSAENOBUFS);
1258 return ret;
1261 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
1262 * from an fd and return the value converted to milli seconds
1263 * or 0 if there is an infinite time out */
1264 static inline INT64 get_rcvsnd_timeo( int fd, BOOL is_recv)
1266 struct timeval tv;
1267 socklen_t len = sizeof(tv);
1268 int optname, res;
1270 if (is_recv)
1271 #ifdef SO_RCVTIMEO
1272 optname = SO_RCVTIMEO;
1273 #else
1274 return 0;
1275 #endif
1276 else
1277 #ifdef SO_SNDTIMEO
1278 optname = SO_SNDTIMEO;
1279 #else
1280 return 0;
1281 #endif
1283 res = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
1284 if (res < 0)
1285 return 0;
1286 return (UINT64)tv.tv_sec * 1000 + tv.tv_usec / 1000;
1289 /* utility: given an fd, will block until one of the events occurs */
1290 static inline int do_block( int fd, int events, int timeout )
1292 struct pollfd pfd;
1293 int ret;
1295 pfd.fd = fd;
1296 pfd.events = events;
1298 while ((ret = poll(&pfd, 1, timeout)) < 0)
1300 if (errno != EINTR)
1301 return -1;
1303 if( ret == 0 )
1304 return 0;
1305 return pfd.revents;
1308 static int
1309 convert_af_w2u(int windowsaf) {
1310 unsigned int i;
1312 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1313 if (ws_af_map[i][0] == windowsaf)
1314 return ws_af_map[i][1];
1315 FIXME("unhandled Windows address family %d\n", windowsaf);
1316 return -1;
1319 static int
1320 convert_af_u2w(int unixaf) {
1321 unsigned int i;
1323 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1324 if (ws_af_map[i][1] == unixaf)
1325 return ws_af_map[i][0];
1326 FIXME("unhandled UNIX address family %d\n", unixaf);
1327 return -1;
1330 static int
1331 convert_proto_w2u(int windowsproto) {
1332 unsigned int i;
1334 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1335 if (ws_proto_map[i][0] == windowsproto)
1336 return ws_proto_map[i][1];
1338 /* check for extended IPX */
1339 if (IS_IPX_PROTO(windowsproto))
1340 return windowsproto;
1342 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
1343 return -1;
1346 static int
1347 convert_proto_u2w(int unixproto) {
1348 unsigned int i;
1350 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1351 if (ws_proto_map[i][1] == unixproto)
1352 return ws_proto_map[i][0];
1354 /* if value is inside IPX range just return it - the kernel simply
1355 * echoes the value used in the socket() function */
1356 if (IS_IPX_PROTO(unixproto))
1357 return unixproto;
1359 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
1360 return -1;
1363 static int
1364 convert_socktype_w2u(int windowssocktype) {
1365 unsigned int i;
1367 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1368 if (ws_socktype_map[i][0] == windowssocktype)
1369 return ws_socktype_map[i][1];
1370 FIXME("unhandled Windows socket type %d\n", windowssocktype);
1371 return -1;
1374 static int
1375 convert_socktype_u2w(int unixsocktype) {
1376 unsigned int i;
1378 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1379 if (ws_socktype_map[i][1] == unixsocktype)
1380 return ws_socktype_map[i][0];
1381 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
1382 return -1;
1385 static int set_ipx_packettype(int sock, int ptype)
1387 #ifdef HAS_IPX
1388 int fd = get_sock_fd( sock, 0, NULL ), ret = 0;
1389 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", ptype, fd);
1391 if (fd == -1) return SOCKET_ERROR;
1393 /* We try to set the ipx type on ipx socket level. */
1394 #ifdef SOL_IPX
1395 if(setsockopt(fd, SOL_IPX, IPX_TYPE, &ptype, sizeof(ptype)) == -1)
1397 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
1398 ret = SOCKET_ERROR;
1400 #else
1402 struct ipx val;
1403 /* Should we retrieve val using a getsockopt call and then
1404 * set the modified one? */
1405 val.ipx_pt = ptype;
1406 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
1408 #endif
1409 release_sock_fd( sock, fd );
1410 return ret;
1411 #else
1412 WARN("IPX support is not enabled, can't set packet type\n");
1413 return SOCKET_ERROR;
1414 #endif
1417 /* ----------------------------------- API -----
1419 * Init / cleanup / error checking.
1422 /***********************************************************************
1423 * WSAStartup (WS2_32.115)
1425 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
1427 TRACE("verReq=%x\n", wVersionRequested);
1429 if (LOBYTE(wVersionRequested) < 1)
1430 return WSAVERNOTSUPPORTED;
1432 if (!lpWSAData) return WSAEINVAL;
1434 num_startup++;
1436 /* that's the whole of the negotiation for now */
1437 lpWSAData->wVersion = wVersionRequested;
1438 /* return winsock information */
1439 lpWSAData->wHighVersion = 0x0202;
1440 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
1441 strcpy(lpWSAData->szSystemStatus, "Running" );
1442 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
1443 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
1444 /* don't do anything with lpWSAData->lpVendorInfo */
1445 /* (some apps don't allocate the space for this field) */
1447 TRACE("succeeded starts: %d\n", num_startup);
1448 return 0;
1452 /***********************************************************************
1453 * WSACleanup (WS2_32.116)
1455 INT WINAPI WSACleanup(void)
1457 if (num_startup) {
1458 num_startup--;
1459 TRACE("pending cleanups: %d\n", num_startup);
1460 return 0;
1462 SetLastError(WSANOTINITIALISED);
1463 return SOCKET_ERROR;
1467 /***********************************************************************
1468 * WSAGetLastError (WS2_32.111)
1470 INT WINAPI WSAGetLastError(void)
1472 return GetLastError();
1475 /***********************************************************************
1476 * WSASetLastError (WS2_32.112)
1478 void WINAPI WSASetLastError(INT iError) {
1479 SetLastError(iError);
1482 static struct WS_hostent *check_buffer_he(int size)
1484 struct per_thread_data * ptb = get_per_thread_data();
1485 if (ptb->he_buffer)
1487 if (ptb->he_len >= size ) return ptb->he_buffer;
1488 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1490 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
1491 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
1492 return ptb->he_buffer;
1495 static struct WS_servent *check_buffer_se(int size)
1497 struct per_thread_data * ptb = get_per_thread_data();
1498 if (ptb->se_buffer)
1500 if (ptb->se_len >= size ) return ptb->se_buffer;
1501 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1503 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
1504 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
1505 return ptb->se_buffer;
1508 static struct WS_protoent *check_buffer_pe(int size)
1510 struct per_thread_data * ptb = get_per_thread_data();
1511 if (ptb->pe_buffer)
1513 if (ptb->pe_len >= size ) return ptb->pe_buffer;
1514 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1516 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
1517 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
1518 return ptb->pe_buffer;
1521 /* ----------------------------------- i/o APIs */
1523 static inline BOOL supported_pf(int pf)
1525 switch (pf)
1527 case WS_AF_INET:
1528 case WS_AF_INET6:
1529 return TRUE;
1530 #ifdef HAS_IPX
1531 case WS_AF_IPX:
1532 return TRUE;
1533 #endif
1534 #ifdef HAS_IRDA
1535 case WS_AF_IRDA:
1536 return TRUE;
1537 #endif
1538 default:
1539 return FALSE;
1543 static inline BOOL supported_protocol(int protocol)
1545 int i;
1546 for (i = 0; i < sizeof(valid_protocols) / sizeof(valid_protocols[0]); i++)
1547 if (protocol == valid_protocols[i])
1548 return TRUE;
1549 return FALSE;
1552 /**********************************************************************/
1554 /* Returns the length of the converted address if successful, 0 if it was too small to
1555 * start with.
1557 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
1558 union generic_unix_sockaddr *uaddr)
1560 unsigned int uaddrlen = 0;
1562 switch (wsaddr->sa_family)
1564 #ifdef HAS_IPX
1565 case WS_AF_IPX:
1567 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
1568 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
1570 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
1571 return 0;
1573 uaddrlen = sizeof(struct sockaddr_ipx);
1574 memset( uaddr, 0, uaddrlen );
1575 uipx->sipx_family=AF_IPX;
1576 uipx->sipx_port=wsipx->sa_socket;
1577 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1578 * in one go
1580 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
1581 #ifdef IPX_FRAME_NONE
1582 uipx->sipx_type=IPX_FRAME_NONE;
1583 #endif
1584 break;
1586 #endif
1587 case WS_AF_INET6: {
1588 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
1589 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
1591 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1592 * scope_id, one without.
1594 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
1595 uaddrlen = sizeof(struct sockaddr_in6);
1596 memset( uaddr, 0, uaddrlen );
1597 uin6->sin6_family = AF_INET6;
1598 uin6->sin6_port = win6->sin6_port;
1599 uin6->sin6_flowinfo = win6->sin6_flowinfo;
1600 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1601 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
1602 #endif
1603 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
1604 break;
1606 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
1607 return 0;
1609 case WS_AF_INET: {
1610 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
1611 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
1613 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
1614 return 0;
1615 uaddrlen = sizeof(struct sockaddr_in);
1616 memset( uaddr, 0, uaddrlen );
1617 uin->sin_family = AF_INET;
1618 uin->sin_port = win->sin_port;
1619 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
1620 break;
1622 #ifdef HAS_IRDA
1623 case WS_AF_IRDA: {
1624 struct sockaddr_irda *uin = (struct sockaddr_irda *)uaddr;
1625 const SOCKADDR_IRDA *win = (const SOCKADDR_IRDA *)wsaddr;
1627 if (wsaddrlen < sizeof(SOCKADDR_IRDA))
1628 return 0;
1629 uaddrlen = sizeof(struct sockaddr_irda);
1630 memset( uaddr, 0, uaddrlen );
1631 uin->sir_family = AF_IRDA;
1632 if (!strncmp( win->irdaServiceName, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1634 unsigned int lsap_sel = 0;
1636 sscanf( win->irdaServiceName, "LSAP-SEL%u", &lsap_sel );
1637 uin->sir_lsap_sel = lsap_sel;
1639 else
1641 uin->sir_lsap_sel = LSAP_ANY;
1642 memcpy( uin->sir_name, win->irdaServiceName, 25 );
1644 memcpy( &uin->sir_addr, win->irdaDeviceID, sizeof(uin->sir_addr) );
1645 break;
1647 #endif
1648 case WS_AF_UNSPEC: {
1649 /* Try to determine the needed space by the passed windows sockaddr space */
1650 switch (wsaddrlen) {
1651 default: /* likely an ipv4 address */
1652 case sizeof(struct WS_sockaddr_in):
1653 uaddrlen = sizeof(struct sockaddr_in);
1654 break;
1655 #ifdef HAS_IPX
1656 case sizeof(struct WS_sockaddr_ipx):
1657 uaddrlen = sizeof(struct sockaddr_ipx);
1658 break;
1659 #endif
1660 #ifdef HAS_IRDA
1661 case sizeof(SOCKADDR_IRDA):
1662 uaddrlen = sizeof(struct sockaddr_irda);
1663 break;
1664 #endif
1665 case sizeof(struct WS_sockaddr_in6):
1666 case sizeof(struct WS_sockaddr_in6_old):
1667 uaddrlen = sizeof(struct sockaddr_in6);
1668 break;
1670 memset( uaddr, 0, uaddrlen );
1671 break;
1673 default:
1674 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
1675 return 0;
1677 return uaddrlen;
1680 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
1682 switch (uaddr->sa_family)
1684 #ifdef HAS_IPX
1685 case AF_IPX:
1687 static const struct sockaddr_ipx emptyAddr;
1688 struct sockaddr_ipx *ipx = (struct sockaddr_ipx*) uaddr;
1689 return ipx->sipx_port
1690 || memcmp(&ipx->sipx_network, &emptyAddr.sipx_network, sizeof(emptyAddr.sipx_network))
1691 || memcmp(&ipx->sipx_node, &emptyAddr.sipx_node, sizeof(emptyAddr.sipx_node));
1693 #endif
1694 case AF_INET6:
1696 static const struct sockaddr_in6 emptyAddr;
1697 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
1698 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
1700 case AF_INET:
1702 static const struct sockaddr_in emptyAddr;
1703 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
1704 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
1706 case AF_UNSPEC:
1707 return FALSE;
1708 default:
1709 FIXME("unknown address family %d\n", uaddr->sa_family);
1710 return TRUE;
1714 /* Returns -1 if getsockname fails, 0 if not bound, 1 otherwise */
1715 static int is_fd_bound(int fd, union generic_unix_sockaddr *uaddr, socklen_t *uaddrlen)
1717 union generic_unix_sockaddr inaddr;
1718 socklen_t inlen;
1719 int res;
1721 if (!uaddr) uaddr = &inaddr;
1722 if (!uaddrlen) uaddrlen = &inlen;
1724 *uaddrlen = sizeof(inaddr);
1725 res = getsockname(fd, &uaddr->addr, uaddrlen);
1726 if (!res) res = is_sockaddr_bound(&uaddr->addr, *uaddrlen);
1727 return res;
1730 /* Returns 0 if successful, -1 if the buffer is too small */
1731 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
1733 int res;
1735 switch(uaddr->sa_family)
1737 #ifdef HAS_IPX
1738 case AF_IPX:
1740 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
1741 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
1743 res=-1;
1744 switch (*wsaddrlen) /* how much can we copy? */
1746 default:
1747 res=0; /* enough */
1748 *wsaddrlen = sizeof(*wsipx);
1749 wsipx->sa_socket=uipx->sipx_port;
1750 /* fall through */
1751 case 13:
1752 case 12:
1753 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
1754 /* fall through */
1755 case 11:
1756 case 10:
1757 case 9:
1758 case 8:
1759 case 7:
1760 case 6:
1761 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1762 /* fall through */
1763 case 5:
1764 case 4:
1765 case 3:
1766 case 2:
1767 wsipx->sa_family=WS_AF_IPX;
1768 /* fall through */
1769 case 1:
1770 case 0:
1771 /* way too small */
1772 break;
1775 break;
1776 #endif
1777 #ifdef HAS_IRDA
1778 case AF_IRDA: {
1779 const struct sockaddr_irda *uin = (const struct sockaddr_irda *)uaddr;
1780 SOCKADDR_IRDA *win = (SOCKADDR_IRDA *)wsaddr;
1782 if (*wsaddrlen < sizeof(SOCKADDR_IRDA))
1783 return -1;
1784 win->irdaAddressFamily = WS_AF_IRDA;
1785 memcpy( win->irdaDeviceID, &uin->sir_addr, sizeof(win->irdaDeviceID) );
1786 if (uin->sir_lsap_sel != LSAP_ANY)
1787 sprintf( win->irdaServiceName, "LSAP-SEL%u", uin->sir_lsap_sel );
1788 else
1789 memcpy( win->irdaServiceName, uin->sir_name,
1790 sizeof(win->irdaServiceName) );
1791 return 0;
1793 #endif
1794 case AF_INET6: {
1795 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1796 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1798 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1799 return -1;
1800 win6old->sin6_family = WS_AF_INET6;
1801 win6old->sin6_port = uin6->sin6_port;
1802 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1803 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1804 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1805 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1806 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1807 win6->sin6_scope_id = uin6->sin6_scope_id;
1808 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1810 else
1811 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1812 #else
1813 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1814 #endif
1815 return 0;
1817 case AF_INET: {
1818 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1819 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1821 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1822 return -1;
1823 win->sin_family = WS_AF_INET;
1824 win->sin_port = uin->sin_port;
1825 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1826 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1827 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1828 return 0;
1830 case AF_UNSPEC: {
1831 memset(wsaddr,0,*wsaddrlen);
1832 return 0;
1834 default:
1835 FIXME("Unknown address family %d\n", uaddr->sa_family);
1836 return -1;
1838 return res;
1841 static INT WS_DuplicateSocket(BOOL unicode, SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo)
1843 HANDLE hProcess;
1844 int size;
1845 WSAPROTOCOL_INFOW infow;
1847 TRACE("(unicode %d, socket %04lx, processid %x, buffer %p)\n",
1848 unicode, s, dwProcessId, lpProtocolInfo);
1850 if (!ws_protocol_info(s, unicode, &infow, &size))
1851 return SOCKET_ERROR;
1853 if (!(hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId)))
1855 SetLastError(WSAEINVAL);
1856 return SOCKET_ERROR;
1859 if (!lpProtocolInfo)
1861 CloseHandle(hProcess);
1862 SetLastError(WSAEFAULT);
1863 return SOCKET_ERROR;
1866 /* I don't know what the real Windoze does next, this is a hack */
1867 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
1868 * the target use the global duplicate, or we could copy a reference to us to the structure
1869 * and let the target duplicate it from us, but let's do it as simple as possible */
1870 memcpy(lpProtocolInfo, &infow, size);
1871 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
1872 hProcess, (LPHANDLE)&lpProtocolInfo->dwServiceFlags3,
1873 0, FALSE, DUPLICATE_SAME_ACCESS);
1874 CloseHandle(hProcess);
1875 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
1876 return 0;
1879 /*****************************************************************************
1880 * WS_EnterSingleProtocolW [internal]
1882 * enters the protocol information of one given protocol into the given
1883 * buffer.
1885 * RETURNS
1886 * TRUE if a protocol was entered into the buffer.
1888 * BUGS
1889 * - only implemented for IPX, SPX, SPXII, TCP, UDP
1890 * - there is no check that the operating system supports the returned
1891 * protocols
1893 static BOOL WS_EnterSingleProtocolW( INT protocol, WSAPROTOCOL_INFOW* info )
1895 memset( info, 0, sizeof(WSAPROTOCOL_INFOW) );
1896 info->iProtocol = protocol;
1898 switch (protocol)
1900 case WS_IPPROTO_TCP:
1901 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_EXPEDITED_DATA |
1902 XP1_GRACEFUL_CLOSE | XP1_GUARANTEED_ORDER |
1903 XP1_GUARANTEED_DELIVERY;
1904 info->ProviderId = ProviderIdIP;
1905 info->dwCatalogEntryId = 0x3e9;
1906 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1907 info->ProtocolChain.ChainLen = 1;
1908 info->iVersion = 2;
1909 info->iAddressFamily = WS_AF_INET;
1910 info->iMaxSockAddr = 0x10;
1911 info->iMinSockAddr = 0x10;
1912 info->iSocketType = WS_SOCK_STREAM;
1913 strcpyW( info->szProtocol, NameTcpW );
1914 break;
1916 case WS_IPPROTO_UDP:
1917 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_SUPPORT_BROADCAST |
1918 XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED |
1919 XP1_CONNECTIONLESS;
1920 info->ProviderId = ProviderIdIP;
1921 info->dwCatalogEntryId = 0x3ea;
1922 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1923 info->ProtocolChain.ChainLen = 1;
1924 info->iVersion = 2;
1925 info->iAddressFamily = WS_AF_INET;
1926 info->iMaxSockAddr = 0x10;
1927 info->iMinSockAddr = 0x10;
1928 info->iSocketType = WS_SOCK_DGRAM;
1929 info->dwMessageSize = 0xffbb;
1930 strcpyW( info->szProtocol, NameUdpW );
1931 break;
1933 case WS_NSPROTO_IPX:
1934 info->dwServiceFlags1 = XP1_PARTIAL_MESSAGE | XP1_SUPPORT_BROADCAST |
1935 XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED |
1936 XP1_CONNECTIONLESS;
1937 info->ProviderId = ProviderIdIPX;
1938 info->dwCatalogEntryId = 0x406;
1939 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1940 info->ProtocolChain.ChainLen = 1;
1941 info->iVersion = 2;
1942 info->iAddressFamily = WS_AF_IPX;
1943 info->iMaxSockAddr = 0x10;
1944 info->iMinSockAddr = 0x0e;
1945 info->iSocketType = WS_SOCK_DGRAM;
1946 info->iProtocolMaxOffset = 0xff;
1947 info->dwMessageSize = 0x240;
1948 strcpyW( info->szProtocol, NameIpxW );
1949 break;
1951 case WS_NSPROTO_SPX:
1952 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_PSEUDO_STREAM |
1953 XP1_MESSAGE_ORIENTED | XP1_GUARANTEED_ORDER |
1954 XP1_GUARANTEED_DELIVERY;
1955 info->ProviderId = ProviderIdSPX;
1956 info->dwCatalogEntryId = 0x407;
1957 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1958 info->ProtocolChain.ChainLen = 1;
1959 info->iVersion = 2;
1960 info->iAddressFamily = WS_AF_IPX;
1961 info->iMaxSockAddr = 0x10;
1962 info->iMinSockAddr = 0x0e;
1963 info->iSocketType = WS_SOCK_SEQPACKET;
1964 info->dwMessageSize = 0xffffffff;
1965 strcpyW( info->szProtocol, NameSpxW );
1966 break;
1968 case WS_NSPROTO_SPXII:
1969 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_GRACEFUL_CLOSE |
1970 XP1_PSEUDO_STREAM | XP1_MESSAGE_ORIENTED |
1971 XP1_GUARANTEED_ORDER | XP1_GUARANTEED_DELIVERY;
1972 info->ProviderId = ProviderIdSPX;
1973 info->dwCatalogEntryId = 0x409;
1974 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1975 info->ProtocolChain.ChainLen = 1;
1976 info->iVersion = 2;
1977 info->iAddressFamily = WS_AF_IPX;
1978 info->iMaxSockAddr = 0x10;
1979 info->iMinSockAddr = 0x0e;
1980 info->iSocketType = WS_SOCK_SEQPACKET;
1981 info->dwMessageSize = 0xffffffff;
1982 strcpyW( info->szProtocol, NameSpxIIW );
1983 break;
1985 default:
1986 FIXME("unknown Protocol <0x%08x>\n", protocol);
1987 return FALSE;
1989 return TRUE;
1992 /*****************************************************************************
1993 * WS_EnterSingleProtocolA [internal]
1995 * see function WS_EnterSingleProtocolW
1998 static BOOL WS_EnterSingleProtocolA( INT protocol, WSAPROTOCOL_INFOA* info )
2000 WSAPROTOCOL_INFOW infow;
2001 INT ret;
2002 memset( info, 0, sizeof(WSAPROTOCOL_INFOA) );
2004 ret = WS_EnterSingleProtocolW( protocol, &infow );
2005 if (ret)
2007 /* convert the structure from W to A */
2008 memcpy( info, &infow, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
2009 WideCharToMultiByte( CP_ACP, 0, infow.szProtocol, -1,
2010 info->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL );
2013 return ret;
2016 static INT WS_EnumProtocols( BOOL unicode, const INT *protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
2018 INT i = 0, items = 0;
2019 DWORD size = 0;
2020 union _info
2022 LPWSAPROTOCOL_INFOA a;
2023 LPWSAPROTOCOL_INFOW w;
2024 } info;
2025 info.w = buffer;
2027 if (!protocols) protocols = valid_protocols;
2029 while (protocols[i])
2031 if(supported_protocol(protocols[i++]))
2032 items++;
2035 size = items * (unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA));
2037 TRACE("unicode %d, protocols %p, buffer %p, length %p %d, items %d, required %d\n",
2038 unicode, protocols, buffer, len, len ? *len : 0, items, size);
2040 if (*len < size || !buffer)
2042 *len = size;
2043 SetLastError(WSAENOBUFS);
2044 return SOCKET_ERROR;
2047 for (i = items = 0; protocols[i]; i++)
2049 if (!supported_protocol(protocols[i])) continue;
2050 if (unicode)
2052 if (WS_EnterSingleProtocolW( protocols[i], &info.w[items] ))
2053 items++;
2055 else
2057 if (WS_EnterSingleProtocolA( protocols[i], &info.a[items] ))
2058 items++;
2061 return items;
2064 static BOOL ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size)
2066 NTSTATUS status;
2068 *size = unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA);
2069 memset(buffer, 0, *size);
2071 SERVER_START_REQ( get_socket_info )
2073 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
2074 status = wine_server_call( req );
2075 if (!status)
2077 buffer->iAddressFamily = convert_af_u2w(reply->family);
2078 buffer->iSocketType = convert_socktype_u2w(reply->type);
2079 buffer->iProtocol = convert_proto_u2w(reply->protocol);
2082 SERVER_END_REQ;
2084 if (status)
2086 unsigned int err = NtStatusToWSAError( status );
2087 SetLastError( err == WSAEBADF ? WSAENOTSOCK : err );
2088 return FALSE;
2091 if (unicode)
2092 WS_EnterSingleProtocolW( buffer->iProtocol, buffer);
2093 else
2094 WS_EnterSingleProtocolA( buffer->iProtocol, (WSAPROTOCOL_INFOA *)buffer);
2096 return TRUE;
2099 /**************************************************************************
2100 * Functions for handling overlapped I/O
2101 **************************************************************************/
2103 /* user APC called upon async completion */
2104 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
2106 struct ws2_async *wsa = arg;
2108 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
2109 iosb->Information, wsa->user_overlapped,
2110 wsa->flags );
2111 release_async_io( &wsa->io );
2114 /***********************************************************************
2115 * WS2_recv (INTERNAL)
2117 * Workhorse for both synchronous and asynchronous recv() operations.
2119 static int WS2_recv( int fd, struct ws2_async *wsa, int flags )
2121 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2122 char pktbuf[512];
2123 #endif
2124 struct msghdr hdr;
2125 union generic_unix_sockaddr unix_sockaddr;
2126 int n;
2128 hdr.msg_name = NULL;
2130 if (wsa->addr)
2132 hdr.msg_namelen = sizeof(unix_sockaddr);
2133 hdr.msg_name = &unix_sockaddr;
2135 else
2136 hdr.msg_namelen = 0;
2138 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
2139 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
2140 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2141 hdr.msg_accrights = NULL;
2142 hdr.msg_accrightslen = 0;
2143 #else
2144 hdr.msg_control = pktbuf;
2145 hdr.msg_controllen = sizeof(pktbuf);
2146 hdr.msg_flags = 0;
2147 #endif
2149 while ((n = recvmsg(fd, &hdr, flags)) == -1)
2151 if (errno != EINTR)
2152 return -1;
2155 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2156 if (wsa->control)
2158 ERR("Message control headers cannot be properly supported on this system.\n");
2159 wsa->control->len = 0;
2161 #else
2162 if (wsa->control && !convert_control_headers(&hdr, wsa->control))
2164 WARN("Application passed insufficient room for control headers.\n");
2165 *wsa->lpFlags |= WS_MSG_CTRUNC;
2166 errno = EMSGSIZE;
2167 return -1;
2169 #endif
2171 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
2172 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
2174 * quoting linux 2.6 net/ipv4/tcp.c:
2175 * "According to UNIX98, msg_name/msg_namelen are ignored
2176 * on connected socket. I was just happy when found this 8) --ANK"
2178 * likewise MSDN says that lpFrom and lpFromlen are ignored for
2179 * connection-oriented sockets, so don't try to update lpFrom.
2181 if (wsa->addr && hdr.msg_namelen)
2182 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
2184 return n;
2187 /***********************************************************************
2188 * WS2_async_recv (INTERNAL)
2190 * Handler for overlapped recv() operations.
2192 static NTSTATUS WS2_async_recv( void *user, IO_STATUS_BLOCK *iosb,
2193 NTSTATUS status, void **apc, void **arg )
2195 struct ws2_async *wsa = user;
2196 int result = 0, fd;
2198 switch (status)
2200 case STATUS_ALERTED:
2201 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
2202 break;
2204 result = WS2_recv( fd, wsa, convert_flags(wsa->flags) );
2205 wine_server_release_fd( wsa->hSocket, fd );
2206 if (result >= 0)
2208 status = STATUS_SUCCESS;
2209 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
2211 else
2213 if (errno == EAGAIN)
2215 status = STATUS_PENDING;
2216 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
2218 else
2220 result = 0;
2221 status = wsaErrStatus();
2224 break;
2226 if (status != STATUS_PENDING)
2228 iosb->u.Status = status;
2229 iosb->Information = result;
2230 if (wsa->completion_func)
2232 *apc = ws2_async_apc;
2233 *arg = wsa;
2235 else
2236 release_async_io( &wsa->io );
2238 return status;
2241 /***********************************************************************
2242 * WS2_async_accept_recv (INTERNAL)
2244 * This function is used to finish the read part of an accept request. It is
2245 * needed to place the completion on the correct socket (listener).
2247 static NTSTATUS WS2_async_accept_recv( void *user, IO_STATUS_BLOCK *iosb,
2248 NTSTATUS status, void **apc, void **arg )
2250 void *junk;
2251 struct ws2_accept_async *wsa = user;
2253 status = WS2_async_recv( wsa->read, iosb, status, &junk, &junk );
2254 if (status == STATUS_PENDING)
2255 return status;
2257 if (wsa->cvalue)
2258 WS_AddCompletion( HANDLE2SOCKET(wsa->listen_socket), wsa->cvalue, iosb->u.Status, iosb->Information );
2260 release_async_io( &wsa->io );
2261 return status;
2264 /***********************************************************************
2265 * WS2_async_accept (INTERNAL)
2267 * This is the function called to satisfy the AcceptEx callback
2269 static NTSTATUS WS2_async_accept( void *user, IO_STATUS_BLOCK *iosb,
2270 NTSTATUS status, void **apc, void **arg )
2272 struct ws2_accept_async *wsa = user;
2273 int len;
2274 char *addr;
2276 TRACE("status: 0x%x listen: %p, accept: %p\n", status, wsa->listen_socket, wsa->accept_socket);
2278 if (status == STATUS_ALERTED)
2280 SERVER_START_REQ( accept_into_socket )
2282 req->lhandle = wine_server_obj_handle( wsa->listen_socket );
2283 req->ahandle = wine_server_obj_handle( wsa->accept_socket );
2284 status = wine_server_call( req );
2286 SERVER_END_REQ;
2288 if (status == STATUS_CANT_WAIT)
2289 return STATUS_PENDING;
2291 if (status == STATUS_INVALID_HANDLE)
2293 FIXME("AcceptEx accepting socket closed but request was not cancelled\n");
2294 status = STATUS_CANCELLED;
2297 else if (status == STATUS_HANDLES_CLOSED)
2298 status = STATUS_CANCELLED; /* strange windows behavior */
2300 if (status != STATUS_SUCCESS)
2301 goto finish;
2303 /* WS2 Spec says size param is extra 16 bytes long...what do we put in it? */
2304 addr = ((char *)wsa->buf) + wsa->data_len;
2305 len = wsa->local_len - sizeof(int);
2306 WS_getsockname(HANDLE2SOCKET(wsa->accept_socket),
2307 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
2308 *(int *)addr = len;
2310 addr += wsa->local_len;
2311 len = wsa->remote_len - sizeof(int);
2312 WS_getpeername(HANDLE2SOCKET(wsa->accept_socket),
2313 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
2314 *(int *)addr = len;
2316 if (!wsa->read)
2317 goto finish;
2319 SERVER_START_REQ( register_async )
2321 req->type = ASYNC_TYPE_READ;
2322 req->async.handle = wine_server_obj_handle( wsa->accept_socket );
2323 req->async.event = wine_server_obj_handle( wsa->user_overlapped->hEvent );
2324 req->async.callback = wine_server_client_ptr( WS2_async_accept_recv );
2325 req->async.iosb = wine_server_client_ptr( iosb );
2326 req->async.arg = wine_server_client_ptr( wsa );
2327 status = wine_server_call( req );
2329 SERVER_END_REQ;
2331 if (status != STATUS_PENDING)
2332 goto finish;
2334 /* The APC has finished but no completion should be sent for the operation yet, additional processing
2335 * needs to be performed by WS2_async_accept_recv() first. */
2336 return STATUS_MORE_PROCESSING_REQUIRED;
2338 finish:
2339 iosb->u.Status = status;
2340 iosb->Information = 0;
2342 if (wsa->read) release_async_io( &wsa->read->io );
2343 release_async_io( &wsa->io );
2344 return status;
2347 /***********************************************************************
2348 * WS2_send (INTERNAL)
2350 * Workhorse for both synchronous and asynchronous send() operations.
2352 static int WS2_send( int fd, struct ws2_async *wsa, int flags )
2354 struct msghdr hdr;
2355 union generic_unix_sockaddr unix_addr;
2356 int n, ret;
2358 hdr.msg_name = NULL;
2359 hdr.msg_namelen = 0;
2361 if (wsa->addr)
2363 hdr.msg_name = &unix_addr;
2364 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
2365 if ( !hdr.msg_namelen )
2367 errno = EFAULT;
2368 return -1;
2371 #if defined(HAS_IPX) && defined(SOL_IPX)
2372 if(wsa->addr->sa_family == WS_AF_IPX)
2374 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
2375 int val=0;
2376 socklen_t len = sizeof(int);
2378 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
2379 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
2380 * the packet type and then we can retrieve it using getsockopt. After that we can set the
2381 * ipx type in the sockaddr_opx structure with the stored value.
2383 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
2384 uipx->sipx_type = val;
2386 #endif
2389 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
2390 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
2391 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2392 hdr.msg_accrights = NULL;
2393 hdr.msg_accrightslen = 0;
2394 #else
2395 hdr.msg_control = NULL;
2396 hdr.msg_controllen = 0;
2397 hdr.msg_flags = 0;
2398 #endif
2400 while ((ret = sendmsg(fd, &hdr, flags)) == -1)
2402 if (errno != EINTR)
2403 return -1;
2406 n = ret;
2407 while (wsa->first_iovec < wsa->n_iovecs && wsa->iovec[wsa->first_iovec].iov_len <= n)
2408 n -= wsa->iovec[wsa->first_iovec++].iov_len;
2409 if (wsa->first_iovec < wsa->n_iovecs)
2411 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
2412 wsa->iovec[wsa->first_iovec].iov_len -= n;
2414 return ret;
2417 /***********************************************************************
2418 * WS2_async_send (INTERNAL)
2420 * Handler for overlapped send() operations.
2422 static NTSTATUS WS2_async_send( void *user, IO_STATUS_BLOCK *iosb,
2423 NTSTATUS status, void **apc, void **arg )
2425 struct ws2_async *wsa = user;
2426 int result = 0, fd;
2428 switch (status)
2430 case STATUS_ALERTED:
2431 if ( wsa->n_iovecs <= wsa->first_iovec )
2433 /* Nothing to do */
2434 status = STATUS_SUCCESS;
2435 break;
2437 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
2438 break;
2440 /* check to see if the data is ready (non-blocking) */
2441 result = WS2_send( fd, wsa, convert_flags(wsa->flags) );
2442 wine_server_release_fd( wsa->hSocket, fd );
2444 if (result >= 0)
2446 if (wsa->first_iovec < wsa->n_iovecs)
2447 status = STATUS_PENDING;
2448 else
2449 status = STATUS_SUCCESS;
2451 iosb->Information += result;
2453 else if (errno == EAGAIN)
2455 status = STATUS_PENDING;
2457 else
2459 status = wsaErrStatus();
2461 break;
2463 if (status != STATUS_PENDING)
2465 iosb->u.Status = status;
2466 if (wsa->completion_func)
2468 *apc = ws2_async_apc;
2469 *arg = wsa;
2471 else
2472 release_async_io( &wsa->io );
2474 return status;
2477 /***********************************************************************
2478 * WS2_async_shutdown (INTERNAL)
2480 * Handler for shutdown() operations on overlapped sockets.
2482 static NTSTATUS WS2_async_shutdown( void *user, IO_STATUS_BLOCK *iosb,
2483 NTSTATUS status, void **apc, void **arg )
2485 struct ws2_async_shutdown *wsa = user;
2486 int fd, err = 1;
2488 switch (status)
2490 case STATUS_ALERTED:
2491 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
2492 break;
2494 switch ( wsa->type )
2496 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
2497 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
2499 status = err ? wsaErrStatus() : STATUS_SUCCESS;
2500 wine_server_release_fd( wsa->hSocket, fd );
2501 break;
2503 iosb->u.Status = status;
2504 iosb->Information = 0;
2505 release_async_io( &wsa->io );
2506 return status;
2509 /***********************************************************************
2510 * WS2_register_async_shutdown (INTERNAL)
2512 * Helper function for WS_shutdown() on overlapped sockets.
2514 static int WS2_register_async_shutdown( SOCKET s, int type )
2516 struct ws2_async_shutdown *wsa;
2517 NTSTATUS status;
2519 TRACE("socket %04lx type %d\n", s, type);
2521 wsa = (struct ws2_async_shutdown *)alloc_async_io( sizeof(*wsa) );
2522 if ( !wsa )
2523 return WSAEFAULT;
2525 wsa->hSocket = SOCKET2HANDLE(s);
2526 wsa->type = type;
2528 SERVER_START_REQ( register_async )
2530 req->type = type;
2531 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2532 req->async.callback = wine_server_client_ptr( WS2_async_shutdown );
2533 req->async.iosb = wine_server_client_ptr( &wsa->iosb );
2534 req->async.arg = wine_server_client_ptr( wsa );
2535 req->async.cvalue = 0;
2536 status = wine_server_call( req );
2538 SERVER_END_REQ;
2540 if (status != STATUS_PENDING)
2542 HeapFree( GetProcessHeap(), 0, wsa );
2543 return NtStatusToWSAError( status );
2545 return 0;
2548 /***********************************************************************
2549 * accept (WS2_32.1)
2551 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr, int *addrlen32)
2553 NTSTATUS status;
2554 SOCKET as;
2555 BOOL is_blocking;
2557 TRACE("socket %04lx\n", s );
2558 status = _is_blocking(s, &is_blocking);
2559 if (status)
2561 set_error(status);
2562 return INVALID_SOCKET;
2565 do {
2566 /* try accepting first (if there is a deferred connection) */
2567 SERVER_START_REQ( accept_socket )
2569 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
2570 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
2571 req->attributes = OBJ_INHERIT;
2572 status = wine_server_call( req );
2573 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
2575 SERVER_END_REQ;
2576 if (!status)
2578 if (addr && WS_getpeername(as, addr, addrlen32))
2580 WS_closesocket(as);
2581 return SOCKET_ERROR;
2583 TRACE("\taccepted %04lx\n", as);
2584 return as;
2586 if (is_blocking && status == STATUS_CANT_WAIT)
2588 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2589 /* block here */
2590 do_block(fd, POLLIN, -1);
2591 _sync_sock_state(s); /* let wineserver notice connection */
2592 release_sock_fd( s, fd );
2594 } while (is_blocking && status == STATUS_CANT_WAIT);
2596 set_error(status);
2597 return INVALID_SOCKET;
2600 /***********************************************************************
2601 * AcceptEx
2603 static BOOL WINAPI WS2_AcceptEx(SOCKET listener, SOCKET acceptor, PVOID dest, DWORD dest_len,
2604 DWORD local_addr_len, DWORD rem_addr_len, LPDWORD received,
2605 LPOVERLAPPED overlapped)
2607 DWORD status;
2608 struct ws2_accept_async *wsa;
2609 int fd;
2611 TRACE("(%04lx, %04lx, %p, %d, %d, %d, %p, %p)\n", listener, acceptor, dest, dest_len, local_addr_len,
2612 rem_addr_len, received, overlapped);
2614 if (!dest)
2616 SetLastError(WSAEINVAL);
2617 return FALSE;
2620 if (!overlapped)
2622 SetLastError(WSA_INVALID_PARAMETER);
2623 return FALSE;
2626 if (!rem_addr_len)
2628 SetLastError(WSAEFAULT);
2629 return FALSE;
2632 fd = get_sock_fd( listener, FILE_READ_DATA, NULL );
2633 if (fd == -1)
2635 SetLastError(WSAENOTSOCK);
2636 return FALSE;
2638 release_sock_fd( listener, fd );
2640 fd = get_sock_fd( acceptor, FILE_READ_DATA, NULL );
2641 if (fd == -1)
2643 SetLastError(WSAENOTSOCK);
2644 return FALSE;
2646 release_sock_fd( acceptor, fd );
2648 wsa = (struct ws2_accept_async *)alloc_async_io( sizeof(*wsa) );
2649 if(!wsa)
2651 SetLastError(WSAEFAULT);
2652 return FALSE;
2655 wsa->listen_socket = SOCKET2HANDLE(listener);
2656 wsa->accept_socket = SOCKET2HANDLE(acceptor);
2657 wsa->user_overlapped = overlapped;
2658 wsa->cvalue = !((ULONG_PTR)overlapped->hEvent & 1) ? (ULONG_PTR)overlapped : 0;
2659 wsa->buf = dest;
2660 wsa->data_len = dest_len;
2661 wsa->local_len = local_addr_len;
2662 wsa->remote_len = rem_addr_len;
2663 wsa->read = NULL;
2665 if (wsa->data_len)
2667 /* set up a read request if we need it */
2668 wsa->read = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[1]) );
2669 if (!wsa->read)
2671 HeapFree( GetProcessHeap(), 0, wsa );
2672 SetLastError(WSAEFAULT);
2673 return FALSE;
2676 wsa->read->hSocket = wsa->accept_socket;
2677 wsa->read->flags = 0;
2678 wsa->read->lpFlags = &wsa->read->flags;
2679 wsa->read->addr = NULL;
2680 wsa->read->addrlen.ptr = NULL;
2681 wsa->read->control = NULL;
2682 wsa->read->n_iovecs = 1;
2683 wsa->read->first_iovec = 0;
2684 wsa->read->completion_func = NULL;
2685 wsa->read->iovec[0].iov_base = wsa->buf;
2686 wsa->read->iovec[0].iov_len = wsa->data_len;
2689 SERVER_START_REQ( register_async )
2691 req->type = ASYNC_TYPE_READ;
2692 req->async.handle = wine_server_obj_handle( SOCKET2HANDLE(listener) );
2693 req->async.event = wine_server_obj_handle( overlapped->hEvent );
2694 req->async.callback = wine_server_client_ptr( WS2_async_accept );
2695 req->async.iosb = wine_server_client_ptr( overlapped );
2696 req->async.arg = wine_server_client_ptr( wsa );
2697 req->async.cvalue = wsa->cvalue;
2698 status = wine_server_call( req );
2700 SERVER_END_REQ;
2702 if(status != STATUS_PENDING)
2704 HeapFree( GetProcessHeap(), 0, wsa->read );
2705 HeapFree( GetProcessHeap(), 0, wsa );
2708 SetLastError( NtStatusToWSAError(status) );
2709 return FALSE;
2712 /***********************************************************************
2713 * GetAcceptExSockaddrs
2715 static void WINAPI WS2_GetAcceptExSockaddrs(PVOID buffer, DWORD data_size, DWORD local_size, DWORD remote_size,
2716 struct WS_sockaddr **local_addr, LPINT local_addr_len,
2717 struct WS_sockaddr **remote_addr, LPINT remote_addr_len)
2719 char *cbuf = buffer;
2720 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer, data_size, local_size, remote_size, local_addr,
2721 local_addr_len, remote_addr, remote_addr_len );
2722 cbuf += data_size;
2724 *local_addr_len = *(int *) cbuf;
2725 *local_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2727 cbuf += local_size;
2729 *remote_addr_len = *(int *) cbuf;
2730 *remote_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2733 /***********************************************************************
2734 * WSASendMsg
2736 int WINAPI WSASendMsg( SOCKET s, LPWSAMSG msg, DWORD dwFlags, LPDWORD lpNumberOfBytesSent,
2737 LPWSAOVERLAPPED lpOverlapped,
2738 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
2740 if (!msg)
2742 SetLastError( WSAEFAULT );
2743 return SOCKET_ERROR;
2746 return WS2_sendto( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesSent,
2747 dwFlags, msg->name, msg->namelen,
2748 lpOverlapped, lpCompletionRoutine );
2751 /***********************************************************************
2752 * WSARecvMsg
2754 * Perform a receive operation that is capable of returning message
2755 * control headers. It is important to note that the WSAMSG parameter
2756 * must remain valid throughout the operation, even when an overlapped
2757 * receive is performed.
2759 static int WINAPI WS2_WSARecvMsg( SOCKET s, LPWSAMSG msg, LPDWORD lpNumberOfBytesRecvd,
2760 LPWSAOVERLAPPED lpOverlapped,
2761 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2763 if (!msg)
2765 SetLastError( WSAEFAULT );
2766 return SOCKET_ERROR;
2769 return WS2_recv_base( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesRecvd,
2770 &msg->dwFlags, msg->name, &msg->namelen,
2771 lpOverlapped, lpCompletionRoutine, &msg->Control );
2774 /***********************************************************************
2775 * interface_bind (INTERNAL)
2777 * Take bind() calls on any name corresponding to a local network adapter and restrict the given socket to
2778 * operating only on the specified interface. This restriction consists of two components:
2779 * 1) An outgoing packet restriction suggesting the egress interface for all packets.
2780 * 2) An incoming packet restriction dropping packets not meant for the interface.
2781 * If the function succeeds in placing these restrictions (returns TRUE) then the name for the bind() may
2782 * safely be changed to INADDR_ANY, permitting the transmission and receipt of broadcast packets on the
2783 * socket. This behavior is only relevant to UDP sockets and is needed for applications that expect to be able
2784 * to receive broadcast packets on a socket that is bound to a specific network interface.
2786 static BOOL interface_bind( SOCKET s, int fd, struct sockaddr *addr )
2788 struct sockaddr_in *in_sock = (struct sockaddr_in *) addr;
2789 in_addr_t bind_addr = in_sock->sin_addr.s_addr;
2790 PIP_ADAPTER_INFO adapters = NULL, adapter;
2791 BOOL ret = FALSE;
2792 DWORD adap_size;
2793 int enable = 1;
2795 if (bind_addr == htonl(INADDR_ANY) || bind_addr == htonl(INADDR_LOOPBACK))
2796 return FALSE; /* Not binding to a network adapter, special interface binding unnecessary. */
2797 if (_get_fd_type(fd) != SOCK_DGRAM)
2798 return FALSE; /* Special interface binding is only necessary for UDP datagrams. */
2799 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
2800 goto cleanup;
2801 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
2802 if (adapters == NULL || GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
2803 goto cleanup;
2804 /* Search the IPv4 adapter list for the appropriate binding interface */
2805 for (adapter = adapters; adapter != NULL; adapter = adapter->Next)
2807 in_addr_t adapter_addr = (in_addr_t) inet_addr(adapter->IpAddressList.IpAddress.String);
2809 if (bind_addr == adapter_addr)
2811 #if defined(IP_BOUND_IF)
2812 /* IP_BOUND_IF sets both the incoming and outgoing restriction at once */
2813 if (setsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &adapter->Index, sizeof(adapter->Index)) != 0)
2814 goto cleanup;
2815 ret = TRUE;
2816 #elif defined(LINUX_BOUND_IF)
2817 in_addr_t ifindex = (in_addr_t) htonl(adapter->Index);
2818 struct interface_filter specific_interface_filter;
2819 struct sock_fprog filter_prog;
2821 if (setsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex, sizeof(ifindex)) != 0)
2822 goto cleanup; /* Failed to suggest egress interface */
2823 specific_interface_filter = generic_interface_filter;
2824 specific_interface_filter.iface_rule.k = adapter->Index;
2825 specific_interface_filter.ip_rule.k = htonl(adapter_addr);
2826 filter_prog.len = sizeof(generic_interface_filter)/sizeof(struct sock_filter);
2827 filter_prog.filter = (struct sock_filter *) &specific_interface_filter;
2828 if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog, sizeof(filter_prog)) != 0)
2829 goto cleanup; /* Failed to specify incoming packet filter */
2830 ret = TRUE;
2831 #else
2832 FIXME("Broadcast packets on interface-bound sockets are not currently supported on this platform, "
2833 "receiving broadcast packets will not work on socket %04lx.\n", s);
2834 #endif
2835 break;
2838 /* Will soon be switching to INADDR_ANY: permit address reuse */
2839 if (ret && setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) == 0)
2840 TRACE("Socket %04lx bound to interface index %d\n", s, adapter->Index);
2841 else
2842 ret = FALSE;
2844 cleanup:
2845 if(!ret)
2846 ERR("Failed to bind to interface, receiving broadcast packets will not work on socket %04lx.\n", s);
2847 HeapFree(GetProcessHeap(), 0, adapters);
2848 return ret;
2851 /***********************************************************************
2852 * bind (WS2_32.2)
2854 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
2856 int fd = get_sock_fd( s, 0, NULL );
2857 int res = SOCKET_ERROR;
2859 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2861 if (fd != -1)
2863 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
2865 SetLastError(WSAEAFNOSUPPORT);
2867 else
2869 union generic_unix_sockaddr uaddr;
2870 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2871 if (!uaddrlen)
2873 SetLastError(WSAEFAULT);
2875 else
2877 #ifdef IPV6_V6ONLY
2878 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
2879 if (name->sa_family == WS_AF_INET6 &&
2880 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
2882 int enable = 1;
2883 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
2885 release_sock_fd( s, fd );
2886 SetLastError(WSAEAFNOSUPPORT);
2887 return SOCKET_ERROR;
2890 #endif
2891 if (name->sa_family == WS_AF_INET)
2893 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2894 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2896 /* Trying to bind to the default host interface, using
2897 * INADDR_ANY instead*/
2898 WARN("Trying to bind to magic IP address, using "
2899 "INADDR_ANY instead.\n");
2900 in4->sin_addr.s_addr = htonl(INADDR_ANY);
2902 else if (interface_bind(s, fd, &uaddr.addr))
2903 in4->sin_addr.s_addr = htonl(INADDR_ANY);
2905 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
2907 int loc_errno = errno;
2908 WARN("\tfailure - errno = %i\n", errno);
2909 errno = loc_errno;
2910 switch (errno)
2912 case EADDRNOTAVAIL:
2913 SetLastError(WSAEINVAL);
2914 break;
2915 case EADDRINUSE:
2917 int optval = 0;
2918 socklen_t optlen = sizeof(optval);
2919 /* Windows >= 2003 will return different results depending on
2920 * SO_REUSEADDR, WSAEACCES may be returned representing that
2921 * the socket hijacking protection prevented the bind */
2922 if (!getsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&optval, &optlen) && optval)
2924 SetLastError(WSAEACCES);
2925 break;
2927 /* fall through */
2929 default:
2930 SetLastError(wsaErrno());
2931 break;
2934 else
2936 res=0; /* success */
2940 release_sock_fd( s, fd );
2942 return res;
2945 /***********************************************************************
2946 * closesocket (WS2_32.3)
2948 int WINAPI WS_closesocket(SOCKET s)
2950 int res = SOCKET_ERROR, fd;
2951 if (num_startup)
2953 fd = get_sock_fd(s, FILE_READ_DATA, NULL);
2954 if (fd >= 0)
2956 release_sock_fd(s, fd);
2957 if (CloseHandle(SOCKET2HANDLE(s)))
2958 res = 0;
2960 else
2961 SetLastError(WSAENOTSOCK);
2963 else
2964 SetLastError(WSANOTINITIALISED);
2965 TRACE("(socket %04lx) -> %d\n", s, res);
2966 return res;
2969 static int do_connect(int fd, const struct WS_sockaddr* name, int namelen)
2971 union generic_unix_sockaddr uaddr;
2972 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2974 if (!uaddrlen)
2975 return WSAEFAULT;
2977 if (name->sa_family == WS_AF_INET)
2979 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2980 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2982 /* Trying to connect to magic replace-loopback address,
2983 * assuming we really want to connect to localhost */
2984 TRACE("Trying to connect to magic IP address, using "
2985 "INADDR_LOOPBACK instead.\n");
2986 in4->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
2990 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
2991 return 0;
2993 return wsaErrno();
2996 /***********************************************************************
2997 * connect (WS2_32.4)
2999 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
3001 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
3003 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
3005 if (fd != -1)
3007 NTSTATUS status;
3008 BOOL is_blocking;
3009 int ret = do_connect(fd, name, namelen);
3010 if (ret == 0)
3011 goto connect_success;
3013 if (ret == WSAEINPROGRESS)
3015 /* tell wineserver that a connection is in progress */
3016 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3017 FD_CONNECT,
3018 FD_WINE_CONNECTED|FD_WINE_LISTENING);
3019 status = _is_blocking( s, &is_blocking );
3020 if (status)
3022 release_sock_fd( s, fd );
3023 set_error( status );
3024 return SOCKET_ERROR;
3026 if (is_blocking)
3028 int result;
3029 /* block here */
3030 do_block(fd, POLLIN | POLLOUT, -1);
3031 _sync_sock_state(s); /* let wineserver notice connection */
3032 /* retrieve any error codes from it */
3033 result = _get_sock_error(s, FD_CONNECT_BIT);
3034 if (result)
3035 SetLastError(NtStatusToWSAError(result));
3036 else
3038 goto connect_success;
3041 else
3043 SetLastError(WSAEWOULDBLOCK);
3046 else
3048 SetLastError(ret);
3050 release_sock_fd( s, fd );
3052 return SOCKET_ERROR;
3054 connect_success:
3055 release_sock_fd( s, fd );
3056 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3057 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
3058 FD_CONNECT|FD_WINE_LISTENING);
3059 TRACE("\tconnected %04lx\n", s);
3060 return 0;
3063 /***********************************************************************
3064 * WSAConnect (WS2_32.30)
3066 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
3067 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
3068 LPQOS lpSQOS, LPQOS lpGQOS )
3070 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
3071 FIXME("unsupported parameters!\n");
3072 return WS_connect( s, name, namelen );
3075 /***********************************************************************
3076 * ConnectEx
3078 static BOOL WINAPI WS2_ConnectEx(SOCKET s, const struct WS_sockaddr* name, int namelen,
3079 PVOID sendBuf, DWORD sendBufLen, LPDWORD sent, LPOVERLAPPED ov)
3081 int fd, ret, status;
3083 if (!ov)
3085 SetLastError( ERROR_INVALID_PARAMETER );
3086 return FALSE;
3089 fd = get_sock_fd( s, FILE_READ_DATA, NULL );
3090 if (fd == -1)
3092 SetLastError( WSAENOTSOCK );
3093 return FALSE;
3096 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
3097 s, name, debugstr_sockaddr(name), namelen, sendBuf, sendBufLen, ov);
3099 ret = is_fd_bound(fd, NULL, NULL);
3100 if (ret <= 0)
3102 SetLastError(ret == -1 ? wsaErrno() : WSAEINVAL);
3103 release_sock_fd( s, fd );
3104 return FALSE;
3107 ret = do_connect(fd, name, namelen);
3108 if (ret == 0)
3110 WSABUF wsabuf;
3112 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3113 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
3114 FD_CONNECT|FD_WINE_LISTENING);
3116 wsabuf.len = sendBufLen;
3117 wsabuf.buf = (char*) sendBuf;
3119 /* WSASend takes care of completion if need be */
3120 if (WSASend(s, &wsabuf, sendBuf ? 1 : 0, sent, 0, ov, NULL) != SOCKET_ERROR)
3121 goto connection_success;
3123 else if (ret == WSAEINPROGRESS)
3125 struct ws2_async *wsa;
3126 ULONG_PTR cvalue = (((ULONG_PTR)ov->hEvent & 1) == 0) ? (ULONG_PTR)ov : 0;
3128 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3129 FD_CONNECT,
3130 FD_WINE_CONNECTED|FD_WINE_LISTENING);
3132 /* Indirectly call WSASend */
3133 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof( struct ws2_async, iovec[1] ))))
3135 SetLastError(WSAEFAULT);
3137 else
3139 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)ov;
3140 iosb->u.Status = STATUS_PENDING;
3141 iosb->Information = 0;
3143 wsa->hSocket = SOCKET2HANDLE(s);
3144 wsa->addr = NULL;
3145 wsa->addrlen.val = 0;
3146 wsa->flags = 0;
3147 wsa->lpFlags = &wsa->flags;
3148 wsa->control = NULL;
3149 wsa->n_iovecs = sendBuf ? 1 : 0;
3150 wsa->first_iovec = 0;
3151 wsa->completion_func = NULL;
3152 wsa->iovec[0].iov_base = sendBuf;
3153 wsa->iovec[0].iov_len = sendBufLen;
3155 SERVER_START_REQ( register_async )
3157 req->type = ASYNC_TYPE_WRITE;
3158 req->async.handle = wine_server_obj_handle( wsa->hSocket );
3159 req->async.callback = wine_server_client_ptr( WS2_async_send );
3160 req->async.iosb = wine_server_client_ptr( iosb );
3161 req->async.arg = wine_server_client_ptr( wsa );
3162 req->async.event = wine_server_obj_handle( ov->hEvent );
3163 req->async.cvalue = cvalue;
3164 status = wine_server_call( req );
3166 SERVER_END_REQ;
3168 if (status != STATUS_PENDING) HeapFree(GetProcessHeap(), 0, wsa);
3170 /* If the connect already failed */
3171 if (status == STATUS_PIPE_DISCONNECTED)
3172 status = _get_sock_error(s, FD_CONNECT_BIT);
3173 SetLastError( NtStatusToWSAError(status) );
3176 else
3178 SetLastError(ret);
3181 release_sock_fd( s, fd );
3182 return FALSE;
3184 connection_success:
3185 release_sock_fd( s, fd );
3186 return TRUE;
3190 /***********************************************************************
3191 * getpeername (WS2_32.5)
3193 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
3195 int fd;
3196 int res;
3198 TRACE("socket %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
3200 fd = get_sock_fd( s, 0, NULL );
3201 res = SOCKET_ERROR;
3203 if (fd != -1)
3205 union generic_unix_sockaddr uaddr;
3206 socklen_t uaddrlen = sizeof(uaddr);
3208 if (getpeername(fd, &uaddr.addr, &uaddrlen) == 0)
3210 if (!name || !namelen)
3211 SetLastError(WSAEFAULT);
3212 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3213 /* The buffer was too small */
3214 SetLastError(WSAEFAULT);
3215 else
3217 res = 0;
3218 TRACE("=> %s\n", debugstr_sockaddr(name));
3221 else
3222 SetLastError(wsaErrno());
3223 release_sock_fd( s, fd );
3225 return res;
3228 /* When binding to an UDP address with filter support the getsockname call on the socket
3229 * will always return 0.0.0.0 instead of the filtered interface address. This function
3230 * checks if the socket is interface-bound on UDP and return the correct address.
3231 * This is required because applications often do a bind() with port zero followed by a
3232 * getsockname() to retrieve the port and address acquired.
3234 static void interface_bind_check(int fd, struct sockaddr_in *addr)
3236 #if !defined(IP_BOUND_IF) && !defined(LINUX_BOUND_IF)
3237 return;
3238 #else
3239 int ifindex;
3240 socklen_t len;
3242 /* Check for IPv4, address 0.0.0.0 and UDP socket */
3243 if (addr->sin_family != AF_INET || addr->sin_addr.s_addr != 0)
3244 return;
3245 if (_get_fd_type(fd) != SOCK_DGRAM)
3246 return;
3248 ifindex = -1;
3249 len = sizeof(ifindex);
3250 #if defined(IP_BOUND_IF)
3251 getsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &ifindex, &len);
3252 #elif defined(LINUX_BOUND_IF)
3253 getsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex, &len);
3254 if (ifindex > 0) ifindex = ntohl(ifindex);
3255 #endif
3256 if (ifindex > 0)
3258 PIP_ADAPTER_INFO adapters, adapter;
3259 DWORD adap_size;
3261 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
3262 return;
3263 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
3264 if (adapters && GetAdaptersInfo(adapters, &adap_size) == NO_ERROR)
3266 /* Search the IPv4 adapter list for the appropriate bound interface */
3267 for (adapter = adapters; adapter != NULL; adapter = adapter->Next)
3269 in_addr_t adapter_addr;
3270 if (adapter->Index != ifindex) continue;
3272 adapter_addr = inet_addr(adapter->IpAddressList.IpAddress.String);
3273 addr->sin_addr.s_addr = adapter_addr;
3274 TRACE("reporting interface address from adapter %d\n", ifindex);
3275 break;
3278 HeapFree(GetProcessHeap(), 0, adapters);
3280 #endif
3283 /***********************************************************************
3284 * getsockname (WS2_32.6)
3286 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
3288 int fd;
3289 int res;
3291 TRACE("socket %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
3293 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
3294 if( (name == NULL) || (namelen == NULL) )
3296 SetLastError( WSAEFAULT );
3297 return SOCKET_ERROR;
3300 fd = get_sock_fd( s, 0, NULL );
3301 res = SOCKET_ERROR;
3303 if (fd != -1)
3305 union generic_unix_sockaddr uaddr;
3306 socklen_t uaddrlen;
3307 int bound = is_fd_bound(fd, &uaddr, &uaddrlen);
3309 if (bound <= 0)
3311 SetLastError(bound == -1 ? wsaErrno() : WSAEINVAL);
3313 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3315 /* The buffer was too small */
3316 SetLastError(WSAEFAULT);
3318 else
3320 interface_bind_check(fd, (struct sockaddr_in*) &uaddr);
3321 if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3323 /* The buffer was too small */
3324 SetLastError(WSAEFAULT);
3326 else
3328 res = 0;
3329 TRACE("=> %s\n", debugstr_sockaddr(name));
3332 release_sock_fd( s, fd );
3334 return res;
3337 /***********************************************************************
3338 * getsockopt (WS2_32.7)
3340 INT WINAPI WS_getsockopt(SOCKET s, INT level,
3341 INT optname, char *optval, INT *optlen)
3343 int fd;
3344 INT ret = 0;
3346 TRACE("(socket %04lx, %s, optval %s, optlen %p (%d))\n", s,
3347 debugstr_sockopt(level, optname), debugstr_optval(optval, 0),
3348 optlen, optlen ? *optlen : 0);
3350 switch(level)
3352 case WS_SOL_SOCKET:
3354 switch(optname)
3356 /* Handle common cases. The special cases are below, sorted
3357 * alphabetically */
3358 case WS_SO_BROADCAST:
3359 case WS_SO_DEBUG:
3360 case WS_SO_KEEPALIVE:
3361 case WS_SO_OOBINLINE:
3362 case WS_SO_RCVBUF:
3363 case WS_SO_REUSEADDR:
3364 case WS_SO_SNDBUF:
3365 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3366 return SOCKET_ERROR;
3367 convert_sockopt(&level, &optname);
3368 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3370 SetLastError(wsaErrno());
3371 ret = SOCKET_ERROR;
3373 release_sock_fd( s, fd );
3374 return ret;
3375 case WS_SO_ACCEPTCONN:
3376 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3377 return SOCKET_ERROR;
3378 if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, optval, (socklen_t *)optlen) != 0 )
3380 SetLastError(wsaErrno());
3381 ret = SOCKET_ERROR;
3383 else
3385 /* BSD returns != 0 while Windows return exact == 1 */
3386 if (*(int *)optval) *(int *)optval = 1;
3388 release_sock_fd( s, fd );
3389 return ret;
3390 case WS_SO_BSP_STATE:
3392 int req_size, addr_size;
3393 WSAPROTOCOL_INFOW infow;
3394 CSADDR_INFO *csinfo;
3396 ret = ws_protocol_info(s, TRUE, &infow, &addr_size);
3397 if (ret)
3399 if (infow.iAddressFamily == WS_AF_INET)
3400 addr_size = sizeof(struct sockaddr_in);
3401 else if (infow.iAddressFamily == WS_AF_INET6)
3402 addr_size = sizeof(struct sockaddr_in6);
3403 else
3405 FIXME("Family %d is unsupported for SO_BSP_STATE\n", infow.iAddressFamily);
3406 SetLastError(WSAEAFNOSUPPORT);
3407 return SOCKET_ERROR;
3410 req_size = sizeof(CSADDR_INFO) + addr_size * 2;
3411 if (*optlen < req_size)
3413 ret = 0;
3414 SetLastError(WSAEFAULT);
3416 else
3418 union generic_unix_sockaddr uaddr;
3419 socklen_t uaddrlen;
3421 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3422 return SOCKET_ERROR;
3424 csinfo = (CSADDR_INFO*) optval;
3426 /* Check if the sock is bound */
3427 if (is_fd_bound(fd, &uaddr, &uaddrlen) == 1)
3429 csinfo->LocalAddr.lpSockaddr =
3430 (LPSOCKADDR) (optval + sizeof(CSADDR_INFO));
3431 ws_sockaddr_u2ws(&uaddr.addr, csinfo->LocalAddr.lpSockaddr, &addr_size);
3432 csinfo->LocalAddr.iSockaddrLength = addr_size;
3434 else
3436 csinfo->LocalAddr.lpSockaddr = NULL;
3437 csinfo->LocalAddr.iSockaddrLength = 0;
3440 /* Check if the sock is connected */
3441 if (!getpeername(fd, &uaddr.addr, &uaddrlen) &&
3442 is_sockaddr_bound(&uaddr.addr, uaddrlen))
3444 csinfo->RemoteAddr.lpSockaddr =
3445 (LPSOCKADDR) (optval + sizeof(CSADDR_INFO) + addr_size);
3446 ws_sockaddr_u2ws(&uaddr.addr, csinfo->RemoteAddr.lpSockaddr, &addr_size);
3447 csinfo->RemoteAddr.iSockaddrLength = addr_size;
3449 else
3451 csinfo->RemoteAddr.lpSockaddr = NULL;
3452 csinfo->RemoteAddr.iSockaddrLength = 0;
3455 csinfo->iSocketType = infow.iSocketType;
3456 csinfo->iProtocol = infow.iProtocol;
3457 release_sock_fd( s, fd );
3460 return ret ? 0 : SOCKET_ERROR;
3462 case WS_SO_DONTLINGER:
3464 struct linger lingval;
3465 socklen_t len = sizeof(struct linger);
3467 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
3469 SetLastError(WSAEFAULT);
3470 return SOCKET_ERROR;
3472 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3473 return SOCKET_ERROR;
3475 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
3477 SetLastError(wsaErrno());
3478 ret = SOCKET_ERROR;
3480 else
3482 *(BOOL *)optval = !lingval.l_onoff;
3483 *optlen = sizeof(BOOL);
3486 release_sock_fd( s, fd );
3487 return ret;
3490 case WS_SO_CONNECT_TIME:
3492 static int pretendtime = 0;
3493 struct WS_sockaddr addr;
3494 int len = sizeof(addr);
3496 if (!optlen || *optlen < sizeof(DWORD) || !optval)
3498 SetLastError(WSAEFAULT);
3499 return SOCKET_ERROR;
3501 if (WS_getpeername(s, &addr, &len) == SOCKET_ERROR)
3502 *(DWORD *)optval = ~0u;
3503 else
3505 if (!pretendtime) FIXME("WS_SO_CONNECT_TIME - faking results\n");
3506 *(DWORD *)optval = pretendtime++;
3508 *optlen = sizeof(DWORD);
3509 return ret;
3511 /* As mentioned in setsockopt, Windows ignores this, so we
3512 * always return true here */
3513 case WS_SO_DONTROUTE:
3514 if (!optlen || *optlen < sizeof(BOOL) || !optval)
3516 SetLastError(WSAEFAULT);
3517 return SOCKET_ERROR;
3519 *(BOOL *)optval = TRUE;
3520 *optlen = sizeof(BOOL);
3521 return 0;
3523 case WS_SO_ERROR:
3525 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3526 return SOCKET_ERROR;
3527 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, optval, (socklen_t *)optlen) != 0 )
3529 SetLastError(wsaErrno());
3530 ret = SOCKET_ERROR;
3532 release_sock_fd( s, fd );
3534 /* The wineserver may have swallowed the error before us */
3535 if (!ret && *(int*) optval == 0)
3537 int i, events[FD_MAX_EVENTS];
3538 _get_sock_errors(s, events);
3539 for (i = 0; i < FD_MAX_EVENTS; i++)
3541 if(events[i])
3543 events[i] = NtStatusToWSAError(events[i]);
3544 TRACE("returning SO_ERROR %d from wine server\n", events[i]);
3545 *(int*) optval = events[i];
3546 break;
3550 return ret;
3553 case WS_SO_LINGER:
3555 struct linger lingval;
3556 socklen_t len = sizeof(struct linger);
3558 /* struct linger and LINGER have different sizes */
3559 if (!optlen || *optlen < sizeof(LINGER) || !optval)
3561 SetLastError(WSAEFAULT);
3562 return SOCKET_ERROR;
3564 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3565 return SOCKET_ERROR;
3567 if (_get_fd_type(fd) == SOCK_DGRAM)
3569 SetLastError(WSAENOPROTOOPT);
3570 ret = SOCKET_ERROR;
3572 else if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0)
3574 SetLastError(wsaErrno());
3575 ret = SOCKET_ERROR;
3577 else
3579 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
3580 ((LINGER *)optval)->l_linger = lingval.l_linger;
3581 *optlen = sizeof(struct linger);
3584 release_sock_fd( s, fd );
3585 return ret;
3588 case WS_SO_MAX_MSG_SIZE:
3589 if (!optlen || *optlen < sizeof(int) || !optval)
3591 SetLastError(WSAEFAULT);
3592 return SOCKET_ERROR;
3594 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
3595 *(int *)optval = 65507;
3596 *optlen = sizeof(int);
3597 return 0;
3599 /* SO_OPENTYPE does not require a valid socket handle. */
3600 case WS_SO_OPENTYPE:
3601 if (!optlen || *optlen < sizeof(int) || !optval)
3603 SetLastError(WSAEFAULT);
3604 return SOCKET_ERROR;
3606 *(int *)optval = get_per_thread_data()->opentype;
3607 *optlen = sizeof(int);
3608 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
3609 return 0;
3610 case WS_SO_PROTOCOL_INFOA:
3611 case WS_SO_PROTOCOL_INFOW:
3613 int size;
3614 WSAPROTOCOL_INFOW infow;
3616 ret = ws_protocol_info(s, optname == WS_SO_PROTOCOL_INFOW, &infow, &size);
3617 if (ret)
3619 if (!optlen || !optval || *optlen < size)
3621 if(optlen) *optlen = size;
3622 ret = 0;
3623 SetLastError(WSAEFAULT);
3625 else
3626 memcpy(optval, &infow, size);
3628 return ret ? 0 : SOCKET_ERROR;
3630 case WS_SO_RCVTIMEO:
3631 case WS_SO_SNDTIMEO:
3633 INT64 timeout;
3635 if (!optlen || *optlen < sizeof(int)|| !optval)
3637 SetLastError(WSAEFAULT);
3638 return SOCKET_ERROR;
3640 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3641 return SOCKET_ERROR;
3643 timeout = get_rcvsnd_timeo(fd, optname == WS_SO_RCVTIMEO);
3644 *(int *)optval = timeout <= UINT_MAX ? timeout : UINT_MAX;
3646 release_sock_fd( s, fd );
3647 return ret;
3649 case WS_SO_TYPE:
3651 int sock_type;
3652 if (!optlen || *optlen < sizeof(int) || !optval)
3654 SetLastError(WSAEFAULT);
3655 return SOCKET_ERROR;
3657 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3658 return SOCKET_ERROR;
3660 sock_type = _get_fd_type(fd);
3661 if (sock_type == -1)
3663 SetLastError(wsaErrno());
3664 ret = SOCKET_ERROR;
3666 else
3667 (*(int *)optval) = convert_socktype_u2w(sock_type);
3669 release_sock_fd( s, fd );
3670 return ret;
3672 default:
3673 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
3674 SetLastError(WSAENOPROTOOPT);
3675 return SOCKET_ERROR;
3676 } /* end switch(optname) */
3677 }/* end case WS_SOL_SOCKET */
3678 #ifdef HAS_IPX
3679 case WS_NSPROTO_IPX:
3681 struct WS_sockaddr_ipx addr;
3682 IPX_ADDRESS_DATA *data;
3683 int namelen;
3684 switch(optname)
3686 case WS_IPX_PTYPE:
3687 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3688 #ifdef SOL_IPX
3689 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (socklen_t *)optlen) == -1)
3691 ret = SOCKET_ERROR;
3693 #else
3695 struct ipx val;
3696 socklen_t len=sizeof(struct ipx);
3697 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
3698 ret = SOCKET_ERROR;
3699 else
3700 *optval = (int)val.ipx_pt;
3702 #endif
3703 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
3704 release_sock_fd( s, fd );
3705 return ret;
3707 case WS_IPX_ADDRESS:
3709 * On a Win2000 system with one network card there are usually
3710 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
3711 * Using this call you can then retrieve info about this all.
3712 * In case of Linux it is a bit different. Usually you have
3713 * only "one" device active and further it is not possible to
3714 * query things like the linkspeed.
3716 FIXME("IPX_ADDRESS\n");
3717 namelen = sizeof(struct WS_sockaddr_ipx);
3718 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
3719 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
3721 data = (IPX_ADDRESS_DATA*)optval;
3722 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
3723 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
3724 data->adapternum = 0;
3725 data->wan = FALSE; /* We are not on a wan for now .. */
3726 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
3727 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
3728 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
3729 * note 1MB = 1000kB in this case */
3730 return 0;
3732 case WS_IPX_MAX_ADAPTER_NUM:
3733 FIXME("IPX_MAX_ADAPTER_NUM\n");
3734 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
3735 return 0;
3737 default:
3738 FIXME("IPX optname:%x\n", optname);
3739 return SOCKET_ERROR;
3740 }/* end switch(optname) */
3741 } /* end case WS_NSPROTO_IPX */
3742 #endif
3744 #ifdef HAS_IRDA
3745 #define MAX_IRDA_DEVICES 10
3747 case WS_SOL_IRLMP:
3748 switch(optname)
3750 case WS_IRLMP_ENUMDEVICES:
3752 char buf[sizeof(struct irda_device_list) +
3753 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
3754 int res;
3755 socklen_t len = sizeof(buf);
3757 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3758 return SOCKET_ERROR;
3759 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
3760 release_sock_fd( s, fd );
3761 if (res < 0)
3763 SetLastError(wsaErrno());
3764 return SOCKET_ERROR;
3766 else
3768 struct irda_device_list *src = (struct irda_device_list *)buf;
3769 DEVICELIST *dst = (DEVICELIST *)optval;
3770 INT needed = sizeof(DEVICELIST);
3771 unsigned int i;
3773 if (src->len > 0)
3774 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
3775 if (*optlen < needed)
3777 SetLastError(WSAEFAULT);
3778 return SOCKET_ERROR;
3780 *optlen = needed;
3781 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
3782 dst->numDevice = src->len;
3783 for (i = 0; i < src->len; i++)
3785 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
3786 src->dev[i].saddr, src->dev[i].daddr,
3787 src->dev[i].info, src->dev[i].hints[0],
3788 src->dev[i].hints[1]);
3789 memcpy( dst->Device[i].irdaDeviceID,
3790 &src->dev[i].daddr,
3791 sizeof(dst->Device[i].irdaDeviceID) ) ;
3792 memcpy( dst->Device[i].irdaDeviceName,
3793 src->dev[i].info,
3794 sizeof(dst->Device[i].irdaDeviceName) ) ;
3795 memcpy( &dst->Device[i].irdaDeviceHints1,
3796 &src->dev[i].hints[0],
3797 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
3798 memcpy( &dst->Device[i].irdaDeviceHints2,
3799 &src->dev[i].hints[1],
3800 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
3801 dst->Device[i].irdaCharSet = src->dev[i].charset;
3803 return 0;
3806 default:
3807 FIXME("IrDA optname:0x%x\n", optname);
3808 return SOCKET_ERROR;
3810 break; /* case WS_SOL_IRLMP */
3811 #undef MAX_IRDA_DEVICES
3812 #endif
3814 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3815 case WS_IPPROTO_TCP:
3816 switch(optname)
3818 case WS_TCP_NODELAY:
3819 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3820 return SOCKET_ERROR;
3821 convert_sockopt(&level, &optname);
3822 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3824 SetLastError(wsaErrno());
3825 ret = SOCKET_ERROR;
3827 release_sock_fd( s, fd );
3828 return ret;
3830 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
3831 return SOCKET_ERROR;
3833 case WS_IPPROTO_IP:
3834 switch(optname)
3836 case WS_IP_ADD_MEMBERSHIP:
3837 case WS_IP_DROP_MEMBERSHIP:
3838 #ifdef IP_HDRINCL
3839 case WS_IP_HDRINCL:
3840 #endif
3841 case WS_IP_MULTICAST_IF:
3842 case WS_IP_MULTICAST_LOOP:
3843 case WS_IP_MULTICAST_TTL:
3844 case WS_IP_OPTIONS:
3845 #ifdef IP_PKTINFO
3846 case WS_IP_PKTINFO:
3847 #endif
3848 case WS_IP_TOS:
3849 case WS_IP_TTL:
3850 #ifdef IP_UNICAST_IF
3851 case WS_IP_UNICAST_IF:
3852 #endif
3853 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3854 return SOCKET_ERROR;
3855 convert_sockopt(&level, &optname);
3856 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3858 SetLastError(wsaErrno());
3859 ret = SOCKET_ERROR;
3861 release_sock_fd( s, fd );
3862 return ret;
3863 case WS_IP_DONTFRAGMENT:
3864 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
3865 *(BOOL*)optval = FALSE;
3866 return 0;
3868 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
3869 return SOCKET_ERROR;
3871 case WS_IPPROTO_IPV6:
3872 switch(optname)
3874 #ifdef IPV6_ADD_MEMBERSHIP
3875 case WS_IPV6_ADD_MEMBERSHIP:
3876 #endif
3877 #ifdef IPV6_DROP_MEMBERSHIP
3878 case WS_IPV6_DROP_MEMBERSHIP:
3879 #endif
3880 case WS_IPV6_MULTICAST_IF:
3881 case WS_IPV6_MULTICAST_HOPS:
3882 case WS_IPV6_MULTICAST_LOOP:
3883 case WS_IPV6_UNICAST_HOPS:
3884 case WS_IPV6_V6ONLY:
3885 #ifdef IPV6_UNICAST_IF
3886 case WS_IPV6_UNICAST_IF:
3887 #endif
3888 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3889 return SOCKET_ERROR;
3890 convert_sockopt(&level, &optname);
3891 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3893 SetLastError(wsaErrno());
3894 ret = SOCKET_ERROR;
3896 release_sock_fd( s, fd );
3897 return ret;
3898 case WS_IPV6_DONTFRAG:
3899 FIXME("WS_IPV6_DONTFRAG is always false!\n");
3900 *(BOOL*)optval = FALSE;
3901 return 0;
3903 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
3904 return SOCKET_ERROR;
3906 default:
3907 WARN("Unknown level: 0x%08x\n", level);
3908 SetLastError(WSAEINVAL);
3909 return SOCKET_ERROR;
3910 } /* end switch(level) */
3913 /***********************************************************************
3914 * htonl (WS2_32.8)
3916 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
3918 return htonl(hostlong);
3922 /***********************************************************************
3923 * htons (WS2_32.9)
3925 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
3927 return htons(hostshort);
3930 /***********************************************************************
3931 * WSAHtonl (WS2_32.46)
3932 * From MSDN description of error codes, this function should also
3933 * check if WinSock has been initialized and the socket is a valid
3934 * socket. But why? This function only translates a host byte order
3935 * u_long into a network byte order u_long...
3937 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
3939 if (lpnetlong)
3941 *lpnetlong = htonl(hostlong);
3942 return 0;
3944 SetLastError(WSAEFAULT);
3945 return SOCKET_ERROR;
3948 /***********************************************************************
3949 * WSAHtons (WS2_32.47)
3950 * From MSDN description of error codes, this function should also
3951 * check if WinSock has been initialized and the socket is a valid
3952 * socket. But why? This function only translates a host byte order
3953 * u_short into a network byte order u_short...
3955 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
3958 if (lpnetshort)
3960 *lpnetshort = htons(hostshort);
3961 return 0;
3963 SetLastError(WSAEFAULT);
3964 return SOCKET_ERROR;
3968 /***********************************************************************
3969 * inet_addr (WS2_32.11)
3971 WS_u_long WINAPI WS_inet_addr(const char *cp)
3973 if (!cp) return INADDR_NONE;
3974 return inet_addr(cp);
3978 /***********************************************************************
3979 * ntohl (WS2_32.14)
3981 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
3983 return ntohl(netlong);
3987 /***********************************************************************
3988 * ntohs (WS2_32.15)
3990 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
3992 return ntohs(netshort);
3996 /***********************************************************************
3997 * inet_ntoa (WS2_32.12)
3999 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
4001 char* s = inet_ntoa(*((struct in_addr*)&in));
4002 if( s )
4004 struct per_thread_data *data = get_per_thread_data();
4005 strcpy(data->ntoa_buffer, s);
4006 return data->ntoa_buffer;
4008 SetLastError(wsaErrno());
4009 return NULL;
4012 static const char *debugstr_wsaioctl(DWORD ioctl)
4014 const char *buf_type, *family;
4016 switch(ioctl & 0x18000000)
4018 case WS_IOC_WS2:
4019 family = "IOC_WS2";
4020 break;
4021 case WS_IOC_PROTOCOL:
4022 family = "IOC_PROTOCOL";
4023 break;
4024 case WS_IOC_VENDOR:
4025 family = "IOC_VENDOR";
4026 break;
4027 default: /* WS_IOC_UNIX */
4029 BYTE size = (ioctl >> 16) & WS_IOCPARM_MASK;
4030 char x = (ioctl & 0xff00) >> 8;
4031 BYTE y = ioctl & 0xff;
4032 char args[14];
4034 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
4036 case WS_IOC_VOID:
4037 buf_type = "_IO";
4038 sprintf(args, "%d, %d", x, y);
4039 break;
4040 case WS_IOC_IN:
4041 buf_type = "_IOW";
4042 sprintf(args, "'%c', %d, %d", x, y, size);
4043 break;
4044 case WS_IOC_OUT:
4045 buf_type = "_IOR";
4046 sprintf(args, "'%c', %d, %d", x, y, size);
4047 break;
4048 default:
4049 buf_type = "?";
4050 sprintf(args, "'%c', %d, %d", x, y, size);
4051 break;
4053 return wine_dbg_sprintf("%s(%s)", buf_type, args);
4057 /* We are different from WS_IOC_UNIX. */
4058 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
4060 case WS_IOC_VOID:
4061 buf_type = "_WSAIO";
4062 break;
4063 case WS_IOC_INOUT:
4064 buf_type = "_WSAIORW";
4065 break;
4066 case WS_IOC_IN:
4067 buf_type = "_WSAIOW";
4068 break;
4069 case WS_IOC_OUT:
4070 buf_type = "_WSAIOR";
4071 break;
4072 default:
4073 buf_type = "?";
4074 break;
4077 return wine_dbg_sprintf("%s(%s, %d)", buf_type, family,
4078 (USHORT)(ioctl & 0xffff));
4081 /* do an ioctl call through the server */
4082 static DWORD server_ioctl_sock( SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size,
4083 LPVOID out_buff, DWORD out_size, LPDWORD ret_size,
4084 LPWSAOVERLAPPED overlapped,
4085 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
4087 HANDLE event = overlapped ? overlapped->hEvent : 0;
4088 HANDLE handle = SOCKET2HANDLE( s );
4089 struct ws2_async *wsa;
4090 NTSTATUS status;
4091 PIO_STATUS_BLOCK io;
4093 if (!(wsa = (struct ws2_async *)alloc_async_io( sizeof(*wsa) )))
4094 return WSA_NOT_ENOUGH_MEMORY;
4095 wsa->hSocket = handle;
4096 wsa->user_overlapped = overlapped;
4097 wsa->completion_func = completion;
4098 io = (overlapped ? (PIO_STATUS_BLOCK)overlapped : &wsa->local_iosb);
4100 status = NtDeviceIoControlFile( handle, event, ws2_async_apc, wsa, io, code,
4101 in_buff, in_size, out_buff, out_size );
4102 if (status == STATUS_NOT_SUPPORTED)
4104 FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
4105 code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
4107 else if (status == STATUS_SUCCESS)
4108 *ret_size = io->Information; /* "Information" is the size written to the output buffer */
4110 if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, wsa );
4112 return NtStatusToWSAError( status );
4115 /**********************************************************************
4116 * WSAIoctl (WS2_32.50)
4119 INT WINAPI WSAIoctl(SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size, LPVOID out_buff,
4120 DWORD out_size, LPDWORD ret_size, LPWSAOVERLAPPED overlapped,
4121 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
4123 int fd;
4124 DWORD status = 0, total = 0;
4126 TRACE("%04lx, %s, %p, %d, %p, %d, %p, %p, %p\n",
4127 s, debugstr_wsaioctl(code), in_buff, in_size, out_buff, out_size, ret_size, overlapped, completion);
4129 switch (code)
4131 case WS_FIONBIO:
4132 if (in_size != sizeof(WS_u_long) || IS_INTRESOURCE(in_buff))
4134 SetLastError(WSAEFAULT);
4135 return SOCKET_ERROR;
4137 TRACE("-> FIONBIO (%x)\n", *(WS_u_long*)in_buff);
4138 if (_get_sock_mask(s))
4140 /* AsyncSelect()'ed sockets are always nonblocking */
4141 if (!*(WS_u_long *)in_buff) status = WSAEINVAL;
4142 break;
4144 if (*(WS_u_long *)in_buff)
4145 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
4146 else
4147 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
4148 break;
4150 case WS_FIONREAD:
4152 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
4154 SetLastError(WSAEFAULT);
4155 return SOCKET_ERROR;
4157 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
4158 if (ioctl(fd, FIONREAD, out_buff ) == -1)
4159 status = wsaErrno();
4160 release_sock_fd( s, fd );
4161 break;
4164 case WS_SIOCATMARK:
4166 unsigned int oob = 0, atmark = 0;
4167 socklen_t oobsize = sizeof(int);
4168 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
4170 SetLastError(WSAEFAULT);
4171 return SOCKET_ERROR;
4173 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
4174 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
4175 if ((getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &oob, &oobsize ) == -1)
4176 || (!oob && ioctl(fd, SIOCATMARK, &atmark ) == -1))
4177 status = wsaErrno();
4178 else
4180 /* The SIOCATMARK value read from ioctl() is reversed
4181 * because BSD returns TRUE if it's in the OOB mark
4182 * while Windows returns TRUE if there are NO OOB bytes.
4184 (*(WS_u_long *) out_buff) = oob || !atmark;
4187 release_sock_fd( s, fd );
4188 break;
4191 case WS_FIOASYNC:
4192 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
4193 SetLastError(WSAEINVAL);
4194 return SOCKET_ERROR;
4196 case WS_SIO_GET_INTERFACE_LIST:
4198 INTERFACE_INFO* intArray = out_buff;
4199 DWORD size, numInt = 0, apiReturn;
4201 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
4203 if (!out_buff || !ret_size)
4205 SetLastError(WSAEFAULT);
4206 return SOCKET_ERROR;
4209 fd = get_sock_fd( s, 0, NULL );
4210 if (fd == -1) return SOCKET_ERROR;
4212 apiReturn = GetAdaptersInfo(NULL, &size);
4213 if (apiReturn == ERROR_BUFFER_OVERFLOW)
4215 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
4217 if (table)
4219 if (GetAdaptersInfo(table, &size) == NO_ERROR)
4221 PIP_ADAPTER_INFO ptr;
4223 for (ptr = table, numInt = 0; ptr; ptr = ptr->Next)
4225 unsigned int addr, mask, bcast;
4226 struct ifreq ifInfo;
4228 /* Skip interfaces without an IPv4 address. */
4229 if (ptr->IpAddressList.IpAddress.String[0] == '\0')
4230 continue;
4232 if ((numInt + 1)*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > out_size)
4234 WARN("Buffer too small = %u, out_size = %u\n", numInt + 1, out_size);
4235 status = WSAEFAULT;
4236 break;
4239 /* Socket Status Flags */
4240 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
4241 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
4243 ERR("Error obtaining status flags for socket!\n");
4244 status = WSAEINVAL;
4245 break;
4247 else
4249 /* set flags; the values of IFF_* are not the same
4250 under Linux and Windows, therefore must generate
4251 new flags */
4252 intArray->iiFlags = 0;
4253 if (ifInfo.ifr_flags & IFF_BROADCAST)
4254 intArray->iiFlags |= WS_IFF_BROADCAST;
4255 #ifdef IFF_POINTOPOINT
4256 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
4257 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
4258 #endif
4259 if (ifInfo.ifr_flags & IFF_LOOPBACK)
4260 intArray->iiFlags |= WS_IFF_LOOPBACK;
4261 if (ifInfo.ifr_flags & IFF_UP)
4262 intArray->iiFlags |= WS_IFF_UP;
4263 if (ifInfo.ifr_flags & IFF_MULTICAST)
4264 intArray->iiFlags |= WS_IFF_MULTICAST;
4267 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
4268 mask = inet_addr(ptr->IpAddressList.IpMask.String);
4269 bcast = addr | ~mask;
4270 intArray->iiAddress.AddressIn.sin_family = AF_INET;
4271 intArray->iiAddress.AddressIn.sin_port = 0;
4272 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
4273 addr;
4274 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
4275 intArray->iiNetmask.AddressIn.sin_port = 0;
4276 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
4277 mask;
4278 intArray->iiBroadcastAddress.AddressIn.sin_family =
4279 AF_INET;
4280 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
4281 intArray->iiBroadcastAddress.AddressIn.sin_addr.
4282 WS_s_addr = bcast;
4283 intArray++;
4284 numInt++;
4287 else
4289 ERR("Unable to get interface table!\n");
4290 status = WSAEINVAL;
4292 HeapFree(GetProcessHeap(),0,table);
4294 else status = WSAEINVAL;
4296 else if (apiReturn != ERROR_NO_DATA)
4298 ERR("Unable to get interface table!\n");
4299 status = WSAEINVAL;
4301 /* Calculate the size of the array being returned */
4302 total = sizeof(INTERFACE_INFO) * numInt;
4303 release_sock_fd( s, fd );
4304 break;
4307 case WS_SIO_ADDRESS_LIST_QUERY:
4309 DWORD size;
4311 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
4313 if (!ret_size)
4315 SetLastError(WSAEFAULT);
4316 return SOCKET_ERROR;
4319 if (out_size && out_size < FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[0]))
4321 *ret_size = 0;
4322 SetLastError(WSAEINVAL);
4323 return SOCKET_ERROR;
4326 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
4328 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
4329 SOCKET_ADDRESS_LIST *sa_list;
4330 SOCKADDR_IN *sockaddr;
4331 SOCKET_ADDRESS *sa;
4332 unsigned int i;
4333 DWORD num;
4335 if (!table || GetAdaptersInfo(table, &size))
4337 HeapFree(GetProcessHeap(), 0, table);
4338 status = WSAEINVAL;
4339 break;
4342 for (p = table, num = 0; p; p = p->Next)
4343 if (p->IpAddressList.IpAddress.String[0]) num++;
4345 total = FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[num]) + num * sizeof(*sockaddr);
4346 if (total > out_size || !out_buff)
4348 *ret_size = total;
4349 HeapFree(GetProcessHeap(), 0, table);
4350 status = WSAEFAULT;
4351 break;
4354 sa_list = out_buff;
4355 sa = sa_list->Address;
4356 sockaddr = (SOCKADDR_IN *)&sa[num];
4357 sa_list->iAddressCount = num;
4359 for (p = table, i = 0; p; p = p->Next)
4361 if (!p->IpAddressList.IpAddress.String[0]) continue;
4363 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
4364 sa[i].iSockaddrLength = sizeof(SOCKADDR);
4366 sockaddr[i].sin_family = AF_INET;
4367 sockaddr[i].sin_port = 0;
4368 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
4369 i++;
4372 HeapFree(GetProcessHeap(), 0, table);
4374 else
4376 WARN("unable to get IP address list\n");
4377 status = WSAEINVAL;
4379 break;
4382 case WS_SIO_FLUSH:
4383 FIXME("SIO_FLUSH: stub.\n");
4384 break;
4386 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
4388 static const GUID connectex_guid = WSAID_CONNECTEX;
4389 static const GUID disconnectex_guid = WSAID_DISCONNECTEX;
4390 static const GUID acceptex_guid = WSAID_ACCEPTEX;
4391 static const GUID getaccepexsockaddrs_guid = WSAID_GETACCEPTEXSOCKADDRS;
4392 static const GUID transmitfile_guid = WSAID_TRANSMITFILE;
4393 static const GUID transmitpackets_guid = WSAID_TRANSMITPACKETS;
4394 static const GUID wsarecvmsg_guid = WSAID_WSARECVMSG;
4395 static const GUID wsasendmsg_guid = WSAID_WSASENDMSG;
4397 if ( IsEqualGUID(&connectex_guid, in_buff) )
4399 *(LPFN_CONNECTEX *)out_buff = WS2_ConnectEx;
4400 break;
4402 else if ( IsEqualGUID(&disconnectex_guid, in_buff) )
4404 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented DisconnectEx\n");
4406 else if ( IsEqualGUID(&acceptex_guid, in_buff) )
4408 *(LPFN_ACCEPTEX *)out_buff = WS2_AcceptEx;
4409 break;
4411 else if ( IsEqualGUID(&getaccepexsockaddrs_guid, in_buff) )
4413 *(LPFN_GETACCEPTEXSOCKADDRS *)out_buff = WS2_GetAcceptExSockaddrs;
4414 break;
4416 else if ( IsEqualGUID(&transmitfile_guid, in_buff) )
4418 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitFile\n");
4420 else if ( IsEqualGUID(&transmitpackets_guid, in_buff) )
4422 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitPackets\n");
4424 else if ( IsEqualGUID(&wsarecvmsg_guid, in_buff) )
4426 *(LPFN_WSARECVMSG *)out_buff = WS2_WSARecvMsg;
4427 break;
4429 else if ( IsEqualGUID(&wsasendmsg_guid, in_buff) )
4431 *(LPFN_WSASENDMSG *)out_buff = WSASendMsg;
4432 break;
4434 else
4435 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff));
4437 status = WSAEOPNOTSUPP;
4438 break;
4440 case WS_SIO_KEEPALIVE_VALS:
4442 struct tcp_keepalive *k;
4443 int keepalive, keepidle, keepintvl;
4445 if (!in_buff || in_size < sizeof(struct tcp_keepalive))
4447 SetLastError(WSAEFAULT);
4448 return SOCKET_ERROR;
4451 k = in_buff;
4452 keepalive = k->onoff ? 1 : 0;
4453 keepidle = max( 1, (k->keepalivetime + 500) / 1000 );
4454 keepintvl = max( 1, (k->keepaliveinterval + 500) / 1000 );
4456 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
4458 fd = get_sock_fd(s, 0, NULL);
4459 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
4460 status = WSAEINVAL;
4461 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
4462 /* these values need to be set only if SO_KEEPALIVE is enabled */
4463 else if(keepalive)
4465 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
4466 status = WSAEINVAL;
4467 else if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
4468 status = WSAEINVAL;
4470 #else
4471 else
4472 FIXME("ignoring keepalive interval and timeout\n");
4473 #endif
4474 release_sock_fd(s, fd);
4475 break;
4477 case WS_SIO_ROUTING_INTERFACE_QUERY:
4479 struct WS_sockaddr *daddr = (struct WS_sockaddr *)in_buff;
4480 struct WS_sockaddr_in *daddr_in = (struct WS_sockaddr_in *)daddr;
4481 struct WS_sockaddr_in *saddr_in = out_buff;
4482 MIB_IPFORWARDROW row;
4483 PMIB_IPADDRTABLE ipAddrTable = NULL;
4484 DWORD size, i, found_index;
4486 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
4488 if (!in_buff || in_size < sizeof(struct WS_sockaddr) ||
4489 !out_buff || out_size < sizeof(struct WS_sockaddr_in) || !ret_size)
4491 SetLastError(WSAEFAULT);
4492 return SOCKET_ERROR;
4494 if (daddr->sa_family != AF_INET)
4496 FIXME("unsupported address family %d\n", daddr->sa_family);
4497 status = WSAEAFNOSUPPORT;
4498 break;
4500 if (GetBestRoute(daddr_in->sin_addr.S_un.S_addr, 0, &row) != NOERROR ||
4501 GetIpAddrTable(NULL, &size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
4503 status = WSAEFAULT;
4504 break;
4506 ipAddrTable = HeapAlloc(GetProcessHeap(), 0, size);
4507 if (GetIpAddrTable(ipAddrTable, &size, FALSE))
4509 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4510 status = WSAEFAULT;
4511 break;
4513 for (i = 0, found_index = ipAddrTable->dwNumEntries;
4514 i < ipAddrTable->dwNumEntries; i++)
4516 if (ipAddrTable->table[i].dwIndex == row.dwForwardIfIndex)
4517 found_index = i;
4519 if (found_index == ipAddrTable->dwNumEntries)
4521 ERR("no matching IP address for interface %d\n",
4522 row.dwForwardIfIndex);
4523 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4524 status = WSAEFAULT;
4525 break;
4527 saddr_in->sin_family = AF_INET;
4528 saddr_in->sin_addr.S_un.S_addr = ipAddrTable->table[found_index].dwAddr;
4529 saddr_in->sin_port = 0;
4530 total = sizeof(struct WS_sockaddr_in);
4531 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4532 break;
4534 case WS_SIO_SET_COMPATIBILITY_MODE:
4535 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
4536 status = WSAEOPNOTSUPP;
4537 break;
4538 case WS_SIO_UDP_CONNRESET:
4539 FIXME("WS_SIO_UDP_CONNRESET stub\n");
4540 break;
4541 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
4542 SetLastError(WSAEOPNOTSUPP);
4543 return SOCKET_ERROR;
4544 default:
4545 status = WSAEOPNOTSUPP;
4546 break;
4549 if (status == WSAEOPNOTSUPP)
4551 status = server_ioctl_sock(s, code, in_buff, in_size, out_buff, out_size, &total,
4552 overlapped, completion);
4553 if (status != WSAEOPNOTSUPP)
4555 if (status == 0 || status == WSA_IO_PENDING)
4556 TRACE("-> %s request\n", debugstr_wsaioctl(code));
4557 else
4558 ERR("-> %s request failed with status 0x%x\n", debugstr_wsaioctl(code), status);
4560 /* overlapped and completion operations will be handled by the server */
4561 completion = NULL;
4562 overlapped = NULL;
4564 else
4565 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code));
4568 if (completion)
4570 FIXME( "completion routine %p not supported\n", completion );
4572 else if (overlapped)
4574 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
4575 overlapped->Internal = status;
4576 overlapped->InternalHigh = total;
4577 if (overlapped->hEvent) NtSetEvent( overlapped->hEvent, NULL );
4578 if (cvalue) WS_AddCompletion( HANDLE2SOCKET(s), cvalue, status, total );
4581 if (!status)
4583 if (ret_size) *ret_size = total;
4584 return 0;
4586 SetLastError( status );
4587 return SOCKET_ERROR;
4591 /***********************************************************************
4592 * ioctlsocket (WS2_32.10)
4594 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
4596 DWORD ret_size;
4597 return WSAIoctl( s, cmd, argp, sizeof(WS_u_long), argp, sizeof(WS_u_long), &ret_size, NULL, NULL );
4600 /***********************************************************************
4601 * listen (WS2_32.13)
4603 int WINAPI WS_listen(SOCKET s, int backlog)
4605 int fd = get_sock_fd( s, FILE_READ_DATA, NULL ), ret = SOCKET_ERROR;
4607 TRACE("socket %04lx, backlog %d\n", s, backlog);
4608 if (fd != -1)
4610 int bound = is_fd_bound(fd, NULL, NULL);
4612 if (bound <= 0)
4614 SetLastError(bound == -1 ? wsaErrno() : WSAEINVAL);
4616 else if (listen(fd, backlog) == 0)
4618 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
4619 FD_WINE_LISTENING,
4620 FD_CONNECT|FD_WINE_CONNECTED);
4621 ret = 0;
4623 else
4624 SetLastError(wsaErrno());
4625 release_sock_fd( s, fd );
4627 else
4628 SetLastError(WSAENOTSOCK);
4629 return ret;
4632 /***********************************************************************
4633 * recv (WS2_32.16)
4635 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
4637 DWORD n, dwFlags = flags;
4638 WSABUF wsabuf;
4640 wsabuf.len = len;
4641 wsabuf.buf = buf;
4643 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
4644 return SOCKET_ERROR;
4645 else
4646 return n;
4649 /***********************************************************************
4650 * recvfrom (WS2_32.17)
4652 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
4653 struct WS_sockaddr *from, int *fromlen)
4655 DWORD n, dwFlags = flags;
4656 WSABUF wsabuf;
4658 wsabuf.len = len;
4659 wsabuf.buf = buf;
4661 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL, NULL) == SOCKET_ERROR )
4662 return SOCKET_ERROR;
4663 else
4664 return n;
4667 /* allocate a poll array for the corresponding fd sets */
4668 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
4669 const WS_fd_set *exceptfds, int *count_ptr )
4671 unsigned int i, j = 0, count = 0;
4672 struct pollfd *fds;
4674 if (readfds) count += readfds->fd_count;
4675 if (writefds) count += writefds->fd_count;
4676 if (exceptfds) count += exceptfds->fd_count;
4677 *count_ptr = count;
4678 if (!count)
4680 SetLastError(WSAEINVAL);
4681 return NULL;
4683 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0]))))
4685 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
4686 return NULL;
4688 if (readfds)
4689 for (i = 0; i < readfds->fd_count; i++, j++)
4691 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
4692 if (fds[j].fd == -1) goto failed;
4693 fds[j].revents = 0;
4694 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1)
4696 fds[j].events = POLLIN;
4698 else
4700 release_sock_fd( readfds->fd_array[i], fds[j].fd );
4701 fds[j].fd = -1;
4702 fds[j].events = 0;
4705 if (writefds)
4706 for (i = 0; i < writefds->fd_count; i++, j++)
4708 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
4709 if (fds[j].fd == -1) goto failed;
4710 fds[j].revents = 0;
4711 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1 ||
4712 _get_fd_type(fds[j].fd) == SOCK_DGRAM)
4714 fds[j].events = POLLOUT;
4716 else
4718 release_sock_fd( writefds->fd_array[i], fds[j].fd );
4719 fds[j].fd = -1;
4720 fds[j].events = 0;
4723 if (exceptfds)
4724 for (i = 0; i < exceptfds->fd_count; i++, j++)
4726 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
4727 if (fds[j].fd == -1) goto failed;
4728 fds[j].revents = 0;
4729 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1)
4731 int oob_inlined = 0;
4732 socklen_t olen = sizeof(oob_inlined);
4734 fds[j].events = POLLHUP;
4736 /* Check if we need to test for urgent data or not */
4737 getsockopt(fds[j].fd, SOL_SOCKET, SO_OOBINLINE, (char*) &oob_inlined, &olen);
4738 if (!oob_inlined)
4739 fds[j].events |= POLLPRI;
4741 else
4743 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
4744 fds[j].fd = -1;
4745 fds[j].events = 0;
4748 return fds;
4750 failed:
4751 count = j;
4752 j = 0;
4753 if (readfds)
4754 for (i = 0; i < readfds->fd_count && j < count; i++, j++)
4755 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
4756 if (writefds)
4757 for (i = 0; i < writefds->fd_count && j < count; i++, j++)
4758 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
4759 if (exceptfds)
4760 for (i = 0; i < exceptfds->fd_count && j < count; i++, j++)
4761 if (fds[j].fd != -1) release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
4762 HeapFree( GetProcessHeap(), 0, fds );
4763 return NULL;
4766 /* release the file descriptor obtained in fd_sets_to_poll */
4767 /* must be called with the original fd_set arrays, before calling get_poll_results */
4768 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
4769 const WS_fd_set *exceptfds, struct pollfd *fds )
4771 unsigned int i, j = 0;
4773 if (readfds)
4775 for (i = 0; i < readfds->fd_count; i++, j++)
4776 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
4778 if (writefds)
4780 for (i = 0; i < writefds->fd_count; i++, j++)
4781 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
4783 if (exceptfds)
4785 for (i = 0; i < exceptfds->fd_count; i++, j++)
4787 if (fds[j].fd == -1) continue;
4788 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
4789 if (fds[j].revents & POLLHUP)
4791 int fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
4792 if (fd != -1)
4793 release_sock_fd( exceptfds->fd_array[i], fd );
4794 else
4795 fds[j].revents = 0;
4801 static int do_poll(struct pollfd *pollfds, int count, int timeout)
4803 struct timeval tv1, tv2;
4804 int ret, torig = timeout;
4806 if (timeout > 0) gettimeofday( &tv1, 0 );
4808 while ((ret = poll( pollfds, count, timeout )) < 0)
4810 if (errno != EINTR) break;
4811 if (timeout < 0) continue;
4812 if (timeout == 0) return 0;
4814 gettimeofday( &tv2, 0 );
4816 tv2.tv_sec -= tv1.tv_sec;
4817 tv2.tv_usec -= tv1.tv_usec;
4818 if (tv2.tv_usec < 0)
4820 tv2.tv_usec += 1000000;
4821 tv2.tv_sec -= 1;
4824 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
4825 if (timeout <= 0) return 0;
4827 return ret;
4830 /* map the poll results back into the Windows fd sets */
4831 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
4832 const struct pollfd *fds )
4834 const struct pollfd *poll_writefds = fds + (readfds ? readfds->fd_count : 0);
4835 const struct pollfd *poll_exceptfds = poll_writefds + (writefds ? writefds->fd_count : 0);
4836 unsigned int i, k, total = 0;
4838 if (readfds)
4840 for (i = k = 0; i < readfds->fd_count; i++)
4842 if (fds[i].revents ||
4843 (readfds == writefds && (poll_writefds[i].revents & POLLOUT) && !(poll_writefds[i].revents & POLLHUP)) ||
4844 (readfds == exceptfds && poll_exceptfds[i].revents))
4845 readfds->fd_array[k++] = readfds->fd_array[i];
4847 readfds->fd_count = k;
4848 total += k;
4850 if (writefds && writefds != readfds)
4852 for (i = k = 0; i < writefds->fd_count; i++)
4854 if (((poll_writefds[i].revents & POLLOUT) && !(poll_writefds[i].revents & POLLHUP)) ||
4855 (writefds == exceptfds && poll_exceptfds[i].revents))
4856 writefds->fd_array[k++] = writefds->fd_array[i];
4858 writefds->fd_count = k;
4859 total += k;
4861 if (exceptfds && exceptfds != readfds && exceptfds != writefds)
4863 for (i = k = 0; i < exceptfds->fd_count; i++)
4864 if (poll_exceptfds[i].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
4865 exceptfds->fd_count = k;
4866 total += k;
4868 return total;
4871 /***********************************************************************
4872 * select (WS2_32.18)
4874 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
4875 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
4876 const struct WS_timeval* ws_timeout)
4878 struct pollfd *pollfds;
4879 int count, ret, timeout = -1;
4881 TRACE("read %p, write %p, excp %p timeout %p\n",
4882 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
4884 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )))
4885 return SOCKET_ERROR;
4887 if (ws_timeout)
4888 timeout = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
4890 ret = do_poll(pollfds, count, timeout);
4891 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
4893 if (ret == -1) SetLastError(wsaErrno());
4894 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
4895 HeapFree( GetProcessHeap(), 0, pollfds );
4896 return ret;
4899 /* helper to send completion messages for client-only i/o operation case */
4900 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
4901 ULONG Information )
4903 SERVER_START_REQ( add_fd_completion )
4905 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
4906 req->cvalue = CompletionValue;
4907 req->status = CompletionStatus;
4908 req->information = Information;
4909 wine_server_call( req );
4911 SERVER_END_REQ;
4915 /***********************************************************************
4916 * send (WS2_32.19)
4918 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
4920 DWORD n;
4921 WSABUF wsabuf;
4923 wsabuf.len = len;
4924 wsabuf.buf = (char*) buf;
4926 if ( WS2_sendto( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
4927 return SOCKET_ERROR;
4928 else
4929 return n;
4932 /***********************************************************************
4933 * WSASend (WS2_32.72)
4935 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4936 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4937 LPWSAOVERLAPPED lpOverlapped,
4938 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4940 return WS2_sendto( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
4941 NULL, 0, lpOverlapped, lpCompletionRoutine );
4944 /***********************************************************************
4945 * WSASendDisconnect (WS2_32.73)
4947 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
4949 return WS_shutdown( s, SD_SEND );
4953 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4954 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4955 const struct WS_sockaddr *to, int tolen,
4956 LPWSAOVERLAPPED lpOverlapped,
4957 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4959 unsigned int i, options;
4960 int n, fd, err, overlapped, flags;
4961 struct ws2_async *wsa = NULL, localwsa;
4962 int totalLength = 0;
4963 DWORD bytes_sent;
4964 BOOL is_blocking;
4966 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
4967 s, lpBuffers, dwBufferCount, dwFlags,
4968 to, tolen, lpOverlapped, lpCompletionRoutine);
4970 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
4971 TRACE( "fd=%d, options=%x\n", fd, options );
4973 if ( fd == -1 ) return SOCKET_ERROR;
4975 if (!lpOverlapped && !lpNumberOfBytesSent)
4977 err = WSAEFAULT;
4978 goto error;
4981 overlapped = (lpOverlapped || lpCompletionRoutine) &&
4982 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
4983 if (overlapped || dwBufferCount > 1)
4985 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[dwBufferCount]))))
4987 err = WSAEFAULT;
4988 goto error;
4991 else
4992 wsa = &localwsa;
4994 wsa->hSocket = SOCKET2HANDLE(s);
4995 wsa->addr = (struct WS_sockaddr *)to;
4996 wsa->addrlen.val = tolen;
4997 wsa->flags = dwFlags;
4998 wsa->lpFlags = &wsa->flags;
4999 wsa->control = NULL;
5000 wsa->n_iovecs = dwBufferCount;
5001 wsa->first_iovec = 0;
5002 for ( i = 0; i < dwBufferCount; i++ )
5004 wsa->iovec[i].iov_base = lpBuffers[i].buf;
5005 wsa->iovec[i].iov_len = lpBuffers[i].len;
5006 totalLength += lpBuffers[i].len;
5009 flags = convert_flags(dwFlags);
5010 n = WS2_send( fd, wsa, flags );
5011 if (n == -1 && errno != EAGAIN)
5013 err = wsaErrno();
5014 goto error;
5017 if (overlapped)
5019 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
5020 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
5022 wsa->user_overlapped = lpOverlapped;
5023 wsa->completion_func = lpCompletionRoutine;
5024 release_sock_fd( s, fd );
5026 if (n == -1 || n < totalLength)
5028 iosb->u.Status = STATUS_PENDING;
5029 iosb->Information = n == -1 ? 0 : n;
5031 SERVER_START_REQ( register_async )
5033 req->type = ASYNC_TYPE_WRITE;
5034 req->async.handle = wine_server_obj_handle( wsa->hSocket );
5035 req->async.callback = wine_server_client_ptr( WS2_async_send );
5036 req->async.iosb = wine_server_client_ptr( iosb );
5037 req->async.arg = wine_server_client_ptr( wsa );
5038 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
5039 req->async.cvalue = cvalue;
5040 err = wine_server_call( req );
5042 SERVER_END_REQ;
5044 /* Enable the event only after starting the async. The server will deliver it as soon as
5045 the async is done. */
5046 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
5048 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
5049 SetLastError(NtStatusToWSAError( err ));
5050 return SOCKET_ERROR;
5053 iosb->u.Status = STATUS_SUCCESS;
5054 iosb->Information = n;
5055 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = n;
5056 if (!wsa->completion_func)
5058 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
5059 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
5060 HeapFree( GetProcessHeap(), 0, wsa );
5062 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
5063 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
5064 SetLastError(ERROR_SUCCESS);
5065 return 0;
5068 if ((err = _is_blocking( s, &is_blocking )))
5070 err = NtStatusToWSAError( err );
5071 goto error;
5074 if ( is_blocking )
5076 /* On a blocking non-overlapped stream socket,
5077 * sending blocks until the entire buffer is sent. */
5078 DWORD timeout_start = GetTickCount();
5080 bytes_sent = n == -1 ? 0 : n;
5082 while (wsa->first_iovec < wsa->n_iovecs)
5084 struct pollfd pfd;
5085 int poll_timeout = -1;
5086 INT64 timeout = get_rcvsnd_timeo(fd, FALSE);
5088 if (timeout)
5090 timeout -= GetTickCount() - timeout_start;
5091 if (timeout < 0) poll_timeout = 0;
5092 else poll_timeout = timeout <= INT_MAX ? timeout : INT_MAX;
5095 pfd.fd = fd;
5096 pfd.events = POLLOUT;
5098 if (!poll_timeout || !poll( &pfd, 1, poll_timeout ))
5100 err = WSAETIMEDOUT;
5101 goto error; /* msdn says a timeout in send is fatal */
5104 n = WS2_send( fd, wsa, flags );
5105 if (n == -1 && errno != EAGAIN)
5107 err = wsaErrno();
5108 goto error;
5111 if (n >= 0)
5112 bytes_sent += n;
5115 else /* non-blocking */
5117 if (n < totalLength)
5118 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
5119 if (n == -1)
5121 err = WSAEWOULDBLOCK;
5122 goto error;
5124 bytes_sent = n;
5127 TRACE(" -> %i bytes\n", bytes_sent);
5129 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = bytes_sent;
5130 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
5131 release_sock_fd( s, fd );
5132 SetLastError(ERROR_SUCCESS);
5133 return 0;
5135 error:
5136 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
5137 release_sock_fd( s, fd );
5138 WARN(" -> ERROR %d\n", err);
5139 SetLastError(err);
5140 return SOCKET_ERROR;
5143 /***********************************************************************
5144 * WSASendTo (WS2_32.74)
5146 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5147 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
5148 const struct WS_sockaddr *to, int tolen,
5149 LPWSAOVERLAPPED lpOverlapped,
5150 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5152 return WS2_sendto( s, lpBuffers, dwBufferCount,
5153 lpNumberOfBytesSent, dwFlags,
5154 to, tolen,
5155 lpOverlapped, lpCompletionRoutine );
5158 /***********************************************************************
5159 * sendto (WS2_32.20)
5161 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
5162 const struct WS_sockaddr *to, int tolen)
5164 DWORD n;
5165 WSABUF wsabuf;
5167 wsabuf.len = len;
5168 wsabuf.buf = (char*) buf;
5170 if ( WS2_sendto(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
5171 return SOCKET_ERROR;
5172 else
5173 return n;
5176 /***********************************************************************
5177 * setsockopt (WS2_32.21)
5179 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
5180 const char *optval, int optlen)
5182 int fd;
5183 int woptval;
5184 struct linger linger;
5185 struct timeval tval;
5187 TRACE("(socket %04lx, %s, optval %s, optlen %d)\n", s,
5188 debugstr_sockopt(level, optname), debugstr_optval(optval, optlen),
5189 optlen);
5191 /* some broken apps pass the value directly instead of a pointer to it */
5192 if(optlen && IS_INTRESOURCE(optval))
5194 SetLastError(WSAEFAULT);
5195 return SOCKET_ERROR;
5198 switch(level)
5200 case WS_SOL_SOCKET:
5201 switch(optname)
5203 /* Some options need some conversion before they can be sent to
5204 * setsockopt. The conversions are done here, then they will fall through
5205 * to the general case. Special options that are not passed to
5206 * setsockopt follow below that.*/
5208 case WS_SO_DONTLINGER:
5209 if (!optval)
5211 SetLastError(WSAEFAULT);
5212 return SOCKET_ERROR;
5214 linger.l_onoff = *(const int*)optval == 0;
5215 linger.l_linger = 0;
5216 level = SOL_SOCKET;
5217 optname = SO_LINGER;
5218 optval = (char*)&linger;
5219 optlen = sizeof(struct linger);
5220 break;
5222 case WS_SO_LINGER:
5223 if (!optval)
5225 SetLastError(WSAEFAULT);
5226 return SOCKET_ERROR;
5228 linger.l_onoff = ((LINGER*)optval)->l_onoff;
5229 linger.l_linger = ((LINGER*)optval)->l_linger;
5230 level = SOL_SOCKET;
5231 optname = SO_LINGER;
5232 optval = (char*)&linger;
5233 optlen = sizeof(struct linger);
5234 break;
5236 case WS_SO_RCVBUF:
5237 if (*(const int*)optval < 2048)
5239 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
5240 return 0;
5242 /* Fall through */
5244 /* The options listed here don't need any special handling. Thanks to
5245 * the conversion happening above, options from there will fall through
5246 * to this, too.*/
5247 case WS_SO_ACCEPTCONN:
5248 case WS_SO_BROADCAST:
5249 case WS_SO_ERROR:
5250 case WS_SO_KEEPALIVE:
5251 case WS_SO_OOBINLINE:
5252 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
5253 * however, using it the BSD way fixes bug 8513 and seems to be what
5254 * most programmers assume, anyway */
5255 case WS_SO_REUSEADDR:
5256 case WS_SO_SNDBUF:
5257 case WS_SO_TYPE:
5258 convert_sockopt(&level, &optname);
5259 break;
5261 /* SO_DEBUG is a privileged operation, ignore it. */
5262 case WS_SO_DEBUG:
5263 TRACE("Ignoring SO_DEBUG\n");
5264 return 0;
5266 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
5267 * socket. According to MSDN, this option is silently ignored.*/
5268 case WS_SO_DONTROUTE:
5269 TRACE("Ignoring SO_DONTROUTE\n");
5270 return 0;
5272 /* Stops two sockets from being bound to the same port. Always happens
5273 * on unix systems, so just drop it. */
5274 case WS_SO_EXCLUSIVEADDRUSE:
5275 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
5276 return 0;
5278 /* After a ConnectEx call succeeds, the socket can't be used with half of the
5279 * normal winsock functions on windows. We don't have that problem. */
5280 case WS_SO_UPDATE_CONNECT_CONTEXT:
5281 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
5282 return 0;
5284 /* After a AcceptEx call succeeds, the socket can't be used with half of the
5285 * normal winsock functions on windows. We don't have that problem. */
5286 case WS_SO_UPDATE_ACCEPT_CONTEXT:
5287 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
5288 return 0;
5290 /* SO_OPENTYPE does not require a valid socket handle. */
5291 case WS_SO_OPENTYPE:
5292 if (!optlen || optlen < sizeof(int) || !optval)
5294 SetLastError(WSAEFAULT);
5295 return SOCKET_ERROR;
5297 get_per_thread_data()->opentype = *(const int *)optval;
5298 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
5299 return 0;
5301 #ifdef SO_RCVTIMEO
5302 case WS_SO_RCVTIMEO:
5303 #endif
5304 #ifdef SO_SNDTIMEO
5305 case WS_SO_SNDTIMEO:
5306 #endif
5307 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
5308 if (optval && optlen == sizeof(UINT32)) {
5309 /* WinSock passes milliseconds instead of struct timeval */
5310 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
5311 tval.tv_sec = *(const UINT32*)optval / 1000;
5312 /* min of 500 milliseconds */
5313 if (tval.tv_sec == 0 && tval.tv_usec && tval.tv_usec < 500000)
5314 tval.tv_usec = 500000;
5315 optlen = sizeof(struct timeval);
5316 optval = (char*)&tval;
5317 } else if (optlen == sizeof(struct timeval)) {
5318 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
5319 } else {
5320 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
5321 return 0;
5323 convert_sockopt(&level, &optname);
5324 break;
5325 #endif
5327 default:
5328 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
5329 SetLastError(WSAENOPROTOOPT);
5330 return SOCKET_ERROR;
5332 break; /* case WS_SOL_SOCKET */
5334 #ifdef HAS_IPX
5335 case WS_NSPROTO_IPX:
5336 switch(optname)
5338 case WS_IPX_PTYPE:
5339 return set_ipx_packettype(s, *(int*)optval);
5341 case WS_IPX_FILTERPTYPE:
5342 /* Sets the receive filter packet type, at the moment we don't support it */
5343 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
5344 /* Returning 0 is better for now than returning a SOCKET_ERROR */
5345 return 0;
5347 default:
5348 FIXME("opt_name:%x\n", optname);
5349 return SOCKET_ERROR;
5351 break; /* case WS_NSPROTO_IPX */
5352 #endif
5354 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
5355 case WS_IPPROTO_TCP:
5356 switch(optname)
5358 case WS_TCP_NODELAY:
5359 convert_sockopt(&level, &optname);
5360 break;
5361 default:
5362 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
5363 return SOCKET_ERROR;
5365 break;
5367 case WS_IPPROTO_IP:
5368 switch(optname)
5370 case WS_IP_ADD_MEMBERSHIP:
5371 case WS_IP_DROP_MEMBERSHIP:
5372 #ifdef IP_HDRINCL
5373 case WS_IP_HDRINCL:
5374 #endif
5375 case WS_IP_MULTICAST_IF:
5376 case WS_IP_MULTICAST_LOOP:
5377 case WS_IP_MULTICAST_TTL:
5378 case WS_IP_OPTIONS:
5379 #ifdef IP_PKTINFO
5380 case WS_IP_PKTINFO:
5381 #endif
5382 case WS_IP_TOS:
5383 case WS_IP_TTL:
5384 #ifdef IP_UNICAST_IF
5385 case WS_IP_UNICAST_IF:
5386 #endif
5387 convert_sockopt(&level, &optname);
5388 break;
5389 case WS_IP_DONTFRAGMENT:
5390 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
5391 return 0;
5392 default:
5393 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
5394 return SOCKET_ERROR;
5396 break;
5398 case WS_IPPROTO_IPV6:
5399 switch(optname)
5401 #ifdef IPV6_ADD_MEMBERSHIP
5402 case WS_IPV6_ADD_MEMBERSHIP:
5403 #endif
5404 #ifdef IPV6_DROP_MEMBERSHIP
5405 case WS_IPV6_DROP_MEMBERSHIP:
5406 #endif
5407 case WS_IPV6_MULTICAST_IF:
5408 case WS_IPV6_MULTICAST_HOPS:
5409 case WS_IPV6_MULTICAST_LOOP:
5410 case WS_IPV6_UNICAST_HOPS:
5411 case WS_IPV6_V6ONLY:
5412 #ifdef IPV6_UNICAST_IF
5413 case WS_IPV6_UNICAST_IF:
5414 #endif
5415 convert_sockopt(&level, &optname);
5416 break;
5417 case WS_IPV6_DONTFRAG:
5418 FIXME("IPV6_DONTFRAG is silently ignored!\n");
5419 return 0;
5420 case WS_IPV6_PROTECTION_LEVEL:
5421 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
5422 return 0;
5423 default:
5424 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
5425 return SOCKET_ERROR;
5427 break;
5429 default:
5430 WARN("Unknown level: 0x%08x\n", level);
5431 SetLastError(WSAEINVAL);
5432 return SOCKET_ERROR;
5433 } /* end switch(level) */
5435 /* avoid endianness issues if argument is a 16-bit int */
5436 if (optval && optlen < sizeof(int))
5438 woptval= *((const INT16 *) optval);
5439 optval= (char*) &woptval;
5440 woptval&= (1 << optlen * 8) - 1;
5441 optlen=sizeof(int);
5443 fd = get_sock_fd( s, 0, NULL );
5444 if (fd == -1) return SOCKET_ERROR;
5446 if (setsockopt(fd, level, optname, optval, optlen) == 0)
5448 #ifdef __APPLE__
5449 if (level == SOL_SOCKET && optname == SO_REUSEADDR &&
5450 setsockopt(fd, level, SO_REUSEPORT, optval, optlen) != 0)
5452 SetLastError(wsaErrno());
5453 release_sock_fd( s, fd );
5454 return SOCKET_ERROR;
5456 #endif
5457 release_sock_fd( s, fd );
5458 return 0;
5460 TRACE("Setting socket error, %d\n", wsaErrno());
5461 SetLastError(wsaErrno());
5462 release_sock_fd( s, fd );
5464 return SOCKET_ERROR;
5467 /***********************************************************************
5468 * shutdown (WS2_32.22)
5470 int WINAPI WS_shutdown(SOCKET s, int how)
5472 int fd, err = WSAENOTSOCK;
5473 unsigned int options = 0, clear_flags = 0;
5475 fd = get_sock_fd( s, 0, &options );
5476 TRACE("socket %04lx, how 0x%x, options 0x%x\n", s, how, options );
5478 if (fd == -1)
5479 return SOCKET_ERROR;
5481 switch( how )
5483 case SD_RECEIVE: /* drop receives */
5484 clear_flags |= FD_READ;
5485 break;
5486 case SD_SEND: /* drop sends */
5487 clear_flags |= FD_WRITE;
5488 break;
5489 case SD_BOTH: /* drop all */
5490 clear_flags |= FD_READ|FD_WRITE;
5491 /*fall through */
5492 default:
5493 clear_flags |= FD_WINE_LISTENING;
5496 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
5498 switch ( how )
5500 case SD_RECEIVE:
5501 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
5502 break;
5503 case SD_SEND:
5504 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
5505 break;
5506 case SD_BOTH:
5507 default:
5508 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
5509 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
5510 break;
5512 if (err) goto error;
5514 else /* non-overlapped mode */
5516 if ( shutdown( fd, how ) )
5518 err = wsaErrno();
5519 goto error;
5523 release_sock_fd( s, fd );
5524 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
5525 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
5526 return 0;
5528 error:
5529 release_sock_fd( s, fd );
5530 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
5531 SetLastError( err );
5532 return SOCKET_ERROR;
5535 /***********************************************************************
5536 * socket (WS2_32.23)
5538 SOCKET WINAPI WS_socket(int af, int type, int protocol)
5540 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
5542 return WSASocketW( af, type, protocol, NULL, 0,
5543 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
5547 /***********************************************************************
5548 * gethostbyaddr (WS2_32.51)
5550 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
5552 struct WS_hostent *retval = NULL;
5553 struct hostent* host;
5554 int unixtype = convert_af_w2u(type);
5555 const char *paddr = addr;
5556 unsigned long loopback;
5557 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5558 char *extrabuf;
5559 int ebufsize = 1024;
5560 struct hostent hostentry;
5561 int locerr = ENOBUFS;
5562 #endif
5564 /* convert back the magic loopback address if necessary */
5565 if (unixtype == AF_INET && len == 4 && !memcmp(addr, magic_loopback_addr, 4))
5567 loopback = htonl(INADDR_LOOPBACK);
5568 paddr = (char*) &loopback;
5571 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5572 host = NULL;
5573 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
5574 while(extrabuf) {
5575 int res = gethostbyaddr_r(paddr, len, unixtype,
5576 &hostentry, extrabuf, ebufsize, &host, &locerr);
5577 if (res != ERANGE) break;
5578 ebufsize *=2;
5579 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
5581 if (host) retval = WS_dup_he(host);
5582 else SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
5583 HeapFree(GetProcessHeap(),0,extrabuf);
5584 #else
5585 EnterCriticalSection( &csWSgetXXXbyYYY );
5586 host = gethostbyaddr(paddr, len, unixtype);
5587 if (host) retval = WS_dup_he(host);
5588 else SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
5589 LeaveCriticalSection( &csWSgetXXXbyYYY );
5590 #endif
5591 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
5592 return retval;
5595 /***********************************************************************
5596 * WS_compare_routes_by_metric_asc (INTERNAL)
5598 * Comparison function for qsort(), for sorting two routes (struct route)
5599 * by metric in ascending order.
5601 static int WS_compare_routes_by_metric_asc(const void *left, const void *right)
5603 return ((const struct route*)left)->metric - ((const struct route*)right)->metric;
5606 /***********************************************************************
5607 * WS_get_local_ips (INTERNAL)
5609 * Returns the list of local IP addresses by going through the network
5610 * adapters and using the local routing table to sort the addresses
5611 * from highest routing priority to lowest routing priority. This
5612 * functionality is inferred from the description for obtaining local
5613 * IP addresses given in the Knowledge Base Article Q160215.
5615 * Please note that the returned hostent is only freed when the thread
5616 * closes and is replaced if another hostent is requested.
5618 static struct WS_hostent* WS_get_local_ips( char *hostname )
5620 int numroutes = 0, i, j;
5621 DWORD n;
5622 PIP_ADAPTER_INFO adapters = NULL, k;
5623 struct WS_hostent *hostlist = NULL;
5624 PMIB_IPFORWARDTABLE routes = NULL;
5625 struct route *route_addrs = NULL;
5626 DWORD adap_size, route_size;
5628 /* Obtain the size of the adapter list and routing table, also allocate memory */
5629 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
5630 return NULL;
5631 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
5632 return NULL;
5633 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
5634 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
5635 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
5636 if (adapters == NULL || routes == NULL || route_addrs == NULL)
5637 goto cleanup;
5638 /* Obtain the adapter list and the full routing table */
5639 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
5640 goto cleanup;
5641 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
5642 goto cleanup;
5643 /* Store the interface associated with each route */
5644 for (n = 0; n < routes->dwNumEntries; n++)
5646 IF_INDEX ifindex;
5647 DWORD ifmetric;
5648 BOOL exists = FALSE;
5650 if (routes->table[n].u1.ForwardType != MIB_IPROUTE_TYPE_DIRECT)
5651 continue;
5652 ifindex = routes->table[n].dwForwardIfIndex;
5653 ifmetric = routes->table[n].dwForwardMetric1;
5654 /* Only store the lowest valued metric for an interface */
5655 for (j = 0; j < numroutes; j++)
5657 if (route_addrs[j].interface == ifindex)
5659 if (route_addrs[j].metric > ifmetric)
5660 route_addrs[j].metric = ifmetric;
5661 exists = TRUE;
5664 if (exists)
5665 continue;
5666 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
5667 if (route_addrs == NULL)
5668 goto cleanup; /* Memory allocation error, fail gracefully */
5669 route_addrs[numroutes].interface = ifindex;
5670 route_addrs[numroutes].metric = ifmetric;
5671 /* If no IP is found in the next step (for whatever reason)
5672 * then fall back to the magic loopback address.
5674 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
5675 numroutes++;
5677 if (numroutes == 0)
5678 goto cleanup; /* No routes, fall back to the Magic IP */
5679 /* Find the IP address associated with each found interface */
5680 for (i = 0; i < numroutes; i++)
5682 for (k = adapters; k != NULL; k = k->Next)
5684 char *ip = k->IpAddressList.IpAddress.String;
5686 if (route_addrs[i].interface == k->Index)
5687 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
5690 /* Allocate a hostent and enough memory for all the IPs,
5691 * including the NULL at the end of the list.
5693 hostlist = WS_create_he(hostname, 1, 0, numroutes+1, sizeof(struct in_addr));
5694 if (hostlist == NULL)
5695 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
5696 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
5697 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
5698 hostlist->h_addrtype = AF_INET;
5699 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
5700 /* Reorder the entries before placing them in the host list. Windows expects
5701 * the IP list in order from highest priority to lowest (the critical thing
5702 * is that most applications expect the first IP to be the default route).
5704 if (numroutes > 1)
5705 qsort(route_addrs, numroutes, sizeof(struct route), WS_compare_routes_by_metric_asc);
5707 for (i = 0; i < numroutes; i++)
5708 (*(struct in_addr *) hostlist->h_addr_list[i]) = route_addrs[i].addr;
5710 /* Cleanup all allocated memory except the address list,
5711 * the address list is used by the calling app.
5713 cleanup:
5714 HeapFree(GetProcessHeap(), 0, route_addrs);
5715 HeapFree(GetProcessHeap(), 0, adapters);
5716 HeapFree(GetProcessHeap(), 0, routes);
5717 return hostlist;
5720 /***********************************************************************
5721 * gethostbyname (WS2_32.52)
5723 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
5725 struct WS_hostent *retval = NULL;
5726 struct hostent* host;
5727 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5728 char *extrabuf;
5729 int ebufsize=1024;
5730 struct hostent hostentry;
5731 int locerr = ENOBUFS;
5732 #endif
5733 char hostname[100];
5734 if(!num_startup) {
5735 SetLastError(WSANOTINITIALISED);
5736 return NULL;
5738 if( gethostname( hostname, 100) == -1) {
5739 SetLastError(WSAENOBUFS); /* appropriate ? */
5740 return retval;
5742 if( !name || !name[0]) {
5743 name = hostname;
5745 /* If the hostname of the local machine is requested then return the
5746 * complete list of local IP addresses */
5747 if(strcmp(name, hostname) == 0)
5748 retval = WS_get_local_ips(hostname);
5749 /* If any other hostname was requested (or the routing table lookup failed)
5750 * then return the IP found by the host OS */
5751 if(retval == NULL)
5753 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5754 host = NULL;
5755 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
5756 while(extrabuf) {
5757 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
5758 if( res != ERANGE) break;
5759 ebufsize *=2;
5760 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
5762 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
5763 #else
5764 EnterCriticalSection( &csWSgetXXXbyYYY );
5765 host = gethostbyname(name);
5766 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
5767 #endif
5768 if (host) retval = WS_dup_he(host);
5769 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5770 HeapFree(GetProcessHeap(),0,extrabuf);
5771 #else
5772 LeaveCriticalSection( &csWSgetXXXbyYYY );
5773 #endif
5775 if (retval && retval->h_addr_list[0][0] == 127 &&
5776 strcmp(name, "localhost") != 0)
5778 /* hostname != "localhost" but has loopback address. replace by our
5779 * special address.*/
5780 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
5782 TRACE( "%s ret %p\n", debugstr_a(name), retval );
5783 return retval;
5787 /***********************************************************************
5788 * getprotobyname (WS2_32.53)
5790 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
5792 struct WS_protoent* retval = NULL;
5793 #ifdef HAVE_GETPROTOBYNAME
5794 struct protoent* proto;
5795 EnterCriticalSection( &csWSgetXXXbyYYY );
5796 if( (proto = getprotobyname(name)) != NULL )
5798 retval = WS_dup_pe(proto);
5800 else {
5801 MESSAGE("protocol %s not found; You might want to add "
5802 "this to /etc/protocols\n", debugstr_a(name) );
5803 SetLastError(WSANO_DATA);
5805 LeaveCriticalSection( &csWSgetXXXbyYYY );
5806 #endif
5807 TRACE( "%s ret %p\n", debugstr_a(name), retval );
5808 return retval;
5812 /***********************************************************************
5813 * getprotobynumber (WS2_32.54)
5815 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
5817 struct WS_protoent* retval = NULL;
5818 #ifdef HAVE_GETPROTOBYNUMBER
5819 struct protoent* proto;
5820 EnterCriticalSection( &csWSgetXXXbyYYY );
5821 if( (proto = getprotobynumber(number)) != NULL )
5823 retval = WS_dup_pe(proto);
5825 else {
5826 MESSAGE("protocol number %d not found; You might want to add "
5827 "this to /etc/protocols\n", number );
5828 SetLastError(WSANO_DATA);
5830 LeaveCriticalSection( &csWSgetXXXbyYYY );
5831 #endif
5832 TRACE("%i ret %p\n", number, retval);
5833 return retval;
5837 /***********************************************************************
5838 * getservbyname (WS2_32.55)
5840 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
5842 struct WS_servent* retval = NULL;
5843 struct servent* serv;
5844 char *name_str;
5845 char *proto_str = NULL;
5847 if (!(name_str = strdup_lower(name))) return NULL;
5849 if (proto && *proto)
5851 if (!(proto_str = strdup_lower(proto)))
5853 HeapFree( GetProcessHeap(), 0, name_str );
5854 return NULL;
5858 EnterCriticalSection( &csWSgetXXXbyYYY );
5859 serv = getservbyname(name_str, proto_str);
5860 if( serv != NULL )
5862 retval = WS_dup_se(serv);
5864 else SetLastError(WSANO_DATA);
5865 LeaveCriticalSection( &csWSgetXXXbyYYY );
5866 HeapFree( GetProcessHeap(), 0, proto_str );
5867 HeapFree( GetProcessHeap(), 0, name_str );
5868 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
5869 return retval;
5872 /***********************************************************************
5873 * freeaddrinfo (WS2_32.@)
5875 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
5877 while (res) {
5878 struct WS_addrinfo *next;
5880 HeapFree(GetProcessHeap(),0,res->ai_canonname);
5881 HeapFree(GetProcessHeap(),0,res->ai_addr);
5882 next = res->ai_next;
5883 HeapFree(GetProcessHeap(),0,res);
5884 res = next;
5888 /* helper functions for getaddrinfo()/getnameinfo() */
5889 static int convert_aiflag_w2u(int winflags) {
5890 unsigned int i;
5891 int unixflags = 0;
5893 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
5894 if (ws_aiflag_map[i][0] & winflags) {
5895 unixflags |= ws_aiflag_map[i][1];
5896 winflags &= ~ws_aiflag_map[i][0];
5898 if (winflags)
5899 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
5900 return unixflags;
5903 static int convert_niflag_w2u(int winflags) {
5904 unsigned int i;
5905 int unixflags = 0;
5907 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
5908 if (ws_niflag_map[i][0] & winflags) {
5909 unixflags |= ws_niflag_map[i][1];
5910 winflags &= ~ws_niflag_map[i][0];
5912 if (winflags)
5913 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
5914 return unixflags;
5917 static int convert_aiflag_u2w(int unixflags) {
5918 unsigned int i;
5919 int winflags = 0;
5921 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
5922 if (ws_aiflag_map[i][1] & unixflags) {
5923 winflags |= ws_aiflag_map[i][0];
5924 unixflags &= ~ws_aiflag_map[i][1];
5926 if (unixflags) /* will warn usually */
5927 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
5928 return winflags;
5931 static int convert_eai_u2w(int unixret) {
5932 int i;
5934 if (!unixret) return 0;
5936 for (i=0;ws_eai_map[i][0];i++)
5937 if (ws_eai_map[i][1] == unixret)
5938 return ws_eai_map[i][0];
5940 if (unixret == EAI_SYSTEM)
5941 /* There are broken versions of glibc which return EAI_SYSTEM
5942 * and set errno to 0 instead of returning EAI_NONAME.
5944 return errno ? sock_get_error( errno ) : WS_EAI_NONAME;
5946 FIXME("Unhandled unix EAI_xxx ret %d\n", unixret);
5947 return unixret;
5950 static char *get_hostname(void)
5952 char *ret;
5953 DWORD size = 0;
5955 GetComputerNameExA( ComputerNamePhysicalDnsHostname, NULL, &size );
5956 if (GetLastError() != ERROR_MORE_DATA) return NULL;
5957 if (!(ret = HeapAlloc( GetProcessHeap(), 0, size ))) return NULL;
5958 if (!GetComputerNameExA( ComputerNamePhysicalDnsHostname, ret, &size ))
5960 HeapFree( GetProcessHeap(), 0, ret );
5961 return NULL;
5963 return ret;
5966 /***********************************************************************
5967 * getaddrinfo (WS2_32.@)
5969 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
5971 #ifdef HAVE_GETADDRINFO
5972 struct addrinfo *unixaires = NULL;
5973 int result;
5974 struct addrinfo unixhints, *punixhints = NULL;
5975 char *hostname = NULL;
5976 const char *node;
5978 *res = NULL;
5979 if (!nodename && !servname)
5981 SetLastError(WSAHOST_NOT_FOUND);
5982 return WSAHOST_NOT_FOUND;
5985 if (!nodename)
5986 node = NULL;
5987 else if (!nodename[0])
5989 node = hostname = get_hostname();
5990 if (!node) return WSA_NOT_ENOUGH_MEMORY;
5992 else
5993 node = nodename;
5995 /* servname tweak required by OSX and BSD kernels */
5996 if (servname && !servname[0]) servname = "0";
5998 if (hints) {
5999 punixhints = &unixhints;
6001 memset(&unixhints, 0, sizeof(unixhints));
6002 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
6004 /* zero is a wildcard, no need to convert */
6005 if (hints->ai_family)
6006 punixhints->ai_family = convert_af_w2u(hints->ai_family);
6007 if (hints->ai_socktype)
6008 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
6009 if (hints->ai_protocol)
6010 punixhints->ai_protocol = max(convert_proto_w2u(hints->ai_protocol), 0);
6012 if (punixhints->ai_socktype < 0)
6014 SetLastError(WSAESOCKTNOSUPPORT);
6015 HeapFree(GetProcessHeap(), 0, hostname);
6016 return SOCKET_ERROR;
6019 /* windows allows invalid combinations of socket type and protocol, unix does not.
6020 * fix the parameters here to make getaddrinfo call always work */
6021 if (punixhints->ai_protocol == IPPROTO_TCP &&
6022 punixhints->ai_socktype != SOCK_STREAM && punixhints->ai_socktype != SOCK_SEQPACKET)
6023 punixhints->ai_socktype = 0;
6025 else if (punixhints->ai_protocol == IPPROTO_UDP && punixhints->ai_socktype != SOCK_DGRAM)
6026 punixhints->ai_socktype = 0;
6028 else if (IS_IPX_PROTO(punixhints->ai_protocol) && punixhints->ai_socktype != SOCK_DGRAM)
6029 punixhints->ai_socktype = 0;
6032 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
6033 result = getaddrinfo(node, servname, punixhints, &unixaires);
6035 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
6036 HeapFree(GetProcessHeap(), 0, hostname);
6038 if (!result) {
6039 struct addrinfo *xuai = unixaires;
6040 struct WS_addrinfo **xai = res;
6042 *xai = NULL;
6043 while (xuai) {
6044 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
6045 SIZE_T len;
6047 if (!ai)
6048 goto outofmem;
6050 *xai = ai;xai = &ai->ai_next;
6051 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
6052 ai->ai_family = convert_af_u2w(xuai->ai_family);
6053 /* copy whatever was sent in the hints */
6054 if(hints) {
6055 ai->ai_socktype = hints->ai_socktype;
6056 ai->ai_protocol = hints->ai_protocol;
6057 } else {
6058 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
6059 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
6061 if (xuai->ai_canonname) {
6062 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
6063 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
6064 if (!ai->ai_canonname)
6065 goto outofmem;
6066 strcpy(ai->ai_canonname,xuai->ai_canonname);
6068 len = xuai->ai_addrlen;
6069 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
6070 if (!ai->ai_addr)
6071 goto outofmem;
6072 ai->ai_addrlen = len;
6073 do {
6074 int winlen = ai->ai_addrlen;
6076 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
6077 ai->ai_addrlen = winlen;
6078 break;
6080 len = 2*len;
6081 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
6082 if (!ai->ai_addr)
6083 goto outofmem;
6084 ai->ai_addrlen = len;
6085 } while (1);
6086 xuai = xuai->ai_next;
6088 freeaddrinfo(unixaires);
6090 if (TRACE_ON(winsock))
6092 struct WS_addrinfo *ai = *res;
6093 while (ai)
6095 TRACE("=> %p, flags %#x, family %d, type %d, protocol %d, len %ld, name %s, addr %s\n",
6096 ai, ai->ai_flags, ai->ai_family, ai->ai_socktype, ai->ai_protocol, ai->ai_addrlen,
6097 ai->ai_canonname, debugstr_sockaddr(ai->ai_addr));
6098 ai = ai->ai_next;
6101 } else
6102 result = convert_eai_u2w(result);
6104 SetLastError(result);
6105 return result;
6107 outofmem:
6108 if (*res) WS_freeaddrinfo(*res);
6109 if (unixaires) freeaddrinfo(unixaires);
6110 return WSA_NOT_ENOUGH_MEMORY;
6111 #else
6112 FIXME("getaddrinfo() failed, not found during buildtime.\n");
6113 return EAI_FAIL;
6114 #endif
6117 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
6119 struct WS_addrinfoW *ret;
6121 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
6122 ret->ai_flags = ai->ai_flags;
6123 ret->ai_family = ai->ai_family;
6124 ret->ai_socktype = ai->ai_socktype;
6125 ret->ai_protocol = ai->ai_protocol;
6126 ret->ai_addrlen = ai->ai_addrlen;
6127 ret->ai_canonname = NULL;
6128 ret->ai_addr = NULL;
6129 ret->ai_next = NULL;
6130 if (ai->ai_canonname)
6132 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
6133 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR))))
6135 HeapFree(GetProcessHeap(), 0, ret);
6136 return NULL;
6138 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
6140 if (ai->ai_addr)
6142 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, ai->ai_addrlen)))
6144 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
6145 HeapFree(GetProcessHeap(), 0, ret);
6146 return NULL;
6148 memcpy(ret->ai_addr, ai->ai_addr, ai->ai_addrlen);
6150 return ret;
6153 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
6155 struct WS_addrinfoW *ret, *infoW;
6157 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
6158 while (info->ai_next)
6160 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
6162 FreeAddrInfoW(ret);
6163 return NULL;
6165 infoW = infoW->ai_next;
6166 info = info->ai_next;
6168 return ret;
6171 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
6173 struct WS_addrinfo *ret;
6175 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
6176 ret->ai_flags = ai->ai_flags;
6177 ret->ai_family = ai->ai_family;
6178 ret->ai_socktype = ai->ai_socktype;
6179 ret->ai_protocol = ai->ai_protocol;
6180 ret->ai_addrlen = ai->ai_addrlen;
6181 ret->ai_canonname = NULL;
6182 ret->ai_addr = NULL;
6183 ret->ai_next = NULL;
6184 if (ai->ai_canonname)
6186 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
6187 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
6189 HeapFree(GetProcessHeap(), 0, ret);
6190 return NULL;
6192 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
6194 if (ai->ai_addr)
6196 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
6198 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
6199 HeapFree(GetProcessHeap(), 0, ret);
6200 return NULL;
6202 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
6204 return ret;
6207 /***********************************************************************
6208 * GetAddrInfoW (WS2_32.@)
6210 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
6212 int ret, len;
6213 char *nodenameA = NULL, *servnameA = NULL;
6214 struct WS_addrinfo *resA, *hintsA = NULL;
6216 *res = NULL;
6217 if (nodename)
6219 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
6220 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
6221 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
6223 if (servname)
6225 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
6226 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
6228 HeapFree(GetProcessHeap(), 0, nodenameA);
6229 return EAI_MEMORY;
6231 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
6234 if (hints) hintsA = addrinfo_WtoA(hints);
6235 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
6236 WS_freeaddrinfo(hintsA);
6238 if (!ret)
6240 *res = addrinfo_list_AtoW(resA);
6241 WS_freeaddrinfo(resA);
6244 HeapFree(GetProcessHeap(), 0, nodenameA);
6245 HeapFree(GetProcessHeap(), 0, servnameA);
6246 return ret;
6249 /***********************************************************************
6250 * FreeAddrInfoW (WS2_32.@)
6252 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
6254 while (ai)
6256 ADDRINFOW *next;
6257 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
6258 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
6259 next = ai->ai_next;
6260 HeapFree(GetProcessHeap(), 0, ai);
6261 ai = next;
6265 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
6266 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
6268 #ifdef HAVE_GETNAMEINFO
6269 int ret;
6270 union generic_unix_sockaddr sa_u;
6271 unsigned int size;
6273 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
6274 serv, servlen, flags);
6276 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
6277 if (!size)
6279 SetLastError(WSAEFAULT);
6280 return WSA_NOT_ENOUGH_MEMORY;
6282 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
6283 return convert_eai_u2w(ret);
6284 #else
6285 FIXME("getnameinfo() failed, not found during buildtime.\n");
6286 return EAI_FAIL;
6287 #endif
6290 int WINAPI GetNameInfoW(const SOCKADDR *sa, WS_socklen_t salen, PWCHAR host,
6291 DWORD hostlen, PWCHAR serv, DWORD servlen, INT flags)
6293 int ret;
6294 char *hostA = NULL, *servA = NULL;
6296 if (host && (!(hostA = HeapAlloc(GetProcessHeap(), 0, hostlen)))) return EAI_MEMORY;
6297 if (serv && (!(servA = HeapAlloc(GetProcessHeap(), 0, servlen))))
6299 HeapFree(GetProcessHeap(), 0, hostA);
6300 return EAI_MEMORY;
6303 ret = WS_getnameinfo(sa, salen, hostA, hostlen, servA, servlen, flags);
6304 if (!ret)
6306 if (host) MultiByteToWideChar(CP_ACP, 0, hostA, -1, host, hostlen);
6307 if (serv) MultiByteToWideChar(CP_ACP, 0, servA, -1, serv, servlen);
6310 HeapFree(GetProcessHeap(), 0, hostA);
6311 HeapFree(GetProcessHeap(), 0, servA);
6312 return ret;
6315 /***********************************************************************
6316 * getservbyport (WS2_32.56)
6318 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
6320 struct WS_servent* retval = NULL;
6321 #ifdef HAVE_GETSERVBYPORT
6322 struct servent* serv;
6323 char *proto_str = NULL;
6325 if (proto && *proto)
6327 if (!(proto_str = strdup_lower(proto))) return NULL;
6329 EnterCriticalSection( &csWSgetXXXbyYYY );
6330 if( (serv = getservbyport(port, proto_str)) != NULL ) {
6331 retval = WS_dup_se(serv);
6333 else SetLastError(WSANO_DATA);
6334 LeaveCriticalSection( &csWSgetXXXbyYYY );
6335 HeapFree( GetProcessHeap(), 0, proto_str );
6336 #endif
6337 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
6338 return retval;
6342 /***********************************************************************
6343 * gethostname (WS2_32.57)
6345 int WINAPI WS_gethostname(char *name, int namelen)
6347 char buf[256];
6348 int len;
6350 TRACE("name %p, len %d\n", name, namelen);
6352 if (!name)
6354 SetLastError(WSAEFAULT);
6355 return SOCKET_ERROR;
6358 if (gethostname(buf, sizeof(buf)) != 0)
6360 SetLastError(wsaErrno());
6361 return SOCKET_ERROR;
6364 TRACE("<- '%s'\n", buf);
6365 len = strlen(buf);
6366 if (len > 15)
6367 WARN("Windows supports NetBIOS name length up to 15 bytes!\n");
6368 if (namelen <= len)
6370 SetLastError(WSAEFAULT);
6371 WARN("<- not enough space for hostname, required %d, got %d!\n", len + 1, namelen);
6372 return SOCKET_ERROR;
6374 strcpy(name, buf);
6375 return 0;
6379 /* ------------------------------------- Windows sockets extensions -- *
6381 * ------------------------------------------------------------------- */
6383 /***********************************************************************
6384 * WSAEnumNetworkEvents (WS2_32.36)
6386 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
6388 int ret;
6389 int i;
6390 int errors[FD_MAX_EVENTS];
6392 TRACE("%04lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
6394 SERVER_START_REQ( get_socket_event )
6396 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6397 req->service = TRUE;
6398 req->c_event = wine_server_obj_handle( hEvent );
6399 wine_server_set_reply( req, errors, sizeof(errors) );
6400 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
6402 SERVER_END_REQ;
6403 if (!ret)
6405 for (i = 0; i < FD_MAX_EVENTS; i++)
6406 lpEvent->iErrorCode[i] = NtStatusToWSAError(errors[i]);
6407 return 0;
6409 SetLastError(WSAEINVAL);
6410 return SOCKET_ERROR;
6413 /***********************************************************************
6414 * WSAEventSelect (WS2_32.39)
6416 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
6418 int ret;
6420 TRACE("%04lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
6422 SERVER_START_REQ( set_socket_event )
6424 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6425 req->mask = lEvent;
6426 req->event = wine_server_obj_handle( hEvent );
6427 req->window = 0;
6428 req->msg = 0;
6429 ret = wine_server_call( req );
6431 SERVER_END_REQ;
6432 if (!ret) return 0;
6433 SetLastError(WSAEINVAL);
6434 return SOCKET_ERROR;
6437 /**********************************************************************
6438 * WSAGetOverlappedResult (WS2_32.40)
6440 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
6441 LPDWORD lpcbTransfer, BOOL fWait,
6442 LPDWORD lpdwFlags )
6444 NTSTATUS status;
6446 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
6447 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
6449 if ( lpOverlapped == NULL )
6451 ERR( "Invalid pointer\n" );
6452 SetLastError(WSA_INVALID_PARAMETER);
6453 return FALSE;
6456 status = lpOverlapped->Internal;
6457 if (status == STATUS_PENDING)
6459 if (!fWait)
6461 SetLastError( WSA_IO_INCOMPLETE );
6462 return FALSE;
6465 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
6466 INFINITE ) == WAIT_FAILED)
6467 return FALSE;
6468 status = lpOverlapped->Internal;
6471 if ( lpcbTransfer )
6472 *lpcbTransfer = lpOverlapped->InternalHigh;
6474 if ( lpdwFlags )
6475 *lpdwFlags = lpOverlapped->u.s.Offset;
6477 if (status) SetLastError( RtlNtStatusToDosError(status) );
6478 return !status;
6482 /***********************************************************************
6483 * WSAAsyncSelect (WS2_32.101)
6485 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
6487 int ret;
6489 TRACE("%04lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
6491 SERVER_START_REQ( set_socket_event )
6493 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6494 req->mask = lEvent;
6495 req->event = 0;
6496 req->window = wine_server_user_handle( hWnd );
6497 req->msg = uMsg;
6498 ret = wine_server_call( req );
6500 SERVER_END_REQ;
6501 if (!ret) return 0;
6502 SetLastError(WSAEINVAL);
6503 return SOCKET_ERROR;
6506 /***********************************************************************
6507 * WSACreateEvent (WS2_32.31)
6510 WSAEVENT WINAPI WSACreateEvent(void)
6512 /* Create a manual-reset event, with initial state: unsignaled */
6513 TRACE("\n");
6515 return CreateEventW(NULL, TRUE, FALSE, NULL);
6518 /***********************************************************************
6519 * WSACloseEvent (WS2_32.29)
6522 BOOL WINAPI WSACloseEvent(WSAEVENT event)
6524 TRACE ("event=%p\n", event);
6526 return CloseHandle(event);
6529 /***********************************************************************
6530 * WSASocketA (WS2_32.78)
6533 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
6534 LPWSAPROTOCOL_INFOA lpProtocolInfo,
6535 GROUP g, DWORD dwFlags)
6537 INT len;
6538 WSAPROTOCOL_INFOW info;
6540 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
6541 af, type, protocol, lpProtocolInfo, g, dwFlags);
6543 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
6545 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
6546 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
6547 info.szProtocol, WSAPROTOCOL_LEN + 1);
6549 if (!len)
6551 SetLastError(WSAEINVAL);
6552 return SOCKET_ERROR;
6555 return WSASocketW(af, type, protocol, &info, g, dwFlags);
6558 /***********************************************************************
6559 * WSASocketW (WS2_32.79)
6562 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
6563 LPWSAPROTOCOL_INFOW lpProtocolInfo,
6564 GROUP g, DWORD dwFlags)
6566 SOCKET ret;
6567 DWORD err;
6568 int unixaf, unixtype, ipxptype = -1;
6571 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
6572 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
6575 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
6576 af, type, protocol, lpProtocolInfo, g, dwFlags );
6578 if (!num_startup)
6580 err = WSANOTINITIALISED;
6581 goto done;
6584 /* hack for WSADuplicateSocket */
6585 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
6586 ret = lpProtocolInfo->dwServiceFlags3;
6587 TRACE("\tgot duplicate %04lx\n", ret);
6588 return ret;
6591 if (lpProtocolInfo)
6593 if (af == FROM_PROTOCOL_INFO || !af)
6594 af = lpProtocolInfo->iAddressFamily;
6595 if (type == FROM_PROTOCOL_INFO || !type)
6596 type = lpProtocolInfo->iSocketType;
6597 if (protocol == FROM_PROTOCOL_INFO || !protocol)
6598 protocol = lpProtocolInfo->iProtocol;
6601 if (!type && (af || protocol))
6603 int autoproto = protocol;
6604 WSAPROTOCOL_INFOW infow;
6606 /* default to the first valid protocol */
6607 if (!autoproto)
6608 autoproto = valid_protocols[0];
6609 else if(IS_IPX_PROTO(autoproto))
6610 autoproto = WS_NSPROTO_IPX;
6612 if (WS_EnterSingleProtocolW(autoproto, &infow))
6614 type = infow.iSocketType;
6616 /* after win2003 it's no longer possible to pass AF_UNSPEC
6617 using the protocol info struct */
6618 if (!lpProtocolInfo && af == WS_AF_UNSPEC)
6619 af = infow.iAddressFamily;
6624 Windows has an extension to the IPX protocol that allows one to create sockets
6625 and set the IPX packet type at the same time, to do that a caller will use
6626 a protocol like NSPROTO_IPX + <PACKET TYPE>
6628 if (IS_IPX_PROTO(protocol))
6629 ipxptype = protocol - WS_NSPROTO_IPX;
6631 /* convert the socket family, type and protocol */
6632 unixaf = convert_af_w2u(af);
6633 unixtype = convert_socktype_w2u(type);
6634 protocol = convert_proto_w2u(protocol);
6635 if (unixaf == AF_UNSPEC) unixaf = -1;
6637 /* filter invalid parameters */
6638 if (protocol < 0)
6640 /* the type could not be converted */
6641 if (type && unixtype < 0)
6643 err = WSAESOCKTNOSUPPORT;
6644 goto done;
6647 err = WSAEPROTONOSUPPORT;
6648 goto done;
6650 if (unixaf < 0)
6652 /* both family and protocol can't be invalid */
6653 if (protocol <= 0)
6655 err = WSAEINVAL;
6656 goto done;
6659 /* family could not be converted and neither socket type */
6660 if (unixtype < 0 && af >= 0)
6663 err = WSAESOCKTNOSUPPORT;
6664 goto done;
6667 err = WSAEAFNOSUPPORT;
6668 goto done;
6671 SERVER_START_REQ( create_socket )
6673 req->family = unixaf;
6674 req->type = unixtype;
6675 req->protocol = protocol;
6676 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
6677 req->attributes = (dwFlags & WSA_FLAG_NO_HANDLE_INHERIT) ? 0 : OBJ_INHERIT;
6678 req->flags = dwFlags & ~WSA_FLAG_NO_HANDLE_INHERIT;
6679 set_error( wine_server_call( req ) );
6680 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
6682 SERVER_END_REQ;
6683 if (ret)
6685 TRACE("\tcreated %04lx\n", ret );
6686 if (ipxptype > 0)
6687 set_ipx_packettype(ret, ipxptype);
6688 return ret;
6691 err = GetLastError();
6692 if (err == WSAEACCES) /* raw socket denied */
6694 if (type == SOCK_RAW)
6695 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
6696 else
6697 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
6699 else
6701 /* invalid combination of valid parameters, like SOCK_STREAM + IPPROTO_UDP */
6702 if (err == WSAEINVAL)
6703 err = WSAESOCKTNOSUPPORT;
6704 else if (err == WSAEOPNOTSUPP)
6705 err = WSAEPROTONOSUPPORT;
6708 done:
6709 WARN("\t\tfailed, error %d!\n", err);
6710 SetLastError(err);
6711 return INVALID_SOCKET;
6714 /***********************************************************************
6715 * WSAJoinLeaf (WS2_32.58)
6718 SOCKET WINAPI WSAJoinLeaf(
6719 SOCKET s,
6720 const struct WS_sockaddr *addr,
6721 int addrlen,
6722 LPWSABUF lpCallerData,
6723 LPWSABUF lpCalleeData,
6724 LPQOS lpSQOS,
6725 LPQOS lpGQOS,
6726 DWORD dwFlags)
6728 FIXME("stub.\n");
6729 return INVALID_SOCKET;
6732 /***********************************************************************
6733 * __WSAFDIsSet (WS2_32.151)
6735 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
6737 int i = set->fd_count, ret = 0;
6739 while (i--)
6740 if (set->fd_array[i] == s)
6742 ret = 1;
6743 break;
6746 TRACE("(socket %04lx, fd_set %p, count %i) <- %d\n", s, set, set->fd_count, ret);
6747 return ret;
6750 /***********************************************************************
6751 * WSAIsBlocking (WS2_32.114)
6753 BOOL WINAPI WSAIsBlocking(void)
6755 /* By default WinSock should set all its sockets to non-blocking mode
6756 * and poll in PeekMessage loop when processing "blocking" ones. This
6757 * function is supposed to tell if the program is in this loop. Our
6758 * blocking calls are truly blocking so we always return FALSE.
6760 * Note: It is allowed to call this function without prior WSAStartup().
6763 TRACE("\n");
6764 return FALSE;
6767 /***********************************************************************
6768 * WSACancelBlockingCall (WS2_32.113)
6770 INT WINAPI WSACancelBlockingCall(void)
6772 TRACE("\n");
6773 return 0;
6776 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
6778 FIXME("How was this called?\n");
6779 return x();
6783 /***********************************************************************
6784 * WSASetBlockingHook (WS2_32.109)
6786 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
6788 FARPROC prev = blocking_hook;
6789 blocking_hook = lpBlockFunc;
6790 TRACE("hook %p\n", lpBlockFunc);
6791 return prev;
6795 /***********************************************************************
6796 * WSAUnhookBlockingHook (WS2_32.110)
6798 INT WINAPI WSAUnhookBlockingHook(void)
6800 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
6801 return 0;
6805 /* ----------------------------------- end of API stuff */
6807 /* ----------------------------------- helper functions -
6809 * TODO: Merge WS_dup_..() stuff into one function that
6810 * would operate with a generic structure containing internal
6811 * pointers (via a template of some kind).
6814 static int list_size(char** l, int item_size)
6816 int i,j = 0;
6817 if(l)
6818 { for(i=0;l[i];i++)
6819 j += (item_size) ? item_size : strlen(l[i]) + 1;
6820 j += (i + 1) * sizeof(char*); }
6821 return j;
6824 static int list_dup(char** l_src, char** l_to, int item_size)
6826 char *p;
6827 int i;
6829 for (i = 0; l_src[i]; i++) ;
6830 p = (char *)(l_to + i + 1);
6831 for (i = 0; l_src[i]; i++)
6833 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
6834 memcpy(p, l_src[i], count);
6835 l_to[i] = p;
6836 p += count;
6838 l_to[i] = NULL;
6839 return p - (char *)l_to;
6842 /* ----- hostent */
6844 /* create a hostent entry
6846 * Creates the entry with enough memory for the name, aliases
6847 * addresses, and the address pointers. Also copies the name
6848 * and sets up all the pointers.
6850 * NOTE: The alias and address lists must be allocated with room
6851 * for the NULL item terminating the list. This is true even if
6852 * the list has no items ("aliases" and "addresses" must be
6853 * at least "1", a truly empty list is invalid).
6855 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length)
6857 struct WS_hostent *p_to;
6858 char *p;
6859 int size = (sizeof(struct WS_hostent) +
6860 strlen(name) + 1 +
6861 sizeof(char *) * aliases +
6862 aliases_size +
6863 sizeof(char *) * addresses +
6864 address_length * (addresses - 1)), i;
6866 if (!(p_to = check_buffer_he(size))) return NULL;
6867 memset(p_to, 0, size);
6869 /* Use the memory in the same way winsock does.
6870 * First set the pointer for aliases, second set the pointers for addresses.
6871 * Third fill the addresses indexes, fourth jump aliases names size.
6872 * Fifth fill the hostname.
6873 * NOTE: This method is valid for OS version's >= XP.
6875 p = (char *)(p_to + 1);
6876 p_to->h_aliases = (char **)p;
6877 p += sizeof(char *)*aliases;
6879 p_to->h_addr_list = (char **)p;
6880 p += sizeof(char *)*addresses;
6882 for (i = 0, addresses--; i < addresses; i++, p += address_length)
6883 p_to->h_addr_list[i] = p;
6885 /* NOTE: h_aliases must be filled in manually because we don't know each string
6886 * size, leave these pointers NULL (already set to NULL by memset earlier).
6888 p += aliases_size;
6890 p_to->h_name = p;
6891 strcpy(p, name);
6893 return p_to;
6896 /* duplicate hostent entry
6897 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
6898 * Ditto for protoent and servent.
6900 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
6902 int i, addresses = 0, alias_size = 0;
6903 struct WS_hostent *p_to;
6904 char *p;
6906 for( i = 0; p_he->h_aliases[i]; i++) alias_size += strlen(p_he->h_aliases[i]) + 1;
6907 while (p_he->h_addr_list[addresses]) addresses++;
6909 p_to = WS_create_he(p_he->h_name, i + 1, alias_size, addresses + 1, p_he->h_length);
6911 if (!p_to) return NULL;
6912 p_to->h_addrtype = convert_af_u2w(p_he->h_addrtype);
6913 p_to->h_length = p_he->h_length;
6915 for(i = 0, p = p_to->h_addr_list[0]; p_he->h_addr_list[i]; i++, p += p_to->h_length)
6916 memcpy(p, p_he->h_addr_list[i], p_to->h_length);
6918 /* Fill the aliases after the IP data */
6919 for(i = 0; p_he->h_aliases[i]; i++)
6921 p_to->h_aliases[i] = p;
6922 strcpy(p, p_he->h_aliases[i]);
6923 p += strlen(p) + 1;
6926 return p_to;
6929 /* ----- protoent */
6931 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
6933 char *p;
6934 struct WS_protoent *p_to;
6936 int size = (sizeof(*p_pe) +
6937 strlen(p_pe->p_name) + 1 +
6938 list_size(p_pe->p_aliases, 0));
6940 if (!(p_to = check_buffer_pe(size))) return NULL;
6941 p_to->p_proto = p_pe->p_proto;
6943 p = (char *)(p_to + 1);
6944 p_to->p_name = p;
6945 strcpy(p, p_pe->p_name);
6946 p += strlen(p) + 1;
6948 p_to->p_aliases = (char **)p;
6949 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
6950 return p_to;
6953 /* ----- servent */
6955 static struct WS_servent *WS_dup_se(const struct servent* p_se)
6957 char *p;
6958 struct WS_servent *p_to;
6960 int size = (sizeof(*p_se) +
6961 strlen(p_se->s_proto) + 1 +
6962 strlen(p_se->s_name) + 1 +
6963 list_size(p_se->s_aliases, 0));
6965 if (!(p_to = check_buffer_se(size))) return NULL;
6966 p_to->s_port = p_se->s_port;
6968 p = (char *)(p_to + 1);
6969 p_to->s_name = p;
6970 strcpy(p, p_se->s_name);
6971 p += strlen(p) + 1;
6973 p_to->s_proto = p;
6974 strcpy(p, p_se->s_proto);
6975 p += strlen(p) + 1;
6977 p_to->s_aliases = (char **)p;
6978 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
6979 return p_to;
6983 /***********************************************************************
6984 * WSARecv (WS2_32.67)
6986 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6987 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
6988 LPWSAOVERLAPPED lpOverlapped,
6989 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
6991 return WS2_recv_base(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
6992 NULL, NULL, lpOverlapped, lpCompletionRoutine, NULL);
6995 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6996 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
6997 struct WS_sockaddr *lpFrom,
6998 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
6999 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
7000 LPWSABUF lpControlBuffer )
7002 unsigned int i, options;
7003 int n, fd, err, overlapped, flags;
7004 struct ws2_async *wsa = NULL, localwsa;
7005 BOOL is_blocking;
7006 DWORD timeout_start = GetTickCount();
7007 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
7009 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
7010 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
7011 (lpFromlen ? *lpFromlen : -1),
7012 lpOverlapped, lpCompletionRoutine);
7014 fd = get_sock_fd( s, FILE_READ_DATA, &options );
7015 TRACE( "fd=%d, options=%x\n", fd, options );
7017 if (fd == -1) return SOCKET_ERROR;
7019 if (*lpFlags & WS_MSG_OOB)
7021 /* It's invalid to receive OOB data from an OOBINLINED socket
7022 * as OOB data is turned into normal data. */
7023 i = sizeof(n);
7024 if (!getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, (char*) &n, &i) && n)
7026 err = WSAEINVAL;
7027 goto error;
7031 overlapped = (lpOverlapped || lpCompletionRoutine) &&
7032 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
7033 if (overlapped || dwBufferCount > 1)
7035 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[dwBufferCount]))))
7037 err = WSAEFAULT;
7038 goto error;
7041 else
7042 wsa = &localwsa;
7044 wsa->hSocket = SOCKET2HANDLE(s);
7045 wsa->flags = *lpFlags;
7046 wsa->lpFlags = lpFlags;
7047 wsa->addr = lpFrom;
7048 wsa->addrlen.ptr = lpFromlen;
7049 wsa->control = lpControlBuffer;
7050 wsa->n_iovecs = dwBufferCount;
7051 wsa->first_iovec = 0;
7052 for (i = 0; i < dwBufferCount; i++)
7054 /* check buffer first to trigger write watches */
7055 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
7057 err = WSAEFAULT;
7058 goto error;
7060 wsa->iovec[i].iov_base = lpBuffers[i].buf;
7061 wsa->iovec[i].iov_len = lpBuffers[i].len;
7064 flags = convert_flags(wsa->flags);
7065 for (;;)
7067 n = WS2_recv( fd, wsa, flags );
7068 if (n == -1)
7070 /* Unix-like systems return EINVAL when attempting to read OOB data from
7071 * an empty socket buffer, convert that to a Windows expected return. */
7072 if ((flags & MSG_OOB) && errno == EINVAL)
7073 errno = EWOULDBLOCK;
7075 if (errno != EAGAIN)
7077 int loc_errno = errno;
7078 err = wsaErrno();
7079 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
7080 goto error;
7083 else if (lpNumberOfBytesRecvd) *lpNumberOfBytesRecvd = n;
7085 if (overlapped)
7087 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
7089 wsa->user_overlapped = lpOverlapped;
7090 wsa->completion_func = lpCompletionRoutine;
7091 release_sock_fd( s, fd );
7093 if (n == -1)
7095 iosb->u.Status = STATUS_PENDING;
7096 iosb->Information = 0;
7098 SERVER_START_REQ( register_async )
7100 req->type = ASYNC_TYPE_READ;
7101 req->async.handle = wine_server_obj_handle( wsa->hSocket );
7102 req->async.callback = wine_server_client_ptr( WS2_async_recv );
7103 req->async.iosb = wine_server_client_ptr( iosb );
7104 req->async.arg = wine_server_client_ptr( wsa );
7105 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
7106 req->async.cvalue = cvalue;
7107 err = wine_server_call( req );
7109 SERVER_END_REQ;
7111 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
7112 SetLastError(NtStatusToWSAError( err ));
7113 return SOCKET_ERROR;
7116 iosb->u.Status = STATUS_SUCCESS;
7117 iosb->Information = n;
7118 if (!wsa->completion_func)
7120 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
7121 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
7122 HeapFree( GetProcessHeap(), 0, wsa );
7124 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
7125 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
7126 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7127 return 0;
7130 if (n != -1) break;
7132 if ((err = _is_blocking( s, &is_blocking )))
7134 err = NtStatusToWSAError( err );
7135 goto error;
7138 if ( is_blocking )
7140 struct pollfd pfd;
7141 int poll_timeout = -1;
7142 INT64 timeout = get_rcvsnd_timeo(fd, TRUE);
7144 if (timeout)
7146 timeout -= GetTickCount() - timeout_start;
7147 if (timeout < 0) poll_timeout = 0;
7148 else poll_timeout = timeout <= INT_MAX ? timeout : INT_MAX;
7151 pfd.fd = fd;
7152 pfd.events = POLLIN;
7153 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
7155 if (!poll_timeout || !poll( &pfd, 1, poll_timeout ))
7157 err = WSAETIMEDOUT;
7158 /* a timeout is not fatal */
7159 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7160 goto error;
7163 else
7165 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7166 err = WSAEWOULDBLOCK;
7167 goto error;
7171 TRACE(" -> %i bytes\n", n);
7172 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
7173 release_sock_fd( s, fd );
7174 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7175 SetLastError(ERROR_SUCCESS);
7177 return 0;
7179 error:
7180 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
7181 release_sock_fd( s, fd );
7182 WARN(" -> ERROR %d\n", err);
7183 SetLastError( err );
7184 return SOCKET_ERROR;
7187 /***********************************************************************
7188 * WSARecvFrom (WS2_32.69)
7190 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
7191 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
7192 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
7193 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
7196 return WS2_recv_base( s, lpBuffers, dwBufferCount,
7197 lpNumberOfBytesRecvd, lpFlags,
7198 lpFrom, lpFromlen,
7199 lpOverlapped, lpCompletionRoutine, NULL );
7202 /***********************************************************************
7203 * WSCInstallProvider (WS2_32.88)
7205 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
7206 LPCWSTR lpszProviderDllPath,
7207 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
7208 DWORD dwNumberOfEntries,
7209 LPINT lpErrno )
7211 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
7212 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
7213 dwNumberOfEntries, lpErrno);
7214 *lpErrno = 0;
7215 return 0;
7219 /***********************************************************************
7220 * WSCDeinstallProvider (WS2_32.83)
7222 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
7224 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
7225 *lpErrno = 0;
7226 return 0;
7230 /***********************************************************************
7231 * WSAAccept (WS2_32.26)
7233 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
7234 LPCONDITIONPROC lpfnCondition, DWORD_PTR dwCallbackData)
7237 int ret = 0, size;
7238 WSABUF CallerId, CallerData, CalleeId, CalleeData;
7239 /* QOS SQOS, GQOS; */
7240 GROUP g;
7241 SOCKET cs;
7242 SOCKADDR src_addr, dst_addr;
7244 TRACE("socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
7245 s, addr, addrlen, lpfnCondition, dwCallbackData);
7247 cs = WS_accept(s, addr, addrlen);
7248 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
7249 if (!lpfnCondition) return cs;
7251 if (addr && addrlen)
7253 CallerId.buf = (char *)addr;
7254 CallerId.len = *addrlen;
7256 else
7258 size = sizeof(src_addr);
7259 WS_getpeername(cs, &src_addr, &size);
7260 CallerId.buf = (char *)&src_addr;
7261 CallerId.len = size;
7263 CallerData.buf = NULL;
7264 CallerData.len = 0;
7266 size = sizeof(dst_addr);
7267 WS_getsockname(cs, &dst_addr, &size);
7269 CalleeId.buf = (char *)&dst_addr;
7270 CalleeId.len = sizeof(dst_addr);
7272 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
7273 &CalleeId, &CalleeData, &g, dwCallbackData);
7275 switch (ret)
7277 case CF_ACCEPT:
7278 return cs;
7279 case CF_DEFER:
7280 SERVER_START_REQ( set_socket_deferred )
7282 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
7283 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
7284 if ( !wine_server_call_err ( req ) )
7286 SetLastError( WSATRY_AGAIN );
7287 WS_closesocket( cs );
7290 SERVER_END_REQ;
7291 return SOCKET_ERROR;
7292 case CF_REJECT:
7293 WS_closesocket(cs);
7294 SetLastError(WSAECONNREFUSED);
7295 return SOCKET_ERROR;
7296 default:
7297 FIXME("Unknown return type from Condition function\n");
7298 SetLastError(WSAENOTSOCK);
7299 return SOCKET_ERROR;
7303 /***********************************************************************
7304 * WSADuplicateSocketA (WS2_32.32)
7306 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
7308 return WS_DuplicateSocket(FALSE, s, dwProcessId, (LPWSAPROTOCOL_INFOW) lpProtocolInfo);
7311 /***********************************************************************
7312 * WSADuplicateSocketW (WS2_32.33)
7314 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
7316 return WS_DuplicateSocket(TRUE, s, dwProcessId, lpProtocolInfo);
7319 /***********************************************************************
7320 * WSAInstallServiceClassA (WS2_32.48)
7322 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
7324 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
7325 SetLastError(WSAEACCES);
7326 return SOCKET_ERROR;
7329 /***********************************************************************
7330 * WSAInstallServiceClassW (WS2_32.49)
7332 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
7334 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
7335 SetLastError(WSAEACCES);
7336 return SOCKET_ERROR;
7339 /***********************************************************************
7340 * WSARemoveServiceClass (WS2_32.70)
7342 int WINAPI WSARemoveServiceClass(LPGUID info)
7344 FIXME("Request to remove service %p\n",info);
7345 SetLastError(WSATYPE_NOT_FOUND);
7346 return SOCKET_ERROR;
7349 /***********************************************************************
7350 * inet_ntop (WS2_32.@)
7352 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
7354 #ifdef HAVE_INET_NTOP
7355 struct WS_in6_addr *in6;
7356 struct WS_in_addr *in;
7357 PCSTR pdst;
7359 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
7360 if (!buffer)
7362 SetLastError( STATUS_INVALID_PARAMETER );
7363 return NULL;
7366 switch (family)
7368 case WS_AF_INET:
7370 in = addr;
7371 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
7372 break;
7374 case WS_AF_INET6:
7376 in6 = addr;
7377 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
7378 break;
7380 default:
7381 SetLastError( WSAEAFNOSUPPORT );
7382 return NULL;
7385 if (!pdst) SetLastError( STATUS_INVALID_PARAMETER );
7386 return pdst;
7387 #else
7388 FIXME( "not supported on this platform\n" );
7389 SetLastError( WSAEAFNOSUPPORT );
7390 return NULL;
7391 #endif
7394 /***********************************************************************
7395 * inet_pton (WS2_32.@)
7397 INT WINAPI WS_inet_pton( INT family, PCSTR addr, PVOID buffer)
7399 #ifdef HAVE_INET_PTON
7400 int unixaf, ret;
7402 TRACE("family %d, addr '%s', buffer (%p)\n", family, addr ? addr : "(null)", buffer);
7404 if (!addr || !buffer)
7406 SetLastError(WSAEFAULT);
7407 return SOCKET_ERROR;
7410 unixaf = convert_af_w2u(family);
7411 if (unixaf != AF_INET && unixaf != AF_INET6)
7413 SetLastError(WSAEAFNOSUPPORT);
7414 return SOCKET_ERROR;
7417 ret = inet_pton(unixaf, addr, buffer);
7418 if (ret == -1) SetLastError(wsaErrno());
7419 return ret;
7420 #else
7421 FIXME( "not supported on this platform\n" );
7422 SetLastError( WSAEAFNOSUPPORT );
7423 return SOCKET_ERROR;
7424 #endif
7428 /***********************************************************************
7429 * WSAStringToAddressA (WS2_32.80)
7431 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
7432 INT AddressFamily,
7433 LPWSAPROTOCOL_INFOA lpProtocolInfo,
7434 LPSOCKADDR lpAddress,
7435 LPINT lpAddressLength)
7437 INT res=0;
7438 LPSTR workBuffer=NULL,ptrPort;
7440 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
7441 lpProtocolInfo, lpAddress, lpAddressLength );
7443 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
7445 if (!AddressString)
7447 SetLastError(WSAEINVAL);
7448 return SOCKET_ERROR;
7451 if (lpProtocolInfo)
7452 FIXME("ProtocolInfo not implemented.\n");
7454 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
7455 strlen(AddressString) + 1);
7456 if (!workBuffer)
7458 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7459 return SOCKET_ERROR;
7462 strcpy(workBuffer, AddressString);
7464 switch(AddressFamily)
7466 case WS_AF_INET:
7468 struct in_addr inetaddr;
7470 /* If lpAddressLength is too small, tell caller the size we need */
7471 if (*lpAddressLength < sizeof(SOCKADDR_IN))
7473 *lpAddressLength = sizeof(SOCKADDR_IN);
7474 res = WSAEFAULT;
7475 break;
7477 *lpAddressLength = sizeof(SOCKADDR_IN);
7478 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
7480 ((LPSOCKADDR_IN)lpAddress)->sin_family = WS_AF_INET;
7482 ptrPort = strchr(workBuffer, ':');
7483 if(ptrPort)
7485 /* User may have entered an IPv6 and asked to parse as IPv4 */
7486 if(strchr(ptrPort + 1, ':'))
7488 res = WSAEINVAL;
7489 break;
7491 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
7492 *ptrPort = '\0';
7494 else
7496 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
7499 if(inet_aton(workBuffer, &inetaddr) > 0)
7501 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
7502 res = 0;
7504 else
7505 res = WSAEINVAL;
7507 break;
7510 case WS_AF_INET6:
7512 struct in6_addr inetaddr;
7513 /* If lpAddressLength is too small, tell caller the size we need */
7514 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
7516 *lpAddressLength = sizeof(SOCKADDR_IN6);
7517 res = WSAEFAULT;
7518 break;
7520 #ifdef HAVE_INET_PTON
7521 *lpAddressLength = sizeof(SOCKADDR_IN6);
7522 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
7524 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
7526 /* This one is a bit tricky. An IPv6 address contains colons, so the
7527 * check from IPv4 doesn't work like that. However, IPv6 addresses that
7528 * contain a port are written with braces like [fd12:3456:7890::1]:12345
7529 * so what we will do is to look for ']', check if the next char is a
7530 * colon, and if it is, parse the port as in IPv4. */
7532 ptrPort = strchr(workBuffer, ']');
7533 if(ptrPort && *(++ptrPort) == ':')
7535 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort+1));
7536 *ptrPort = '\0';
7538 else
7540 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
7543 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
7545 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
7546 sizeof(struct in6_addr));
7547 res = 0;
7549 else
7550 #endif /* HAVE_INET_PTON */
7551 res = WSAEINVAL;
7553 break;
7555 default:
7556 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
7557 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
7558 res = WSAEINVAL;
7561 HeapFree(GetProcessHeap(), 0, workBuffer);
7563 if (!res) return 0;
7564 SetLastError(res);
7565 return SOCKET_ERROR;
7568 /***********************************************************************
7569 * WSAStringToAddressW (WS2_32.81)
7571 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
7572 * If this should be the case, it would be required to map these digits
7573 * to Unicode digits (0-9) using FoldString first.
7575 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
7576 INT AddressFamily,
7577 LPWSAPROTOCOL_INFOW lpProtocolInfo,
7578 LPSOCKADDR lpAddress,
7579 LPINT lpAddressLength)
7581 INT sBuffer,res=0;
7582 LPSTR workBuffer=NULL;
7583 WSAPROTOCOL_INFOA infoA;
7584 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
7586 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
7587 lpAddress, lpAddressLength );
7589 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
7591 /* if ProtocolInfo is available - convert to ANSI variant */
7592 if (lpProtocolInfo)
7594 lpProtoInfoA = &infoA;
7595 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
7597 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
7598 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
7600 SetLastError(WSAEINVAL);
7601 return SOCKET_ERROR;
7605 if (AddressString)
7607 /* Translate AddressString to ANSI code page - assumes that only
7608 standard digits 0-9 are used with this API call */
7609 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
7610 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
7612 if (workBuffer)
7614 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
7615 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
7616 lpAddress,lpAddressLength);
7617 HeapFree( GetProcessHeap(), 0, workBuffer );
7618 return res;
7620 else
7621 res = WSA_NOT_ENOUGH_MEMORY;
7623 else
7624 res = WSAEINVAL;
7626 SetLastError(res);
7627 return SOCKET_ERROR;
7630 /***********************************************************************
7631 * WSAAddressToStringA (WS2_32.27)
7633 * See WSAAddressToStringW
7635 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
7636 LPWSAPROTOCOL_INFOA info, LPSTR string,
7637 LPDWORD lenstr )
7639 DWORD size;
7640 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
7641 CHAR *p;
7643 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
7645 if (!sockaddr) return SOCKET_ERROR;
7646 if (!string || !lenstr) return SOCKET_ERROR;
7648 switch(sockaddr->sa_family)
7650 case WS_AF_INET:
7651 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
7652 sprintf( buffer, "%u.%u.%u.%u:%u",
7653 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
7654 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
7655 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
7656 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
7657 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
7659 p = strchr( buffer, ':' );
7660 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
7661 break;
7663 case WS_AF_INET6:
7665 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
7667 buffer[0] = 0;
7668 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
7669 if ((sockaddr6->sin6_port))
7670 strcpy(buffer, "[");
7671 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, buffer+strlen(buffer), sizeof(buffer)))
7673 SetLastError(WSAEINVAL);
7674 return SOCKET_ERROR;
7676 if ((sockaddr6->sin6_scope_id))
7677 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
7678 if ((sockaddr6->sin6_port))
7679 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
7680 break;
7683 default:
7684 SetLastError(WSAEINVAL);
7685 return SOCKET_ERROR;
7688 size = strlen( buffer ) + 1;
7690 if (*lenstr < size)
7692 *lenstr = size;
7693 SetLastError(WSAEFAULT);
7694 return SOCKET_ERROR;
7697 TRACE("=> %s,%u bytes\n", debugstr_a(buffer), size);
7698 *lenstr = size;
7699 strcpy( string, buffer );
7700 return 0;
7703 /***********************************************************************
7704 * WSAAddressToStringW (WS2_32.28)
7706 * Convert a sockaddr address into a readable address string.
7708 * PARAMS
7709 * sockaddr [I] Pointer to a sockaddr structure.
7710 * len [I] Size of the sockaddr structure.
7711 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
7712 * string [I/O] Pointer to a buffer to receive the address string.
7713 * lenstr [I/O] Size of the receive buffer in WCHARs.
7715 * RETURNS
7716 * Success: 0
7717 * Failure: SOCKET_ERROR
7719 * NOTES
7720 * The 'info' parameter is ignored.
7722 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
7723 LPWSAPROTOCOL_INFOW info, LPWSTR string,
7724 LPDWORD lenstr )
7726 INT ret;
7727 DWORD size;
7728 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
7729 CHAR bufAddr[54];
7731 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
7733 size = *lenstr;
7734 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
7736 if (ret) return ret;
7738 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
7740 if (*lenstr < size)
7742 *lenstr = size;
7743 SetLastError(WSAEFAULT);
7744 return SOCKET_ERROR;
7747 TRACE("=> %s,%u bytes\n", debugstr_w(buffer), size);
7748 *lenstr = size;
7749 lstrcpyW( string, buffer );
7750 return 0;
7753 /***********************************************************************
7754 * WSAEnumNameSpaceProvidersA (WS2_32.34)
7756 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
7758 FIXME( "(%p %p) Stub!\n", len, buffer );
7759 return 0;
7762 /***********************************************************************
7763 * WSAEnumNameSpaceProvidersW (WS2_32.35)
7765 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
7767 FIXME( "(%p %p) Stub!\n", len, buffer );
7768 return 0;
7771 /***********************************************************************
7772 * WSAGetQOSByName (WS2_32.41)
7774 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
7776 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
7777 return FALSE;
7780 /***********************************************************************
7781 * WSAGetServiceClassInfoA (WS2_32.42)
7783 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
7784 LPWSASERVICECLASSINFOA info )
7786 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
7787 len, info );
7788 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7789 return SOCKET_ERROR;
7792 /***********************************************************************
7793 * WSAGetServiceClassInfoW (WS2_32.43)
7795 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
7796 LPWSASERVICECLASSINFOW info )
7798 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
7799 len, info );
7800 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7801 return SOCKET_ERROR;
7804 /***********************************************************************
7805 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
7807 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
7809 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
7810 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7811 return SOCKET_ERROR;
7814 /***********************************************************************
7815 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
7817 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
7819 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
7820 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7821 return SOCKET_ERROR;
7824 /***********************************************************************
7825 * WSALookupServiceBeginA (WS2_32.59)
7827 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
7828 DWORD dwControlFlags,
7829 LPHANDLE lphLookup)
7831 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
7832 lphLookup);
7833 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7834 return SOCKET_ERROR;
7837 /***********************************************************************
7838 * WSALookupServiceBeginW (WS2_32.60)
7840 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
7841 DWORD dwControlFlags,
7842 LPHANDLE lphLookup)
7844 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
7845 lphLookup);
7846 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7847 return SOCKET_ERROR;
7850 /***********************************************************************
7851 * WSALookupServiceEnd (WS2_32.61)
7853 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
7855 FIXME("(%p) Stub!\n", lookup );
7856 return 0;
7859 /***********************************************************************
7860 * WSALookupServiceNextA (WS2_32.62)
7862 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
7864 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
7865 SetLastError(WSA_E_NO_MORE);
7866 return SOCKET_ERROR;
7869 /***********************************************************************
7870 * WSALookupServiceNextW (WS2_32.63)
7872 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
7874 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
7875 SetLastError(WSA_E_NO_MORE);
7876 return SOCKET_ERROR;
7879 /***********************************************************************
7880 * WSANtohl (WS2_32.64)
7882 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
7884 TRACE( "(%04lx 0x%08x %p)\n", s, netlong, lphostlong );
7886 if (!lphostlong) return WSAEFAULT;
7888 *lphostlong = ntohl( netlong );
7889 return 0;
7892 /***********************************************************************
7893 * WSANtohs (WS2_32.65)
7895 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
7897 TRACE( "(%04lx 0x%08x %p)\n", s, netshort, lphostshort );
7899 if (!lphostshort) return WSAEFAULT;
7901 *lphostshort = ntohs( netshort );
7902 return 0;
7905 /***********************************************************************
7906 * WSAProviderConfigChange (WS2_32.66)
7908 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
7909 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
7911 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
7912 return SOCKET_ERROR;
7915 /***********************************************************************
7916 * WSARecvDisconnect (WS2_32.68)
7918 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
7920 TRACE( "(%04lx %p)\n", s, disconnectdata );
7922 return WS_shutdown( s, SD_RECEIVE );
7925 /***********************************************************************
7926 * WSASetServiceA (WS2_32.76)
7928 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
7930 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
7931 return 0;
7934 /***********************************************************************
7935 * WSASetServiceW (WS2_32.77)
7937 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
7939 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
7940 return 0;
7943 /***********************************************************************
7944 * WSCEnableNSProvider (WS2_32.84)
7946 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
7948 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
7949 return 0;
7952 /***********************************************************************
7953 * WSCGetProviderPath (WS2_32.86)
7955 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
7957 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
7959 if (!errcode || !provider || !len) return WSAEFAULT;
7961 *errcode = WSAEINVAL;
7962 return SOCKET_ERROR;
7965 /***********************************************************************
7966 * WSCInstallNameSpace (WS2_32.87)
7968 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
7969 DWORD version, LPGUID provider )
7971 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
7972 namespace, version, debugstr_guid(provider) );
7973 return 0;
7976 /***********************************************************************
7977 * WSCUnInstallNameSpace (WS2_32.89)
7979 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
7981 FIXME("(%p) Stub!\n", lpProviderId);
7982 return NO_ERROR;
7985 /***********************************************************************
7986 * WSCWriteProviderOrder (WS2_32.91)
7988 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
7990 FIXME("(%p 0x%08x) Stub!\n", entry, number);
7991 return 0;
7994 /***********************************************************************
7995 * WSANSPIoctl (WS2_32.91)
7997 INT WINAPI WSANSPIoctl( HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer,
7998 DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer,
7999 LPDWORD lpcbBytesReturned, LPWSACOMPLETION lpCompletion )
8001 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup, dwControlCode,
8002 lpvInBuffer, cbInBuffer, lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpCompletion);
8003 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8004 return SOCKET_ERROR;
8007 /*****************************************************************************
8008 * WSAEnumProtocolsA [WS2_32.@]
8010 * see function WSAEnumProtocolsW
8012 INT WINAPI WSAEnumProtocolsA( LPINT protocols, LPWSAPROTOCOL_INFOA buffer, LPDWORD len )
8014 return WS_EnumProtocols( FALSE, protocols, (LPWSAPROTOCOL_INFOW) buffer, len);
8017 /*****************************************************************************
8018 * WSAEnumProtocolsW [WS2_32.@]
8020 * Retrieves information about specified set of active network protocols.
8022 * PARAMS
8023 * protocols [I] Pointer to null-terminated array of protocol id's. NULL
8024 * retrieves information on all available protocols.
8025 * buffer [I] Pointer to a buffer to be filled with WSAPROTOCOL_INFO
8026 * structures.
8027 * len [I/O] Pointer to a variable specifying buffer size. On output
8028 * the variable holds the number of bytes needed when the
8029 * specified size is too small.
8031 * RETURNS
8032 * Success: number of WSAPROTOCOL_INFO structures in buffer.
8033 * Failure: SOCKET_ERROR
8035 * NOTES
8036 * NT4SP5 does not return SPX if protocols == NULL
8038 * BUGS
8039 * - NT4SP5 returns in addition these list of NETBIOS protocols
8040 * (address family 17), each entry two times one for socket type 2 and 5
8042 * iProtocol szProtocol
8043 * 0x80000000 \Device\NwlnkNb
8044 * 0xfffffffa \Device\NetBT_CBENT7
8045 * 0xfffffffb \Device\Nbf_CBENT7
8046 * 0xfffffffc \Device\NetBT_NdisWan5
8047 * 0xfffffffd \Device\NetBT_El9202
8048 * 0xfffffffe \Device\Nbf_El9202
8049 * 0xffffffff \Device\Nbf_NdisWan4
8051 * - there is no check that the operating system supports the returned
8052 * protocols
8054 INT WINAPI WSAEnumProtocolsW( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
8056 return WS_EnumProtocols( TRUE, protocols, buffer, len);
8059 /*****************************************************************************
8060 * WSCEnumProtocols [WS2_32.@]
8062 * PARAMS
8063 * protocols [I] Null-terminated array of iProtocol values.
8064 * buffer [O] Buffer of WSAPROTOCOL_INFOW structures.
8065 * len [I/O] Size of buffer on input/output.
8066 * errno [O] Error code.
8068 * RETURNS
8069 * Success: number of protocols to be reported on.
8070 * Failure: SOCKET_ERROR. error is in errno.
8072 * BUGS
8073 * Doesn't supply info on layered protocols.
8076 INT WINAPI WSCEnumProtocols( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len, LPINT err )
8078 INT ret = WSAEnumProtocolsW( protocols, buffer, len );
8080 if (ret == SOCKET_ERROR) *err = WSAENOBUFS;
8082 return ret;