qmgr: Add IHttpNegotiate support to the bind status callback.
[wine.git] / dlls / ws2_32 / socket.c
blobfdf68a38f6ad46b1e67f0768324e698cd503ece9
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 struct per_thread_data *get_per_thread_data(void)
1101 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
1102 /* lazy initialization */
1103 if (!ptb)
1105 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
1106 NtCurrentTeb()->WinSockData = ptb;
1108 return ptb;
1111 static void free_per_thread_data(void)
1113 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
1115 if (!ptb) return;
1117 /* delete scratch buffers */
1118 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1119 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1120 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1121 ptb->he_buffer = NULL;
1122 ptb->se_buffer = NULL;
1123 ptb->pe_buffer = NULL;
1125 HeapFree( GetProcessHeap(), 0, ptb );
1126 NtCurrentTeb()->WinSockData = NULL;
1129 /***********************************************************************
1130 * DllMain (WS2_32.init)
1132 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
1134 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
1135 switch (fdwReason) {
1136 case DLL_PROCESS_ATTACH:
1137 break;
1138 case DLL_PROCESS_DETACH:
1139 if (fImpLoad) break;
1140 free_per_thread_data();
1141 DeleteCriticalSection(&csWSgetXXXbyYYY);
1142 break;
1143 case DLL_THREAD_DETACH:
1144 free_per_thread_data();
1145 break;
1147 return TRUE;
1150 /***********************************************************************
1151 * convert_flags()
1153 * Converts send/recv flags from Windows format.
1154 * Return the converted flag bits, unsupported flags remain unchanged.
1156 static int convert_flags(int flags)
1158 int i, out;
1159 if (!flags) return 0;
1161 for (out = i = 0; flags && i < sizeof(ws_flags_map) / sizeof(ws_flags_map[0]); i++)
1163 if (ws_flags_map[i][0] & flags)
1165 out |= ws_flags_map[i][1];
1166 flags &= ~ws_flags_map[i][0];
1169 if (flags)
1171 FIXME("Unknown send/recv flags 0x%x, using anyway...\n", flags);
1172 out |= flags;
1174 return out;
1177 /***********************************************************************
1178 * convert_sockopt()
1180 * Converts socket flags from Windows format.
1181 * Return 1 if converted, 0 if not (error).
1183 static int convert_sockopt(INT *level, INT *optname)
1185 unsigned int i;
1186 switch (*level)
1188 case WS_SOL_SOCKET:
1189 *level = SOL_SOCKET;
1190 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
1191 if( ws_sock_map[i][0] == *optname )
1193 *optname = ws_sock_map[i][1];
1194 return 1;
1197 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
1198 break;
1199 case WS_IPPROTO_TCP:
1200 *level = IPPROTO_TCP;
1201 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
1202 if ( ws_tcp_map[i][0] == *optname )
1204 *optname = ws_tcp_map[i][1];
1205 return 1;
1208 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
1209 break;
1210 case WS_IPPROTO_IP:
1211 *level = IPPROTO_IP;
1212 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
1213 if (ws_ip_map[i][0] == *optname )
1215 *optname = ws_ip_map[i][1];
1216 return 1;
1219 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
1220 break;
1221 case WS_IPPROTO_IPV6:
1222 *level = IPPROTO_IPV6;
1223 for(i=0; i<sizeof(ws_ipv6_map)/sizeof(ws_ipv6_map[0]); i++) {
1224 if (ws_ipv6_map[i][0] == *optname )
1226 *optname = ws_ipv6_map[i][1];
1227 return 1;
1230 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname);
1231 break;
1232 default: FIXME("Unimplemented or unknown socket level\n");
1234 return 0;
1237 /* ----------------------------------- Per-thread info (or per-process?) */
1239 static char *strdup_lower(const char *str)
1241 int i;
1242 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
1244 if (ret)
1246 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
1247 ret[i] = 0;
1249 else SetLastError(WSAENOBUFS);
1250 return ret;
1253 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
1254 * from an fd and return the value converted to milli seconds
1255 * or 0 if there is an infinite time out */
1256 static inline INT64 get_rcvsnd_timeo( int fd, BOOL is_recv)
1258 struct timeval tv;
1259 socklen_t len = sizeof(tv);
1260 int optname, res;
1262 if (is_recv)
1263 #ifdef SO_RCVTIMEO
1264 optname = SO_RCVTIMEO;
1265 #else
1266 return 0;
1267 #endif
1268 else
1269 #ifdef SO_SNDTIMEO
1270 optname = SO_SNDTIMEO;
1271 #else
1272 return 0;
1273 #endif
1275 res = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
1276 if (res < 0)
1277 return 0;
1278 return (UINT64)tv.tv_sec * 1000 + tv.tv_usec / 1000;
1281 /* utility: given an fd, will block until one of the events occurs */
1282 static inline int do_block( int fd, int events, int timeout )
1284 struct pollfd pfd;
1285 int ret;
1287 pfd.fd = fd;
1288 pfd.events = events;
1290 while ((ret = poll(&pfd, 1, timeout)) < 0)
1292 if (errno != EINTR)
1293 return -1;
1295 if( ret == 0 )
1296 return 0;
1297 return pfd.revents;
1300 static int
1301 convert_af_w2u(int windowsaf) {
1302 unsigned int i;
1304 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1305 if (ws_af_map[i][0] == windowsaf)
1306 return ws_af_map[i][1];
1307 FIXME("unhandled Windows address family %d\n", windowsaf);
1308 return -1;
1311 static int
1312 convert_af_u2w(int unixaf) {
1313 unsigned int i;
1315 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1316 if (ws_af_map[i][1] == unixaf)
1317 return ws_af_map[i][0];
1318 FIXME("unhandled UNIX address family %d\n", unixaf);
1319 return -1;
1322 static int
1323 convert_proto_w2u(int windowsproto) {
1324 unsigned int i;
1326 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1327 if (ws_proto_map[i][0] == windowsproto)
1328 return ws_proto_map[i][1];
1330 /* check for extended IPX */
1331 if (IS_IPX_PROTO(windowsproto))
1332 return windowsproto;
1334 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
1335 return -1;
1338 static int
1339 convert_proto_u2w(int unixproto) {
1340 unsigned int i;
1342 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1343 if (ws_proto_map[i][1] == unixproto)
1344 return ws_proto_map[i][0];
1346 /* if value is inside IPX range just return it - the kernel simply
1347 * echoes the value used in the socket() function */
1348 if (IS_IPX_PROTO(unixproto))
1349 return unixproto;
1351 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
1352 return -1;
1355 static int
1356 convert_socktype_w2u(int windowssocktype) {
1357 unsigned int i;
1359 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1360 if (ws_socktype_map[i][0] == windowssocktype)
1361 return ws_socktype_map[i][1];
1362 FIXME("unhandled Windows socket type %d\n", windowssocktype);
1363 return -1;
1366 static int
1367 convert_socktype_u2w(int unixsocktype) {
1368 unsigned int i;
1370 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1371 if (ws_socktype_map[i][1] == unixsocktype)
1372 return ws_socktype_map[i][0];
1373 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
1374 return -1;
1377 static int set_ipx_packettype(int sock, int ptype)
1379 #ifdef HAS_IPX
1380 int fd = get_sock_fd( sock, 0, NULL ), ret = 0;
1381 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", ptype, fd);
1383 if (fd == -1) return SOCKET_ERROR;
1385 /* We try to set the ipx type on ipx socket level. */
1386 #ifdef SOL_IPX
1387 if(setsockopt(fd, SOL_IPX, IPX_TYPE, &ptype, sizeof(ptype)) == -1)
1389 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
1390 ret = SOCKET_ERROR;
1392 #else
1394 struct ipx val;
1395 /* Should we retrieve val using a getsockopt call and then
1396 * set the modified one? */
1397 val.ipx_pt = ptype;
1398 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
1400 #endif
1401 release_sock_fd( sock, fd );
1402 return ret;
1403 #else
1404 WARN("IPX support is not enabled, can't set packet type\n");
1405 return SOCKET_ERROR;
1406 #endif
1409 /* ----------------------------------- API -----
1411 * Init / cleanup / error checking.
1414 /***********************************************************************
1415 * WSAStartup (WS2_32.115)
1417 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
1419 TRACE("verReq=%x\n", wVersionRequested);
1421 if (LOBYTE(wVersionRequested) < 1)
1422 return WSAVERNOTSUPPORTED;
1424 if (!lpWSAData) return WSAEINVAL;
1426 num_startup++;
1428 /* that's the whole of the negotiation for now */
1429 lpWSAData->wVersion = wVersionRequested;
1430 /* return winsock information */
1431 lpWSAData->wHighVersion = 0x0202;
1432 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
1433 strcpy(lpWSAData->szSystemStatus, "Running" );
1434 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
1435 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
1436 /* don't do anything with lpWSAData->lpVendorInfo */
1437 /* (some apps don't allocate the space for this field) */
1439 TRACE("succeeded starts: %d\n", num_startup);
1440 return 0;
1444 /***********************************************************************
1445 * WSACleanup (WS2_32.116)
1447 INT WINAPI WSACleanup(void)
1449 if (num_startup) {
1450 num_startup--;
1451 TRACE("pending cleanups: %d\n", num_startup);
1452 return 0;
1454 SetLastError(WSANOTINITIALISED);
1455 return SOCKET_ERROR;
1459 /***********************************************************************
1460 * WSAGetLastError (WS2_32.111)
1462 INT WINAPI WSAGetLastError(void)
1464 return GetLastError();
1467 /***********************************************************************
1468 * WSASetLastError (WS2_32.112)
1470 void WINAPI WSASetLastError(INT iError) {
1471 SetLastError(iError);
1474 static struct WS_hostent *check_buffer_he(int size)
1476 struct per_thread_data * ptb = get_per_thread_data();
1477 if (ptb->he_buffer)
1479 if (ptb->he_len >= size ) return ptb->he_buffer;
1480 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1482 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
1483 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
1484 return ptb->he_buffer;
1487 static struct WS_servent *check_buffer_se(int size)
1489 struct per_thread_data * ptb = get_per_thread_data();
1490 if (ptb->se_buffer)
1492 if (ptb->se_len >= size ) return ptb->se_buffer;
1493 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1495 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
1496 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
1497 return ptb->se_buffer;
1500 static struct WS_protoent *check_buffer_pe(int size)
1502 struct per_thread_data * ptb = get_per_thread_data();
1503 if (ptb->pe_buffer)
1505 if (ptb->pe_len >= size ) return ptb->pe_buffer;
1506 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1508 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
1509 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
1510 return ptb->pe_buffer;
1513 /* ----------------------------------- i/o APIs */
1515 static inline BOOL supported_pf(int pf)
1517 switch (pf)
1519 case WS_AF_INET:
1520 case WS_AF_INET6:
1521 return TRUE;
1522 #ifdef HAS_IPX
1523 case WS_AF_IPX:
1524 return TRUE;
1525 #endif
1526 #ifdef HAS_IRDA
1527 case WS_AF_IRDA:
1528 return TRUE;
1529 #endif
1530 default:
1531 return FALSE;
1535 static inline BOOL supported_protocol(int protocol)
1537 int i;
1538 for (i = 0; i < sizeof(valid_protocols) / sizeof(valid_protocols[0]); i++)
1539 if (protocol == valid_protocols[i])
1540 return TRUE;
1541 return FALSE;
1544 /**********************************************************************/
1546 /* Returns the length of the converted address if successful, 0 if it was too small to
1547 * start with.
1549 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
1550 union generic_unix_sockaddr *uaddr)
1552 unsigned int uaddrlen = 0;
1554 switch (wsaddr->sa_family)
1556 #ifdef HAS_IPX
1557 case WS_AF_IPX:
1559 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
1560 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
1562 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
1563 return 0;
1565 uaddrlen = sizeof(struct sockaddr_ipx);
1566 memset( uaddr, 0, uaddrlen );
1567 uipx->sipx_family=AF_IPX;
1568 uipx->sipx_port=wsipx->sa_socket;
1569 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1570 * in one go
1572 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
1573 #ifdef IPX_FRAME_NONE
1574 uipx->sipx_type=IPX_FRAME_NONE;
1575 #endif
1576 break;
1578 #endif
1579 case WS_AF_INET6: {
1580 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
1581 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
1583 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1584 * scope_id, one without.
1586 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
1587 uaddrlen = sizeof(struct sockaddr_in6);
1588 memset( uaddr, 0, uaddrlen );
1589 uin6->sin6_family = AF_INET6;
1590 uin6->sin6_port = win6->sin6_port;
1591 uin6->sin6_flowinfo = win6->sin6_flowinfo;
1592 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1593 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
1594 #endif
1595 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
1596 break;
1598 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
1599 return 0;
1601 case WS_AF_INET: {
1602 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
1603 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
1605 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
1606 return 0;
1607 uaddrlen = sizeof(struct sockaddr_in);
1608 memset( uaddr, 0, uaddrlen );
1609 uin->sin_family = AF_INET;
1610 uin->sin_port = win->sin_port;
1611 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
1612 break;
1614 #ifdef HAS_IRDA
1615 case WS_AF_IRDA: {
1616 struct sockaddr_irda *uin = (struct sockaddr_irda *)uaddr;
1617 const SOCKADDR_IRDA *win = (const SOCKADDR_IRDA *)wsaddr;
1619 if (wsaddrlen < sizeof(SOCKADDR_IRDA))
1620 return 0;
1621 uaddrlen = sizeof(struct sockaddr_irda);
1622 memset( uaddr, 0, uaddrlen );
1623 uin->sir_family = AF_IRDA;
1624 if (!strncmp( win->irdaServiceName, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1626 unsigned int lsap_sel = 0;
1628 sscanf( win->irdaServiceName, "LSAP-SEL%u", &lsap_sel );
1629 uin->sir_lsap_sel = lsap_sel;
1631 else
1633 uin->sir_lsap_sel = LSAP_ANY;
1634 memcpy( uin->sir_name, win->irdaServiceName, 25 );
1636 memcpy( &uin->sir_addr, win->irdaDeviceID, sizeof(uin->sir_addr) );
1637 break;
1639 #endif
1640 case WS_AF_UNSPEC: {
1641 /* Try to determine the needed space by the passed windows sockaddr space */
1642 switch (wsaddrlen) {
1643 default: /* likely an ipv4 address */
1644 case sizeof(struct WS_sockaddr_in):
1645 uaddrlen = sizeof(struct sockaddr_in);
1646 break;
1647 #ifdef HAS_IPX
1648 case sizeof(struct WS_sockaddr_ipx):
1649 uaddrlen = sizeof(struct sockaddr_ipx);
1650 break;
1651 #endif
1652 #ifdef HAS_IRDA
1653 case sizeof(SOCKADDR_IRDA):
1654 uaddrlen = sizeof(struct sockaddr_irda);
1655 break;
1656 #endif
1657 case sizeof(struct WS_sockaddr_in6):
1658 case sizeof(struct WS_sockaddr_in6_old):
1659 uaddrlen = sizeof(struct sockaddr_in6);
1660 break;
1662 memset( uaddr, 0, uaddrlen );
1663 break;
1665 default:
1666 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
1667 return 0;
1669 return uaddrlen;
1672 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
1674 switch (uaddr->sa_family)
1676 #ifdef HAS_IPX
1677 case AF_IPX:
1679 static const struct sockaddr_ipx emptyAddr;
1680 struct sockaddr_ipx *ipx = (struct sockaddr_ipx*) uaddr;
1681 return ipx->sipx_port
1682 || memcmp(&ipx->sipx_network, &emptyAddr.sipx_network, sizeof(emptyAddr.sipx_network))
1683 || memcmp(&ipx->sipx_node, &emptyAddr.sipx_node, sizeof(emptyAddr.sipx_node));
1685 #endif
1686 case AF_INET6:
1688 static const struct sockaddr_in6 emptyAddr;
1689 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
1690 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
1692 case AF_INET:
1694 static const struct sockaddr_in emptyAddr;
1695 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
1696 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
1698 case AF_UNSPEC:
1699 return FALSE;
1700 default:
1701 FIXME("unknown address family %d\n", uaddr->sa_family);
1702 return TRUE;
1706 /* Returns -1 if getsockname fails, 0 if not bound, 1 otherwise */
1707 static int is_fd_bound(int fd, union generic_unix_sockaddr *uaddr, socklen_t *uaddrlen)
1709 union generic_unix_sockaddr inaddr;
1710 socklen_t inlen;
1711 int res;
1713 if (!uaddr) uaddr = &inaddr;
1714 if (!uaddrlen) uaddrlen = &inlen;
1716 *uaddrlen = sizeof(inaddr);
1717 res = getsockname(fd, &uaddr->addr, uaddrlen);
1718 if (!res) res = is_sockaddr_bound(&uaddr->addr, *uaddrlen);
1719 return res;
1722 /* Returns 0 if successful, -1 if the buffer is too small */
1723 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
1725 int res;
1727 switch(uaddr->sa_family)
1729 #ifdef HAS_IPX
1730 case AF_IPX:
1732 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
1733 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
1735 res=-1;
1736 switch (*wsaddrlen) /* how much can we copy? */
1738 default:
1739 res=0; /* enough */
1740 *wsaddrlen = sizeof(*wsipx);
1741 wsipx->sa_socket=uipx->sipx_port;
1742 /* fall through */
1743 case 13:
1744 case 12:
1745 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
1746 /* fall through */
1747 case 11:
1748 case 10:
1749 case 9:
1750 case 8:
1751 case 7:
1752 case 6:
1753 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1754 /* fall through */
1755 case 5:
1756 case 4:
1757 case 3:
1758 case 2:
1759 wsipx->sa_family=WS_AF_IPX;
1760 /* fall through */
1761 case 1:
1762 case 0:
1763 /* way too small */
1764 break;
1767 break;
1768 #endif
1769 #ifdef HAS_IRDA
1770 case AF_IRDA: {
1771 const struct sockaddr_irda *uin = (const struct sockaddr_irda *)uaddr;
1772 SOCKADDR_IRDA *win = (SOCKADDR_IRDA *)wsaddr;
1774 if (*wsaddrlen < sizeof(SOCKADDR_IRDA))
1775 return -1;
1776 win->irdaAddressFamily = WS_AF_IRDA;
1777 memcpy( win->irdaDeviceID, &uin->sir_addr, sizeof(win->irdaDeviceID) );
1778 if (uin->sir_lsap_sel != LSAP_ANY)
1779 sprintf( win->irdaServiceName, "LSAP-SEL%u", uin->sir_lsap_sel );
1780 else
1781 memcpy( win->irdaServiceName, uin->sir_name,
1782 sizeof(win->irdaServiceName) );
1783 return 0;
1785 #endif
1786 case AF_INET6: {
1787 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1788 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1790 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1791 return -1;
1792 win6old->sin6_family = WS_AF_INET6;
1793 win6old->sin6_port = uin6->sin6_port;
1794 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1795 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1796 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1797 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1798 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1799 win6->sin6_scope_id = uin6->sin6_scope_id;
1800 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1802 else
1803 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1804 #else
1805 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1806 #endif
1807 return 0;
1809 case AF_INET: {
1810 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1811 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1813 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1814 return -1;
1815 win->sin_family = WS_AF_INET;
1816 win->sin_port = uin->sin_port;
1817 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1818 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1819 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1820 return 0;
1822 case AF_UNSPEC: {
1823 memset(wsaddr,0,*wsaddrlen);
1824 return 0;
1826 default:
1827 FIXME("Unknown address family %d\n", uaddr->sa_family);
1828 return -1;
1830 return res;
1833 static INT WS_DuplicateSocket(BOOL unicode, SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo)
1835 HANDLE hProcess;
1836 int size;
1837 WSAPROTOCOL_INFOW infow;
1839 TRACE("(unicode %d, socket %04lx, processid %x, buffer %p)\n",
1840 unicode, s, dwProcessId, lpProtocolInfo);
1842 if (!ws_protocol_info(s, unicode, &infow, &size))
1843 return SOCKET_ERROR;
1845 if (!(hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId)))
1847 SetLastError(WSAEINVAL);
1848 return SOCKET_ERROR;
1851 if (!lpProtocolInfo)
1853 CloseHandle(hProcess);
1854 SetLastError(WSAEFAULT);
1855 return SOCKET_ERROR;
1858 /* I don't know what the real Windoze does next, this is a hack */
1859 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
1860 * the target use the global duplicate, or we could copy a reference to us to the structure
1861 * and let the target duplicate it from us, but let's do it as simple as possible */
1862 memcpy(lpProtocolInfo, &infow, size);
1863 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
1864 hProcess, (LPHANDLE)&lpProtocolInfo->dwServiceFlags3,
1865 0, FALSE, DUPLICATE_SAME_ACCESS);
1866 CloseHandle(hProcess);
1867 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
1868 return 0;
1871 /*****************************************************************************
1872 * WS_EnterSingleProtocolW [internal]
1874 * enters the protocol information of one given protocol into the given
1875 * buffer.
1877 * RETURNS
1878 * TRUE if a protocol was entered into the buffer.
1880 * BUGS
1881 * - only implemented for IPX, SPX, SPXII, TCP, UDP
1882 * - there is no check that the operating system supports the returned
1883 * protocols
1885 static BOOL WS_EnterSingleProtocolW( INT protocol, WSAPROTOCOL_INFOW* info )
1887 memset( info, 0, sizeof(WSAPROTOCOL_INFOW) );
1888 info->iProtocol = protocol;
1890 switch (protocol)
1892 case WS_IPPROTO_TCP:
1893 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_EXPEDITED_DATA |
1894 XP1_GRACEFUL_CLOSE | XP1_GUARANTEED_ORDER |
1895 XP1_GUARANTEED_DELIVERY;
1896 info->ProviderId = ProviderIdIP;
1897 info->dwCatalogEntryId = 0x3e9;
1898 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1899 info->ProtocolChain.ChainLen = 1;
1900 info->iVersion = 2;
1901 info->iAddressFamily = WS_AF_INET;
1902 info->iMaxSockAddr = 0x10;
1903 info->iMinSockAddr = 0x10;
1904 info->iSocketType = WS_SOCK_STREAM;
1905 strcpyW( info->szProtocol, NameTcpW );
1906 break;
1908 case WS_IPPROTO_UDP:
1909 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_SUPPORT_BROADCAST |
1910 XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED |
1911 XP1_CONNECTIONLESS;
1912 info->ProviderId = ProviderIdIP;
1913 info->dwCatalogEntryId = 0x3ea;
1914 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1915 info->ProtocolChain.ChainLen = 1;
1916 info->iVersion = 2;
1917 info->iAddressFamily = WS_AF_INET;
1918 info->iMaxSockAddr = 0x10;
1919 info->iMinSockAddr = 0x10;
1920 info->iSocketType = WS_SOCK_DGRAM;
1921 info->dwMessageSize = 0xffbb;
1922 strcpyW( info->szProtocol, NameUdpW );
1923 break;
1925 case WS_NSPROTO_IPX:
1926 info->dwServiceFlags1 = XP1_PARTIAL_MESSAGE | XP1_SUPPORT_BROADCAST |
1927 XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED |
1928 XP1_CONNECTIONLESS;
1929 info->ProviderId = ProviderIdIPX;
1930 info->dwCatalogEntryId = 0x406;
1931 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1932 info->ProtocolChain.ChainLen = 1;
1933 info->iVersion = 2;
1934 info->iAddressFamily = WS_AF_IPX;
1935 info->iMaxSockAddr = 0x10;
1936 info->iMinSockAddr = 0x0e;
1937 info->iSocketType = WS_SOCK_DGRAM;
1938 info->iProtocolMaxOffset = 0xff;
1939 info->dwMessageSize = 0x240;
1940 strcpyW( info->szProtocol, NameIpxW );
1941 break;
1943 case WS_NSPROTO_SPX:
1944 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_PSEUDO_STREAM |
1945 XP1_MESSAGE_ORIENTED | XP1_GUARANTEED_ORDER |
1946 XP1_GUARANTEED_DELIVERY;
1947 info->ProviderId = ProviderIdSPX;
1948 info->dwCatalogEntryId = 0x407;
1949 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1950 info->ProtocolChain.ChainLen = 1;
1951 info->iVersion = 2;
1952 info->iAddressFamily = WS_AF_IPX;
1953 info->iMaxSockAddr = 0x10;
1954 info->iMinSockAddr = 0x0e;
1955 info->iSocketType = WS_SOCK_SEQPACKET;
1956 info->dwMessageSize = 0xffffffff;
1957 strcpyW( info->szProtocol, NameSpxW );
1958 break;
1960 case WS_NSPROTO_SPXII:
1961 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_GRACEFUL_CLOSE |
1962 XP1_PSEUDO_STREAM | XP1_MESSAGE_ORIENTED |
1963 XP1_GUARANTEED_ORDER | XP1_GUARANTEED_DELIVERY;
1964 info->ProviderId = ProviderIdSPX;
1965 info->dwCatalogEntryId = 0x409;
1966 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1967 info->ProtocolChain.ChainLen = 1;
1968 info->iVersion = 2;
1969 info->iAddressFamily = WS_AF_IPX;
1970 info->iMaxSockAddr = 0x10;
1971 info->iMinSockAddr = 0x0e;
1972 info->iSocketType = WS_SOCK_SEQPACKET;
1973 info->dwMessageSize = 0xffffffff;
1974 strcpyW( info->szProtocol, NameSpxIIW );
1975 break;
1977 default:
1978 FIXME("unknown Protocol <0x%08x>\n", protocol);
1979 return FALSE;
1981 return TRUE;
1984 /*****************************************************************************
1985 * WS_EnterSingleProtocolA [internal]
1987 * see function WS_EnterSingleProtocolW
1990 static BOOL WS_EnterSingleProtocolA( INT protocol, WSAPROTOCOL_INFOA* info )
1992 WSAPROTOCOL_INFOW infow;
1993 INT ret;
1994 memset( info, 0, sizeof(WSAPROTOCOL_INFOA) );
1996 ret = WS_EnterSingleProtocolW( protocol, &infow );
1997 if (ret)
1999 /* convert the structure from W to A */
2000 memcpy( info, &infow, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
2001 WideCharToMultiByte( CP_ACP, 0, infow.szProtocol, -1,
2002 info->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL );
2005 return ret;
2008 static INT WS_EnumProtocols( BOOL unicode, const INT *protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
2010 INT i = 0, items = 0;
2011 DWORD size = 0;
2012 union _info
2014 LPWSAPROTOCOL_INFOA a;
2015 LPWSAPROTOCOL_INFOW w;
2016 } info;
2017 info.w = buffer;
2019 if (!protocols) protocols = valid_protocols;
2021 while (protocols[i])
2023 if(supported_protocol(protocols[i++]))
2024 items++;
2027 size = items * (unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA));
2029 TRACE("unicode %d, protocols %p, buffer %p, length %p %d, items %d, required %d\n",
2030 unicode, protocols, buffer, len, len ? *len : 0, items, size);
2032 if (*len < size || !buffer)
2034 *len = size;
2035 SetLastError(WSAENOBUFS);
2036 return SOCKET_ERROR;
2039 for (i = items = 0; protocols[i]; i++)
2041 if (!supported_protocol(protocols[i])) continue;
2042 if (unicode)
2044 if (WS_EnterSingleProtocolW( protocols[i], &info.w[items] ))
2045 items++;
2047 else
2049 if (WS_EnterSingleProtocolA( protocols[i], &info.a[items] ))
2050 items++;
2053 return items;
2056 static BOOL ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size)
2058 NTSTATUS status;
2060 *size = unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA);
2061 memset(buffer, 0, *size);
2063 SERVER_START_REQ( get_socket_info )
2065 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
2066 status = wine_server_call( req );
2067 if (!status)
2069 buffer->iAddressFamily = convert_af_u2w(reply->family);
2070 buffer->iSocketType = convert_socktype_u2w(reply->type);
2071 buffer->iProtocol = convert_proto_u2w(reply->protocol);
2074 SERVER_END_REQ;
2076 if (status)
2078 unsigned int err = NtStatusToWSAError( status );
2079 SetLastError( err == WSAEBADF ? WSAENOTSOCK : err );
2080 return FALSE;
2083 if (unicode)
2084 WS_EnterSingleProtocolW( buffer->iProtocol, buffer);
2085 else
2086 WS_EnterSingleProtocolA( buffer->iProtocol, (WSAPROTOCOL_INFOA *)buffer);
2088 return TRUE;
2091 /**************************************************************************
2092 * Functions for handling overlapped I/O
2093 **************************************************************************/
2095 /* user APC called upon async completion */
2096 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
2098 struct ws2_async *wsa = arg;
2100 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
2101 iosb->Information, wsa->user_overlapped,
2102 wsa->flags );
2103 release_async_io( &wsa->io );
2106 /***********************************************************************
2107 * WS2_recv (INTERNAL)
2109 * Workhorse for both synchronous and asynchronous recv() operations.
2111 static int WS2_recv( int fd, struct ws2_async *wsa, int flags )
2113 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2114 char pktbuf[512];
2115 #endif
2116 struct msghdr hdr;
2117 union generic_unix_sockaddr unix_sockaddr;
2118 int n;
2120 hdr.msg_name = NULL;
2122 if (wsa->addr)
2124 hdr.msg_namelen = sizeof(unix_sockaddr);
2125 hdr.msg_name = &unix_sockaddr;
2127 else
2128 hdr.msg_namelen = 0;
2130 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
2131 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
2132 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2133 hdr.msg_accrights = NULL;
2134 hdr.msg_accrightslen = 0;
2135 #else
2136 hdr.msg_control = pktbuf;
2137 hdr.msg_controllen = sizeof(pktbuf);
2138 hdr.msg_flags = 0;
2139 #endif
2141 while ((n = recvmsg(fd, &hdr, flags)) == -1)
2143 if (errno != EINTR)
2144 return -1;
2147 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2148 if (wsa->control)
2150 ERR("Message control headers cannot be properly supported on this system.\n");
2151 wsa->control->len = 0;
2153 #else
2154 if (wsa->control && !convert_control_headers(&hdr, wsa->control))
2156 WARN("Application passed insufficient room for control headers.\n");
2157 *wsa->lpFlags |= WS_MSG_CTRUNC;
2158 errno = EMSGSIZE;
2159 return -1;
2161 #endif
2163 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
2164 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
2166 * quoting linux 2.6 net/ipv4/tcp.c:
2167 * "According to UNIX98, msg_name/msg_namelen are ignored
2168 * on connected socket. I was just happy when found this 8) --ANK"
2170 * likewise MSDN says that lpFrom and lpFromlen are ignored for
2171 * connection-oriented sockets, so don't try to update lpFrom.
2173 if (wsa->addr && hdr.msg_namelen)
2174 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
2176 return n;
2179 /***********************************************************************
2180 * WS2_async_recv (INTERNAL)
2182 * Handler for overlapped recv() operations.
2184 static NTSTATUS WS2_async_recv( void *user, IO_STATUS_BLOCK *iosb,
2185 NTSTATUS status, void **apc, void **arg )
2187 struct ws2_async *wsa = user;
2188 int result = 0, fd;
2190 switch (status)
2192 case STATUS_ALERTED:
2193 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
2194 break;
2196 result = WS2_recv( fd, wsa, convert_flags(wsa->flags) );
2197 wine_server_release_fd( wsa->hSocket, fd );
2198 if (result >= 0)
2200 status = STATUS_SUCCESS;
2201 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
2203 else
2205 if (errno == EAGAIN)
2207 status = STATUS_PENDING;
2208 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
2210 else
2212 result = 0;
2213 status = wsaErrStatus();
2216 break;
2218 if (status != STATUS_PENDING)
2220 iosb->u.Status = status;
2221 iosb->Information = result;
2222 if (wsa->completion_func)
2224 *apc = ws2_async_apc;
2225 *arg = wsa;
2227 else
2228 release_async_io( &wsa->io );
2230 return status;
2233 /***********************************************************************
2234 * WS2_async_accept_recv (INTERNAL)
2236 * This function is used to finish the read part of an accept request. It is
2237 * needed to place the completion on the correct socket (listener).
2239 static NTSTATUS WS2_async_accept_recv( void *user, IO_STATUS_BLOCK *iosb,
2240 NTSTATUS status, void **apc, void **arg )
2242 void *junk;
2243 struct ws2_accept_async *wsa = user;
2245 status = WS2_async_recv( wsa->read, iosb, status, &junk, &junk );
2246 if (status == STATUS_PENDING)
2247 return status;
2249 if (wsa->cvalue)
2250 WS_AddCompletion( HANDLE2SOCKET(wsa->listen_socket), wsa->cvalue, iosb->u.Status, iosb->Information );
2252 release_async_io( &wsa->io );
2253 return status;
2256 /***********************************************************************
2257 * WS2_async_accept (INTERNAL)
2259 * This is the function called to satisfy the AcceptEx callback
2261 static NTSTATUS WS2_async_accept( void *user, IO_STATUS_BLOCK *iosb,
2262 NTSTATUS status, void **apc, void **arg )
2264 struct ws2_accept_async *wsa = user;
2265 int len;
2266 char *addr;
2268 TRACE("status: 0x%x listen: %p, accept: %p\n", status, wsa->listen_socket, wsa->accept_socket);
2270 if (status == STATUS_ALERTED)
2272 SERVER_START_REQ( accept_into_socket )
2274 req->lhandle = wine_server_obj_handle( wsa->listen_socket );
2275 req->ahandle = wine_server_obj_handle( wsa->accept_socket );
2276 status = wine_server_call( req );
2278 SERVER_END_REQ;
2280 if (status == STATUS_CANT_WAIT)
2281 return STATUS_PENDING;
2283 if (status == STATUS_INVALID_HANDLE)
2285 FIXME("AcceptEx accepting socket closed but request was not cancelled\n");
2286 status = STATUS_CANCELLED;
2289 else if (status == STATUS_HANDLES_CLOSED)
2290 status = STATUS_CANCELLED; /* strange windows behavior */
2292 if (status != STATUS_SUCCESS)
2293 goto finish;
2295 /* WS2 Spec says size param is extra 16 bytes long...what do we put in it? */
2296 addr = ((char *)wsa->buf) + wsa->data_len;
2297 len = wsa->local_len - sizeof(int);
2298 WS_getsockname(HANDLE2SOCKET(wsa->accept_socket),
2299 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
2300 *(int *)addr = len;
2302 addr += wsa->local_len;
2303 len = wsa->remote_len - sizeof(int);
2304 WS_getpeername(HANDLE2SOCKET(wsa->accept_socket),
2305 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
2306 *(int *)addr = len;
2308 if (!wsa->read)
2309 goto finish;
2311 SERVER_START_REQ( register_async )
2313 req->type = ASYNC_TYPE_READ;
2314 req->async.handle = wine_server_obj_handle( wsa->accept_socket );
2315 req->async.event = wine_server_obj_handle( wsa->user_overlapped->hEvent );
2316 req->async.callback = wine_server_client_ptr( WS2_async_accept_recv );
2317 req->async.iosb = wine_server_client_ptr( iosb );
2318 req->async.arg = wine_server_client_ptr( wsa );
2319 status = wine_server_call( req );
2321 SERVER_END_REQ;
2323 if (status != STATUS_PENDING)
2324 goto finish;
2326 /* The APC has finished but no completion should be sent for the operation yet, additional processing
2327 * needs to be performed by WS2_async_accept_recv() first. */
2328 return STATUS_MORE_PROCESSING_REQUIRED;
2330 finish:
2331 iosb->u.Status = status;
2332 iosb->Information = 0;
2334 if (wsa->read) release_async_io( &wsa->read->io );
2335 release_async_io( &wsa->io );
2336 return status;
2339 /***********************************************************************
2340 * WS2_send (INTERNAL)
2342 * Workhorse for both synchronous and asynchronous send() operations.
2344 static int WS2_send( int fd, struct ws2_async *wsa, int flags )
2346 struct msghdr hdr;
2347 union generic_unix_sockaddr unix_addr;
2348 int n, ret;
2350 hdr.msg_name = NULL;
2351 hdr.msg_namelen = 0;
2353 if (wsa->addr)
2355 hdr.msg_name = &unix_addr;
2356 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
2357 if ( !hdr.msg_namelen )
2359 errno = EFAULT;
2360 return -1;
2363 #if defined(HAS_IPX) && defined(SOL_IPX)
2364 if(wsa->addr->sa_family == WS_AF_IPX)
2366 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
2367 int val=0;
2368 socklen_t len = sizeof(int);
2370 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
2371 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
2372 * the packet type and then we can retrieve it using getsockopt. After that we can set the
2373 * ipx type in the sockaddr_opx structure with the stored value.
2375 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
2376 uipx->sipx_type = val;
2378 #endif
2381 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
2382 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
2383 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2384 hdr.msg_accrights = NULL;
2385 hdr.msg_accrightslen = 0;
2386 #else
2387 hdr.msg_control = NULL;
2388 hdr.msg_controllen = 0;
2389 hdr.msg_flags = 0;
2390 #endif
2392 while ((ret = sendmsg(fd, &hdr, flags)) == -1)
2394 if (errno != EINTR)
2395 return -1;
2398 n = ret;
2399 while (wsa->first_iovec < wsa->n_iovecs && wsa->iovec[wsa->first_iovec].iov_len <= n)
2400 n -= wsa->iovec[wsa->first_iovec++].iov_len;
2401 if (wsa->first_iovec < wsa->n_iovecs)
2403 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
2404 wsa->iovec[wsa->first_iovec].iov_len -= n;
2406 return ret;
2409 /***********************************************************************
2410 * WS2_async_send (INTERNAL)
2412 * Handler for overlapped send() operations.
2414 static NTSTATUS WS2_async_send( void *user, IO_STATUS_BLOCK *iosb,
2415 NTSTATUS status, void **apc, void **arg )
2417 struct ws2_async *wsa = user;
2418 int result = 0, fd;
2420 switch (status)
2422 case STATUS_ALERTED:
2423 if ( wsa->n_iovecs <= wsa->first_iovec )
2425 /* Nothing to do */
2426 status = STATUS_SUCCESS;
2427 break;
2429 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
2430 break;
2432 /* check to see if the data is ready (non-blocking) */
2433 result = WS2_send( fd, wsa, convert_flags(wsa->flags) );
2434 wine_server_release_fd( wsa->hSocket, fd );
2436 if (result >= 0)
2438 if (wsa->first_iovec < wsa->n_iovecs)
2439 status = STATUS_PENDING;
2440 else
2441 status = STATUS_SUCCESS;
2443 iosb->Information += result;
2445 else if (errno == EAGAIN)
2447 status = STATUS_PENDING;
2449 else
2451 status = wsaErrStatus();
2453 break;
2455 if (status != STATUS_PENDING)
2457 iosb->u.Status = status;
2458 if (wsa->completion_func)
2460 *apc = ws2_async_apc;
2461 *arg = wsa;
2463 else
2464 release_async_io( &wsa->io );
2466 return status;
2469 /***********************************************************************
2470 * WS2_async_shutdown (INTERNAL)
2472 * Handler for shutdown() operations on overlapped sockets.
2474 static NTSTATUS WS2_async_shutdown( void *user, IO_STATUS_BLOCK *iosb,
2475 NTSTATUS status, void **apc, void **arg )
2477 struct ws2_async_shutdown *wsa = user;
2478 int fd, err = 1;
2480 switch (status)
2482 case STATUS_ALERTED:
2483 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
2484 break;
2486 switch ( wsa->type )
2488 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
2489 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
2491 status = err ? wsaErrStatus() : STATUS_SUCCESS;
2492 wine_server_release_fd( wsa->hSocket, fd );
2493 break;
2495 iosb->u.Status = status;
2496 iosb->Information = 0;
2497 release_async_io( &wsa->io );
2498 return status;
2501 /***********************************************************************
2502 * WS2_register_async_shutdown (INTERNAL)
2504 * Helper function for WS_shutdown() on overlapped sockets.
2506 static int WS2_register_async_shutdown( SOCKET s, int type )
2508 struct ws2_async_shutdown *wsa;
2509 NTSTATUS status;
2511 TRACE("socket %04lx type %d\n", s, type);
2513 wsa = (struct ws2_async_shutdown *)alloc_async_io( sizeof(*wsa) );
2514 if ( !wsa )
2515 return WSAEFAULT;
2517 wsa->hSocket = SOCKET2HANDLE(s);
2518 wsa->type = type;
2520 SERVER_START_REQ( register_async )
2522 req->type = type;
2523 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2524 req->async.callback = wine_server_client_ptr( WS2_async_shutdown );
2525 req->async.iosb = wine_server_client_ptr( &wsa->iosb );
2526 req->async.arg = wine_server_client_ptr( wsa );
2527 req->async.cvalue = 0;
2528 status = wine_server_call( req );
2530 SERVER_END_REQ;
2532 if (status != STATUS_PENDING)
2534 HeapFree( GetProcessHeap(), 0, wsa );
2535 return NtStatusToWSAError( status );
2537 return 0;
2540 /***********************************************************************
2541 * accept (WS2_32.1)
2543 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr, int *addrlen32)
2545 NTSTATUS status;
2546 SOCKET as;
2547 BOOL is_blocking;
2549 TRACE("socket %04lx\n", s );
2550 status = _is_blocking(s, &is_blocking);
2551 if (status)
2553 set_error(status);
2554 return INVALID_SOCKET;
2557 do {
2558 /* try accepting first (if there is a deferred connection) */
2559 SERVER_START_REQ( accept_socket )
2561 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
2562 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
2563 req->attributes = OBJ_INHERIT;
2564 status = wine_server_call( req );
2565 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
2567 SERVER_END_REQ;
2568 if (!status)
2570 if (addr && WS_getpeername(as, addr, addrlen32))
2572 WS_closesocket(as);
2573 return SOCKET_ERROR;
2575 return as;
2577 if (is_blocking && status == STATUS_CANT_WAIT)
2579 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2580 /* block here */
2581 do_block(fd, POLLIN, -1);
2582 _sync_sock_state(s); /* let wineserver notice connection */
2583 release_sock_fd( s, fd );
2585 } while (is_blocking && status == STATUS_CANT_WAIT);
2587 set_error(status);
2588 return INVALID_SOCKET;
2591 /***********************************************************************
2592 * AcceptEx
2594 static BOOL WINAPI WS2_AcceptEx(SOCKET listener, SOCKET acceptor, PVOID dest, DWORD dest_len,
2595 DWORD local_addr_len, DWORD rem_addr_len, LPDWORD received,
2596 LPOVERLAPPED overlapped)
2598 DWORD status;
2599 struct ws2_accept_async *wsa;
2600 int fd;
2602 TRACE("(%04lx, %04lx, %p, %d, %d, %d, %p, %p)\n", listener, acceptor, dest, dest_len, local_addr_len,
2603 rem_addr_len, received, overlapped);
2605 if (!dest)
2607 SetLastError(WSAEINVAL);
2608 return FALSE;
2611 if (!overlapped)
2613 SetLastError(WSA_INVALID_PARAMETER);
2614 return FALSE;
2617 if (!rem_addr_len)
2619 SetLastError(WSAEFAULT);
2620 return FALSE;
2623 fd = get_sock_fd( listener, FILE_READ_DATA, NULL );
2624 if (fd == -1)
2626 SetLastError(WSAENOTSOCK);
2627 return FALSE;
2629 release_sock_fd( listener, fd );
2631 fd = get_sock_fd( acceptor, FILE_READ_DATA, NULL );
2632 if (fd == -1)
2634 SetLastError(WSAENOTSOCK);
2635 return FALSE;
2637 release_sock_fd( acceptor, fd );
2639 wsa = (struct ws2_accept_async *)alloc_async_io( sizeof(*wsa) );
2640 if(!wsa)
2642 SetLastError(WSAEFAULT);
2643 return FALSE;
2646 wsa->listen_socket = SOCKET2HANDLE(listener);
2647 wsa->accept_socket = SOCKET2HANDLE(acceptor);
2648 wsa->user_overlapped = overlapped;
2649 wsa->cvalue = !((ULONG_PTR)overlapped->hEvent & 1) ? (ULONG_PTR)overlapped : 0;
2650 wsa->buf = dest;
2651 wsa->data_len = dest_len;
2652 wsa->local_len = local_addr_len;
2653 wsa->remote_len = rem_addr_len;
2654 wsa->read = NULL;
2656 if (wsa->data_len)
2658 /* set up a read request if we need it */
2659 wsa->read = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[1]) );
2660 if (!wsa->read)
2662 HeapFree( GetProcessHeap(), 0, wsa );
2663 SetLastError(WSAEFAULT);
2664 return FALSE;
2667 wsa->read->hSocket = wsa->accept_socket;
2668 wsa->read->flags = 0;
2669 wsa->read->lpFlags = &wsa->read->flags;
2670 wsa->read->addr = NULL;
2671 wsa->read->addrlen.ptr = NULL;
2672 wsa->read->control = NULL;
2673 wsa->read->n_iovecs = 1;
2674 wsa->read->first_iovec = 0;
2675 wsa->read->completion_func = NULL;
2676 wsa->read->iovec[0].iov_base = wsa->buf;
2677 wsa->read->iovec[0].iov_len = wsa->data_len;
2680 SERVER_START_REQ( register_async )
2682 req->type = ASYNC_TYPE_READ;
2683 req->async.handle = wine_server_obj_handle( SOCKET2HANDLE(listener) );
2684 req->async.event = wine_server_obj_handle( overlapped->hEvent );
2685 req->async.callback = wine_server_client_ptr( WS2_async_accept );
2686 req->async.iosb = wine_server_client_ptr( overlapped );
2687 req->async.arg = wine_server_client_ptr( wsa );
2688 req->async.cvalue = wsa->cvalue;
2689 status = wine_server_call( req );
2691 SERVER_END_REQ;
2693 if(status != STATUS_PENDING)
2695 HeapFree( GetProcessHeap(), 0, wsa->read );
2696 HeapFree( GetProcessHeap(), 0, wsa );
2699 SetLastError( NtStatusToWSAError(status) );
2700 return FALSE;
2703 /***********************************************************************
2704 * GetAcceptExSockaddrs
2706 static void WINAPI WS2_GetAcceptExSockaddrs(PVOID buffer, DWORD data_size, DWORD local_size, DWORD remote_size,
2707 struct WS_sockaddr **local_addr, LPINT local_addr_len,
2708 struct WS_sockaddr **remote_addr, LPINT remote_addr_len)
2710 char *cbuf = buffer;
2711 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer, data_size, local_size, remote_size, local_addr,
2712 local_addr_len, remote_addr, remote_addr_len );
2713 cbuf += data_size;
2715 *local_addr_len = *(int *) cbuf;
2716 *local_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2718 cbuf += local_size;
2720 *remote_addr_len = *(int *) cbuf;
2721 *remote_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2724 /***********************************************************************
2725 * WSASendMsg
2727 int WINAPI WSASendMsg( SOCKET s, LPWSAMSG msg, DWORD dwFlags, LPDWORD lpNumberOfBytesSent,
2728 LPWSAOVERLAPPED lpOverlapped,
2729 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
2731 if (!msg)
2733 SetLastError( WSAEFAULT );
2734 return SOCKET_ERROR;
2737 return WS2_sendto( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesSent,
2738 dwFlags, msg->name, msg->namelen,
2739 lpOverlapped, lpCompletionRoutine );
2742 /***********************************************************************
2743 * WSARecvMsg
2745 * Perform a receive operation that is capable of returning message
2746 * control headers. It is important to note that the WSAMSG parameter
2747 * must remain valid throughout the operation, even when an overlapped
2748 * receive is performed.
2750 static int WINAPI WS2_WSARecvMsg( SOCKET s, LPWSAMSG msg, LPDWORD lpNumberOfBytesRecvd,
2751 LPWSAOVERLAPPED lpOverlapped,
2752 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2754 if (!msg)
2756 SetLastError( WSAEFAULT );
2757 return SOCKET_ERROR;
2760 return WS2_recv_base( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesRecvd,
2761 &msg->dwFlags, msg->name, &msg->namelen,
2762 lpOverlapped, lpCompletionRoutine, &msg->Control );
2765 /***********************************************************************
2766 * interface_bind (INTERNAL)
2768 * Take bind() calls on any name corresponding to a local network adapter and restrict the given socket to
2769 * operating only on the specified interface. This restriction consists of two components:
2770 * 1) An outgoing packet restriction suggesting the egress interface for all packets.
2771 * 2) An incoming packet restriction dropping packets not meant for the interface.
2772 * If the function succeeds in placing these restrictions (returns TRUE) then the name for the bind() may
2773 * safely be changed to INADDR_ANY, permitting the transmission and receipt of broadcast packets on the
2774 * socket. This behavior is only relevant to UDP sockets and is needed for applications that expect to be able
2775 * to receive broadcast packets on a socket that is bound to a specific network interface.
2777 static BOOL interface_bind( SOCKET s, int fd, struct sockaddr *addr )
2779 struct sockaddr_in *in_sock = (struct sockaddr_in *) addr;
2780 unsigned int sock_type = 0;
2781 socklen_t optlen = sizeof(sock_type);
2782 in_addr_t bind_addr = in_sock->sin_addr.s_addr;
2783 PIP_ADAPTER_INFO adapters = NULL, adapter;
2784 BOOL ret = FALSE;
2785 DWORD adap_size;
2786 int enable = 1;
2788 if (bind_addr == htonl(INADDR_ANY) || bind_addr == htonl(INADDR_LOOPBACK))
2789 return FALSE; /* Not binding to a network adapter, special interface binding unnecessary. */
2790 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &sock_type, &optlen) == -1 || sock_type != SOCK_DGRAM)
2791 return FALSE; /* Special interface binding is only necessary for UDP datagrams. */
2792 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
2793 goto cleanup;
2794 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
2795 if (adapters == NULL || GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
2796 goto cleanup;
2797 /* Search the IPv4 adapter list for the appropriate binding interface */
2798 for (adapter = adapters; adapter != NULL; adapter = adapter->Next)
2800 in_addr_t adapter_addr = (in_addr_t) inet_addr(adapter->IpAddressList.IpAddress.String);
2802 if (bind_addr == adapter_addr)
2804 #if defined(IP_BOUND_IF)
2805 /* IP_BOUND_IF sets both the incoming and outgoing restriction at once */
2806 if (setsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &adapter->Index, sizeof(adapter->Index)) != 0)
2807 goto cleanup;
2808 ret = TRUE;
2809 #elif defined(LINUX_BOUND_IF)
2810 in_addr_t ifindex = (in_addr_t) htonl(adapter->Index);
2811 struct interface_filter specific_interface_filter;
2812 struct sock_fprog filter_prog;
2814 if (setsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex, sizeof(ifindex)) != 0)
2815 goto cleanup; /* Failed to suggest egress interface */
2816 specific_interface_filter = generic_interface_filter;
2817 specific_interface_filter.iface_rule.k = adapter->Index;
2818 specific_interface_filter.ip_rule.k = htonl(adapter_addr);
2819 filter_prog.len = sizeof(generic_interface_filter)/sizeof(struct sock_filter);
2820 filter_prog.filter = (struct sock_filter *) &specific_interface_filter;
2821 if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog, sizeof(filter_prog)) != 0)
2822 goto cleanup; /* Failed to specify incoming packet filter */
2823 ret = TRUE;
2824 #else
2825 FIXME("Broadcast packets on interface-bound sockets are not currently supported on this platform, "
2826 "receiving broadcast packets will not work on socket %04lx.\n", s);
2827 #endif
2828 break;
2831 /* Will soon be switching to INADDR_ANY: permit address reuse */
2832 if (ret && setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) == 0)
2833 TRACE("Socket %04lx bound to interface index %d\n", s, adapter->Index);
2834 else
2835 ret = FALSE;
2837 cleanup:
2838 if(!ret)
2839 ERR("Failed to bind to interface, receiving broadcast packets will not work on socket %04lx.\n", s);
2840 HeapFree(GetProcessHeap(), 0, adapters);
2841 return ret;
2844 /***********************************************************************
2845 * bind (WS2_32.2)
2847 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
2849 int fd = get_sock_fd( s, 0, NULL );
2850 int res = SOCKET_ERROR;
2852 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2854 if (fd != -1)
2856 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
2858 SetLastError(WSAEAFNOSUPPORT);
2860 else
2862 union generic_unix_sockaddr uaddr;
2863 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2864 if (!uaddrlen)
2866 SetLastError(WSAEFAULT);
2868 else
2870 #ifdef IPV6_V6ONLY
2871 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
2872 if (name->sa_family == WS_AF_INET6 &&
2873 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
2875 int enable = 1;
2876 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
2878 release_sock_fd( s, fd );
2879 SetLastError(WSAEAFNOSUPPORT);
2880 return SOCKET_ERROR;
2883 #endif
2884 if (name->sa_family == WS_AF_INET)
2886 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2887 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2889 /* Trying to bind to the default host interface, using
2890 * INADDR_ANY instead*/
2891 WARN("Trying to bind to magic IP address, using "
2892 "INADDR_ANY instead.\n");
2893 in4->sin_addr.s_addr = htonl(INADDR_ANY);
2895 else if (interface_bind(s, fd, &uaddr.addr))
2896 in4->sin_addr.s_addr = htonl(INADDR_ANY);
2898 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
2900 int loc_errno = errno;
2901 WARN("\tfailure - errno = %i\n", errno);
2902 errno = loc_errno;
2903 switch (errno)
2905 case EADDRNOTAVAIL:
2906 SetLastError(WSAEINVAL);
2907 break;
2908 case EADDRINUSE:
2910 int optval = 0;
2911 socklen_t optlen = sizeof(optval);
2912 /* Windows >= 2003 will return different results depending on
2913 * SO_REUSEADDR, WSAEACCES may be returned representing that
2914 * the socket hijacking protection prevented the bind */
2915 if (!getsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&optval, &optlen) && optval)
2917 SetLastError(WSAEACCES);
2918 break;
2920 /* fall through */
2922 default:
2923 SetLastError(wsaErrno());
2924 break;
2927 else
2929 res=0; /* success */
2933 release_sock_fd( s, fd );
2935 return res;
2938 /***********************************************************************
2939 * closesocket (WS2_32.3)
2941 int WINAPI WS_closesocket(SOCKET s)
2943 int res = SOCKET_ERROR, fd;
2944 if (num_startup)
2946 fd = get_sock_fd(s, FILE_READ_DATA, NULL);
2947 if (fd >= 0)
2949 release_sock_fd(s, fd);
2950 if (CloseHandle(SOCKET2HANDLE(s)))
2951 res = 0;
2953 else
2954 SetLastError(WSAENOTSOCK);
2956 else
2957 SetLastError(WSANOTINITIALISED);
2958 TRACE("(socket %04lx) -> %d\n", s, res);
2959 return res;
2962 static int do_connect(int fd, const struct WS_sockaddr* name, int namelen)
2964 union generic_unix_sockaddr uaddr;
2965 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2967 if (!uaddrlen)
2968 return WSAEFAULT;
2970 if (name->sa_family == WS_AF_INET)
2972 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2973 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2975 /* Trying to connect to magic replace-loopback address,
2976 * assuming we really want to connect to localhost */
2977 TRACE("Trying to connect to magic IP address, using "
2978 "INADDR_LOOPBACK instead.\n");
2979 in4->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
2983 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
2984 return 0;
2986 return wsaErrno();
2989 /***********************************************************************
2990 * connect (WS2_32.4)
2992 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
2994 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2996 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2998 if (fd != -1)
3000 NTSTATUS status;
3001 BOOL is_blocking;
3002 int ret = do_connect(fd, name, namelen);
3003 if (ret == 0)
3004 goto connect_success;
3006 if (ret == WSAEINPROGRESS)
3008 /* tell wineserver that a connection is in progress */
3009 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3010 FD_CONNECT,
3011 FD_WINE_CONNECTED|FD_WINE_LISTENING);
3012 status = _is_blocking( s, &is_blocking );
3013 if (status)
3015 release_sock_fd( s, fd );
3016 set_error( status );
3017 return SOCKET_ERROR;
3019 if (is_blocking)
3021 int result;
3022 /* block here */
3023 do_block(fd, POLLIN | POLLOUT, -1);
3024 _sync_sock_state(s); /* let wineserver notice connection */
3025 /* retrieve any error codes from it */
3026 result = _get_sock_error(s, FD_CONNECT_BIT);
3027 if (result)
3028 SetLastError(NtStatusToWSAError(result));
3029 else
3031 goto connect_success;
3034 else
3036 SetLastError(WSAEWOULDBLOCK);
3039 else
3041 SetLastError(ret);
3043 release_sock_fd( s, fd );
3045 return SOCKET_ERROR;
3047 connect_success:
3048 release_sock_fd( s, fd );
3049 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3050 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
3051 FD_CONNECT|FD_WINE_LISTENING);
3052 TRACE("\tconnected %04lx\n", s);
3053 return 0;
3056 /***********************************************************************
3057 * WSAConnect (WS2_32.30)
3059 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
3060 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
3061 LPQOS lpSQOS, LPQOS lpGQOS )
3063 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
3064 FIXME("unsupported parameters!\n");
3065 return WS_connect( s, name, namelen );
3068 /***********************************************************************
3069 * ConnectEx
3071 static BOOL WINAPI WS2_ConnectEx(SOCKET s, const struct WS_sockaddr* name, int namelen,
3072 PVOID sendBuf, DWORD sendBufLen, LPDWORD sent, LPOVERLAPPED ov)
3074 int fd, ret, status;
3076 if (!ov)
3078 SetLastError( ERROR_INVALID_PARAMETER );
3079 return FALSE;
3082 fd = get_sock_fd( s, FILE_READ_DATA, NULL );
3083 if (fd == -1)
3085 SetLastError( WSAENOTSOCK );
3086 return FALSE;
3089 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
3090 s, name, debugstr_sockaddr(name), namelen, sendBuf, sendBufLen, ov);
3092 ret = is_fd_bound(fd, NULL, NULL);
3093 if (ret <= 0)
3095 SetLastError(ret == -1 ? wsaErrno() : WSAEINVAL);
3096 release_sock_fd( s, fd );
3097 return FALSE;
3100 ret = do_connect(fd, name, namelen);
3101 if (ret == 0)
3103 WSABUF wsabuf;
3105 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3106 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
3107 FD_CONNECT|FD_WINE_LISTENING);
3109 wsabuf.len = sendBufLen;
3110 wsabuf.buf = (char*) sendBuf;
3112 /* WSASend takes care of completion if need be */
3113 if (WSASend(s, &wsabuf, sendBuf ? 1 : 0, sent, 0, ov, NULL) != SOCKET_ERROR)
3114 goto connection_success;
3116 else if (ret == WSAEINPROGRESS)
3118 struct ws2_async *wsa;
3119 ULONG_PTR cvalue = (((ULONG_PTR)ov->hEvent & 1) == 0) ? (ULONG_PTR)ov : 0;
3121 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3122 FD_CONNECT,
3123 FD_WINE_CONNECTED|FD_WINE_LISTENING);
3125 /* Indirectly call WSASend */
3126 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof( struct ws2_async, iovec[1] ))))
3128 SetLastError(WSAEFAULT);
3130 else
3132 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)ov;
3133 iosb->u.Status = STATUS_PENDING;
3134 iosb->Information = 0;
3136 wsa->hSocket = SOCKET2HANDLE(s);
3137 wsa->addr = NULL;
3138 wsa->addrlen.val = 0;
3139 wsa->flags = 0;
3140 wsa->lpFlags = &wsa->flags;
3141 wsa->control = NULL;
3142 wsa->n_iovecs = sendBuf ? 1 : 0;
3143 wsa->first_iovec = 0;
3144 wsa->completion_func = NULL;
3145 wsa->iovec[0].iov_base = sendBuf;
3146 wsa->iovec[0].iov_len = sendBufLen;
3148 SERVER_START_REQ( register_async )
3150 req->type = ASYNC_TYPE_WRITE;
3151 req->async.handle = wine_server_obj_handle( wsa->hSocket );
3152 req->async.callback = wine_server_client_ptr( WS2_async_send );
3153 req->async.iosb = wine_server_client_ptr( iosb );
3154 req->async.arg = wine_server_client_ptr( wsa );
3155 req->async.event = wine_server_obj_handle( ov->hEvent );
3156 req->async.cvalue = cvalue;
3157 status = wine_server_call( req );
3159 SERVER_END_REQ;
3161 if (status != STATUS_PENDING) HeapFree(GetProcessHeap(), 0, wsa);
3163 /* If the connect already failed */
3164 if (status == STATUS_PIPE_DISCONNECTED)
3165 status = _get_sock_error(s, FD_CONNECT_BIT);
3166 SetLastError( NtStatusToWSAError(status) );
3169 else
3171 SetLastError(ret);
3174 release_sock_fd( s, fd );
3175 return FALSE;
3177 connection_success:
3178 release_sock_fd( s, fd );
3179 return TRUE;
3183 /***********************************************************************
3184 * getpeername (WS2_32.5)
3186 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
3188 int fd;
3189 int res;
3191 TRACE("socket %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
3193 fd = get_sock_fd( s, 0, NULL );
3194 res = SOCKET_ERROR;
3196 if (fd != -1)
3198 union generic_unix_sockaddr uaddr;
3199 socklen_t uaddrlen = sizeof(uaddr);
3201 if (getpeername(fd, &uaddr.addr, &uaddrlen) == 0)
3203 if (!name || !namelen)
3204 SetLastError(WSAEFAULT);
3205 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3206 /* The buffer was too small */
3207 SetLastError(WSAEFAULT);
3208 else
3210 res = 0;
3211 TRACE("=> %s\n", debugstr_sockaddr(name));
3214 else
3215 SetLastError(wsaErrno());
3216 release_sock_fd( s, fd );
3218 return res;
3221 /* When binding to an UDP address with filter support the getsockname call on the socket
3222 * will always return 0.0.0.0 instead of the filtered interface address. This function
3223 * checks if the socket is interface-bound on UDP and return the correct address.
3224 * This is required because applications often do a bind() with port zero followed by a
3225 * getsockname() to retrieve the port and address acquired.
3227 static void interface_bind_check(int fd, struct sockaddr_in *addr)
3229 #if !defined(IP_BOUND_IF) && !defined(LINUX_BOUND_IF)
3230 return;
3231 #else
3232 int ifindex;
3233 socklen_t len = sizeof(ifindex);
3235 /* Check for IPv4, address 0.0.0.0 and UDP socket */
3236 if (addr->sin_family != AF_INET || addr->sin_addr.s_addr != 0)
3237 return;
3238 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &ifindex, &len) || ifindex != SOCK_DGRAM)
3239 return;
3241 ifindex = -1;
3242 len = sizeof(ifindex);
3243 #if defined(IP_BOUND_IF)
3244 getsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &ifindex, &len);
3245 #elif defined(LINUX_BOUND_IF)
3246 getsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex, &len);
3247 if (ifindex > 0) ifindex = ntohl(ifindex);
3248 #endif
3249 if (ifindex > 0)
3251 PIP_ADAPTER_INFO adapters, adapter;
3252 DWORD adap_size;
3254 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
3255 return;
3256 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
3257 if (adapters && GetAdaptersInfo(adapters, &adap_size) == NO_ERROR)
3259 /* Search the IPv4 adapter list for the appropriate bound interface */
3260 for (adapter = adapters; adapter != NULL; adapter = adapter->Next)
3262 in_addr_t adapter_addr;
3263 if (adapter->Index != ifindex) continue;
3265 adapter_addr = inet_addr(adapter->IpAddressList.IpAddress.String);
3266 addr->sin_addr.s_addr = adapter_addr;
3267 TRACE("reporting interface address from adapter %d\n", ifindex);
3268 break;
3271 HeapFree(GetProcessHeap(), 0, adapters);
3273 #endif
3276 /***********************************************************************
3277 * getsockname (WS2_32.6)
3279 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
3281 int fd;
3282 int res;
3284 TRACE("socket %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
3286 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
3287 if( (name == NULL) || (namelen == NULL) )
3289 SetLastError( WSAEFAULT );
3290 return SOCKET_ERROR;
3293 fd = get_sock_fd( s, 0, NULL );
3294 res = SOCKET_ERROR;
3296 if (fd != -1)
3298 union generic_unix_sockaddr uaddr;
3299 socklen_t uaddrlen;
3300 int bound = is_fd_bound(fd, &uaddr, &uaddrlen);
3302 if (bound <= 0)
3304 SetLastError(bound == -1 ? wsaErrno() : WSAEINVAL);
3306 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3308 /* The buffer was too small */
3309 SetLastError(WSAEFAULT);
3311 else
3313 interface_bind_check(fd, (struct sockaddr_in*) &uaddr);
3314 if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3316 /* The buffer was too small */
3317 SetLastError(WSAEFAULT);
3319 else
3321 res = 0;
3322 TRACE("=> %s\n", debugstr_sockaddr(name));
3325 release_sock_fd( s, fd );
3327 return res;
3330 /***********************************************************************
3331 * getsockopt (WS2_32.7)
3333 INT WINAPI WS_getsockopt(SOCKET s, INT level,
3334 INT optname, char *optval, INT *optlen)
3336 int fd;
3337 INT ret = 0;
3339 TRACE("(socket %04lx, %s, optval %s, optlen %p (%d))\n", s,
3340 debugstr_sockopt(level, optname), debugstr_optval(optval, 0),
3341 optlen, optlen ? *optlen : 0);
3343 switch(level)
3345 case WS_SOL_SOCKET:
3347 switch(optname)
3349 /* Handle common cases. The special cases are below, sorted
3350 * alphabetically */
3351 case WS_SO_BROADCAST:
3352 case WS_SO_DEBUG:
3353 case WS_SO_KEEPALIVE:
3354 case WS_SO_OOBINLINE:
3355 case WS_SO_RCVBUF:
3356 case WS_SO_REUSEADDR:
3357 case WS_SO_SNDBUF:
3358 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3359 return SOCKET_ERROR;
3360 convert_sockopt(&level, &optname);
3361 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3363 SetLastError(wsaErrno());
3364 ret = SOCKET_ERROR;
3366 release_sock_fd( s, fd );
3367 return ret;
3368 case WS_SO_ACCEPTCONN:
3369 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3370 return SOCKET_ERROR;
3371 if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, optval, (socklen_t *)optlen) != 0 )
3373 SetLastError(wsaErrno());
3374 ret = SOCKET_ERROR;
3376 else
3378 /* BSD returns != 0 while Windows return exact == 1 */
3379 if (*(int *)optval) *(int *)optval = 1;
3381 release_sock_fd( s, fd );
3382 return ret;
3383 case WS_SO_BSP_STATE:
3385 int req_size, addr_size;
3386 WSAPROTOCOL_INFOW infow;
3387 CSADDR_INFO *csinfo;
3389 ret = ws_protocol_info(s, TRUE, &infow, &addr_size);
3390 if (ret)
3392 if (infow.iAddressFamily == WS_AF_INET)
3393 addr_size = sizeof(struct sockaddr_in);
3394 else if (infow.iAddressFamily == WS_AF_INET6)
3395 addr_size = sizeof(struct sockaddr_in6);
3396 else
3398 FIXME("Family %d is unsupported for SO_BSP_STATE\n", infow.iAddressFamily);
3399 SetLastError(WSAEAFNOSUPPORT);
3400 return SOCKET_ERROR;
3403 req_size = sizeof(CSADDR_INFO) + addr_size * 2;
3404 if (*optlen < req_size)
3406 ret = 0;
3407 SetLastError(WSAEFAULT);
3409 else
3411 union generic_unix_sockaddr uaddr;
3412 socklen_t uaddrlen;
3414 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3415 return SOCKET_ERROR;
3417 csinfo = (CSADDR_INFO*) optval;
3419 /* Check if the sock is bound */
3420 if (is_fd_bound(fd, &uaddr, &uaddrlen) == 1)
3422 csinfo->LocalAddr.lpSockaddr =
3423 (LPSOCKADDR) (optval + sizeof(CSADDR_INFO));
3424 ws_sockaddr_u2ws(&uaddr.addr, csinfo->LocalAddr.lpSockaddr, &addr_size);
3425 csinfo->LocalAddr.iSockaddrLength = addr_size;
3427 else
3429 csinfo->LocalAddr.lpSockaddr = NULL;
3430 csinfo->LocalAddr.iSockaddrLength = 0;
3433 /* Check if the sock is connected */
3434 if (!getpeername(fd, &uaddr.addr, &uaddrlen) &&
3435 is_sockaddr_bound(&uaddr.addr, uaddrlen))
3437 csinfo->RemoteAddr.lpSockaddr =
3438 (LPSOCKADDR) (optval + sizeof(CSADDR_INFO) + addr_size);
3439 ws_sockaddr_u2ws(&uaddr.addr, csinfo->RemoteAddr.lpSockaddr, &addr_size);
3440 csinfo->RemoteAddr.iSockaddrLength = addr_size;
3442 else
3444 csinfo->RemoteAddr.lpSockaddr = NULL;
3445 csinfo->RemoteAddr.iSockaddrLength = 0;
3448 csinfo->iSocketType = infow.iSocketType;
3449 csinfo->iProtocol = infow.iProtocol;
3450 release_sock_fd( s, fd );
3453 return ret ? 0 : SOCKET_ERROR;
3455 case WS_SO_DONTLINGER:
3457 struct linger lingval;
3458 socklen_t len = sizeof(struct linger);
3460 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
3462 SetLastError(WSAEFAULT);
3463 return SOCKET_ERROR;
3465 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3466 return SOCKET_ERROR;
3468 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
3470 SetLastError(wsaErrno());
3471 ret = SOCKET_ERROR;
3473 else
3475 *(BOOL *)optval = !lingval.l_onoff;
3476 *optlen = sizeof(BOOL);
3479 release_sock_fd( s, fd );
3480 return ret;
3483 case WS_SO_CONNECT_TIME:
3485 static int pretendtime = 0;
3486 struct WS_sockaddr addr;
3487 int len = sizeof(addr);
3489 if (!optlen || *optlen < sizeof(DWORD) || !optval)
3491 SetLastError(WSAEFAULT);
3492 return SOCKET_ERROR;
3494 if (WS_getpeername(s, &addr, &len) == SOCKET_ERROR)
3495 *(DWORD *)optval = ~0u;
3496 else
3498 if (!pretendtime) FIXME("WS_SO_CONNECT_TIME - faking results\n");
3499 *(DWORD *)optval = pretendtime++;
3501 *optlen = sizeof(DWORD);
3502 return ret;
3504 /* As mentioned in setsockopt, Windows ignores this, so we
3505 * always return true here */
3506 case WS_SO_DONTROUTE:
3507 if (!optlen || *optlen < sizeof(BOOL) || !optval)
3509 SetLastError(WSAEFAULT);
3510 return SOCKET_ERROR;
3512 *(BOOL *)optval = TRUE;
3513 *optlen = sizeof(BOOL);
3514 return 0;
3516 case WS_SO_ERROR:
3518 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3519 return SOCKET_ERROR;
3520 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, optval, (socklen_t *)optlen) != 0 )
3522 SetLastError(wsaErrno());
3523 ret = SOCKET_ERROR;
3525 release_sock_fd( s, fd );
3527 /* The wineserver may have swallowed the error before us */
3528 if (!ret && *(int*) optval == 0)
3530 int i, events[FD_MAX_EVENTS];
3531 _get_sock_errors(s, events);
3532 for (i = 0; i < FD_MAX_EVENTS; i++)
3534 if(events[i])
3536 events[i] = NtStatusToWSAError(events[i]);
3537 TRACE("returning SO_ERROR %d from wine server\n", events[i]);
3538 *(int*) optval = events[i];
3539 break;
3543 return ret;
3546 case WS_SO_LINGER:
3548 struct linger lingval;
3549 int so_type;
3550 socklen_t len = sizeof(struct linger), slen = sizeof(int);
3552 /* struct linger and LINGER have different sizes */
3553 if (!optlen || *optlen < sizeof(LINGER) || !optval)
3555 SetLastError(WSAEFAULT);
3556 return SOCKET_ERROR;
3558 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3559 return SOCKET_ERROR;
3561 if ((getsockopt(fd, SOL_SOCKET, SO_TYPE, &so_type, &slen) == 0 && so_type == SOCK_DGRAM))
3563 SetLastError(WSAENOPROTOOPT);
3564 ret = SOCKET_ERROR;
3566 else if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0)
3568 SetLastError(wsaErrno());
3569 ret = SOCKET_ERROR;
3571 else
3573 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
3574 ((LINGER *)optval)->l_linger = lingval.l_linger;
3575 *optlen = sizeof(struct linger);
3578 release_sock_fd( s, fd );
3579 return ret;
3582 case WS_SO_MAX_MSG_SIZE:
3583 if (!optlen || *optlen < sizeof(int) || !optval)
3585 SetLastError(WSAEFAULT);
3586 return SOCKET_ERROR;
3588 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
3589 *(int *)optval = 65507;
3590 *optlen = sizeof(int);
3591 return 0;
3593 /* SO_OPENTYPE does not require a valid socket handle. */
3594 case WS_SO_OPENTYPE:
3595 if (!optlen || *optlen < sizeof(int) || !optval)
3597 SetLastError(WSAEFAULT);
3598 return SOCKET_ERROR;
3600 *(int *)optval = get_per_thread_data()->opentype;
3601 *optlen = sizeof(int);
3602 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
3603 return 0;
3604 case WS_SO_PROTOCOL_INFOA:
3605 case WS_SO_PROTOCOL_INFOW:
3607 int size;
3608 WSAPROTOCOL_INFOW infow;
3610 ret = ws_protocol_info(s, optname == WS_SO_PROTOCOL_INFOW, &infow, &size);
3611 if (ret)
3613 if (!optlen || !optval || *optlen < size)
3615 if(optlen) *optlen = size;
3616 ret = 0;
3617 SetLastError(WSAEFAULT);
3619 else
3620 memcpy(optval, &infow, size);
3622 return ret ? 0 : SOCKET_ERROR;
3624 case WS_SO_RCVTIMEO:
3625 case WS_SO_SNDTIMEO:
3627 INT64 timeout;
3629 if (!optlen || *optlen < sizeof(int)|| !optval)
3631 SetLastError(WSAEFAULT);
3632 return SOCKET_ERROR;
3634 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3635 return SOCKET_ERROR;
3637 timeout = get_rcvsnd_timeo(fd, optname == WS_SO_RCVTIMEO);
3638 *(int *)optval = timeout <= UINT_MAX ? timeout : UINT_MAX;
3640 release_sock_fd( s, fd );
3641 return ret;
3643 case WS_SO_TYPE:
3645 if (!optlen || *optlen < sizeof(int) || !optval)
3647 SetLastError(WSAEFAULT);
3648 return SOCKET_ERROR;
3650 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3651 return SOCKET_ERROR;
3653 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, optval, (socklen_t *)optlen) != 0 )
3655 SetLastError(wsaErrno());
3656 ret = SOCKET_ERROR;
3658 else
3659 (*(int *)optval) = convert_socktype_u2w(*(int *)optval);
3661 release_sock_fd( s, fd );
3662 return ret;
3664 default:
3665 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
3666 SetLastError(WSAENOPROTOOPT);
3667 return SOCKET_ERROR;
3668 } /* end switch(optname) */
3669 }/* end case WS_SOL_SOCKET */
3670 #ifdef HAS_IPX
3671 case WS_NSPROTO_IPX:
3673 struct WS_sockaddr_ipx addr;
3674 IPX_ADDRESS_DATA *data;
3675 int namelen;
3676 switch(optname)
3678 case WS_IPX_PTYPE:
3679 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3680 #ifdef SOL_IPX
3681 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (socklen_t *)optlen) == -1)
3683 ret = SOCKET_ERROR;
3685 #else
3687 struct ipx val;
3688 socklen_t len=sizeof(struct ipx);
3689 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
3690 ret = SOCKET_ERROR;
3691 else
3692 *optval = (int)val.ipx_pt;
3694 #endif
3695 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
3696 release_sock_fd( s, fd );
3697 return ret;
3699 case WS_IPX_ADDRESS:
3701 * On a Win2000 system with one network card there are usually
3702 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
3703 * Using this call you can then retrieve info about this all.
3704 * In case of Linux it is a bit different. Usually you have
3705 * only "one" device active and further it is not possible to
3706 * query things like the linkspeed.
3708 FIXME("IPX_ADDRESS\n");
3709 namelen = sizeof(struct WS_sockaddr_ipx);
3710 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
3711 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
3713 data = (IPX_ADDRESS_DATA*)optval;
3714 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
3715 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
3716 data->adapternum = 0;
3717 data->wan = FALSE; /* We are not on a wan for now .. */
3718 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
3719 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
3720 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
3721 * note 1MB = 1000kB in this case */
3722 return 0;
3724 case WS_IPX_MAX_ADAPTER_NUM:
3725 FIXME("IPX_MAX_ADAPTER_NUM\n");
3726 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
3727 return 0;
3729 default:
3730 FIXME("IPX optname:%x\n", optname);
3731 return SOCKET_ERROR;
3732 }/* end switch(optname) */
3733 } /* end case WS_NSPROTO_IPX */
3734 #endif
3736 #ifdef HAS_IRDA
3737 #define MAX_IRDA_DEVICES 10
3739 case WS_SOL_IRLMP:
3740 switch(optname)
3742 case WS_IRLMP_ENUMDEVICES:
3744 char buf[sizeof(struct irda_device_list) +
3745 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
3746 int res;
3747 socklen_t len = sizeof(buf);
3749 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3750 return SOCKET_ERROR;
3751 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
3752 release_sock_fd( s, fd );
3753 if (res < 0)
3755 SetLastError(wsaErrno());
3756 return SOCKET_ERROR;
3758 else
3760 struct irda_device_list *src = (struct irda_device_list *)buf;
3761 DEVICELIST *dst = (DEVICELIST *)optval;
3762 INT needed = sizeof(DEVICELIST);
3763 unsigned int i;
3765 if (src->len > 0)
3766 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
3767 if (*optlen < needed)
3769 SetLastError(WSAEFAULT);
3770 return SOCKET_ERROR;
3772 *optlen = needed;
3773 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
3774 dst->numDevice = src->len;
3775 for (i = 0; i < src->len; i++)
3777 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
3778 src->dev[i].saddr, src->dev[i].daddr,
3779 src->dev[i].info, src->dev[i].hints[0],
3780 src->dev[i].hints[1]);
3781 memcpy( dst->Device[i].irdaDeviceID,
3782 &src->dev[i].daddr,
3783 sizeof(dst->Device[i].irdaDeviceID) ) ;
3784 memcpy( dst->Device[i].irdaDeviceName,
3785 src->dev[i].info,
3786 sizeof(dst->Device[i].irdaDeviceName) ) ;
3787 memcpy( &dst->Device[i].irdaDeviceHints1,
3788 &src->dev[i].hints[0],
3789 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
3790 memcpy( &dst->Device[i].irdaDeviceHints2,
3791 &src->dev[i].hints[1],
3792 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
3793 dst->Device[i].irdaCharSet = src->dev[i].charset;
3795 return 0;
3798 default:
3799 FIXME("IrDA optname:0x%x\n", optname);
3800 return SOCKET_ERROR;
3802 break; /* case WS_SOL_IRLMP */
3803 #undef MAX_IRDA_DEVICES
3804 #endif
3806 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3807 case WS_IPPROTO_TCP:
3808 switch(optname)
3810 case WS_TCP_NODELAY:
3811 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3812 return SOCKET_ERROR;
3813 convert_sockopt(&level, &optname);
3814 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3816 SetLastError(wsaErrno());
3817 ret = SOCKET_ERROR;
3819 release_sock_fd( s, fd );
3820 return ret;
3822 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
3823 return SOCKET_ERROR;
3825 case WS_IPPROTO_IP:
3826 switch(optname)
3828 case WS_IP_ADD_MEMBERSHIP:
3829 case WS_IP_DROP_MEMBERSHIP:
3830 #ifdef IP_HDRINCL
3831 case WS_IP_HDRINCL:
3832 #endif
3833 case WS_IP_MULTICAST_IF:
3834 case WS_IP_MULTICAST_LOOP:
3835 case WS_IP_MULTICAST_TTL:
3836 case WS_IP_OPTIONS:
3837 #ifdef IP_PKTINFO
3838 case WS_IP_PKTINFO:
3839 #endif
3840 case WS_IP_TOS:
3841 case WS_IP_TTL:
3842 #ifdef IP_UNICAST_IF
3843 case WS_IP_UNICAST_IF:
3844 #endif
3845 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3846 return SOCKET_ERROR;
3847 convert_sockopt(&level, &optname);
3848 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3850 SetLastError(wsaErrno());
3851 ret = SOCKET_ERROR;
3853 release_sock_fd( s, fd );
3854 return ret;
3855 case WS_IP_DONTFRAGMENT:
3856 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
3857 *(BOOL*)optval = FALSE;
3858 return 0;
3860 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
3861 return SOCKET_ERROR;
3863 case WS_IPPROTO_IPV6:
3864 switch(optname)
3866 #ifdef IPV6_ADD_MEMBERSHIP
3867 case WS_IPV6_ADD_MEMBERSHIP:
3868 #endif
3869 #ifdef IPV6_DROP_MEMBERSHIP
3870 case WS_IPV6_DROP_MEMBERSHIP:
3871 #endif
3872 case WS_IPV6_MULTICAST_IF:
3873 case WS_IPV6_MULTICAST_HOPS:
3874 case WS_IPV6_MULTICAST_LOOP:
3875 case WS_IPV6_UNICAST_HOPS:
3876 case WS_IPV6_V6ONLY:
3877 #ifdef IPV6_UNICAST_IF
3878 case WS_IPV6_UNICAST_IF:
3879 #endif
3880 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3881 return SOCKET_ERROR;
3882 convert_sockopt(&level, &optname);
3883 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3885 SetLastError(wsaErrno());
3886 ret = SOCKET_ERROR;
3888 release_sock_fd( s, fd );
3889 return ret;
3890 case WS_IPV6_DONTFRAG:
3891 FIXME("WS_IPV6_DONTFRAG is always false!\n");
3892 *(BOOL*)optval = FALSE;
3893 return 0;
3895 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
3896 return SOCKET_ERROR;
3898 default:
3899 WARN("Unknown level: 0x%08x\n", level);
3900 SetLastError(WSAEINVAL);
3901 return SOCKET_ERROR;
3902 } /* end switch(level) */
3905 /***********************************************************************
3906 * htonl (WS2_32.8)
3908 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
3910 return htonl(hostlong);
3914 /***********************************************************************
3915 * htons (WS2_32.9)
3917 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
3919 return htons(hostshort);
3922 /***********************************************************************
3923 * WSAHtonl (WS2_32.46)
3924 * From MSDN description of error codes, this function should also
3925 * check if WinSock has been initialized and the socket is a valid
3926 * socket. But why? This function only translates a host byte order
3927 * u_long into a network byte order u_long...
3929 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
3931 if (lpnetlong)
3933 *lpnetlong = htonl(hostlong);
3934 return 0;
3936 SetLastError(WSAEFAULT);
3937 return SOCKET_ERROR;
3940 /***********************************************************************
3941 * WSAHtons (WS2_32.47)
3942 * From MSDN description of error codes, this function should also
3943 * check if WinSock has been initialized and the socket is a valid
3944 * socket. But why? This function only translates a host byte order
3945 * u_short into a network byte order u_short...
3947 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
3950 if (lpnetshort)
3952 *lpnetshort = htons(hostshort);
3953 return 0;
3955 SetLastError(WSAEFAULT);
3956 return SOCKET_ERROR;
3960 /***********************************************************************
3961 * inet_addr (WS2_32.11)
3963 WS_u_long WINAPI WS_inet_addr(const char *cp)
3965 if (!cp) return INADDR_NONE;
3966 return inet_addr(cp);
3970 /***********************************************************************
3971 * ntohl (WS2_32.14)
3973 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
3975 return ntohl(netlong);
3979 /***********************************************************************
3980 * ntohs (WS2_32.15)
3982 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
3984 return ntohs(netshort);
3988 /***********************************************************************
3989 * inet_ntoa (WS2_32.12)
3991 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
3993 char* s = inet_ntoa(*((struct in_addr*)&in));
3994 if( s )
3996 struct per_thread_data *data = get_per_thread_data();
3997 strcpy(data->ntoa_buffer, s);
3998 return data->ntoa_buffer;
4000 SetLastError(wsaErrno());
4001 return NULL;
4004 static const char *debugstr_wsaioctl(DWORD ioctl)
4006 const char *buf_type, *family;
4008 switch(ioctl & 0x18000000)
4010 case WS_IOC_WS2:
4011 family = "IOC_WS2";
4012 break;
4013 case WS_IOC_PROTOCOL:
4014 family = "IOC_PROTOCOL";
4015 break;
4016 case WS_IOC_VENDOR:
4017 family = "IOC_VENDOR";
4018 break;
4019 default: /* WS_IOC_UNIX */
4021 BYTE size = (ioctl >> 16) & WS_IOCPARM_MASK;
4022 char x = (ioctl & 0xff00) >> 8;
4023 BYTE y = ioctl & 0xff;
4024 char args[14];
4026 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
4028 case WS_IOC_VOID:
4029 buf_type = "_IO";
4030 sprintf(args, "%d, %d", x, y);
4031 break;
4032 case WS_IOC_IN:
4033 buf_type = "_IOW";
4034 sprintf(args, "'%c', %d, %d", x, y, size);
4035 break;
4036 case WS_IOC_OUT:
4037 buf_type = "_IOR";
4038 sprintf(args, "'%c', %d, %d", x, y, size);
4039 break;
4040 default:
4041 buf_type = "?";
4042 sprintf(args, "'%c', %d, %d", x, y, size);
4043 break;
4045 return wine_dbg_sprintf("%s(%s)", buf_type, args);
4049 /* We are different from WS_IOC_UNIX. */
4050 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
4052 case WS_IOC_VOID:
4053 buf_type = "_WSAIO";
4054 break;
4055 case WS_IOC_INOUT:
4056 buf_type = "_WSAIORW";
4057 break;
4058 case WS_IOC_IN:
4059 buf_type = "_WSAIOW";
4060 break;
4061 case WS_IOC_OUT:
4062 buf_type = "_WSAIOR";
4063 break;
4064 default:
4065 buf_type = "?";
4066 break;
4069 return wine_dbg_sprintf("%s(%s, %d)", buf_type, family,
4070 (USHORT)(ioctl & 0xffff));
4073 /* do an ioctl call through the server */
4074 static DWORD server_ioctl_sock( SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size,
4075 LPVOID out_buff, DWORD out_size, LPDWORD ret_size,
4076 LPWSAOVERLAPPED overlapped,
4077 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
4079 HANDLE event = overlapped ? overlapped->hEvent : 0;
4080 HANDLE handle = SOCKET2HANDLE( s );
4081 struct ws2_async *wsa;
4082 NTSTATUS status;
4083 PIO_STATUS_BLOCK io;
4085 if (!(wsa = (struct ws2_async *)alloc_async_io( sizeof(*wsa) )))
4086 return WSA_NOT_ENOUGH_MEMORY;
4087 wsa->hSocket = handle;
4088 wsa->user_overlapped = overlapped;
4089 wsa->completion_func = completion;
4090 io = (overlapped ? (PIO_STATUS_BLOCK)overlapped : &wsa->local_iosb);
4092 status = NtDeviceIoControlFile( handle, event, ws2_async_apc, wsa, io, code,
4093 in_buff, in_size, out_buff, out_size );
4094 if (status == STATUS_NOT_SUPPORTED)
4096 FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
4097 code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
4099 else if (status == STATUS_SUCCESS)
4100 *ret_size = io->Information; /* "Information" is the size written to the output buffer */
4102 if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, wsa );
4104 return NtStatusToWSAError( status );
4107 /**********************************************************************
4108 * WSAIoctl (WS2_32.50)
4111 INT WINAPI WSAIoctl(SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size, LPVOID out_buff,
4112 DWORD out_size, LPDWORD ret_size, LPWSAOVERLAPPED overlapped,
4113 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
4115 int fd;
4116 DWORD status = 0, total = 0;
4118 TRACE("%04lx, %s, %p, %d, %p, %d, %p, %p, %p\n",
4119 s, debugstr_wsaioctl(code), in_buff, in_size, out_buff, out_size, ret_size, overlapped, completion);
4121 switch (code)
4123 case WS_FIONBIO:
4124 if (in_size != sizeof(WS_u_long) || IS_INTRESOURCE(in_buff))
4126 SetLastError(WSAEFAULT);
4127 return SOCKET_ERROR;
4129 TRACE("-> FIONBIO (%x)\n", *(WS_u_long*)in_buff);
4130 if (_get_sock_mask(s))
4132 /* AsyncSelect()'ed sockets are always nonblocking */
4133 if (!*(WS_u_long *)in_buff) status = WSAEINVAL;
4134 break;
4136 if (*(WS_u_long *)in_buff)
4137 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
4138 else
4139 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
4140 break;
4142 case WS_FIONREAD:
4144 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
4146 SetLastError(WSAEFAULT);
4147 return SOCKET_ERROR;
4149 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
4150 if (ioctl(fd, FIONREAD, out_buff ) == -1)
4151 status = wsaErrno();
4152 release_sock_fd( s, fd );
4153 break;
4156 case WS_SIOCATMARK:
4158 unsigned int oob = 0, atmark = 0;
4159 socklen_t oobsize = sizeof(int);
4160 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
4162 SetLastError(WSAEFAULT);
4163 return SOCKET_ERROR;
4165 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
4166 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
4167 if ((getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &oob, &oobsize ) == -1)
4168 || (!oob && ioctl(fd, SIOCATMARK, &atmark ) == -1))
4169 status = wsaErrno();
4170 else
4172 /* The SIOCATMARK value read from ioctl() is reversed
4173 * because BSD returns TRUE if it's in the OOB mark
4174 * while Windows returns TRUE if there are NO OOB bytes.
4176 (*(WS_u_long *) out_buff) = oob || !atmark;
4179 release_sock_fd( s, fd );
4180 break;
4183 case WS_FIOASYNC:
4184 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
4185 SetLastError(WSAEINVAL);
4186 return SOCKET_ERROR;
4188 case WS_SIO_GET_INTERFACE_LIST:
4190 INTERFACE_INFO* intArray = out_buff;
4191 DWORD size, numInt = 0, apiReturn;
4193 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
4195 if (!out_buff || !ret_size)
4197 SetLastError(WSAEFAULT);
4198 return SOCKET_ERROR;
4201 fd = get_sock_fd( s, 0, NULL );
4202 if (fd == -1) return SOCKET_ERROR;
4204 apiReturn = GetAdaptersInfo(NULL, &size);
4205 if (apiReturn == ERROR_BUFFER_OVERFLOW)
4207 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
4209 if (table)
4211 if (GetAdaptersInfo(table, &size) == NO_ERROR)
4213 PIP_ADAPTER_INFO ptr;
4215 for (ptr = table, numInt = 0; ptr; ptr = ptr->Next)
4217 unsigned int addr, mask, bcast;
4218 struct ifreq ifInfo;
4220 /* Skip interfaces without an IPv4 address. */
4221 if (ptr->IpAddressList.IpAddress.String[0] == '\0')
4222 continue;
4224 if ((numInt + 1)*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > out_size)
4226 WARN("Buffer too small = %u, out_size = %u\n", numInt + 1, out_size);
4227 status = WSAEFAULT;
4228 break;
4231 /* Socket Status Flags */
4232 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
4233 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
4235 ERR("Error obtaining status flags for socket!\n");
4236 status = WSAEINVAL;
4237 break;
4239 else
4241 /* set flags; the values of IFF_* are not the same
4242 under Linux and Windows, therefore must generate
4243 new flags */
4244 intArray->iiFlags = 0;
4245 if (ifInfo.ifr_flags & IFF_BROADCAST)
4246 intArray->iiFlags |= WS_IFF_BROADCAST;
4247 #ifdef IFF_POINTOPOINT
4248 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
4249 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
4250 #endif
4251 if (ifInfo.ifr_flags & IFF_LOOPBACK)
4252 intArray->iiFlags |= WS_IFF_LOOPBACK;
4253 if (ifInfo.ifr_flags & IFF_UP)
4254 intArray->iiFlags |= WS_IFF_UP;
4255 if (ifInfo.ifr_flags & IFF_MULTICAST)
4256 intArray->iiFlags |= WS_IFF_MULTICAST;
4259 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
4260 mask = inet_addr(ptr->IpAddressList.IpMask.String);
4261 bcast = addr | ~mask;
4262 intArray->iiAddress.AddressIn.sin_family = AF_INET;
4263 intArray->iiAddress.AddressIn.sin_port = 0;
4264 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
4265 addr;
4266 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
4267 intArray->iiNetmask.AddressIn.sin_port = 0;
4268 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
4269 mask;
4270 intArray->iiBroadcastAddress.AddressIn.sin_family =
4271 AF_INET;
4272 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
4273 intArray->iiBroadcastAddress.AddressIn.sin_addr.
4274 WS_s_addr = bcast;
4275 intArray++;
4276 numInt++;
4279 else
4281 ERR("Unable to get interface table!\n");
4282 status = WSAEINVAL;
4284 HeapFree(GetProcessHeap(),0,table);
4286 else status = WSAEINVAL;
4288 else if (apiReturn != ERROR_NO_DATA)
4290 ERR("Unable to get interface table!\n");
4291 status = WSAEINVAL;
4293 /* Calculate the size of the array being returned */
4294 total = sizeof(INTERFACE_INFO) * numInt;
4295 release_sock_fd( s, fd );
4296 break;
4299 case WS_SIO_ADDRESS_LIST_QUERY:
4301 DWORD size;
4303 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
4305 if (!ret_size)
4307 SetLastError(WSAEFAULT);
4308 return SOCKET_ERROR;
4311 if (out_size && out_size < FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[0]))
4313 *ret_size = 0;
4314 SetLastError(WSAEINVAL);
4315 return SOCKET_ERROR;
4318 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
4320 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
4321 SOCKET_ADDRESS_LIST *sa_list;
4322 SOCKADDR_IN *sockaddr;
4323 SOCKET_ADDRESS *sa;
4324 unsigned int i;
4325 DWORD num;
4327 if (!table || GetAdaptersInfo(table, &size))
4329 HeapFree(GetProcessHeap(), 0, table);
4330 status = WSAEINVAL;
4331 break;
4334 for (p = table, num = 0; p; p = p->Next)
4335 if (p->IpAddressList.IpAddress.String[0]) num++;
4337 total = FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[num]) + num * sizeof(*sockaddr);
4338 if (total > out_size || !out_buff)
4340 *ret_size = total;
4341 HeapFree(GetProcessHeap(), 0, table);
4342 status = WSAEFAULT;
4343 break;
4346 sa_list = out_buff;
4347 sa = sa_list->Address;
4348 sockaddr = (SOCKADDR_IN *)&sa[num];
4349 sa_list->iAddressCount = num;
4351 for (p = table, i = 0; p; p = p->Next)
4353 if (!p->IpAddressList.IpAddress.String[0]) continue;
4355 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
4356 sa[i].iSockaddrLength = sizeof(SOCKADDR);
4358 sockaddr[i].sin_family = AF_INET;
4359 sockaddr[i].sin_port = 0;
4360 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
4361 i++;
4364 HeapFree(GetProcessHeap(), 0, table);
4366 else
4368 WARN("unable to get IP address list\n");
4369 status = WSAEINVAL;
4371 break;
4374 case WS_SIO_FLUSH:
4375 FIXME("SIO_FLUSH: stub.\n");
4376 break;
4378 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
4380 static const GUID connectex_guid = WSAID_CONNECTEX;
4381 static const GUID disconnectex_guid = WSAID_DISCONNECTEX;
4382 static const GUID acceptex_guid = WSAID_ACCEPTEX;
4383 static const GUID getaccepexsockaddrs_guid = WSAID_GETACCEPTEXSOCKADDRS;
4384 static const GUID transmitfile_guid = WSAID_TRANSMITFILE;
4385 static const GUID transmitpackets_guid = WSAID_TRANSMITPACKETS;
4386 static const GUID wsarecvmsg_guid = WSAID_WSARECVMSG;
4387 static const GUID wsasendmsg_guid = WSAID_WSASENDMSG;
4389 if ( IsEqualGUID(&connectex_guid, in_buff) )
4391 *(LPFN_CONNECTEX *)out_buff = WS2_ConnectEx;
4392 break;
4394 else if ( IsEqualGUID(&disconnectex_guid, in_buff) )
4396 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented DisconnectEx\n");
4398 else if ( IsEqualGUID(&acceptex_guid, in_buff) )
4400 *(LPFN_ACCEPTEX *)out_buff = WS2_AcceptEx;
4401 break;
4403 else if ( IsEqualGUID(&getaccepexsockaddrs_guid, in_buff) )
4405 *(LPFN_GETACCEPTEXSOCKADDRS *)out_buff = WS2_GetAcceptExSockaddrs;
4406 break;
4408 else if ( IsEqualGUID(&transmitfile_guid, in_buff) )
4410 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitFile\n");
4412 else if ( IsEqualGUID(&transmitpackets_guid, in_buff) )
4414 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitPackets\n");
4416 else if ( IsEqualGUID(&wsarecvmsg_guid, in_buff) )
4418 *(LPFN_WSARECVMSG *)out_buff = WS2_WSARecvMsg;
4419 break;
4421 else if ( IsEqualGUID(&wsasendmsg_guid, in_buff) )
4423 *(LPFN_WSASENDMSG *)out_buff = WSASendMsg;
4424 break;
4426 else
4427 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff));
4429 status = WSAEOPNOTSUPP;
4430 break;
4432 case WS_SIO_KEEPALIVE_VALS:
4434 struct tcp_keepalive *k;
4435 int keepalive, keepidle, keepintvl;
4437 if (!in_buff || in_size < sizeof(struct tcp_keepalive))
4439 SetLastError(WSAEFAULT);
4440 return SOCKET_ERROR;
4443 k = in_buff;
4444 keepalive = k->onoff ? 1 : 0;
4445 keepidle = max( 1, (k->keepalivetime + 500) / 1000 );
4446 keepintvl = max( 1, (k->keepaliveinterval + 500) / 1000 );
4448 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
4450 fd = get_sock_fd(s, 0, NULL);
4451 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
4452 status = WSAEINVAL;
4453 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
4454 /* these values need to be set only if SO_KEEPALIVE is enabled */
4455 else if(keepalive)
4457 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
4458 status = WSAEINVAL;
4459 else if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
4460 status = WSAEINVAL;
4462 #else
4463 else
4464 FIXME("ignoring keepalive interval and timeout\n");
4465 #endif
4466 release_sock_fd(s, fd);
4467 break;
4469 case WS_SIO_ROUTING_INTERFACE_QUERY:
4471 struct WS_sockaddr *daddr = (struct WS_sockaddr *)in_buff;
4472 struct WS_sockaddr_in *daddr_in = (struct WS_sockaddr_in *)daddr;
4473 struct WS_sockaddr_in *saddr_in = out_buff;
4474 MIB_IPFORWARDROW row;
4475 PMIB_IPADDRTABLE ipAddrTable = NULL;
4476 DWORD size, i, found_index;
4478 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
4480 if (!in_buff || in_size < sizeof(struct WS_sockaddr) ||
4481 !out_buff || out_size < sizeof(struct WS_sockaddr_in) || !ret_size)
4483 SetLastError(WSAEFAULT);
4484 return SOCKET_ERROR;
4486 if (daddr->sa_family != AF_INET)
4488 FIXME("unsupported address family %d\n", daddr->sa_family);
4489 status = WSAEAFNOSUPPORT;
4490 break;
4492 if (GetBestRoute(daddr_in->sin_addr.S_un.S_addr, 0, &row) != NOERROR ||
4493 GetIpAddrTable(NULL, &size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
4495 status = WSAEFAULT;
4496 break;
4498 ipAddrTable = HeapAlloc(GetProcessHeap(), 0, size);
4499 if (GetIpAddrTable(ipAddrTable, &size, FALSE))
4501 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4502 status = WSAEFAULT;
4503 break;
4505 for (i = 0, found_index = ipAddrTable->dwNumEntries;
4506 i < ipAddrTable->dwNumEntries; i++)
4508 if (ipAddrTable->table[i].dwIndex == row.dwForwardIfIndex)
4509 found_index = i;
4511 if (found_index == ipAddrTable->dwNumEntries)
4513 ERR("no matching IP address for interface %d\n",
4514 row.dwForwardIfIndex);
4515 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4516 status = WSAEFAULT;
4517 break;
4519 saddr_in->sin_family = AF_INET;
4520 saddr_in->sin_addr.S_un.S_addr = ipAddrTable->table[found_index].dwAddr;
4521 saddr_in->sin_port = 0;
4522 total = sizeof(struct WS_sockaddr_in);
4523 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4524 break;
4526 case WS_SIO_SET_COMPATIBILITY_MODE:
4527 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
4528 status = WSAEOPNOTSUPP;
4529 break;
4530 case WS_SIO_UDP_CONNRESET:
4531 FIXME("WS_SIO_UDP_CONNRESET stub\n");
4532 break;
4533 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
4534 SetLastError(WSAEOPNOTSUPP);
4535 return SOCKET_ERROR;
4536 default:
4537 status = WSAEOPNOTSUPP;
4538 break;
4541 if (status == WSAEOPNOTSUPP)
4543 status = server_ioctl_sock(s, code, in_buff, in_size, out_buff, out_size, &total,
4544 overlapped, completion);
4545 if (status != WSAEOPNOTSUPP)
4547 if (status == 0 || status == WSA_IO_PENDING)
4548 TRACE("-> %s request\n", debugstr_wsaioctl(code));
4549 else
4550 ERR("-> %s request failed with status 0x%x\n", debugstr_wsaioctl(code), status);
4552 /* overlapped and completion operations will be handled by the server */
4553 completion = NULL;
4554 overlapped = NULL;
4556 else
4557 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code));
4560 if (completion)
4562 FIXME( "completion routine %p not supported\n", completion );
4564 else if (overlapped)
4566 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
4567 overlapped->Internal = status;
4568 overlapped->InternalHigh = total;
4569 if (overlapped->hEvent) NtSetEvent( overlapped->hEvent, NULL );
4570 if (cvalue) WS_AddCompletion( HANDLE2SOCKET(s), cvalue, status, total );
4573 if (!status)
4575 if (ret_size) *ret_size = total;
4576 return 0;
4578 SetLastError( status );
4579 return SOCKET_ERROR;
4583 /***********************************************************************
4584 * ioctlsocket (WS2_32.10)
4586 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
4588 DWORD ret_size;
4589 return WSAIoctl( s, cmd, argp, sizeof(WS_u_long), argp, sizeof(WS_u_long), &ret_size, NULL, NULL );
4592 /***********************************************************************
4593 * listen (WS2_32.13)
4595 int WINAPI WS_listen(SOCKET s, int backlog)
4597 int fd = get_sock_fd( s, FILE_READ_DATA, NULL ), ret = SOCKET_ERROR;
4599 TRACE("socket %04lx, backlog %d\n", s, backlog);
4600 if (fd != -1)
4602 int bound = is_fd_bound(fd, NULL, NULL);
4604 if (bound <= 0)
4606 SetLastError(bound == -1 ? wsaErrno() : WSAEINVAL);
4608 else if (listen(fd, backlog) == 0)
4610 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
4611 FD_WINE_LISTENING,
4612 FD_CONNECT|FD_WINE_CONNECTED);
4613 ret = 0;
4615 else
4616 SetLastError(wsaErrno());
4617 release_sock_fd( s, fd );
4619 else
4620 SetLastError(WSAENOTSOCK);
4621 return ret;
4624 /***********************************************************************
4625 * recv (WS2_32.16)
4627 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
4629 DWORD n, dwFlags = flags;
4630 WSABUF wsabuf;
4632 wsabuf.len = len;
4633 wsabuf.buf = buf;
4635 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
4636 return SOCKET_ERROR;
4637 else
4638 return n;
4641 /***********************************************************************
4642 * recvfrom (WS2_32.17)
4644 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
4645 struct WS_sockaddr *from, int *fromlen)
4647 DWORD n, dwFlags = flags;
4648 WSABUF wsabuf;
4650 wsabuf.len = len;
4651 wsabuf.buf = buf;
4653 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL, NULL) == SOCKET_ERROR )
4654 return SOCKET_ERROR;
4655 else
4656 return n;
4659 /* allocate a poll array for the corresponding fd sets */
4660 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
4661 const WS_fd_set *exceptfds, int *count_ptr )
4663 unsigned int i, j = 0, count = 0;
4664 struct pollfd *fds;
4666 if (readfds) count += readfds->fd_count;
4667 if (writefds) count += writefds->fd_count;
4668 if (exceptfds) count += exceptfds->fd_count;
4669 *count_ptr = count;
4670 if (!count)
4672 SetLastError(WSAEINVAL);
4673 return NULL;
4675 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0]))))
4677 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
4678 return NULL;
4680 if (readfds)
4681 for (i = 0; i < readfds->fd_count; i++, j++)
4683 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
4684 if (fds[j].fd == -1) goto failed;
4685 fds[j].revents = 0;
4686 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1)
4688 fds[j].events = POLLIN;
4690 else
4692 release_sock_fd( readfds->fd_array[i], fds[j].fd );
4693 fds[j].fd = -1;
4694 fds[j].events = 0;
4697 if (writefds)
4698 for (i = 0; i < writefds->fd_count; i++, j++)
4700 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
4701 if (fds[j].fd == -1) goto failed;
4702 fds[j].revents = 0;
4703 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1)
4705 fds[j].events = POLLOUT;
4707 else
4709 release_sock_fd( writefds->fd_array[i], fds[j].fd );
4710 fds[j].fd = -1;
4711 fds[j].events = 0;
4714 if (exceptfds)
4715 for (i = 0; i < exceptfds->fd_count; i++, j++)
4717 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
4718 if (fds[j].fd == -1) goto failed;
4719 fds[j].revents = 0;
4720 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1)
4722 int oob_inlined = 0;
4723 socklen_t olen = sizeof(oob_inlined);
4725 fds[j].events = POLLHUP;
4727 /* Check if we need to test for urgent data or not */
4728 getsockopt(fds[j].fd, SOL_SOCKET, SO_OOBINLINE, (char*) &oob_inlined, &olen);
4729 if (!oob_inlined)
4730 fds[j].events |= POLLPRI;
4732 else
4734 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
4735 fds[j].fd = -1;
4736 fds[j].events = 0;
4739 return fds;
4741 failed:
4742 count = j;
4743 j = 0;
4744 if (readfds)
4745 for (i = 0; i < readfds->fd_count && j < count; i++, j++)
4746 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
4747 if (writefds)
4748 for (i = 0; i < writefds->fd_count && j < count; i++, j++)
4749 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
4750 if (exceptfds)
4751 for (i = 0; i < exceptfds->fd_count && j < count; i++, j++)
4752 if (fds[j].fd != -1) release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
4753 HeapFree( GetProcessHeap(), 0, fds );
4754 return NULL;
4757 /* release the file descriptor obtained in fd_sets_to_poll */
4758 /* must be called with the original fd_set arrays, before calling get_poll_results */
4759 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
4760 const WS_fd_set *exceptfds, struct pollfd *fds )
4762 unsigned int i, j = 0;
4764 if (readfds)
4766 for (i = 0; i < readfds->fd_count; i++, j++)
4767 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
4769 if (writefds)
4771 for (i = 0; i < writefds->fd_count; i++, j++)
4772 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
4774 if (exceptfds)
4776 for (i = 0; i < exceptfds->fd_count; i++, j++)
4778 if (fds[j].fd == -1) continue;
4779 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
4780 if (fds[j].revents & POLLHUP)
4782 int fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
4783 if (fd != -1)
4784 release_sock_fd( exceptfds->fd_array[i], fd );
4785 else
4786 fds[j].revents = 0;
4792 static int do_poll(struct pollfd *pollfds, int count, int timeout)
4794 struct timeval tv1, tv2;
4795 int ret, torig = timeout;
4797 if (timeout > 0) gettimeofday( &tv1, 0 );
4799 while ((ret = poll( pollfds, count, timeout )) < 0)
4801 if (errno != EINTR) break;
4802 if (timeout < 0) continue;
4804 gettimeofday( &tv2, 0 );
4806 tv2.tv_sec -= tv1.tv_sec;
4807 tv2.tv_usec -= tv1.tv_usec;
4808 if (tv2.tv_usec < 0)
4810 tv2.tv_usec += 1000000;
4811 tv2.tv_sec -= 1;
4814 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
4815 if (timeout <= 0) return 0;
4817 return ret;
4820 /* map the poll results back into the Windows fd sets */
4821 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
4822 const struct pollfd *fds )
4824 const struct pollfd *poll_writefds = fds + (readfds ? readfds->fd_count : 0);
4825 const struct pollfd *poll_exceptfds = poll_writefds + (writefds ? writefds->fd_count : 0);
4826 unsigned int i, k, total = 0;
4828 if (readfds)
4830 for (i = k = 0; i < readfds->fd_count; i++)
4832 if (fds[i].revents ||
4833 (readfds == writefds && (poll_writefds[i].revents & POLLOUT) && !(poll_writefds[i].revents & POLLHUP)) ||
4834 (readfds == exceptfds && poll_exceptfds[i].revents))
4835 readfds->fd_array[k++] = readfds->fd_array[i];
4837 readfds->fd_count = k;
4838 total += k;
4840 if (writefds && writefds != readfds)
4842 for (i = k = 0; i < writefds->fd_count; i++)
4844 if (((poll_writefds[i].revents & POLLOUT) && !(poll_writefds[i].revents & POLLHUP)) ||
4845 (writefds == exceptfds && poll_exceptfds[i].revents))
4846 writefds->fd_array[k++] = writefds->fd_array[i];
4848 writefds->fd_count = k;
4849 total += k;
4851 if (exceptfds && exceptfds != readfds && exceptfds != writefds)
4853 for (i = k = 0; i < exceptfds->fd_count; i++)
4854 if (poll_exceptfds[i].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
4855 exceptfds->fd_count = k;
4856 total += k;
4858 return total;
4861 /***********************************************************************
4862 * select (WS2_32.18)
4864 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
4865 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
4866 const struct WS_timeval* ws_timeout)
4868 struct pollfd *pollfds;
4869 int count, ret, timeout = -1;
4871 TRACE("read %p, write %p, excp %p timeout %p\n",
4872 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
4874 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )))
4875 return SOCKET_ERROR;
4877 if (ws_timeout)
4878 timeout = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
4880 ret = do_poll(pollfds, count, timeout);
4881 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
4883 if (ret == -1) SetLastError(wsaErrno());
4884 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
4885 HeapFree( GetProcessHeap(), 0, pollfds );
4886 return ret;
4889 /* helper to send completion messages for client-only i/o operation case */
4890 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
4891 ULONG Information )
4893 SERVER_START_REQ( add_fd_completion )
4895 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
4896 req->cvalue = CompletionValue;
4897 req->status = CompletionStatus;
4898 req->information = Information;
4899 wine_server_call( req );
4901 SERVER_END_REQ;
4905 /***********************************************************************
4906 * send (WS2_32.19)
4908 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
4910 DWORD n;
4911 WSABUF wsabuf;
4913 wsabuf.len = len;
4914 wsabuf.buf = (char*) buf;
4916 if ( WS2_sendto( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
4917 return SOCKET_ERROR;
4918 else
4919 return n;
4922 /***********************************************************************
4923 * WSASend (WS2_32.72)
4925 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4926 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4927 LPWSAOVERLAPPED lpOverlapped,
4928 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4930 return WS2_sendto( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
4931 NULL, 0, lpOverlapped, lpCompletionRoutine );
4934 /***********************************************************************
4935 * WSASendDisconnect (WS2_32.73)
4937 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
4939 return WS_shutdown( s, SD_SEND );
4943 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4944 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4945 const struct WS_sockaddr *to, int tolen,
4946 LPWSAOVERLAPPED lpOverlapped,
4947 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4949 unsigned int i, options;
4950 int n, fd, err, overlapped, flags;
4951 struct ws2_async *wsa = NULL, localwsa;
4952 int totalLength = 0;
4953 DWORD bytes_sent;
4954 BOOL is_blocking;
4956 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
4957 s, lpBuffers, dwBufferCount, dwFlags,
4958 to, tolen, lpOverlapped, lpCompletionRoutine);
4960 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
4961 TRACE( "fd=%d, options=%x\n", fd, options );
4963 if ( fd == -1 ) return SOCKET_ERROR;
4965 if (!lpOverlapped && !lpNumberOfBytesSent)
4967 err = WSAEFAULT;
4968 goto error;
4971 overlapped = (lpOverlapped || lpCompletionRoutine) &&
4972 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
4973 if (overlapped || dwBufferCount > 1)
4975 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[dwBufferCount]))))
4977 err = WSAEFAULT;
4978 goto error;
4981 else
4982 wsa = &localwsa;
4984 wsa->hSocket = SOCKET2HANDLE(s);
4985 wsa->addr = (struct WS_sockaddr *)to;
4986 wsa->addrlen.val = tolen;
4987 wsa->flags = dwFlags;
4988 wsa->lpFlags = &wsa->flags;
4989 wsa->control = NULL;
4990 wsa->n_iovecs = dwBufferCount;
4991 wsa->first_iovec = 0;
4992 for ( i = 0; i < dwBufferCount; i++ )
4994 wsa->iovec[i].iov_base = lpBuffers[i].buf;
4995 wsa->iovec[i].iov_len = lpBuffers[i].len;
4996 totalLength += lpBuffers[i].len;
4999 flags = convert_flags(dwFlags);
5000 n = WS2_send( fd, wsa, flags );
5001 if (n == -1 && errno != EAGAIN)
5003 err = wsaErrno();
5004 goto error;
5007 if (overlapped)
5009 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
5010 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
5012 wsa->user_overlapped = lpOverlapped;
5013 wsa->completion_func = lpCompletionRoutine;
5014 release_sock_fd( s, fd );
5016 if (n == -1 || n < totalLength)
5018 iosb->u.Status = STATUS_PENDING;
5019 iosb->Information = n == -1 ? 0 : n;
5021 SERVER_START_REQ( register_async )
5023 req->type = ASYNC_TYPE_WRITE;
5024 req->async.handle = wine_server_obj_handle( wsa->hSocket );
5025 req->async.callback = wine_server_client_ptr( WS2_async_send );
5026 req->async.iosb = wine_server_client_ptr( iosb );
5027 req->async.arg = wine_server_client_ptr( wsa );
5028 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
5029 req->async.cvalue = cvalue;
5030 err = wine_server_call( req );
5032 SERVER_END_REQ;
5034 /* Enable the event only after starting the async. The server will deliver it as soon as
5035 the async is done. */
5036 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
5038 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
5039 SetLastError(NtStatusToWSAError( err ));
5040 return SOCKET_ERROR;
5043 iosb->u.Status = STATUS_SUCCESS;
5044 iosb->Information = n;
5045 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = n;
5046 if (!wsa->completion_func)
5048 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
5049 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
5050 HeapFree( GetProcessHeap(), 0, wsa );
5052 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
5053 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
5054 SetLastError(ERROR_SUCCESS);
5055 return 0;
5058 if ((err = _is_blocking( s, &is_blocking )))
5060 err = NtStatusToWSAError( err );
5061 goto error;
5064 if ( is_blocking )
5066 /* On a blocking non-overlapped stream socket,
5067 * sending blocks until the entire buffer is sent. */
5068 DWORD timeout_start = GetTickCount();
5070 bytes_sent = n == -1 ? 0 : n;
5072 while (wsa->first_iovec < wsa->n_iovecs)
5074 struct pollfd pfd;
5075 int poll_timeout = -1;
5076 INT64 timeout = get_rcvsnd_timeo(fd, FALSE);
5078 if (timeout)
5080 timeout -= GetTickCount() - timeout_start;
5081 if (timeout < 0) poll_timeout = 0;
5082 else poll_timeout = timeout <= INT_MAX ? timeout : INT_MAX;
5085 pfd.fd = fd;
5086 pfd.events = POLLOUT;
5088 if (!poll_timeout || !poll( &pfd, 1, poll_timeout ))
5090 err = WSAETIMEDOUT;
5091 goto error; /* msdn says a timeout in send is fatal */
5094 n = WS2_send( fd, wsa, flags );
5095 if (n == -1 && errno != EAGAIN)
5097 err = wsaErrno();
5098 goto error;
5101 if (n >= 0)
5102 bytes_sent += n;
5105 else /* non-blocking */
5107 if (n < totalLength)
5108 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
5109 if (n == -1)
5111 err = WSAEWOULDBLOCK;
5112 goto error;
5114 bytes_sent = n;
5117 TRACE(" -> %i bytes\n", bytes_sent);
5119 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = bytes_sent;
5120 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
5121 release_sock_fd( s, fd );
5122 SetLastError(ERROR_SUCCESS);
5123 return 0;
5125 error:
5126 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
5127 release_sock_fd( s, fd );
5128 WARN(" -> ERROR %d\n", err);
5129 SetLastError(err);
5130 return SOCKET_ERROR;
5133 /***********************************************************************
5134 * WSASendTo (WS2_32.74)
5136 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5137 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
5138 const struct WS_sockaddr *to, int tolen,
5139 LPWSAOVERLAPPED lpOverlapped,
5140 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5142 return WS2_sendto( s, lpBuffers, dwBufferCount,
5143 lpNumberOfBytesSent, dwFlags,
5144 to, tolen,
5145 lpOverlapped, lpCompletionRoutine );
5148 /***********************************************************************
5149 * sendto (WS2_32.20)
5151 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
5152 const struct WS_sockaddr *to, int tolen)
5154 DWORD n;
5155 WSABUF wsabuf;
5157 wsabuf.len = len;
5158 wsabuf.buf = (char*) buf;
5160 if ( WS2_sendto(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
5161 return SOCKET_ERROR;
5162 else
5163 return n;
5166 /***********************************************************************
5167 * setsockopt (WS2_32.21)
5169 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
5170 const char *optval, int optlen)
5172 int fd;
5173 int woptval;
5174 struct linger linger;
5175 struct timeval tval;
5177 TRACE("(socket %04lx, %s, optval %s, optlen %d)\n", s,
5178 debugstr_sockopt(level, optname), debugstr_optval(optval, optlen),
5179 optlen);
5181 /* some broken apps pass the value directly instead of a pointer to it */
5182 if(optlen && IS_INTRESOURCE(optval))
5184 SetLastError(WSAEFAULT);
5185 return SOCKET_ERROR;
5188 switch(level)
5190 case WS_SOL_SOCKET:
5191 switch(optname)
5193 /* Some options need some conversion before they can be sent to
5194 * setsockopt. The conversions are done here, then they will fall through
5195 * to the general case. Special options that are not passed to
5196 * setsockopt follow below that.*/
5198 case WS_SO_DONTLINGER:
5199 if (!optval)
5201 SetLastError(WSAEFAULT);
5202 return SOCKET_ERROR;
5204 linger.l_onoff = *(const int*)optval == 0;
5205 linger.l_linger = 0;
5206 level = SOL_SOCKET;
5207 optname = SO_LINGER;
5208 optval = (char*)&linger;
5209 optlen = sizeof(struct linger);
5210 break;
5212 case WS_SO_LINGER:
5213 if (!optval)
5215 SetLastError(WSAEFAULT);
5216 return SOCKET_ERROR;
5218 linger.l_onoff = ((LINGER*)optval)->l_onoff;
5219 linger.l_linger = ((LINGER*)optval)->l_linger;
5220 level = SOL_SOCKET;
5221 optname = SO_LINGER;
5222 optval = (char*)&linger;
5223 optlen = sizeof(struct linger);
5224 break;
5226 case WS_SO_RCVBUF:
5227 if (*(const int*)optval < 2048)
5229 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
5230 return 0;
5232 /* Fall through */
5234 /* The options listed here don't need any special handling. Thanks to
5235 * the conversion happening above, options from there will fall through
5236 * to this, too.*/
5237 case WS_SO_ACCEPTCONN:
5238 case WS_SO_BROADCAST:
5239 case WS_SO_ERROR:
5240 case WS_SO_KEEPALIVE:
5241 case WS_SO_OOBINLINE:
5242 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
5243 * however, using it the BSD way fixes bug 8513 and seems to be what
5244 * most programmers assume, anyway */
5245 case WS_SO_REUSEADDR:
5246 case WS_SO_SNDBUF:
5247 case WS_SO_TYPE:
5248 convert_sockopt(&level, &optname);
5249 break;
5251 /* SO_DEBUG is a privileged operation, ignore it. */
5252 case WS_SO_DEBUG:
5253 TRACE("Ignoring SO_DEBUG\n");
5254 return 0;
5256 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
5257 * socket. According to MSDN, this option is silently ignored.*/
5258 case WS_SO_DONTROUTE:
5259 TRACE("Ignoring SO_DONTROUTE\n");
5260 return 0;
5262 /* Stops two sockets from being bound to the same port. Always happens
5263 * on unix systems, so just drop it. */
5264 case WS_SO_EXCLUSIVEADDRUSE:
5265 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
5266 return 0;
5268 /* After a ConnectEx call succeeds, the socket can't be used with half of the
5269 * normal winsock functions on windows. We don't have that problem. */
5270 case WS_SO_UPDATE_CONNECT_CONTEXT:
5271 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
5272 return 0;
5274 /* After a AcceptEx call succeeds, the socket can't be used with half of the
5275 * normal winsock functions on windows. We don't have that problem. */
5276 case WS_SO_UPDATE_ACCEPT_CONTEXT:
5277 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
5278 return 0;
5280 /* SO_OPENTYPE does not require a valid socket handle. */
5281 case WS_SO_OPENTYPE:
5282 if (!optlen || optlen < sizeof(int) || !optval)
5284 SetLastError(WSAEFAULT);
5285 return SOCKET_ERROR;
5287 get_per_thread_data()->opentype = *(const int *)optval;
5288 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
5289 return 0;
5291 #ifdef SO_RCVTIMEO
5292 case WS_SO_RCVTIMEO:
5293 #endif
5294 #ifdef SO_SNDTIMEO
5295 case WS_SO_SNDTIMEO:
5296 #endif
5297 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
5298 if (optval && optlen == sizeof(UINT32)) {
5299 /* WinSock passes milliseconds instead of struct timeval */
5300 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
5301 tval.tv_sec = *(const UINT32*)optval / 1000;
5302 /* min of 500 milliseconds */
5303 if (tval.tv_sec == 0 && tval.tv_usec && tval.tv_usec < 500000)
5304 tval.tv_usec = 500000;
5305 optlen = sizeof(struct timeval);
5306 optval = (char*)&tval;
5307 } else if (optlen == sizeof(struct timeval)) {
5308 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
5309 } else {
5310 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
5311 return 0;
5313 convert_sockopt(&level, &optname);
5314 break;
5315 #endif
5317 default:
5318 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
5319 SetLastError(WSAENOPROTOOPT);
5320 return SOCKET_ERROR;
5322 break; /* case WS_SOL_SOCKET */
5324 #ifdef HAS_IPX
5325 case WS_NSPROTO_IPX:
5326 switch(optname)
5328 case WS_IPX_PTYPE:
5329 return set_ipx_packettype(s, *(int*)optval);
5331 case WS_IPX_FILTERPTYPE:
5332 /* Sets the receive filter packet type, at the moment we don't support it */
5333 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
5334 /* Returning 0 is better for now than returning a SOCKET_ERROR */
5335 return 0;
5337 default:
5338 FIXME("opt_name:%x\n", optname);
5339 return SOCKET_ERROR;
5341 break; /* case WS_NSPROTO_IPX */
5342 #endif
5344 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
5345 case WS_IPPROTO_TCP:
5346 switch(optname)
5348 case WS_TCP_NODELAY:
5349 convert_sockopt(&level, &optname);
5350 break;
5351 default:
5352 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
5353 return SOCKET_ERROR;
5355 break;
5357 case WS_IPPROTO_IP:
5358 switch(optname)
5360 case WS_IP_ADD_MEMBERSHIP:
5361 case WS_IP_DROP_MEMBERSHIP:
5362 #ifdef IP_HDRINCL
5363 case WS_IP_HDRINCL:
5364 #endif
5365 case WS_IP_MULTICAST_IF:
5366 case WS_IP_MULTICAST_LOOP:
5367 case WS_IP_MULTICAST_TTL:
5368 case WS_IP_OPTIONS:
5369 #ifdef IP_PKTINFO
5370 case WS_IP_PKTINFO:
5371 #endif
5372 case WS_IP_TOS:
5373 case WS_IP_TTL:
5374 #ifdef IP_UNICAST_IF
5375 case WS_IP_UNICAST_IF:
5376 #endif
5377 convert_sockopt(&level, &optname);
5378 break;
5379 case WS_IP_DONTFRAGMENT:
5380 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
5381 return 0;
5382 default:
5383 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
5384 return SOCKET_ERROR;
5386 break;
5388 case WS_IPPROTO_IPV6:
5389 switch(optname)
5391 #ifdef IPV6_ADD_MEMBERSHIP
5392 case WS_IPV6_ADD_MEMBERSHIP:
5393 #endif
5394 #ifdef IPV6_DROP_MEMBERSHIP
5395 case WS_IPV6_DROP_MEMBERSHIP:
5396 #endif
5397 case WS_IPV6_MULTICAST_IF:
5398 case WS_IPV6_MULTICAST_HOPS:
5399 case WS_IPV6_MULTICAST_LOOP:
5400 case WS_IPV6_UNICAST_HOPS:
5401 case WS_IPV6_V6ONLY:
5402 #ifdef IPV6_UNICAST_IF
5403 case WS_IPV6_UNICAST_IF:
5404 #endif
5405 convert_sockopt(&level, &optname);
5406 break;
5407 case WS_IPV6_DONTFRAG:
5408 FIXME("IPV6_DONTFRAG is silently ignored!\n");
5409 return 0;
5410 case WS_IPV6_PROTECTION_LEVEL:
5411 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
5412 return 0;
5413 default:
5414 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
5415 return SOCKET_ERROR;
5417 break;
5419 default:
5420 WARN("Unknown level: 0x%08x\n", level);
5421 SetLastError(WSAEINVAL);
5422 return SOCKET_ERROR;
5423 } /* end switch(level) */
5425 /* avoid endianness issues if argument is a 16-bit int */
5426 if (optval && optlen < sizeof(int))
5428 woptval= *((const INT16 *) optval);
5429 optval= (char*) &woptval;
5430 woptval&= (1 << optlen * 8) - 1;
5431 optlen=sizeof(int);
5433 fd = get_sock_fd( s, 0, NULL );
5434 if (fd == -1) return SOCKET_ERROR;
5436 if (setsockopt(fd, level, optname, optval, optlen) == 0)
5438 #ifdef __APPLE__
5439 if (level == SOL_SOCKET && optname == SO_REUSEADDR &&
5440 setsockopt(fd, level, SO_REUSEPORT, optval, optlen) != 0)
5442 SetLastError(wsaErrno());
5443 release_sock_fd( s, fd );
5444 return SOCKET_ERROR;
5446 #endif
5447 release_sock_fd( s, fd );
5448 return 0;
5450 TRACE("Setting socket error, %d\n", wsaErrno());
5451 SetLastError(wsaErrno());
5452 release_sock_fd( s, fd );
5454 return SOCKET_ERROR;
5457 /***********************************************************************
5458 * shutdown (WS2_32.22)
5460 int WINAPI WS_shutdown(SOCKET s, int how)
5462 int fd, err = WSAENOTSOCK;
5463 unsigned int options = 0, clear_flags = 0;
5465 fd = get_sock_fd( s, 0, &options );
5466 TRACE("socket %04lx, how 0x%x, options 0x%x\n", s, how, options );
5468 if (fd == -1)
5469 return SOCKET_ERROR;
5471 switch( how )
5473 case SD_RECEIVE: /* drop receives */
5474 clear_flags |= FD_READ;
5475 break;
5476 case SD_SEND: /* drop sends */
5477 clear_flags |= FD_WRITE;
5478 break;
5479 case SD_BOTH: /* drop all */
5480 clear_flags |= FD_READ|FD_WRITE;
5481 /*fall through */
5482 default:
5483 clear_flags |= FD_WINE_LISTENING;
5486 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
5488 switch ( how )
5490 case SD_RECEIVE:
5491 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
5492 break;
5493 case SD_SEND:
5494 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
5495 break;
5496 case SD_BOTH:
5497 default:
5498 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
5499 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
5500 break;
5502 if (err) goto error;
5504 else /* non-overlapped mode */
5506 if ( shutdown( fd, how ) )
5508 err = wsaErrno();
5509 goto error;
5513 release_sock_fd( s, fd );
5514 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
5515 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
5516 return 0;
5518 error:
5519 release_sock_fd( s, fd );
5520 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
5521 SetLastError( err );
5522 return SOCKET_ERROR;
5525 /***********************************************************************
5526 * socket (WS2_32.23)
5528 SOCKET WINAPI WS_socket(int af, int type, int protocol)
5530 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
5532 return WSASocketW( af, type, protocol, NULL, 0,
5533 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
5537 /***********************************************************************
5538 * gethostbyaddr (WS2_32.51)
5540 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
5542 struct WS_hostent *retval = NULL;
5543 struct hostent* host;
5544 int unixtype = convert_af_w2u(type);
5545 const char *paddr = addr;
5546 unsigned long loopback;
5547 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5548 char *extrabuf;
5549 int ebufsize = 1024;
5550 struct hostent hostentry;
5551 int locerr = ENOBUFS;
5552 #endif
5554 /* convert back the magic loopback address if necessary */
5555 if (unixtype == AF_INET && len == 4 && !memcmp(addr, magic_loopback_addr, 4))
5557 loopback = htonl(INADDR_LOOPBACK);
5558 paddr = (char*) &loopback;
5561 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5562 host = NULL;
5563 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
5564 while(extrabuf) {
5565 int res = gethostbyaddr_r(paddr, len, unixtype,
5566 &hostentry, extrabuf, ebufsize, &host, &locerr);
5567 if (res != ERANGE) break;
5568 ebufsize *=2;
5569 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
5571 if (host) retval = WS_dup_he(host);
5572 else SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
5573 HeapFree(GetProcessHeap(),0,extrabuf);
5574 #else
5575 EnterCriticalSection( &csWSgetXXXbyYYY );
5576 host = gethostbyaddr(paddr, len, unixtype);
5577 if (host) retval = WS_dup_he(host);
5578 else SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
5579 LeaveCriticalSection( &csWSgetXXXbyYYY );
5580 #endif
5581 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
5582 return retval;
5585 /***********************************************************************
5586 * WS_compare_routes_by_metric_asc (INTERNAL)
5588 * Comparison function for qsort(), for sorting two routes (struct route)
5589 * by metric in ascending order.
5591 static int WS_compare_routes_by_metric_asc(const void *left, const void *right)
5593 return ((const struct route*)left)->metric - ((const struct route*)right)->metric;
5596 /***********************************************************************
5597 * WS_get_local_ips (INTERNAL)
5599 * Returns the list of local IP addresses by going through the network
5600 * adapters and using the local routing table to sort the addresses
5601 * from highest routing priority to lowest routing priority. This
5602 * functionality is inferred from the description for obtaining local
5603 * IP addresses given in the Knowledge Base Article Q160215.
5605 * Please note that the returned hostent is only freed when the thread
5606 * closes and is replaced if another hostent is requested.
5608 static struct WS_hostent* WS_get_local_ips( char *hostname )
5610 int numroutes = 0, i, j;
5611 DWORD n;
5612 PIP_ADAPTER_INFO adapters = NULL, k;
5613 struct WS_hostent *hostlist = NULL;
5614 PMIB_IPFORWARDTABLE routes = NULL;
5615 struct route *route_addrs = NULL;
5616 DWORD adap_size, route_size;
5618 /* Obtain the size of the adapter list and routing table, also allocate memory */
5619 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
5620 return NULL;
5621 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
5622 return NULL;
5623 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
5624 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
5625 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
5626 if (adapters == NULL || routes == NULL || route_addrs == NULL)
5627 goto cleanup;
5628 /* Obtain the adapter list and the full routing table */
5629 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
5630 goto cleanup;
5631 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
5632 goto cleanup;
5633 /* Store the interface associated with each route */
5634 for (n = 0; n < routes->dwNumEntries; n++)
5636 IF_INDEX ifindex;
5637 DWORD ifmetric;
5638 BOOL exists = FALSE;
5640 if (routes->table[n].u1.ForwardType != MIB_IPROUTE_TYPE_DIRECT)
5641 continue;
5642 ifindex = routes->table[n].dwForwardIfIndex;
5643 ifmetric = routes->table[n].dwForwardMetric1;
5644 /* Only store the lowest valued metric for an interface */
5645 for (j = 0; j < numroutes; j++)
5647 if (route_addrs[j].interface == ifindex)
5649 if (route_addrs[j].metric > ifmetric)
5650 route_addrs[j].metric = ifmetric;
5651 exists = TRUE;
5654 if (exists)
5655 continue;
5656 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
5657 if (route_addrs == NULL)
5658 goto cleanup; /* Memory allocation error, fail gracefully */
5659 route_addrs[numroutes].interface = ifindex;
5660 route_addrs[numroutes].metric = ifmetric;
5661 /* If no IP is found in the next step (for whatever reason)
5662 * then fall back to the magic loopback address.
5664 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
5665 numroutes++;
5667 if (numroutes == 0)
5668 goto cleanup; /* No routes, fall back to the Magic IP */
5669 /* Find the IP address associated with each found interface */
5670 for (i = 0; i < numroutes; i++)
5672 for (k = adapters; k != NULL; k = k->Next)
5674 char *ip = k->IpAddressList.IpAddress.String;
5676 if (route_addrs[i].interface == k->Index)
5677 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
5680 /* Allocate a hostent and enough memory for all the IPs,
5681 * including the NULL at the end of the list.
5683 hostlist = WS_create_he(hostname, 1, 0, numroutes+1, sizeof(struct in_addr));
5684 if (hostlist == NULL)
5685 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
5686 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
5687 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
5688 hostlist->h_addrtype = AF_INET;
5689 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
5690 /* Reorder the entries before placing them in the host list. Windows expects
5691 * the IP list in order from highest priority to lowest (the critical thing
5692 * is that most applications expect the first IP to be the default route).
5694 if (numroutes > 1)
5695 qsort(route_addrs, numroutes, sizeof(struct route), WS_compare_routes_by_metric_asc);
5697 for (i = 0; i < numroutes; i++)
5698 (*(struct in_addr *) hostlist->h_addr_list[i]) = route_addrs[i].addr;
5700 /* Cleanup all allocated memory except the address list,
5701 * the address list is used by the calling app.
5703 cleanup:
5704 HeapFree(GetProcessHeap(), 0, route_addrs);
5705 HeapFree(GetProcessHeap(), 0, adapters);
5706 HeapFree(GetProcessHeap(), 0, routes);
5707 return hostlist;
5710 /***********************************************************************
5711 * gethostbyname (WS2_32.52)
5713 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
5715 struct WS_hostent *retval = NULL;
5716 struct hostent* host;
5717 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5718 char *extrabuf;
5719 int ebufsize=1024;
5720 struct hostent hostentry;
5721 int locerr = ENOBUFS;
5722 #endif
5723 char hostname[100];
5724 if(!num_startup) {
5725 SetLastError(WSANOTINITIALISED);
5726 return NULL;
5728 if( gethostname( hostname, 100) == -1) {
5729 SetLastError(WSAENOBUFS); /* appropriate ? */
5730 return retval;
5732 if( !name || !name[0]) {
5733 name = hostname;
5735 /* If the hostname of the local machine is requested then return the
5736 * complete list of local IP addresses */
5737 if(strcmp(name, hostname) == 0)
5738 retval = WS_get_local_ips(hostname);
5739 /* If any other hostname was requested (or the routing table lookup failed)
5740 * then return the IP found by the host OS */
5741 if(retval == NULL)
5743 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5744 host = NULL;
5745 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
5746 while(extrabuf) {
5747 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
5748 if( res != ERANGE) break;
5749 ebufsize *=2;
5750 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
5752 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
5753 #else
5754 EnterCriticalSection( &csWSgetXXXbyYYY );
5755 host = gethostbyname(name);
5756 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
5757 #endif
5758 if (host) retval = WS_dup_he(host);
5759 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5760 HeapFree(GetProcessHeap(),0,extrabuf);
5761 #else
5762 LeaveCriticalSection( &csWSgetXXXbyYYY );
5763 #endif
5765 if (retval && retval->h_addr_list[0][0] == 127 &&
5766 strcmp(name, "localhost") != 0)
5768 /* hostname != "localhost" but has loopback address. replace by our
5769 * special address.*/
5770 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
5772 TRACE( "%s ret %p\n", debugstr_a(name), retval );
5773 return retval;
5777 /***********************************************************************
5778 * getprotobyname (WS2_32.53)
5780 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
5782 struct WS_protoent* retval = NULL;
5783 #ifdef HAVE_GETPROTOBYNAME
5784 struct protoent* proto;
5785 EnterCriticalSection( &csWSgetXXXbyYYY );
5786 if( (proto = getprotobyname(name)) != NULL )
5788 retval = WS_dup_pe(proto);
5790 else {
5791 MESSAGE("protocol %s not found; You might want to add "
5792 "this to /etc/protocols\n", debugstr_a(name) );
5793 SetLastError(WSANO_DATA);
5795 LeaveCriticalSection( &csWSgetXXXbyYYY );
5796 #endif
5797 TRACE( "%s ret %p\n", debugstr_a(name), retval );
5798 return retval;
5802 /***********************************************************************
5803 * getprotobynumber (WS2_32.54)
5805 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
5807 struct WS_protoent* retval = NULL;
5808 #ifdef HAVE_GETPROTOBYNUMBER
5809 struct protoent* proto;
5810 EnterCriticalSection( &csWSgetXXXbyYYY );
5811 if( (proto = getprotobynumber(number)) != NULL )
5813 retval = WS_dup_pe(proto);
5815 else {
5816 MESSAGE("protocol number %d not found; You might want to add "
5817 "this to /etc/protocols\n", number );
5818 SetLastError(WSANO_DATA);
5820 LeaveCriticalSection( &csWSgetXXXbyYYY );
5821 #endif
5822 TRACE("%i ret %p\n", number, retval);
5823 return retval;
5827 /***********************************************************************
5828 * getservbyname (WS2_32.55)
5830 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
5832 struct WS_servent* retval = NULL;
5833 struct servent* serv;
5834 char *name_str;
5835 char *proto_str = NULL;
5837 if (!(name_str = strdup_lower(name))) return NULL;
5839 if (proto && *proto)
5841 if (!(proto_str = strdup_lower(proto)))
5843 HeapFree( GetProcessHeap(), 0, name_str );
5844 return NULL;
5848 EnterCriticalSection( &csWSgetXXXbyYYY );
5849 serv = getservbyname(name_str, proto_str);
5850 if( serv != NULL )
5852 retval = WS_dup_se(serv);
5854 else SetLastError(WSANO_DATA);
5855 LeaveCriticalSection( &csWSgetXXXbyYYY );
5856 HeapFree( GetProcessHeap(), 0, proto_str );
5857 HeapFree( GetProcessHeap(), 0, name_str );
5858 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
5859 return retval;
5862 /***********************************************************************
5863 * freeaddrinfo (WS2_32.@)
5865 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
5867 while (res) {
5868 struct WS_addrinfo *next;
5870 HeapFree(GetProcessHeap(),0,res->ai_canonname);
5871 HeapFree(GetProcessHeap(),0,res->ai_addr);
5872 next = res->ai_next;
5873 HeapFree(GetProcessHeap(),0,res);
5874 res = next;
5878 /* helper functions for getaddrinfo()/getnameinfo() */
5879 static int convert_aiflag_w2u(int winflags) {
5880 unsigned int i;
5881 int unixflags = 0;
5883 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
5884 if (ws_aiflag_map[i][0] & winflags) {
5885 unixflags |= ws_aiflag_map[i][1];
5886 winflags &= ~ws_aiflag_map[i][0];
5888 if (winflags)
5889 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
5890 return unixflags;
5893 static int convert_niflag_w2u(int winflags) {
5894 unsigned int i;
5895 int unixflags = 0;
5897 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
5898 if (ws_niflag_map[i][0] & winflags) {
5899 unixflags |= ws_niflag_map[i][1];
5900 winflags &= ~ws_niflag_map[i][0];
5902 if (winflags)
5903 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
5904 return unixflags;
5907 static int convert_aiflag_u2w(int unixflags) {
5908 unsigned int i;
5909 int winflags = 0;
5911 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
5912 if (ws_aiflag_map[i][1] & unixflags) {
5913 winflags |= ws_aiflag_map[i][0];
5914 unixflags &= ~ws_aiflag_map[i][1];
5916 if (unixflags) /* will warn usually */
5917 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
5918 return winflags;
5921 static int convert_eai_u2w(int unixret) {
5922 int i;
5924 if (!unixret) return 0;
5926 for (i=0;ws_eai_map[i][0];i++)
5927 if (ws_eai_map[i][1] == unixret)
5928 return ws_eai_map[i][0];
5930 if (unixret == EAI_SYSTEM)
5931 /* There are broken versions of glibc which return EAI_SYSTEM
5932 * and set errno to 0 instead of returning EAI_NONAME.
5934 return errno ? sock_get_error( errno ) : WS_EAI_NONAME;
5936 FIXME("Unhandled unix EAI_xxx ret %d\n", unixret);
5937 return unixret;
5940 static char *get_hostname(void)
5942 char *ret;
5943 DWORD size = 0;
5945 GetComputerNameExA( ComputerNamePhysicalDnsHostname, NULL, &size );
5946 if (GetLastError() != ERROR_MORE_DATA) return NULL;
5947 if (!(ret = HeapAlloc( GetProcessHeap(), 0, size ))) return NULL;
5948 if (!GetComputerNameExA( ComputerNamePhysicalDnsHostname, ret, &size ))
5950 HeapFree( GetProcessHeap(), 0, ret );
5951 return NULL;
5953 return ret;
5956 /***********************************************************************
5957 * getaddrinfo (WS2_32.@)
5959 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
5961 #ifdef HAVE_GETADDRINFO
5962 struct addrinfo *unixaires = NULL;
5963 int result;
5964 struct addrinfo unixhints, *punixhints = NULL;
5965 char *hostname = NULL;
5966 const char *node;
5968 *res = NULL;
5969 if (!nodename && !servname)
5971 SetLastError(WSAHOST_NOT_FOUND);
5972 return WSAHOST_NOT_FOUND;
5975 if (!nodename)
5976 node = NULL;
5977 else if (!nodename[0])
5979 node = hostname = get_hostname();
5980 if (!node) return WSA_NOT_ENOUGH_MEMORY;
5982 else
5983 node = nodename;
5985 /* servname tweak required by OSX and BSD kernels */
5986 if (servname && !servname[0]) servname = "0";
5988 if (hints) {
5989 punixhints = &unixhints;
5991 memset(&unixhints, 0, sizeof(unixhints));
5992 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
5994 /* zero is a wildcard, no need to convert */
5995 if (hints->ai_family)
5996 punixhints->ai_family = convert_af_w2u(hints->ai_family);
5997 if (hints->ai_socktype)
5998 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
5999 if (hints->ai_protocol)
6000 punixhints->ai_protocol = max(convert_proto_w2u(hints->ai_protocol), 0);
6002 if (punixhints->ai_socktype < 0)
6004 SetLastError(WSAESOCKTNOSUPPORT);
6005 HeapFree(GetProcessHeap(), 0, hostname);
6006 return SOCKET_ERROR;
6009 /* windows allows invalid combinations of socket type and protocol, unix does not.
6010 * fix the parameters here to make getaddrinfo call always work */
6011 if (punixhints->ai_protocol == IPPROTO_TCP &&
6012 punixhints->ai_socktype != SOCK_STREAM && punixhints->ai_socktype != SOCK_SEQPACKET)
6013 punixhints->ai_socktype = 0;
6015 else if (punixhints->ai_protocol == IPPROTO_UDP && punixhints->ai_socktype != SOCK_DGRAM)
6016 punixhints->ai_socktype = 0;
6018 else if (IS_IPX_PROTO(punixhints->ai_protocol) && punixhints->ai_socktype != SOCK_DGRAM)
6019 punixhints->ai_socktype = 0;
6022 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
6023 result = getaddrinfo(node, servname, punixhints, &unixaires);
6025 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
6026 HeapFree(GetProcessHeap(), 0, hostname);
6028 if (!result) {
6029 struct addrinfo *xuai = unixaires;
6030 struct WS_addrinfo **xai = res;
6032 *xai = NULL;
6033 while (xuai) {
6034 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
6035 SIZE_T len;
6037 if (!ai)
6038 goto outofmem;
6040 *xai = ai;xai = &ai->ai_next;
6041 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
6042 ai->ai_family = convert_af_u2w(xuai->ai_family);
6043 /* copy whatever was sent in the hints */
6044 if(hints) {
6045 ai->ai_socktype = hints->ai_socktype;
6046 ai->ai_protocol = hints->ai_protocol;
6047 } else {
6048 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
6049 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
6051 if (xuai->ai_canonname) {
6052 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
6053 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
6054 if (!ai->ai_canonname)
6055 goto outofmem;
6056 strcpy(ai->ai_canonname,xuai->ai_canonname);
6058 len = xuai->ai_addrlen;
6059 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
6060 if (!ai->ai_addr)
6061 goto outofmem;
6062 ai->ai_addrlen = len;
6063 do {
6064 int winlen = ai->ai_addrlen;
6066 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
6067 ai->ai_addrlen = winlen;
6068 break;
6070 len = 2*len;
6071 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
6072 if (!ai->ai_addr)
6073 goto outofmem;
6074 ai->ai_addrlen = len;
6075 } while (1);
6076 xuai = xuai->ai_next;
6078 freeaddrinfo(unixaires);
6080 if (TRACE_ON(winsock))
6082 struct WS_addrinfo *ai = *res;
6083 while (ai)
6085 TRACE("=> %p, flags %#x, family %d, type %d, protocol %d, len %ld, name %s, addr %s\n",
6086 ai, ai->ai_flags, ai->ai_family, ai->ai_socktype, ai->ai_protocol, ai->ai_addrlen,
6087 ai->ai_canonname, debugstr_sockaddr(ai->ai_addr));
6088 ai = ai->ai_next;
6091 } else
6092 result = convert_eai_u2w(result);
6094 SetLastError(result);
6095 return result;
6097 outofmem:
6098 if (*res) WS_freeaddrinfo(*res);
6099 if (unixaires) freeaddrinfo(unixaires);
6100 return WSA_NOT_ENOUGH_MEMORY;
6101 #else
6102 FIXME("getaddrinfo() failed, not found during buildtime.\n");
6103 return EAI_FAIL;
6104 #endif
6107 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
6109 struct WS_addrinfoW *ret;
6111 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
6112 ret->ai_flags = ai->ai_flags;
6113 ret->ai_family = ai->ai_family;
6114 ret->ai_socktype = ai->ai_socktype;
6115 ret->ai_protocol = ai->ai_protocol;
6116 ret->ai_addrlen = ai->ai_addrlen;
6117 ret->ai_canonname = NULL;
6118 ret->ai_addr = NULL;
6119 ret->ai_next = NULL;
6120 if (ai->ai_canonname)
6122 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
6123 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len*sizeof(WCHAR))))
6125 HeapFree(GetProcessHeap(), 0, ret);
6126 return NULL;
6128 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
6130 if (ai->ai_addr)
6132 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, ai->ai_addrlen)))
6134 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
6135 HeapFree(GetProcessHeap(), 0, ret);
6136 return NULL;
6138 memcpy(ret->ai_addr, ai->ai_addr, ai->ai_addrlen);
6140 return ret;
6143 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
6145 struct WS_addrinfoW *ret, *infoW;
6147 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
6148 while (info->ai_next)
6150 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
6152 FreeAddrInfoW(ret);
6153 return NULL;
6155 infoW = infoW->ai_next;
6156 info = info->ai_next;
6158 return ret;
6161 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
6163 struct WS_addrinfo *ret;
6165 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
6166 ret->ai_flags = ai->ai_flags;
6167 ret->ai_family = ai->ai_family;
6168 ret->ai_socktype = ai->ai_socktype;
6169 ret->ai_protocol = ai->ai_protocol;
6170 ret->ai_addrlen = ai->ai_addrlen;
6171 ret->ai_canonname = NULL;
6172 ret->ai_addr = NULL;
6173 ret->ai_next = NULL;
6174 if (ai->ai_canonname)
6176 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
6177 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
6179 HeapFree(GetProcessHeap(), 0, ret);
6180 return NULL;
6182 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
6184 if (ai->ai_addr)
6186 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
6188 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
6189 HeapFree(GetProcessHeap(), 0, ret);
6190 return NULL;
6192 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
6194 return ret;
6197 /***********************************************************************
6198 * GetAddrInfoW (WS2_32.@)
6200 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
6202 int ret, len;
6203 char *nodenameA = NULL, *servnameA = NULL;
6204 struct WS_addrinfo *resA, *hintsA = NULL;
6206 *res = NULL;
6207 if (nodename)
6209 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
6210 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
6211 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
6213 if (servname)
6215 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
6216 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
6218 HeapFree(GetProcessHeap(), 0, nodenameA);
6219 return EAI_MEMORY;
6221 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
6224 if (hints) hintsA = addrinfo_WtoA(hints);
6225 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
6226 WS_freeaddrinfo(hintsA);
6228 if (!ret)
6230 *res = addrinfo_list_AtoW(resA);
6231 WS_freeaddrinfo(resA);
6234 HeapFree(GetProcessHeap(), 0, nodenameA);
6235 HeapFree(GetProcessHeap(), 0, servnameA);
6236 return ret;
6239 /***********************************************************************
6240 * FreeAddrInfoW (WS2_32.@)
6242 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
6244 while (ai)
6246 ADDRINFOW *next;
6247 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
6248 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
6249 next = ai->ai_next;
6250 HeapFree(GetProcessHeap(), 0, ai);
6251 ai = next;
6255 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
6256 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
6258 #ifdef HAVE_GETNAMEINFO
6259 int ret;
6260 union generic_unix_sockaddr sa_u;
6261 unsigned int size;
6263 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
6264 serv, servlen, flags);
6266 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
6267 if (!size)
6269 SetLastError(WSAEFAULT);
6270 return WSA_NOT_ENOUGH_MEMORY;
6272 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
6273 return convert_eai_u2w(ret);
6274 #else
6275 FIXME("getnameinfo() failed, not found during buildtime.\n");
6276 return EAI_FAIL;
6277 #endif
6280 int WINAPI GetNameInfoW(const SOCKADDR *sa, WS_socklen_t salen, PWCHAR host,
6281 DWORD hostlen, PWCHAR serv, DWORD servlen, INT flags)
6283 int ret;
6284 char *hostA = NULL, *servA = NULL;
6286 if (host && (!(hostA = HeapAlloc(GetProcessHeap(), 0, hostlen)))) return EAI_MEMORY;
6287 if (serv && (!(servA = HeapAlloc(GetProcessHeap(), 0, servlen))))
6289 HeapFree(GetProcessHeap(), 0, hostA);
6290 return EAI_MEMORY;
6293 ret = WS_getnameinfo(sa, salen, hostA, hostlen, servA, servlen, flags);
6294 if (!ret)
6296 if (host) MultiByteToWideChar(CP_ACP, 0, hostA, -1, host, hostlen);
6297 if (serv) MultiByteToWideChar(CP_ACP, 0, servA, -1, serv, servlen);
6300 HeapFree(GetProcessHeap(), 0, hostA);
6301 HeapFree(GetProcessHeap(), 0, servA);
6302 return ret;
6305 /***********************************************************************
6306 * getservbyport (WS2_32.56)
6308 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
6310 struct WS_servent* retval = NULL;
6311 #ifdef HAVE_GETSERVBYPORT
6312 struct servent* serv;
6313 char *proto_str = NULL;
6315 if (proto && *proto)
6317 if (!(proto_str = strdup_lower(proto))) return NULL;
6319 EnterCriticalSection( &csWSgetXXXbyYYY );
6320 if( (serv = getservbyport(port, proto_str)) != NULL ) {
6321 retval = WS_dup_se(serv);
6323 else SetLastError(WSANO_DATA);
6324 LeaveCriticalSection( &csWSgetXXXbyYYY );
6325 HeapFree( GetProcessHeap(), 0, proto_str );
6326 #endif
6327 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
6328 return retval;
6332 /***********************************************************************
6333 * gethostname (WS2_32.57)
6335 int WINAPI WS_gethostname(char *name, int namelen)
6337 char buf[256];
6338 int len;
6340 TRACE("name %p, len %d\n", name, namelen);
6342 if (!name)
6344 SetLastError(WSAEFAULT);
6345 return SOCKET_ERROR;
6348 if (gethostname(buf, sizeof(buf)) != 0)
6350 SetLastError(wsaErrno());
6351 return SOCKET_ERROR;
6354 TRACE("<- '%s'\n", buf);
6355 len = strlen(buf);
6356 if (len > 15)
6357 WARN("Windows supports NetBIOS name length up to 15 bytes!\n");
6358 if (namelen <= len)
6360 SetLastError(WSAEFAULT);
6361 WARN("<- not enough space for hostname, required %d, got %d!\n", len + 1, namelen);
6362 return SOCKET_ERROR;
6364 strcpy(name, buf);
6365 return 0;
6369 /* ------------------------------------- Windows sockets extensions -- *
6371 * ------------------------------------------------------------------- */
6373 /***********************************************************************
6374 * WSAEnumNetworkEvents (WS2_32.36)
6376 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
6378 int ret;
6379 int i;
6380 int errors[FD_MAX_EVENTS];
6382 TRACE("%04lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
6384 SERVER_START_REQ( get_socket_event )
6386 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6387 req->service = TRUE;
6388 req->c_event = wine_server_obj_handle( hEvent );
6389 wine_server_set_reply( req, errors, sizeof(errors) );
6390 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
6392 SERVER_END_REQ;
6393 if (!ret)
6395 for (i = 0; i < FD_MAX_EVENTS; i++)
6396 lpEvent->iErrorCode[i] = NtStatusToWSAError(errors[i]);
6397 return 0;
6399 SetLastError(WSAEINVAL);
6400 return SOCKET_ERROR;
6403 /***********************************************************************
6404 * WSAEventSelect (WS2_32.39)
6406 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
6408 int ret;
6410 TRACE("%04lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
6412 SERVER_START_REQ( set_socket_event )
6414 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6415 req->mask = lEvent;
6416 req->event = wine_server_obj_handle( hEvent );
6417 req->window = 0;
6418 req->msg = 0;
6419 ret = wine_server_call( req );
6421 SERVER_END_REQ;
6422 if (!ret) return 0;
6423 SetLastError(WSAEINVAL);
6424 return SOCKET_ERROR;
6427 /**********************************************************************
6428 * WSAGetOverlappedResult (WS2_32.40)
6430 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
6431 LPDWORD lpcbTransfer, BOOL fWait,
6432 LPDWORD lpdwFlags )
6434 NTSTATUS status;
6436 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
6437 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
6439 if ( lpOverlapped == NULL )
6441 ERR( "Invalid pointer\n" );
6442 SetLastError(WSA_INVALID_PARAMETER);
6443 return FALSE;
6446 status = lpOverlapped->Internal;
6447 if (status == STATUS_PENDING)
6449 if (!fWait)
6451 SetLastError( WSA_IO_INCOMPLETE );
6452 return FALSE;
6455 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
6456 INFINITE ) == WAIT_FAILED)
6457 return FALSE;
6458 status = lpOverlapped->Internal;
6461 if ( lpcbTransfer )
6462 *lpcbTransfer = lpOverlapped->InternalHigh;
6464 if ( lpdwFlags )
6465 *lpdwFlags = lpOverlapped->u.s.Offset;
6467 if (status) SetLastError( RtlNtStatusToDosError(status) );
6468 return !status;
6472 /***********************************************************************
6473 * WSAAsyncSelect (WS2_32.101)
6475 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
6477 int ret;
6479 TRACE("%04lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
6481 SERVER_START_REQ( set_socket_event )
6483 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6484 req->mask = lEvent;
6485 req->event = 0;
6486 req->window = wine_server_user_handle( hWnd );
6487 req->msg = uMsg;
6488 ret = wine_server_call( req );
6490 SERVER_END_REQ;
6491 if (!ret) return 0;
6492 SetLastError(WSAEINVAL);
6493 return SOCKET_ERROR;
6496 /***********************************************************************
6497 * WSACreateEvent (WS2_32.31)
6500 WSAEVENT WINAPI WSACreateEvent(void)
6502 /* Create a manual-reset event, with initial state: unsignaled */
6503 TRACE("\n");
6505 return CreateEventW(NULL, TRUE, FALSE, NULL);
6508 /***********************************************************************
6509 * WSACloseEvent (WS2_32.29)
6512 BOOL WINAPI WSACloseEvent(WSAEVENT event)
6514 TRACE ("event=%p\n", event);
6516 return CloseHandle(event);
6519 /***********************************************************************
6520 * WSASocketA (WS2_32.78)
6523 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
6524 LPWSAPROTOCOL_INFOA lpProtocolInfo,
6525 GROUP g, DWORD dwFlags)
6527 INT len;
6528 WSAPROTOCOL_INFOW info;
6530 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
6531 af, type, protocol, lpProtocolInfo, g, dwFlags);
6533 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
6535 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
6536 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
6537 info.szProtocol, WSAPROTOCOL_LEN + 1);
6539 if (!len)
6541 SetLastError(WSAEINVAL);
6542 return SOCKET_ERROR;
6545 return WSASocketW(af, type, protocol, &info, g, dwFlags);
6548 /***********************************************************************
6549 * WSASocketW (WS2_32.79)
6552 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
6553 LPWSAPROTOCOL_INFOW lpProtocolInfo,
6554 GROUP g, DWORD dwFlags)
6556 SOCKET ret;
6557 DWORD err;
6558 int unixaf, unixtype, ipxptype = -1;
6561 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
6562 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
6565 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
6566 af, type, protocol, lpProtocolInfo, g, dwFlags );
6568 if (!num_startup)
6570 err = WSANOTINITIALISED;
6571 goto done;
6574 /* hack for WSADuplicateSocket */
6575 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
6576 ret = lpProtocolInfo->dwServiceFlags3;
6577 TRACE("\tgot duplicate %04lx\n", ret);
6578 return ret;
6581 if (lpProtocolInfo)
6583 if (af == FROM_PROTOCOL_INFO || !af)
6584 af = lpProtocolInfo->iAddressFamily;
6585 if (type == FROM_PROTOCOL_INFO || !type)
6586 type = lpProtocolInfo->iSocketType;
6587 if (protocol == FROM_PROTOCOL_INFO || !protocol)
6588 protocol = lpProtocolInfo->iProtocol;
6591 if (!type && (af || protocol))
6593 int autoproto = protocol;
6594 WSAPROTOCOL_INFOW infow;
6596 /* default to the first valid protocol */
6597 if (!autoproto)
6598 autoproto = valid_protocols[0];
6599 else if(IS_IPX_PROTO(autoproto))
6600 autoproto = WS_NSPROTO_IPX;
6602 if (WS_EnterSingleProtocolW(autoproto, &infow))
6604 type = infow.iSocketType;
6606 /* after win2003 it's no longer possible to pass AF_UNSPEC
6607 using the protocol info struct */
6608 if (!lpProtocolInfo && af == WS_AF_UNSPEC)
6609 af = infow.iAddressFamily;
6614 Windows has an extension to the IPX protocol that allows one to create sockets
6615 and set the IPX packet type at the same time, to do that a caller will use
6616 a protocol like NSPROTO_IPX + <PACKET TYPE>
6618 if (IS_IPX_PROTO(protocol))
6619 ipxptype = protocol - WS_NSPROTO_IPX;
6621 /* convert the socket family, type and protocol */
6622 unixaf = convert_af_w2u(af);
6623 unixtype = convert_socktype_w2u(type);
6624 protocol = convert_proto_w2u(protocol);
6625 if (unixaf == AF_UNSPEC) unixaf = -1;
6627 /* filter invalid parameters */
6628 if (protocol < 0)
6630 /* the type could not be converted */
6631 if (type && unixtype < 0)
6633 err = WSAESOCKTNOSUPPORT;
6634 goto done;
6637 err = WSAEPROTONOSUPPORT;
6638 goto done;
6640 if (unixaf < 0)
6642 /* both family and protocol can't be invalid */
6643 if (protocol <= 0)
6645 err = WSAEINVAL;
6646 goto done;
6649 /* family could not be converted and neither socket type */
6650 if (unixtype < 0 && af >= 0)
6653 err = WSAESOCKTNOSUPPORT;
6654 goto done;
6657 err = WSAEAFNOSUPPORT;
6658 goto done;
6661 SERVER_START_REQ( create_socket )
6663 req->family = unixaf;
6664 req->type = unixtype;
6665 req->protocol = protocol;
6666 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
6667 req->attributes = (dwFlags & WSA_FLAG_NO_HANDLE_INHERIT) ? 0 : OBJ_INHERIT;
6668 req->flags = dwFlags & ~WSA_FLAG_NO_HANDLE_INHERIT;
6669 set_error( wine_server_call( req ) );
6670 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
6672 SERVER_END_REQ;
6673 if (ret)
6675 TRACE("\tcreated %04lx\n", ret );
6676 if (ipxptype > 0)
6677 set_ipx_packettype(ret, ipxptype);
6678 return ret;
6681 err = GetLastError();
6682 if (err == WSAEACCES) /* raw socket denied */
6684 if (type == SOCK_RAW)
6685 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
6686 else
6687 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
6689 else
6691 /* invalid combination of valid parameters, like SOCK_STREAM + IPPROTO_UDP */
6692 if (err == WSAEINVAL)
6693 err = WSAESOCKTNOSUPPORT;
6694 else if (err == WSAEOPNOTSUPP)
6695 err = WSAEPROTONOSUPPORT;
6698 done:
6699 WARN("\t\tfailed, error %d!\n", err);
6700 SetLastError(err);
6701 return INVALID_SOCKET;
6704 /***********************************************************************
6705 * WSAJoinLeaf (WS2_32.58)
6708 SOCKET WINAPI WSAJoinLeaf(
6709 SOCKET s,
6710 const struct WS_sockaddr *addr,
6711 int addrlen,
6712 LPWSABUF lpCallerData,
6713 LPWSABUF lpCalleeData,
6714 LPQOS lpSQOS,
6715 LPQOS lpGQOS,
6716 DWORD dwFlags)
6718 FIXME("stub.\n");
6719 return INVALID_SOCKET;
6722 /***********************************************************************
6723 * __WSAFDIsSet (WS2_32.151)
6725 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
6727 int i = set->fd_count, ret = 0;
6729 while (i--)
6730 if (set->fd_array[i] == s)
6732 ret = 1;
6733 break;
6736 TRACE("(socket %04lx, fd_set %p, count %i) <- %d\n", s, set, set->fd_count, ret);
6737 return ret;
6740 /***********************************************************************
6741 * WSAIsBlocking (WS2_32.114)
6743 BOOL WINAPI WSAIsBlocking(void)
6745 /* By default WinSock should set all its sockets to non-blocking mode
6746 * and poll in PeekMessage loop when processing "blocking" ones. This
6747 * function is supposed to tell if the program is in this loop. Our
6748 * blocking calls are truly blocking so we always return FALSE.
6750 * Note: It is allowed to call this function without prior WSAStartup().
6753 TRACE("\n");
6754 return FALSE;
6757 /***********************************************************************
6758 * WSACancelBlockingCall (WS2_32.113)
6760 INT WINAPI WSACancelBlockingCall(void)
6762 TRACE("\n");
6763 return 0;
6766 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
6768 FIXME("How was this called?\n");
6769 return x();
6773 /***********************************************************************
6774 * WSASetBlockingHook (WS2_32.109)
6776 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
6778 FARPROC prev = blocking_hook;
6779 blocking_hook = lpBlockFunc;
6780 TRACE("hook %p\n", lpBlockFunc);
6781 return prev;
6785 /***********************************************************************
6786 * WSAUnhookBlockingHook (WS2_32.110)
6788 INT WINAPI WSAUnhookBlockingHook(void)
6790 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
6791 return 0;
6795 /* ----------------------------------- end of API stuff */
6797 /* ----------------------------------- helper functions -
6799 * TODO: Merge WS_dup_..() stuff into one function that
6800 * would operate with a generic structure containing internal
6801 * pointers (via a template of some kind).
6804 static int list_size(char** l, int item_size)
6806 int i,j = 0;
6807 if(l)
6808 { for(i=0;l[i];i++)
6809 j += (item_size) ? item_size : strlen(l[i]) + 1;
6810 j += (i + 1) * sizeof(char*); }
6811 return j;
6814 static int list_dup(char** l_src, char** l_to, int item_size)
6816 char *p;
6817 int i;
6819 for (i = 0; l_src[i]; i++) ;
6820 p = (char *)(l_to + i + 1);
6821 for (i = 0; l_src[i]; i++)
6823 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
6824 memcpy(p, l_src[i], count);
6825 l_to[i] = p;
6826 p += count;
6828 l_to[i] = NULL;
6829 return p - (char *)l_to;
6832 /* ----- hostent */
6834 /* create a hostent entry
6836 * Creates the entry with enough memory for the name, aliases
6837 * addresses, and the address pointers. Also copies the name
6838 * and sets up all the pointers.
6840 * NOTE: The alias and address lists must be allocated with room
6841 * for the NULL item terminating the list. This is true even if
6842 * the list has no items ("aliases" and "addresses" must be
6843 * at least "1", a truly empty list is invalid).
6845 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length)
6847 struct WS_hostent *p_to;
6848 char *p;
6849 int size = (sizeof(struct WS_hostent) +
6850 strlen(name) + 1 +
6851 sizeof(char *) * aliases +
6852 aliases_size +
6853 sizeof(char *) * addresses +
6854 address_length * (addresses - 1)), i;
6856 if (!(p_to = check_buffer_he(size))) return NULL;
6857 memset(p_to, 0, size);
6859 /* Use the memory in the same way winsock does.
6860 * First set the pointer for aliases, second set the pointers for addresses.
6861 * Third fill the addresses indexes, fourth jump aliases names size.
6862 * Fifth fill the hostname.
6863 * NOTE: This method is valid for OS version's >= XP.
6865 p = (char *)(p_to + 1);
6866 p_to->h_aliases = (char **)p;
6867 p += sizeof(char *)*aliases;
6869 p_to->h_addr_list = (char **)p;
6870 p += sizeof(char *)*addresses;
6872 for (i = 0, addresses--; i < addresses; i++, p += address_length)
6873 p_to->h_addr_list[i] = p;
6875 /* NOTE: h_aliases must be filled in manually because we don't know each string
6876 * size, leave these pointers NULL (already set to NULL by memset earlier).
6878 p += aliases_size;
6880 p_to->h_name = p;
6881 strcpy(p, name);
6883 return p_to;
6886 /* duplicate hostent entry
6887 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
6888 * Ditto for protoent and servent.
6890 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
6892 int i, addresses = 0, alias_size = 0;
6893 struct WS_hostent *p_to;
6894 char *p;
6896 for( i = 0; p_he->h_aliases[i]; i++) alias_size += strlen(p_he->h_aliases[i]) + 1;
6897 while (p_he->h_addr_list[addresses]) addresses++;
6899 p_to = WS_create_he(p_he->h_name, i + 1, alias_size, addresses + 1, p_he->h_length);
6901 if (!p_to) return NULL;
6902 p_to->h_addrtype = convert_af_u2w(p_he->h_addrtype);
6903 p_to->h_length = p_he->h_length;
6905 for(i = 0, p = p_to->h_addr_list[0]; p_he->h_addr_list[i]; i++, p += p_to->h_length)
6906 memcpy(p, p_he->h_addr_list[i], p_to->h_length);
6908 /* Fill the aliases after the IP data */
6909 for(i = 0; p_he->h_aliases[i]; i++)
6911 p_to->h_aliases[i] = p;
6912 strcpy(p, p_he->h_aliases[i]);
6913 p += strlen(p) + 1;
6916 return p_to;
6919 /* ----- protoent */
6921 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
6923 char *p;
6924 struct WS_protoent *p_to;
6926 int size = (sizeof(*p_pe) +
6927 strlen(p_pe->p_name) + 1 +
6928 list_size(p_pe->p_aliases, 0));
6930 if (!(p_to = check_buffer_pe(size))) return NULL;
6931 p_to->p_proto = p_pe->p_proto;
6933 p = (char *)(p_to + 1);
6934 p_to->p_name = p;
6935 strcpy(p, p_pe->p_name);
6936 p += strlen(p) + 1;
6938 p_to->p_aliases = (char **)p;
6939 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
6940 return p_to;
6943 /* ----- servent */
6945 static struct WS_servent *WS_dup_se(const struct servent* p_se)
6947 char *p;
6948 struct WS_servent *p_to;
6950 int size = (sizeof(*p_se) +
6951 strlen(p_se->s_proto) + 1 +
6952 strlen(p_se->s_name) + 1 +
6953 list_size(p_se->s_aliases, 0));
6955 if (!(p_to = check_buffer_se(size))) return NULL;
6956 p_to->s_port = p_se->s_port;
6958 p = (char *)(p_to + 1);
6959 p_to->s_name = p;
6960 strcpy(p, p_se->s_name);
6961 p += strlen(p) + 1;
6963 p_to->s_proto = p;
6964 strcpy(p, p_se->s_proto);
6965 p += strlen(p) + 1;
6967 p_to->s_aliases = (char **)p;
6968 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
6969 return p_to;
6973 /***********************************************************************
6974 * WSARecv (WS2_32.67)
6976 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6977 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
6978 LPWSAOVERLAPPED lpOverlapped,
6979 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
6981 return WS2_recv_base(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
6982 NULL, NULL, lpOverlapped, lpCompletionRoutine, NULL);
6985 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6986 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
6987 struct WS_sockaddr *lpFrom,
6988 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
6989 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
6990 LPWSABUF lpControlBuffer )
6992 unsigned int i, options;
6993 int n, fd, err, overlapped, flags;
6994 struct ws2_async *wsa = NULL, localwsa;
6995 BOOL is_blocking;
6996 DWORD timeout_start = GetTickCount();
6997 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
6999 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
7000 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
7001 (lpFromlen ? *lpFromlen : -1),
7002 lpOverlapped, lpCompletionRoutine);
7004 fd = get_sock_fd( s, FILE_READ_DATA, &options );
7005 TRACE( "fd=%d, options=%x\n", fd, options );
7007 if (fd == -1) return SOCKET_ERROR;
7009 if (*lpFlags & WS_MSG_OOB)
7011 /* It's invalid to receive OOB data from an OOBINLINED socket
7012 * as OOB data is turned into normal data. */
7013 i = sizeof(n);
7014 if (!getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, (char*) &n, &i) && n)
7016 err = WSAEINVAL;
7017 goto error;
7021 overlapped = (lpOverlapped || lpCompletionRoutine) &&
7022 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
7023 if (overlapped || dwBufferCount > 1)
7025 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[dwBufferCount]))))
7027 err = WSAEFAULT;
7028 goto error;
7031 else
7032 wsa = &localwsa;
7034 wsa->hSocket = SOCKET2HANDLE(s);
7035 wsa->flags = *lpFlags;
7036 wsa->lpFlags = lpFlags;
7037 wsa->addr = lpFrom;
7038 wsa->addrlen.ptr = lpFromlen;
7039 wsa->control = lpControlBuffer;
7040 wsa->n_iovecs = dwBufferCount;
7041 wsa->first_iovec = 0;
7042 for (i = 0; i < dwBufferCount; i++)
7044 /* check buffer first to trigger write watches */
7045 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
7047 err = WSAEFAULT;
7048 goto error;
7050 wsa->iovec[i].iov_base = lpBuffers[i].buf;
7051 wsa->iovec[i].iov_len = lpBuffers[i].len;
7054 flags = convert_flags(wsa->flags);
7055 for (;;)
7057 n = WS2_recv( fd, wsa, flags );
7058 if (n == -1)
7060 /* Unix-like systems return EINVAL when attempting to read OOB data from
7061 * an empty socket buffer, convert that to a Windows expected return. */
7062 if ((flags & MSG_OOB) && errno == EINVAL)
7063 errno = EWOULDBLOCK;
7065 if (errno != EAGAIN)
7067 int loc_errno = errno;
7068 err = wsaErrno();
7069 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
7070 goto error;
7073 else if (lpNumberOfBytesRecvd) *lpNumberOfBytesRecvd = n;
7075 if (overlapped)
7077 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
7079 wsa->user_overlapped = lpOverlapped;
7080 wsa->completion_func = lpCompletionRoutine;
7081 release_sock_fd( s, fd );
7083 if (n == -1)
7085 iosb->u.Status = STATUS_PENDING;
7086 iosb->Information = 0;
7088 SERVER_START_REQ( register_async )
7090 req->type = ASYNC_TYPE_READ;
7091 req->async.handle = wine_server_obj_handle( wsa->hSocket );
7092 req->async.callback = wine_server_client_ptr( WS2_async_recv );
7093 req->async.iosb = wine_server_client_ptr( iosb );
7094 req->async.arg = wine_server_client_ptr( wsa );
7095 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
7096 req->async.cvalue = cvalue;
7097 err = wine_server_call( req );
7099 SERVER_END_REQ;
7101 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
7102 SetLastError(NtStatusToWSAError( err ));
7103 return SOCKET_ERROR;
7106 iosb->u.Status = STATUS_SUCCESS;
7107 iosb->Information = n;
7108 if (!wsa->completion_func)
7110 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
7111 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
7112 HeapFree( GetProcessHeap(), 0, wsa );
7114 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
7115 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
7116 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7117 return 0;
7120 if (n != -1) break;
7122 if ((err = _is_blocking( s, &is_blocking )))
7124 err = NtStatusToWSAError( err );
7125 goto error;
7128 if ( is_blocking )
7130 struct pollfd pfd;
7131 int poll_timeout = -1;
7132 INT64 timeout = get_rcvsnd_timeo(fd, TRUE);
7134 if (timeout)
7136 timeout -= GetTickCount() - timeout_start;
7137 if (timeout < 0) poll_timeout = 0;
7138 else poll_timeout = timeout <= INT_MAX ? timeout : INT_MAX;
7141 pfd.fd = fd;
7142 pfd.events = POLLIN;
7143 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
7145 if (!poll_timeout || !poll( &pfd, 1, poll_timeout ))
7147 err = WSAETIMEDOUT;
7148 /* a timeout is not fatal */
7149 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7150 goto error;
7153 else
7155 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7156 err = WSAEWOULDBLOCK;
7157 goto error;
7161 TRACE(" -> %i bytes\n", n);
7162 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
7163 release_sock_fd( s, fd );
7164 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7165 SetLastError(ERROR_SUCCESS);
7167 return 0;
7169 error:
7170 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
7171 release_sock_fd( s, fd );
7172 WARN(" -> ERROR %d\n", err);
7173 SetLastError( err );
7174 return SOCKET_ERROR;
7177 /***********************************************************************
7178 * WSARecvFrom (WS2_32.69)
7180 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
7181 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
7182 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
7183 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
7186 return WS2_recv_base( s, lpBuffers, dwBufferCount,
7187 lpNumberOfBytesRecvd, lpFlags,
7188 lpFrom, lpFromlen,
7189 lpOverlapped, lpCompletionRoutine, NULL );
7192 /***********************************************************************
7193 * WSCInstallProvider (WS2_32.88)
7195 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
7196 LPCWSTR lpszProviderDllPath,
7197 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
7198 DWORD dwNumberOfEntries,
7199 LPINT lpErrno )
7201 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
7202 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
7203 dwNumberOfEntries, lpErrno);
7204 *lpErrno = 0;
7205 return 0;
7209 /***********************************************************************
7210 * WSCDeinstallProvider (WS2_32.83)
7212 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
7214 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
7215 *lpErrno = 0;
7216 return 0;
7220 /***********************************************************************
7221 * WSAAccept (WS2_32.26)
7223 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
7224 LPCONDITIONPROC lpfnCondition, DWORD_PTR dwCallbackData)
7227 int ret = 0, size;
7228 WSABUF CallerId, CallerData, CalleeId, CalleeData;
7229 /* QOS SQOS, GQOS; */
7230 GROUP g;
7231 SOCKET cs;
7232 SOCKADDR src_addr, dst_addr;
7234 TRACE("socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
7235 s, addr, addrlen, lpfnCondition, dwCallbackData);
7237 cs = WS_accept(s, addr, addrlen);
7238 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
7239 if (!lpfnCondition) return cs;
7241 if (addr && addrlen)
7243 CallerId.buf = (char *)addr;
7244 CallerId.len = *addrlen;
7246 else
7248 size = sizeof(src_addr);
7249 WS_getpeername(cs, &src_addr, &size);
7250 CallerId.buf = (char *)&src_addr;
7251 CallerId.len = size;
7253 CallerData.buf = NULL;
7254 CallerData.len = 0;
7256 size = sizeof(dst_addr);
7257 WS_getsockname(cs, &dst_addr, &size);
7259 CalleeId.buf = (char *)&dst_addr;
7260 CalleeId.len = sizeof(dst_addr);
7262 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
7263 &CalleeId, &CalleeData, &g, dwCallbackData);
7265 switch (ret)
7267 case CF_ACCEPT:
7268 return cs;
7269 case CF_DEFER:
7270 SERVER_START_REQ( set_socket_deferred )
7272 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
7273 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
7274 if ( !wine_server_call_err ( req ) )
7276 SetLastError( WSATRY_AGAIN );
7277 WS_closesocket( cs );
7280 SERVER_END_REQ;
7281 return SOCKET_ERROR;
7282 case CF_REJECT:
7283 WS_closesocket(cs);
7284 SetLastError(WSAECONNREFUSED);
7285 return SOCKET_ERROR;
7286 default:
7287 FIXME("Unknown return type from Condition function\n");
7288 SetLastError(WSAENOTSOCK);
7289 return SOCKET_ERROR;
7293 /***********************************************************************
7294 * WSADuplicateSocketA (WS2_32.32)
7296 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
7298 return WS_DuplicateSocket(FALSE, s, dwProcessId, (LPWSAPROTOCOL_INFOW) lpProtocolInfo);
7301 /***********************************************************************
7302 * WSADuplicateSocketW (WS2_32.33)
7304 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
7306 return WS_DuplicateSocket(TRUE, s, dwProcessId, lpProtocolInfo);
7309 /***********************************************************************
7310 * WSAInstallServiceClassA (WS2_32.48)
7312 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
7314 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
7315 SetLastError(WSAEACCES);
7316 return SOCKET_ERROR;
7319 /***********************************************************************
7320 * WSAInstallServiceClassW (WS2_32.49)
7322 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
7324 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
7325 SetLastError(WSAEACCES);
7326 return SOCKET_ERROR;
7329 /***********************************************************************
7330 * WSARemoveServiceClass (WS2_32.70)
7332 int WINAPI WSARemoveServiceClass(LPGUID info)
7334 FIXME("Request to remove service %p\n",info);
7335 SetLastError(WSATYPE_NOT_FOUND);
7336 return SOCKET_ERROR;
7339 /***********************************************************************
7340 * inet_ntop (WS2_32.@)
7342 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
7344 #ifdef HAVE_INET_NTOP
7345 struct WS_in6_addr *in6;
7346 struct WS_in_addr *in;
7347 PCSTR pdst;
7349 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
7350 if (!buffer)
7352 SetLastError( STATUS_INVALID_PARAMETER );
7353 return NULL;
7356 switch (family)
7358 case WS_AF_INET:
7360 in = addr;
7361 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
7362 break;
7364 case WS_AF_INET6:
7366 in6 = addr;
7367 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
7368 break;
7370 default:
7371 SetLastError( WSAEAFNOSUPPORT );
7372 return NULL;
7375 if (!pdst) SetLastError( STATUS_INVALID_PARAMETER );
7376 return pdst;
7377 #else
7378 FIXME( "not supported on this platform\n" );
7379 SetLastError( WSAEAFNOSUPPORT );
7380 return NULL;
7381 #endif
7384 /***********************************************************************
7385 * inet_pton (WS2_32.@)
7387 INT WINAPI WS_inet_pton( INT family, PCSTR addr, PVOID buffer)
7389 #ifdef HAVE_INET_PTON
7390 int unixaf, ret;
7392 TRACE("family %d, addr '%s', buffer (%p)\n", family, addr ? addr : "(null)", buffer);
7394 if (!addr || !buffer)
7396 SetLastError(WSAEFAULT);
7397 return SOCKET_ERROR;
7400 unixaf = convert_af_w2u(family);
7401 if (unixaf != AF_INET && unixaf != AF_INET6)
7403 SetLastError(WSAEAFNOSUPPORT);
7404 return SOCKET_ERROR;
7407 ret = inet_pton(unixaf, addr, buffer);
7408 if (ret == -1) SetLastError(wsaErrno());
7409 return ret;
7410 #else
7411 FIXME( "not supported on this platform\n" );
7412 SetLastError( WSAEAFNOSUPPORT );
7413 return SOCKET_ERROR;
7414 #endif
7418 /***********************************************************************
7419 * WSAStringToAddressA (WS2_32.80)
7421 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
7422 INT AddressFamily,
7423 LPWSAPROTOCOL_INFOA lpProtocolInfo,
7424 LPSOCKADDR lpAddress,
7425 LPINT lpAddressLength)
7427 INT res=0;
7428 LPSTR workBuffer=NULL,ptrPort;
7430 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
7431 lpProtocolInfo, lpAddress, lpAddressLength );
7433 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
7435 if (!AddressString)
7437 SetLastError(WSAEINVAL);
7438 return SOCKET_ERROR;
7441 if (lpProtocolInfo)
7442 FIXME("ProtocolInfo not implemented.\n");
7444 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
7445 strlen(AddressString) + 1);
7446 if (!workBuffer)
7448 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7449 return SOCKET_ERROR;
7452 strcpy(workBuffer, AddressString);
7454 switch(AddressFamily)
7456 case WS_AF_INET:
7458 struct in_addr inetaddr;
7460 /* If lpAddressLength is too small, tell caller the size we need */
7461 if (*lpAddressLength < sizeof(SOCKADDR_IN))
7463 *lpAddressLength = sizeof(SOCKADDR_IN);
7464 res = WSAEFAULT;
7465 break;
7467 *lpAddressLength = sizeof(SOCKADDR_IN);
7468 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
7470 ((LPSOCKADDR_IN)lpAddress)->sin_family = WS_AF_INET;
7472 ptrPort = strchr(workBuffer, ':');
7473 if(ptrPort)
7475 /* User may have entered an IPv6 and asked to parse as IPv4 */
7476 if(strchr(ptrPort + 1, ':'))
7478 res = WSAEINVAL;
7479 break;
7481 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
7482 *ptrPort = '\0';
7484 else
7486 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
7489 if(inet_aton(workBuffer, &inetaddr) > 0)
7491 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
7492 res = 0;
7494 else
7495 res = WSAEINVAL;
7497 break;
7500 case WS_AF_INET6:
7502 struct in6_addr inetaddr;
7503 /* If lpAddressLength is too small, tell caller the size we need */
7504 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
7506 *lpAddressLength = sizeof(SOCKADDR_IN6);
7507 res = WSAEFAULT;
7508 break;
7510 #ifdef HAVE_INET_PTON
7511 *lpAddressLength = sizeof(SOCKADDR_IN6);
7512 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
7514 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
7516 /* This one is a bit tricky. An IPv6 address contains colons, so the
7517 * check from IPv4 doesn't work like that. However, IPv6 addresses that
7518 * contain a port are written with braces like [fd12:3456:7890::1]:12345
7519 * so what we will do is to look for ']', check if the next char is a
7520 * colon, and if it is, parse the port as in IPv4. */
7522 ptrPort = strchr(workBuffer, ']');
7523 if(ptrPort && *(++ptrPort) == ':')
7525 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort+1));
7526 *ptrPort = '\0';
7528 else
7530 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
7533 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
7535 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
7536 sizeof(struct in6_addr));
7537 res = 0;
7539 else
7540 #endif /* HAVE_INET_PTON */
7541 res = WSAEINVAL;
7543 break;
7545 default:
7546 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
7547 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
7548 res = WSAEINVAL;
7551 HeapFree(GetProcessHeap(), 0, workBuffer);
7553 if (!res) return 0;
7554 SetLastError(res);
7555 return SOCKET_ERROR;
7558 /***********************************************************************
7559 * WSAStringToAddressW (WS2_32.81)
7561 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
7562 * If this should be the case, it would be required to map these digits
7563 * to Unicode digits (0-9) using FoldString first.
7565 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
7566 INT AddressFamily,
7567 LPWSAPROTOCOL_INFOW lpProtocolInfo,
7568 LPSOCKADDR lpAddress,
7569 LPINT lpAddressLength)
7571 INT sBuffer,res=0;
7572 LPSTR workBuffer=NULL;
7573 WSAPROTOCOL_INFOA infoA;
7574 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
7576 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
7577 lpAddress, lpAddressLength );
7579 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
7581 /* if ProtocolInfo is available - convert to ANSI variant */
7582 if (lpProtocolInfo)
7584 lpProtoInfoA = &infoA;
7585 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
7587 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
7588 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
7590 SetLastError(WSAEINVAL);
7591 return SOCKET_ERROR;
7595 if (AddressString)
7597 /* Translate AddressString to ANSI code page - assumes that only
7598 standard digits 0-9 are used with this API call */
7599 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
7600 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
7602 if (workBuffer)
7604 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
7605 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
7606 lpAddress,lpAddressLength);
7607 HeapFree( GetProcessHeap(), 0, workBuffer );
7608 return res;
7610 else
7611 res = WSA_NOT_ENOUGH_MEMORY;
7613 else
7614 res = WSAEINVAL;
7616 SetLastError(res);
7617 return SOCKET_ERROR;
7620 /***********************************************************************
7621 * WSAAddressToStringA (WS2_32.27)
7623 * See WSAAddressToStringW
7625 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
7626 LPWSAPROTOCOL_INFOA info, LPSTR string,
7627 LPDWORD lenstr )
7629 DWORD size;
7630 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
7631 CHAR *p;
7633 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
7635 if (!sockaddr) return SOCKET_ERROR;
7636 if (!string || !lenstr) return SOCKET_ERROR;
7638 switch(sockaddr->sa_family)
7640 case WS_AF_INET:
7641 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
7642 sprintf( buffer, "%u.%u.%u.%u:%u",
7643 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
7644 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
7645 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
7646 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
7647 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
7649 p = strchr( buffer, ':' );
7650 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
7651 break;
7653 case WS_AF_INET6:
7655 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
7657 buffer[0] = 0;
7658 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
7659 if ((sockaddr6->sin6_port))
7660 strcpy(buffer, "[");
7661 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, buffer+strlen(buffer), sizeof(buffer)))
7663 SetLastError(WSAEINVAL);
7664 return SOCKET_ERROR;
7666 if ((sockaddr6->sin6_scope_id))
7667 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
7668 if ((sockaddr6->sin6_port))
7669 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
7670 break;
7673 default:
7674 SetLastError(WSAEINVAL);
7675 return SOCKET_ERROR;
7678 size = strlen( buffer ) + 1;
7680 if (*lenstr < size)
7682 *lenstr = size;
7683 SetLastError(WSAEFAULT);
7684 return SOCKET_ERROR;
7687 TRACE("=> %s,%u bytes\n", debugstr_a(buffer), size);
7688 *lenstr = size;
7689 strcpy( string, buffer );
7690 return 0;
7693 /***********************************************************************
7694 * WSAAddressToStringW (WS2_32.28)
7696 * Convert a sockaddr address into a readable address string.
7698 * PARAMS
7699 * sockaddr [I] Pointer to a sockaddr structure.
7700 * len [I] Size of the sockaddr structure.
7701 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
7702 * string [I/O] Pointer to a buffer to receive the address string.
7703 * lenstr [I/O] Size of the receive buffer in WCHARs.
7705 * RETURNS
7706 * Success: 0
7707 * Failure: SOCKET_ERROR
7709 * NOTES
7710 * The 'info' parameter is ignored.
7712 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
7713 LPWSAPROTOCOL_INFOW info, LPWSTR string,
7714 LPDWORD lenstr )
7716 INT ret;
7717 DWORD size;
7718 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
7719 CHAR bufAddr[54];
7721 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
7723 size = *lenstr;
7724 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
7726 if (ret) return ret;
7728 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
7730 if (*lenstr < size)
7732 *lenstr = size;
7733 SetLastError(WSAEFAULT);
7734 return SOCKET_ERROR;
7737 TRACE("=> %s,%u bytes\n", debugstr_w(buffer), size);
7738 *lenstr = size;
7739 lstrcpyW( string, buffer );
7740 return 0;
7743 /***********************************************************************
7744 * WSAEnumNameSpaceProvidersA (WS2_32.34)
7746 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
7748 FIXME( "(%p %p) Stub!\n", len, buffer );
7749 return 0;
7752 /***********************************************************************
7753 * WSAEnumNameSpaceProvidersW (WS2_32.35)
7755 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
7757 FIXME( "(%p %p) Stub!\n", len, buffer );
7758 return 0;
7761 /***********************************************************************
7762 * WSAGetQOSByName (WS2_32.41)
7764 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
7766 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
7767 return FALSE;
7770 /***********************************************************************
7771 * WSAGetServiceClassInfoA (WS2_32.42)
7773 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
7774 LPWSASERVICECLASSINFOA info )
7776 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
7777 len, info );
7778 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7779 return SOCKET_ERROR;
7782 /***********************************************************************
7783 * WSAGetServiceClassInfoW (WS2_32.43)
7785 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
7786 LPWSASERVICECLASSINFOW info )
7788 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
7789 len, info );
7790 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7791 return SOCKET_ERROR;
7794 /***********************************************************************
7795 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
7797 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
7799 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
7800 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7801 return SOCKET_ERROR;
7804 /***********************************************************************
7805 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
7807 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
7809 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
7810 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7811 return SOCKET_ERROR;
7814 /***********************************************************************
7815 * WSALookupServiceBeginA (WS2_32.59)
7817 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
7818 DWORD dwControlFlags,
7819 LPHANDLE lphLookup)
7821 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
7822 lphLookup);
7823 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7824 return SOCKET_ERROR;
7827 /***********************************************************************
7828 * WSALookupServiceBeginW (WS2_32.60)
7830 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
7831 DWORD dwControlFlags,
7832 LPHANDLE lphLookup)
7834 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
7835 lphLookup);
7836 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7837 return SOCKET_ERROR;
7840 /***********************************************************************
7841 * WSALookupServiceEnd (WS2_32.61)
7843 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
7845 FIXME("(%p) Stub!\n", lookup );
7846 return 0;
7849 /***********************************************************************
7850 * WSALookupServiceNextA (WS2_32.62)
7852 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
7854 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
7855 SetLastError(WSA_E_NO_MORE);
7856 return SOCKET_ERROR;
7859 /***********************************************************************
7860 * WSALookupServiceNextW (WS2_32.63)
7862 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
7864 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
7865 SetLastError(WSA_E_NO_MORE);
7866 return SOCKET_ERROR;
7869 /***********************************************************************
7870 * WSANtohl (WS2_32.64)
7872 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
7874 TRACE( "(%04lx 0x%08x %p)\n", s, netlong, lphostlong );
7876 if (!lphostlong) return WSAEFAULT;
7878 *lphostlong = ntohl( netlong );
7879 return 0;
7882 /***********************************************************************
7883 * WSANtohs (WS2_32.65)
7885 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
7887 TRACE( "(%04lx 0x%08x %p)\n", s, netshort, lphostshort );
7889 if (!lphostshort) return WSAEFAULT;
7891 *lphostshort = ntohs( netshort );
7892 return 0;
7895 /***********************************************************************
7896 * WSAProviderConfigChange (WS2_32.66)
7898 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
7899 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
7901 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
7902 return SOCKET_ERROR;
7905 /***********************************************************************
7906 * WSARecvDisconnect (WS2_32.68)
7908 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
7910 TRACE( "(%04lx %p)\n", s, disconnectdata );
7912 return WS_shutdown( s, SD_RECEIVE );
7915 /***********************************************************************
7916 * WSASetServiceA (WS2_32.76)
7918 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
7920 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
7921 return 0;
7924 /***********************************************************************
7925 * WSASetServiceW (WS2_32.77)
7927 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
7929 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
7930 return 0;
7933 /***********************************************************************
7934 * WSCEnableNSProvider (WS2_32.84)
7936 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
7938 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
7939 return 0;
7942 /***********************************************************************
7943 * WSCGetProviderPath (WS2_32.86)
7945 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
7947 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
7949 if (!errcode || !provider || !len) return WSAEFAULT;
7951 *errcode = WSAEINVAL;
7952 return SOCKET_ERROR;
7955 /***********************************************************************
7956 * WSCInstallNameSpace (WS2_32.87)
7958 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
7959 DWORD version, LPGUID provider )
7961 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
7962 namespace, version, debugstr_guid(provider) );
7963 return 0;
7966 /***********************************************************************
7967 * WSCUnInstallNameSpace (WS2_32.89)
7969 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
7971 FIXME("(%p) Stub!\n", lpProviderId);
7972 return NO_ERROR;
7975 /***********************************************************************
7976 * WSCWriteProviderOrder (WS2_32.91)
7978 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
7980 FIXME("(%p 0x%08x) Stub!\n", entry, number);
7981 return 0;
7984 /***********************************************************************
7985 * WSANSPIoctl (WS2_32.91)
7987 INT WINAPI WSANSPIoctl( HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer,
7988 DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer,
7989 LPDWORD lpcbBytesReturned, LPWSACOMPLETION lpCompletion )
7991 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup, dwControlCode,
7992 lpvInBuffer, cbInBuffer, lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpCompletion);
7993 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7994 return SOCKET_ERROR;
7997 /*****************************************************************************
7998 * WSAEnumProtocolsA [WS2_32.@]
8000 * see function WSAEnumProtocolsW
8002 INT WINAPI WSAEnumProtocolsA( LPINT protocols, LPWSAPROTOCOL_INFOA buffer, LPDWORD len )
8004 return WS_EnumProtocols( FALSE, protocols, (LPWSAPROTOCOL_INFOW) buffer, len);
8007 /*****************************************************************************
8008 * WSAEnumProtocolsW [WS2_32.@]
8010 * Retrieves information about specified set of active network protocols.
8012 * PARAMS
8013 * protocols [I] Pointer to null-terminated array of protocol id's. NULL
8014 * retrieves information on all available protocols.
8015 * buffer [I] Pointer to a buffer to be filled with WSAPROTOCOL_INFO
8016 * structures.
8017 * len [I/O] Pointer to a variable specifying buffer size. On output
8018 * the variable holds the number of bytes needed when the
8019 * specified size is too small.
8021 * RETURNS
8022 * Success: number of WSAPROTOCOL_INFO structures in buffer.
8023 * Failure: SOCKET_ERROR
8025 * NOTES
8026 * NT4SP5 does not return SPX if protocols == NULL
8028 * BUGS
8029 * - NT4SP5 returns in addition these list of NETBIOS protocols
8030 * (address family 17), each entry two times one for socket type 2 and 5
8032 * iProtocol szProtocol
8033 * 0x80000000 \Device\NwlnkNb
8034 * 0xfffffffa \Device\NetBT_CBENT7
8035 * 0xfffffffb \Device\Nbf_CBENT7
8036 * 0xfffffffc \Device\NetBT_NdisWan5
8037 * 0xfffffffd \Device\NetBT_El9202
8038 * 0xfffffffe \Device\Nbf_El9202
8039 * 0xffffffff \Device\Nbf_NdisWan4
8041 * - there is no check that the operating system supports the returned
8042 * protocols
8044 INT WINAPI WSAEnumProtocolsW( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
8046 return WS_EnumProtocols( TRUE, protocols, buffer, len);
8049 /*****************************************************************************
8050 * WSCEnumProtocols [WS2_32.@]
8052 * PARAMS
8053 * protocols [I] Null-terminated array of iProtocol values.
8054 * buffer [O] Buffer of WSAPROTOCOL_INFOW structures.
8055 * len [I/O] Size of buffer on input/output.
8056 * errno [O] Error code.
8058 * RETURNS
8059 * Success: number of protocols to be reported on.
8060 * Failure: SOCKET_ERROR. error is in errno.
8062 * BUGS
8063 * Doesn't supply info on layered protocols.
8066 INT WINAPI WSCEnumProtocols( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len, LPINT err )
8068 INT ret = WSAEnumProtocolsW( protocols, buffer, len );
8070 if (ret == SOCKET_ERROR) *err = WSAENOBUFS;
8072 return ret;