ws2_32: Use Win32 APIs for interlocked functions.
[wine.git] / dlls / ws2_32 / socket.c
bloba3b6b2647921b5d7c01be9249b23e6c7512c5369
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 #ifdef HAVE_SYS_IPC_H
37 # include <sys/ipc.h>
38 #endif
39 #ifdef HAVE_SYS_IOCTL_H
40 # include <sys/ioctl.h>
41 #endif
42 #ifdef HAVE_SYS_FILIO_H
43 # include <sys/filio.h>
44 #endif
45 #ifdef HAVE_SYS_SOCKIO_H
46 # include <sys/sockio.h>
47 #endif
49 #if defined(__EMX__)
50 # include <sys/so_ioctl.h>
51 #endif
53 #ifdef HAVE_SYS_PARAM_H
54 # include <sys/param.h>
55 #endif
57 #ifdef HAVE_SYS_MSG_H
58 # include <sys/msg.h>
59 #endif
60 #ifdef HAVE_SYS_WAIT_H
61 # include <sys/wait.h>
62 #endif
63 #ifdef HAVE_SYS_UIO_H
64 # include <sys/uio.h>
65 #endif
66 #ifdef HAVE_SYS_SOCKET_H
67 #include <sys/socket.h>
68 #endif
69 #ifdef HAVE_NETINET_IN_H
70 # include <netinet/in.h>
71 #endif
72 #ifdef HAVE_NETINET_TCP_H
73 # include <netinet/tcp.h>
74 #endif
75 #ifdef HAVE_ARPA_INET_H
76 # include <arpa/inet.h>
77 #endif
78 #include <ctype.h>
79 #include <fcntl.h>
80 #include <errno.h>
81 #ifdef HAVE_NETDB_H
82 #include <netdb.h>
83 #endif
84 #ifdef HAVE_UNISTD_H
85 # include <unistd.h>
86 #endif
87 #include <stdlib.h>
88 #ifdef HAVE_ARPA_NAMESER_H
89 # include <arpa/nameser.h>
90 #endif
91 #ifdef HAVE_RESOLV_H
92 # include <resolv.h>
93 #endif
94 #ifdef HAVE_NET_IF_H
95 # include <net/if.h>
96 #endif
97 #ifdef HAVE_LINUX_FILTER_H
98 # include <linux/filter.h>
99 #endif
101 #ifdef HAVE_NETIPX_IPX_H
102 # include <netipx/ipx.h>
103 #elif defined(HAVE_LINUX_IPX_H)
104 # ifdef HAVE_ASM_TYPES_H
105 # include <asm/types.h>
106 # endif
107 # ifdef HAVE_LINUX_TYPES_H
108 # include <linux/types.h>
109 # endif
110 # include <linux/ipx.h>
111 #endif
112 #if defined(SOL_IPX) || defined(SO_DEFAULT_HEADERS)
113 # define HAS_IPX
114 #endif
116 #ifdef HAVE_LINUX_IRDA_H
117 # ifdef HAVE_LINUX_TYPES_H
118 # include <linux/types.h>
119 # endif
120 # include <linux/irda.h>
121 # define HAS_IRDA
122 #endif
124 #ifdef HAVE_POLL_H
125 #include <poll.h>
126 #endif
127 #ifdef HAVE_SYS_POLL_H
128 # include <sys/poll.h>
129 #endif
130 #ifdef HAVE_SYS_TIME_H
131 # include <sys/time.h>
132 #endif
134 #define NONAMELESSUNION
135 #define NONAMELESSSTRUCT
136 #include "ntstatus.h"
137 #define WIN32_NO_STATUS
138 #include "windef.h"
139 #include "winbase.h"
140 #include "wingdi.h"
141 #include "winuser.h"
142 #include "winerror.h"
143 #include "winnls.h"
144 #include "winsock2.h"
145 #include "mswsock.h"
146 #include "ws2tcpip.h"
147 #include "ws2spi.h"
148 #include "wsipx.h"
149 #include "wshisotp.h"
150 #include "mstcpip.h"
151 #include "af_irda.h"
152 #include "winnt.h"
153 #define USE_WC_PREFIX /* For CMSG_DATA */
154 #include "iphlpapi.h"
155 #include "wine/server.h"
156 #include "wine/debug.h"
157 #include "wine/exception.h"
158 #include "wine/unicode.h"
160 #ifdef HAS_IPX
161 # include "wsnwlink.h"
162 #endif
164 #if defined(linux) && !defined(IP_UNICAST_IF)
165 #define IP_UNICAST_IF 50
166 #endif
168 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
169 # define sipx_network sipx_addr.x_net
170 # define sipx_node sipx_addr.x_host.c_host
171 #endif /* __FreeBSD__ */
173 #ifndef INADDR_NONE
174 #define INADDR_NONE ~0UL
175 #endif
177 WINE_DEFAULT_DEBUG_CHANNEL(winsock);
178 WINE_DECLARE_DEBUG_CHANNEL(winediag);
180 /* names of the protocols */
181 static const WCHAR NameIpxW[] = {'I', 'P', 'X', '\0'};
182 static const WCHAR NameSpxW[] = {'S', 'P', 'X', '\0'};
183 static const WCHAR NameSpxIIW[] = {'S', 'P', 'X', ' ', 'I', 'I', '\0'};
184 static const WCHAR NameTcpW[] = {'T', 'C', 'P', '/', 'I', 'P', '\0'};
185 static const WCHAR NameUdpW[] = {'U', 'D', 'P', '/', 'I', 'P', '\0'};
187 /* Taken from Win2k */
188 static const GUID ProviderIdIP = { 0xe70f1aa0, 0xab8b, 0x11cf,
189 { 0x8c, 0xa3, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
190 static const GUID ProviderIdIPX = { 0x11058240, 0xbe47, 0x11cf,
191 { 0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
192 static const GUID ProviderIdSPX = { 0x11058241, 0xbe47, 0x11cf,
193 { 0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
195 static const INT valid_protocols[] =
197 WS_IPPROTO_TCP,
198 WS_IPPROTO_UDP,
199 WS_NSPROTO_IPX,
200 WS_NSPROTO_SPX,
201 WS_NSPROTO_SPXII,
205 #define IS_IPX_PROTO(X) ((X) >= WS_NSPROTO_IPX && (X) <= WS_NSPROTO_IPX + 255)
207 #if defined(IP_UNICAST_IF) && defined(SO_ATTACH_FILTER)
208 # define LINUX_BOUND_IF
209 struct interface_filter {
210 struct sock_filter iface_memaddr;
211 struct sock_filter iface_rule;
212 struct sock_filter ip_memaddr;
213 struct sock_filter ip_rule;
214 struct sock_filter return_keep;
215 struct sock_filter return_dump;
217 # define FILTER_JUMP_DUMP(here) (u_char)(offsetof(struct interface_filter, return_dump) \
218 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
219 /sizeof(struct sock_filter)
220 # define FILTER_JUMP_KEEP(here) (u_char)(offsetof(struct interface_filter, return_keep) \
221 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
222 /sizeof(struct sock_filter)
223 # define FILTER_JUMP_NEXT() (u_char)(0)
224 # define SKF_NET_DESTIP 16 /* offset in the network header to the destination IP */
225 static struct interface_filter generic_interface_filter = {
226 /* This filter rule allows incoming packets on the specified interface, which works for all
227 * remotely generated packets and for locally generated broadcast packets. */
228 BPF_STMT(BPF_LD+BPF_W+BPF_ABS, SKF_AD_OFF+SKF_AD_IFINDEX),
229 BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0xdeadbeef, FILTER_JUMP_KEEP(iface_rule), FILTER_JUMP_NEXT()),
230 /* This rule allows locally generated packets targeted at the specific IP address of the chosen
231 * adapter (local packets not destined for the broadcast address do not have IFINDEX set) */
232 BPF_STMT(BPF_LD+BPF_W+BPF_ABS, SKF_NET_OFF+SKF_NET_DESTIP),
233 BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0xdeadbeef, FILTER_JUMP_KEEP(ip_rule), FILTER_JUMP_DUMP(ip_rule)),
234 BPF_STMT(BPF_RET+BPF_K, (u_int)-1), /* keep packet */
235 BPF_STMT(BPF_RET+BPF_K, 0) /* dump packet */
237 #endif /* LINUX_BOUND_IF */
240 * The actual definition of WSASendTo, wrapped in a different function name
241 * so that internal calls from ws2_32 itself will not trigger programs like
242 * Garena, which hooks WSASendTo/WSARecvFrom calls.
244 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
245 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
246 const struct WS_sockaddr *to, int tolen,
247 LPWSAOVERLAPPED lpOverlapped,
248 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine );
251 * Internal fundamental receive function, essentially WSARecvFrom with an
252 * additional parameter to support message control headers.
254 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
255 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
256 struct WS_sockaddr *lpFrom,
257 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
258 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
259 LPWSABUF lpControlBuffer );
261 /* critical section to protect some non-reentrant net function */
262 static CRITICAL_SECTION csWSgetXXXbyYYY;
263 static CRITICAL_SECTION_DEBUG critsect_debug =
265 0, 0, &csWSgetXXXbyYYY,
266 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
267 0, 0, { (DWORD_PTR)(__FILE__ ": csWSgetXXXbyYYY") }
269 static CRITICAL_SECTION csWSgetXXXbyYYY = { &critsect_debug, -1, 0, 0, 0, 0 };
271 union generic_unix_sockaddr
273 struct sockaddr addr;
274 char data[128]; /* should be big enough for all families */
277 static inline const char *debugstr_sockaddr( const struct WS_sockaddr *a )
279 if (!a) return "(nil)";
280 switch (a->sa_family)
282 case WS_AF_INET:
283 return wine_dbg_sprintf("{ family AF_INET, address %s, port %d }",
284 inet_ntoa(((const struct sockaddr_in *)a)->sin_addr),
285 ntohs(((const struct sockaddr_in *)a)->sin_port));
286 case WS_AF_INET6:
288 char buf[46];
289 const char *p;
290 struct WS_sockaddr_in6 *sin = (struct WS_sockaddr_in6 *)a;
292 p = WS_inet_ntop( WS_AF_INET6, &sin->sin6_addr, buf, sizeof(buf) );
293 if (!p)
294 p = "(unknown IPv6 address)";
295 return wine_dbg_sprintf("{ family AF_INET6, address %s, port %d }",
296 p, ntohs(sin->sin6_port));
298 case WS_AF_IPX:
300 int i;
301 char netnum[16], nodenum[16];
302 struct WS_sockaddr_ipx *sin = (struct WS_sockaddr_ipx *)a;
304 for (i = 0;i < 4; i++) sprintf(netnum + i * 2, "%02X", (unsigned char) sin->sa_netnum[i]);
305 for (i = 0;i < 6; i++) sprintf(nodenum + i * 2, "%02X", (unsigned char) sin->sa_nodenum[i]);
307 return wine_dbg_sprintf("{ family AF_IPX, address %s.%s, ipx socket %d }",
308 netnum, nodenum, sin->sa_socket);
310 case WS_AF_IRDA:
312 DWORD addr;
314 memcpy( &addr, ((const SOCKADDR_IRDA *)a)->irdaDeviceID, sizeof(addr) );
315 addr = ntohl( addr );
316 return wine_dbg_sprintf("{ family AF_IRDA, addr %08x, name %s }",
317 addr,
318 ((const SOCKADDR_IRDA *)a)->irdaServiceName);
320 default:
321 return wine_dbg_sprintf("{ family %d }", a->sa_family);
325 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
326 #define SOCKET2HANDLE(s) ((HANDLE)(s))
327 #define HANDLE2SOCKET(h) ((SOCKET)(h))
329 /****************************************************************
330 * Async IO declarations
331 ****************************************************************/
333 struct ws2_async_io
335 struct ws2_async_io *next;
338 struct ws2_async_shutdown
340 struct ws2_async_io io;
341 HANDLE hSocket;
342 IO_STATUS_BLOCK iosb;
343 int type;
346 struct ws2_async
348 struct ws2_async_io io;
349 HANDLE hSocket;
350 LPWSAOVERLAPPED user_overlapped;
351 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
352 IO_STATUS_BLOCK local_iosb;
353 struct WS_sockaddr *addr;
354 union
356 int val; /* for send operations */
357 int *ptr; /* for recv operations */
358 } addrlen;
359 DWORD flags;
360 DWORD *lpFlags;
361 WSABUF *control;
362 unsigned int n_iovecs;
363 unsigned int first_iovec;
364 struct iovec iovec[1];
367 struct ws2_accept_async
369 struct ws2_async_io io;
370 HANDLE listen_socket;
371 HANDLE accept_socket;
372 LPOVERLAPPED user_overlapped;
373 ULONG_PTR cvalue;
374 PVOID buf; /* buffer to write data to */
375 int data_len;
376 int local_len;
377 int remote_len;
378 struct ws2_async *read;
381 static struct ws2_async_io *async_io_freelist;
383 static void release_async_io( struct ws2_async_io *io )
385 for (;;)
387 struct ws2_async_io *next = async_io_freelist;
388 io->next = next;
389 if (InterlockedCompareExchangePointer( (void **)&async_io_freelist, io, next ) == next) return;
393 static struct ws2_async_io *alloc_async_io( DWORD size )
395 /* first free remaining previous fileinfos */
397 struct ws2_async_io *io = InterlockedExchangePointer( (void **)&async_io_freelist, NULL );
399 while (io)
401 struct ws2_async_io *next = io->next;
402 HeapFree( GetProcessHeap(), 0, io );
403 io = next;
406 return HeapAlloc( GetProcessHeap(), 0, size );
409 /****************************************************************/
411 /* ----------------------------------- internal data */
413 /* ws_... struct conversion flags */
415 typedef struct /* WSAAsyncSelect() control struct */
417 HANDLE service, event, sock;
418 HWND hWnd;
419 UINT uMsg;
420 LONG lEvent;
421 } ws_select_info;
423 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
424 #define WS_MAX_UDP_DATAGRAM 1024
425 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
427 /* hostent's, servent's and protent's are stored in one buffer per thread,
428 * as documented on MSDN for the functions that return any of the buffers */
429 struct per_thread_data
431 int opentype;
432 struct WS_hostent *he_buffer;
433 struct WS_servent *se_buffer;
434 struct WS_protoent *pe_buffer;
435 int he_len;
436 int se_len;
437 int pe_len;
438 char ntoa_buffer[16]; /* 4*3 digits + 3 '.' + 1 '\0' */
441 /* internal: routing description information */
442 struct route {
443 struct in_addr addr;
444 IF_INDEX interface;
445 DWORD metric;
448 static INT num_startup; /* reference counter */
449 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
451 /* function prototypes */
452 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length);
453 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
454 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
455 static struct WS_servent *WS_dup_se(const struct servent* p_se);
456 static int ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size);
458 int WSAIOCTL_GetInterfaceCount(void);
459 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
461 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus, ULONG Information );
463 #define MAP_OPTION(opt) { WS_##opt, opt }
465 static const int ws_sock_map[][2] =
467 MAP_OPTION( SO_DEBUG ),
468 MAP_OPTION( SO_ACCEPTCONN ),
469 MAP_OPTION( SO_REUSEADDR ),
470 MAP_OPTION( SO_KEEPALIVE ),
471 MAP_OPTION( SO_DONTROUTE ),
472 MAP_OPTION( SO_BROADCAST ),
473 MAP_OPTION( SO_LINGER ),
474 MAP_OPTION( SO_OOBINLINE ),
475 MAP_OPTION( SO_SNDBUF ),
476 MAP_OPTION( SO_RCVBUF ),
477 MAP_OPTION( SO_ERROR ),
478 MAP_OPTION( SO_TYPE ),
479 #ifdef SO_RCVTIMEO
480 MAP_OPTION( SO_RCVTIMEO ),
481 #endif
482 #ifdef SO_SNDTIMEO
483 MAP_OPTION( SO_SNDTIMEO ),
484 #endif
487 static const int ws_tcp_map[][2] =
489 #ifdef TCP_NODELAY
490 MAP_OPTION( TCP_NODELAY ),
491 #endif
494 static const int ws_ip_map[][2] =
496 MAP_OPTION( IP_MULTICAST_IF ),
497 MAP_OPTION( IP_MULTICAST_TTL ),
498 MAP_OPTION( IP_MULTICAST_LOOP ),
499 MAP_OPTION( IP_ADD_MEMBERSHIP ),
500 MAP_OPTION( IP_DROP_MEMBERSHIP ),
501 MAP_OPTION( IP_OPTIONS ),
502 #ifdef IP_HDRINCL
503 MAP_OPTION( IP_HDRINCL ),
504 #endif
505 MAP_OPTION( IP_TOS ),
506 MAP_OPTION( IP_TTL ),
507 #ifdef IP_PKTINFO
508 MAP_OPTION( IP_PKTINFO ),
509 #endif
510 #ifdef IP_UNICAST_IF
511 MAP_OPTION( IP_UNICAST_IF ),
512 #endif
515 static const int ws_ipv6_map[][2] =
517 #ifdef IPV6_ADD_MEMBERSHIP
518 MAP_OPTION( IPV6_ADD_MEMBERSHIP ),
519 #endif
520 #ifdef IPV6_DROP_MEMBERSHIP
521 MAP_OPTION( IPV6_DROP_MEMBERSHIP ),
522 #endif
523 MAP_OPTION( IPV6_MULTICAST_IF ),
524 MAP_OPTION( IPV6_MULTICAST_HOPS ),
525 MAP_OPTION( IPV6_MULTICAST_LOOP ),
526 MAP_OPTION( IPV6_UNICAST_HOPS ),
527 MAP_OPTION( IPV6_V6ONLY ),
528 #ifdef IPV6_UNICAST_IF
529 MAP_OPTION( IPV6_UNICAST_IF ),
530 #endif
533 static const int ws_af_map[][2] =
535 MAP_OPTION( AF_UNSPEC ),
536 MAP_OPTION( AF_INET ),
537 MAP_OPTION( AF_INET6 ),
538 #ifdef HAS_IPX
539 MAP_OPTION( AF_IPX ),
540 #endif
541 #ifdef AF_IRDA
542 MAP_OPTION( AF_IRDA ),
543 #endif
544 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
547 static const int ws_socktype_map[][2] =
549 MAP_OPTION( SOCK_DGRAM ),
550 MAP_OPTION( SOCK_STREAM ),
551 MAP_OPTION( SOCK_RAW ),
552 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
555 static const int ws_proto_map[][2] =
557 MAP_OPTION( IPPROTO_IP ),
558 MAP_OPTION( IPPROTO_TCP ),
559 MAP_OPTION( IPPROTO_UDP ),
560 MAP_OPTION( IPPROTO_ICMP ),
561 MAP_OPTION( IPPROTO_IGMP ),
562 MAP_OPTION( IPPROTO_RAW ),
563 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
566 static const int ws_aiflag_map[][2] =
568 MAP_OPTION( AI_PASSIVE ),
569 MAP_OPTION( AI_CANONNAME ),
570 MAP_OPTION( AI_NUMERICHOST ),
571 #ifdef AI_NUMERICSERV
572 MAP_OPTION( AI_NUMERICSERV ),
573 #endif
574 #ifdef AI_V4MAPPED
575 MAP_OPTION( AI_V4MAPPED ),
576 #endif
577 MAP_OPTION( AI_ADDRCONFIG ),
580 static const int ws_niflag_map[][2] =
582 MAP_OPTION( NI_NOFQDN ),
583 MAP_OPTION( NI_NUMERICHOST ),
584 MAP_OPTION( NI_NAMEREQD ),
585 MAP_OPTION( NI_NUMERICSERV ),
586 MAP_OPTION( NI_DGRAM ),
589 static const int ws_eai_map[][2] =
591 MAP_OPTION( EAI_AGAIN ),
592 MAP_OPTION( EAI_BADFLAGS ),
593 MAP_OPTION( EAI_FAIL ),
594 MAP_OPTION( EAI_FAMILY ),
595 MAP_OPTION( EAI_MEMORY ),
596 /* Note: EAI_NODATA is deprecated, but still
597 * used by Windows and Linux... We map the newer
598 * EAI_NONAME to EAI_NODATA for now until Windows
599 * changes too.
601 #ifdef EAI_NODATA
602 MAP_OPTION( EAI_NODATA ),
603 #endif
604 #ifdef EAI_NONAME
605 { WS_EAI_NODATA, EAI_NONAME },
606 #endif
608 MAP_OPTION( EAI_SERVICE ),
609 MAP_OPTION( EAI_SOCKTYPE ),
610 { 0, 0 }
613 static const char magic_loopback_addr[] = {127, 12, 34, 56};
615 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
616 #ifdef IP_PKTINFO
617 static inline WSACMSGHDR *fill_control_message(int level, int type, WSACMSGHDR *current, ULONG *maxsize, void *data, int len)
619 ULONG msgsize = sizeof(WSACMSGHDR) + WSA_CMSG_ALIGN(len);
620 char *ptr = (char *) current + sizeof(WSACMSGHDR);
622 /* Make sure there is at least enough room for this entry */
623 if (msgsize > *maxsize)
624 return NULL;
625 *maxsize -= msgsize;
626 /* Fill in the entry */
627 current->cmsg_len = sizeof(WSACMSGHDR) + len;
628 current->cmsg_level = level;
629 current->cmsg_type = type;
630 memcpy(ptr, data, len);
631 /* Return the pointer to where next entry should go */
632 return (WSACMSGHDR *) (ptr + WSA_CMSG_ALIGN(len));
634 #endif /* IP_PKTINFO */
636 static inline int convert_control_headers(struct msghdr *hdr, WSABUF *control)
638 #ifdef IP_PKTINFO
639 WSACMSGHDR *cmsg_win = (WSACMSGHDR *) control->buf, *ptr;
640 ULONG ctlsize = control->len;
641 struct cmsghdr *cmsg_unix;
643 ptr = cmsg_win;
644 /* Loop over all the headers, converting as appropriate */
645 for (cmsg_unix = CMSG_FIRSTHDR(hdr); cmsg_unix != NULL; cmsg_unix = CMSG_NXTHDR(hdr, cmsg_unix))
647 switch(cmsg_unix->cmsg_level)
649 case IPPROTO_IP:
650 switch(cmsg_unix->cmsg_type)
652 case IP_PKTINFO:
654 /* Convert the Unix IP_PKTINFO structure to the Windows version */
655 struct in_pktinfo *data_unix = (struct in_pktinfo *) CMSG_DATA(cmsg_unix);
656 struct WS_in_pktinfo data_win;
658 memcpy(&data_win.ipi_addr,&data_unix->ipi_addr.s_addr,4); /* 4 bytes = 32 address bits */
659 data_win.ipi_ifindex = data_unix->ipi_ifindex;
660 ptr = fill_control_message(WS_IPPROTO_IP, WS_IP_PKTINFO, ptr, &ctlsize,
661 (void*)&data_win, sizeof(data_win));
662 if (!ptr) goto error;
663 } break;
664 default:
665 FIXME("Unhandled IPPROTO_IP message header type %d\n", cmsg_unix->cmsg_type);
666 break;
668 break;
669 default:
670 FIXME("Unhandled message header level %d\n", cmsg_unix->cmsg_level);
671 break;
675 error:
676 /* Set the length of the returned control headers */
677 control->len = (ptr == NULL ? 0 : (char*)ptr - (char*)cmsg_win);
678 return (ptr != NULL);
679 #else /* IP_PKTINFO */
680 control->len = 0;
681 return 1;
682 #endif /* IP_PKTINFO */
684 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
686 /* ----------------------------------- error handling */
688 static NTSTATUS sock_get_ntstatus( int err )
690 switch ( err )
692 case EBADF: return STATUS_INVALID_HANDLE;
693 case EBUSY: return STATUS_DEVICE_BUSY;
694 case EPERM:
695 case EACCES: return STATUS_ACCESS_DENIED;
696 case EFAULT: return STATUS_NO_MEMORY;
697 case EINVAL: return STATUS_INVALID_PARAMETER;
698 case ENFILE:
699 case EMFILE: return STATUS_TOO_MANY_OPENED_FILES;
700 case EWOULDBLOCK: return STATUS_CANT_WAIT;
701 case EINPROGRESS: return STATUS_PENDING;
702 case EALREADY: return STATUS_NETWORK_BUSY;
703 case ENOTSOCK: return STATUS_OBJECT_TYPE_MISMATCH;
704 case EDESTADDRREQ: return STATUS_INVALID_PARAMETER;
705 case EMSGSIZE: return STATUS_BUFFER_OVERFLOW;
706 case EPROTONOSUPPORT:
707 case ESOCKTNOSUPPORT:
708 case EPFNOSUPPORT:
709 case EAFNOSUPPORT:
710 case EPROTOTYPE: return STATUS_NOT_SUPPORTED;
711 case ENOPROTOOPT: return STATUS_INVALID_PARAMETER;
712 case EOPNOTSUPP: return STATUS_NOT_SUPPORTED;
713 case EADDRINUSE: return STATUS_ADDRESS_ALREADY_ASSOCIATED;
714 case EADDRNOTAVAIL: return STATUS_INVALID_PARAMETER;
715 case ECONNREFUSED: return STATUS_CONNECTION_REFUSED;
716 case ESHUTDOWN: return STATUS_PIPE_DISCONNECTED;
717 case ENOTCONN: return STATUS_CONNECTION_DISCONNECTED;
718 case ETIMEDOUT: return STATUS_IO_TIMEOUT;
719 case ENETUNREACH: return STATUS_NETWORK_UNREACHABLE;
720 case ENETDOWN: return STATUS_NETWORK_BUSY;
721 case EPIPE:
722 case ECONNRESET: return STATUS_CONNECTION_RESET;
723 case ECONNABORTED: return STATUS_CONNECTION_ABORTED;
725 case 0: return STATUS_SUCCESS;
726 default:
727 WARN("Unknown errno %d!\n", err);
728 return STATUS_UNSUCCESSFUL;
732 static UINT sock_get_error( int err )
734 switch(err)
736 case EINTR: return WSAEINTR;
737 case EBADF: return WSAEBADF;
738 case EPERM:
739 case EACCES: return WSAEACCES;
740 case EFAULT: return WSAEFAULT;
741 case EINVAL: return WSAEINVAL;
742 case EMFILE: return WSAEMFILE;
743 case EWOULDBLOCK: return WSAEWOULDBLOCK;
744 case EINPROGRESS: return WSAEINPROGRESS;
745 case EALREADY: return WSAEALREADY;
746 case ENOTSOCK: return WSAENOTSOCK;
747 case EDESTADDRREQ: return WSAEDESTADDRREQ;
748 case EMSGSIZE: return WSAEMSGSIZE;
749 case EPROTOTYPE: return WSAEPROTOTYPE;
750 case ENOPROTOOPT: return WSAENOPROTOOPT;
751 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
752 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
753 case EOPNOTSUPP: return WSAEOPNOTSUPP;
754 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
755 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
756 case EADDRINUSE: return WSAEADDRINUSE;
757 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
758 case ENETDOWN: return WSAENETDOWN;
759 case ENETUNREACH: return WSAENETUNREACH;
760 case ENETRESET: return WSAENETRESET;
761 case ECONNABORTED: return WSAECONNABORTED;
762 case EPIPE:
763 case ECONNRESET: return WSAECONNRESET;
764 case ENOBUFS: return WSAENOBUFS;
765 case EISCONN: return WSAEISCONN;
766 case ENOTCONN: return WSAENOTCONN;
767 case ESHUTDOWN: return WSAESHUTDOWN;
768 case ETOOMANYREFS: return WSAETOOMANYREFS;
769 case ETIMEDOUT: return WSAETIMEDOUT;
770 case ECONNREFUSED: return WSAECONNREFUSED;
771 case ELOOP: return WSAELOOP;
772 case ENAMETOOLONG: return WSAENAMETOOLONG;
773 case EHOSTDOWN: return WSAEHOSTDOWN;
774 case EHOSTUNREACH: return WSAEHOSTUNREACH;
775 case ENOTEMPTY: return WSAENOTEMPTY;
776 #ifdef EPROCLIM
777 case EPROCLIM: return WSAEPROCLIM;
778 #endif
779 #ifdef EUSERS
780 case EUSERS: return WSAEUSERS;
781 #endif
782 #ifdef EDQUOT
783 case EDQUOT: return WSAEDQUOT;
784 #endif
785 #ifdef ESTALE
786 case ESTALE: return WSAESTALE;
787 #endif
788 #ifdef EREMOTE
789 case EREMOTE: return WSAEREMOTE;
790 #endif
792 /* just in case we ever get here and there are no problems */
793 case 0: return 0;
794 default:
795 WARN("Unknown errno %d!\n", err);
796 return WSAEOPNOTSUPP;
800 static UINT wsaErrno(void)
802 int loc_errno = errno;
803 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
805 return sock_get_error( loc_errno );
808 /* most ws2 overlapped functions return an ntstatus-based error code */
809 static NTSTATUS wsaErrStatus(void)
811 int loc_errno = errno;
812 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
814 return sock_get_ntstatus(loc_errno);
817 static UINT wsaHerrno(int loc_errno)
819 WARN("h_errno %d.\n", loc_errno);
821 switch(loc_errno)
823 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
824 case TRY_AGAIN: return WSATRY_AGAIN;
825 case NO_RECOVERY: return WSANO_RECOVERY;
826 case NO_DATA: return WSANO_DATA;
827 case ENOBUFS: return WSAENOBUFS;
829 case 0: return 0;
830 default:
831 WARN("Unknown h_errno %d!\n", loc_errno);
832 return WSAEOPNOTSUPP;
836 static inline DWORD NtStatusToWSAError( const DWORD status )
838 /* We only need to cover the status codes set by server async request handling */
839 DWORD wserr;
840 switch ( status )
842 case STATUS_SUCCESS: wserr = 0; break;
843 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
844 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
845 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
846 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
847 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
848 case STATUS_NETWORK_BUSY: wserr = WSAEALREADY; break;
849 case STATUS_NETWORK_UNREACHABLE: wserr = WSAENETUNREACH; break;
850 case STATUS_CONNECTION_REFUSED: wserr = WSAECONNREFUSED; break;
851 case STATUS_CONNECTION_DISCONNECTED: wserr = WSAENOTCONN; break;
852 case STATUS_CONNECTION_RESET: wserr = WSAECONNRESET; break;
853 case STATUS_CONNECTION_ABORTED: wserr = WSAECONNABORTED; break;
854 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
855 case STATUS_ADDRESS_ALREADY_ASSOCIATED: wserr = WSAEADDRINUSE; break;
856 case STATUS_IO_TIMEOUT:
857 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
858 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
859 case STATUS_ACCESS_DENIED: wserr = WSAEACCES; break;
860 case STATUS_TOO_MANY_OPENED_FILES: wserr = WSAEMFILE; break;
861 case STATUS_CANT_WAIT: wserr = WSAEWOULDBLOCK; break;
862 case STATUS_BUFFER_OVERFLOW: wserr = WSAEMSGSIZE; break;
863 case STATUS_NOT_SUPPORTED: wserr = WSAEOPNOTSUPP; break;
864 case STATUS_HOST_UNREACHABLE: wserr = WSAEHOSTUNREACH; break;
866 default:
867 wserr = RtlNtStatusToDosError( status );
868 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
870 return wserr;
873 /* set last error code from NT status without mapping WSA errors */
874 static inline unsigned int set_error( unsigned int err )
876 if (err)
878 err = NtStatusToWSAError( err );
879 SetLastError( err );
881 return err;
884 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
886 int fd;
887 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
888 return -1;
889 return fd;
892 static inline void release_sock_fd( SOCKET s, int fd )
894 wine_server_release_fd( SOCKET2HANDLE(s), fd );
897 static void _enable_event( HANDLE s, unsigned int event,
898 unsigned int sstate, unsigned int cstate )
900 SERVER_START_REQ( enable_socket_event )
902 req->handle = wine_server_obj_handle( s );
903 req->mask = event;
904 req->sstate = sstate;
905 req->cstate = cstate;
906 wine_server_call( req );
908 SERVER_END_REQ;
911 static NTSTATUS _is_blocking(SOCKET s, BOOL *ret)
913 NTSTATUS status;
914 SERVER_START_REQ( get_socket_event )
916 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
917 req->service = FALSE;
918 req->c_event = 0;
919 status = wine_server_call( req );
920 *ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
922 SERVER_END_REQ;
923 return status;
926 static unsigned int _get_sock_mask(SOCKET s)
928 unsigned int ret;
929 SERVER_START_REQ( get_socket_event )
931 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
932 req->service = FALSE;
933 req->c_event = 0;
934 wine_server_call( req );
935 ret = reply->mask;
937 SERVER_END_REQ;
938 return ret;
941 static void _sync_sock_state(SOCKET s)
943 BOOL dummy;
944 /* do a dummy wineserver request in order to let
945 the wineserver run through its select loop once */
946 (void)_is_blocking(s, &dummy);
949 static int _get_sock_error(SOCKET s, unsigned int bit)
951 int events[FD_MAX_EVENTS];
953 SERVER_START_REQ( get_socket_event )
955 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
956 req->service = FALSE;
957 req->c_event = 0;
958 wine_server_set_reply( req, events, sizeof(events) );
959 wine_server_call( req );
961 SERVER_END_REQ;
962 return events[bit];
965 static struct per_thread_data *get_per_thread_data(void)
967 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
968 /* lazy initialization */
969 if (!ptb)
971 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
972 NtCurrentTeb()->WinSockData = ptb;
974 return ptb;
977 static void free_per_thread_data(void)
979 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
981 if (!ptb) return;
983 /* delete scratch buffers */
984 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
985 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
986 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
987 ptb->he_buffer = NULL;
988 ptb->se_buffer = NULL;
989 ptb->pe_buffer = NULL;
991 HeapFree( GetProcessHeap(), 0, ptb );
992 NtCurrentTeb()->WinSockData = NULL;
995 /***********************************************************************
996 * DllMain (WS2_32.init)
998 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
1000 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
1001 switch (fdwReason) {
1002 case DLL_PROCESS_ATTACH:
1003 break;
1004 case DLL_PROCESS_DETACH:
1005 if (fImpLoad) break;
1006 free_per_thread_data();
1007 DeleteCriticalSection(&csWSgetXXXbyYYY);
1008 break;
1009 case DLL_THREAD_DETACH:
1010 free_per_thread_data();
1011 break;
1013 return TRUE;
1016 /***********************************************************************
1017 * convert_sockopt()
1019 * Converts socket flags from Windows format.
1020 * Return 1 if converted, 0 if not (error).
1022 static int convert_sockopt(INT *level, INT *optname)
1024 unsigned int i;
1025 switch (*level)
1027 case WS_SOL_SOCKET:
1028 *level = SOL_SOCKET;
1029 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
1030 if( ws_sock_map[i][0] == *optname )
1032 *optname = ws_sock_map[i][1];
1033 return 1;
1036 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
1037 break;
1038 case WS_IPPROTO_TCP:
1039 *level = IPPROTO_TCP;
1040 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
1041 if ( ws_tcp_map[i][0] == *optname )
1043 *optname = ws_tcp_map[i][1];
1044 return 1;
1047 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
1048 break;
1049 case WS_IPPROTO_IP:
1050 *level = IPPROTO_IP;
1051 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
1052 if (ws_ip_map[i][0] == *optname )
1054 *optname = ws_ip_map[i][1];
1055 return 1;
1058 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
1059 break;
1060 case WS_IPPROTO_IPV6:
1061 *level = IPPROTO_IPV6;
1062 for(i=0; i<sizeof(ws_ipv6_map)/sizeof(ws_ipv6_map[0]); i++) {
1063 if (ws_ipv6_map[i][0] == *optname )
1065 *optname = ws_ipv6_map[i][1];
1066 return 1;
1069 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname);
1070 break;
1071 default: FIXME("Unimplemented or unknown socket level\n");
1073 return 0;
1076 /* ----------------------------------- Per-thread info (or per-process?) */
1078 static char *strdup_lower(const char *str)
1080 int i;
1081 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
1083 if (ret)
1085 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
1086 ret[i] = 0;
1088 else SetLastError(WSAENOBUFS);
1089 return ret;
1092 static inline int sock_error_p(int s)
1094 unsigned int optval;
1095 socklen_t optlen = sizeof(optval);
1096 getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
1097 if (optval) WARN("\t[%i] error: %d\n", s, optval);
1098 return optval != 0;
1101 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
1102 * from an fd and return the value converted to milli seconds
1103 * or -1 if there is an infinite time out */
1104 static inline int get_rcvsnd_timeo( int fd, int optname)
1106 struct timeval tv;
1107 socklen_t len = sizeof(tv);
1108 int ret = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
1109 if( ret >= 0)
1110 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
1111 if( ret <= 0 ) /* tv == {0,0} means infinite time out */
1112 return -1;
1113 return ret;
1116 /* macro wrappers for portability */
1117 #ifdef SO_RCVTIMEO
1118 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
1119 #else
1120 #define GET_RCVTIMEO(fd) (-1)
1121 #endif
1123 #ifdef SO_SNDTIMEO
1124 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
1125 #else
1126 #define GET_SNDTIMEO(fd) (-1)
1127 #endif
1129 /* utility: given an fd, will block until one of the events occurs */
1130 static inline int do_block( int fd, int events, int timeout )
1132 struct pollfd pfd;
1133 int ret;
1135 pfd.fd = fd;
1136 pfd.events = events;
1138 while ((ret = poll(&pfd, 1, timeout)) < 0)
1140 if (errno != EINTR)
1141 return -1;
1143 if( ret == 0 )
1144 return 0;
1145 return pfd.revents;
1148 static int
1149 convert_af_w2u(int windowsaf) {
1150 unsigned int i;
1152 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1153 if (ws_af_map[i][0] == windowsaf)
1154 return ws_af_map[i][1];
1155 FIXME("unhandled Windows address family %d\n", windowsaf);
1156 return -1;
1159 static int
1160 convert_af_u2w(int unixaf) {
1161 unsigned int i;
1163 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1164 if (ws_af_map[i][1] == unixaf)
1165 return ws_af_map[i][0];
1166 FIXME("unhandled UNIX address family %d\n", unixaf);
1167 return -1;
1170 static int
1171 convert_proto_w2u(int windowsproto) {
1172 unsigned int i;
1174 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1175 if (ws_proto_map[i][0] == windowsproto)
1176 return ws_proto_map[i][1];
1178 /* check for extended IPX */
1179 if (IS_IPX_PROTO(windowsproto))
1180 return windowsproto;
1182 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
1183 return -1;
1186 static int
1187 convert_proto_u2w(int unixproto) {
1188 unsigned int i;
1190 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1191 if (ws_proto_map[i][1] == unixproto)
1192 return ws_proto_map[i][0];
1194 /* if value is inside IPX range just return it - the kernel simply
1195 * echoes the value used in the socket() function */
1196 if (IS_IPX_PROTO(unixproto))
1197 return unixproto;
1199 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
1200 return -1;
1203 static int
1204 convert_socktype_w2u(int windowssocktype) {
1205 unsigned int i;
1207 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1208 if (ws_socktype_map[i][0] == windowssocktype)
1209 return ws_socktype_map[i][1];
1210 FIXME("unhandled Windows socket type %d\n", windowssocktype);
1211 return -1;
1214 static int
1215 convert_socktype_u2w(int unixsocktype) {
1216 unsigned int i;
1218 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1219 if (ws_socktype_map[i][1] == unixsocktype)
1220 return ws_socktype_map[i][0];
1221 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
1222 return -1;
1225 static int set_ipx_packettype(int sock, int ptype)
1227 #ifdef HAS_IPX
1228 int fd = get_sock_fd( sock, 0, NULL ), ret = 0;
1229 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", ptype, fd);
1231 if (fd == -1) return SOCKET_ERROR;
1233 /* We try to set the ipx type on ipx socket level. */
1234 #ifdef SOL_IPX
1235 if(setsockopt(fd, SOL_IPX, IPX_TYPE, &ptype, sizeof(ptype)) == -1)
1237 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
1238 ret = SOCKET_ERROR;
1240 #else
1242 struct ipx val;
1243 /* Should we retrieve val using a getsockopt call and then
1244 * set the modified one? */
1245 val.ipx_pt = ptype;
1246 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
1248 #endif
1249 release_sock_fd( sock, fd );
1250 return ret;
1251 #else
1252 WARN("IPX support is not enabled, can't set packet type\n");
1253 return SOCKET_ERROR;
1254 #endif
1257 /* ----------------------------------- API -----
1259 * Init / cleanup / error checking.
1262 /***********************************************************************
1263 * WSAStartup (WS2_32.115)
1265 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
1267 TRACE("verReq=%x\n", wVersionRequested);
1269 if (LOBYTE(wVersionRequested) < 1)
1270 return WSAVERNOTSUPPORTED;
1272 if (!lpWSAData) return WSAEINVAL;
1274 num_startup++;
1276 /* that's the whole of the negotiation for now */
1277 lpWSAData->wVersion = wVersionRequested;
1278 /* return winsock information */
1279 lpWSAData->wHighVersion = 0x0202;
1280 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
1281 strcpy(lpWSAData->szSystemStatus, "Running" );
1282 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
1283 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
1284 /* don't do anything with lpWSAData->lpVendorInfo */
1285 /* (some apps don't allocate the space for this field) */
1287 TRACE("succeeded starts: %d\n", num_startup);
1288 return 0;
1292 /***********************************************************************
1293 * WSACleanup (WS2_32.116)
1295 INT WINAPI WSACleanup(void)
1297 if (num_startup) {
1298 num_startup--;
1299 TRACE("pending cleanups: %d\n", num_startup);
1300 return 0;
1302 SetLastError(WSANOTINITIALISED);
1303 return SOCKET_ERROR;
1307 /***********************************************************************
1308 * WSAGetLastError (WS2_32.111)
1310 INT WINAPI WSAGetLastError(void)
1312 return GetLastError();
1315 /***********************************************************************
1316 * WSASetLastError (WS2_32.112)
1318 void WINAPI WSASetLastError(INT iError) {
1319 SetLastError(iError);
1322 static struct WS_hostent *check_buffer_he(int size)
1324 struct per_thread_data * ptb = get_per_thread_data();
1325 if (ptb->he_buffer)
1327 if (ptb->he_len >= size ) return ptb->he_buffer;
1328 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1330 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
1331 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
1332 return ptb->he_buffer;
1335 static struct WS_servent *check_buffer_se(int size)
1337 struct per_thread_data * ptb = get_per_thread_data();
1338 if (ptb->se_buffer)
1340 if (ptb->se_len >= size ) return ptb->se_buffer;
1341 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1343 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
1344 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
1345 return ptb->se_buffer;
1348 static struct WS_protoent *check_buffer_pe(int size)
1350 struct per_thread_data * ptb = get_per_thread_data();
1351 if (ptb->pe_buffer)
1353 if (ptb->pe_len >= size ) return ptb->pe_buffer;
1354 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1356 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
1357 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
1358 return ptb->pe_buffer;
1361 /* ----------------------------------- i/o APIs */
1363 static inline BOOL supported_pf(int pf)
1365 switch (pf)
1367 case WS_AF_INET:
1368 case WS_AF_INET6:
1369 return TRUE;
1370 #ifdef HAS_IPX
1371 case WS_AF_IPX:
1372 return TRUE;
1373 #endif
1374 #ifdef HAS_IRDA
1375 case WS_AF_IRDA:
1376 return TRUE;
1377 #endif
1378 default:
1379 return FALSE;
1383 static inline BOOL supported_protocol(int protocol)
1385 int i;
1386 for (i = 0; i < sizeof(valid_protocols) / sizeof(valid_protocols[0]); i++)
1387 if (protocol == valid_protocols[i])
1388 return TRUE;
1389 return FALSE;
1392 /**********************************************************************/
1394 /* Returns the length of the converted address if successful, 0 if it was too small to
1395 * start with.
1397 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
1398 union generic_unix_sockaddr *uaddr)
1400 unsigned int uaddrlen = 0;
1402 switch (wsaddr->sa_family)
1404 #ifdef HAS_IPX
1405 case WS_AF_IPX:
1407 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
1408 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
1410 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
1411 return 0;
1413 uaddrlen = sizeof(struct sockaddr_ipx);
1414 memset( uaddr, 0, uaddrlen );
1415 uipx->sipx_family=AF_IPX;
1416 uipx->sipx_port=wsipx->sa_socket;
1417 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1418 * in one go
1420 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
1421 #ifdef IPX_FRAME_NONE
1422 uipx->sipx_type=IPX_FRAME_NONE;
1423 #endif
1424 break;
1426 #endif
1427 case WS_AF_INET6: {
1428 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
1429 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
1431 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1432 * scope_id, one without.
1434 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
1435 uaddrlen = sizeof(struct sockaddr_in6);
1436 memset( uaddr, 0, uaddrlen );
1437 uin6->sin6_family = AF_INET6;
1438 uin6->sin6_port = win6->sin6_port;
1439 uin6->sin6_flowinfo = win6->sin6_flowinfo;
1440 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1441 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
1442 #endif
1443 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
1444 break;
1446 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
1447 return 0;
1449 case WS_AF_INET: {
1450 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
1451 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
1453 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
1454 return 0;
1455 uaddrlen = sizeof(struct sockaddr_in);
1456 memset( uaddr, 0, uaddrlen );
1457 uin->sin_family = AF_INET;
1458 uin->sin_port = win->sin_port;
1459 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
1460 break;
1462 #ifdef HAS_IRDA
1463 case WS_AF_IRDA: {
1464 struct sockaddr_irda *uin = (struct sockaddr_irda *)uaddr;
1465 const SOCKADDR_IRDA *win = (const SOCKADDR_IRDA *)wsaddr;
1467 if (wsaddrlen < sizeof(SOCKADDR_IRDA))
1468 return 0;
1469 uaddrlen = sizeof(struct sockaddr_irda);
1470 memset( uaddr, 0, uaddrlen );
1471 uin->sir_family = AF_IRDA;
1472 if (!strncmp( win->irdaServiceName, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1474 unsigned int lsap_sel = 0;
1476 sscanf( win->irdaServiceName, "LSAP-SEL%u", &lsap_sel );
1477 uin->sir_lsap_sel = lsap_sel;
1479 else
1481 uin->sir_lsap_sel = LSAP_ANY;
1482 memcpy( uin->sir_name, win->irdaServiceName, 25 );
1484 memcpy( &uin->sir_addr, win->irdaDeviceID, sizeof(uin->sir_addr) );
1485 break;
1487 #endif
1488 case WS_AF_UNSPEC: {
1489 /* Try to determine the needed space by the passed windows sockaddr space */
1490 switch (wsaddrlen) {
1491 default: /* likely an ipv4 address */
1492 case sizeof(struct WS_sockaddr_in):
1493 uaddrlen = sizeof(struct sockaddr_in);
1494 break;
1495 #ifdef HAS_IPX
1496 case sizeof(struct WS_sockaddr_ipx):
1497 uaddrlen = sizeof(struct sockaddr_ipx);
1498 break;
1499 #endif
1500 #ifdef HAS_IRDA
1501 case sizeof(SOCKADDR_IRDA):
1502 uaddrlen = sizeof(struct sockaddr_irda);
1503 break;
1504 #endif
1505 case sizeof(struct WS_sockaddr_in6):
1506 case sizeof(struct WS_sockaddr_in6_old):
1507 uaddrlen = sizeof(struct sockaddr_in6);
1508 break;
1510 memset( uaddr, 0, uaddrlen );
1511 break;
1513 default:
1514 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
1515 return 0;
1517 return uaddrlen;
1520 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
1522 switch (uaddr->sa_family)
1524 #ifdef HAS_IPX
1525 case AF_IPX:
1527 static const struct sockaddr_ipx emptyAddr;
1528 struct sockaddr_ipx *ipx = (struct sockaddr_ipx*) uaddr;
1529 return ipx->sipx_port
1530 || memcmp(&ipx->sipx_network, &emptyAddr.sipx_network, sizeof(emptyAddr.sipx_network))
1531 || memcmp(&ipx->sipx_node, &emptyAddr.sipx_node, sizeof(emptyAddr.sipx_node));
1533 #endif
1534 case AF_INET6:
1536 static const struct sockaddr_in6 emptyAddr;
1537 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
1538 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
1540 case AF_INET:
1542 static const struct sockaddr_in emptyAddr;
1543 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
1544 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
1546 case AF_UNSPEC:
1547 return FALSE;
1548 default:
1549 FIXME("unknown address family %d\n", uaddr->sa_family);
1550 return TRUE;
1554 /* Returns 0 if successful, -1 if the buffer is too small */
1555 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
1557 int res;
1559 switch(uaddr->sa_family)
1561 #ifdef HAS_IPX
1562 case AF_IPX:
1564 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
1565 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
1567 res=-1;
1568 switch (*wsaddrlen) /* how much can we copy? */
1570 default:
1571 res=0; /* enough */
1572 *wsaddrlen = sizeof(*wsipx);
1573 wsipx->sa_socket=uipx->sipx_port;
1574 /* fall through */
1575 case 13:
1576 case 12:
1577 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
1578 /* fall through */
1579 case 11:
1580 case 10:
1581 case 9:
1582 case 8:
1583 case 7:
1584 case 6:
1585 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1586 /* fall through */
1587 case 5:
1588 case 4:
1589 case 3:
1590 case 2:
1591 wsipx->sa_family=WS_AF_IPX;
1592 /* fall through */
1593 case 1:
1594 case 0:
1595 /* way too small */
1596 break;
1599 break;
1600 #endif
1601 #ifdef HAS_IRDA
1602 case AF_IRDA: {
1603 const struct sockaddr_irda *uin = (const struct sockaddr_irda *)uaddr;
1604 SOCKADDR_IRDA *win = (SOCKADDR_IRDA *)wsaddr;
1606 if (*wsaddrlen < sizeof(SOCKADDR_IRDA))
1607 return -1;
1608 win->irdaAddressFamily = WS_AF_IRDA;
1609 memcpy( win->irdaDeviceID, &uin->sir_addr, sizeof(win->irdaDeviceID) );
1610 if (uin->sir_lsap_sel != LSAP_ANY)
1611 sprintf( win->irdaServiceName, "LSAP-SEL%u", uin->sir_lsap_sel );
1612 else
1613 memcpy( win->irdaServiceName, uin->sir_name,
1614 sizeof(win->irdaServiceName) );
1615 return 0;
1617 #endif
1618 case AF_INET6: {
1619 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1620 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1622 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1623 return -1;
1624 win6old->sin6_family = WS_AF_INET6;
1625 win6old->sin6_port = uin6->sin6_port;
1626 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1627 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1628 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1629 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1630 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1631 win6->sin6_scope_id = uin6->sin6_scope_id;
1632 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1634 else
1635 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1636 #else
1637 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1638 #endif
1639 return 0;
1641 case AF_INET: {
1642 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1643 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1645 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1646 return -1;
1647 win->sin_family = WS_AF_INET;
1648 win->sin_port = uin->sin_port;
1649 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1650 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1651 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1652 return 0;
1654 case AF_UNSPEC: {
1655 memset(wsaddr,0,*wsaddrlen);
1656 return 0;
1658 default:
1659 FIXME("Unknown address family %d\n", uaddr->sa_family);
1660 return -1;
1662 return res;
1665 static INT WS_DuplicateSocket(BOOL unicode, SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo)
1667 HANDLE hProcess;
1668 int size;
1669 WSAPROTOCOL_INFOW infow;
1671 TRACE("(unicode %d, socket %04lx, processid %x, buffer %p)\n",
1672 unicode, s, dwProcessId, lpProtocolInfo);
1674 if (!ws_protocol_info(s, unicode, &infow, &size))
1675 return SOCKET_ERROR;
1677 if (!(hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId)))
1679 SetLastError(WSAEINVAL);
1680 return SOCKET_ERROR;
1683 if (!lpProtocolInfo)
1685 CloseHandle(hProcess);
1686 SetLastError(WSAEFAULT);
1687 return SOCKET_ERROR;
1690 /* I don't know what the real Windoze does next, this is a hack */
1691 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
1692 * the target use the global duplicate, or we could copy a reference to us to the structure
1693 * and let the target duplicate it from us, but let's do it as simple as possible */
1694 memcpy(lpProtocolInfo, &infow, size);
1695 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
1696 hProcess, (LPHANDLE)&lpProtocolInfo->dwServiceFlags3,
1697 0, FALSE, DUPLICATE_SAME_ACCESS);
1698 CloseHandle(hProcess);
1699 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
1700 return 0;
1703 /*****************************************************************************
1704 * WS_EnterSingleProtocolW [internal]
1706 * enters the protocol information of one given protocol into the given
1707 * buffer.
1709 * RETURNS
1710 * TRUE if a protocol was entered into the buffer.
1712 * BUGS
1713 * - only implemented for IPX, SPX, SPXII, TCP, UDP
1714 * - there is no check that the operating system supports the returned
1715 * protocols
1717 static BOOL WS_EnterSingleProtocolW( INT protocol, WSAPROTOCOL_INFOW* info )
1719 memset( info, 0, sizeof(WSAPROTOCOL_INFOW) );
1720 info->iProtocol = protocol;
1722 switch (protocol)
1724 case WS_IPPROTO_TCP:
1725 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_EXPEDITED_DATA |
1726 XP1_GRACEFUL_CLOSE | XP1_GUARANTEED_ORDER |
1727 XP1_GUARANTEED_DELIVERY;
1728 info->ProviderId = ProviderIdIP;
1729 info->dwCatalogEntryId = 0x3e9;
1730 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1731 info->ProtocolChain.ChainLen = 1;
1732 info->iVersion = 2;
1733 info->iAddressFamily = WS_AF_INET;
1734 info->iMaxSockAddr = 0x10;
1735 info->iMinSockAddr = 0x10;
1736 info->iSocketType = WS_SOCK_STREAM;
1737 strcpyW( info->szProtocol, NameTcpW );
1738 break;
1740 case WS_IPPROTO_UDP:
1741 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_SUPPORT_BROADCAST |
1742 XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED |
1743 XP1_CONNECTIONLESS;
1744 info->ProviderId = ProviderIdIP;
1745 info->dwCatalogEntryId = 0x3ea;
1746 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1747 info->ProtocolChain.ChainLen = 1;
1748 info->iVersion = 2;
1749 info->iAddressFamily = WS_AF_INET;
1750 info->iMaxSockAddr = 0x10;
1751 info->iMinSockAddr = 0x10;
1752 info->iSocketType = WS_SOCK_DGRAM;
1753 info->dwMessageSize = 0xffbb;
1754 strcpyW( info->szProtocol, NameUdpW );
1755 break;
1757 case WS_NSPROTO_IPX:
1758 info->dwServiceFlags1 = XP1_PARTIAL_MESSAGE | XP1_SUPPORT_BROADCAST |
1759 XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED |
1760 XP1_CONNECTIONLESS;
1761 info->ProviderId = ProviderIdIPX;
1762 info->dwCatalogEntryId = 0x406;
1763 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1764 info->ProtocolChain.ChainLen = 1;
1765 info->iVersion = 2;
1766 info->iAddressFamily = WS_AF_IPX;
1767 info->iMaxSockAddr = 0x10;
1768 info->iMinSockAddr = 0x0e;
1769 info->iSocketType = WS_SOCK_DGRAM;
1770 info->iProtocolMaxOffset = 0xff;
1771 info->dwMessageSize = 0x240;
1772 strcpyW( info->szProtocol, NameIpxW );
1773 break;
1775 case WS_NSPROTO_SPX:
1776 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_PSEUDO_STREAM |
1777 XP1_MESSAGE_ORIENTED | XP1_GUARANTEED_ORDER |
1778 XP1_GUARANTEED_DELIVERY;
1779 info->ProviderId = ProviderIdSPX;
1780 info->dwCatalogEntryId = 0x407;
1781 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1782 info->ProtocolChain.ChainLen = 1;
1783 info->iVersion = 2;
1784 info->iAddressFamily = WS_AF_IPX;
1785 info->iMaxSockAddr = 0x10;
1786 info->iMinSockAddr = 0x0e;
1787 info->iSocketType = WS_SOCK_SEQPACKET;
1788 info->dwMessageSize = 0xffffffff;
1789 strcpyW( info->szProtocol, NameSpxW );
1790 break;
1792 case WS_NSPROTO_SPXII:
1793 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_GRACEFUL_CLOSE |
1794 XP1_PSEUDO_STREAM | XP1_MESSAGE_ORIENTED |
1795 XP1_GUARANTEED_ORDER | XP1_GUARANTEED_DELIVERY;
1796 info->ProviderId = ProviderIdSPX;
1797 info->dwCatalogEntryId = 0x409;
1798 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1799 info->ProtocolChain.ChainLen = 1;
1800 info->iVersion = 2;
1801 info->iAddressFamily = WS_AF_IPX;
1802 info->iMaxSockAddr = 0x10;
1803 info->iMinSockAddr = 0x0e;
1804 info->iSocketType = WS_SOCK_SEQPACKET;
1805 info->dwMessageSize = 0xffffffff;
1806 strcpyW( info->szProtocol, NameSpxIIW );
1807 break;
1809 default:
1810 FIXME("unknown Protocol <0x%08x>\n", protocol);
1811 return FALSE;
1813 return TRUE;
1816 /*****************************************************************************
1817 * WS_EnterSingleProtocolA [internal]
1819 * see function WS_EnterSingleProtocolW
1822 static BOOL WS_EnterSingleProtocolA( INT protocol, WSAPROTOCOL_INFOA* info )
1824 WSAPROTOCOL_INFOW infow;
1825 INT ret;
1826 memset( info, 0, sizeof(WSAPROTOCOL_INFOA) );
1828 ret = WS_EnterSingleProtocolW( protocol, &infow );
1829 if (ret)
1831 /* convert the structure from W to A */
1832 memcpy( info, &infow, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
1833 WideCharToMultiByte( CP_ACP, 0, infow.szProtocol, -1,
1834 info->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL );
1837 return ret;
1840 static INT WS_EnumProtocols( BOOL unicode, const INT *protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
1842 INT i = 0, items = 0;
1843 DWORD size = 0;
1844 union _info
1846 LPWSAPROTOCOL_INFOA a;
1847 LPWSAPROTOCOL_INFOW w;
1848 } info;
1849 info.w = buffer;
1851 if (!protocols) protocols = valid_protocols;
1853 while (protocols[i])
1855 if(supported_protocol(protocols[i++]))
1856 items++;
1859 size = items * (unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA));
1861 TRACE("unicode %d, protocols %p, buffer %p, length %p %d, items %d, required %d\n",
1862 unicode, protocols, buffer, len, len ? *len : 0, items, size);
1864 if (*len < size || !buffer)
1866 *len = size;
1867 SetLastError(WSAENOBUFS);
1868 return SOCKET_ERROR;
1871 for (i = items = 0; protocols[i]; i++)
1873 if (!supported_protocol(protocols[i])) continue;
1874 if (unicode)
1876 if (WS_EnterSingleProtocolW( protocols[i], &info.w[items] ))
1877 items++;
1879 else
1881 if (WS_EnterSingleProtocolA( protocols[i], &info.a[items] ))
1882 items++;
1885 return items;
1888 static BOOL ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size)
1890 NTSTATUS status;
1892 *size = unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA);
1893 memset(buffer, 0, *size);
1895 SERVER_START_REQ( get_socket_info )
1897 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1898 status = wine_server_call( req );
1899 if (!status)
1901 buffer->iAddressFamily = convert_af_u2w(reply->family);
1902 buffer->iSocketType = convert_socktype_u2w(reply->type);
1903 buffer->iProtocol = convert_proto_u2w(reply->protocol);
1906 SERVER_END_REQ;
1908 if (status)
1910 unsigned int err = NtStatusToWSAError( status );
1911 SetLastError( err == WSAEBADF ? WSAENOTSOCK : err );
1912 return FALSE;
1915 if (unicode)
1916 WS_EnterSingleProtocolW( buffer->iProtocol, buffer);
1917 else
1918 WS_EnterSingleProtocolA( buffer->iProtocol, (WSAPROTOCOL_INFOA *)buffer);
1920 return TRUE;
1923 /**************************************************************************
1924 * Functions for handling overlapped I/O
1925 **************************************************************************/
1927 /* user APC called upon async completion */
1928 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1930 struct ws2_async *wsa = arg;
1932 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
1933 iosb->Information, wsa->user_overlapped,
1934 wsa->flags );
1935 release_async_io( &wsa->io );
1938 /***********************************************************************
1939 * WS2_recv (INTERNAL)
1941 * Workhorse for both synchronous and asynchronous recv() operations.
1943 static int WS2_recv( int fd, struct ws2_async *wsa )
1945 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1946 char pktbuf[512];
1947 #endif
1948 struct msghdr hdr;
1949 union generic_unix_sockaddr unix_sockaddr;
1950 int n;
1952 hdr.msg_name = NULL;
1954 if (wsa->addr)
1956 hdr.msg_namelen = sizeof(unix_sockaddr);
1957 hdr.msg_name = &unix_sockaddr;
1959 else
1960 hdr.msg_namelen = 0;
1962 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1963 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1964 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1965 hdr.msg_accrights = NULL;
1966 hdr.msg_accrightslen = 0;
1967 #else
1968 hdr.msg_control = pktbuf;
1969 hdr.msg_controllen = sizeof(pktbuf);
1970 hdr.msg_flags = 0;
1971 #endif
1973 while ((n = recvmsg(fd, &hdr, wsa->flags)) == -1)
1975 if (errno != EINTR)
1976 return -1;
1979 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1980 if (wsa->control)
1982 ERR("Message control headers cannot be properly supported on this system.\n");
1983 wsa->control->len = 0;
1985 #else
1986 if (wsa->control && !convert_control_headers(&hdr, wsa->control))
1988 WARN("Application passed insufficient room for control headers.\n");
1989 *wsa->lpFlags |= WS_MSG_CTRUNC;
1990 errno = EMSGSIZE;
1991 return -1;
1993 #endif
1995 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
1996 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
1998 * quoting linux 2.6 net/ipv4/tcp.c:
1999 * "According to UNIX98, msg_name/msg_namelen are ignored
2000 * on connected socket. I was just happy when found this 8) --ANK"
2002 * likewise MSDN says that lpFrom and lpFromlen are ignored for
2003 * connection-oriented sockets, so don't try to update lpFrom.
2005 if (wsa->addr && hdr.msg_namelen)
2006 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
2008 return n;
2011 /***********************************************************************
2012 * WS2_async_recv (INTERNAL)
2014 * Handler for overlapped recv() operations.
2016 static NTSTATUS WS2_async_recv( void *user, IO_STATUS_BLOCK *iosb,
2017 NTSTATUS status, void **apc, void **arg )
2019 struct ws2_async *wsa = user;
2020 int result = 0, fd;
2022 switch (status)
2024 case STATUS_ALERTED:
2025 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
2026 break;
2028 result = WS2_recv( fd, wsa );
2029 wine_server_release_fd( wsa->hSocket, fd );
2030 if (result >= 0)
2032 status = STATUS_SUCCESS;
2033 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
2035 else
2037 if (errno == EAGAIN)
2039 status = STATUS_PENDING;
2040 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
2042 else
2044 result = 0;
2045 status = wsaErrStatus();
2048 break;
2050 if (status != STATUS_PENDING)
2052 iosb->u.Status = status;
2053 iosb->Information = result;
2054 if (wsa->completion_func)
2056 *apc = ws2_async_apc;
2057 *arg = wsa;
2059 else
2060 release_async_io( &wsa->io );
2062 return status;
2065 /***********************************************************************
2066 * WS2_async_accept_recv (INTERNAL)
2068 * This function is used to finish the read part of an accept request. It is
2069 * needed to place the completion on the correct socket (listener).
2071 static NTSTATUS WS2_async_accept_recv( void *user, IO_STATUS_BLOCK *iosb,
2072 NTSTATUS status, void **apc, void **arg )
2074 void *junk;
2075 struct ws2_accept_async *wsa = user;
2077 status = WS2_async_recv( wsa->read, iosb, status, &junk, &junk );
2078 if (status == STATUS_PENDING)
2079 return status;
2081 if (wsa->cvalue)
2082 WS_AddCompletion( HANDLE2SOCKET(wsa->listen_socket), wsa->cvalue, iosb->u.Status, iosb->Information );
2084 release_async_io( &wsa->io );
2085 return status;
2088 /***********************************************************************
2089 * WS2_async_accept (INTERNAL)
2091 * This is the function called to satisfy the AcceptEx callback
2093 static NTSTATUS WS2_async_accept( void *user, IO_STATUS_BLOCK *iosb,
2094 NTSTATUS status, void **apc, void **arg )
2096 struct ws2_accept_async *wsa = user;
2097 int len;
2098 char *addr;
2100 TRACE("status: 0x%x listen: %p, accept: %p\n", status, wsa->listen_socket, wsa->accept_socket);
2102 if (status == STATUS_ALERTED)
2104 SERVER_START_REQ( accept_into_socket )
2106 req->lhandle = wine_server_obj_handle( wsa->listen_socket );
2107 req->ahandle = wine_server_obj_handle( wsa->accept_socket );
2108 status = wine_server_call( req );
2110 SERVER_END_REQ;
2112 if (status == STATUS_CANT_WAIT)
2113 return STATUS_PENDING;
2115 if (status == STATUS_INVALID_HANDLE)
2117 FIXME("AcceptEx accepting socket closed but request was not cancelled\n");
2118 status = STATUS_CANCELLED;
2121 else if (status == STATUS_HANDLES_CLOSED)
2122 status = STATUS_CANCELLED; /* strange windows behavior */
2124 if (status != STATUS_SUCCESS)
2125 goto finish;
2127 /* WS2 Spec says size param is extra 16 bytes long...what do we put in it? */
2128 addr = ((char *)wsa->buf) + wsa->data_len;
2129 len = wsa->local_len - sizeof(int);
2130 WS_getsockname(HANDLE2SOCKET(wsa->accept_socket),
2131 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
2132 *(int *)addr = len;
2134 addr += wsa->local_len;
2135 len = wsa->remote_len - sizeof(int);
2136 WS_getpeername(HANDLE2SOCKET(wsa->accept_socket),
2137 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
2138 *(int *)addr = len;
2140 if (!wsa->read)
2141 goto finish;
2143 SERVER_START_REQ( register_async )
2145 req->type = ASYNC_TYPE_READ;
2146 req->async.handle = wine_server_obj_handle( wsa->accept_socket );
2147 req->async.event = wine_server_obj_handle( wsa->user_overlapped->hEvent );
2148 req->async.callback = wine_server_client_ptr( WS2_async_accept_recv );
2149 req->async.iosb = wine_server_client_ptr( iosb );
2150 req->async.arg = wine_server_client_ptr( wsa );
2151 status = wine_server_call( req );
2153 SERVER_END_REQ;
2155 if (status != STATUS_PENDING)
2156 goto finish;
2158 /* The APC has finished but no completion should be sent for the operation yet, additional processing
2159 * needs to be performed by WS2_async_accept_recv() first. */
2160 return STATUS_MORE_PROCESSING_REQUIRED;
2162 finish:
2163 iosb->u.Status = status;
2164 iosb->Information = 0;
2166 if (wsa->read) release_async_io( &wsa->read->io );
2167 release_async_io( &wsa->io );
2168 return status;
2171 /***********************************************************************
2172 * WS2_send (INTERNAL)
2174 * Workhorse for both synchronous and asynchronous send() operations.
2176 static int WS2_send( int fd, struct ws2_async *wsa )
2178 struct msghdr hdr;
2179 union generic_unix_sockaddr unix_addr;
2180 int n, ret;
2182 hdr.msg_name = NULL;
2183 hdr.msg_namelen = 0;
2185 if (wsa->addr)
2187 hdr.msg_name = &unix_addr;
2188 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
2189 if ( !hdr.msg_namelen )
2191 errno = EFAULT;
2192 return -1;
2195 #if defined(HAS_IPX) && defined(SOL_IPX)
2196 if(wsa->addr->sa_family == WS_AF_IPX)
2198 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
2199 int val=0;
2200 socklen_t len = sizeof(int);
2202 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
2203 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
2204 * the packet type and then we can retrieve it using getsockopt. After that we can set the
2205 * ipx type in the sockaddr_opx structure with the stored value.
2207 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
2208 uipx->sipx_type = val;
2210 #endif
2213 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
2214 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
2215 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2216 hdr.msg_accrights = NULL;
2217 hdr.msg_accrightslen = 0;
2218 #else
2219 hdr.msg_control = NULL;
2220 hdr.msg_controllen = 0;
2221 hdr.msg_flags = 0;
2222 #endif
2224 while ((ret = sendmsg(fd, &hdr, wsa->flags)) == -1)
2226 if (errno != EINTR)
2227 return -1;
2230 n = ret;
2231 while (wsa->first_iovec < wsa->n_iovecs && wsa->iovec[wsa->first_iovec].iov_len <= n)
2232 n -= wsa->iovec[wsa->first_iovec++].iov_len;
2233 if (wsa->first_iovec < wsa->n_iovecs)
2235 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
2236 wsa->iovec[wsa->first_iovec].iov_len -= n;
2238 return ret;
2241 /***********************************************************************
2242 * WS2_async_send (INTERNAL)
2244 * Handler for overlapped send() operations.
2246 static NTSTATUS WS2_async_send( void *user, IO_STATUS_BLOCK *iosb,
2247 NTSTATUS status, void **apc, void **arg )
2249 struct ws2_async *wsa = user;
2250 int result = 0, fd;
2252 switch (status)
2254 case STATUS_ALERTED:
2255 if ( wsa->n_iovecs <= wsa->first_iovec )
2257 /* Nothing to do */
2258 status = STATUS_SUCCESS;
2259 break;
2261 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
2262 break;
2264 /* check to see if the data is ready (non-blocking) */
2265 result = WS2_send( fd, wsa );
2266 wine_server_release_fd( wsa->hSocket, fd );
2268 if (result >= 0)
2270 if (wsa->first_iovec < wsa->n_iovecs)
2271 status = STATUS_PENDING;
2272 else
2273 status = STATUS_SUCCESS;
2275 iosb->Information += result;
2277 else if (errno == EAGAIN)
2279 status = STATUS_PENDING;
2281 else
2283 status = wsaErrStatus();
2285 break;
2287 if (status != STATUS_PENDING)
2289 iosb->u.Status = status;
2290 if (wsa->completion_func)
2292 *apc = ws2_async_apc;
2293 *arg = wsa;
2295 else
2296 release_async_io( &wsa->io );
2298 return status;
2301 /***********************************************************************
2302 * WS2_async_shutdown (INTERNAL)
2304 * Handler for shutdown() operations on overlapped sockets.
2306 static NTSTATUS WS2_async_shutdown( void *user, IO_STATUS_BLOCK *iosb,
2307 NTSTATUS status, void **apc, void **arg )
2309 struct ws2_async_shutdown *wsa = user;
2310 int fd, err = 1;
2312 switch (status)
2314 case STATUS_ALERTED:
2315 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
2316 break;
2318 switch ( wsa->type )
2320 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
2321 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
2323 status = err ? wsaErrStatus() : STATUS_SUCCESS;
2324 wine_server_release_fd( wsa->hSocket, fd );
2325 break;
2327 iosb->u.Status = status;
2328 iosb->Information = 0;
2329 release_async_io( &wsa->io );
2330 return status;
2333 /***********************************************************************
2334 * WS2_register_async_shutdown (INTERNAL)
2336 * Helper function for WS_shutdown() on overlapped sockets.
2338 static int WS2_register_async_shutdown( SOCKET s, int type )
2340 struct ws2_async_shutdown *wsa;
2341 NTSTATUS status;
2343 TRACE("socket %04lx type %d\n", s, type);
2345 wsa = (struct ws2_async_shutdown *)alloc_async_io( sizeof(*wsa) );
2346 if ( !wsa )
2347 return WSAEFAULT;
2349 wsa->hSocket = SOCKET2HANDLE(s);
2350 wsa->type = type;
2352 SERVER_START_REQ( register_async )
2354 req->type = type;
2355 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2356 req->async.callback = wine_server_client_ptr( WS2_async_shutdown );
2357 req->async.iosb = wine_server_client_ptr( &wsa->iosb );
2358 req->async.arg = wine_server_client_ptr( wsa );
2359 req->async.cvalue = 0;
2360 status = wine_server_call( req );
2362 SERVER_END_REQ;
2364 if (status != STATUS_PENDING)
2366 HeapFree( GetProcessHeap(), 0, wsa );
2367 return NtStatusToWSAError( status );
2369 return 0;
2372 /***********************************************************************
2373 * accept (WS2_32.1)
2375 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr, int *addrlen32)
2377 NTSTATUS status;
2378 SOCKET as;
2379 BOOL is_blocking;
2381 TRACE("socket %04lx\n", s );
2382 status = _is_blocking(s, &is_blocking);
2383 if (status)
2385 set_error(status);
2386 return INVALID_SOCKET;
2389 do {
2390 /* try accepting first (if there is a deferred connection) */
2391 SERVER_START_REQ( accept_socket )
2393 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
2394 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
2395 req->attributes = OBJ_INHERIT;
2396 status = wine_server_call( req );
2397 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
2399 SERVER_END_REQ;
2400 if (!status)
2402 if (addr && WS_getpeername(as, addr, addrlen32))
2404 WS_closesocket(as);
2405 return SOCKET_ERROR;
2407 return as;
2409 if (is_blocking && status == STATUS_CANT_WAIT)
2411 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2412 /* block here */
2413 do_block(fd, POLLIN, -1);
2414 _sync_sock_state(s); /* let wineserver notice connection */
2415 release_sock_fd( s, fd );
2417 } while (is_blocking && status == STATUS_CANT_WAIT);
2419 set_error(status);
2420 return INVALID_SOCKET;
2423 /***********************************************************************
2424 * AcceptEx
2426 static BOOL WINAPI WS2_AcceptEx(SOCKET listener, SOCKET acceptor, PVOID dest, DWORD dest_len,
2427 DWORD local_addr_len, DWORD rem_addr_len, LPDWORD received,
2428 LPOVERLAPPED overlapped)
2430 DWORD status;
2431 struct ws2_accept_async *wsa;
2432 int fd;
2434 TRACE("(%04lx, %04lx, %p, %d, %d, %d, %p, %p)\n", listener, acceptor, dest, dest_len, local_addr_len,
2435 rem_addr_len, received, overlapped);
2437 if (!dest)
2439 SetLastError(WSAEINVAL);
2440 return FALSE;
2443 if (!overlapped)
2445 SetLastError(WSA_INVALID_PARAMETER);
2446 return FALSE;
2449 if (!rem_addr_len)
2451 SetLastError(WSAEFAULT);
2452 return FALSE;
2455 fd = get_sock_fd( listener, FILE_READ_DATA, NULL );
2456 if (fd == -1)
2458 SetLastError(WSAENOTSOCK);
2459 return FALSE;
2461 release_sock_fd( listener, fd );
2463 fd = get_sock_fd( acceptor, FILE_READ_DATA, NULL );
2464 if (fd == -1)
2466 SetLastError(WSAENOTSOCK);
2467 return FALSE;
2469 release_sock_fd( acceptor, fd );
2471 wsa = (struct ws2_accept_async *)alloc_async_io( sizeof(*wsa) );
2472 if(!wsa)
2474 SetLastError(WSAEFAULT);
2475 return FALSE;
2478 wsa->listen_socket = SOCKET2HANDLE(listener);
2479 wsa->accept_socket = SOCKET2HANDLE(acceptor);
2480 wsa->user_overlapped = overlapped;
2481 wsa->cvalue = !((ULONG_PTR)overlapped->hEvent & 1) ? (ULONG_PTR)overlapped : 0;
2482 wsa->buf = dest;
2483 wsa->data_len = dest_len;
2484 wsa->local_len = local_addr_len;
2485 wsa->remote_len = rem_addr_len;
2486 wsa->read = NULL;
2488 if (wsa->data_len)
2490 /* set up a read request if we need it */
2491 wsa->read = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[1]) );
2492 if (!wsa->read)
2494 HeapFree( GetProcessHeap(), 0, wsa );
2495 SetLastError(WSAEFAULT);
2496 return FALSE;
2499 wsa->read->hSocket = wsa->accept_socket;
2500 wsa->read->flags = 0;
2501 wsa->read->lpFlags = &wsa->read->flags;
2502 wsa->read->addr = NULL;
2503 wsa->read->addrlen.ptr = NULL;
2504 wsa->read->control = NULL;
2505 wsa->read->n_iovecs = 1;
2506 wsa->read->first_iovec = 0;
2507 wsa->read->completion_func = NULL;
2508 wsa->read->iovec[0].iov_base = wsa->buf;
2509 wsa->read->iovec[0].iov_len = wsa->data_len;
2512 SERVER_START_REQ( register_async )
2514 req->type = ASYNC_TYPE_READ;
2515 req->async.handle = wine_server_obj_handle( SOCKET2HANDLE(listener) );
2516 req->async.event = wine_server_obj_handle( overlapped->hEvent );
2517 req->async.callback = wine_server_client_ptr( WS2_async_accept );
2518 req->async.iosb = wine_server_client_ptr( overlapped );
2519 req->async.arg = wine_server_client_ptr( wsa );
2520 req->async.cvalue = wsa->cvalue;
2521 status = wine_server_call( req );
2523 SERVER_END_REQ;
2525 if(status != STATUS_PENDING)
2527 HeapFree( GetProcessHeap(), 0, wsa->read );
2528 HeapFree( GetProcessHeap(), 0, wsa );
2531 SetLastError( NtStatusToWSAError(status) );
2532 return FALSE;
2535 /***********************************************************************
2536 * GetAcceptExSockaddrs
2538 static void WINAPI WS2_GetAcceptExSockaddrs(PVOID buffer, DWORD data_size, DWORD local_size, DWORD remote_size,
2539 struct WS_sockaddr **local_addr, LPINT local_addr_len,
2540 struct WS_sockaddr **remote_addr, LPINT remote_addr_len)
2542 char *cbuf = buffer;
2543 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer, data_size, local_size, remote_size, local_addr,
2544 local_addr_len, remote_addr, remote_addr_len );
2545 cbuf += data_size;
2547 *local_addr_len = *(int *) cbuf;
2548 *local_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2550 cbuf += local_size;
2552 *remote_addr_len = *(int *) cbuf;
2553 *remote_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2556 /***********************************************************************
2557 * WSASendMsg
2559 int WINAPI WSASendMsg( SOCKET s, LPWSAMSG msg, DWORD dwFlags, LPDWORD lpNumberOfBytesSent,
2560 LPWSAOVERLAPPED lpOverlapped,
2561 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
2563 if (!msg)
2565 SetLastError( WSAEFAULT );
2566 return SOCKET_ERROR;
2569 return WS2_sendto( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesSent,
2570 dwFlags, msg->name, msg->namelen,
2571 lpOverlapped, lpCompletionRoutine );
2574 /***********************************************************************
2575 * WSARecvMsg
2577 * Perform a receive operation that is capable of returning message
2578 * control headers. It is important to note that the WSAMSG parameter
2579 * must remain valid throughout the operation, even when an overlapped
2580 * receive is performed.
2582 static int WINAPI WS2_WSARecvMsg( SOCKET s, LPWSAMSG msg, LPDWORD lpNumberOfBytesRecvd,
2583 LPWSAOVERLAPPED lpOverlapped,
2584 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2586 if (!msg)
2588 SetLastError( WSAEFAULT );
2589 return SOCKET_ERROR;
2592 return WS2_recv_base( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesRecvd,
2593 &msg->dwFlags, msg->name, &msg->namelen,
2594 lpOverlapped, lpCompletionRoutine, &msg->Control );
2597 /***********************************************************************
2598 * interface_bind (INTERNAL)
2600 * Take bind() calls on any name corresponding to a local network adapter and restrict the given socket to
2601 * operating only on the specified interface. This restriction consists of two components:
2602 * 1) An outgoing packet restriction suggesting the egress interface for all packets.
2603 * 2) An incoming packet restriction dropping packets not meant for the interface.
2604 * If the function succeeds in placing these restrictions (returns TRUE) then the name for the bind() may
2605 * safely be changed to INADDR_ANY, permitting the transmission and receipt of broadcast packets on the
2606 * socket. This behavior is only relevant to UDP sockets and is needed for applications that expect to be able
2607 * to receive broadcast packets on a socket that is bound to a specific network interface.
2609 static BOOL interface_bind( SOCKET s, int fd, struct sockaddr *addr )
2611 struct sockaddr_in *in_sock = (struct sockaddr_in *) addr;
2612 unsigned int sock_type = 0;
2613 socklen_t optlen = sizeof(sock_type);
2614 in_addr_t bind_addr = in_sock->sin_addr.s_addr;
2615 PIP_ADAPTER_INFO adapters = NULL, adapter;
2616 BOOL ret = FALSE;
2617 DWORD adap_size;
2618 int enable = 1;
2620 if (bind_addr == htonl(INADDR_ANY) || bind_addr == htonl(INADDR_LOOPBACK))
2621 return FALSE; /* Not binding to a network adapter, special interface binding unnecessary. */
2622 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &sock_type, &optlen) == -1 || sock_type != SOCK_DGRAM)
2623 return FALSE; /* Special interface binding is only necessary for UDP datagrams. */
2624 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
2625 goto cleanup;
2626 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
2627 if (adapters == NULL || GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
2628 goto cleanup;
2629 /* Search the IPv4 adapter list for the appropriate binding interface */
2630 for (adapter = adapters; adapter != NULL; adapter = adapter->Next)
2632 in_addr_t adapter_addr = (in_addr_t) inet_addr(adapter->IpAddressList.IpAddress.String);
2634 if (bind_addr == adapter_addr)
2636 #if defined(IP_BOUND_IF)
2637 /* IP_BOUND_IF sets both the incoming and outgoing restriction at once */
2638 if (setsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &adapter->Index, sizeof(adapter->Index)) != 0)
2639 goto cleanup;
2640 ret = TRUE;
2641 #elif defined(LINUX_BOUND_IF)
2642 in_addr_t ifindex = (in_addr_t) htonl(adapter->Index);
2643 struct interface_filter specific_interface_filter;
2644 struct sock_fprog filter_prog;
2646 if (setsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex, sizeof(ifindex)) != 0)
2647 goto cleanup; /* Failed to suggest egress interface */
2648 specific_interface_filter = generic_interface_filter;
2649 specific_interface_filter.iface_rule.k = adapter->Index;
2650 specific_interface_filter.ip_rule.k = htonl(adapter_addr);
2651 filter_prog.len = sizeof(generic_interface_filter)/sizeof(struct sock_filter);
2652 filter_prog.filter = (struct sock_filter *) &specific_interface_filter;
2653 if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog, sizeof(filter_prog)) != 0)
2654 goto cleanup; /* Failed to specify incoming packet filter */
2655 ret = TRUE;
2656 #else
2657 FIXME("Broadcast packets on interface-bound sockets are not currently supported on this platform, "
2658 "receiving broadcast packets will not work on socket %04lx.\n", s);
2659 #endif
2660 break;
2663 /* Will soon be switching to INADDR_ANY: permit address reuse */
2664 if (ret && setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) == 0)
2665 TRACE("Socket %04lx bound to interface index %d\n", s, adapter->Index);
2666 else
2667 ret = FALSE;
2669 cleanup:
2670 if(!ret)
2671 ERR("Failed to bind to interface, receiving broadcast packets will not work on socket %04lx.\n", s);
2672 HeapFree(GetProcessHeap(), 0, adapters);
2673 return ret;
2676 /***********************************************************************
2677 * bind (WS2_32.2)
2679 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
2681 int fd = get_sock_fd( s, 0, NULL );
2682 int res = SOCKET_ERROR;
2684 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2686 if (fd != -1)
2688 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
2690 SetLastError(WSAEAFNOSUPPORT);
2692 else
2694 union generic_unix_sockaddr uaddr;
2695 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2696 if (!uaddrlen)
2698 SetLastError(WSAEFAULT);
2700 else
2702 #ifdef IPV6_V6ONLY
2703 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
2704 if (name->sa_family == WS_AF_INET6 &&
2705 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
2707 int enable = 1;
2708 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
2710 release_sock_fd( s, fd );
2711 SetLastError(WSAEAFNOSUPPORT);
2712 return SOCKET_ERROR;
2715 #endif
2716 if (name->sa_family == WS_AF_INET)
2718 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2719 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2721 /* Trying to bind to the default host interface, using
2722 * INADDR_ANY instead*/
2723 WARN("Trying to bind to magic IP address, using "
2724 "INADDR_ANY instead.\n");
2725 in4->sin_addr.s_addr = htonl(INADDR_ANY);
2727 else if (interface_bind(s, fd, &uaddr.addr))
2728 in4->sin_addr.s_addr = htonl(INADDR_ANY);
2730 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
2732 int loc_errno = errno;
2733 WARN("\tfailure - errno = %i\n", errno);
2734 errno = loc_errno;
2735 switch (errno)
2737 case EBADF:
2738 SetLastError(WSAENOTSOCK);
2739 break;
2740 case EADDRNOTAVAIL:
2741 SetLastError(WSAEINVAL);
2742 break;
2743 case EADDRINUSE:
2745 int optval = 0;
2746 socklen_t optlen = sizeof(optval);
2747 /* Windows >= 2003 will return different results depending on
2748 * SO_REUSEADDR, WSAEACCES may be returned representing that
2749 * the socket hijacking protection prevented the bind */
2750 if (!getsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&optval, &optlen) && optval)
2752 SetLastError(WSAEACCES);
2753 break;
2755 /* fall through */
2757 default:
2758 SetLastError(wsaErrno());
2759 break;
2762 else
2764 res=0; /* success */
2768 release_sock_fd( s, fd );
2770 return res;
2773 /***********************************************************************
2774 * closesocket (WS2_32.3)
2776 int WINAPI WS_closesocket(SOCKET s)
2778 int res = SOCKET_ERROR, fd;
2779 if (num_startup)
2781 fd = get_sock_fd(s, FILE_READ_DATA, NULL);
2782 if (fd >= 0)
2784 release_sock_fd(s, fd);
2785 if (CloseHandle(SOCKET2HANDLE(s)))
2786 res = 0;
2788 else
2789 SetLastError(WSAENOTSOCK);
2791 else
2792 SetLastError(WSANOTINITIALISED);
2793 TRACE("(socket %04lx) -> %d\n", s, res);
2794 return res;
2797 static int do_connect(int fd, const struct WS_sockaddr* name, int namelen)
2799 union generic_unix_sockaddr uaddr;
2800 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2802 if (!uaddrlen)
2803 return WSAEFAULT;
2805 if (name->sa_family == WS_AF_INET)
2807 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2808 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2810 /* Trying to connect to magic replace-loopback address,
2811 * assuming we really want to connect to localhost */
2812 TRACE("Trying to connect to magic IP address, using "
2813 "INADDR_LOOPBACK instead.\n");
2814 in4->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
2818 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
2819 return 0;
2821 return wsaErrno();
2824 /***********************************************************************
2825 * connect (WS2_32.4)
2827 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
2829 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2831 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2833 if (fd != -1)
2835 NTSTATUS status;
2836 BOOL is_blocking;
2837 int ret = do_connect(fd, name, namelen);
2838 if (ret == 0)
2839 goto connect_success;
2841 if (ret == WSAEINPROGRESS)
2843 /* tell wineserver that a connection is in progress */
2844 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2845 FD_CONNECT,
2846 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2847 status = _is_blocking( s, &is_blocking );
2848 if (status)
2850 release_sock_fd( s, fd );
2851 set_error( status );
2852 return SOCKET_ERROR;
2854 if (is_blocking)
2856 int result;
2857 /* block here */
2858 do_block(fd, POLLIN | POLLOUT, -1);
2859 _sync_sock_state(s); /* let wineserver notice connection */
2860 /* retrieve any error codes from it */
2861 result = _get_sock_error(s, FD_CONNECT_BIT);
2862 if (result)
2863 SetLastError(NtStatusToWSAError(result));
2864 else
2866 goto connect_success;
2869 else
2871 SetLastError(WSAEWOULDBLOCK);
2874 else
2876 SetLastError(ret);
2878 release_sock_fd( s, fd );
2880 return SOCKET_ERROR;
2882 connect_success:
2883 release_sock_fd( s, fd );
2884 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2885 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2886 FD_CONNECT|FD_WINE_LISTENING);
2887 return 0;
2890 /***********************************************************************
2891 * WSAConnect (WS2_32.30)
2893 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
2894 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
2895 LPQOS lpSQOS, LPQOS lpGQOS )
2897 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
2898 FIXME("unsupported parameters!\n");
2899 return WS_connect( s, name, namelen );
2902 /***********************************************************************
2903 * ConnectEx
2905 static BOOL WINAPI WS2_ConnectEx(SOCKET s, const struct WS_sockaddr* name, int namelen,
2906 PVOID sendBuf, DWORD sendBufLen, LPDWORD sent, LPOVERLAPPED ov)
2908 int fd, ret, status;
2909 union generic_unix_sockaddr uaddr;
2910 socklen_t uaddrlen = sizeof(uaddr);
2912 if (!ov)
2914 SetLastError( ERROR_INVALID_PARAMETER );
2915 return FALSE;
2918 fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2919 if (fd == -1)
2921 SetLastError( WSAENOTSOCK );
2922 return FALSE;
2925 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
2926 s, name, debugstr_sockaddr(name), namelen, sendBuf, sendBufLen, ov);
2928 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
2930 SetLastError(wsaErrno());
2931 return FALSE;
2933 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
2935 SetLastError(WSAEINVAL);
2936 return FALSE;
2939 ret = do_connect(fd, name, namelen);
2940 if (ret == 0)
2942 WSABUF wsabuf;
2944 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2945 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2946 FD_CONNECT|FD_WINE_LISTENING);
2948 wsabuf.len = sendBufLen;
2949 wsabuf.buf = (char*) sendBuf;
2951 /* WSASend takes care of completion if need be */
2952 if (WSASend(s, &wsabuf, sendBuf ? 1 : 0, sent, 0, ov, NULL) != SOCKET_ERROR)
2953 goto connection_success;
2955 else if (ret == WSAEINPROGRESS)
2957 struct ws2_async *wsa;
2958 ULONG_PTR cvalue = (((ULONG_PTR)ov->hEvent & 1) == 0) ? (ULONG_PTR)ov : 0;
2960 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2961 FD_CONNECT,
2962 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2964 /* Indirectly call WSASend */
2965 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof( struct ws2_async, iovec[1] ))))
2967 SetLastError(WSAEFAULT);
2969 else
2971 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)ov;
2972 iosb->u.Status = STATUS_PENDING;
2973 iosb->Information = 0;
2975 wsa->hSocket = SOCKET2HANDLE(s);
2976 wsa->addr = NULL;
2977 wsa->addrlen.val = 0;
2978 wsa->flags = 0;
2979 wsa->lpFlags = &wsa->flags;
2980 wsa->control = NULL;
2981 wsa->n_iovecs = sendBuf ? 1 : 0;
2982 wsa->first_iovec = 0;
2983 wsa->completion_func = NULL;
2984 wsa->iovec[0].iov_base = sendBuf;
2985 wsa->iovec[0].iov_len = sendBufLen;
2987 SERVER_START_REQ( register_async )
2989 req->type = ASYNC_TYPE_WRITE;
2990 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2991 req->async.callback = wine_server_client_ptr( WS2_async_send );
2992 req->async.iosb = wine_server_client_ptr( iosb );
2993 req->async.arg = wine_server_client_ptr( wsa );
2994 req->async.event = wine_server_obj_handle( ov->hEvent );
2995 req->async.cvalue = cvalue;
2996 status = wine_server_call( req );
2998 SERVER_END_REQ;
3000 if (status != STATUS_PENDING) HeapFree(GetProcessHeap(), 0, wsa);
3002 /* If the connect already failed */
3003 if (status == STATUS_PIPE_DISCONNECTED)
3004 status = _get_sock_error(s, FD_CONNECT_BIT);
3005 SetLastError( NtStatusToWSAError(status) );
3008 else
3010 SetLastError(ret);
3013 release_sock_fd( s, fd );
3014 return FALSE;
3016 connection_success:
3017 release_sock_fd( s, fd );
3018 return TRUE;
3022 /***********************************************************************
3023 * getpeername (WS2_32.5)
3025 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
3027 int fd;
3028 int res;
3030 TRACE("socket %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
3032 fd = get_sock_fd( s, 0, NULL );
3033 res = SOCKET_ERROR;
3035 if (fd != -1)
3037 union generic_unix_sockaddr uaddr;
3038 socklen_t uaddrlen = sizeof(uaddr);
3040 if (getpeername(fd, &uaddr.addr, &uaddrlen) == 0)
3042 if (!name || !namelen)
3043 SetLastError(WSAEFAULT);
3044 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3045 /* The buffer was too small */
3046 SetLastError(WSAEFAULT);
3047 else
3049 res = 0;
3050 TRACE("=> %s\n", debugstr_sockaddr(name));
3053 else
3054 SetLastError(wsaErrno());
3055 release_sock_fd( s, fd );
3057 return res;
3060 /***********************************************************************
3061 * getsockname (WS2_32.6)
3063 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
3065 int fd;
3066 int res;
3068 TRACE("socket %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
3070 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
3071 if( (name == NULL) || (namelen == NULL) )
3073 SetLastError( WSAEFAULT );
3074 return SOCKET_ERROR;
3077 fd = get_sock_fd( s, 0, NULL );
3078 res = SOCKET_ERROR;
3080 if (fd != -1)
3082 union generic_unix_sockaddr uaddr;
3083 socklen_t uaddrlen = sizeof(uaddr);
3085 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
3087 SetLastError(wsaErrno());
3089 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
3091 SetLastError(WSAEINVAL);
3093 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3095 /* The buffer was too small */
3096 SetLastError(WSAEFAULT);
3098 else
3100 res=0;
3101 TRACE("=> %s\n", debugstr_sockaddr(name));
3103 release_sock_fd( s, fd );
3105 return res;
3108 /***********************************************************************
3109 * getsockopt (WS2_32.7)
3111 INT WINAPI WS_getsockopt(SOCKET s, INT level,
3112 INT optname, char *optval, INT *optlen)
3114 int fd;
3115 INT ret = 0;
3117 TRACE("socket %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
3118 s, level, optname, optval, optlen ? *optlen : 0);
3120 switch(level)
3122 case WS_SOL_SOCKET:
3124 switch(optname)
3126 /* Handle common cases. The special cases are below, sorted
3127 * alphabetically */
3128 case WS_SO_BROADCAST:
3129 case WS_SO_DEBUG:
3130 case WS_SO_ERROR:
3131 case WS_SO_KEEPALIVE:
3132 case WS_SO_OOBINLINE:
3133 case WS_SO_RCVBUF:
3134 case WS_SO_REUSEADDR:
3135 case WS_SO_SNDBUF:
3136 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3137 return SOCKET_ERROR;
3138 convert_sockopt(&level, &optname);
3139 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3141 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3142 ret = SOCKET_ERROR;
3144 release_sock_fd( s, fd );
3145 return ret;
3146 case WS_SO_ACCEPTCONN:
3147 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3148 return SOCKET_ERROR;
3149 if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, optval, (socklen_t *)optlen) != 0 )
3151 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3152 ret = SOCKET_ERROR;
3154 else
3156 /* BSD returns != 0 while Windows return exact == 1 */
3157 if (*(int *)optval) *(int *)optval = 1;
3159 release_sock_fd( s, fd );
3160 return ret;
3161 case WS_SO_BSP_STATE:
3163 int req_size, addr_size;
3164 WSAPROTOCOL_INFOW infow;
3165 CSADDR_INFO *csinfo;
3167 ret = ws_protocol_info(s, TRUE, &infow, &addr_size);
3168 if (ret)
3170 if (infow.iAddressFamily == WS_AF_INET)
3171 addr_size = sizeof(struct sockaddr_in);
3172 else if (infow.iAddressFamily == WS_AF_INET6)
3173 addr_size = sizeof(struct sockaddr_in6);
3174 else
3176 FIXME("Family %d is unsupported for SO_BSP_STATE\n", infow.iAddressFamily);
3177 SetLastError(WSAEAFNOSUPPORT);
3178 return SOCKET_ERROR;
3181 req_size = sizeof(CSADDR_INFO) + addr_size * 2;
3182 if (*optlen < req_size)
3184 ret = 0;
3185 SetLastError(WSAEFAULT);
3187 else
3189 union generic_unix_sockaddr uaddr;
3190 socklen_t uaddrlen = sizeof(uaddr);
3192 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3193 return SOCKET_ERROR;
3195 csinfo = (CSADDR_INFO*) optval;
3197 /* Check if the sock is bound */
3198 if (!getsockname(fd, &uaddr.addr, &uaddrlen) &&
3199 is_sockaddr_bound(&uaddr.addr, uaddrlen))
3201 csinfo->LocalAddr.lpSockaddr =
3202 (LPSOCKADDR) (optval + sizeof(CSADDR_INFO));
3203 ws_sockaddr_u2ws(&uaddr.addr, csinfo->LocalAddr.lpSockaddr, &addr_size);
3204 csinfo->LocalAddr.iSockaddrLength = addr_size;
3206 else
3208 csinfo->LocalAddr.lpSockaddr = NULL;
3209 csinfo->LocalAddr.iSockaddrLength = 0;
3212 /* Check if the sock is connected */
3213 if (!getpeername(fd, &uaddr.addr, &uaddrlen) &&
3214 is_sockaddr_bound(&uaddr.addr, uaddrlen))
3216 csinfo->RemoteAddr.lpSockaddr =
3217 (LPSOCKADDR) (optval + sizeof(CSADDR_INFO) + addr_size);
3218 ws_sockaddr_u2ws(&uaddr.addr, csinfo->RemoteAddr.lpSockaddr, &addr_size);
3219 csinfo->RemoteAddr.iSockaddrLength = addr_size;
3221 else
3223 csinfo->RemoteAddr.lpSockaddr = NULL;
3224 csinfo->RemoteAddr.iSockaddrLength = 0;
3227 csinfo->iSocketType = infow.iSocketType;
3228 csinfo->iProtocol = infow.iProtocol;
3229 release_sock_fd( s, fd );
3232 return ret ? 0 : SOCKET_ERROR;
3234 case WS_SO_DONTLINGER:
3236 struct linger lingval;
3237 socklen_t len = sizeof(struct linger);
3239 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
3241 SetLastError(WSAEFAULT);
3242 return SOCKET_ERROR;
3244 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3245 return SOCKET_ERROR;
3247 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
3249 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3250 ret = SOCKET_ERROR;
3252 else
3254 *(BOOL *)optval = !lingval.l_onoff;
3255 *optlen = sizeof(BOOL);
3258 release_sock_fd( s, fd );
3259 return ret;
3262 case WS_SO_CONNECT_TIME:
3264 static int pretendtime = 0;
3265 struct WS_sockaddr addr;
3266 int len = sizeof(addr);
3268 if (!optlen || *optlen < sizeof(DWORD) || !optval)
3270 SetLastError(WSAEFAULT);
3271 return SOCKET_ERROR;
3273 if (WS_getpeername(s, &addr, &len) == SOCKET_ERROR)
3274 *(DWORD *)optval = ~0u;
3275 else
3277 if (!pretendtime) FIXME("WS_SO_CONNECT_TIME - faking results\n");
3278 *(DWORD *)optval = pretendtime++;
3280 *optlen = sizeof(DWORD);
3281 return ret;
3283 /* As mentioned in setsockopt, Windows ignores this, so we
3284 * always return true here */
3285 case WS_SO_DONTROUTE:
3286 if (!optlen || *optlen < sizeof(BOOL) || !optval)
3288 SetLastError(WSAEFAULT);
3289 return SOCKET_ERROR;
3291 *(BOOL *)optval = TRUE;
3292 *optlen = sizeof(BOOL);
3293 return 0;
3295 case WS_SO_LINGER:
3297 struct linger lingval;
3298 int so_type;
3299 socklen_t len = sizeof(struct linger), slen = sizeof(int);
3301 /* struct linger and LINGER have different sizes */
3302 if (!optlen || *optlen < sizeof(LINGER) || !optval)
3304 SetLastError(WSAEFAULT);
3305 return SOCKET_ERROR;
3307 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3308 return SOCKET_ERROR;
3310 if ((getsockopt(fd, SOL_SOCKET, SO_TYPE, &so_type, &slen) == 0 && so_type == SOCK_DGRAM))
3312 SetLastError(WSAENOPROTOOPT);
3313 ret = SOCKET_ERROR;
3315 else if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0)
3317 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3318 ret = SOCKET_ERROR;
3320 else
3322 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
3323 ((LINGER *)optval)->l_linger = lingval.l_linger;
3324 *optlen = sizeof(struct linger);
3327 release_sock_fd( s, fd );
3328 return ret;
3331 case WS_SO_MAX_MSG_SIZE:
3332 if (!optlen || *optlen < sizeof(int) || !optval)
3334 SetLastError(WSAEFAULT);
3335 return SOCKET_ERROR;
3337 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
3338 *(int *)optval = 65507;
3339 *optlen = sizeof(int);
3340 return 0;
3342 /* SO_OPENTYPE does not require a valid socket handle. */
3343 case WS_SO_OPENTYPE:
3344 if (!optlen || *optlen < sizeof(int) || !optval)
3346 SetLastError(WSAEFAULT);
3347 return SOCKET_ERROR;
3349 *(int *)optval = get_per_thread_data()->opentype;
3350 *optlen = sizeof(int);
3351 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
3352 return 0;
3353 case WS_SO_PROTOCOL_INFOA:
3354 case WS_SO_PROTOCOL_INFOW:
3356 int size;
3357 WSAPROTOCOL_INFOW infow;
3359 ret = ws_protocol_info(s, optname == WS_SO_PROTOCOL_INFOW, &infow, &size);
3360 if (ret)
3362 if (!optlen || !optval || *optlen < size)
3364 if(optlen) *optlen = size;
3365 ret = 0;
3366 SetLastError(WSAEFAULT);
3368 else
3369 memcpy(optval, &infow, size);
3371 return ret ? 0 : SOCKET_ERROR;
3373 #ifdef SO_RCVTIMEO
3374 case WS_SO_RCVTIMEO:
3375 #endif
3376 #ifdef SO_SNDTIMEO
3377 case WS_SO_SNDTIMEO:
3378 #endif
3379 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
3381 struct timeval tv;
3382 socklen_t len = sizeof(struct timeval);
3384 if (!optlen || *optlen < sizeof(int)|| !optval)
3386 SetLastError(WSAEFAULT);
3387 return SOCKET_ERROR;
3389 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3390 return SOCKET_ERROR;
3392 convert_sockopt(&level, &optname);
3393 if (getsockopt(fd, level, optname, &tv, &len) != 0 )
3395 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3396 ret = SOCKET_ERROR;
3398 else
3400 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
3401 *optlen = sizeof(int);
3404 release_sock_fd( s, fd );
3405 return ret;
3407 #endif
3408 case WS_SO_TYPE:
3410 if (!optlen || *optlen < sizeof(int) || !optval)
3412 SetLastError(WSAEFAULT);
3413 return SOCKET_ERROR;
3415 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3416 return SOCKET_ERROR;
3418 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, optval, (socklen_t *)optlen) != 0 )
3420 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3421 ret = SOCKET_ERROR;
3423 else
3424 (*(int *)optval) = convert_socktype_u2w(*(int *)optval);
3426 release_sock_fd( s, fd );
3427 return ret;
3429 default:
3430 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
3431 SetLastError(WSAENOPROTOOPT);
3432 return SOCKET_ERROR;
3433 } /* end switch(optname) */
3434 }/* end case WS_SOL_SOCKET */
3435 #ifdef HAS_IPX
3436 case WS_NSPROTO_IPX:
3438 struct WS_sockaddr_ipx addr;
3439 IPX_ADDRESS_DATA *data;
3440 int namelen;
3441 switch(optname)
3443 case WS_IPX_PTYPE:
3444 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3445 #ifdef SOL_IPX
3446 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (socklen_t *)optlen) == -1)
3448 ret = SOCKET_ERROR;
3450 #else
3452 struct ipx val;
3453 socklen_t len=sizeof(struct ipx);
3454 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
3455 ret = SOCKET_ERROR;
3456 else
3457 *optval = (int)val.ipx_pt;
3459 #endif
3460 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
3461 release_sock_fd( s, fd );
3462 return ret;
3464 case WS_IPX_ADDRESS:
3466 * On a Win2000 system with one network card there are usually
3467 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
3468 * Using this call you can then retrieve info about this all.
3469 * In case of Linux it is a bit different. Usually you have
3470 * only "one" device active and further it is not possible to
3471 * query things like the linkspeed.
3473 FIXME("IPX_ADDRESS\n");
3474 namelen = sizeof(struct WS_sockaddr_ipx);
3475 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
3476 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
3478 data = (IPX_ADDRESS_DATA*)optval;
3479 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
3480 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
3481 data->adapternum = 0;
3482 data->wan = FALSE; /* We are not on a wan for now .. */
3483 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
3484 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
3485 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
3486 * note 1MB = 1000kB in this case */
3487 return 0;
3489 case WS_IPX_MAX_ADAPTER_NUM:
3490 FIXME("IPX_MAX_ADAPTER_NUM\n");
3491 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
3492 return 0;
3494 default:
3495 FIXME("IPX optname:%x\n", optname);
3496 return SOCKET_ERROR;
3497 }/* end switch(optname) */
3498 } /* end case WS_NSPROTO_IPX */
3499 #endif
3501 #ifdef HAS_IRDA
3502 #define MAX_IRDA_DEVICES 10
3504 case WS_SOL_IRLMP:
3505 switch(optname)
3507 case WS_IRLMP_ENUMDEVICES:
3509 char buf[sizeof(struct irda_device_list) +
3510 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
3511 int res;
3512 socklen_t len = sizeof(buf);
3514 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3515 return SOCKET_ERROR;
3516 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
3517 release_sock_fd( s, fd );
3518 if (res < 0)
3520 SetLastError(wsaErrno());
3521 return SOCKET_ERROR;
3523 else
3525 struct irda_device_list *src = (struct irda_device_list *)buf;
3526 DEVICELIST *dst = (DEVICELIST *)optval;
3527 INT needed = sizeof(DEVICELIST);
3528 unsigned int i;
3530 if (src->len > 0)
3531 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
3532 if (*optlen < needed)
3534 SetLastError(WSAEFAULT);
3535 return SOCKET_ERROR;
3537 *optlen = needed;
3538 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
3539 dst->numDevice = src->len;
3540 for (i = 0; i < src->len; i++)
3542 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
3543 src->dev[i].saddr, src->dev[i].daddr,
3544 src->dev[i].info, src->dev[i].hints[0],
3545 src->dev[i].hints[1]);
3546 memcpy( dst->Device[i].irdaDeviceID,
3547 &src->dev[i].daddr,
3548 sizeof(dst->Device[i].irdaDeviceID) ) ;
3549 memcpy( dst->Device[i].irdaDeviceName,
3550 src->dev[i].info,
3551 sizeof(dst->Device[i].irdaDeviceName) ) ;
3552 memcpy( &dst->Device[i].irdaDeviceHints1,
3553 &src->dev[i].hints[0],
3554 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
3555 memcpy( &dst->Device[i].irdaDeviceHints2,
3556 &src->dev[i].hints[1],
3557 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
3558 dst->Device[i].irdaCharSet = src->dev[i].charset;
3560 return 0;
3563 default:
3564 FIXME("IrDA optname:0x%x\n", optname);
3565 return SOCKET_ERROR;
3567 break; /* case WS_SOL_IRLMP */
3568 #undef MAX_IRDA_DEVICES
3569 #endif
3571 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3572 case WS_IPPROTO_TCP:
3573 switch(optname)
3575 case WS_TCP_NODELAY:
3576 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3577 return SOCKET_ERROR;
3578 convert_sockopt(&level, &optname);
3579 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3581 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3582 ret = SOCKET_ERROR;
3584 release_sock_fd( s, fd );
3585 return ret;
3587 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
3588 return SOCKET_ERROR;
3590 case WS_IPPROTO_IP:
3591 switch(optname)
3593 case WS_IP_ADD_MEMBERSHIP:
3594 case WS_IP_DROP_MEMBERSHIP:
3595 #ifdef IP_HDRINCL
3596 case WS_IP_HDRINCL:
3597 #endif
3598 case WS_IP_MULTICAST_IF:
3599 case WS_IP_MULTICAST_LOOP:
3600 case WS_IP_MULTICAST_TTL:
3601 case WS_IP_OPTIONS:
3602 #ifdef IP_PKTINFO
3603 case WS_IP_PKTINFO:
3604 #endif
3605 case WS_IP_TOS:
3606 case WS_IP_TTL:
3607 #ifdef IP_UNICAST_IF
3608 case WS_IP_UNICAST_IF:
3609 #endif
3610 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3611 return SOCKET_ERROR;
3612 convert_sockopt(&level, &optname);
3613 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3615 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3616 ret = SOCKET_ERROR;
3618 release_sock_fd( s, fd );
3619 return ret;
3620 case WS_IP_DONTFRAGMENT:
3621 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
3622 *(BOOL*)optval = FALSE;
3623 return 0;
3625 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
3626 return SOCKET_ERROR;
3628 case WS_IPPROTO_IPV6:
3629 switch(optname)
3631 #ifdef IPV6_ADD_MEMBERSHIP
3632 case WS_IPV6_ADD_MEMBERSHIP:
3633 #endif
3634 #ifdef IPV6_DROP_MEMBERSHIP
3635 case WS_IPV6_DROP_MEMBERSHIP:
3636 #endif
3637 case WS_IPV6_MULTICAST_IF:
3638 case WS_IPV6_MULTICAST_HOPS:
3639 case WS_IPV6_MULTICAST_LOOP:
3640 case WS_IPV6_UNICAST_HOPS:
3641 case WS_IPV6_V6ONLY:
3642 #ifdef IPV6_UNICAST_IF
3643 case WS_IPV6_UNICAST_IF:
3644 #endif
3645 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3646 return SOCKET_ERROR;
3647 convert_sockopt(&level, &optname);
3648 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3650 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3651 ret = SOCKET_ERROR;
3653 release_sock_fd( s, fd );
3654 return ret;
3655 case WS_IPV6_DONTFRAG:
3656 FIXME("WS_IPV6_DONTFRAG is always false!\n");
3657 *(BOOL*)optval = FALSE;
3658 return 0;
3660 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
3661 return SOCKET_ERROR;
3663 default:
3664 WARN("Unknown level: 0x%08x\n", level);
3665 SetLastError(WSAEINVAL);
3666 return SOCKET_ERROR;
3667 } /* end switch(level) */
3670 /***********************************************************************
3671 * htonl (WS2_32.8)
3673 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
3675 return htonl(hostlong);
3679 /***********************************************************************
3680 * htons (WS2_32.9)
3682 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
3684 return htons(hostshort);
3687 /***********************************************************************
3688 * WSAHtonl (WS2_32.46)
3689 * From MSDN description of error codes, this function should also
3690 * check if WinSock has been initialized and the socket is a valid
3691 * socket. But why? This function only translates a host byte order
3692 * u_long into a network byte order u_long...
3694 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
3696 if (lpnetlong)
3698 *lpnetlong = htonl(hostlong);
3699 return 0;
3701 SetLastError(WSAEFAULT);
3702 return SOCKET_ERROR;
3705 /***********************************************************************
3706 * WSAHtons (WS2_32.47)
3707 * From MSDN description of error codes, this function should also
3708 * check if WinSock has been initialized and the socket is a valid
3709 * socket. But why? This function only translates a host byte order
3710 * u_short into a network byte order u_short...
3712 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
3715 if (lpnetshort)
3717 *lpnetshort = htons(hostshort);
3718 return 0;
3720 SetLastError(WSAEFAULT);
3721 return SOCKET_ERROR;
3725 /***********************************************************************
3726 * inet_addr (WS2_32.11)
3728 WS_u_long WINAPI WS_inet_addr(const char *cp)
3730 if (!cp) return INADDR_NONE;
3731 return inet_addr(cp);
3735 /***********************************************************************
3736 * ntohl (WS2_32.14)
3738 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
3740 return ntohl(netlong);
3744 /***********************************************************************
3745 * ntohs (WS2_32.15)
3747 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
3749 return ntohs(netshort);
3753 /***********************************************************************
3754 * inet_ntoa (WS2_32.12)
3756 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
3758 char* s = inet_ntoa(*((struct in_addr*)&in));
3759 if( s )
3761 struct per_thread_data *data = get_per_thread_data();
3762 strcpy(data->ntoa_buffer, s);
3763 return data->ntoa_buffer;
3765 SetLastError(wsaErrno());
3766 return NULL;
3769 static const char *debugstr_wsaioctl(DWORD ioctl)
3771 const char *buf_type, *family;
3773 switch(ioctl & 0x18000000)
3775 case WS_IOC_WS2:
3776 family = "IOC_WS2";
3777 break;
3778 case WS_IOC_PROTOCOL:
3779 family = "IOC_PROTOCOL";
3780 break;
3781 case WS_IOC_VENDOR:
3782 family = "IOC_VENDOR";
3783 break;
3784 default: /* WS_IOC_UNIX */
3786 BYTE size = (ioctl >> 16) & WS_IOCPARM_MASK;
3787 char x = (ioctl & 0xff00) >> 8;
3788 BYTE y = ioctl & 0xff;
3789 char args[14];
3791 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3793 case WS_IOC_VOID:
3794 buf_type = "_IO";
3795 sprintf(args, "%d, %d", x, y);
3796 break;
3797 case WS_IOC_IN:
3798 buf_type = "_IOW";
3799 sprintf(args, "'%c', %d, %d", x, y, size);
3800 break;
3801 case WS_IOC_OUT:
3802 buf_type = "_IOR";
3803 sprintf(args, "'%c', %d, %d", x, y, size);
3804 break;
3805 default:
3806 buf_type = "?";
3807 sprintf(args, "'%c', %d, %d", x, y, size);
3808 break;
3810 return wine_dbg_sprintf("%s(%s)", buf_type, args);
3814 /* We are different from WS_IOC_UNIX. */
3815 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3817 case WS_IOC_VOID:
3818 buf_type = "_WSAIO";
3819 break;
3820 case WS_IOC_INOUT:
3821 buf_type = "_WSAIORW";
3822 break;
3823 case WS_IOC_IN:
3824 buf_type = "_WSAIOW";
3825 break;
3826 case WS_IOC_OUT:
3827 buf_type = "_WSAIOR";
3828 break;
3829 default:
3830 buf_type = "?";
3831 break;
3834 return wine_dbg_sprintf("%s(%s, %d)", buf_type, family,
3835 (USHORT)(ioctl & 0xffff));
3838 /* do an ioctl call through the server */
3839 static DWORD server_ioctl_sock( SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size,
3840 LPVOID out_buff, DWORD out_size, LPDWORD ret_size,
3841 LPWSAOVERLAPPED overlapped,
3842 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
3844 HANDLE event = overlapped ? overlapped->hEvent : 0;
3845 HANDLE handle = SOCKET2HANDLE( s );
3846 struct ws2_async *wsa;
3847 NTSTATUS status;
3848 PIO_STATUS_BLOCK io;
3850 if (!(wsa = (struct ws2_async *)alloc_async_io( sizeof(*wsa) )))
3851 return WSA_NOT_ENOUGH_MEMORY;
3852 wsa->hSocket = handle;
3853 wsa->user_overlapped = overlapped;
3854 wsa->completion_func = completion;
3855 io = (overlapped ? (PIO_STATUS_BLOCK)overlapped : &wsa->local_iosb);
3857 status = NtDeviceIoControlFile( handle, event, ws2_async_apc, wsa, io, code,
3858 in_buff, in_size, out_buff, out_size );
3859 if (status == STATUS_NOT_SUPPORTED)
3861 FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
3862 code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
3864 else if (status == STATUS_SUCCESS)
3865 *ret_size = io->Information; /* "Information" is the size written to the output buffer */
3867 if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, wsa );
3869 return NtStatusToWSAError( status );
3872 /**********************************************************************
3873 * WSAIoctl (WS2_32.50)
3876 INT WINAPI WSAIoctl(SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size, LPVOID out_buff,
3877 DWORD out_size, LPDWORD ret_size, LPWSAOVERLAPPED overlapped,
3878 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
3880 int fd;
3881 DWORD status = 0, total = 0;
3883 TRACE("%04lx, %s, %p, %d, %p, %d, %p, %p, %p\n",
3884 s, debugstr_wsaioctl(code), in_buff, in_size, out_buff, out_size, ret_size, overlapped, completion);
3886 switch (code)
3888 case WS_FIONBIO:
3889 if (in_size != sizeof(WS_u_long) || IS_INTRESOURCE(in_buff))
3891 SetLastError(WSAEFAULT);
3892 return SOCKET_ERROR;
3894 TRACE("-> FIONBIO (%x)\n", *(WS_u_long*)in_buff);
3895 if (_get_sock_mask(s))
3897 /* AsyncSelect()'ed sockets are always nonblocking */
3898 if (!*(WS_u_long *)in_buff) status = WSAEINVAL;
3899 break;
3901 if (*(WS_u_long *)in_buff)
3902 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
3903 else
3904 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
3905 break;
3907 case WS_FIONREAD:
3909 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
3911 SetLastError(WSAEFAULT);
3912 return SOCKET_ERROR;
3914 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3915 if (ioctl(fd, FIONREAD, out_buff ) == -1)
3916 status = (errno == EBADF) ? WSAENOTSOCK : wsaErrno();
3917 release_sock_fd( s, fd );
3918 break;
3921 case WS_SIOCATMARK:
3923 unsigned int oob = 0, atmark = 0;
3924 socklen_t oobsize = sizeof(int);
3925 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
3927 SetLastError(WSAEFAULT);
3928 return SOCKET_ERROR;
3930 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3931 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
3932 if ((getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &oob, &oobsize ) == -1)
3933 || (!oob && ioctl(fd, SIOCATMARK, &atmark ) == -1))
3934 status = (errno == EBADF) ? WSAENOTSOCK : wsaErrno();
3935 else
3937 /* The SIOCATMARK value read from ioctl() is reversed
3938 * because BSD returns TRUE if it's in the OOB mark
3939 * while Windows returns TRUE if there are NO OOB bytes.
3941 (*(WS_u_long *) out_buff) = oob || !atmark;
3944 release_sock_fd( s, fd );
3945 break;
3948 case WS_FIOASYNC:
3949 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
3950 SetLastError(WSAEINVAL);
3951 return SOCKET_ERROR;
3953 case WS_SIO_GET_INTERFACE_LIST:
3955 INTERFACE_INFO* intArray = out_buff;
3956 DWORD size, numInt = 0, apiReturn;
3958 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
3960 if (!out_buff || !ret_size)
3962 SetLastError(WSAEFAULT);
3963 return SOCKET_ERROR;
3966 fd = get_sock_fd( s, 0, NULL );
3967 if (fd == -1) return SOCKET_ERROR;
3969 apiReturn = GetAdaptersInfo(NULL, &size);
3970 if (apiReturn == ERROR_BUFFER_OVERFLOW)
3972 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
3974 if (table)
3976 if (GetAdaptersInfo(table, &size) == NO_ERROR)
3978 PIP_ADAPTER_INFO ptr;
3980 for (ptr = table, numInt = 0; ptr; ptr = ptr->Next)
3982 unsigned int addr, mask, bcast;
3983 struct ifreq ifInfo;
3985 /* Skip interfaces without an IPv4 address. */
3986 if (ptr->IpAddressList.IpAddress.String[0] == '\0')
3987 continue;
3989 if ((numInt + 1)*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > out_size)
3991 WARN("Buffer too small = %u, out_size = %u\n", numInt + 1, out_size);
3992 status = WSAEFAULT;
3993 break;
3996 /* Socket Status Flags */
3997 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
3998 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
4000 ERR("Error obtaining status flags for socket!\n");
4001 status = WSAEINVAL;
4002 break;
4004 else
4006 /* set flags; the values of IFF_* are not the same
4007 under Linux and Windows, therefore must generate
4008 new flags */
4009 intArray->iiFlags = 0;
4010 if (ifInfo.ifr_flags & IFF_BROADCAST)
4011 intArray->iiFlags |= WS_IFF_BROADCAST;
4012 #ifdef IFF_POINTOPOINT
4013 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
4014 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
4015 #endif
4016 if (ifInfo.ifr_flags & IFF_LOOPBACK)
4017 intArray->iiFlags |= WS_IFF_LOOPBACK;
4018 if (ifInfo.ifr_flags & IFF_UP)
4019 intArray->iiFlags |= WS_IFF_UP;
4020 if (ifInfo.ifr_flags & IFF_MULTICAST)
4021 intArray->iiFlags |= WS_IFF_MULTICAST;
4024 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
4025 mask = inet_addr(ptr->IpAddressList.IpMask.String);
4026 bcast = addr | ~mask;
4027 intArray->iiAddress.AddressIn.sin_family = AF_INET;
4028 intArray->iiAddress.AddressIn.sin_port = 0;
4029 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
4030 addr;
4031 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
4032 intArray->iiNetmask.AddressIn.sin_port = 0;
4033 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
4034 mask;
4035 intArray->iiBroadcastAddress.AddressIn.sin_family =
4036 AF_INET;
4037 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
4038 intArray->iiBroadcastAddress.AddressIn.sin_addr.
4039 WS_s_addr = bcast;
4040 intArray++;
4041 numInt++;
4044 else
4046 ERR("Unable to get interface table!\n");
4047 status = WSAEINVAL;
4049 HeapFree(GetProcessHeap(),0,table);
4051 else status = WSAEINVAL;
4053 else if (apiReturn != ERROR_NO_DATA)
4055 ERR("Unable to get interface table!\n");
4056 status = WSAEINVAL;
4058 /* Calculate the size of the array being returned */
4059 total = sizeof(INTERFACE_INFO) * numInt;
4060 release_sock_fd( s, fd );
4061 break;
4064 case WS_SIO_ADDRESS_LIST_QUERY:
4066 DWORD size;
4068 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
4070 if (!ret_size)
4072 SetLastError(WSAEFAULT);
4073 return SOCKET_ERROR;
4076 if (out_size && out_size < FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[0]))
4078 *ret_size = 0;
4079 SetLastError(WSAEINVAL);
4080 return SOCKET_ERROR;
4083 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
4085 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
4086 SOCKET_ADDRESS_LIST *sa_list;
4087 SOCKADDR_IN *sockaddr;
4088 SOCKET_ADDRESS *sa;
4089 unsigned int i;
4090 DWORD num;
4092 if (!table || GetAdaptersInfo(table, &size))
4094 HeapFree(GetProcessHeap(), 0, table);
4095 status = WSAEINVAL;
4096 break;
4099 for (p = table, num = 0; p; p = p->Next)
4100 if (p->IpAddressList.IpAddress.String[0]) num++;
4102 total = FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[num]) + num * sizeof(*sockaddr);
4103 if (total > out_size || !out_buff)
4105 *ret_size = total;
4106 HeapFree(GetProcessHeap(), 0, table);
4107 status = WSAEFAULT;
4108 break;
4111 sa_list = out_buff;
4112 sa = sa_list->Address;
4113 sockaddr = (SOCKADDR_IN *)&sa[num];
4114 sa_list->iAddressCount = num;
4116 for (p = table, i = 0; p; p = p->Next)
4118 if (!p->IpAddressList.IpAddress.String[0]) continue;
4120 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
4121 sa[i].iSockaddrLength = sizeof(SOCKADDR);
4123 sockaddr[i].sin_family = AF_INET;
4124 sockaddr[i].sin_port = 0;
4125 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
4126 i++;
4129 HeapFree(GetProcessHeap(), 0, table);
4131 else
4133 WARN("unable to get IP address list\n");
4134 status = WSAEINVAL;
4136 break;
4139 case WS_SIO_FLUSH:
4140 FIXME("SIO_FLUSH: stub.\n");
4141 break;
4143 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
4145 static const GUID connectex_guid = WSAID_CONNECTEX;
4146 static const GUID disconnectex_guid = WSAID_DISCONNECTEX;
4147 static const GUID acceptex_guid = WSAID_ACCEPTEX;
4148 static const GUID getaccepexsockaddrs_guid = WSAID_GETACCEPTEXSOCKADDRS;
4149 static const GUID transmitfile_guid = WSAID_TRANSMITFILE;
4150 static const GUID transmitpackets_guid = WSAID_TRANSMITPACKETS;
4151 static const GUID wsarecvmsg_guid = WSAID_WSARECVMSG;
4152 static const GUID wsasendmsg_guid = WSAID_WSASENDMSG;
4154 if ( IsEqualGUID(&connectex_guid, in_buff) )
4156 *(LPFN_CONNECTEX *)out_buff = WS2_ConnectEx;
4157 break;
4159 else if ( IsEqualGUID(&disconnectex_guid, in_buff) )
4161 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented DisconnectEx\n");
4163 else if ( IsEqualGUID(&acceptex_guid, in_buff) )
4165 *(LPFN_ACCEPTEX *)out_buff = WS2_AcceptEx;
4166 break;
4168 else if ( IsEqualGUID(&getaccepexsockaddrs_guid, in_buff) )
4170 *(LPFN_GETACCEPTEXSOCKADDRS *)out_buff = WS2_GetAcceptExSockaddrs;
4171 break;
4173 else if ( IsEqualGUID(&transmitfile_guid, in_buff) )
4175 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitFile\n");
4177 else if ( IsEqualGUID(&transmitpackets_guid, in_buff) )
4179 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitPackets\n");
4181 else if ( IsEqualGUID(&wsarecvmsg_guid, in_buff) )
4183 *(LPFN_WSARECVMSG *)out_buff = WS2_WSARecvMsg;
4184 break;
4186 else if ( IsEqualGUID(&wsasendmsg_guid, in_buff) )
4188 *(LPFN_WSASENDMSG *)out_buff = WSASendMsg;
4189 break;
4191 else
4192 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff));
4194 status = WSAEOPNOTSUPP;
4195 break;
4197 case WS_SIO_KEEPALIVE_VALS:
4199 struct tcp_keepalive *k;
4200 int keepalive, keepidle, keepintvl;
4202 if (!in_buff || in_size < sizeof(struct tcp_keepalive))
4204 SetLastError(WSAEFAULT);
4205 return SOCKET_ERROR;
4208 k = in_buff;
4209 keepalive = k->onoff ? 1 : 0;
4210 keepidle = max( 1, (k->keepalivetime + 500) / 1000 );
4211 keepintvl = max( 1, (k->keepaliveinterval + 500) / 1000 );
4213 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
4215 fd = get_sock_fd(s, 0, NULL);
4216 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
4217 status = WSAEINVAL;
4218 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
4219 /* these values need to be set only if SO_KEEPALIVE is enabled */
4220 else if(keepalive)
4222 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
4223 status = WSAEINVAL;
4224 else if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
4225 status = WSAEINVAL;
4227 #else
4228 else
4229 FIXME("ignoring keepalive interval and timeout\n");
4230 #endif
4231 release_sock_fd(s, fd);
4232 break;
4234 case WS_SIO_ROUTING_INTERFACE_QUERY:
4236 struct WS_sockaddr *daddr = (struct WS_sockaddr *)in_buff;
4237 struct WS_sockaddr_in *daddr_in = (struct WS_sockaddr_in *)daddr;
4238 struct WS_sockaddr_in *saddr_in = out_buff;
4239 MIB_IPFORWARDROW row;
4240 PMIB_IPADDRTABLE ipAddrTable = NULL;
4241 DWORD size, i, found_index;
4243 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
4245 if (!in_buff || in_size < sizeof(struct WS_sockaddr) ||
4246 !out_buff || out_size < sizeof(struct WS_sockaddr_in) || !ret_size)
4248 SetLastError(WSAEFAULT);
4249 return SOCKET_ERROR;
4251 if (daddr->sa_family != AF_INET)
4253 FIXME("unsupported address family %d\n", daddr->sa_family);
4254 status = WSAEAFNOSUPPORT;
4255 break;
4257 if (GetBestRoute(daddr_in->sin_addr.S_un.S_addr, 0, &row) != NOERROR ||
4258 GetIpAddrTable(NULL, &size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
4260 status = WSAEFAULT;
4261 break;
4263 ipAddrTable = HeapAlloc(GetProcessHeap(), 0, size);
4264 if (GetIpAddrTable(ipAddrTable, &size, FALSE))
4266 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4267 status = WSAEFAULT;
4268 break;
4270 for (i = 0, found_index = ipAddrTable->dwNumEntries;
4271 i < ipAddrTable->dwNumEntries; i++)
4273 if (ipAddrTable->table[i].dwIndex == row.dwForwardIfIndex)
4274 found_index = i;
4276 if (found_index == ipAddrTable->dwNumEntries)
4278 ERR("no matching IP address for interface %d\n",
4279 row.dwForwardIfIndex);
4280 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4281 status = WSAEFAULT;
4282 break;
4284 saddr_in->sin_family = AF_INET;
4285 saddr_in->sin_addr.S_un.S_addr = ipAddrTable->table[found_index].dwAddr;
4286 saddr_in->sin_port = 0;
4287 total = sizeof(struct WS_sockaddr_in);
4288 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4289 break;
4291 case WS_SIO_SET_COMPATIBILITY_MODE:
4292 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
4293 status = WSAEOPNOTSUPP;
4294 break;
4295 case WS_SIO_UDP_CONNRESET:
4296 FIXME("WS_SIO_UDP_CONNRESET stub\n");
4297 break;
4298 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
4299 SetLastError(WSAEOPNOTSUPP);
4300 return SOCKET_ERROR;
4301 default:
4302 status = WSAEOPNOTSUPP;
4303 break;
4306 if (status == WSAEOPNOTSUPP)
4308 status = server_ioctl_sock(s, code, in_buff, in_size, out_buff, out_size, &total,
4309 overlapped, completion);
4310 if (status != WSAEOPNOTSUPP)
4312 if (status == 0 || status == WSA_IO_PENDING)
4313 TRACE("-> %s request\n", debugstr_wsaioctl(code));
4314 else
4315 ERR("-> %s request failed with status 0x%x\n", debugstr_wsaioctl(code), status);
4317 /* overlapped and completion operations will be handled by the server */
4318 completion = NULL;
4319 overlapped = NULL;
4321 else
4322 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code));
4325 if (completion)
4327 FIXME( "completion routine %p not supported\n", completion );
4329 else if (overlapped)
4331 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
4332 overlapped->Internal = status;
4333 overlapped->InternalHigh = total;
4334 if (overlapped->hEvent) NtSetEvent( overlapped->hEvent, NULL );
4335 if (cvalue) WS_AddCompletion( HANDLE2SOCKET(s), cvalue, status, total );
4338 if (!status)
4340 if (ret_size) *ret_size = total;
4341 return 0;
4343 SetLastError( status );
4344 return SOCKET_ERROR;
4348 /***********************************************************************
4349 * ioctlsocket (WS2_32.10)
4351 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
4353 DWORD ret_size;
4354 return WSAIoctl( s, cmd, argp, sizeof(WS_u_long), argp, sizeof(WS_u_long), &ret_size, NULL, NULL );
4357 /***********************************************************************
4358 * listen (WS2_32.13)
4360 int WINAPI WS_listen(SOCKET s, int backlog)
4362 int fd = get_sock_fd( s, FILE_READ_DATA, NULL ), ret = SOCKET_ERROR;
4364 TRACE("socket %04lx, backlog %d\n", s, backlog);
4365 if (fd != -1)
4367 union generic_unix_sockaddr uaddr;
4368 socklen_t uaddrlen = sizeof(uaddr);
4370 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
4372 SetLastError(wsaErrno());
4374 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
4376 SetLastError(WSAEINVAL);
4378 else if (listen(fd, backlog) == 0)
4380 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
4381 FD_WINE_LISTENING,
4382 FD_CONNECT|FD_WINE_CONNECTED);
4383 ret = 0;
4385 else
4386 SetLastError(wsaErrno());
4387 release_sock_fd( s, fd );
4389 else
4390 SetLastError(WSAENOTSOCK);
4391 return ret;
4394 /***********************************************************************
4395 * recv (WS2_32.16)
4397 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
4399 DWORD n, dwFlags = flags;
4400 WSABUF wsabuf;
4402 wsabuf.len = len;
4403 wsabuf.buf = buf;
4405 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
4406 return SOCKET_ERROR;
4407 else
4408 return n;
4411 /***********************************************************************
4412 * recvfrom (WS2_32.17)
4414 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
4415 struct WS_sockaddr *from, int *fromlen)
4417 DWORD n, dwFlags = flags;
4418 WSABUF wsabuf;
4420 wsabuf.len = len;
4421 wsabuf.buf = buf;
4423 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL, NULL) == SOCKET_ERROR )
4424 return SOCKET_ERROR;
4425 else
4426 return n;
4429 /* allocate a poll array for the corresponding fd sets */
4430 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
4431 const WS_fd_set *exceptfds, int *count_ptr )
4433 unsigned int i, j = 0, count = 0;
4434 struct pollfd *fds;
4436 if (readfds) count += readfds->fd_count;
4437 if (writefds) count += writefds->fd_count;
4438 if (exceptfds) count += exceptfds->fd_count;
4439 *count_ptr = count;
4440 if (!count)
4442 SetLastError(WSAEINVAL);
4443 return NULL;
4445 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0]))))
4447 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
4448 return NULL;
4450 if (readfds)
4451 for (i = 0; i < readfds->fd_count; i++, j++)
4453 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
4454 if (fds[j].fd == -1) goto failed;
4455 fds[j].events = POLLIN;
4456 fds[j].revents = 0;
4458 if (writefds)
4459 for (i = 0; i < writefds->fd_count; i++, j++)
4461 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
4462 if (fds[j].fd == -1) goto failed;
4463 fds[j].events = POLLOUT;
4464 fds[j].revents = 0;
4466 if (exceptfds)
4467 for (i = 0; i < exceptfds->fd_count; i++, j++)
4469 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
4470 if (fds[j].fd == -1) goto failed;
4471 fds[j].events = POLLHUP;
4472 fds[j].revents = 0;
4474 return fds;
4476 failed:
4477 count = j;
4478 j = 0;
4479 if (readfds)
4480 for (i = 0; i < readfds->fd_count && j < count; i++, j++)
4481 release_sock_fd( readfds->fd_array[i], fds[j].fd );
4482 if (writefds)
4483 for (i = 0; i < writefds->fd_count && j < count; i++, j++)
4484 release_sock_fd( writefds->fd_array[i], fds[j].fd );
4485 if (exceptfds)
4486 for (i = 0; i < exceptfds->fd_count && j < count; i++, j++)
4487 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
4488 HeapFree( GetProcessHeap(), 0, fds );
4489 return NULL;
4492 /* release the file descriptor obtained in fd_sets_to_poll */
4493 /* must be called with the original fd_set arrays, before calling get_poll_results */
4494 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
4495 const WS_fd_set *exceptfds, struct pollfd *fds )
4497 unsigned int i, j = 0;
4499 if (readfds)
4501 for (i = 0; i < readfds->fd_count; i++, j++)
4502 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
4504 if (writefds)
4506 for (i = 0; i < writefds->fd_count; i++, j++)
4507 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
4509 if (exceptfds)
4511 for (i = 0; i < exceptfds->fd_count; i++, j++)
4512 if (fds[j].fd != -1)
4514 /* make sure we have a real error before releasing the fd */
4515 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
4516 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
4521 /* map the poll results back into the Windows fd sets */
4522 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
4523 const struct pollfd *fds )
4525 const struct pollfd *poll_writefds = fds + (readfds ? readfds->fd_count : 0);
4526 const struct pollfd *poll_exceptfds = poll_writefds + (writefds ? writefds->fd_count : 0);
4527 unsigned int i, k, total = 0;
4529 if (readfds)
4531 for (i = k = 0; i < readfds->fd_count; i++)
4533 if (fds[i].revents ||
4534 (readfds == writefds && (poll_writefds[i].revents & POLLOUT) && !(poll_writefds[i].revents & POLLHUP)) ||
4535 (readfds == exceptfds && poll_exceptfds[i].revents))
4536 readfds->fd_array[k++] = readfds->fd_array[i];
4538 readfds->fd_count = k;
4539 total += k;
4541 if (writefds && writefds != readfds)
4543 for (i = k = 0; i < writefds->fd_count; i++)
4545 if (((poll_writefds[i].revents & POLLOUT) && !(poll_writefds[i].revents & POLLHUP)) ||
4546 (writefds == exceptfds && poll_exceptfds[i].revents))
4547 writefds->fd_array[k++] = writefds->fd_array[i];
4549 writefds->fd_count = k;
4550 total += k;
4552 if (exceptfds && exceptfds != readfds && exceptfds != writefds)
4554 for (i = k = 0; i < exceptfds->fd_count; i++)
4555 if (poll_exceptfds[i].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
4556 exceptfds->fd_count = k;
4557 total += k;
4559 return total;
4563 /***********************************************************************
4564 * select (WS2_32.18)
4566 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
4567 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
4568 const struct WS_timeval* ws_timeout)
4570 struct pollfd *pollfds;
4571 struct timeval tv1, tv2;
4572 int torig = 0;
4573 int count, ret, timeout = -1;
4575 TRACE("read %p, write %p, excp %p timeout %p\n",
4576 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
4578 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )))
4579 return SOCKET_ERROR;
4581 if (ws_timeout)
4583 torig = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
4584 timeout = torig;
4585 gettimeofday( &tv1, 0 );
4588 while ((ret = poll( pollfds, count, timeout )) < 0)
4590 if (errno == EINTR)
4592 if (!ws_timeout) continue;
4593 gettimeofday( &tv2, 0 );
4595 tv2.tv_sec -= tv1.tv_sec;
4596 tv2.tv_usec -= tv1.tv_usec;
4597 if (tv2.tv_usec < 0)
4599 tv2.tv_usec += 1000000;
4600 tv2.tv_sec -= 1;
4603 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
4604 if (timeout <= 0) break;
4605 } else break;
4607 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
4609 if (ret == -1) SetLastError(wsaErrno());
4610 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
4611 HeapFree( GetProcessHeap(), 0, pollfds );
4612 return ret;
4615 /* helper to send completion messages for client-only i/o operation case */
4616 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
4617 ULONG Information )
4619 SERVER_START_REQ( add_fd_completion )
4621 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
4622 req->cvalue = CompletionValue;
4623 req->status = CompletionStatus;
4624 req->information = Information;
4625 wine_server_call( req );
4627 SERVER_END_REQ;
4631 /***********************************************************************
4632 * send (WS2_32.19)
4634 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
4636 DWORD n;
4637 WSABUF wsabuf;
4639 wsabuf.len = len;
4640 wsabuf.buf = (char*) buf;
4642 if ( WS2_sendto( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
4643 return SOCKET_ERROR;
4644 else
4645 return n;
4648 /***********************************************************************
4649 * WSASend (WS2_32.72)
4651 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4652 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4653 LPWSAOVERLAPPED lpOverlapped,
4654 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4656 return WS2_sendto( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
4657 NULL, 0, lpOverlapped, lpCompletionRoutine );
4660 /***********************************************************************
4661 * WSASendDisconnect (WS2_32.73)
4663 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
4665 return WS_shutdown( s, SD_SEND );
4669 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4670 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4671 const struct WS_sockaddr *to, int tolen,
4672 LPWSAOVERLAPPED lpOverlapped,
4673 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4675 unsigned int i, options;
4676 int n, fd, err, overlapped;
4677 struct ws2_async *wsa = NULL, localwsa;
4678 int totalLength = 0;
4679 DWORD bytes_sent;
4680 BOOL is_blocking;
4682 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
4683 s, lpBuffers, dwBufferCount, dwFlags,
4684 to, tolen, lpOverlapped, lpCompletionRoutine);
4686 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
4687 TRACE( "fd=%d, options=%x\n", fd, options );
4689 if ( fd == -1 ) return SOCKET_ERROR;
4691 if (!lpOverlapped && !lpNumberOfBytesSent)
4693 err = WSAEFAULT;
4694 goto error;
4697 overlapped = (lpOverlapped || lpCompletionRoutine) &&
4698 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
4699 if (overlapped || dwBufferCount > 1)
4701 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[dwBufferCount]))))
4703 err = WSAEFAULT;
4704 goto error;
4707 else
4708 wsa = &localwsa;
4710 wsa->hSocket = SOCKET2HANDLE(s);
4711 wsa->addr = (struct WS_sockaddr *)to;
4712 wsa->addrlen.val = tolen;
4713 wsa->flags = dwFlags;
4714 wsa->lpFlags = &wsa->flags;
4715 wsa->control = NULL;
4716 wsa->n_iovecs = dwBufferCount;
4717 wsa->first_iovec = 0;
4718 for ( i = 0; i < dwBufferCount; i++ )
4720 wsa->iovec[i].iov_base = lpBuffers[i].buf;
4721 wsa->iovec[i].iov_len = lpBuffers[i].len;
4722 totalLength += lpBuffers[i].len;
4725 n = WS2_send( fd, wsa );
4726 if (n == -1 && errno != EAGAIN)
4728 err = wsaErrno();
4729 goto error;
4732 if (overlapped)
4734 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
4735 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
4737 wsa->user_overlapped = lpOverlapped;
4738 wsa->completion_func = lpCompletionRoutine;
4739 release_sock_fd( s, fd );
4741 if (n == -1 || n < totalLength)
4743 iosb->u.Status = STATUS_PENDING;
4744 iosb->Information = n == -1 ? 0 : n;
4746 SERVER_START_REQ( register_async )
4748 req->type = ASYNC_TYPE_WRITE;
4749 req->async.handle = wine_server_obj_handle( wsa->hSocket );
4750 req->async.callback = wine_server_client_ptr( WS2_async_send );
4751 req->async.iosb = wine_server_client_ptr( iosb );
4752 req->async.arg = wine_server_client_ptr( wsa );
4753 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
4754 req->async.cvalue = cvalue;
4755 err = wine_server_call( req );
4757 SERVER_END_REQ;
4759 /* Enable the event only after starting the async. The server will deliver it as soon as
4760 the async is done. */
4761 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
4763 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
4764 SetLastError(NtStatusToWSAError( err ));
4765 return SOCKET_ERROR;
4768 iosb->u.Status = STATUS_SUCCESS;
4769 iosb->Information = n;
4770 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = n;
4771 if (!wsa->completion_func)
4773 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
4774 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
4775 HeapFree( GetProcessHeap(), 0, wsa );
4777 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
4778 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
4779 SetLastError(ERROR_SUCCESS);
4780 return 0;
4783 if ((err = _is_blocking( s, &is_blocking )))
4785 err = NtStatusToWSAError( err );
4786 goto error;
4789 if ( is_blocking )
4791 /* On a blocking non-overlapped stream socket,
4792 * sending blocks until the entire buffer is sent. */
4793 DWORD timeout_start = GetTickCount();
4795 bytes_sent = n == -1 ? 0 : n;
4797 while (wsa->first_iovec < wsa->n_iovecs)
4799 struct pollfd pfd;
4800 int timeout = GET_SNDTIMEO(fd);
4802 if (timeout != -1)
4804 timeout -= GetTickCount() - timeout_start;
4805 if (timeout < 0) timeout = 0;
4808 pfd.fd = fd;
4809 pfd.events = POLLOUT;
4811 if (!timeout || !poll( &pfd, 1, timeout ))
4813 err = WSAETIMEDOUT;
4814 goto error; /* msdn says a timeout in send is fatal */
4817 n = WS2_send( fd, wsa );
4818 if (n == -1 && errno != EAGAIN)
4820 err = wsaErrno();
4821 goto error;
4824 if (n >= 0)
4825 bytes_sent += n;
4828 else /* non-blocking */
4830 if (n < totalLength)
4831 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
4832 if (n == -1)
4834 err = WSAEWOULDBLOCK;
4835 goto error;
4837 bytes_sent = n;
4840 TRACE(" -> %i bytes\n", bytes_sent);
4842 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = bytes_sent;
4843 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
4844 release_sock_fd( s, fd );
4845 SetLastError(ERROR_SUCCESS);
4846 return 0;
4848 error:
4849 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
4850 release_sock_fd( s, fd );
4851 WARN(" -> ERROR %d\n", err);
4852 SetLastError(err);
4853 return SOCKET_ERROR;
4856 /***********************************************************************
4857 * WSASendTo (WS2_32.74)
4859 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4860 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4861 const struct WS_sockaddr *to, int tolen,
4862 LPWSAOVERLAPPED lpOverlapped,
4863 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4865 return WS2_sendto( s, lpBuffers, dwBufferCount,
4866 lpNumberOfBytesSent, dwFlags,
4867 to, tolen,
4868 lpOverlapped, lpCompletionRoutine );
4871 /***********************************************************************
4872 * sendto (WS2_32.20)
4874 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
4875 const struct WS_sockaddr *to, int tolen)
4877 DWORD n;
4878 WSABUF wsabuf;
4880 wsabuf.len = len;
4881 wsabuf.buf = (char*) buf;
4883 if ( WS2_sendto(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
4884 return SOCKET_ERROR;
4885 else
4886 return n;
4889 /***********************************************************************
4890 * setsockopt (WS2_32.21)
4892 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
4893 const char *optval, int optlen)
4895 int fd;
4896 int woptval;
4897 struct linger linger;
4898 struct timeval tval;
4900 TRACE("socket %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
4901 s, level, optname, optval, optlen);
4903 /* some broken apps pass the value directly instead of a pointer to it */
4904 if(optlen && IS_INTRESOURCE(optval))
4906 SetLastError(WSAEFAULT);
4907 return SOCKET_ERROR;
4910 switch(level)
4912 case WS_SOL_SOCKET:
4913 switch(optname)
4915 /* Some options need some conversion before they can be sent to
4916 * setsockopt. The conversions are done here, then they will fall through
4917 * to the general case. Special options that are not passed to
4918 * setsockopt follow below that.*/
4920 case WS_SO_DONTLINGER:
4921 if (!optval)
4923 SetLastError(WSAEFAULT);
4924 return SOCKET_ERROR;
4926 linger.l_onoff = *(const int*)optval == 0;
4927 linger.l_linger = 0;
4928 level = SOL_SOCKET;
4929 optname = SO_LINGER;
4930 optval = (char*)&linger;
4931 optlen = sizeof(struct linger);
4932 break;
4934 case WS_SO_LINGER:
4935 if (!optval)
4937 SetLastError(WSAEFAULT);
4938 return SOCKET_ERROR;
4940 linger.l_onoff = ((LINGER*)optval)->l_onoff;
4941 linger.l_linger = ((LINGER*)optval)->l_linger;
4942 level = SOL_SOCKET;
4943 optname = SO_LINGER;
4944 optval = (char*)&linger;
4945 optlen = sizeof(struct linger);
4946 break;
4948 case WS_SO_RCVBUF:
4949 if (*(const int*)optval < 2048)
4951 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
4952 return 0;
4954 /* Fall through */
4956 /* The options listed here don't need any special handling. Thanks to
4957 * the conversion happening above, options from there will fall through
4958 * to this, too.*/
4959 case WS_SO_ACCEPTCONN:
4960 case WS_SO_BROADCAST:
4961 case WS_SO_ERROR:
4962 case WS_SO_KEEPALIVE:
4963 case WS_SO_OOBINLINE:
4964 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
4965 * however, using it the BSD way fixes bug 8513 and seems to be what
4966 * most programmers assume, anyway */
4967 case WS_SO_REUSEADDR:
4968 case WS_SO_SNDBUF:
4969 case WS_SO_TYPE:
4970 convert_sockopt(&level, &optname);
4971 break;
4973 /* SO_DEBUG is a privileged operation, ignore it. */
4974 case WS_SO_DEBUG:
4975 TRACE("Ignoring SO_DEBUG\n");
4976 return 0;
4978 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
4979 * socket. According to MSDN, this option is silently ignored.*/
4980 case WS_SO_DONTROUTE:
4981 TRACE("Ignoring SO_DONTROUTE\n");
4982 return 0;
4984 /* Stops two sockets from being bound to the same port. Always happens
4985 * on unix systems, so just drop it. */
4986 case WS_SO_EXCLUSIVEADDRUSE:
4987 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
4988 return 0;
4990 /* After a ConnectEx call succeeds, the socket can't be used with half of the
4991 * normal winsock functions on windows. We don't have that problem. */
4992 case WS_SO_UPDATE_CONNECT_CONTEXT:
4993 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
4994 return 0;
4996 /* After a AcceptEx call succeeds, the socket can't be used with half of the
4997 * normal winsock functions on windows. We don't have that problem. */
4998 case WS_SO_UPDATE_ACCEPT_CONTEXT:
4999 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
5000 return 0;
5002 /* SO_OPENTYPE does not require a valid socket handle. */
5003 case WS_SO_OPENTYPE:
5004 if (!optlen || optlen < sizeof(int) || !optval)
5006 SetLastError(WSAEFAULT);
5007 return SOCKET_ERROR;
5009 get_per_thread_data()->opentype = *(const int *)optval;
5010 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
5011 return 0;
5013 #ifdef SO_RCVTIMEO
5014 case WS_SO_RCVTIMEO:
5015 #endif
5016 #ifdef SO_SNDTIMEO
5017 case WS_SO_SNDTIMEO:
5018 #endif
5019 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
5020 if (optval && optlen == sizeof(UINT32)) {
5021 /* WinSock passes milliseconds instead of struct timeval */
5022 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
5023 tval.tv_sec = *(const UINT32*)optval / 1000;
5024 /* min of 500 milliseconds */
5025 if (tval.tv_sec == 0 && tval.tv_usec && tval.tv_usec < 500000)
5026 tval.tv_usec = 500000;
5027 optlen = sizeof(struct timeval);
5028 optval = (char*)&tval;
5029 } else if (optlen == sizeof(struct timeval)) {
5030 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
5031 } else {
5032 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
5033 return 0;
5035 convert_sockopt(&level, &optname);
5036 break;
5037 #endif
5039 default:
5040 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
5041 SetLastError(WSAENOPROTOOPT);
5042 return SOCKET_ERROR;
5044 break; /* case WS_SOL_SOCKET */
5046 #ifdef HAS_IPX
5047 case WS_NSPROTO_IPX:
5048 switch(optname)
5050 case WS_IPX_PTYPE:
5051 return set_ipx_packettype(s, *(int*)optval);
5053 case WS_IPX_FILTERPTYPE:
5054 /* Sets the receive filter packet type, at the moment we don't support it */
5055 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
5056 /* Returning 0 is better for now than returning a SOCKET_ERROR */
5057 return 0;
5059 default:
5060 FIXME("opt_name:%x\n", optname);
5061 return SOCKET_ERROR;
5063 break; /* case WS_NSPROTO_IPX */
5064 #endif
5066 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
5067 case WS_IPPROTO_TCP:
5068 switch(optname)
5070 case WS_TCP_NODELAY:
5071 convert_sockopt(&level, &optname);
5072 break;
5073 default:
5074 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
5075 return SOCKET_ERROR;
5077 break;
5079 case WS_IPPROTO_IP:
5080 switch(optname)
5082 case WS_IP_ADD_MEMBERSHIP:
5083 case WS_IP_DROP_MEMBERSHIP:
5084 #ifdef IP_HDRINCL
5085 case WS_IP_HDRINCL:
5086 #endif
5087 case WS_IP_MULTICAST_IF:
5088 case WS_IP_MULTICAST_LOOP:
5089 case WS_IP_MULTICAST_TTL:
5090 case WS_IP_OPTIONS:
5091 #ifdef IP_PKTINFO
5092 case WS_IP_PKTINFO:
5093 #endif
5094 case WS_IP_TOS:
5095 case WS_IP_TTL:
5096 #ifdef IP_UNICAST_IF
5097 case WS_IP_UNICAST_IF:
5098 #endif
5099 convert_sockopt(&level, &optname);
5100 break;
5101 case WS_IP_DONTFRAGMENT:
5102 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
5103 return 0;
5104 default:
5105 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
5106 return SOCKET_ERROR;
5108 break;
5110 case WS_IPPROTO_IPV6:
5111 switch(optname)
5113 #ifdef IPV6_ADD_MEMBERSHIP
5114 case WS_IPV6_ADD_MEMBERSHIP:
5115 #endif
5116 #ifdef IPV6_DROP_MEMBERSHIP
5117 case WS_IPV6_DROP_MEMBERSHIP:
5118 #endif
5119 case WS_IPV6_MULTICAST_IF:
5120 case WS_IPV6_MULTICAST_HOPS:
5121 case WS_IPV6_MULTICAST_LOOP:
5122 case WS_IPV6_UNICAST_HOPS:
5123 case WS_IPV6_V6ONLY:
5124 #ifdef IPV6_UNICAST_IF
5125 case WS_IPV6_UNICAST_IF:
5126 #endif
5127 convert_sockopt(&level, &optname);
5128 break;
5129 case WS_IPV6_DONTFRAG:
5130 FIXME("IPV6_DONTFRAG is silently ignored!\n");
5131 return 0;
5132 case WS_IPV6_PROTECTION_LEVEL:
5133 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
5134 return 0;
5135 default:
5136 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
5137 return SOCKET_ERROR;
5139 break;
5141 default:
5142 WARN("Unknown level: 0x%08x\n", level);
5143 SetLastError(WSAEINVAL);
5144 return SOCKET_ERROR;
5145 } /* end switch(level) */
5147 /* avoid endianness issues if argument is a 16-bit int */
5148 if (optval && optlen < sizeof(int))
5150 woptval= *((const INT16 *) optval);
5151 optval= (char*) &woptval;
5152 woptval&= (1 << optlen * 8) - 1;
5153 optlen=sizeof(int);
5155 fd = get_sock_fd( s, 0, NULL );
5156 if (fd == -1) return SOCKET_ERROR;
5158 if (setsockopt(fd, level, optname, optval, optlen) == 0)
5160 #ifdef __APPLE__
5161 if (level == SOL_SOCKET && optname == SO_REUSEADDR &&
5162 setsockopt(fd, level, SO_REUSEPORT, optval, optlen) != 0)
5164 SetLastError(wsaErrno());
5165 release_sock_fd( s, fd );
5166 return SOCKET_ERROR;
5168 #endif
5169 release_sock_fd( s, fd );
5170 return 0;
5172 TRACE("Setting socket error, %d\n", wsaErrno());
5173 SetLastError(wsaErrno());
5174 release_sock_fd( s, fd );
5176 return SOCKET_ERROR;
5179 /***********************************************************************
5180 * shutdown (WS2_32.22)
5182 int WINAPI WS_shutdown(SOCKET s, int how)
5184 int fd, err = WSAENOTSOCK;
5185 unsigned int options, clear_flags = 0;
5187 fd = get_sock_fd( s, 0, &options );
5188 TRACE("socket %04lx, how %i %x\n", s, how, options );
5190 if (fd == -1)
5191 return SOCKET_ERROR;
5193 switch( how )
5195 case SD_RECEIVE: /* drop receives */
5196 clear_flags |= FD_READ;
5197 break;
5198 case SD_SEND: /* drop sends */
5199 clear_flags |= FD_WRITE;
5200 break;
5201 case SD_BOTH: /* drop all */
5202 clear_flags |= FD_READ|FD_WRITE;
5203 /*fall through */
5204 default:
5205 clear_flags |= FD_WINE_LISTENING;
5208 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
5210 switch ( how )
5212 case SD_RECEIVE:
5213 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
5214 break;
5215 case SD_SEND:
5216 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
5217 break;
5218 case SD_BOTH:
5219 default:
5220 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
5221 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
5222 break;
5224 if (err) goto error;
5226 else /* non-overlapped mode */
5228 if ( shutdown( fd, how ) )
5230 err = wsaErrno();
5231 goto error;
5235 release_sock_fd( s, fd );
5236 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
5237 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
5238 return 0;
5240 error:
5241 release_sock_fd( s, fd );
5242 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
5243 SetLastError( err );
5244 return SOCKET_ERROR;
5247 /***********************************************************************
5248 * socket (WS2_32.23)
5250 SOCKET WINAPI WS_socket(int af, int type, int protocol)
5252 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
5254 return WSASocketA( af, type, protocol, NULL, 0,
5255 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
5259 /***********************************************************************
5260 * gethostbyaddr (WS2_32.51)
5262 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
5264 struct WS_hostent *retval = NULL;
5265 struct hostent* host;
5266 int unixtype = convert_af_w2u(type);
5267 const char *paddr = addr;
5268 unsigned long loopback;
5269 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5270 char *extrabuf;
5271 int ebufsize = 1024;
5272 struct hostent hostentry;
5273 int locerr = ENOBUFS;
5274 #endif
5276 /* convert back the magic loopback address if necessary */
5277 if (unixtype == AF_INET && len == 4 && !memcmp(addr, magic_loopback_addr, 4))
5279 loopback = htonl(INADDR_LOOPBACK);
5280 paddr = (char*) &loopback;
5283 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5284 host = NULL;
5285 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
5286 while(extrabuf) {
5287 int res = gethostbyaddr_r(paddr, len, unixtype,
5288 &hostentry, extrabuf, ebufsize, &host, &locerr);
5289 if (res != ERANGE) break;
5290 ebufsize *=2;
5291 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
5293 if (host) retval = WS_dup_he(host);
5294 else SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
5295 HeapFree(GetProcessHeap(),0,extrabuf);
5296 #else
5297 EnterCriticalSection( &csWSgetXXXbyYYY );
5298 host = gethostbyaddr(paddr, len, unixtype);
5299 if (host) retval = WS_dup_he(host);
5300 else SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
5301 LeaveCriticalSection( &csWSgetXXXbyYYY );
5302 #endif
5303 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
5304 return retval;
5307 /***********************************************************************
5308 * WS_compare_routes_by_metric_asc (INTERNAL)
5310 * Comparison function for qsort(), for sorting two routes (struct route)
5311 * by metric in ascending order.
5313 static int WS_compare_routes_by_metric_asc(const void *left, const void *right)
5315 return ((const struct route*)left)->metric - ((const struct route*)right)->metric;
5318 /***********************************************************************
5319 * WS_get_local_ips (INTERNAL)
5321 * Returns the list of local IP addresses by going through the network
5322 * adapters and using the local routing table to sort the addresses
5323 * from highest routing priority to lowest routing priority. This
5324 * functionality is inferred from the description for obtaining local
5325 * IP addresses given in the Knowledge Base Article Q160215.
5327 * Please note that the returned hostent is only freed when the thread
5328 * closes and is replaced if another hostent is requested.
5330 static struct WS_hostent* WS_get_local_ips( char *hostname )
5332 int numroutes = 0, i, j;
5333 DWORD n;
5334 PIP_ADAPTER_INFO adapters = NULL, k;
5335 struct WS_hostent *hostlist = NULL;
5336 PMIB_IPFORWARDTABLE routes = NULL;
5337 struct route *route_addrs = NULL;
5338 DWORD adap_size, route_size;
5340 /* Obtain the size of the adapter list and routing table, also allocate memory */
5341 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
5342 return NULL;
5343 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
5344 return NULL;
5345 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
5346 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
5347 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
5348 if (adapters == NULL || routes == NULL || route_addrs == NULL)
5349 goto cleanup;
5350 /* Obtain the adapter list and the full routing table */
5351 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
5352 goto cleanup;
5353 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
5354 goto cleanup;
5355 /* Store the interface associated with each route */
5356 for (n = 0; n < routes->dwNumEntries; n++)
5358 IF_INDEX ifindex;
5359 DWORD ifmetric;
5360 BOOL exists = FALSE;
5362 if (routes->table[n].u1.ForwardType != MIB_IPROUTE_TYPE_DIRECT)
5363 continue;
5364 ifindex = routes->table[n].dwForwardIfIndex;
5365 ifmetric = routes->table[n].dwForwardMetric1;
5366 /* Only store the lowest valued metric for an interface */
5367 for (j = 0; j < numroutes; j++)
5369 if (route_addrs[j].interface == ifindex)
5371 if (route_addrs[j].metric > ifmetric)
5372 route_addrs[j].metric = ifmetric;
5373 exists = TRUE;
5376 if (exists)
5377 continue;
5378 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
5379 if (route_addrs == NULL)
5380 goto cleanup; /* Memory allocation error, fail gracefully */
5381 route_addrs[numroutes].interface = ifindex;
5382 route_addrs[numroutes].metric = ifmetric;
5383 /* If no IP is found in the next step (for whatever reason)
5384 * then fall back to the magic loopback address.
5386 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
5387 numroutes++;
5389 if (numroutes == 0)
5390 goto cleanup; /* No routes, fall back to the Magic IP */
5391 /* Find the IP address associated with each found interface */
5392 for (i = 0; i < numroutes; i++)
5394 for (k = adapters; k != NULL; k = k->Next)
5396 char *ip = k->IpAddressList.IpAddress.String;
5398 if (route_addrs[i].interface == k->Index)
5399 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
5402 /* Allocate a hostent and enough memory for all the IPs,
5403 * including the NULL at the end of the list.
5405 hostlist = WS_create_he(hostname, 1, 0, numroutes+1, sizeof(struct in_addr));
5406 if (hostlist == NULL)
5407 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
5408 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
5409 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
5410 hostlist->h_addrtype = AF_INET;
5411 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
5412 /* Reorder the entries before placing them in the host list. Windows expects
5413 * the IP list in order from highest priority to lowest (the critical thing
5414 * is that most applications expect the first IP to be the default route).
5416 if (numroutes > 1)
5417 qsort(route_addrs, numroutes, sizeof(struct route), WS_compare_routes_by_metric_asc);
5419 for (i = 0; i < numroutes; i++)
5420 (*(struct in_addr *) hostlist->h_addr_list[i]) = route_addrs[i].addr;
5422 /* Cleanup all allocated memory except the address list,
5423 * the address list is used by the calling app.
5425 cleanup:
5426 HeapFree(GetProcessHeap(), 0, route_addrs);
5427 HeapFree(GetProcessHeap(), 0, adapters);
5428 HeapFree(GetProcessHeap(), 0, routes);
5429 return hostlist;
5432 /***********************************************************************
5433 * gethostbyname (WS2_32.52)
5435 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
5437 struct WS_hostent *retval = NULL;
5438 struct hostent* host;
5439 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5440 char *extrabuf;
5441 int ebufsize=1024;
5442 struct hostent hostentry;
5443 int locerr = ENOBUFS;
5444 #endif
5445 char hostname[100];
5446 if(!num_startup) {
5447 SetLastError(WSANOTINITIALISED);
5448 return NULL;
5450 if( gethostname( hostname, 100) == -1) {
5451 SetLastError(WSAENOBUFS); /* appropriate ? */
5452 return retval;
5454 if( !name || !name[0]) {
5455 name = hostname;
5457 /* If the hostname of the local machine is requested then return the
5458 * complete list of local IP addresses */
5459 if(strcmp(name, hostname) == 0)
5460 retval = WS_get_local_ips(hostname);
5461 /* If any other hostname was requested (or the routing table lookup failed)
5462 * then return the IP found by the host OS */
5463 if(retval == NULL)
5465 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5466 host = NULL;
5467 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
5468 while(extrabuf) {
5469 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
5470 if( res != ERANGE) break;
5471 ebufsize *=2;
5472 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
5474 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
5475 #else
5476 EnterCriticalSection( &csWSgetXXXbyYYY );
5477 host = gethostbyname(name);
5478 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
5479 #endif
5480 if (host) retval = WS_dup_he(host);
5481 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5482 HeapFree(GetProcessHeap(),0,extrabuf);
5483 #else
5484 LeaveCriticalSection( &csWSgetXXXbyYYY );
5485 #endif
5487 if (retval && retval->h_addr_list[0][0] == 127 &&
5488 strcmp(name, "localhost") != 0)
5490 /* hostname != "localhost" but has loopback address. replace by our
5491 * special address.*/
5492 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
5494 TRACE( "%s ret %p\n", debugstr_a(name), retval );
5495 return retval;
5499 /***********************************************************************
5500 * getprotobyname (WS2_32.53)
5502 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
5504 struct WS_protoent* retval = NULL;
5505 #ifdef HAVE_GETPROTOBYNAME
5506 struct protoent* proto;
5507 EnterCriticalSection( &csWSgetXXXbyYYY );
5508 if( (proto = getprotobyname(name)) != NULL )
5510 retval = WS_dup_pe(proto);
5512 else {
5513 MESSAGE("protocol %s not found; You might want to add "
5514 "this to /etc/protocols\n", debugstr_a(name) );
5515 SetLastError(WSANO_DATA);
5517 LeaveCriticalSection( &csWSgetXXXbyYYY );
5518 #endif
5519 TRACE( "%s ret %p\n", debugstr_a(name), retval );
5520 return retval;
5524 /***********************************************************************
5525 * getprotobynumber (WS2_32.54)
5527 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
5529 struct WS_protoent* retval = NULL;
5530 #ifdef HAVE_GETPROTOBYNUMBER
5531 struct protoent* proto;
5532 EnterCriticalSection( &csWSgetXXXbyYYY );
5533 if( (proto = getprotobynumber(number)) != NULL )
5535 retval = WS_dup_pe(proto);
5537 else {
5538 MESSAGE("protocol number %d not found; You might want to add "
5539 "this to /etc/protocols\n", number );
5540 SetLastError(WSANO_DATA);
5542 LeaveCriticalSection( &csWSgetXXXbyYYY );
5543 #endif
5544 TRACE("%i ret %p\n", number, retval);
5545 return retval;
5549 /***********************************************************************
5550 * getservbyname (WS2_32.55)
5552 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
5554 struct WS_servent* retval = NULL;
5555 struct servent* serv;
5556 char *name_str;
5557 char *proto_str = NULL;
5559 if (!(name_str = strdup_lower(name))) return NULL;
5561 if (proto && *proto)
5563 if (!(proto_str = strdup_lower(proto)))
5565 HeapFree( GetProcessHeap(), 0, name_str );
5566 return NULL;
5570 EnterCriticalSection( &csWSgetXXXbyYYY );
5571 serv = getservbyname(name_str, proto_str);
5572 if( serv != NULL )
5574 retval = WS_dup_se(serv);
5576 else SetLastError(WSANO_DATA);
5577 LeaveCriticalSection( &csWSgetXXXbyYYY );
5578 HeapFree( GetProcessHeap(), 0, proto_str );
5579 HeapFree( GetProcessHeap(), 0, name_str );
5580 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
5581 return retval;
5584 /***********************************************************************
5585 * freeaddrinfo (WS2_32.@)
5587 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
5589 while (res) {
5590 struct WS_addrinfo *next;
5592 HeapFree(GetProcessHeap(),0,res->ai_canonname);
5593 HeapFree(GetProcessHeap(),0,res->ai_addr);
5594 next = res->ai_next;
5595 HeapFree(GetProcessHeap(),0,res);
5596 res = next;
5600 /* helper functions for getaddrinfo()/getnameinfo() */
5601 static int convert_aiflag_w2u(int winflags) {
5602 unsigned int i;
5603 int unixflags = 0;
5605 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
5606 if (ws_aiflag_map[i][0] & winflags) {
5607 unixflags |= ws_aiflag_map[i][1];
5608 winflags &= ~ws_aiflag_map[i][0];
5610 if (winflags)
5611 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
5612 return unixflags;
5615 static int convert_niflag_w2u(int winflags) {
5616 unsigned int i;
5617 int unixflags = 0;
5619 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
5620 if (ws_niflag_map[i][0] & winflags) {
5621 unixflags |= ws_niflag_map[i][1];
5622 winflags &= ~ws_niflag_map[i][0];
5624 if (winflags)
5625 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
5626 return unixflags;
5629 static int convert_aiflag_u2w(int unixflags) {
5630 unsigned int i;
5631 int winflags = 0;
5633 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
5634 if (ws_aiflag_map[i][1] & unixflags) {
5635 winflags |= ws_aiflag_map[i][0];
5636 unixflags &= ~ws_aiflag_map[i][1];
5638 if (unixflags) /* will warn usually */
5639 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
5640 return winflags;
5643 static int convert_eai_u2w(int unixret) {
5644 int i;
5646 if (!unixret) return 0;
5648 for (i=0;ws_eai_map[i][0];i++)
5649 if (ws_eai_map[i][1] == unixret)
5650 return ws_eai_map[i][0];
5652 if (unixret == EAI_SYSTEM)
5653 /* There are broken versions of glibc which return EAI_SYSTEM
5654 * and set errno to 0 instead of returning EAI_NONAME.
5656 return errno ? sock_get_error( errno ) : WS_EAI_NONAME;
5658 FIXME("Unhandled unix EAI_xxx ret %d\n", unixret);
5659 return unixret;
5662 static char *get_hostname(void)
5664 char *ret;
5665 DWORD size = 0;
5667 GetComputerNameExA( ComputerNamePhysicalDnsHostname, NULL, &size );
5668 if (GetLastError() != ERROR_MORE_DATA) return NULL;
5669 if (!(ret = HeapAlloc( GetProcessHeap(), 0, size ))) return NULL;
5670 if (!GetComputerNameExA( ComputerNamePhysicalDnsHostname, ret, &size ))
5672 HeapFree( GetProcessHeap(), 0, ret );
5673 return NULL;
5675 return ret;
5678 /***********************************************************************
5679 * getaddrinfo (WS2_32.@)
5681 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
5683 #ifdef HAVE_GETADDRINFO
5684 struct addrinfo *unixaires = NULL;
5685 int result;
5686 struct addrinfo unixhints, *punixhints = NULL;
5687 char *hostname = NULL;
5688 const char *node;
5690 *res = NULL;
5691 if (!nodename && !servname)
5693 SetLastError(WSAHOST_NOT_FOUND);
5694 return WSAHOST_NOT_FOUND;
5697 if (!nodename)
5698 node = NULL;
5699 else if (!nodename[0])
5701 node = hostname = get_hostname();
5702 if (!node) return WSA_NOT_ENOUGH_MEMORY;
5704 else
5705 node = nodename;
5707 /* servname tweak required by OSX and BSD kernels */
5708 if (servname && !servname[0]) servname = "0";
5710 if (hints) {
5711 punixhints = &unixhints;
5713 memset(&unixhints, 0, sizeof(unixhints));
5714 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
5716 /* zero is a wildcard, no need to convert */
5717 if (hints->ai_family)
5718 punixhints->ai_family = convert_af_w2u(hints->ai_family);
5719 if (hints->ai_socktype)
5720 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
5721 if (hints->ai_protocol)
5722 punixhints->ai_protocol = max(convert_proto_w2u(hints->ai_protocol), 0);
5724 if (punixhints->ai_socktype < 0)
5726 SetLastError(WSAESOCKTNOSUPPORT);
5727 HeapFree(GetProcessHeap(), 0, hostname);
5728 return SOCKET_ERROR;
5731 /* windows allows invalid combinations of socket type and protocol, unix does not.
5732 * fix the parameters here to make getaddrinfo call always work */
5733 if (punixhints->ai_protocol == IPPROTO_TCP &&
5734 punixhints->ai_socktype != SOCK_STREAM && punixhints->ai_socktype != SOCK_SEQPACKET)
5735 punixhints->ai_socktype = 0;
5737 else if (punixhints->ai_protocol == IPPROTO_UDP && punixhints->ai_socktype != SOCK_DGRAM)
5738 punixhints->ai_socktype = 0;
5740 else if (IS_IPX_PROTO(punixhints->ai_protocol) && punixhints->ai_socktype != SOCK_DGRAM)
5741 punixhints->ai_socktype = 0;
5744 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
5745 result = getaddrinfo(node, servname, punixhints, &unixaires);
5747 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
5748 HeapFree(GetProcessHeap(), 0, hostname);
5750 if (!result) {
5751 struct addrinfo *xuai = unixaires;
5752 struct WS_addrinfo **xai = res;
5754 *xai = NULL;
5755 while (xuai) {
5756 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
5757 SIZE_T len;
5759 if (!ai)
5760 goto outofmem;
5762 *xai = ai;xai = &ai->ai_next;
5763 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
5764 ai->ai_family = convert_af_u2w(xuai->ai_family);
5765 /* copy whatever was sent in the hints */
5766 if(hints) {
5767 ai->ai_socktype = hints->ai_socktype;
5768 ai->ai_protocol = hints->ai_protocol;
5769 } else {
5770 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
5771 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
5773 if (xuai->ai_canonname) {
5774 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
5775 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
5776 if (!ai->ai_canonname)
5777 goto outofmem;
5778 strcpy(ai->ai_canonname,xuai->ai_canonname);
5780 len = xuai->ai_addrlen;
5781 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
5782 if (!ai->ai_addr)
5783 goto outofmem;
5784 ai->ai_addrlen = len;
5785 do {
5786 int winlen = ai->ai_addrlen;
5788 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
5789 ai->ai_addrlen = winlen;
5790 break;
5792 len = 2*len;
5793 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
5794 if (!ai->ai_addr)
5795 goto outofmem;
5796 ai->ai_addrlen = len;
5797 } while (1);
5798 xuai = xuai->ai_next;
5800 freeaddrinfo(unixaires);
5802 if (TRACE_ON(winsock))
5804 struct WS_addrinfo *ai = *res;
5805 while (ai)
5807 TRACE("=> %p, flags %#x, family %d, type %d, protocol %d, len %ld, name %s, addr %s\n",
5808 ai, ai->ai_flags, ai->ai_family, ai->ai_socktype, ai->ai_protocol, ai->ai_addrlen,
5809 ai->ai_canonname, debugstr_sockaddr(ai->ai_addr));
5810 ai = ai->ai_next;
5813 } else
5814 result = convert_eai_u2w(result);
5816 SetLastError(result);
5817 return result;
5819 outofmem:
5820 if (*res) WS_freeaddrinfo(*res);
5821 if (unixaires) freeaddrinfo(unixaires);
5822 return WSA_NOT_ENOUGH_MEMORY;
5823 #else
5824 FIXME("getaddrinfo() failed, not found during buildtime.\n");
5825 return EAI_FAIL;
5826 #endif
5829 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
5831 struct WS_addrinfoW *ret;
5833 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
5834 ret->ai_flags = ai->ai_flags;
5835 ret->ai_family = ai->ai_family;
5836 ret->ai_socktype = ai->ai_socktype;
5837 ret->ai_protocol = ai->ai_protocol;
5838 ret->ai_addrlen = ai->ai_addrlen;
5839 ret->ai_canonname = NULL;
5840 ret->ai_addr = NULL;
5841 ret->ai_next = NULL;
5842 if (ai->ai_canonname)
5844 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
5845 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
5847 HeapFree(GetProcessHeap(), 0, ret);
5848 return NULL;
5850 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
5852 if (ai->ai_addr)
5854 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, ai->ai_addrlen)))
5856 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
5857 HeapFree(GetProcessHeap(), 0, ret);
5858 return NULL;
5860 memcpy(ret->ai_addr, ai->ai_addr, ai->ai_addrlen);
5862 return ret;
5865 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
5867 struct WS_addrinfoW *ret, *infoW;
5869 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
5870 while (info->ai_next)
5872 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
5874 FreeAddrInfoW(ret);
5875 return NULL;
5877 infoW = infoW->ai_next;
5878 info = info->ai_next;
5880 return ret;
5883 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
5885 struct WS_addrinfo *ret;
5887 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
5888 ret->ai_flags = ai->ai_flags;
5889 ret->ai_family = ai->ai_family;
5890 ret->ai_socktype = ai->ai_socktype;
5891 ret->ai_protocol = ai->ai_protocol;
5892 ret->ai_addrlen = ai->ai_addrlen;
5893 ret->ai_canonname = NULL;
5894 ret->ai_addr = NULL;
5895 ret->ai_next = NULL;
5896 if (ai->ai_canonname)
5898 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
5899 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
5901 HeapFree(GetProcessHeap(), 0, ret);
5902 return NULL;
5904 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
5906 if (ai->ai_addr)
5908 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
5910 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
5911 HeapFree(GetProcessHeap(), 0, ret);
5912 return NULL;
5914 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
5916 return ret;
5919 /***********************************************************************
5920 * GetAddrInfoW (WS2_32.@)
5922 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
5924 int ret, len;
5925 char *nodenameA = NULL, *servnameA = NULL;
5926 struct WS_addrinfo *resA, *hintsA = NULL;
5928 *res = NULL;
5929 if (nodename)
5931 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
5932 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
5933 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
5935 if (servname)
5937 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
5938 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
5940 HeapFree(GetProcessHeap(), 0, nodenameA);
5941 return EAI_MEMORY;
5943 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
5946 if (hints) hintsA = addrinfo_WtoA(hints);
5947 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
5948 WS_freeaddrinfo(hintsA);
5950 if (!ret)
5952 *res = addrinfo_list_AtoW(resA);
5953 WS_freeaddrinfo(resA);
5956 HeapFree(GetProcessHeap(), 0, nodenameA);
5957 HeapFree(GetProcessHeap(), 0, servnameA);
5958 return ret;
5961 /***********************************************************************
5962 * FreeAddrInfoW (WS2_32.@)
5964 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
5966 while (ai)
5968 ADDRINFOW *next;
5969 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
5970 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
5971 next = ai->ai_next;
5972 HeapFree(GetProcessHeap(), 0, ai);
5973 ai = next;
5977 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
5978 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
5980 #ifdef HAVE_GETNAMEINFO
5981 int ret;
5982 union generic_unix_sockaddr sa_u;
5983 unsigned int size;
5985 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
5986 serv, servlen, flags);
5988 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
5989 if (!size)
5991 SetLastError(WSAEFAULT);
5992 return WSA_NOT_ENOUGH_MEMORY;
5994 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
5995 return convert_eai_u2w(ret);
5996 #else
5997 FIXME("getnameinfo() failed, not found during buildtime.\n");
5998 return EAI_FAIL;
5999 #endif
6002 int WINAPI GetNameInfoW(const SOCKADDR *sa, WS_socklen_t salen, PWCHAR host,
6003 DWORD hostlen, PWCHAR serv, DWORD servlen, INT flags)
6005 int ret;
6006 char *hostA = NULL, *servA = NULL;
6008 if (host && (!(hostA = HeapAlloc(GetProcessHeap(), 0, hostlen)))) return EAI_MEMORY;
6009 if (serv && (!(servA = HeapAlloc(GetProcessHeap(), 0, servlen))))
6011 HeapFree(GetProcessHeap(), 0, hostA);
6012 return EAI_MEMORY;
6015 ret = WS_getnameinfo(sa, salen, hostA, hostlen, servA, servlen, flags);
6016 if (!ret)
6018 if (host) MultiByteToWideChar(CP_ACP, 0, hostA, -1, host, hostlen);
6019 if (serv) MultiByteToWideChar(CP_ACP, 0, servA, -1, serv, servlen);
6022 HeapFree(GetProcessHeap(), 0, hostA);
6023 HeapFree(GetProcessHeap(), 0, servA);
6024 return ret;
6027 /***********************************************************************
6028 * getservbyport (WS2_32.56)
6030 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
6032 struct WS_servent* retval = NULL;
6033 #ifdef HAVE_GETSERVBYPORT
6034 struct servent* serv;
6035 char *proto_str = NULL;
6037 if (proto && *proto)
6039 if (!(proto_str = strdup_lower(proto))) return NULL;
6041 EnterCriticalSection( &csWSgetXXXbyYYY );
6042 if( (serv = getservbyport(port, proto_str)) != NULL ) {
6043 retval = WS_dup_se(serv);
6045 else SetLastError(WSANO_DATA);
6046 LeaveCriticalSection( &csWSgetXXXbyYYY );
6047 HeapFree( GetProcessHeap(), 0, proto_str );
6048 #endif
6049 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
6050 return retval;
6054 /***********************************************************************
6055 * gethostname (WS2_32.57)
6057 int WINAPI WS_gethostname(char *name, int namelen)
6059 TRACE("name %p, len %d\n", name, namelen);
6061 if (gethostname(name, namelen) == 0)
6063 TRACE("<- '%s'\n", name);
6064 return 0;
6066 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
6067 TRACE("<- ERROR !\n");
6068 return SOCKET_ERROR;
6072 /* ------------------------------------- Windows sockets extensions -- *
6074 * ------------------------------------------------------------------- */
6076 /***********************************************************************
6077 * WSAEnumNetworkEvents (WS2_32.36)
6079 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
6081 int ret;
6082 int i;
6083 int errors[FD_MAX_EVENTS];
6085 TRACE("%04lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
6087 SERVER_START_REQ( get_socket_event )
6089 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6090 req->service = TRUE;
6091 req->c_event = wine_server_obj_handle( hEvent );
6092 wine_server_set_reply( req, errors, sizeof(errors) );
6093 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
6095 SERVER_END_REQ;
6096 if (!ret)
6098 for (i = 0; i < FD_MAX_EVENTS; i++)
6099 lpEvent->iErrorCode[i] = NtStatusToWSAError(errors[i]);
6100 return 0;
6102 SetLastError(WSAEINVAL);
6103 return SOCKET_ERROR;
6106 /***********************************************************************
6107 * WSAEventSelect (WS2_32.39)
6109 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
6111 int ret;
6113 TRACE("%04lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
6115 SERVER_START_REQ( set_socket_event )
6117 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6118 req->mask = lEvent;
6119 req->event = wine_server_obj_handle( hEvent );
6120 req->window = 0;
6121 req->msg = 0;
6122 ret = wine_server_call( req );
6124 SERVER_END_REQ;
6125 if (!ret) return 0;
6126 SetLastError(WSAEINVAL);
6127 return SOCKET_ERROR;
6130 /**********************************************************************
6131 * WSAGetOverlappedResult (WS2_32.40)
6133 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
6134 LPDWORD lpcbTransfer, BOOL fWait,
6135 LPDWORD lpdwFlags )
6137 NTSTATUS status;
6139 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
6140 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
6142 if ( lpOverlapped == NULL )
6144 ERR( "Invalid pointer\n" );
6145 SetLastError(WSA_INVALID_PARAMETER);
6146 return FALSE;
6149 status = lpOverlapped->Internal;
6150 if (status == STATUS_PENDING)
6152 if (!fWait)
6154 SetLastError( WSA_IO_INCOMPLETE );
6155 return FALSE;
6158 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
6159 INFINITE ) == WAIT_FAILED)
6160 return FALSE;
6161 status = lpOverlapped->Internal;
6164 if ( lpcbTransfer )
6165 *lpcbTransfer = lpOverlapped->InternalHigh;
6167 if ( lpdwFlags )
6168 *lpdwFlags = lpOverlapped->u.s.Offset;
6170 if (status) SetLastError( RtlNtStatusToDosError(status) );
6171 return !status;
6175 /***********************************************************************
6176 * WSAAsyncSelect (WS2_32.101)
6178 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
6180 int ret;
6182 TRACE("%04lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
6184 SERVER_START_REQ( set_socket_event )
6186 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6187 req->mask = lEvent;
6188 req->event = 0;
6189 req->window = wine_server_user_handle( hWnd );
6190 req->msg = uMsg;
6191 ret = wine_server_call( req );
6193 SERVER_END_REQ;
6194 if (!ret) return 0;
6195 SetLastError(WSAEINVAL);
6196 return SOCKET_ERROR;
6199 /***********************************************************************
6200 * WSACreateEvent (WS2_32.31)
6203 WSAEVENT WINAPI WSACreateEvent(void)
6205 /* Create a manual-reset event, with initial state: unsignaled */
6206 TRACE("\n");
6208 return CreateEventW(NULL, TRUE, FALSE, NULL);
6211 /***********************************************************************
6212 * WSACloseEvent (WS2_32.29)
6215 BOOL WINAPI WSACloseEvent(WSAEVENT event)
6217 TRACE ("event=%p\n", event);
6219 return CloseHandle(event);
6222 /***********************************************************************
6223 * WSASocketA (WS2_32.78)
6226 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
6227 LPWSAPROTOCOL_INFOA lpProtocolInfo,
6228 GROUP g, DWORD dwFlags)
6230 INT len;
6231 WSAPROTOCOL_INFOW info;
6233 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
6234 af, type, protocol, lpProtocolInfo, g, dwFlags);
6236 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
6238 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
6239 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
6240 info.szProtocol, WSAPROTOCOL_LEN + 1);
6242 if (!len)
6244 SetLastError(WSAEINVAL);
6245 return SOCKET_ERROR;
6248 return WSASocketW(af, type, protocol, &info, g, dwFlags);
6251 /***********************************************************************
6252 * WSASocketW (WS2_32.79)
6255 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
6256 LPWSAPROTOCOL_INFOW lpProtocolInfo,
6257 GROUP g, DWORD dwFlags)
6259 SOCKET ret;
6260 DWORD err;
6261 int unixaf, unixtype, ipxptype = -1;
6264 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
6265 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
6268 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
6269 af, type, protocol, lpProtocolInfo, g, dwFlags );
6271 if (!num_startup)
6273 err = WSANOTINITIALISED;
6274 goto done;
6277 /* hack for WSADuplicateSocket */
6278 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
6279 ret = lpProtocolInfo->dwServiceFlags3;
6280 TRACE("\tgot duplicate %04lx\n", ret);
6281 return ret;
6284 if (lpProtocolInfo)
6286 if (af == FROM_PROTOCOL_INFO || !af)
6287 af = lpProtocolInfo->iAddressFamily;
6288 if (type == FROM_PROTOCOL_INFO || !type)
6289 type = lpProtocolInfo->iSocketType;
6290 if (protocol == FROM_PROTOCOL_INFO || !protocol)
6291 protocol = lpProtocolInfo->iProtocol;
6294 if (!type && (af || protocol))
6296 int autoproto = protocol;
6297 WSAPROTOCOL_INFOW infow;
6299 /* default to the first valid protocol */
6300 if (!autoproto)
6301 autoproto = valid_protocols[0];
6302 else if(IS_IPX_PROTO(autoproto))
6303 autoproto = WS_NSPROTO_IPX;
6305 if (WS_EnterSingleProtocolW(autoproto, &infow))
6307 type = infow.iSocketType;
6309 /* after win2003 it's no longer possible to pass AF_UNSPEC
6310 using the protocol info struct */
6311 if (!lpProtocolInfo && af == WS_AF_UNSPEC)
6312 af = infow.iAddressFamily;
6317 Windows has an extension to the IPX protocol that allows one to create sockets
6318 and set the IPX packet type at the same time, to do that a caller will use
6319 a protocol like NSPROTO_IPX + <PACKET TYPE>
6321 if (IS_IPX_PROTO(protocol))
6322 ipxptype = protocol - WS_NSPROTO_IPX;
6324 /* convert the socket family, type and protocol */
6325 unixaf = convert_af_w2u(af);
6326 unixtype = convert_socktype_w2u(type);
6327 protocol = convert_proto_w2u(protocol);
6328 if (unixaf == AF_UNSPEC) unixaf = -1;
6330 /* filter invalid parameters */
6331 if (protocol < 0)
6333 /* the type could not be converted */
6334 if (type && unixtype < 0)
6336 err = WSAESOCKTNOSUPPORT;
6337 goto done;
6340 err = WSAEPROTONOSUPPORT;
6341 goto done;
6343 if (unixaf < 0)
6345 /* both family and protocol can't be invalid */
6346 if (protocol <= 0)
6348 err = WSAEINVAL;
6349 goto done;
6352 /* family could not be converted and neither socket type */
6353 if (unixtype < 0 && af >= 0)
6356 err = WSAESOCKTNOSUPPORT;
6357 goto done;
6360 err = WSAEAFNOSUPPORT;
6361 goto done;
6364 SERVER_START_REQ( create_socket )
6366 req->family = unixaf;
6367 req->type = unixtype;
6368 req->protocol = protocol;
6369 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
6370 req->attributes = OBJ_INHERIT;
6371 req->flags = dwFlags;
6372 set_error( wine_server_call( req ) );
6373 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
6375 SERVER_END_REQ;
6376 if (ret)
6378 TRACE("\tcreated %04lx\n", ret );
6379 if (ipxptype > 0)
6380 set_ipx_packettype(ret, ipxptype);
6381 return ret;
6384 err = GetLastError();
6385 if (err == WSAEACCES) /* raw socket denied */
6387 if (type == SOCK_RAW)
6388 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
6389 else
6390 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
6392 else
6394 /* invalid combination of valid parameters, like SOCK_STREAM + IPPROTO_UDP */
6395 if (err == WSAEINVAL)
6396 err = WSAESOCKTNOSUPPORT;
6397 else if (err == WSAEOPNOTSUPP)
6398 err = WSAEPROTONOSUPPORT;
6401 done:
6402 WARN("\t\tfailed, error %d!\n", err);
6403 SetLastError(err);
6404 return INVALID_SOCKET;
6407 /***********************************************************************
6408 * WSAJoinLeaf (WS2_32.58)
6411 SOCKET WINAPI WSAJoinLeaf(
6412 SOCKET s,
6413 const struct WS_sockaddr *addr,
6414 int addrlen,
6415 LPWSABUF lpCallerData,
6416 LPWSABUF lpCalleeData,
6417 LPQOS lpSQOS,
6418 LPQOS lpGQOS,
6419 DWORD dwFlags)
6421 FIXME("stub.\n");
6422 return INVALID_SOCKET;
6425 /***********************************************************************
6426 * __WSAFDIsSet (WS2_32.151)
6428 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
6430 int i = set->fd_count, ret = 0;
6432 while (i--)
6433 if (set->fd_array[i] == s)
6435 ret = 1;
6436 break;
6439 TRACE("(socket %04lx, fd_set %p, count %i) <- %d\n", s, set, set->fd_count, ret);
6440 return ret;
6443 /***********************************************************************
6444 * WSAIsBlocking (WS2_32.114)
6446 BOOL WINAPI WSAIsBlocking(void)
6448 /* By default WinSock should set all its sockets to non-blocking mode
6449 * and poll in PeekMessage loop when processing "blocking" ones. This
6450 * function is supposed to tell if the program is in this loop. Our
6451 * blocking calls are truly blocking so we always return FALSE.
6453 * Note: It is allowed to call this function without prior WSAStartup().
6456 TRACE("\n");
6457 return FALSE;
6460 /***********************************************************************
6461 * WSACancelBlockingCall (WS2_32.113)
6463 INT WINAPI WSACancelBlockingCall(void)
6465 TRACE("\n");
6466 return 0;
6469 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
6471 FIXME("How was this called?\n");
6472 return x();
6476 /***********************************************************************
6477 * WSASetBlockingHook (WS2_32.109)
6479 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
6481 FARPROC prev = blocking_hook;
6482 blocking_hook = lpBlockFunc;
6483 TRACE("hook %p\n", lpBlockFunc);
6484 return prev;
6488 /***********************************************************************
6489 * WSAUnhookBlockingHook (WS2_32.110)
6491 INT WINAPI WSAUnhookBlockingHook(void)
6493 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
6494 return 0;
6498 /* ----------------------------------- end of API stuff */
6500 /* ----------------------------------- helper functions -
6502 * TODO: Merge WS_dup_..() stuff into one function that
6503 * would operate with a generic structure containing internal
6504 * pointers (via a template of some kind).
6507 static int list_size(char** l, int item_size)
6509 int i,j = 0;
6510 if(l)
6511 { for(i=0;l[i];i++)
6512 j += (item_size) ? item_size : strlen(l[i]) + 1;
6513 j += (i + 1) * sizeof(char*); }
6514 return j;
6517 static int list_dup(char** l_src, char** l_to, int item_size)
6519 char *p;
6520 int i;
6522 for (i = 0; l_src[i]; i++) ;
6523 p = (char *)(l_to + i + 1);
6524 for (i = 0; l_src[i]; i++)
6526 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
6527 memcpy(p, l_src[i], count);
6528 l_to[i] = p;
6529 p += count;
6531 l_to[i] = NULL;
6532 return p - (char *)l_to;
6535 /* ----- hostent */
6537 /* create a hostent entry
6539 * Creates the entry with enough memory for the name, aliases
6540 * addresses, and the address pointers. Also copies the name
6541 * and sets up all the pointers.
6543 * NOTE: The alias and address lists must be allocated with room
6544 * for the NULL item terminating the list. This is true even if
6545 * the list has no items ("aliases" and "addresses" must be
6546 * at least "1", a truly empty list is invalid).
6548 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length)
6550 struct WS_hostent *p_to;
6551 char *p;
6552 int size = (sizeof(struct WS_hostent) +
6553 strlen(name) + 1 +
6554 sizeof(char *) * aliases +
6555 aliases_size +
6556 sizeof(char *) * addresses +
6557 address_length * (addresses - 1)), i;
6559 if (!(p_to = check_buffer_he(size))) return NULL;
6560 memset(p_to, 0, size);
6562 /* Use the memory in the same way winsock does.
6563 * First set the pointer for aliases, second set the pointers for addresses.
6564 * Third fill the addresses indexes, fourth jump aliases names size.
6565 * Fifth fill the hostname.
6566 * NOTE: This method is valid for OS version's >= XP.
6568 p = (char *)(p_to + 1);
6569 p_to->h_aliases = (char **)p;
6570 p += sizeof(char *)*aliases;
6572 p_to->h_addr_list = (char **)p;
6573 p += sizeof(char *)*addresses;
6575 for (i = 0, addresses--; i < addresses; i++, p += address_length)
6576 p_to->h_addr_list[i] = p;
6578 /* NOTE: h_aliases must be filled in manually because we don't know each string
6579 * size, leave these pointers NULL (already set to NULL by memset earlier).
6581 p += aliases_size;
6583 p_to->h_name = p;
6584 strcpy(p, name);
6586 return p_to;
6589 /* duplicate hostent entry
6590 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
6591 * Ditto for protoent and servent.
6593 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
6595 int i, addresses = 0, alias_size = 0;
6596 struct WS_hostent *p_to;
6597 char *p;
6599 for( i = 0; p_he->h_aliases[i]; i++) alias_size += strlen(p_he->h_aliases[i]) + 1;
6600 while (p_he->h_addr_list[addresses]) addresses++;
6602 p_to = WS_create_he(p_he->h_name, i + 1, alias_size, addresses + 1, p_he->h_length);
6604 if (!p_to) return NULL;
6605 p_to->h_addrtype = convert_af_u2w(p_he->h_addrtype);
6606 p_to->h_length = p_he->h_length;
6608 for(i = 0, p = p_to->h_addr_list[0]; p_he->h_addr_list[i]; i++, p += p_to->h_length)
6609 memcpy(p, p_he->h_addr_list[i], p_to->h_length);
6611 /* Fill the aliases after the IP data */
6612 for(i = 0; p_he->h_aliases[i]; i++)
6614 p_to->h_aliases[i] = p;
6615 strcpy(p, p_he->h_aliases[i]);
6616 p += strlen(p) + 1;
6619 return p_to;
6622 /* ----- protoent */
6624 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
6626 char *p;
6627 struct WS_protoent *p_to;
6629 int size = (sizeof(*p_pe) +
6630 strlen(p_pe->p_name) + 1 +
6631 list_size(p_pe->p_aliases, 0));
6633 if (!(p_to = check_buffer_pe(size))) return NULL;
6634 p_to->p_proto = p_pe->p_proto;
6636 p = (char *)(p_to + 1);
6637 p_to->p_name = p;
6638 strcpy(p, p_pe->p_name);
6639 p += strlen(p) + 1;
6641 p_to->p_aliases = (char **)p;
6642 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
6643 return p_to;
6646 /* ----- servent */
6648 static struct WS_servent *WS_dup_se(const struct servent* p_se)
6650 char *p;
6651 struct WS_servent *p_to;
6653 int size = (sizeof(*p_se) +
6654 strlen(p_se->s_proto) + 1 +
6655 strlen(p_se->s_name) + 1 +
6656 list_size(p_se->s_aliases, 0));
6658 if (!(p_to = check_buffer_se(size))) return NULL;
6659 p_to->s_port = p_se->s_port;
6661 p = (char *)(p_to + 1);
6662 p_to->s_name = p;
6663 strcpy(p, p_se->s_name);
6664 p += strlen(p) + 1;
6666 p_to->s_proto = p;
6667 strcpy(p, p_se->s_proto);
6668 p += strlen(p) + 1;
6670 p_to->s_aliases = (char **)p;
6671 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
6672 return p_to;
6676 /***********************************************************************
6677 * WSARecv (WS2_32.67)
6679 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6680 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
6681 LPWSAOVERLAPPED lpOverlapped,
6682 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
6684 return WS2_recv_base(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
6685 NULL, NULL, lpOverlapped, lpCompletionRoutine, NULL);
6688 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6689 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
6690 struct WS_sockaddr *lpFrom,
6691 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
6692 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
6693 LPWSABUF lpControlBuffer )
6695 unsigned int i, options;
6696 int n, fd, err, overlapped;
6697 struct ws2_async *wsa, localwsa;
6698 BOOL is_blocking;
6699 DWORD timeout_start = GetTickCount();
6700 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
6702 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
6703 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
6704 (lpFromlen ? *lpFromlen : -1),
6705 lpOverlapped, lpCompletionRoutine);
6707 fd = get_sock_fd( s, FILE_READ_DATA, &options );
6708 TRACE( "fd=%d, options=%x\n", fd, options );
6710 if (fd == -1) return SOCKET_ERROR;
6712 overlapped = (lpOverlapped || lpCompletionRoutine) &&
6713 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
6714 if (overlapped || dwBufferCount > 1)
6716 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[dwBufferCount]))))
6718 err = WSAEFAULT;
6719 goto error;
6722 else
6723 wsa = &localwsa;
6725 wsa->hSocket = SOCKET2HANDLE(s);
6726 wsa->flags = *lpFlags;
6727 wsa->lpFlags = lpFlags;
6728 wsa->addr = lpFrom;
6729 wsa->addrlen.ptr = lpFromlen;
6730 wsa->control = lpControlBuffer;
6731 wsa->n_iovecs = dwBufferCount;
6732 wsa->first_iovec = 0;
6733 for (i = 0; i < dwBufferCount; i++)
6735 /* check buffer first to trigger write watches */
6736 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
6738 err = WSAEFAULT;
6739 goto error;
6741 wsa->iovec[i].iov_base = lpBuffers[i].buf;
6742 wsa->iovec[i].iov_len = lpBuffers[i].len;
6745 for (;;)
6747 n = WS2_recv( fd, wsa );
6748 if (n == -1)
6750 if (errno != EAGAIN)
6752 int loc_errno = errno;
6753 err = wsaErrno();
6754 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
6755 goto error;
6758 else if (lpNumberOfBytesRecvd) *lpNumberOfBytesRecvd = n;
6760 if (overlapped)
6762 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
6764 wsa->user_overlapped = lpOverlapped;
6765 wsa->completion_func = lpCompletionRoutine;
6766 release_sock_fd( s, fd );
6768 if (n == -1)
6770 iosb->u.Status = STATUS_PENDING;
6771 iosb->Information = 0;
6773 SERVER_START_REQ( register_async )
6775 req->type = ASYNC_TYPE_READ;
6776 req->async.handle = wine_server_obj_handle( wsa->hSocket );
6777 req->async.callback = wine_server_client_ptr( WS2_async_recv );
6778 req->async.iosb = wine_server_client_ptr( iosb );
6779 req->async.arg = wine_server_client_ptr( wsa );
6780 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
6781 req->async.cvalue = cvalue;
6782 err = wine_server_call( req );
6784 SERVER_END_REQ;
6786 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
6787 SetLastError(NtStatusToWSAError( err ));
6788 return SOCKET_ERROR;
6791 iosb->u.Status = STATUS_SUCCESS;
6792 iosb->Information = n;
6793 if (!wsa->completion_func)
6795 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
6796 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
6797 HeapFree( GetProcessHeap(), 0, wsa );
6799 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
6800 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
6801 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6802 return 0;
6805 if (n != -1) break;
6807 if ((err = _is_blocking( s, &is_blocking )))
6809 err = NtStatusToWSAError( err );
6810 goto error;
6813 if ( is_blocking )
6815 struct pollfd pfd;
6816 int timeout = GET_RCVTIMEO(fd);
6817 if (timeout != -1)
6819 timeout -= GetTickCount() - timeout_start;
6820 if (timeout < 0) timeout = 0;
6823 pfd.fd = fd;
6824 pfd.events = POLLIN;
6825 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
6827 if (!timeout || !poll( &pfd, 1, timeout ))
6829 err = WSAETIMEDOUT;
6830 /* a timeout is not fatal */
6831 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6832 goto error;
6835 else
6837 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6838 err = WSAEWOULDBLOCK;
6839 goto error;
6843 TRACE(" -> %i bytes\n", n);
6844 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
6845 release_sock_fd( s, fd );
6846 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6847 SetLastError(ERROR_SUCCESS);
6849 return 0;
6851 error:
6852 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
6853 release_sock_fd( s, fd );
6854 WARN(" -> ERROR %d\n", err);
6855 SetLastError( err );
6856 return SOCKET_ERROR;
6859 /***********************************************************************
6860 * WSARecvFrom (WS2_32.69)
6862 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6863 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
6864 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
6865 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
6868 return WS2_recv_base( s, lpBuffers, dwBufferCount,
6869 lpNumberOfBytesRecvd, lpFlags,
6870 lpFrom, lpFromlen,
6871 lpOverlapped, lpCompletionRoutine, NULL );
6874 /***********************************************************************
6875 * WSCInstallProvider (WS2_32.88)
6877 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
6878 LPCWSTR lpszProviderDllPath,
6879 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
6880 DWORD dwNumberOfEntries,
6881 LPINT lpErrno )
6883 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
6884 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
6885 dwNumberOfEntries, lpErrno);
6886 *lpErrno = 0;
6887 return 0;
6891 /***********************************************************************
6892 * WSCDeinstallProvider (WS2_32.83)
6894 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
6896 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
6897 *lpErrno = 0;
6898 return 0;
6902 /***********************************************************************
6903 * WSAAccept (WS2_32.26)
6905 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
6906 LPCONDITIONPROC lpfnCondition, DWORD_PTR dwCallbackData)
6909 int ret = 0, size;
6910 WSABUF CallerId, CallerData, CalleeId, CalleeData;
6911 /* QOS SQOS, GQOS; */
6912 GROUP g;
6913 SOCKET cs;
6914 SOCKADDR src_addr, dst_addr;
6916 TRACE("socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
6917 s, addr, addrlen, lpfnCondition, dwCallbackData);
6919 cs = WS_accept(s, addr, addrlen);
6920 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
6921 if (!lpfnCondition) return cs;
6923 if (addr && addrlen)
6925 CallerId.buf = (char *)addr;
6926 CallerId.len = *addrlen;
6928 else
6930 size = sizeof(src_addr);
6931 WS_getpeername(cs, &src_addr, &size);
6932 CallerId.buf = (char *)&src_addr;
6933 CallerId.len = size;
6935 CallerData.buf = NULL;
6936 CallerData.len = 0;
6938 size = sizeof(dst_addr);
6939 WS_getsockname(cs, &dst_addr, &size);
6941 CalleeId.buf = (char *)&dst_addr;
6942 CalleeId.len = sizeof(dst_addr);
6944 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
6945 &CalleeId, &CalleeData, &g, dwCallbackData);
6947 switch (ret)
6949 case CF_ACCEPT:
6950 return cs;
6951 case CF_DEFER:
6952 SERVER_START_REQ( set_socket_deferred )
6954 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6955 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
6956 if ( !wine_server_call_err ( req ) )
6958 SetLastError( WSATRY_AGAIN );
6959 WS_closesocket( cs );
6962 SERVER_END_REQ;
6963 return SOCKET_ERROR;
6964 case CF_REJECT:
6965 WS_closesocket(cs);
6966 SetLastError(WSAECONNREFUSED);
6967 return SOCKET_ERROR;
6968 default:
6969 FIXME("Unknown return type from Condition function\n");
6970 SetLastError(WSAENOTSOCK);
6971 return SOCKET_ERROR;
6975 /***********************************************************************
6976 * WSADuplicateSocketA (WS2_32.32)
6978 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
6980 return WS_DuplicateSocket(FALSE, s, dwProcessId, (LPWSAPROTOCOL_INFOW) lpProtocolInfo);
6983 /***********************************************************************
6984 * WSADuplicateSocketW (WS2_32.33)
6986 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
6988 return WS_DuplicateSocket(TRUE, s, dwProcessId, lpProtocolInfo);
6991 /***********************************************************************
6992 * WSAInstallServiceClassA (WS2_32.48)
6994 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
6996 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
6997 SetLastError(WSAEACCES);
6998 return SOCKET_ERROR;
7001 /***********************************************************************
7002 * WSAInstallServiceClassW (WS2_32.49)
7004 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
7006 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
7007 SetLastError(WSAEACCES);
7008 return SOCKET_ERROR;
7011 /***********************************************************************
7012 * WSARemoveServiceClass (WS2_32.70)
7014 int WINAPI WSARemoveServiceClass(LPGUID info)
7016 FIXME("Request to remove service %p\n",info);
7017 SetLastError(WSATYPE_NOT_FOUND);
7018 return SOCKET_ERROR;
7021 /***********************************************************************
7022 * inet_ntop (WS2_32.@)
7024 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
7026 #ifdef HAVE_INET_NTOP
7027 struct WS_in6_addr *in6;
7028 struct WS_in_addr *in;
7029 PCSTR pdst;
7031 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
7032 if (!buffer)
7034 SetLastError( STATUS_INVALID_PARAMETER );
7035 return NULL;
7038 switch (family)
7040 case WS_AF_INET:
7042 in = addr;
7043 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
7044 break;
7046 case WS_AF_INET6:
7048 in6 = addr;
7049 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
7050 break;
7052 default:
7053 SetLastError( WSAEAFNOSUPPORT );
7054 return NULL;
7057 if (!pdst) SetLastError( STATUS_INVALID_PARAMETER );
7058 return pdst;
7059 #else
7060 FIXME( "not supported on this platform\n" );
7061 SetLastError( WSAEAFNOSUPPORT );
7062 return NULL;
7063 #endif
7066 /***********************************************************************
7067 * inet_pton (WS2_32.@)
7069 INT WINAPI WS_inet_pton( INT family, PCSTR addr, PVOID buffer)
7071 #ifdef HAVE_INET_PTON
7072 int unixaf, ret;
7074 TRACE("family %d, addr '%s', buffer (%p)\n", family, addr ? addr : "(null)", buffer);
7076 if (!addr || !buffer)
7078 SetLastError(WSAEFAULT);
7079 return SOCKET_ERROR;
7082 unixaf = convert_af_w2u(family);
7083 if (unixaf != AF_INET && unixaf != AF_INET6)
7085 SetLastError(WSAEAFNOSUPPORT);
7086 return SOCKET_ERROR;
7089 ret = inet_pton(unixaf, addr, buffer);
7090 if (ret == -1) SetLastError(wsaErrno());
7091 return ret;
7092 #else
7093 FIXME( "not supported on this platform\n" );
7094 SetLastError( WSAEAFNOSUPPORT );
7095 return SOCKET_ERROR;
7096 #endif
7100 /***********************************************************************
7101 * WSAStringToAddressA (WS2_32.80)
7103 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
7104 INT AddressFamily,
7105 LPWSAPROTOCOL_INFOA lpProtocolInfo,
7106 LPSOCKADDR lpAddress,
7107 LPINT lpAddressLength)
7109 INT res=0;
7110 LPSTR workBuffer=NULL,ptrPort;
7112 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
7113 lpProtocolInfo, lpAddress, lpAddressLength );
7115 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
7117 if (!AddressString)
7119 SetLastError(WSAEINVAL);
7120 return SOCKET_ERROR;
7123 if (lpProtocolInfo)
7124 FIXME("ProtocolInfo not implemented.\n");
7126 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
7127 strlen(AddressString) + 1);
7128 if (!workBuffer)
7130 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7131 return SOCKET_ERROR;
7134 strcpy(workBuffer, AddressString);
7136 switch(AddressFamily)
7138 case WS_AF_INET:
7140 struct in_addr inetaddr;
7142 /* If lpAddressLength is too small, tell caller the size we need */
7143 if (*lpAddressLength < sizeof(SOCKADDR_IN))
7145 *lpAddressLength = sizeof(SOCKADDR_IN);
7146 res = WSAEFAULT;
7147 break;
7149 *lpAddressLength = sizeof(SOCKADDR_IN);
7150 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
7152 ((LPSOCKADDR_IN)lpAddress)->sin_family = WS_AF_INET;
7154 ptrPort = strchr(workBuffer, ':');
7155 if(ptrPort)
7157 /* User may have entered an IPv6 and asked to parse as IPv4 */
7158 if(strchr(ptrPort + 1, ':'))
7160 res = WSAEINVAL;
7161 break;
7163 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
7164 *ptrPort = '\0';
7166 else
7168 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
7171 if(inet_aton(workBuffer, &inetaddr) > 0)
7173 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
7174 res = 0;
7176 else
7177 res = WSAEINVAL;
7179 break;
7182 case WS_AF_INET6:
7184 struct in6_addr inetaddr;
7185 /* If lpAddressLength is too small, tell caller the size we need */
7186 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
7188 *lpAddressLength = sizeof(SOCKADDR_IN6);
7189 res = WSAEFAULT;
7190 break;
7192 #ifdef HAVE_INET_PTON
7193 *lpAddressLength = sizeof(SOCKADDR_IN6);
7194 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
7196 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
7198 /* This one is a bit tricky. An IPv6 address contains colons, so the
7199 * check from IPv4 doesn't work like that. However, IPv6 addresses that
7200 * contain a port are written with braces like [fd12:3456:7890::1]:12345
7201 * so what we will do is to look for ']', check if the next char is a
7202 * colon, and if it is, parse the port as in IPv4. */
7204 ptrPort = strchr(workBuffer, ']');
7205 if(ptrPort && *(++ptrPort) == ':')
7207 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort+1));
7208 *ptrPort = '\0';
7210 else
7212 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
7215 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
7217 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
7218 sizeof(struct in6_addr));
7219 res = 0;
7221 else
7222 #endif /* HAVE_INET_PTON */
7223 res = WSAEINVAL;
7225 break;
7227 default:
7228 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
7229 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
7230 res = WSAEINVAL;
7233 HeapFree(GetProcessHeap(), 0, workBuffer);
7235 if (!res) return 0;
7236 SetLastError(res);
7237 return SOCKET_ERROR;
7240 /***********************************************************************
7241 * WSAStringToAddressW (WS2_32.81)
7243 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
7244 * If this should be the case, it would be required to map these digits
7245 * to Unicode digits (0-9) using FoldString first.
7247 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
7248 INT AddressFamily,
7249 LPWSAPROTOCOL_INFOW lpProtocolInfo,
7250 LPSOCKADDR lpAddress,
7251 LPINT lpAddressLength)
7253 INT sBuffer,res=0;
7254 LPSTR workBuffer=NULL;
7255 WSAPROTOCOL_INFOA infoA;
7256 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
7258 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
7259 lpAddress, lpAddressLength );
7261 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
7263 /* if ProtocolInfo is available - convert to ANSI variant */
7264 if (lpProtocolInfo)
7266 lpProtoInfoA = &infoA;
7267 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
7269 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
7270 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
7272 SetLastError(WSAEINVAL);
7273 return SOCKET_ERROR;
7277 if (AddressString)
7279 /* Translate AddressString to ANSI code page - assumes that only
7280 standard digits 0-9 are used with this API call */
7281 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
7282 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
7284 if (workBuffer)
7286 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
7287 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
7288 lpAddress,lpAddressLength);
7289 HeapFree( GetProcessHeap(), 0, workBuffer );
7290 return res;
7292 else
7293 res = WSA_NOT_ENOUGH_MEMORY;
7295 else
7296 res = WSAEINVAL;
7298 SetLastError(res);
7299 return SOCKET_ERROR;
7302 /***********************************************************************
7303 * WSAAddressToStringA (WS2_32.27)
7305 * See WSAAddressToStringW
7307 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
7308 LPWSAPROTOCOL_INFOA info, LPSTR string,
7309 LPDWORD lenstr )
7311 DWORD size;
7312 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
7313 CHAR *p;
7315 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
7317 if (!sockaddr) return SOCKET_ERROR;
7318 if (!string || !lenstr) return SOCKET_ERROR;
7320 switch(sockaddr->sa_family)
7322 case WS_AF_INET:
7323 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
7324 sprintf( buffer, "%u.%u.%u.%u:%u",
7325 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
7326 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
7327 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
7328 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
7329 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
7331 p = strchr( buffer, ':' );
7332 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
7333 break;
7335 case WS_AF_INET6:
7337 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
7339 buffer[0] = 0;
7340 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
7341 if ((sockaddr6->sin6_port))
7342 strcpy(buffer, "[");
7343 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, buffer+strlen(buffer), sizeof(buffer)))
7345 SetLastError(WSAEINVAL);
7346 return SOCKET_ERROR;
7348 if ((sockaddr6->sin6_scope_id))
7349 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
7350 if ((sockaddr6->sin6_port))
7351 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
7352 break;
7355 default:
7356 SetLastError(WSAEINVAL);
7357 return SOCKET_ERROR;
7360 size = strlen( buffer ) + 1;
7362 if (*lenstr < size)
7364 *lenstr = size;
7365 SetLastError(WSAEFAULT);
7366 return SOCKET_ERROR;
7369 TRACE("=> %s,%u bytes\n", debugstr_a(buffer), size);
7370 *lenstr = size;
7371 strcpy( string, buffer );
7372 return 0;
7375 /***********************************************************************
7376 * WSAAddressToStringW (WS2_32.28)
7378 * Convert a sockaddr address into a readable address string.
7380 * PARAMS
7381 * sockaddr [I] Pointer to a sockaddr structure.
7382 * len [I] Size of the sockaddr structure.
7383 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
7384 * string [I/O] Pointer to a buffer to receive the address string.
7385 * lenstr [I/O] Size of the receive buffer in WCHARs.
7387 * RETURNS
7388 * Success: 0
7389 * Failure: SOCKET_ERROR
7391 * NOTES
7392 * The 'info' parameter is ignored.
7394 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
7395 LPWSAPROTOCOL_INFOW info, LPWSTR string,
7396 LPDWORD lenstr )
7398 INT ret;
7399 DWORD size;
7400 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
7401 CHAR bufAddr[54];
7403 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
7405 size = *lenstr;
7406 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
7408 if (ret) return ret;
7410 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
7412 if (*lenstr < size)
7414 *lenstr = size;
7415 SetLastError(WSAEFAULT);
7416 return SOCKET_ERROR;
7419 TRACE("=> %s,%u bytes\n", debugstr_w(buffer), size);
7420 *lenstr = size;
7421 lstrcpyW( string, buffer );
7422 return 0;
7425 /***********************************************************************
7426 * WSAEnumNameSpaceProvidersA (WS2_32.34)
7428 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
7430 FIXME( "(%p %p) Stub!\n", len, buffer );
7431 return 0;
7434 /***********************************************************************
7435 * WSAEnumNameSpaceProvidersW (WS2_32.35)
7437 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
7439 FIXME( "(%p %p) Stub!\n", len, buffer );
7440 return 0;
7443 /***********************************************************************
7444 * WSAGetQOSByName (WS2_32.41)
7446 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
7448 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
7449 return FALSE;
7452 /***********************************************************************
7453 * WSAGetServiceClassInfoA (WS2_32.42)
7455 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
7456 LPWSASERVICECLASSINFOA info )
7458 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
7459 len, info );
7460 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7461 return SOCKET_ERROR;
7464 /***********************************************************************
7465 * WSAGetServiceClassInfoW (WS2_32.43)
7467 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
7468 LPWSASERVICECLASSINFOW info )
7470 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
7471 len, info );
7472 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7473 return SOCKET_ERROR;
7476 /***********************************************************************
7477 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
7479 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
7481 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
7482 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7483 return SOCKET_ERROR;
7486 /***********************************************************************
7487 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
7489 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
7491 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
7492 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7493 return SOCKET_ERROR;
7496 /***********************************************************************
7497 * WSALookupServiceBeginA (WS2_32.59)
7499 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
7500 DWORD dwControlFlags,
7501 LPHANDLE lphLookup)
7503 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
7504 lphLookup);
7505 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7506 return SOCKET_ERROR;
7509 /***********************************************************************
7510 * WSALookupServiceBeginW (WS2_32.60)
7512 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
7513 DWORD dwControlFlags,
7514 LPHANDLE lphLookup)
7516 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
7517 lphLookup);
7518 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7519 return SOCKET_ERROR;
7522 /***********************************************************************
7523 * WSALookupServiceEnd (WS2_32.61)
7525 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
7527 FIXME("(%p) Stub!\n", lookup );
7528 return 0;
7531 /***********************************************************************
7532 * WSALookupServiceNextA (WS2_32.62)
7534 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
7536 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
7537 SetLastError(WSA_E_NO_MORE);
7538 return SOCKET_ERROR;
7541 /***********************************************************************
7542 * WSALookupServiceNextW (WS2_32.63)
7544 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
7546 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
7547 SetLastError(WSA_E_NO_MORE);
7548 return SOCKET_ERROR;
7551 /***********************************************************************
7552 * WSANtohl (WS2_32.64)
7554 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
7556 TRACE( "(%04lx 0x%08x %p)\n", s, netlong, lphostlong );
7558 if (!lphostlong) return WSAEFAULT;
7560 *lphostlong = ntohl( netlong );
7561 return 0;
7564 /***********************************************************************
7565 * WSANtohs (WS2_32.65)
7567 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
7569 TRACE( "(%04lx 0x%08x %p)\n", s, netshort, lphostshort );
7571 if (!lphostshort) return WSAEFAULT;
7573 *lphostshort = ntohs( netshort );
7574 return 0;
7577 /***********************************************************************
7578 * WSAProviderConfigChange (WS2_32.66)
7580 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
7581 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
7583 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
7584 return SOCKET_ERROR;
7587 /***********************************************************************
7588 * WSARecvDisconnect (WS2_32.68)
7590 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
7592 TRACE( "(%04lx %p)\n", s, disconnectdata );
7594 return WS_shutdown( s, SD_RECEIVE );
7597 /***********************************************************************
7598 * WSASetServiceA (WS2_32.76)
7600 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
7602 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
7603 return 0;
7606 /***********************************************************************
7607 * WSASetServiceW (WS2_32.77)
7609 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
7611 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
7612 return 0;
7615 /***********************************************************************
7616 * WSCEnableNSProvider (WS2_32.84)
7618 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
7620 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
7621 return 0;
7624 /***********************************************************************
7625 * WSCGetProviderPath (WS2_32.86)
7627 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
7629 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
7631 if (!errcode || !provider || !len) return WSAEFAULT;
7633 *errcode = WSAEINVAL;
7634 return SOCKET_ERROR;
7637 /***********************************************************************
7638 * WSCInstallNameSpace (WS2_32.87)
7640 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
7641 DWORD version, LPGUID provider )
7643 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
7644 namespace, version, debugstr_guid(provider) );
7645 return 0;
7648 /***********************************************************************
7649 * WSCUnInstallNameSpace (WS2_32.89)
7651 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
7653 FIXME("(%p) Stub!\n", lpProviderId);
7654 return NO_ERROR;
7657 /***********************************************************************
7658 * WSCWriteProviderOrder (WS2_32.91)
7660 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
7662 FIXME("(%p 0x%08x) Stub!\n", entry, number);
7663 return 0;
7666 /***********************************************************************
7667 * WSANSPIoctl (WS2_32.91)
7669 INT WINAPI WSANSPIoctl( HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer,
7670 DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer,
7671 LPDWORD lpcbBytesReturned, LPWSACOMPLETION lpCompletion )
7673 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup, dwControlCode,
7674 lpvInBuffer, cbInBuffer, lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpCompletion);
7675 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7676 return SOCKET_ERROR;
7679 /*****************************************************************************
7680 * WSAEnumProtocolsA [WS2_32.@]
7682 * see function WSAEnumProtocolsW
7684 INT WINAPI WSAEnumProtocolsA( LPINT protocols, LPWSAPROTOCOL_INFOA buffer, LPDWORD len )
7686 return WS_EnumProtocols( FALSE, protocols, (LPWSAPROTOCOL_INFOW) buffer, len);
7689 /*****************************************************************************
7690 * WSAEnumProtocolsW [WS2_32.@]
7692 * Retrieves information about specified set of active network protocols.
7694 * PARAMS
7695 * protocols [I] Pointer to null-terminated array of protocol id's. NULL
7696 * retrieves information on all available protocols.
7697 * buffer [I] Pointer to a buffer to be filled with WSAPROTOCOL_INFO
7698 * structures.
7699 * len [I/O] Pointer to a variable specifying buffer size. On output
7700 * the variable holds the number of bytes needed when the
7701 * specified size is too small.
7703 * RETURNS
7704 * Success: number of WSAPROTOCOL_INFO structures in buffer.
7705 * Failure: SOCKET_ERROR
7707 * NOTES
7708 * NT4SP5 does not return SPX if protocols == NULL
7710 * BUGS
7711 * - NT4SP5 returns in addition these list of NETBIOS protocols
7712 * (address family 17), each entry two times one for socket type 2 and 5
7714 * iProtocol szProtocol
7715 * 0x80000000 \Device\NwlnkNb
7716 * 0xfffffffa \Device\NetBT_CBENT7
7717 * 0xfffffffb \Device\Nbf_CBENT7
7718 * 0xfffffffc \Device\NetBT_NdisWan5
7719 * 0xfffffffd \Device\NetBT_El9202
7720 * 0xfffffffe \Device\Nbf_El9202
7721 * 0xffffffff \Device\Nbf_NdisWan4
7723 * - there is no check that the operating system supports the returned
7724 * protocols
7726 INT WINAPI WSAEnumProtocolsW( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
7728 return WS_EnumProtocols( TRUE, protocols, buffer, len);
7731 /*****************************************************************************
7732 * WSCEnumProtocols [WS2_32.@]
7734 * PARAMS
7735 * protocols [I] Null-terminated array of iProtocol values.
7736 * buffer [O] Buffer of WSAPROTOCOL_INFOW structures.
7737 * len [I/O] Size of buffer on input/output.
7738 * errno [O] Error code.
7740 * RETURNS
7741 * Success: number of protocols to be reported on.
7742 * Failure: SOCKET_ERROR. error is in errno.
7744 * BUGS
7745 * Doesn't supply info on layered protocols.
7748 INT WINAPI WSCEnumProtocols( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len, LPINT err )
7750 INT ret = WSAEnumProtocolsW( protocols, buffer, len );
7752 if (ret == SOCKET_ERROR) *err = WSAENOBUFS;
7754 return ret;