ws2_32: Add a helper to get socket type.
[wine.git] / dlls / ws2_32 / socket.c
blob63c965ee9a90d58ef2bf5637287fa8cceb85c3f1
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)
4713 fds[j].events = POLLOUT;
4715 else
4717 release_sock_fd( writefds->fd_array[i], fds[j].fd );
4718 fds[j].fd = -1;
4719 fds[j].events = 0;
4722 if (exceptfds)
4723 for (i = 0; i < exceptfds->fd_count; i++, j++)
4725 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
4726 if (fds[j].fd == -1) goto failed;
4727 fds[j].revents = 0;
4728 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1)
4730 int oob_inlined = 0;
4731 socklen_t olen = sizeof(oob_inlined);
4733 fds[j].events = POLLHUP;
4735 /* Check if we need to test for urgent data or not */
4736 getsockopt(fds[j].fd, SOL_SOCKET, SO_OOBINLINE, (char*) &oob_inlined, &olen);
4737 if (!oob_inlined)
4738 fds[j].events |= POLLPRI;
4740 else
4742 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
4743 fds[j].fd = -1;
4744 fds[j].events = 0;
4747 return fds;
4749 failed:
4750 count = j;
4751 j = 0;
4752 if (readfds)
4753 for (i = 0; i < readfds->fd_count && j < count; i++, j++)
4754 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
4755 if (writefds)
4756 for (i = 0; i < writefds->fd_count && j < count; i++, j++)
4757 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
4758 if (exceptfds)
4759 for (i = 0; i < exceptfds->fd_count && j < count; i++, j++)
4760 if (fds[j].fd != -1) release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
4761 HeapFree( GetProcessHeap(), 0, fds );
4762 return NULL;
4765 /* release the file descriptor obtained in fd_sets_to_poll */
4766 /* must be called with the original fd_set arrays, before calling get_poll_results */
4767 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
4768 const WS_fd_set *exceptfds, struct pollfd *fds )
4770 unsigned int i, j = 0;
4772 if (readfds)
4774 for (i = 0; i < readfds->fd_count; i++, j++)
4775 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
4777 if (writefds)
4779 for (i = 0; i < writefds->fd_count; i++, j++)
4780 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
4782 if (exceptfds)
4784 for (i = 0; i < exceptfds->fd_count; i++, j++)
4786 if (fds[j].fd == -1) continue;
4787 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
4788 if (fds[j].revents & POLLHUP)
4790 int fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
4791 if (fd != -1)
4792 release_sock_fd( exceptfds->fd_array[i], fd );
4793 else
4794 fds[j].revents = 0;
4800 static int do_poll(struct pollfd *pollfds, int count, int timeout)
4802 struct timeval tv1, tv2;
4803 int ret, torig = timeout;
4805 if (timeout > 0) gettimeofday( &tv1, 0 );
4807 while ((ret = poll( pollfds, count, timeout )) < 0)
4809 if (errno != EINTR) break;
4810 if (timeout < 0) continue;
4811 if (timeout == 0) return 0;
4813 gettimeofday( &tv2, 0 );
4815 tv2.tv_sec -= tv1.tv_sec;
4816 tv2.tv_usec -= tv1.tv_usec;
4817 if (tv2.tv_usec < 0)
4819 tv2.tv_usec += 1000000;
4820 tv2.tv_sec -= 1;
4823 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
4824 if (timeout <= 0) return 0;
4826 return ret;
4829 /* map the poll results back into the Windows fd sets */
4830 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
4831 const struct pollfd *fds )
4833 const struct pollfd *poll_writefds = fds + (readfds ? readfds->fd_count : 0);
4834 const struct pollfd *poll_exceptfds = poll_writefds + (writefds ? writefds->fd_count : 0);
4835 unsigned int i, k, total = 0;
4837 if (readfds)
4839 for (i = k = 0; i < readfds->fd_count; i++)
4841 if (fds[i].revents ||
4842 (readfds == writefds && (poll_writefds[i].revents & POLLOUT) && !(poll_writefds[i].revents & POLLHUP)) ||
4843 (readfds == exceptfds && poll_exceptfds[i].revents))
4844 readfds->fd_array[k++] = readfds->fd_array[i];
4846 readfds->fd_count = k;
4847 total += k;
4849 if (writefds && writefds != readfds)
4851 for (i = k = 0; i < writefds->fd_count; i++)
4853 if (((poll_writefds[i].revents & POLLOUT) && !(poll_writefds[i].revents & POLLHUP)) ||
4854 (writefds == exceptfds && poll_exceptfds[i].revents))
4855 writefds->fd_array[k++] = writefds->fd_array[i];
4857 writefds->fd_count = k;
4858 total += k;
4860 if (exceptfds && exceptfds != readfds && exceptfds != writefds)
4862 for (i = k = 0; i < exceptfds->fd_count; i++)
4863 if (poll_exceptfds[i].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
4864 exceptfds->fd_count = k;
4865 total += k;
4867 return total;
4870 /***********************************************************************
4871 * select (WS2_32.18)
4873 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
4874 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
4875 const struct WS_timeval* ws_timeout)
4877 struct pollfd *pollfds;
4878 int count, ret, timeout = -1;
4880 TRACE("read %p, write %p, excp %p timeout %p\n",
4881 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
4883 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )))
4884 return SOCKET_ERROR;
4886 if (ws_timeout)
4887 timeout = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
4889 ret = do_poll(pollfds, count, timeout);
4890 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
4892 if (ret == -1) SetLastError(wsaErrno());
4893 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
4894 HeapFree( GetProcessHeap(), 0, pollfds );
4895 return ret;
4898 /* helper to send completion messages for client-only i/o operation case */
4899 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
4900 ULONG Information )
4902 SERVER_START_REQ( add_fd_completion )
4904 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
4905 req->cvalue = CompletionValue;
4906 req->status = CompletionStatus;
4907 req->information = Information;
4908 wine_server_call( req );
4910 SERVER_END_REQ;
4914 /***********************************************************************
4915 * send (WS2_32.19)
4917 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
4919 DWORD n;
4920 WSABUF wsabuf;
4922 wsabuf.len = len;
4923 wsabuf.buf = (char*) buf;
4925 if ( WS2_sendto( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
4926 return SOCKET_ERROR;
4927 else
4928 return n;
4931 /***********************************************************************
4932 * WSASend (WS2_32.72)
4934 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4935 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4936 LPWSAOVERLAPPED lpOverlapped,
4937 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4939 return WS2_sendto( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
4940 NULL, 0, lpOverlapped, lpCompletionRoutine );
4943 /***********************************************************************
4944 * WSASendDisconnect (WS2_32.73)
4946 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
4948 return WS_shutdown( s, SD_SEND );
4952 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4953 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4954 const struct WS_sockaddr *to, int tolen,
4955 LPWSAOVERLAPPED lpOverlapped,
4956 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4958 unsigned int i, options;
4959 int n, fd, err, overlapped, flags;
4960 struct ws2_async *wsa = NULL, localwsa;
4961 int totalLength = 0;
4962 DWORD bytes_sent;
4963 BOOL is_blocking;
4965 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
4966 s, lpBuffers, dwBufferCount, dwFlags,
4967 to, tolen, lpOverlapped, lpCompletionRoutine);
4969 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
4970 TRACE( "fd=%d, options=%x\n", fd, options );
4972 if ( fd == -1 ) return SOCKET_ERROR;
4974 if (!lpOverlapped && !lpNumberOfBytesSent)
4976 err = WSAEFAULT;
4977 goto error;
4980 overlapped = (lpOverlapped || lpCompletionRoutine) &&
4981 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
4982 if (overlapped || dwBufferCount > 1)
4984 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[dwBufferCount]))))
4986 err = WSAEFAULT;
4987 goto error;
4990 else
4991 wsa = &localwsa;
4993 wsa->hSocket = SOCKET2HANDLE(s);
4994 wsa->addr = (struct WS_sockaddr *)to;
4995 wsa->addrlen.val = tolen;
4996 wsa->flags = dwFlags;
4997 wsa->lpFlags = &wsa->flags;
4998 wsa->control = NULL;
4999 wsa->n_iovecs = dwBufferCount;
5000 wsa->first_iovec = 0;
5001 for ( i = 0; i < dwBufferCount; i++ )
5003 wsa->iovec[i].iov_base = lpBuffers[i].buf;
5004 wsa->iovec[i].iov_len = lpBuffers[i].len;
5005 totalLength += lpBuffers[i].len;
5008 flags = convert_flags(dwFlags);
5009 n = WS2_send( fd, wsa, flags );
5010 if (n == -1 && errno != EAGAIN)
5012 err = wsaErrno();
5013 goto error;
5016 if (overlapped)
5018 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
5019 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
5021 wsa->user_overlapped = lpOverlapped;
5022 wsa->completion_func = lpCompletionRoutine;
5023 release_sock_fd( s, fd );
5025 if (n == -1 || n < totalLength)
5027 iosb->u.Status = STATUS_PENDING;
5028 iosb->Information = n == -1 ? 0 : n;
5030 SERVER_START_REQ( register_async )
5032 req->type = ASYNC_TYPE_WRITE;
5033 req->async.handle = wine_server_obj_handle( wsa->hSocket );
5034 req->async.callback = wine_server_client_ptr( WS2_async_send );
5035 req->async.iosb = wine_server_client_ptr( iosb );
5036 req->async.arg = wine_server_client_ptr( wsa );
5037 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
5038 req->async.cvalue = cvalue;
5039 err = wine_server_call( req );
5041 SERVER_END_REQ;
5043 /* Enable the event only after starting the async. The server will deliver it as soon as
5044 the async is done. */
5045 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
5047 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
5048 SetLastError(NtStatusToWSAError( err ));
5049 return SOCKET_ERROR;
5052 iosb->u.Status = STATUS_SUCCESS;
5053 iosb->Information = n;
5054 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = n;
5055 if (!wsa->completion_func)
5057 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
5058 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
5059 HeapFree( GetProcessHeap(), 0, wsa );
5061 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
5062 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
5063 SetLastError(ERROR_SUCCESS);
5064 return 0;
5067 if ((err = _is_blocking( s, &is_blocking )))
5069 err = NtStatusToWSAError( err );
5070 goto error;
5073 if ( is_blocking )
5075 /* On a blocking non-overlapped stream socket,
5076 * sending blocks until the entire buffer is sent. */
5077 DWORD timeout_start = GetTickCount();
5079 bytes_sent = n == -1 ? 0 : n;
5081 while (wsa->first_iovec < wsa->n_iovecs)
5083 struct pollfd pfd;
5084 int poll_timeout = -1;
5085 INT64 timeout = get_rcvsnd_timeo(fd, FALSE);
5087 if (timeout)
5089 timeout -= GetTickCount() - timeout_start;
5090 if (timeout < 0) poll_timeout = 0;
5091 else poll_timeout = timeout <= INT_MAX ? timeout : INT_MAX;
5094 pfd.fd = fd;
5095 pfd.events = POLLOUT;
5097 if (!poll_timeout || !poll( &pfd, 1, poll_timeout ))
5099 err = WSAETIMEDOUT;
5100 goto error; /* msdn says a timeout in send is fatal */
5103 n = WS2_send( fd, wsa, flags );
5104 if (n == -1 && errno != EAGAIN)
5106 err = wsaErrno();
5107 goto error;
5110 if (n >= 0)
5111 bytes_sent += n;
5114 else /* non-blocking */
5116 if (n < totalLength)
5117 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
5118 if (n == -1)
5120 err = WSAEWOULDBLOCK;
5121 goto error;
5123 bytes_sent = n;
5126 TRACE(" -> %i bytes\n", bytes_sent);
5128 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = bytes_sent;
5129 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
5130 release_sock_fd( s, fd );
5131 SetLastError(ERROR_SUCCESS);
5132 return 0;
5134 error:
5135 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
5136 release_sock_fd( s, fd );
5137 WARN(" -> ERROR %d\n", err);
5138 SetLastError(err);
5139 return SOCKET_ERROR;
5142 /***********************************************************************
5143 * WSASendTo (WS2_32.74)
5145 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5146 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
5147 const struct WS_sockaddr *to, int tolen,
5148 LPWSAOVERLAPPED lpOverlapped,
5149 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5151 return WS2_sendto( s, lpBuffers, dwBufferCount,
5152 lpNumberOfBytesSent, dwFlags,
5153 to, tolen,
5154 lpOverlapped, lpCompletionRoutine );
5157 /***********************************************************************
5158 * sendto (WS2_32.20)
5160 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
5161 const struct WS_sockaddr *to, int tolen)
5163 DWORD n;
5164 WSABUF wsabuf;
5166 wsabuf.len = len;
5167 wsabuf.buf = (char*) buf;
5169 if ( WS2_sendto(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
5170 return SOCKET_ERROR;
5171 else
5172 return n;
5175 /***********************************************************************
5176 * setsockopt (WS2_32.21)
5178 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
5179 const char *optval, int optlen)
5181 int fd;
5182 int woptval;
5183 struct linger linger;
5184 struct timeval tval;
5186 TRACE("(socket %04lx, %s, optval %s, optlen %d)\n", s,
5187 debugstr_sockopt(level, optname), debugstr_optval(optval, optlen),
5188 optlen);
5190 /* some broken apps pass the value directly instead of a pointer to it */
5191 if(optlen && IS_INTRESOURCE(optval))
5193 SetLastError(WSAEFAULT);
5194 return SOCKET_ERROR;
5197 switch(level)
5199 case WS_SOL_SOCKET:
5200 switch(optname)
5202 /* Some options need some conversion before they can be sent to
5203 * setsockopt. The conversions are done here, then they will fall through
5204 * to the general case. Special options that are not passed to
5205 * setsockopt follow below that.*/
5207 case WS_SO_DONTLINGER:
5208 if (!optval)
5210 SetLastError(WSAEFAULT);
5211 return SOCKET_ERROR;
5213 linger.l_onoff = *(const int*)optval == 0;
5214 linger.l_linger = 0;
5215 level = SOL_SOCKET;
5216 optname = SO_LINGER;
5217 optval = (char*)&linger;
5218 optlen = sizeof(struct linger);
5219 break;
5221 case WS_SO_LINGER:
5222 if (!optval)
5224 SetLastError(WSAEFAULT);
5225 return SOCKET_ERROR;
5227 linger.l_onoff = ((LINGER*)optval)->l_onoff;
5228 linger.l_linger = ((LINGER*)optval)->l_linger;
5229 level = SOL_SOCKET;
5230 optname = SO_LINGER;
5231 optval = (char*)&linger;
5232 optlen = sizeof(struct linger);
5233 break;
5235 case WS_SO_RCVBUF:
5236 if (*(const int*)optval < 2048)
5238 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
5239 return 0;
5241 /* Fall through */
5243 /* The options listed here don't need any special handling. Thanks to
5244 * the conversion happening above, options from there will fall through
5245 * to this, too.*/
5246 case WS_SO_ACCEPTCONN:
5247 case WS_SO_BROADCAST:
5248 case WS_SO_ERROR:
5249 case WS_SO_KEEPALIVE:
5250 case WS_SO_OOBINLINE:
5251 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
5252 * however, using it the BSD way fixes bug 8513 and seems to be what
5253 * most programmers assume, anyway */
5254 case WS_SO_REUSEADDR:
5255 case WS_SO_SNDBUF:
5256 case WS_SO_TYPE:
5257 convert_sockopt(&level, &optname);
5258 break;
5260 /* SO_DEBUG is a privileged operation, ignore it. */
5261 case WS_SO_DEBUG:
5262 TRACE("Ignoring SO_DEBUG\n");
5263 return 0;
5265 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
5266 * socket. According to MSDN, this option is silently ignored.*/
5267 case WS_SO_DONTROUTE:
5268 TRACE("Ignoring SO_DONTROUTE\n");
5269 return 0;
5271 /* Stops two sockets from being bound to the same port. Always happens
5272 * on unix systems, so just drop it. */
5273 case WS_SO_EXCLUSIVEADDRUSE:
5274 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
5275 return 0;
5277 /* After a ConnectEx call succeeds, the socket can't be used with half of the
5278 * normal winsock functions on windows. We don't have that problem. */
5279 case WS_SO_UPDATE_CONNECT_CONTEXT:
5280 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
5281 return 0;
5283 /* After a AcceptEx call succeeds, the socket can't be used with half of the
5284 * normal winsock functions on windows. We don't have that problem. */
5285 case WS_SO_UPDATE_ACCEPT_CONTEXT:
5286 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
5287 return 0;
5289 /* SO_OPENTYPE does not require a valid socket handle. */
5290 case WS_SO_OPENTYPE:
5291 if (!optlen || optlen < sizeof(int) || !optval)
5293 SetLastError(WSAEFAULT);
5294 return SOCKET_ERROR;
5296 get_per_thread_data()->opentype = *(const int *)optval;
5297 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
5298 return 0;
5300 #ifdef SO_RCVTIMEO
5301 case WS_SO_RCVTIMEO:
5302 #endif
5303 #ifdef SO_SNDTIMEO
5304 case WS_SO_SNDTIMEO:
5305 #endif
5306 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
5307 if (optval && optlen == sizeof(UINT32)) {
5308 /* WinSock passes milliseconds instead of struct timeval */
5309 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
5310 tval.tv_sec = *(const UINT32*)optval / 1000;
5311 /* min of 500 milliseconds */
5312 if (tval.tv_sec == 0 && tval.tv_usec && tval.tv_usec < 500000)
5313 tval.tv_usec = 500000;
5314 optlen = sizeof(struct timeval);
5315 optval = (char*)&tval;
5316 } else if (optlen == sizeof(struct timeval)) {
5317 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
5318 } else {
5319 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
5320 return 0;
5322 convert_sockopt(&level, &optname);
5323 break;
5324 #endif
5326 default:
5327 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
5328 SetLastError(WSAENOPROTOOPT);
5329 return SOCKET_ERROR;
5331 break; /* case WS_SOL_SOCKET */
5333 #ifdef HAS_IPX
5334 case WS_NSPROTO_IPX:
5335 switch(optname)
5337 case WS_IPX_PTYPE:
5338 return set_ipx_packettype(s, *(int*)optval);
5340 case WS_IPX_FILTERPTYPE:
5341 /* Sets the receive filter packet type, at the moment we don't support it */
5342 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
5343 /* Returning 0 is better for now than returning a SOCKET_ERROR */
5344 return 0;
5346 default:
5347 FIXME("opt_name:%x\n", optname);
5348 return SOCKET_ERROR;
5350 break; /* case WS_NSPROTO_IPX */
5351 #endif
5353 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
5354 case WS_IPPROTO_TCP:
5355 switch(optname)
5357 case WS_TCP_NODELAY:
5358 convert_sockopt(&level, &optname);
5359 break;
5360 default:
5361 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
5362 return SOCKET_ERROR;
5364 break;
5366 case WS_IPPROTO_IP:
5367 switch(optname)
5369 case WS_IP_ADD_MEMBERSHIP:
5370 case WS_IP_DROP_MEMBERSHIP:
5371 #ifdef IP_HDRINCL
5372 case WS_IP_HDRINCL:
5373 #endif
5374 case WS_IP_MULTICAST_IF:
5375 case WS_IP_MULTICAST_LOOP:
5376 case WS_IP_MULTICAST_TTL:
5377 case WS_IP_OPTIONS:
5378 #ifdef IP_PKTINFO
5379 case WS_IP_PKTINFO:
5380 #endif
5381 case WS_IP_TOS:
5382 case WS_IP_TTL:
5383 #ifdef IP_UNICAST_IF
5384 case WS_IP_UNICAST_IF:
5385 #endif
5386 convert_sockopt(&level, &optname);
5387 break;
5388 case WS_IP_DONTFRAGMENT:
5389 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
5390 return 0;
5391 default:
5392 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
5393 return SOCKET_ERROR;
5395 break;
5397 case WS_IPPROTO_IPV6:
5398 switch(optname)
5400 #ifdef IPV6_ADD_MEMBERSHIP
5401 case WS_IPV6_ADD_MEMBERSHIP:
5402 #endif
5403 #ifdef IPV6_DROP_MEMBERSHIP
5404 case WS_IPV6_DROP_MEMBERSHIP:
5405 #endif
5406 case WS_IPV6_MULTICAST_IF:
5407 case WS_IPV6_MULTICAST_HOPS:
5408 case WS_IPV6_MULTICAST_LOOP:
5409 case WS_IPV6_UNICAST_HOPS:
5410 case WS_IPV6_V6ONLY:
5411 #ifdef IPV6_UNICAST_IF
5412 case WS_IPV6_UNICAST_IF:
5413 #endif
5414 convert_sockopt(&level, &optname);
5415 break;
5416 case WS_IPV6_DONTFRAG:
5417 FIXME("IPV6_DONTFRAG is silently ignored!\n");
5418 return 0;
5419 case WS_IPV6_PROTECTION_LEVEL:
5420 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
5421 return 0;
5422 default:
5423 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
5424 return SOCKET_ERROR;
5426 break;
5428 default:
5429 WARN("Unknown level: 0x%08x\n", level);
5430 SetLastError(WSAEINVAL);
5431 return SOCKET_ERROR;
5432 } /* end switch(level) */
5434 /* avoid endianness issues if argument is a 16-bit int */
5435 if (optval && optlen < sizeof(int))
5437 woptval= *((const INT16 *) optval);
5438 optval= (char*) &woptval;
5439 woptval&= (1 << optlen * 8) - 1;
5440 optlen=sizeof(int);
5442 fd = get_sock_fd( s, 0, NULL );
5443 if (fd == -1) return SOCKET_ERROR;
5445 if (setsockopt(fd, level, optname, optval, optlen) == 0)
5447 #ifdef __APPLE__
5448 if (level == SOL_SOCKET && optname == SO_REUSEADDR &&
5449 setsockopt(fd, level, SO_REUSEPORT, optval, optlen) != 0)
5451 SetLastError(wsaErrno());
5452 release_sock_fd( s, fd );
5453 return SOCKET_ERROR;
5455 #endif
5456 release_sock_fd( s, fd );
5457 return 0;
5459 TRACE("Setting socket error, %d\n", wsaErrno());
5460 SetLastError(wsaErrno());
5461 release_sock_fd( s, fd );
5463 return SOCKET_ERROR;
5466 /***********************************************************************
5467 * shutdown (WS2_32.22)
5469 int WINAPI WS_shutdown(SOCKET s, int how)
5471 int fd, err = WSAENOTSOCK;
5472 unsigned int options = 0, clear_flags = 0;
5474 fd = get_sock_fd( s, 0, &options );
5475 TRACE("socket %04lx, how 0x%x, options 0x%x\n", s, how, options );
5477 if (fd == -1)
5478 return SOCKET_ERROR;
5480 switch( how )
5482 case SD_RECEIVE: /* drop receives */
5483 clear_flags |= FD_READ;
5484 break;
5485 case SD_SEND: /* drop sends */
5486 clear_flags |= FD_WRITE;
5487 break;
5488 case SD_BOTH: /* drop all */
5489 clear_flags |= FD_READ|FD_WRITE;
5490 /*fall through */
5491 default:
5492 clear_flags |= FD_WINE_LISTENING;
5495 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
5497 switch ( how )
5499 case SD_RECEIVE:
5500 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
5501 break;
5502 case SD_SEND:
5503 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
5504 break;
5505 case SD_BOTH:
5506 default:
5507 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
5508 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
5509 break;
5511 if (err) goto error;
5513 else /* non-overlapped mode */
5515 if ( shutdown( fd, how ) )
5517 err = wsaErrno();
5518 goto error;
5522 release_sock_fd( s, fd );
5523 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
5524 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
5525 return 0;
5527 error:
5528 release_sock_fd( s, fd );
5529 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
5530 SetLastError( err );
5531 return SOCKET_ERROR;
5534 /***********************************************************************
5535 * socket (WS2_32.23)
5537 SOCKET WINAPI WS_socket(int af, int type, int protocol)
5539 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
5541 return WSASocketW( af, type, protocol, NULL, 0,
5542 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
5546 /***********************************************************************
5547 * gethostbyaddr (WS2_32.51)
5549 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
5551 struct WS_hostent *retval = NULL;
5552 struct hostent* host;
5553 int unixtype = convert_af_w2u(type);
5554 const char *paddr = addr;
5555 unsigned long loopback;
5556 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5557 char *extrabuf;
5558 int ebufsize = 1024;
5559 struct hostent hostentry;
5560 int locerr = ENOBUFS;
5561 #endif
5563 /* convert back the magic loopback address if necessary */
5564 if (unixtype == AF_INET && len == 4 && !memcmp(addr, magic_loopback_addr, 4))
5566 loopback = htonl(INADDR_LOOPBACK);
5567 paddr = (char*) &loopback;
5570 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5571 host = NULL;
5572 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
5573 while(extrabuf) {
5574 int res = gethostbyaddr_r(paddr, len, unixtype,
5575 &hostentry, extrabuf, ebufsize, &host, &locerr);
5576 if (res != ERANGE) break;
5577 ebufsize *=2;
5578 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
5580 if (host) retval = WS_dup_he(host);
5581 else SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
5582 HeapFree(GetProcessHeap(),0,extrabuf);
5583 #else
5584 EnterCriticalSection( &csWSgetXXXbyYYY );
5585 host = gethostbyaddr(paddr, len, unixtype);
5586 if (host) retval = WS_dup_he(host);
5587 else SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
5588 LeaveCriticalSection( &csWSgetXXXbyYYY );
5589 #endif
5590 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
5591 return retval;
5594 /***********************************************************************
5595 * WS_compare_routes_by_metric_asc (INTERNAL)
5597 * Comparison function for qsort(), for sorting two routes (struct route)
5598 * by metric in ascending order.
5600 static int WS_compare_routes_by_metric_asc(const void *left, const void *right)
5602 return ((const struct route*)left)->metric - ((const struct route*)right)->metric;
5605 /***********************************************************************
5606 * WS_get_local_ips (INTERNAL)
5608 * Returns the list of local IP addresses by going through the network
5609 * adapters and using the local routing table to sort the addresses
5610 * from highest routing priority to lowest routing priority. This
5611 * functionality is inferred from the description for obtaining local
5612 * IP addresses given in the Knowledge Base Article Q160215.
5614 * Please note that the returned hostent is only freed when the thread
5615 * closes and is replaced if another hostent is requested.
5617 static struct WS_hostent* WS_get_local_ips( char *hostname )
5619 int numroutes = 0, i, j;
5620 DWORD n;
5621 PIP_ADAPTER_INFO adapters = NULL, k;
5622 struct WS_hostent *hostlist = NULL;
5623 PMIB_IPFORWARDTABLE routes = NULL;
5624 struct route *route_addrs = NULL;
5625 DWORD adap_size, route_size;
5627 /* Obtain the size of the adapter list and routing table, also allocate memory */
5628 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
5629 return NULL;
5630 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
5631 return NULL;
5632 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
5633 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
5634 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
5635 if (adapters == NULL || routes == NULL || route_addrs == NULL)
5636 goto cleanup;
5637 /* Obtain the adapter list and the full routing table */
5638 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
5639 goto cleanup;
5640 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
5641 goto cleanup;
5642 /* Store the interface associated with each route */
5643 for (n = 0; n < routes->dwNumEntries; n++)
5645 IF_INDEX ifindex;
5646 DWORD ifmetric;
5647 BOOL exists = FALSE;
5649 if (routes->table[n].u1.ForwardType != MIB_IPROUTE_TYPE_DIRECT)
5650 continue;
5651 ifindex = routes->table[n].dwForwardIfIndex;
5652 ifmetric = routes->table[n].dwForwardMetric1;
5653 /* Only store the lowest valued metric for an interface */
5654 for (j = 0; j < numroutes; j++)
5656 if (route_addrs[j].interface == ifindex)
5658 if (route_addrs[j].metric > ifmetric)
5659 route_addrs[j].metric = ifmetric;
5660 exists = TRUE;
5663 if (exists)
5664 continue;
5665 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
5666 if (route_addrs == NULL)
5667 goto cleanup; /* Memory allocation error, fail gracefully */
5668 route_addrs[numroutes].interface = ifindex;
5669 route_addrs[numroutes].metric = ifmetric;
5670 /* If no IP is found in the next step (for whatever reason)
5671 * then fall back to the magic loopback address.
5673 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
5674 numroutes++;
5676 if (numroutes == 0)
5677 goto cleanup; /* No routes, fall back to the Magic IP */
5678 /* Find the IP address associated with each found interface */
5679 for (i = 0; i < numroutes; i++)
5681 for (k = adapters; k != NULL; k = k->Next)
5683 char *ip = k->IpAddressList.IpAddress.String;
5685 if (route_addrs[i].interface == k->Index)
5686 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
5689 /* Allocate a hostent and enough memory for all the IPs,
5690 * including the NULL at the end of the list.
5692 hostlist = WS_create_he(hostname, 1, 0, numroutes+1, sizeof(struct in_addr));
5693 if (hostlist == NULL)
5694 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
5695 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
5696 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
5697 hostlist->h_addrtype = AF_INET;
5698 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
5699 /* Reorder the entries before placing them in the host list. Windows expects
5700 * the IP list in order from highest priority to lowest (the critical thing
5701 * is that most applications expect the first IP to be the default route).
5703 if (numroutes > 1)
5704 qsort(route_addrs, numroutes, sizeof(struct route), WS_compare_routes_by_metric_asc);
5706 for (i = 0; i < numroutes; i++)
5707 (*(struct in_addr *) hostlist->h_addr_list[i]) = route_addrs[i].addr;
5709 /* Cleanup all allocated memory except the address list,
5710 * the address list is used by the calling app.
5712 cleanup:
5713 HeapFree(GetProcessHeap(), 0, route_addrs);
5714 HeapFree(GetProcessHeap(), 0, adapters);
5715 HeapFree(GetProcessHeap(), 0, routes);
5716 return hostlist;
5719 /***********************************************************************
5720 * gethostbyname (WS2_32.52)
5722 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
5724 struct WS_hostent *retval = NULL;
5725 struct hostent* host;
5726 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5727 char *extrabuf;
5728 int ebufsize=1024;
5729 struct hostent hostentry;
5730 int locerr = ENOBUFS;
5731 #endif
5732 char hostname[100];
5733 if(!num_startup) {
5734 SetLastError(WSANOTINITIALISED);
5735 return NULL;
5737 if( gethostname( hostname, 100) == -1) {
5738 SetLastError(WSAENOBUFS); /* appropriate ? */
5739 return retval;
5741 if( !name || !name[0]) {
5742 name = hostname;
5744 /* If the hostname of the local machine is requested then return the
5745 * complete list of local IP addresses */
5746 if(strcmp(name, hostname) == 0)
5747 retval = WS_get_local_ips(hostname);
5748 /* If any other hostname was requested (or the routing table lookup failed)
5749 * then return the IP found by the host OS */
5750 if(retval == NULL)
5752 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5753 host = NULL;
5754 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
5755 while(extrabuf) {
5756 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
5757 if( res != ERANGE) break;
5758 ebufsize *=2;
5759 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
5761 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
5762 #else
5763 EnterCriticalSection( &csWSgetXXXbyYYY );
5764 host = gethostbyname(name);
5765 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
5766 #endif
5767 if (host) retval = WS_dup_he(host);
5768 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5769 HeapFree(GetProcessHeap(),0,extrabuf);
5770 #else
5771 LeaveCriticalSection( &csWSgetXXXbyYYY );
5772 #endif
5774 if (retval && retval->h_addr_list[0][0] == 127 &&
5775 strcmp(name, "localhost") != 0)
5777 /* hostname != "localhost" but has loopback address. replace by our
5778 * special address.*/
5779 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
5781 TRACE( "%s ret %p\n", debugstr_a(name), retval );
5782 return retval;
5786 /***********************************************************************
5787 * getprotobyname (WS2_32.53)
5789 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
5791 struct WS_protoent* retval = NULL;
5792 #ifdef HAVE_GETPROTOBYNAME
5793 struct protoent* proto;
5794 EnterCriticalSection( &csWSgetXXXbyYYY );
5795 if( (proto = getprotobyname(name)) != NULL )
5797 retval = WS_dup_pe(proto);
5799 else {
5800 MESSAGE("protocol %s not found; You might want to add "
5801 "this to /etc/protocols\n", debugstr_a(name) );
5802 SetLastError(WSANO_DATA);
5804 LeaveCriticalSection( &csWSgetXXXbyYYY );
5805 #endif
5806 TRACE( "%s ret %p\n", debugstr_a(name), retval );
5807 return retval;
5811 /***********************************************************************
5812 * getprotobynumber (WS2_32.54)
5814 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
5816 struct WS_protoent* retval = NULL;
5817 #ifdef HAVE_GETPROTOBYNUMBER
5818 struct protoent* proto;
5819 EnterCriticalSection( &csWSgetXXXbyYYY );
5820 if( (proto = getprotobynumber(number)) != NULL )
5822 retval = WS_dup_pe(proto);
5824 else {
5825 MESSAGE("protocol number %d not found; You might want to add "
5826 "this to /etc/protocols\n", number );
5827 SetLastError(WSANO_DATA);
5829 LeaveCriticalSection( &csWSgetXXXbyYYY );
5830 #endif
5831 TRACE("%i ret %p\n", number, retval);
5832 return retval;
5836 /***********************************************************************
5837 * getservbyname (WS2_32.55)
5839 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
5841 struct WS_servent* retval = NULL;
5842 struct servent* serv;
5843 char *name_str;
5844 char *proto_str = NULL;
5846 if (!(name_str = strdup_lower(name))) return NULL;
5848 if (proto && *proto)
5850 if (!(proto_str = strdup_lower(proto)))
5852 HeapFree( GetProcessHeap(), 0, name_str );
5853 return NULL;
5857 EnterCriticalSection( &csWSgetXXXbyYYY );
5858 serv = getservbyname(name_str, proto_str);
5859 if( serv != NULL )
5861 retval = WS_dup_se(serv);
5863 else SetLastError(WSANO_DATA);
5864 LeaveCriticalSection( &csWSgetXXXbyYYY );
5865 HeapFree( GetProcessHeap(), 0, proto_str );
5866 HeapFree( GetProcessHeap(), 0, name_str );
5867 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
5868 return retval;
5871 /***********************************************************************
5872 * freeaddrinfo (WS2_32.@)
5874 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
5876 while (res) {
5877 struct WS_addrinfo *next;
5879 HeapFree(GetProcessHeap(),0,res->ai_canonname);
5880 HeapFree(GetProcessHeap(),0,res->ai_addr);
5881 next = res->ai_next;
5882 HeapFree(GetProcessHeap(),0,res);
5883 res = next;
5887 /* helper functions for getaddrinfo()/getnameinfo() */
5888 static int convert_aiflag_w2u(int winflags) {
5889 unsigned int i;
5890 int unixflags = 0;
5892 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
5893 if (ws_aiflag_map[i][0] & winflags) {
5894 unixflags |= ws_aiflag_map[i][1];
5895 winflags &= ~ws_aiflag_map[i][0];
5897 if (winflags)
5898 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
5899 return unixflags;
5902 static int convert_niflag_w2u(int winflags) {
5903 unsigned int i;
5904 int unixflags = 0;
5906 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
5907 if (ws_niflag_map[i][0] & winflags) {
5908 unixflags |= ws_niflag_map[i][1];
5909 winflags &= ~ws_niflag_map[i][0];
5911 if (winflags)
5912 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
5913 return unixflags;
5916 static int convert_aiflag_u2w(int unixflags) {
5917 unsigned int i;
5918 int winflags = 0;
5920 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
5921 if (ws_aiflag_map[i][1] & unixflags) {
5922 winflags |= ws_aiflag_map[i][0];
5923 unixflags &= ~ws_aiflag_map[i][1];
5925 if (unixflags) /* will warn usually */
5926 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
5927 return winflags;
5930 static int convert_eai_u2w(int unixret) {
5931 int i;
5933 if (!unixret) return 0;
5935 for (i=0;ws_eai_map[i][0];i++)
5936 if (ws_eai_map[i][1] == unixret)
5937 return ws_eai_map[i][0];
5939 if (unixret == EAI_SYSTEM)
5940 /* There are broken versions of glibc which return EAI_SYSTEM
5941 * and set errno to 0 instead of returning EAI_NONAME.
5943 return errno ? sock_get_error( errno ) : WS_EAI_NONAME;
5945 FIXME("Unhandled unix EAI_xxx ret %d\n", unixret);
5946 return unixret;
5949 static char *get_hostname(void)
5951 char *ret;
5952 DWORD size = 0;
5954 GetComputerNameExA( ComputerNamePhysicalDnsHostname, NULL, &size );
5955 if (GetLastError() != ERROR_MORE_DATA) return NULL;
5956 if (!(ret = HeapAlloc( GetProcessHeap(), 0, size ))) return NULL;
5957 if (!GetComputerNameExA( ComputerNamePhysicalDnsHostname, ret, &size ))
5959 HeapFree( GetProcessHeap(), 0, ret );
5960 return NULL;
5962 return ret;
5965 /***********************************************************************
5966 * getaddrinfo (WS2_32.@)
5968 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
5970 #ifdef HAVE_GETADDRINFO
5971 struct addrinfo *unixaires = NULL;
5972 int result;
5973 struct addrinfo unixhints, *punixhints = NULL;
5974 char *hostname = NULL;
5975 const char *node;
5977 *res = NULL;
5978 if (!nodename && !servname)
5980 SetLastError(WSAHOST_NOT_FOUND);
5981 return WSAHOST_NOT_FOUND;
5984 if (!nodename)
5985 node = NULL;
5986 else if (!nodename[0])
5988 node = hostname = get_hostname();
5989 if (!node) return WSA_NOT_ENOUGH_MEMORY;
5991 else
5992 node = nodename;
5994 /* servname tweak required by OSX and BSD kernels */
5995 if (servname && !servname[0]) servname = "0";
5997 if (hints) {
5998 punixhints = &unixhints;
6000 memset(&unixhints, 0, sizeof(unixhints));
6001 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
6003 /* zero is a wildcard, no need to convert */
6004 if (hints->ai_family)
6005 punixhints->ai_family = convert_af_w2u(hints->ai_family);
6006 if (hints->ai_socktype)
6007 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
6008 if (hints->ai_protocol)
6009 punixhints->ai_protocol = max(convert_proto_w2u(hints->ai_protocol), 0);
6011 if (punixhints->ai_socktype < 0)
6013 SetLastError(WSAESOCKTNOSUPPORT);
6014 HeapFree(GetProcessHeap(), 0, hostname);
6015 return SOCKET_ERROR;
6018 /* windows allows invalid combinations of socket type and protocol, unix does not.
6019 * fix the parameters here to make getaddrinfo call always work */
6020 if (punixhints->ai_protocol == IPPROTO_TCP &&
6021 punixhints->ai_socktype != SOCK_STREAM && punixhints->ai_socktype != SOCK_SEQPACKET)
6022 punixhints->ai_socktype = 0;
6024 else if (punixhints->ai_protocol == IPPROTO_UDP && punixhints->ai_socktype != SOCK_DGRAM)
6025 punixhints->ai_socktype = 0;
6027 else if (IS_IPX_PROTO(punixhints->ai_protocol) && punixhints->ai_socktype != SOCK_DGRAM)
6028 punixhints->ai_socktype = 0;
6031 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
6032 result = getaddrinfo(node, servname, punixhints, &unixaires);
6034 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
6035 HeapFree(GetProcessHeap(), 0, hostname);
6037 if (!result) {
6038 struct addrinfo *xuai = unixaires;
6039 struct WS_addrinfo **xai = res;
6041 *xai = NULL;
6042 while (xuai) {
6043 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
6044 SIZE_T len;
6046 if (!ai)
6047 goto outofmem;
6049 *xai = ai;xai = &ai->ai_next;
6050 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
6051 ai->ai_family = convert_af_u2w(xuai->ai_family);
6052 /* copy whatever was sent in the hints */
6053 if(hints) {
6054 ai->ai_socktype = hints->ai_socktype;
6055 ai->ai_protocol = hints->ai_protocol;
6056 } else {
6057 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
6058 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
6060 if (xuai->ai_canonname) {
6061 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
6062 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
6063 if (!ai->ai_canonname)
6064 goto outofmem;
6065 strcpy(ai->ai_canonname,xuai->ai_canonname);
6067 len = xuai->ai_addrlen;
6068 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
6069 if (!ai->ai_addr)
6070 goto outofmem;
6071 ai->ai_addrlen = len;
6072 do {
6073 int winlen = ai->ai_addrlen;
6075 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
6076 ai->ai_addrlen = winlen;
6077 break;
6079 len = 2*len;
6080 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
6081 if (!ai->ai_addr)
6082 goto outofmem;
6083 ai->ai_addrlen = len;
6084 } while (1);
6085 xuai = xuai->ai_next;
6087 freeaddrinfo(unixaires);
6089 if (TRACE_ON(winsock))
6091 struct WS_addrinfo *ai = *res;
6092 while (ai)
6094 TRACE("=> %p, flags %#x, family %d, type %d, protocol %d, len %ld, name %s, addr %s\n",
6095 ai, ai->ai_flags, ai->ai_family, ai->ai_socktype, ai->ai_protocol, ai->ai_addrlen,
6096 ai->ai_canonname, debugstr_sockaddr(ai->ai_addr));
6097 ai = ai->ai_next;
6100 } else
6101 result = convert_eai_u2w(result);
6103 SetLastError(result);
6104 return result;
6106 outofmem:
6107 if (*res) WS_freeaddrinfo(*res);
6108 if (unixaires) freeaddrinfo(unixaires);
6109 return WSA_NOT_ENOUGH_MEMORY;
6110 #else
6111 FIXME("getaddrinfo() failed, not found during buildtime.\n");
6112 return EAI_FAIL;
6113 #endif
6116 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
6118 struct WS_addrinfoW *ret;
6120 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
6121 ret->ai_flags = ai->ai_flags;
6122 ret->ai_family = ai->ai_family;
6123 ret->ai_socktype = ai->ai_socktype;
6124 ret->ai_protocol = ai->ai_protocol;
6125 ret->ai_addrlen = ai->ai_addrlen;
6126 ret->ai_canonname = NULL;
6127 ret->ai_addr = NULL;
6128 ret->ai_next = NULL;
6129 if (ai->ai_canonname)
6131 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
6132 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR))))
6134 HeapFree(GetProcessHeap(), 0, ret);
6135 return NULL;
6137 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
6139 if (ai->ai_addr)
6141 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, ai->ai_addrlen)))
6143 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
6144 HeapFree(GetProcessHeap(), 0, ret);
6145 return NULL;
6147 memcpy(ret->ai_addr, ai->ai_addr, ai->ai_addrlen);
6149 return ret;
6152 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
6154 struct WS_addrinfoW *ret, *infoW;
6156 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
6157 while (info->ai_next)
6159 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
6161 FreeAddrInfoW(ret);
6162 return NULL;
6164 infoW = infoW->ai_next;
6165 info = info->ai_next;
6167 return ret;
6170 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
6172 struct WS_addrinfo *ret;
6174 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
6175 ret->ai_flags = ai->ai_flags;
6176 ret->ai_family = ai->ai_family;
6177 ret->ai_socktype = ai->ai_socktype;
6178 ret->ai_protocol = ai->ai_protocol;
6179 ret->ai_addrlen = ai->ai_addrlen;
6180 ret->ai_canonname = NULL;
6181 ret->ai_addr = NULL;
6182 ret->ai_next = NULL;
6183 if (ai->ai_canonname)
6185 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
6186 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
6188 HeapFree(GetProcessHeap(), 0, ret);
6189 return NULL;
6191 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
6193 if (ai->ai_addr)
6195 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
6197 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
6198 HeapFree(GetProcessHeap(), 0, ret);
6199 return NULL;
6201 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
6203 return ret;
6206 /***********************************************************************
6207 * GetAddrInfoW (WS2_32.@)
6209 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
6211 int ret, len;
6212 char *nodenameA = NULL, *servnameA = NULL;
6213 struct WS_addrinfo *resA, *hintsA = NULL;
6215 *res = NULL;
6216 if (nodename)
6218 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
6219 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
6220 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
6222 if (servname)
6224 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
6225 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
6227 HeapFree(GetProcessHeap(), 0, nodenameA);
6228 return EAI_MEMORY;
6230 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
6233 if (hints) hintsA = addrinfo_WtoA(hints);
6234 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
6235 WS_freeaddrinfo(hintsA);
6237 if (!ret)
6239 *res = addrinfo_list_AtoW(resA);
6240 WS_freeaddrinfo(resA);
6243 HeapFree(GetProcessHeap(), 0, nodenameA);
6244 HeapFree(GetProcessHeap(), 0, servnameA);
6245 return ret;
6248 /***********************************************************************
6249 * FreeAddrInfoW (WS2_32.@)
6251 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
6253 while (ai)
6255 ADDRINFOW *next;
6256 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
6257 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
6258 next = ai->ai_next;
6259 HeapFree(GetProcessHeap(), 0, ai);
6260 ai = next;
6264 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
6265 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
6267 #ifdef HAVE_GETNAMEINFO
6268 int ret;
6269 union generic_unix_sockaddr sa_u;
6270 unsigned int size;
6272 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
6273 serv, servlen, flags);
6275 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
6276 if (!size)
6278 SetLastError(WSAEFAULT);
6279 return WSA_NOT_ENOUGH_MEMORY;
6281 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
6282 return convert_eai_u2w(ret);
6283 #else
6284 FIXME("getnameinfo() failed, not found during buildtime.\n");
6285 return EAI_FAIL;
6286 #endif
6289 int WINAPI GetNameInfoW(const SOCKADDR *sa, WS_socklen_t salen, PWCHAR host,
6290 DWORD hostlen, PWCHAR serv, DWORD servlen, INT flags)
6292 int ret;
6293 char *hostA = NULL, *servA = NULL;
6295 if (host && (!(hostA = HeapAlloc(GetProcessHeap(), 0, hostlen)))) return EAI_MEMORY;
6296 if (serv && (!(servA = HeapAlloc(GetProcessHeap(), 0, servlen))))
6298 HeapFree(GetProcessHeap(), 0, hostA);
6299 return EAI_MEMORY;
6302 ret = WS_getnameinfo(sa, salen, hostA, hostlen, servA, servlen, flags);
6303 if (!ret)
6305 if (host) MultiByteToWideChar(CP_ACP, 0, hostA, -1, host, hostlen);
6306 if (serv) MultiByteToWideChar(CP_ACP, 0, servA, -1, serv, servlen);
6309 HeapFree(GetProcessHeap(), 0, hostA);
6310 HeapFree(GetProcessHeap(), 0, servA);
6311 return ret;
6314 /***********************************************************************
6315 * getservbyport (WS2_32.56)
6317 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
6319 struct WS_servent* retval = NULL;
6320 #ifdef HAVE_GETSERVBYPORT
6321 struct servent* serv;
6322 char *proto_str = NULL;
6324 if (proto && *proto)
6326 if (!(proto_str = strdup_lower(proto))) return NULL;
6328 EnterCriticalSection( &csWSgetXXXbyYYY );
6329 if( (serv = getservbyport(port, proto_str)) != NULL ) {
6330 retval = WS_dup_se(serv);
6332 else SetLastError(WSANO_DATA);
6333 LeaveCriticalSection( &csWSgetXXXbyYYY );
6334 HeapFree( GetProcessHeap(), 0, proto_str );
6335 #endif
6336 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
6337 return retval;
6341 /***********************************************************************
6342 * gethostname (WS2_32.57)
6344 int WINAPI WS_gethostname(char *name, int namelen)
6346 char buf[256];
6347 int len;
6349 TRACE("name %p, len %d\n", name, namelen);
6351 if (!name)
6353 SetLastError(WSAEFAULT);
6354 return SOCKET_ERROR;
6357 if (gethostname(buf, sizeof(buf)) != 0)
6359 SetLastError(wsaErrno());
6360 return SOCKET_ERROR;
6363 TRACE("<- '%s'\n", buf);
6364 len = strlen(buf);
6365 if (len > 15)
6366 WARN("Windows supports NetBIOS name length up to 15 bytes!\n");
6367 if (namelen <= len)
6369 SetLastError(WSAEFAULT);
6370 WARN("<- not enough space for hostname, required %d, got %d!\n", len + 1, namelen);
6371 return SOCKET_ERROR;
6373 strcpy(name, buf);
6374 return 0;
6378 /* ------------------------------------- Windows sockets extensions -- *
6380 * ------------------------------------------------------------------- */
6382 /***********************************************************************
6383 * WSAEnumNetworkEvents (WS2_32.36)
6385 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
6387 int ret;
6388 int i;
6389 int errors[FD_MAX_EVENTS];
6391 TRACE("%04lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
6393 SERVER_START_REQ( get_socket_event )
6395 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6396 req->service = TRUE;
6397 req->c_event = wine_server_obj_handle( hEvent );
6398 wine_server_set_reply( req, errors, sizeof(errors) );
6399 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
6401 SERVER_END_REQ;
6402 if (!ret)
6404 for (i = 0; i < FD_MAX_EVENTS; i++)
6405 lpEvent->iErrorCode[i] = NtStatusToWSAError(errors[i]);
6406 return 0;
6408 SetLastError(WSAEINVAL);
6409 return SOCKET_ERROR;
6412 /***********************************************************************
6413 * WSAEventSelect (WS2_32.39)
6415 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
6417 int ret;
6419 TRACE("%04lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
6421 SERVER_START_REQ( set_socket_event )
6423 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6424 req->mask = lEvent;
6425 req->event = wine_server_obj_handle( hEvent );
6426 req->window = 0;
6427 req->msg = 0;
6428 ret = wine_server_call( req );
6430 SERVER_END_REQ;
6431 if (!ret) return 0;
6432 SetLastError(WSAEINVAL);
6433 return SOCKET_ERROR;
6436 /**********************************************************************
6437 * WSAGetOverlappedResult (WS2_32.40)
6439 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
6440 LPDWORD lpcbTransfer, BOOL fWait,
6441 LPDWORD lpdwFlags )
6443 NTSTATUS status;
6445 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
6446 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
6448 if ( lpOverlapped == NULL )
6450 ERR( "Invalid pointer\n" );
6451 SetLastError(WSA_INVALID_PARAMETER);
6452 return FALSE;
6455 status = lpOverlapped->Internal;
6456 if (status == STATUS_PENDING)
6458 if (!fWait)
6460 SetLastError( WSA_IO_INCOMPLETE );
6461 return FALSE;
6464 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
6465 INFINITE ) == WAIT_FAILED)
6466 return FALSE;
6467 status = lpOverlapped->Internal;
6470 if ( lpcbTransfer )
6471 *lpcbTransfer = lpOverlapped->InternalHigh;
6473 if ( lpdwFlags )
6474 *lpdwFlags = lpOverlapped->u.s.Offset;
6476 if (status) SetLastError( RtlNtStatusToDosError(status) );
6477 return !status;
6481 /***********************************************************************
6482 * WSAAsyncSelect (WS2_32.101)
6484 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
6486 int ret;
6488 TRACE("%04lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
6490 SERVER_START_REQ( set_socket_event )
6492 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6493 req->mask = lEvent;
6494 req->event = 0;
6495 req->window = wine_server_user_handle( hWnd );
6496 req->msg = uMsg;
6497 ret = wine_server_call( req );
6499 SERVER_END_REQ;
6500 if (!ret) return 0;
6501 SetLastError(WSAEINVAL);
6502 return SOCKET_ERROR;
6505 /***********************************************************************
6506 * WSACreateEvent (WS2_32.31)
6509 WSAEVENT WINAPI WSACreateEvent(void)
6511 /* Create a manual-reset event, with initial state: unsignaled */
6512 TRACE("\n");
6514 return CreateEventW(NULL, TRUE, FALSE, NULL);
6517 /***********************************************************************
6518 * WSACloseEvent (WS2_32.29)
6521 BOOL WINAPI WSACloseEvent(WSAEVENT event)
6523 TRACE ("event=%p\n", event);
6525 return CloseHandle(event);
6528 /***********************************************************************
6529 * WSASocketA (WS2_32.78)
6532 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
6533 LPWSAPROTOCOL_INFOA lpProtocolInfo,
6534 GROUP g, DWORD dwFlags)
6536 INT len;
6537 WSAPROTOCOL_INFOW info;
6539 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
6540 af, type, protocol, lpProtocolInfo, g, dwFlags);
6542 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
6544 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
6545 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
6546 info.szProtocol, WSAPROTOCOL_LEN + 1);
6548 if (!len)
6550 SetLastError(WSAEINVAL);
6551 return SOCKET_ERROR;
6554 return WSASocketW(af, type, protocol, &info, g, dwFlags);
6557 /***********************************************************************
6558 * WSASocketW (WS2_32.79)
6561 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
6562 LPWSAPROTOCOL_INFOW lpProtocolInfo,
6563 GROUP g, DWORD dwFlags)
6565 SOCKET ret;
6566 DWORD err;
6567 int unixaf, unixtype, ipxptype = -1;
6570 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
6571 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
6574 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
6575 af, type, protocol, lpProtocolInfo, g, dwFlags );
6577 if (!num_startup)
6579 err = WSANOTINITIALISED;
6580 goto done;
6583 /* hack for WSADuplicateSocket */
6584 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
6585 ret = lpProtocolInfo->dwServiceFlags3;
6586 TRACE("\tgot duplicate %04lx\n", ret);
6587 return ret;
6590 if (lpProtocolInfo)
6592 if (af == FROM_PROTOCOL_INFO || !af)
6593 af = lpProtocolInfo->iAddressFamily;
6594 if (type == FROM_PROTOCOL_INFO || !type)
6595 type = lpProtocolInfo->iSocketType;
6596 if (protocol == FROM_PROTOCOL_INFO || !protocol)
6597 protocol = lpProtocolInfo->iProtocol;
6600 if (!type && (af || protocol))
6602 int autoproto = protocol;
6603 WSAPROTOCOL_INFOW infow;
6605 /* default to the first valid protocol */
6606 if (!autoproto)
6607 autoproto = valid_protocols[0];
6608 else if(IS_IPX_PROTO(autoproto))
6609 autoproto = WS_NSPROTO_IPX;
6611 if (WS_EnterSingleProtocolW(autoproto, &infow))
6613 type = infow.iSocketType;
6615 /* after win2003 it's no longer possible to pass AF_UNSPEC
6616 using the protocol info struct */
6617 if (!lpProtocolInfo && af == WS_AF_UNSPEC)
6618 af = infow.iAddressFamily;
6623 Windows has an extension to the IPX protocol that allows one to create sockets
6624 and set the IPX packet type at the same time, to do that a caller will use
6625 a protocol like NSPROTO_IPX + <PACKET TYPE>
6627 if (IS_IPX_PROTO(protocol))
6628 ipxptype = protocol - WS_NSPROTO_IPX;
6630 /* convert the socket family, type and protocol */
6631 unixaf = convert_af_w2u(af);
6632 unixtype = convert_socktype_w2u(type);
6633 protocol = convert_proto_w2u(protocol);
6634 if (unixaf == AF_UNSPEC) unixaf = -1;
6636 /* filter invalid parameters */
6637 if (protocol < 0)
6639 /* the type could not be converted */
6640 if (type && unixtype < 0)
6642 err = WSAESOCKTNOSUPPORT;
6643 goto done;
6646 err = WSAEPROTONOSUPPORT;
6647 goto done;
6649 if (unixaf < 0)
6651 /* both family and protocol can't be invalid */
6652 if (protocol <= 0)
6654 err = WSAEINVAL;
6655 goto done;
6658 /* family could not be converted and neither socket type */
6659 if (unixtype < 0 && af >= 0)
6662 err = WSAESOCKTNOSUPPORT;
6663 goto done;
6666 err = WSAEAFNOSUPPORT;
6667 goto done;
6670 SERVER_START_REQ( create_socket )
6672 req->family = unixaf;
6673 req->type = unixtype;
6674 req->protocol = protocol;
6675 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
6676 req->attributes = (dwFlags & WSA_FLAG_NO_HANDLE_INHERIT) ? 0 : OBJ_INHERIT;
6677 req->flags = dwFlags & ~WSA_FLAG_NO_HANDLE_INHERIT;
6678 set_error( wine_server_call( req ) );
6679 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
6681 SERVER_END_REQ;
6682 if (ret)
6684 TRACE("\tcreated %04lx\n", ret );
6685 if (ipxptype > 0)
6686 set_ipx_packettype(ret, ipxptype);
6687 return ret;
6690 err = GetLastError();
6691 if (err == WSAEACCES) /* raw socket denied */
6693 if (type == SOCK_RAW)
6694 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
6695 else
6696 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
6698 else
6700 /* invalid combination of valid parameters, like SOCK_STREAM + IPPROTO_UDP */
6701 if (err == WSAEINVAL)
6702 err = WSAESOCKTNOSUPPORT;
6703 else if (err == WSAEOPNOTSUPP)
6704 err = WSAEPROTONOSUPPORT;
6707 done:
6708 WARN("\t\tfailed, error %d!\n", err);
6709 SetLastError(err);
6710 return INVALID_SOCKET;
6713 /***********************************************************************
6714 * WSAJoinLeaf (WS2_32.58)
6717 SOCKET WINAPI WSAJoinLeaf(
6718 SOCKET s,
6719 const struct WS_sockaddr *addr,
6720 int addrlen,
6721 LPWSABUF lpCallerData,
6722 LPWSABUF lpCalleeData,
6723 LPQOS lpSQOS,
6724 LPQOS lpGQOS,
6725 DWORD dwFlags)
6727 FIXME("stub.\n");
6728 return INVALID_SOCKET;
6731 /***********************************************************************
6732 * __WSAFDIsSet (WS2_32.151)
6734 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
6736 int i = set->fd_count, ret = 0;
6738 while (i--)
6739 if (set->fd_array[i] == s)
6741 ret = 1;
6742 break;
6745 TRACE("(socket %04lx, fd_set %p, count %i) <- %d\n", s, set, set->fd_count, ret);
6746 return ret;
6749 /***********************************************************************
6750 * WSAIsBlocking (WS2_32.114)
6752 BOOL WINAPI WSAIsBlocking(void)
6754 /* By default WinSock should set all its sockets to non-blocking mode
6755 * and poll in PeekMessage loop when processing "blocking" ones. This
6756 * function is supposed to tell if the program is in this loop. Our
6757 * blocking calls are truly blocking so we always return FALSE.
6759 * Note: It is allowed to call this function without prior WSAStartup().
6762 TRACE("\n");
6763 return FALSE;
6766 /***********************************************************************
6767 * WSACancelBlockingCall (WS2_32.113)
6769 INT WINAPI WSACancelBlockingCall(void)
6771 TRACE("\n");
6772 return 0;
6775 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
6777 FIXME("How was this called?\n");
6778 return x();
6782 /***********************************************************************
6783 * WSASetBlockingHook (WS2_32.109)
6785 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
6787 FARPROC prev = blocking_hook;
6788 blocking_hook = lpBlockFunc;
6789 TRACE("hook %p\n", lpBlockFunc);
6790 return prev;
6794 /***********************************************************************
6795 * WSAUnhookBlockingHook (WS2_32.110)
6797 INT WINAPI WSAUnhookBlockingHook(void)
6799 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
6800 return 0;
6804 /* ----------------------------------- end of API stuff */
6806 /* ----------------------------------- helper functions -
6808 * TODO: Merge WS_dup_..() stuff into one function that
6809 * would operate with a generic structure containing internal
6810 * pointers (via a template of some kind).
6813 static int list_size(char** l, int item_size)
6815 int i,j = 0;
6816 if(l)
6817 { for(i=0;l[i];i++)
6818 j += (item_size) ? item_size : strlen(l[i]) + 1;
6819 j += (i + 1) * sizeof(char*); }
6820 return j;
6823 static int list_dup(char** l_src, char** l_to, int item_size)
6825 char *p;
6826 int i;
6828 for (i = 0; l_src[i]; i++) ;
6829 p = (char *)(l_to + i + 1);
6830 for (i = 0; l_src[i]; i++)
6832 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
6833 memcpy(p, l_src[i], count);
6834 l_to[i] = p;
6835 p += count;
6837 l_to[i] = NULL;
6838 return p - (char *)l_to;
6841 /* ----- hostent */
6843 /* create a hostent entry
6845 * Creates the entry with enough memory for the name, aliases
6846 * addresses, and the address pointers. Also copies the name
6847 * and sets up all the pointers.
6849 * NOTE: The alias and address lists must be allocated with room
6850 * for the NULL item terminating the list. This is true even if
6851 * the list has no items ("aliases" and "addresses" must be
6852 * at least "1", a truly empty list is invalid).
6854 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length)
6856 struct WS_hostent *p_to;
6857 char *p;
6858 int size = (sizeof(struct WS_hostent) +
6859 strlen(name) + 1 +
6860 sizeof(char *) * aliases +
6861 aliases_size +
6862 sizeof(char *) * addresses +
6863 address_length * (addresses - 1)), i;
6865 if (!(p_to = check_buffer_he(size))) return NULL;
6866 memset(p_to, 0, size);
6868 /* Use the memory in the same way winsock does.
6869 * First set the pointer for aliases, second set the pointers for addresses.
6870 * Third fill the addresses indexes, fourth jump aliases names size.
6871 * Fifth fill the hostname.
6872 * NOTE: This method is valid for OS version's >= XP.
6874 p = (char *)(p_to + 1);
6875 p_to->h_aliases = (char **)p;
6876 p += sizeof(char *)*aliases;
6878 p_to->h_addr_list = (char **)p;
6879 p += sizeof(char *)*addresses;
6881 for (i = 0, addresses--; i < addresses; i++, p += address_length)
6882 p_to->h_addr_list[i] = p;
6884 /* NOTE: h_aliases must be filled in manually because we don't know each string
6885 * size, leave these pointers NULL (already set to NULL by memset earlier).
6887 p += aliases_size;
6889 p_to->h_name = p;
6890 strcpy(p, name);
6892 return p_to;
6895 /* duplicate hostent entry
6896 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
6897 * Ditto for protoent and servent.
6899 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
6901 int i, addresses = 0, alias_size = 0;
6902 struct WS_hostent *p_to;
6903 char *p;
6905 for( i = 0; p_he->h_aliases[i]; i++) alias_size += strlen(p_he->h_aliases[i]) + 1;
6906 while (p_he->h_addr_list[addresses]) addresses++;
6908 p_to = WS_create_he(p_he->h_name, i + 1, alias_size, addresses + 1, p_he->h_length);
6910 if (!p_to) return NULL;
6911 p_to->h_addrtype = convert_af_u2w(p_he->h_addrtype);
6912 p_to->h_length = p_he->h_length;
6914 for(i = 0, p = p_to->h_addr_list[0]; p_he->h_addr_list[i]; i++, p += p_to->h_length)
6915 memcpy(p, p_he->h_addr_list[i], p_to->h_length);
6917 /* Fill the aliases after the IP data */
6918 for(i = 0; p_he->h_aliases[i]; i++)
6920 p_to->h_aliases[i] = p;
6921 strcpy(p, p_he->h_aliases[i]);
6922 p += strlen(p) + 1;
6925 return p_to;
6928 /* ----- protoent */
6930 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
6932 char *p;
6933 struct WS_protoent *p_to;
6935 int size = (sizeof(*p_pe) +
6936 strlen(p_pe->p_name) + 1 +
6937 list_size(p_pe->p_aliases, 0));
6939 if (!(p_to = check_buffer_pe(size))) return NULL;
6940 p_to->p_proto = p_pe->p_proto;
6942 p = (char *)(p_to + 1);
6943 p_to->p_name = p;
6944 strcpy(p, p_pe->p_name);
6945 p += strlen(p) + 1;
6947 p_to->p_aliases = (char **)p;
6948 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
6949 return p_to;
6952 /* ----- servent */
6954 static struct WS_servent *WS_dup_se(const struct servent* p_se)
6956 char *p;
6957 struct WS_servent *p_to;
6959 int size = (sizeof(*p_se) +
6960 strlen(p_se->s_proto) + 1 +
6961 strlen(p_se->s_name) + 1 +
6962 list_size(p_se->s_aliases, 0));
6964 if (!(p_to = check_buffer_se(size))) return NULL;
6965 p_to->s_port = p_se->s_port;
6967 p = (char *)(p_to + 1);
6968 p_to->s_name = p;
6969 strcpy(p, p_se->s_name);
6970 p += strlen(p) + 1;
6972 p_to->s_proto = p;
6973 strcpy(p, p_se->s_proto);
6974 p += strlen(p) + 1;
6976 p_to->s_aliases = (char **)p;
6977 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
6978 return p_to;
6982 /***********************************************************************
6983 * WSARecv (WS2_32.67)
6985 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6986 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
6987 LPWSAOVERLAPPED lpOverlapped,
6988 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
6990 return WS2_recv_base(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
6991 NULL, NULL, lpOverlapped, lpCompletionRoutine, NULL);
6994 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6995 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
6996 struct WS_sockaddr *lpFrom,
6997 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
6998 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
6999 LPWSABUF lpControlBuffer )
7001 unsigned int i, options;
7002 int n, fd, err, overlapped, flags;
7003 struct ws2_async *wsa = NULL, localwsa;
7004 BOOL is_blocking;
7005 DWORD timeout_start = GetTickCount();
7006 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
7008 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
7009 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
7010 (lpFromlen ? *lpFromlen : -1),
7011 lpOverlapped, lpCompletionRoutine);
7013 fd = get_sock_fd( s, FILE_READ_DATA, &options );
7014 TRACE( "fd=%d, options=%x\n", fd, options );
7016 if (fd == -1) return SOCKET_ERROR;
7018 if (*lpFlags & WS_MSG_OOB)
7020 /* It's invalid to receive OOB data from an OOBINLINED socket
7021 * as OOB data is turned into normal data. */
7022 i = sizeof(n);
7023 if (!getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, (char*) &n, &i) && n)
7025 err = WSAEINVAL;
7026 goto error;
7030 overlapped = (lpOverlapped || lpCompletionRoutine) &&
7031 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
7032 if (overlapped || dwBufferCount > 1)
7034 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[dwBufferCount]))))
7036 err = WSAEFAULT;
7037 goto error;
7040 else
7041 wsa = &localwsa;
7043 wsa->hSocket = SOCKET2HANDLE(s);
7044 wsa->flags = *lpFlags;
7045 wsa->lpFlags = lpFlags;
7046 wsa->addr = lpFrom;
7047 wsa->addrlen.ptr = lpFromlen;
7048 wsa->control = lpControlBuffer;
7049 wsa->n_iovecs = dwBufferCount;
7050 wsa->first_iovec = 0;
7051 for (i = 0; i < dwBufferCount; i++)
7053 /* check buffer first to trigger write watches */
7054 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
7056 err = WSAEFAULT;
7057 goto error;
7059 wsa->iovec[i].iov_base = lpBuffers[i].buf;
7060 wsa->iovec[i].iov_len = lpBuffers[i].len;
7063 flags = convert_flags(wsa->flags);
7064 for (;;)
7066 n = WS2_recv( fd, wsa, flags );
7067 if (n == -1)
7069 /* Unix-like systems return EINVAL when attempting to read OOB data from
7070 * an empty socket buffer, convert that to a Windows expected return. */
7071 if ((flags & MSG_OOB) && errno == EINVAL)
7072 errno = EWOULDBLOCK;
7074 if (errno != EAGAIN)
7076 int loc_errno = errno;
7077 err = wsaErrno();
7078 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
7079 goto error;
7082 else if (lpNumberOfBytesRecvd) *lpNumberOfBytesRecvd = n;
7084 if (overlapped)
7086 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
7088 wsa->user_overlapped = lpOverlapped;
7089 wsa->completion_func = lpCompletionRoutine;
7090 release_sock_fd( s, fd );
7092 if (n == -1)
7094 iosb->u.Status = STATUS_PENDING;
7095 iosb->Information = 0;
7097 SERVER_START_REQ( register_async )
7099 req->type = ASYNC_TYPE_READ;
7100 req->async.handle = wine_server_obj_handle( wsa->hSocket );
7101 req->async.callback = wine_server_client_ptr( WS2_async_recv );
7102 req->async.iosb = wine_server_client_ptr( iosb );
7103 req->async.arg = wine_server_client_ptr( wsa );
7104 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
7105 req->async.cvalue = cvalue;
7106 err = wine_server_call( req );
7108 SERVER_END_REQ;
7110 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
7111 SetLastError(NtStatusToWSAError( err ));
7112 return SOCKET_ERROR;
7115 iosb->u.Status = STATUS_SUCCESS;
7116 iosb->Information = n;
7117 if (!wsa->completion_func)
7119 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
7120 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
7121 HeapFree( GetProcessHeap(), 0, wsa );
7123 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
7124 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
7125 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7126 return 0;
7129 if (n != -1) break;
7131 if ((err = _is_blocking( s, &is_blocking )))
7133 err = NtStatusToWSAError( err );
7134 goto error;
7137 if ( is_blocking )
7139 struct pollfd pfd;
7140 int poll_timeout = -1;
7141 INT64 timeout = get_rcvsnd_timeo(fd, TRUE);
7143 if (timeout)
7145 timeout -= GetTickCount() - timeout_start;
7146 if (timeout < 0) poll_timeout = 0;
7147 else poll_timeout = timeout <= INT_MAX ? timeout : INT_MAX;
7150 pfd.fd = fd;
7151 pfd.events = POLLIN;
7152 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
7154 if (!poll_timeout || !poll( &pfd, 1, poll_timeout ))
7156 err = WSAETIMEDOUT;
7157 /* a timeout is not fatal */
7158 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7159 goto error;
7162 else
7164 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7165 err = WSAEWOULDBLOCK;
7166 goto error;
7170 TRACE(" -> %i bytes\n", n);
7171 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
7172 release_sock_fd( s, fd );
7173 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7174 SetLastError(ERROR_SUCCESS);
7176 return 0;
7178 error:
7179 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
7180 release_sock_fd( s, fd );
7181 WARN(" -> ERROR %d\n", err);
7182 SetLastError( err );
7183 return SOCKET_ERROR;
7186 /***********************************************************************
7187 * WSARecvFrom (WS2_32.69)
7189 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
7190 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
7191 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
7192 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
7195 return WS2_recv_base( s, lpBuffers, dwBufferCount,
7196 lpNumberOfBytesRecvd, lpFlags,
7197 lpFrom, lpFromlen,
7198 lpOverlapped, lpCompletionRoutine, NULL );
7201 /***********************************************************************
7202 * WSCInstallProvider (WS2_32.88)
7204 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
7205 LPCWSTR lpszProviderDllPath,
7206 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
7207 DWORD dwNumberOfEntries,
7208 LPINT lpErrno )
7210 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
7211 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
7212 dwNumberOfEntries, lpErrno);
7213 *lpErrno = 0;
7214 return 0;
7218 /***********************************************************************
7219 * WSCDeinstallProvider (WS2_32.83)
7221 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
7223 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
7224 *lpErrno = 0;
7225 return 0;
7229 /***********************************************************************
7230 * WSAAccept (WS2_32.26)
7232 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
7233 LPCONDITIONPROC lpfnCondition, DWORD_PTR dwCallbackData)
7236 int ret = 0, size;
7237 WSABUF CallerId, CallerData, CalleeId, CalleeData;
7238 /* QOS SQOS, GQOS; */
7239 GROUP g;
7240 SOCKET cs;
7241 SOCKADDR src_addr, dst_addr;
7243 TRACE("socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
7244 s, addr, addrlen, lpfnCondition, dwCallbackData);
7246 cs = WS_accept(s, addr, addrlen);
7247 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
7248 if (!lpfnCondition) return cs;
7250 if (addr && addrlen)
7252 CallerId.buf = (char *)addr;
7253 CallerId.len = *addrlen;
7255 else
7257 size = sizeof(src_addr);
7258 WS_getpeername(cs, &src_addr, &size);
7259 CallerId.buf = (char *)&src_addr;
7260 CallerId.len = size;
7262 CallerData.buf = NULL;
7263 CallerData.len = 0;
7265 size = sizeof(dst_addr);
7266 WS_getsockname(cs, &dst_addr, &size);
7268 CalleeId.buf = (char *)&dst_addr;
7269 CalleeId.len = sizeof(dst_addr);
7271 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
7272 &CalleeId, &CalleeData, &g, dwCallbackData);
7274 switch (ret)
7276 case CF_ACCEPT:
7277 return cs;
7278 case CF_DEFER:
7279 SERVER_START_REQ( set_socket_deferred )
7281 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
7282 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
7283 if ( !wine_server_call_err ( req ) )
7285 SetLastError( WSATRY_AGAIN );
7286 WS_closesocket( cs );
7289 SERVER_END_REQ;
7290 return SOCKET_ERROR;
7291 case CF_REJECT:
7292 WS_closesocket(cs);
7293 SetLastError(WSAECONNREFUSED);
7294 return SOCKET_ERROR;
7295 default:
7296 FIXME("Unknown return type from Condition function\n");
7297 SetLastError(WSAENOTSOCK);
7298 return SOCKET_ERROR;
7302 /***********************************************************************
7303 * WSADuplicateSocketA (WS2_32.32)
7305 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
7307 return WS_DuplicateSocket(FALSE, s, dwProcessId, (LPWSAPROTOCOL_INFOW) lpProtocolInfo);
7310 /***********************************************************************
7311 * WSADuplicateSocketW (WS2_32.33)
7313 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
7315 return WS_DuplicateSocket(TRUE, s, dwProcessId, lpProtocolInfo);
7318 /***********************************************************************
7319 * WSAInstallServiceClassA (WS2_32.48)
7321 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
7323 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
7324 SetLastError(WSAEACCES);
7325 return SOCKET_ERROR;
7328 /***********************************************************************
7329 * WSAInstallServiceClassW (WS2_32.49)
7331 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
7333 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
7334 SetLastError(WSAEACCES);
7335 return SOCKET_ERROR;
7338 /***********************************************************************
7339 * WSARemoveServiceClass (WS2_32.70)
7341 int WINAPI WSARemoveServiceClass(LPGUID info)
7343 FIXME("Request to remove service %p\n",info);
7344 SetLastError(WSATYPE_NOT_FOUND);
7345 return SOCKET_ERROR;
7348 /***********************************************************************
7349 * inet_ntop (WS2_32.@)
7351 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
7353 #ifdef HAVE_INET_NTOP
7354 struct WS_in6_addr *in6;
7355 struct WS_in_addr *in;
7356 PCSTR pdst;
7358 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
7359 if (!buffer)
7361 SetLastError( STATUS_INVALID_PARAMETER );
7362 return NULL;
7365 switch (family)
7367 case WS_AF_INET:
7369 in = addr;
7370 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
7371 break;
7373 case WS_AF_INET6:
7375 in6 = addr;
7376 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
7377 break;
7379 default:
7380 SetLastError( WSAEAFNOSUPPORT );
7381 return NULL;
7384 if (!pdst) SetLastError( STATUS_INVALID_PARAMETER );
7385 return pdst;
7386 #else
7387 FIXME( "not supported on this platform\n" );
7388 SetLastError( WSAEAFNOSUPPORT );
7389 return NULL;
7390 #endif
7393 /***********************************************************************
7394 * inet_pton (WS2_32.@)
7396 INT WINAPI WS_inet_pton( INT family, PCSTR addr, PVOID buffer)
7398 #ifdef HAVE_INET_PTON
7399 int unixaf, ret;
7401 TRACE("family %d, addr '%s', buffer (%p)\n", family, addr ? addr : "(null)", buffer);
7403 if (!addr || !buffer)
7405 SetLastError(WSAEFAULT);
7406 return SOCKET_ERROR;
7409 unixaf = convert_af_w2u(family);
7410 if (unixaf != AF_INET && unixaf != AF_INET6)
7412 SetLastError(WSAEAFNOSUPPORT);
7413 return SOCKET_ERROR;
7416 ret = inet_pton(unixaf, addr, buffer);
7417 if (ret == -1) SetLastError(wsaErrno());
7418 return ret;
7419 #else
7420 FIXME( "not supported on this platform\n" );
7421 SetLastError( WSAEAFNOSUPPORT );
7422 return SOCKET_ERROR;
7423 #endif
7427 /***********************************************************************
7428 * WSAStringToAddressA (WS2_32.80)
7430 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
7431 INT AddressFamily,
7432 LPWSAPROTOCOL_INFOA lpProtocolInfo,
7433 LPSOCKADDR lpAddress,
7434 LPINT lpAddressLength)
7436 INT res=0;
7437 LPSTR workBuffer=NULL,ptrPort;
7439 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
7440 lpProtocolInfo, lpAddress, lpAddressLength );
7442 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
7444 if (!AddressString)
7446 SetLastError(WSAEINVAL);
7447 return SOCKET_ERROR;
7450 if (lpProtocolInfo)
7451 FIXME("ProtocolInfo not implemented.\n");
7453 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
7454 strlen(AddressString) + 1);
7455 if (!workBuffer)
7457 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7458 return SOCKET_ERROR;
7461 strcpy(workBuffer, AddressString);
7463 switch(AddressFamily)
7465 case WS_AF_INET:
7467 struct in_addr inetaddr;
7469 /* If lpAddressLength is too small, tell caller the size we need */
7470 if (*lpAddressLength < sizeof(SOCKADDR_IN))
7472 *lpAddressLength = sizeof(SOCKADDR_IN);
7473 res = WSAEFAULT;
7474 break;
7476 *lpAddressLength = sizeof(SOCKADDR_IN);
7477 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
7479 ((LPSOCKADDR_IN)lpAddress)->sin_family = WS_AF_INET;
7481 ptrPort = strchr(workBuffer, ':');
7482 if(ptrPort)
7484 /* User may have entered an IPv6 and asked to parse as IPv4 */
7485 if(strchr(ptrPort + 1, ':'))
7487 res = WSAEINVAL;
7488 break;
7490 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
7491 *ptrPort = '\0';
7493 else
7495 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
7498 if(inet_aton(workBuffer, &inetaddr) > 0)
7500 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
7501 res = 0;
7503 else
7504 res = WSAEINVAL;
7506 break;
7509 case WS_AF_INET6:
7511 struct in6_addr inetaddr;
7512 /* If lpAddressLength is too small, tell caller the size we need */
7513 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
7515 *lpAddressLength = sizeof(SOCKADDR_IN6);
7516 res = WSAEFAULT;
7517 break;
7519 #ifdef HAVE_INET_PTON
7520 *lpAddressLength = sizeof(SOCKADDR_IN6);
7521 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
7523 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
7525 /* This one is a bit tricky. An IPv6 address contains colons, so the
7526 * check from IPv4 doesn't work like that. However, IPv6 addresses that
7527 * contain a port are written with braces like [fd12:3456:7890::1]:12345
7528 * so what we will do is to look for ']', check if the next char is a
7529 * colon, and if it is, parse the port as in IPv4. */
7531 ptrPort = strchr(workBuffer, ']');
7532 if(ptrPort && *(++ptrPort) == ':')
7534 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort+1));
7535 *ptrPort = '\0';
7537 else
7539 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
7542 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
7544 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
7545 sizeof(struct in6_addr));
7546 res = 0;
7548 else
7549 #endif /* HAVE_INET_PTON */
7550 res = WSAEINVAL;
7552 break;
7554 default:
7555 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
7556 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
7557 res = WSAEINVAL;
7560 HeapFree(GetProcessHeap(), 0, workBuffer);
7562 if (!res) return 0;
7563 SetLastError(res);
7564 return SOCKET_ERROR;
7567 /***********************************************************************
7568 * WSAStringToAddressW (WS2_32.81)
7570 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
7571 * If this should be the case, it would be required to map these digits
7572 * to Unicode digits (0-9) using FoldString first.
7574 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
7575 INT AddressFamily,
7576 LPWSAPROTOCOL_INFOW lpProtocolInfo,
7577 LPSOCKADDR lpAddress,
7578 LPINT lpAddressLength)
7580 INT sBuffer,res=0;
7581 LPSTR workBuffer=NULL;
7582 WSAPROTOCOL_INFOA infoA;
7583 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
7585 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
7586 lpAddress, lpAddressLength );
7588 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
7590 /* if ProtocolInfo is available - convert to ANSI variant */
7591 if (lpProtocolInfo)
7593 lpProtoInfoA = &infoA;
7594 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
7596 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
7597 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
7599 SetLastError(WSAEINVAL);
7600 return SOCKET_ERROR;
7604 if (AddressString)
7606 /* Translate AddressString to ANSI code page - assumes that only
7607 standard digits 0-9 are used with this API call */
7608 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
7609 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
7611 if (workBuffer)
7613 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
7614 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
7615 lpAddress,lpAddressLength);
7616 HeapFree( GetProcessHeap(), 0, workBuffer );
7617 return res;
7619 else
7620 res = WSA_NOT_ENOUGH_MEMORY;
7622 else
7623 res = WSAEINVAL;
7625 SetLastError(res);
7626 return SOCKET_ERROR;
7629 /***********************************************************************
7630 * WSAAddressToStringA (WS2_32.27)
7632 * See WSAAddressToStringW
7634 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
7635 LPWSAPROTOCOL_INFOA info, LPSTR string,
7636 LPDWORD lenstr )
7638 DWORD size;
7639 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
7640 CHAR *p;
7642 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
7644 if (!sockaddr) return SOCKET_ERROR;
7645 if (!string || !lenstr) return SOCKET_ERROR;
7647 switch(sockaddr->sa_family)
7649 case WS_AF_INET:
7650 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
7651 sprintf( buffer, "%u.%u.%u.%u:%u",
7652 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
7653 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
7654 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
7655 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
7656 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
7658 p = strchr( buffer, ':' );
7659 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
7660 break;
7662 case WS_AF_INET6:
7664 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
7666 buffer[0] = 0;
7667 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
7668 if ((sockaddr6->sin6_port))
7669 strcpy(buffer, "[");
7670 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, buffer+strlen(buffer), sizeof(buffer)))
7672 SetLastError(WSAEINVAL);
7673 return SOCKET_ERROR;
7675 if ((sockaddr6->sin6_scope_id))
7676 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
7677 if ((sockaddr6->sin6_port))
7678 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
7679 break;
7682 default:
7683 SetLastError(WSAEINVAL);
7684 return SOCKET_ERROR;
7687 size = strlen( buffer ) + 1;
7689 if (*lenstr < size)
7691 *lenstr = size;
7692 SetLastError(WSAEFAULT);
7693 return SOCKET_ERROR;
7696 TRACE("=> %s,%u bytes\n", debugstr_a(buffer), size);
7697 *lenstr = size;
7698 strcpy( string, buffer );
7699 return 0;
7702 /***********************************************************************
7703 * WSAAddressToStringW (WS2_32.28)
7705 * Convert a sockaddr address into a readable address string.
7707 * PARAMS
7708 * sockaddr [I] Pointer to a sockaddr structure.
7709 * len [I] Size of the sockaddr structure.
7710 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
7711 * string [I/O] Pointer to a buffer to receive the address string.
7712 * lenstr [I/O] Size of the receive buffer in WCHARs.
7714 * RETURNS
7715 * Success: 0
7716 * Failure: SOCKET_ERROR
7718 * NOTES
7719 * The 'info' parameter is ignored.
7721 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
7722 LPWSAPROTOCOL_INFOW info, LPWSTR string,
7723 LPDWORD lenstr )
7725 INT ret;
7726 DWORD size;
7727 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
7728 CHAR bufAddr[54];
7730 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
7732 size = *lenstr;
7733 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
7735 if (ret) return ret;
7737 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
7739 if (*lenstr < size)
7741 *lenstr = size;
7742 SetLastError(WSAEFAULT);
7743 return SOCKET_ERROR;
7746 TRACE("=> %s,%u bytes\n", debugstr_w(buffer), size);
7747 *lenstr = size;
7748 lstrcpyW( string, buffer );
7749 return 0;
7752 /***********************************************************************
7753 * WSAEnumNameSpaceProvidersA (WS2_32.34)
7755 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
7757 FIXME( "(%p %p) Stub!\n", len, buffer );
7758 return 0;
7761 /***********************************************************************
7762 * WSAEnumNameSpaceProvidersW (WS2_32.35)
7764 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
7766 FIXME( "(%p %p) Stub!\n", len, buffer );
7767 return 0;
7770 /***********************************************************************
7771 * WSAGetQOSByName (WS2_32.41)
7773 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
7775 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
7776 return FALSE;
7779 /***********************************************************************
7780 * WSAGetServiceClassInfoA (WS2_32.42)
7782 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
7783 LPWSASERVICECLASSINFOA info )
7785 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
7786 len, info );
7787 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7788 return SOCKET_ERROR;
7791 /***********************************************************************
7792 * WSAGetServiceClassInfoW (WS2_32.43)
7794 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
7795 LPWSASERVICECLASSINFOW info )
7797 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
7798 len, info );
7799 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7800 return SOCKET_ERROR;
7803 /***********************************************************************
7804 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
7806 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
7808 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
7809 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7810 return SOCKET_ERROR;
7813 /***********************************************************************
7814 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
7816 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
7818 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
7819 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7820 return SOCKET_ERROR;
7823 /***********************************************************************
7824 * WSALookupServiceBeginA (WS2_32.59)
7826 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
7827 DWORD dwControlFlags,
7828 LPHANDLE lphLookup)
7830 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
7831 lphLookup);
7832 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7833 return SOCKET_ERROR;
7836 /***********************************************************************
7837 * WSALookupServiceBeginW (WS2_32.60)
7839 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
7840 DWORD dwControlFlags,
7841 LPHANDLE lphLookup)
7843 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
7844 lphLookup);
7845 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7846 return SOCKET_ERROR;
7849 /***********************************************************************
7850 * WSALookupServiceEnd (WS2_32.61)
7852 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
7854 FIXME("(%p) Stub!\n", lookup );
7855 return 0;
7858 /***********************************************************************
7859 * WSALookupServiceNextA (WS2_32.62)
7861 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
7863 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
7864 SetLastError(WSA_E_NO_MORE);
7865 return SOCKET_ERROR;
7868 /***********************************************************************
7869 * WSALookupServiceNextW (WS2_32.63)
7871 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
7873 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
7874 SetLastError(WSA_E_NO_MORE);
7875 return SOCKET_ERROR;
7878 /***********************************************************************
7879 * WSANtohl (WS2_32.64)
7881 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
7883 TRACE( "(%04lx 0x%08x %p)\n", s, netlong, lphostlong );
7885 if (!lphostlong) return WSAEFAULT;
7887 *lphostlong = ntohl( netlong );
7888 return 0;
7891 /***********************************************************************
7892 * WSANtohs (WS2_32.65)
7894 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
7896 TRACE( "(%04lx 0x%08x %p)\n", s, netshort, lphostshort );
7898 if (!lphostshort) return WSAEFAULT;
7900 *lphostshort = ntohs( netshort );
7901 return 0;
7904 /***********************************************************************
7905 * WSAProviderConfigChange (WS2_32.66)
7907 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
7908 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
7910 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
7911 return SOCKET_ERROR;
7914 /***********************************************************************
7915 * WSARecvDisconnect (WS2_32.68)
7917 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
7919 TRACE( "(%04lx %p)\n", s, disconnectdata );
7921 return WS_shutdown( s, SD_RECEIVE );
7924 /***********************************************************************
7925 * WSASetServiceA (WS2_32.76)
7927 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
7929 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
7930 return 0;
7933 /***********************************************************************
7934 * WSASetServiceW (WS2_32.77)
7936 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
7938 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
7939 return 0;
7942 /***********************************************************************
7943 * WSCEnableNSProvider (WS2_32.84)
7945 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
7947 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
7948 return 0;
7951 /***********************************************************************
7952 * WSCGetProviderPath (WS2_32.86)
7954 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
7956 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
7958 if (!errcode || !provider || !len) return WSAEFAULT;
7960 *errcode = WSAEINVAL;
7961 return SOCKET_ERROR;
7964 /***********************************************************************
7965 * WSCInstallNameSpace (WS2_32.87)
7967 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
7968 DWORD version, LPGUID provider )
7970 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
7971 namespace, version, debugstr_guid(provider) );
7972 return 0;
7975 /***********************************************************************
7976 * WSCUnInstallNameSpace (WS2_32.89)
7978 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
7980 FIXME("(%p) Stub!\n", lpProviderId);
7981 return NO_ERROR;
7984 /***********************************************************************
7985 * WSCWriteProviderOrder (WS2_32.91)
7987 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
7989 FIXME("(%p 0x%08x) Stub!\n", entry, number);
7990 return 0;
7993 /***********************************************************************
7994 * WSANSPIoctl (WS2_32.91)
7996 INT WINAPI WSANSPIoctl( HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer,
7997 DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer,
7998 LPDWORD lpcbBytesReturned, LPWSACOMPLETION lpCompletion )
8000 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup, dwControlCode,
8001 lpvInBuffer, cbInBuffer, lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpCompletion);
8002 SetLastError(WSA_NOT_ENOUGH_MEMORY);
8003 return SOCKET_ERROR;
8006 /*****************************************************************************
8007 * WSAEnumProtocolsA [WS2_32.@]
8009 * see function WSAEnumProtocolsW
8011 INT WINAPI WSAEnumProtocolsA( LPINT protocols, LPWSAPROTOCOL_INFOA buffer, LPDWORD len )
8013 return WS_EnumProtocols( FALSE, protocols, (LPWSAPROTOCOL_INFOW) buffer, len);
8016 /*****************************************************************************
8017 * WSAEnumProtocolsW [WS2_32.@]
8019 * Retrieves information about specified set of active network protocols.
8021 * PARAMS
8022 * protocols [I] Pointer to null-terminated array of protocol id's. NULL
8023 * retrieves information on all available protocols.
8024 * buffer [I] Pointer to a buffer to be filled with WSAPROTOCOL_INFO
8025 * structures.
8026 * len [I/O] Pointer to a variable specifying buffer size. On output
8027 * the variable holds the number of bytes needed when the
8028 * specified size is too small.
8030 * RETURNS
8031 * Success: number of WSAPROTOCOL_INFO structures in buffer.
8032 * Failure: SOCKET_ERROR
8034 * NOTES
8035 * NT4SP5 does not return SPX if protocols == NULL
8037 * BUGS
8038 * - NT4SP5 returns in addition these list of NETBIOS protocols
8039 * (address family 17), each entry two times one for socket type 2 and 5
8041 * iProtocol szProtocol
8042 * 0x80000000 \Device\NwlnkNb
8043 * 0xfffffffa \Device\NetBT_CBENT7
8044 * 0xfffffffb \Device\Nbf_CBENT7
8045 * 0xfffffffc \Device\NetBT_NdisWan5
8046 * 0xfffffffd \Device\NetBT_El9202
8047 * 0xfffffffe \Device\Nbf_El9202
8048 * 0xffffffff \Device\Nbf_NdisWan4
8050 * - there is no check that the operating system supports the returned
8051 * protocols
8053 INT WINAPI WSAEnumProtocolsW( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
8055 return WS_EnumProtocols( TRUE, protocols, buffer, len);
8058 /*****************************************************************************
8059 * WSCEnumProtocols [WS2_32.@]
8061 * PARAMS
8062 * protocols [I] Null-terminated array of iProtocol values.
8063 * buffer [O] Buffer of WSAPROTOCOL_INFOW structures.
8064 * len [I/O] Size of buffer on input/output.
8065 * errno [O] Error code.
8067 * RETURNS
8068 * Success: number of protocols to be reported on.
8069 * Failure: SOCKET_ERROR. error is in errno.
8071 * BUGS
8072 * Doesn't supply info on layered protocols.
8075 INT WINAPI WSCEnumProtocols( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len, LPINT err )
8077 INT ret = WSAEnumProtocolsW( protocols, buffer, len );
8079 if (ret == SOCKET_ERROR) *err = WSAENOBUFS;
8081 return ret;