widl: Handle aggregate returns in a MSVC compatible way.
[wine/multimedia.git] / dlls / ws2_32 / socket.c
blobd5e9fd17cdb24f5e3fa7c36d24a1c9b11a2a34f8
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 typedef struct ws2_async
335 HANDLE hSocket;
336 int type;
337 LPWSAOVERLAPPED user_overlapped;
338 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
339 IO_STATUS_BLOCK local_iosb;
340 struct WS_sockaddr *addr;
341 union
343 int val; /* for send operations */
344 int *ptr; /* for recv operations */
345 } addrlen;
346 DWORD flags;
347 DWORD *lpFlags;
348 WSABUF *control;
349 unsigned int n_iovecs;
350 unsigned int first_iovec;
351 struct iovec iovec[1];
352 } ws2_async;
354 typedef struct ws2_accept_async
356 HANDLE listen_socket;
357 HANDLE accept_socket;
358 LPOVERLAPPED user_overlapped;
359 ULONG_PTR cvalue;
360 PVOID buf; /* buffer to write data to */
361 int data_len;
362 int local_len;
363 int remote_len;
364 struct ws2_async *read;
365 } ws2_accept_async;
367 /****************************************************************/
369 /* ----------------------------------- internal data */
371 /* ws_... struct conversion flags */
373 typedef struct /* WSAAsyncSelect() control struct */
375 HANDLE service, event, sock;
376 HWND hWnd;
377 UINT uMsg;
378 LONG lEvent;
379 } ws_select_info;
381 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
382 #define WS_MAX_UDP_DATAGRAM 1024
383 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
385 /* hostent's, servent's and protent's are stored in one buffer per thread,
386 * as documented on MSDN for the functions that return any of the buffers */
387 struct per_thread_data
389 int opentype;
390 struct WS_hostent *he_buffer;
391 struct WS_servent *se_buffer;
392 struct WS_protoent *pe_buffer;
393 int he_len;
394 int se_len;
395 int pe_len;
396 char ntoa_buffer[16]; /* 4*3 digits + 3 '.' + 1 '\0' */
399 /* internal: routing description information */
400 struct route {
401 struct in_addr addr;
402 IF_INDEX interface;
403 DWORD metric;
406 static INT num_startup; /* reference counter */
407 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
409 /* function prototypes */
410 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length);
411 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
412 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
413 static struct WS_servent *WS_dup_se(const struct servent* p_se);
414 static int ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size);
416 int WSAIOCTL_GetInterfaceCount(void);
417 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
419 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus, ULONG Information );
421 #define MAP_OPTION(opt) { WS_##opt, opt }
423 static const int ws_sock_map[][2] =
425 MAP_OPTION( SO_DEBUG ),
426 MAP_OPTION( SO_ACCEPTCONN ),
427 MAP_OPTION( SO_REUSEADDR ),
428 MAP_OPTION( SO_KEEPALIVE ),
429 MAP_OPTION( SO_DONTROUTE ),
430 MAP_OPTION( SO_BROADCAST ),
431 MAP_OPTION( SO_LINGER ),
432 MAP_OPTION( SO_OOBINLINE ),
433 MAP_OPTION( SO_SNDBUF ),
434 MAP_OPTION( SO_RCVBUF ),
435 MAP_OPTION( SO_ERROR ),
436 MAP_OPTION( SO_TYPE ),
437 #ifdef SO_RCVTIMEO
438 MAP_OPTION( SO_RCVTIMEO ),
439 #endif
440 #ifdef SO_SNDTIMEO
441 MAP_OPTION( SO_SNDTIMEO ),
442 #endif
445 static const int ws_tcp_map[][2] =
447 #ifdef TCP_NODELAY
448 MAP_OPTION( TCP_NODELAY ),
449 #endif
452 static const int ws_ip_map[][2] =
454 MAP_OPTION( IP_MULTICAST_IF ),
455 MAP_OPTION( IP_MULTICAST_TTL ),
456 MAP_OPTION( IP_MULTICAST_LOOP ),
457 MAP_OPTION( IP_ADD_MEMBERSHIP ),
458 MAP_OPTION( IP_DROP_MEMBERSHIP ),
459 MAP_OPTION( IP_OPTIONS ),
460 #ifdef IP_HDRINCL
461 MAP_OPTION( IP_HDRINCL ),
462 #endif
463 MAP_OPTION( IP_TOS ),
464 MAP_OPTION( IP_TTL ),
465 #ifdef IP_PKTINFO
466 MAP_OPTION( IP_PKTINFO ),
467 #endif
468 #ifdef IP_UNICAST_IF
469 MAP_OPTION( IP_UNICAST_IF ),
470 #endif
473 static const int ws_ipv6_map[][2] =
475 #ifdef IPV6_ADD_MEMBERSHIP
476 MAP_OPTION( IPV6_ADD_MEMBERSHIP ),
477 #endif
478 #ifdef IPV6_DROP_MEMBERSHIP
479 MAP_OPTION( IPV6_DROP_MEMBERSHIP ),
480 #endif
481 MAP_OPTION( IPV6_MULTICAST_IF ),
482 MAP_OPTION( IPV6_MULTICAST_HOPS ),
483 MAP_OPTION( IPV6_MULTICAST_LOOP ),
484 MAP_OPTION( IPV6_UNICAST_HOPS ),
485 MAP_OPTION( IPV6_V6ONLY ),
486 #ifdef IPV6_UNICAST_IF
487 MAP_OPTION( IPV6_UNICAST_IF ),
488 #endif
491 static const int ws_af_map[][2] =
493 MAP_OPTION( AF_UNSPEC ),
494 MAP_OPTION( AF_INET ),
495 MAP_OPTION( AF_INET6 ),
496 #ifdef HAS_IPX
497 MAP_OPTION( AF_IPX ),
498 #endif
499 #ifdef AF_IRDA
500 MAP_OPTION( AF_IRDA ),
501 #endif
502 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
505 static const int ws_socktype_map[][2] =
507 MAP_OPTION( SOCK_DGRAM ),
508 MAP_OPTION( SOCK_STREAM ),
509 MAP_OPTION( SOCK_RAW ),
510 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
513 static const int ws_proto_map[][2] =
515 MAP_OPTION( IPPROTO_IP ),
516 MAP_OPTION( IPPROTO_TCP ),
517 MAP_OPTION( IPPROTO_UDP ),
518 MAP_OPTION( IPPROTO_ICMP ),
519 MAP_OPTION( IPPROTO_IGMP ),
520 MAP_OPTION( IPPROTO_RAW ),
521 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
524 static const int ws_aiflag_map[][2] =
526 MAP_OPTION( AI_PASSIVE ),
527 MAP_OPTION( AI_CANONNAME ),
528 MAP_OPTION( AI_NUMERICHOST ),
529 #ifdef AI_NUMERICSERV
530 MAP_OPTION( AI_NUMERICSERV ),
531 #endif
532 MAP_OPTION( AI_V4MAPPED ),
533 MAP_OPTION( AI_ADDRCONFIG ),
536 static const int ws_niflag_map[][2] =
538 MAP_OPTION( NI_NOFQDN ),
539 MAP_OPTION( NI_NUMERICHOST ),
540 MAP_OPTION( NI_NAMEREQD ),
541 MAP_OPTION( NI_NUMERICSERV ),
542 MAP_OPTION( NI_DGRAM ),
545 static const int ws_eai_map[][2] =
547 MAP_OPTION( EAI_AGAIN ),
548 MAP_OPTION( EAI_BADFLAGS ),
549 MAP_OPTION( EAI_FAIL ),
550 MAP_OPTION( EAI_FAMILY ),
551 MAP_OPTION( EAI_MEMORY ),
552 /* Note: EAI_NODATA is deprecated, but still
553 * used by Windows and Linux... We map the newer
554 * EAI_NONAME to EAI_NODATA for now until Windows
555 * changes too.
557 #ifdef EAI_NODATA
558 MAP_OPTION( EAI_NODATA ),
559 #endif
560 #ifdef EAI_NONAME
561 { WS_EAI_NODATA, EAI_NONAME },
562 #endif
564 MAP_OPTION( EAI_SERVICE ),
565 MAP_OPTION( EAI_SOCKTYPE ),
566 { 0, 0 }
569 static const char magic_loopback_addr[] = {127, 12, 34, 56};
571 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
572 #ifdef IP_PKTINFO
573 static inline WSACMSGHDR *fill_control_message(int level, int type, WSACMSGHDR *current, ULONG *maxsize, void *data, int len)
575 ULONG msgsize = sizeof(WSACMSGHDR) + WSA_CMSG_ALIGN(len);
576 char *ptr = (char *) current + sizeof(WSACMSGHDR);
578 /* Make sure there is at least enough room for this entry */
579 if (msgsize > *maxsize)
580 return NULL;
581 *maxsize -= msgsize;
582 /* Fill in the entry */
583 current->cmsg_len = sizeof(WSACMSGHDR) + len;
584 current->cmsg_level = level;
585 current->cmsg_type = type;
586 memcpy(ptr, data, len);
587 /* Return the pointer to where next entry should go */
588 return (WSACMSGHDR *) (ptr + WSA_CMSG_ALIGN(len));
590 #endif /* IP_PKTINFO */
592 static inline int convert_control_headers(struct msghdr *hdr, WSABUF *control)
594 #ifdef IP_PKTINFO
595 WSACMSGHDR *cmsg_win = (WSACMSGHDR *) control->buf, *ptr;
596 ULONG ctlsize = control->len;
597 struct cmsghdr *cmsg_unix;
599 ptr = cmsg_win;
600 /* Loop over all the headers, converting as appropriate */
601 for (cmsg_unix = CMSG_FIRSTHDR(hdr); cmsg_unix != NULL; cmsg_unix = CMSG_NXTHDR(hdr, cmsg_unix))
603 switch(cmsg_unix->cmsg_level)
605 case IPPROTO_IP:
606 switch(cmsg_unix->cmsg_type)
608 case IP_PKTINFO:
610 /* Convert the Unix IP_PKTINFO structure to the Windows version */
611 struct in_pktinfo *data_unix = (struct in_pktinfo *) CMSG_DATA(cmsg_unix);
612 struct WS_in_pktinfo data_win;
614 memcpy(&data_win.ipi_addr,&data_unix->ipi_addr.s_addr,4); /* 4 bytes = 32 address bits */
615 data_win.ipi_ifindex = data_unix->ipi_ifindex;
616 ptr = fill_control_message(WS_IPPROTO_IP, WS_IP_PKTINFO, ptr, &ctlsize,
617 (void*)&data_win, sizeof(data_win));
618 if (!ptr) goto error;
619 } break;
620 default:
621 FIXME("Unhandled IPPROTO_IP message header type %d\n", cmsg_unix->cmsg_type);
622 break;
624 break;
625 default:
626 FIXME("Unhandled message header level %d\n", cmsg_unix->cmsg_level);
627 break;
631 error:
632 /* Set the length of the returned control headers */
633 control->len = (ptr == NULL ? 0 : (char*)ptr - (char*)cmsg_win);
634 return (ptr != NULL);
635 #else /* IP_PKTINFO */
636 control->len = 0;
637 return 1;
638 #endif /* IP_PKTINFO */
640 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
642 /* ----------------------------------- error handling */
644 static NTSTATUS sock_get_ntstatus( int err )
646 switch ( err )
648 case EBADF: return STATUS_INVALID_HANDLE;
649 case EBUSY: return STATUS_DEVICE_BUSY;
650 case EPERM:
651 case EACCES: return STATUS_ACCESS_DENIED;
652 case EFAULT: return STATUS_NO_MEMORY;
653 case EINVAL: return STATUS_INVALID_PARAMETER;
654 case ENFILE:
655 case EMFILE: return STATUS_TOO_MANY_OPENED_FILES;
656 case EWOULDBLOCK: return STATUS_CANT_WAIT;
657 case EINPROGRESS: return STATUS_PENDING;
658 case EALREADY: return STATUS_NETWORK_BUSY;
659 case ENOTSOCK: return STATUS_OBJECT_TYPE_MISMATCH;
660 case EDESTADDRREQ: return STATUS_INVALID_PARAMETER;
661 case EMSGSIZE: return STATUS_BUFFER_OVERFLOW;
662 case EPROTONOSUPPORT:
663 case ESOCKTNOSUPPORT:
664 case EPFNOSUPPORT:
665 case EAFNOSUPPORT:
666 case EPROTOTYPE: return STATUS_NOT_SUPPORTED;
667 case ENOPROTOOPT: return STATUS_INVALID_PARAMETER;
668 case EOPNOTSUPP: return STATUS_NOT_SUPPORTED;
669 case EADDRINUSE: return STATUS_ADDRESS_ALREADY_ASSOCIATED;
670 case EADDRNOTAVAIL: return STATUS_INVALID_PARAMETER;
671 case ECONNREFUSED: return STATUS_CONNECTION_REFUSED;
672 case ESHUTDOWN: return STATUS_PIPE_DISCONNECTED;
673 case ENOTCONN: return STATUS_CONNECTION_DISCONNECTED;
674 case ETIMEDOUT: return STATUS_IO_TIMEOUT;
675 case ENETUNREACH: return STATUS_NETWORK_UNREACHABLE;
676 case ENETDOWN: return STATUS_NETWORK_BUSY;
677 case EPIPE:
678 case ECONNRESET: return STATUS_CONNECTION_RESET;
679 case ECONNABORTED: return STATUS_CONNECTION_ABORTED;
681 case 0: return STATUS_SUCCESS;
682 default:
683 WARN("Unknown errno %d!\n", err);
684 return STATUS_UNSUCCESSFUL;
688 static UINT sock_get_error( int err )
690 switch(err)
692 case EINTR: return WSAEINTR;
693 case EBADF: return WSAEBADF;
694 case EPERM:
695 case EACCES: return WSAEACCES;
696 case EFAULT: return WSAEFAULT;
697 case EINVAL: return WSAEINVAL;
698 case EMFILE: return WSAEMFILE;
699 case EWOULDBLOCK: return WSAEWOULDBLOCK;
700 case EINPROGRESS: return WSAEINPROGRESS;
701 case EALREADY: return WSAEALREADY;
702 case ENOTSOCK: return WSAENOTSOCK;
703 case EDESTADDRREQ: return WSAEDESTADDRREQ;
704 case EMSGSIZE: return WSAEMSGSIZE;
705 case EPROTOTYPE: return WSAEPROTOTYPE;
706 case ENOPROTOOPT: return WSAENOPROTOOPT;
707 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
708 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
709 case EOPNOTSUPP: return WSAEOPNOTSUPP;
710 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
711 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
712 case EADDRINUSE: return WSAEADDRINUSE;
713 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
714 case ENETDOWN: return WSAENETDOWN;
715 case ENETUNREACH: return WSAENETUNREACH;
716 case ENETRESET: return WSAENETRESET;
717 case ECONNABORTED: return WSAECONNABORTED;
718 case EPIPE:
719 case ECONNRESET: return WSAECONNRESET;
720 case ENOBUFS: return WSAENOBUFS;
721 case EISCONN: return WSAEISCONN;
722 case ENOTCONN: return WSAENOTCONN;
723 case ESHUTDOWN: return WSAESHUTDOWN;
724 case ETOOMANYREFS: return WSAETOOMANYREFS;
725 case ETIMEDOUT: return WSAETIMEDOUT;
726 case ECONNREFUSED: return WSAECONNREFUSED;
727 case ELOOP: return WSAELOOP;
728 case ENAMETOOLONG: return WSAENAMETOOLONG;
729 case EHOSTDOWN: return WSAEHOSTDOWN;
730 case EHOSTUNREACH: return WSAEHOSTUNREACH;
731 case ENOTEMPTY: return WSAENOTEMPTY;
732 #ifdef EPROCLIM
733 case EPROCLIM: return WSAEPROCLIM;
734 #endif
735 #ifdef EUSERS
736 case EUSERS: return WSAEUSERS;
737 #endif
738 #ifdef EDQUOT
739 case EDQUOT: return WSAEDQUOT;
740 #endif
741 #ifdef ESTALE
742 case ESTALE: return WSAESTALE;
743 #endif
744 #ifdef EREMOTE
745 case EREMOTE: return WSAEREMOTE;
746 #endif
748 /* just in case we ever get here and there are no problems */
749 case 0: return 0;
750 default:
751 WARN("Unknown errno %d!\n", err);
752 return WSAEOPNOTSUPP;
756 static UINT wsaErrno(void)
758 int loc_errno = errno;
759 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
761 return sock_get_error( loc_errno );
764 /* most ws2 overlapped functions return an ntstatus-based error code */
765 static NTSTATUS wsaErrStatus(void)
767 int loc_errno = errno;
768 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
770 return sock_get_ntstatus(loc_errno);
773 static UINT wsaHerrno(int loc_errno)
775 WARN("h_errno %d.\n", loc_errno);
777 switch(loc_errno)
779 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
780 case TRY_AGAIN: return WSATRY_AGAIN;
781 case NO_RECOVERY: return WSANO_RECOVERY;
782 case NO_DATA: return WSANO_DATA;
783 case ENOBUFS: return WSAENOBUFS;
785 case 0: return 0;
786 default:
787 WARN("Unknown h_errno %d!\n", loc_errno);
788 return WSAEOPNOTSUPP;
792 static inline DWORD NtStatusToWSAError( const DWORD status )
794 /* We only need to cover the status codes set by server async request handling */
795 DWORD wserr;
796 switch ( status )
798 case STATUS_SUCCESS: wserr = 0; break;
799 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
800 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
801 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
802 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
803 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
804 case STATUS_NETWORK_BUSY: wserr = WSAEALREADY; break;
805 case STATUS_NETWORK_UNREACHABLE: wserr = WSAENETUNREACH; break;
806 case STATUS_CONNECTION_REFUSED: wserr = WSAECONNREFUSED; break;
807 case STATUS_CONNECTION_DISCONNECTED: wserr = WSAENOTCONN; break;
808 case STATUS_CONNECTION_RESET: wserr = WSAECONNRESET; break;
809 case STATUS_CONNECTION_ABORTED: wserr = WSAECONNABORTED; break;
810 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
811 case STATUS_ADDRESS_ALREADY_ASSOCIATED: wserr = WSAEADDRINUSE; break;
812 case STATUS_IO_TIMEOUT:
813 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
814 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
815 case STATUS_ACCESS_DENIED: wserr = WSAEACCES; break;
816 case STATUS_TOO_MANY_OPENED_FILES: wserr = WSAEMFILE; break;
817 case STATUS_CANT_WAIT: wserr = WSAEWOULDBLOCK; break;
818 case STATUS_BUFFER_OVERFLOW: wserr = WSAEMSGSIZE; break;
819 case STATUS_NOT_SUPPORTED: wserr = WSAEOPNOTSUPP; break;
820 case STATUS_HOST_UNREACHABLE: wserr = WSAEHOSTUNREACH; break;
822 default:
823 wserr = RtlNtStatusToDosError( status );
824 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
826 return wserr;
829 /* set last error code from NT status without mapping WSA errors */
830 static inline unsigned int set_error( unsigned int err )
832 if (err)
834 err = NtStatusToWSAError( err );
835 SetLastError( err );
837 return err;
840 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
842 int fd;
843 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
844 return -1;
845 return fd;
848 static inline void release_sock_fd( SOCKET s, int fd )
850 wine_server_release_fd( SOCKET2HANDLE(s), fd );
853 static void _enable_event( HANDLE s, unsigned int event,
854 unsigned int sstate, unsigned int cstate )
856 SERVER_START_REQ( enable_socket_event )
858 req->handle = wine_server_obj_handle( s );
859 req->mask = event;
860 req->sstate = sstate;
861 req->cstate = cstate;
862 wine_server_call( req );
864 SERVER_END_REQ;
867 static NTSTATUS _is_blocking(SOCKET s, BOOL *ret)
869 NTSTATUS status;
870 SERVER_START_REQ( get_socket_event )
872 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
873 req->service = FALSE;
874 req->c_event = 0;
875 status = wine_server_call( req );
876 *ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
878 SERVER_END_REQ;
879 return status;
882 static unsigned int _get_sock_mask(SOCKET s)
884 unsigned int ret;
885 SERVER_START_REQ( get_socket_event )
887 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
888 req->service = FALSE;
889 req->c_event = 0;
890 wine_server_call( req );
891 ret = reply->mask;
893 SERVER_END_REQ;
894 return ret;
897 static void _sync_sock_state(SOCKET s)
899 BOOL dummy;
900 /* do a dummy wineserver request in order to let
901 the wineserver run through its select loop once */
902 (void)_is_blocking(s, &dummy);
905 static int _get_sock_error(SOCKET s, unsigned int bit)
907 int events[FD_MAX_EVENTS];
909 SERVER_START_REQ( get_socket_event )
911 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
912 req->service = FALSE;
913 req->c_event = 0;
914 wine_server_set_reply( req, events, sizeof(events) );
915 wine_server_call( req );
917 SERVER_END_REQ;
918 return events[bit];
921 static struct per_thread_data *get_per_thread_data(void)
923 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
924 /* lazy initialization */
925 if (!ptb)
927 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
928 NtCurrentTeb()->WinSockData = ptb;
930 return ptb;
933 static void free_per_thread_data(void)
935 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
937 if (!ptb) return;
939 /* delete scratch buffers */
940 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
941 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
942 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
943 ptb->he_buffer = NULL;
944 ptb->se_buffer = NULL;
945 ptb->pe_buffer = NULL;
947 HeapFree( GetProcessHeap(), 0, ptb );
948 NtCurrentTeb()->WinSockData = NULL;
951 /***********************************************************************
952 * DllMain (WS2_32.init)
954 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
956 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
957 switch (fdwReason) {
958 case DLL_PROCESS_ATTACH:
959 break;
960 case DLL_PROCESS_DETACH:
961 if (fImpLoad) break;
962 free_per_thread_data();
963 DeleteCriticalSection(&csWSgetXXXbyYYY);
964 break;
965 case DLL_THREAD_DETACH:
966 free_per_thread_data();
967 break;
969 return TRUE;
972 /***********************************************************************
973 * convert_sockopt()
975 * Converts socket flags from Windows format.
976 * Return 1 if converted, 0 if not (error).
978 static int convert_sockopt(INT *level, INT *optname)
980 unsigned int i;
981 switch (*level)
983 case WS_SOL_SOCKET:
984 *level = SOL_SOCKET;
985 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
986 if( ws_sock_map[i][0] == *optname )
988 *optname = ws_sock_map[i][1];
989 return 1;
992 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
993 break;
994 case WS_IPPROTO_TCP:
995 *level = IPPROTO_TCP;
996 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
997 if ( ws_tcp_map[i][0] == *optname )
999 *optname = ws_tcp_map[i][1];
1000 return 1;
1003 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
1004 break;
1005 case WS_IPPROTO_IP:
1006 *level = IPPROTO_IP;
1007 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
1008 if (ws_ip_map[i][0] == *optname )
1010 *optname = ws_ip_map[i][1];
1011 return 1;
1014 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
1015 break;
1016 case WS_IPPROTO_IPV6:
1017 *level = IPPROTO_IPV6;
1018 for(i=0; i<sizeof(ws_ipv6_map)/sizeof(ws_ipv6_map[0]); i++) {
1019 if (ws_ipv6_map[i][0] == *optname )
1021 *optname = ws_ipv6_map[i][1];
1022 return 1;
1025 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname);
1026 break;
1027 default: FIXME("Unimplemented or unknown socket level\n");
1029 return 0;
1032 /* ----------------------------------- Per-thread info (or per-process?) */
1034 static char *strdup_lower(const char *str)
1036 int i;
1037 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
1039 if (ret)
1041 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
1042 ret[i] = 0;
1044 else SetLastError(WSAENOBUFS);
1045 return ret;
1048 static inline int sock_error_p(int s)
1050 unsigned int optval;
1051 socklen_t optlen = sizeof(optval);
1052 getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
1053 if (optval) WARN("\t[%i] error: %d\n", s, optval);
1054 return optval != 0;
1057 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
1058 * from an fd and return the value converted to milli seconds
1059 * or -1 if there is an infinite time out */
1060 static inline int get_rcvsnd_timeo( int fd, int optname)
1062 struct timeval tv;
1063 socklen_t len = sizeof(tv);
1064 int ret = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
1065 if( ret >= 0)
1066 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
1067 if( ret <= 0 ) /* tv == {0,0} means infinite time out */
1068 return -1;
1069 return ret;
1072 /* macro wrappers for portability */
1073 #ifdef SO_RCVTIMEO
1074 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
1075 #else
1076 #define GET_RCVTIMEO(fd) (-1)
1077 #endif
1079 #ifdef SO_SNDTIMEO
1080 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
1081 #else
1082 #define GET_SNDTIMEO(fd) (-1)
1083 #endif
1085 /* utility: given an fd, will block until one of the events occurs */
1086 static inline int do_block( int fd, int events, int timeout )
1088 struct pollfd pfd;
1089 int ret;
1091 pfd.fd = fd;
1092 pfd.events = events;
1094 while ((ret = poll(&pfd, 1, timeout)) < 0)
1096 if (errno != EINTR)
1097 return -1;
1099 if( ret == 0 )
1100 return 0;
1101 return pfd.revents;
1104 static int
1105 convert_af_w2u(int windowsaf) {
1106 unsigned int i;
1108 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1109 if (ws_af_map[i][0] == windowsaf)
1110 return ws_af_map[i][1];
1111 FIXME("unhandled Windows address family %d\n", windowsaf);
1112 return -1;
1115 static int
1116 convert_af_u2w(int unixaf) {
1117 unsigned int i;
1119 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1120 if (ws_af_map[i][1] == unixaf)
1121 return ws_af_map[i][0];
1122 FIXME("unhandled UNIX address family %d\n", unixaf);
1123 return -1;
1126 static int
1127 convert_proto_w2u(int windowsproto) {
1128 unsigned int i;
1130 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1131 if (ws_proto_map[i][0] == windowsproto)
1132 return ws_proto_map[i][1];
1134 /* check for extended IPX */
1135 if (IS_IPX_PROTO(windowsproto))
1136 return windowsproto;
1138 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
1139 return -1;
1142 static int
1143 convert_proto_u2w(int unixproto) {
1144 unsigned int i;
1146 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1147 if (ws_proto_map[i][1] == unixproto)
1148 return ws_proto_map[i][0];
1150 /* if value is inside IPX range just return it - the kernel simply
1151 * echoes the value used in the socket() function */
1152 if (IS_IPX_PROTO(unixproto))
1153 return unixproto;
1155 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
1156 return -1;
1159 static int
1160 convert_socktype_w2u(int windowssocktype) {
1161 unsigned int i;
1163 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1164 if (ws_socktype_map[i][0] == windowssocktype)
1165 return ws_socktype_map[i][1];
1166 FIXME("unhandled Windows socket type %d\n", windowssocktype);
1167 return -1;
1170 static int
1171 convert_socktype_u2w(int unixsocktype) {
1172 unsigned int i;
1174 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1175 if (ws_socktype_map[i][1] == unixsocktype)
1176 return ws_socktype_map[i][0];
1177 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
1178 return -1;
1181 static int set_ipx_packettype(int sock, int ptype)
1183 #ifdef HAS_IPX
1184 int fd = get_sock_fd( sock, 0, NULL ), ret = 0;
1185 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", ptype, fd);
1187 if (fd == -1) return SOCKET_ERROR;
1189 /* We try to set the ipx type on ipx socket level. */
1190 #ifdef SOL_IPX
1191 if(setsockopt(fd, SOL_IPX, IPX_TYPE, &ptype, sizeof(ptype)) == -1)
1193 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
1194 ret = SOCKET_ERROR;
1196 #else
1198 struct ipx val;
1199 /* Should we retrieve val using a getsockopt call and then
1200 * set the modified one? */
1201 val.ipx_pt = ptype;
1202 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
1204 #endif
1205 release_sock_fd( sock, fd );
1206 return ret;
1207 #else
1208 WARN("IPX support is not enabled, can't set packet type\n");
1209 return SOCKET_ERROR;
1210 #endif
1213 /* ----------------------------------- API -----
1215 * Init / cleanup / error checking.
1218 /***********************************************************************
1219 * WSAStartup (WS2_32.115)
1221 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
1223 TRACE("verReq=%x\n", wVersionRequested);
1225 if (LOBYTE(wVersionRequested) < 1)
1226 return WSAVERNOTSUPPORTED;
1228 if (!lpWSAData) return WSAEINVAL;
1230 num_startup++;
1232 /* that's the whole of the negotiation for now */
1233 lpWSAData->wVersion = wVersionRequested;
1234 /* return winsock information */
1235 lpWSAData->wHighVersion = 0x0202;
1236 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
1237 strcpy(lpWSAData->szSystemStatus, "Running" );
1238 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
1239 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
1240 /* don't do anything with lpWSAData->lpVendorInfo */
1241 /* (some apps don't allocate the space for this field) */
1243 TRACE("succeeded starts: %d\n", num_startup);
1244 return 0;
1248 /***********************************************************************
1249 * WSACleanup (WS2_32.116)
1251 INT WINAPI WSACleanup(void)
1253 if (num_startup) {
1254 num_startup--;
1255 TRACE("pending cleanups: %d\n", num_startup);
1256 return 0;
1258 SetLastError(WSANOTINITIALISED);
1259 return SOCKET_ERROR;
1263 /***********************************************************************
1264 * WSAGetLastError (WS2_32.111)
1266 INT WINAPI WSAGetLastError(void)
1268 return GetLastError();
1271 /***********************************************************************
1272 * WSASetLastError (WS2_32.112)
1274 void WINAPI WSASetLastError(INT iError) {
1275 SetLastError(iError);
1278 static struct WS_hostent *check_buffer_he(int size)
1280 struct per_thread_data * ptb = get_per_thread_data();
1281 if (ptb->he_buffer)
1283 if (ptb->he_len >= size ) return ptb->he_buffer;
1284 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1286 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
1287 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
1288 return ptb->he_buffer;
1291 static struct WS_servent *check_buffer_se(int size)
1293 struct per_thread_data * ptb = get_per_thread_data();
1294 if (ptb->se_buffer)
1296 if (ptb->se_len >= size ) return ptb->se_buffer;
1297 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1299 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
1300 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
1301 return ptb->se_buffer;
1304 static struct WS_protoent *check_buffer_pe(int size)
1306 struct per_thread_data * ptb = get_per_thread_data();
1307 if (ptb->pe_buffer)
1309 if (ptb->pe_len >= size ) return ptb->pe_buffer;
1310 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1312 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
1313 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
1314 return ptb->pe_buffer;
1317 /* ----------------------------------- i/o APIs */
1319 static inline BOOL supported_pf(int pf)
1321 switch (pf)
1323 case WS_AF_INET:
1324 case WS_AF_INET6:
1325 return TRUE;
1326 #ifdef HAS_IPX
1327 case WS_AF_IPX:
1328 return TRUE;
1329 #endif
1330 #ifdef HAS_IRDA
1331 case WS_AF_IRDA:
1332 return TRUE;
1333 #endif
1334 default:
1335 return FALSE;
1339 static inline BOOL supported_protocol(int protocol)
1341 int i;
1342 for (i = 0; i < sizeof(valid_protocols) / sizeof(valid_protocols[0]); i++)
1343 if (protocol == valid_protocols[i])
1344 return TRUE;
1345 return FALSE;
1348 /**********************************************************************/
1350 /* Returns the length of the converted address if successful, 0 if it was too small to
1351 * start with.
1353 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
1354 union generic_unix_sockaddr *uaddr)
1356 unsigned int uaddrlen = 0;
1358 switch (wsaddr->sa_family)
1360 #ifdef HAS_IPX
1361 case WS_AF_IPX:
1363 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
1364 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
1366 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
1367 return 0;
1369 uaddrlen = sizeof(struct sockaddr_ipx);
1370 memset( uaddr, 0, uaddrlen );
1371 uipx->sipx_family=AF_IPX;
1372 uipx->sipx_port=wsipx->sa_socket;
1373 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1374 * in one go
1376 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
1377 #ifdef IPX_FRAME_NONE
1378 uipx->sipx_type=IPX_FRAME_NONE;
1379 #endif
1380 break;
1382 #endif
1383 case WS_AF_INET6: {
1384 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
1385 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
1387 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1388 * scope_id, one without.
1390 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
1391 uaddrlen = sizeof(struct sockaddr_in6);
1392 memset( uaddr, 0, uaddrlen );
1393 uin6->sin6_family = AF_INET6;
1394 uin6->sin6_port = win6->sin6_port;
1395 uin6->sin6_flowinfo = win6->sin6_flowinfo;
1396 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1397 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
1398 #endif
1399 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
1400 break;
1402 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
1403 return 0;
1405 case WS_AF_INET: {
1406 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
1407 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
1409 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
1410 return 0;
1411 uaddrlen = sizeof(struct sockaddr_in);
1412 memset( uaddr, 0, uaddrlen );
1413 uin->sin_family = AF_INET;
1414 uin->sin_port = win->sin_port;
1415 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
1416 break;
1418 #ifdef HAS_IRDA
1419 case WS_AF_IRDA: {
1420 struct sockaddr_irda *uin = (struct sockaddr_irda *)uaddr;
1421 const SOCKADDR_IRDA *win = (const SOCKADDR_IRDA *)wsaddr;
1423 if (wsaddrlen < sizeof(SOCKADDR_IRDA))
1424 return 0;
1425 uaddrlen = sizeof(struct sockaddr_irda);
1426 memset( uaddr, 0, uaddrlen );
1427 uin->sir_family = AF_IRDA;
1428 if (!strncmp( win->irdaServiceName, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1430 unsigned int lsap_sel = 0;
1432 sscanf( win->irdaServiceName, "LSAP-SEL%u", &lsap_sel );
1433 uin->sir_lsap_sel = lsap_sel;
1435 else
1437 uin->sir_lsap_sel = LSAP_ANY;
1438 memcpy( uin->sir_name, win->irdaServiceName, 25 );
1440 memcpy( &uin->sir_addr, win->irdaDeviceID, sizeof(uin->sir_addr) );
1441 break;
1443 #endif
1444 case WS_AF_UNSPEC: {
1445 /* Try to determine the needed space by the passed windows sockaddr space */
1446 switch (wsaddrlen) {
1447 default: /* likely an ipv4 address */
1448 case sizeof(struct WS_sockaddr_in):
1449 uaddrlen = sizeof(struct sockaddr_in);
1450 break;
1451 #ifdef HAS_IPX
1452 case sizeof(struct WS_sockaddr_ipx):
1453 uaddrlen = sizeof(struct sockaddr_ipx);
1454 break;
1455 #endif
1456 #ifdef HAS_IRDA
1457 case sizeof(SOCKADDR_IRDA):
1458 uaddrlen = sizeof(struct sockaddr_irda);
1459 break;
1460 #endif
1461 case sizeof(struct WS_sockaddr_in6):
1462 case sizeof(struct WS_sockaddr_in6_old):
1463 uaddrlen = sizeof(struct sockaddr_in6);
1464 break;
1466 memset( uaddr, 0, uaddrlen );
1467 break;
1469 default:
1470 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
1471 return 0;
1473 return uaddrlen;
1476 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
1478 switch (uaddr->sa_family)
1480 #ifdef HAS_IPX
1481 case AF_IPX:
1483 static const struct sockaddr_ipx emptyAddr;
1484 struct sockaddr_ipx *ipx = (struct sockaddr_ipx*) uaddr;
1485 return ipx->sipx_port
1486 || memcmp(&ipx->sipx_network, &emptyAddr.sipx_network, sizeof(emptyAddr.sipx_network))
1487 || memcmp(&ipx->sipx_node, &emptyAddr.sipx_node, sizeof(emptyAddr.sipx_node));
1489 #endif
1490 case AF_INET6:
1492 static const struct sockaddr_in6 emptyAddr;
1493 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
1494 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
1496 case AF_INET:
1498 static const struct sockaddr_in emptyAddr;
1499 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
1500 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
1502 case AF_UNSPEC:
1503 return FALSE;
1504 default:
1505 FIXME("unknown address family %d\n", uaddr->sa_family);
1506 return TRUE;
1510 /* Returns 0 if successful, -1 if the buffer is too small */
1511 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
1513 int res;
1515 switch(uaddr->sa_family)
1517 #ifdef HAS_IPX
1518 case AF_IPX:
1520 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
1521 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
1523 res=-1;
1524 switch (*wsaddrlen) /* how much can we copy? */
1526 default:
1527 res=0; /* enough */
1528 *wsaddrlen = sizeof(*wsipx);
1529 wsipx->sa_socket=uipx->sipx_port;
1530 /* fall through */
1531 case 13:
1532 case 12:
1533 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
1534 /* fall through */
1535 case 11:
1536 case 10:
1537 case 9:
1538 case 8:
1539 case 7:
1540 case 6:
1541 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1542 /* fall through */
1543 case 5:
1544 case 4:
1545 case 3:
1546 case 2:
1547 wsipx->sa_family=WS_AF_IPX;
1548 /* fall through */
1549 case 1:
1550 case 0:
1551 /* way too small */
1552 break;
1555 break;
1556 #endif
1557 #ifdef HAS_IRDA
1558 case AF_IRDA: {
1559 const struct sockaddr_irda *uin = (const struct sockaddr_irda *)uaddr;
1560 SOCKADDR_IRDA *win = (SOCKADDR_IRDA *)wsaddr;
1562 if (*wsaddrlen < sizeof(SOCKADDR_IRDA))
1563 return -1;
1564 win->irdaAddressFamily = WS_AF_IRDA;
1565 memcpy( win->irdaDeviceID, &uin->sir_addr, sizeof(win->irdaDeviceID) );
1566 if (uin->sir_lsap_sel != LSAP_ANY)
1567 sprintf( win->irdaServiceName, "LSAP-SEL%u", uin->sir_lsap_sel );
1568 else
1569 memcpy( win->irdaServiceName, uin->sir_name,
1570 sizeof(win->irdaServiceName) );
1571 return 0;
1573 #endif
1574 case AF_INET6: {
1575 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1576 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1578 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1579 return -1;
1580 win6old->sin6_family = WS_AF_INET6;
1581 win6old->sin6_port = uin6->sin6_port;
1582 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1583 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1584 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1585 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1586 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1587 win6->sin6_scope_id = uin6->sin6_scope_id;
1588 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1590 else
1591 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1592 #else
1593 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1594 #endif
1595 return 0;
1597 case AF_INET: {
1598 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1599 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1601 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1602 return -1;
1603 win->sin_family = WS_AF_INET;
1604 win->sin_port = uin->sin_port;
1605 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1606 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1607 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1608 return 0;
1610 case AF_UNSPEC: {
1611 memset(wsaddr,0,*wsaddrlen);
1612 return 0;
1614 default:
1615 FIXME("Unknown address family %d\n", uaddr->sa_family);
1616 return -1;
1618 return res;
1621 static INT WS_DuplicateSocket(BOOL unicode, SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo)
1623 HANDLE hProcess;
1624 int size;
1625 WSAPROTOCOL_INFOW infow;
1627 TRACE("(unicode %d, socket %04lx, processid %x, buffer %p)\n",
1628 unicode, s, dwProcessId, lpProtocolInfo);
1630 if (!ws_protocol_info(s, unicode, &infow, &size))
1631 return SOCKET_ERROR;
1633 if (!(hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId)))
1635 SetLastError(WSAEINVAL);
1636 return SOCKET_ERROR;
1639 if (!lpProtocolInfo)
1641 CloseHandle(hProcess);
1642 SetLastError(WSAEFAULT);
1643 return SOCKET_ERROR;
1646 /* I don't know what the real Windoze does next, this is a hack */
1647 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
1648 * the target use the global duplicate, or we could copy a reference to us to the structure
1649 * and let the target duplicate it from us, but let's do it as simple as possible */
1650 memcpy(lpProtocolInfo, &infow, size);
1651 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
1652 hProcess, (LPHANDLE)&lpProtocolInfo->dwServiceFlags3,
1653 0, FALSE, DUPLICATE_SAME_ACCESS);
1654 CloseHandle(hProcess);
1655 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
1656 return 0;
1659 /*****************************************************************************
1660 * WS_EnterSingleProtocolW [internal]
1662 * enters the protocol information of one given protocol into the given
1663 * buffer.
1665 * RETURNS
1666 * TRUE if a protocol was entered into the buffer.
1668 * BUGS
1669 * - only implemented for IPX, SPX, SPXII, TCP, UDP
1670 * - there is no check that the operating system supports the returned
1671 * protocols
1673 static BOOL WS_EnterSingleProtocolW( INT protocol, WSAPROTOCOL_INFOW* info )
1675 memset( info, 0, sizeof(WSAPROTOCOL_INFOW) );
1676 info->iProtocol = protocol;
1678 switch (protocol)
1680 case WS_IPPROTO_TCP:
1681 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_EXPEDITED_DATA |
1682 XP1_GRACEFUL_CLOSE | XP1_GUARANTEED_ORDER |
1683 XP1_GUARANTEED_DELIVERY;
1684 info->ProviderId = ProviderIdIP;
1685 info->dwCatalogEntryId = 0x3e9;
1686 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1687 info->ProtocolChain.ChainLen = 1;
1688 info->iVersion = 2;
1689 info->iAddressFamily = WS_AF_INET;
1690 info->iMaxSockAddr = 0x10;
1691 info->iMinSockAddr = 0x10;
1692 info->iSocketType = WS_SOCK_STREAM;
1693 strcpyW( info->szProtocol, NameTcpW );
1694 break;
1696 case WS_IPPROTO_UDP:
1697 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_SUPPORT_BROADCAST |
1698 XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED |
1699 XP1_CONNECTIONLESS;
1700 info->ProviderId = ProviderIdIP;
1701 info->dwCatalogEntryId = 0x3ea;
1702 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1703 info->ProtocolChain.ChainLen = 1;
1704 info->iVersion = 2;
1705 info->iAddressFamily = WS_AF_INET;
1706 info->iMaxSockAddr = 0x10;
1707 info->iMinSockAddr = 0x10;
1708 info->iSocketType = WS_SOCK_DGRAM;
1709 info->dwMessageSize = 0xffbb;
1710 strcpyW( info->szProtocol, NameUdpW );
1711 break;
1713 case WS_NSPROTO_IPX:
1714 info->dwServiceFlags1 = XP1_PARTIAL_MESSAGE | XP1_SUPPORT_BROADCAST |
1715 XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED |
1716 XP1_CONNECTIONLESS;
1717 info->ProviderId = ProviderIdIPX;
1718 info->dwCatalogEntryId = 0x406;
1719 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1720 info->ProtocolChain.ChainLen = 1;
1721 info->iVersion = 2;
1722 info->iAddressFamily = WS_AF_IPX;
1723 info->iMaxSockAddr = 0x10;
1724 info->iMinSockAddr = 0x0e;
1725 info->iSocketType = WS_SOCK_DGRAM;
1726 info->iProtocolMaxOffset = 0xff;
1727 info->dwMessageSize = 0x240;
1728 strcpyW( info->szProtocol, NameIpxW );
1729 break;
1731 case WS_NSPROTO_SPX:
1732 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_PSEUDO_STREAM |
1733 XP1_MESSAGE_ORIENTED | XP1_GUARANTEED_ORDER |
1734 XP1_GUARANTEED_DELIVERY;
1735 info->ProviderId = ProviderIdSPX;
1736 info->dwCatalogEntryId = 0x407;
1737 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1738 info->ProtocolChain.ChainLen = 1;
1739 info->iVersion = 2;
1740 info->iAddressFamily = WS_AF_IPX;
1741 info->iMaxSockAddr = 0x10;
1742 info->iMinSockAddr = 0x0e;
1743 info->iSocketType = WS_SOCK_SEQPACKET;
1744 info->dwMessageSize = 0xffffffff;
1745 strcpyW( info->szProtocol, NameSpxW );
1746 break;
1748 case WS_NSPROTO_SPXII:
1749 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_GRACEFUL_CLOSE |
1750 XP1_PSEUDO_STREAM | XP1_MESSAGE_ORIENTED |
1751 XP1_GUARANTEED_ORDER | XP1_GUARANTEED_DELIVERY;
1752 info->ProviderId = ProviderIdSPX;
1753 info->dwCatalogEntryId = 0x409;
1754 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1755 info->ProtocolChain.ChainLen = 1;
1756 info->iVersion = 2;
1757 info->iAddressFamily = WS_AF_IPX;
1758 info->iMaxSockAddr = 0x10;
1759 info->iMinSockAddr = 0x0e;
1760 info->iSocketType = WS_SOCK_SEQPACKET;
1761 info->dwMessageSize = 0xffffffff;
1762 strcpyW( info->szProtocol, NameSpxIIW );
1763 break;
1765 default:
1766 FIXME("unknown Protocol <0x%08x>\n", protocol);
1767 return FALSE;
1769 return TRUE;
1772 /*****************************************************************************
1773 * WS_EnterSingleProtocolA [internal]
1775 * see function WS_EnterSingleProtocolW
1778 static BOOL WS_EnterSingleProtocolA( INT protocol, WSAPROTOCOL_INFOA* info )
1780 WSAPROTOCOL_INFOW infow;
1781 INT ret;
1782 memset( info, 0, sizeof(WSAPROTOCOL_INFOA) );
1784 ret = WS_EnterSingleProtocolW( protocol, &infow );
1785 if (ret)
1787 /* convert the structure from W to A */
1788 memcpy( info, &infow, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
1789 WideCharToMultiByte( CP_ACP, 0, infow.szProtocol, -1,
1790 info->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL );
1793 return ret;
1796 static INT WS_EnumProtocols( BOOL unicode, const INT *protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
1798 INT i = 0, items = 0;
1799 DWORD size = 0;
1800 union _info
1802 LPWSAPROTOCOL_INFOA a;
1803 LPWSAPROTOCOL_INFOW w;
1804 } info;
1805 info.w = buffer;
1807 if (!protocols) protocols = valid_protocols;
1809 while (protocols[i])
1811 if(supported_protocol(protocols[i++]))
1812 items++;
1815 size = items * (unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA));
1817 TRACE("unicode %d, protocols %p, buffer %p, length %p %d, items %d, required %d\n",
1818 unicode, protocols, buffer, len, len ? *len : 0, items, size);
1820 if (*len < size || !buffer)
1822 *len = size;
1823 WSASetLastError(WSAENOBUFS);
1824 return SOCKET_ERROR;
1827 for (i = items = 0; protocols[i]; i++)
1829 if (!supported_protocol(protocols[i])) continue;
1830 if (unicode)
1832 if (WS_EnterSingleProtocolW( protocols[i], &info.w[items] ))
1833 items++;
1835 else
1837 if (WS_EnterSingleProtocolA( protocols[i], &info.a[items] ))
1838 items++;
1841 return items;
1844 static BOOL ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size)
1846 NTSTATUS status;
1848 *size = unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA);
1849 memset(buffer, 0, *size);
1851 SERVER_START_REQ( get_socket_info )
1853 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1854 status = wine_server_call( req );
1855 if (!status)
1857 buffer->iAddressFamily = convert_af_u2w(reply->family);
1858 buffer->iSocketType = convert_socktype_u2w(reply->type);
1859 buffer->iProtocol = convert_proto_u2w(reply->protocol);
1862 SERVER_END_REQ;
1864 if (status)
1866 unsigned int err = NtStatusToWSAError( status );
1867 SetLastError( err == WSAEBADF ? WSAENOTSOCK : err );
1868 return FALSE;
1871 if (unicode)
1872 WS_EnterSingleProtocolW( buffer->iProtocol, buffer);
1873 else
1874 WS_EnterSingleProtocolA( buffer->iProtocol, (WSAPROTOCOL_INFOA *)buffer);
1876 return TRUE;
1879 /**************************************************************************
1880 * Functions for handling overlapped I/O
1881 **************************************************************************/
1883 /* user APC called upon async completion */
1884 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1886 ws2_async *wsa = arg;
1888 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
1889 iosb->Information, wsa->user_overlapped,
1890 wsa->flags );
1891 HeapFree( GetProcessHeap(), 0, wsa );
1894 /***********************************************************************
1895 * WS2_recv (INTERNAL)
1897 * Workhorse for both synchronous and asynchronous recv() operations.
1899 static int WS2_recv( int fd, struct ws2_async *wsa )
1901 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1902 char pktbuf[512];
1903 #endif
1904 struct msghdr hdr;
1905 union generic_unix_sockaddr unix_sockaddr;
1906 int n;
1908 hdr.msg_name = NULL;
1910 if (wsa->addr)
1912 hdr.msg_namelen = sizeof(unix_sockaddr);
1913 hdr.msg_name = &unix_sockaddr;
1915 else
1916 hdr.msg_namelen = 0;
1918 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1919 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1920 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1921 hdr.msg_accrights = NULL;
1922 hdr.msg_accrightslen = 0;
1923 #else
1924 hdr.msg_control = pktbuf;
1925 hdr.msg_controllen = sizeof(pktbuf);
1926 hdr.msg_flags = 0;
1927 #endif
1929 while ((n = recvmsg(fd, &hdr, wsa->flags)) == -1)
1931 if (errno != EINTR)
1932 return -1;
1935 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1936 if (wsa->control)
1938 ERR("Message control headers cannot be properly supported on this system.\n");
1939 wsa->control->len = 0;
1941 #else
1942 if (wsa->control && !convert_control_headers(&hdr, wsa->control))
1944 WARN("Application passed insufficient room for control headers.\n");
1945 *wsa->lpFlags |= WS_MSG_CTRUNC;
1946 errno = EMSGSIZE;
1947 return -1;
1949 #endif
1951 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
1952 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
1954 * quoting linux 2.6 net/ipv4/tcp.c:
1955 * "According to UNIX98, msg_name/msg_namelen are ignored
1956 * on connected socket. I was just happy when found this 8) --ANK"
1958 * likewise MSDN says that lpFrom and lpFromlen are ignored for
1959 * connection-oriented sockets, so don't try to update lpFrom.
1961 if (wsa->addr && hdr.msg_namelen)
1962 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
1964 return n;
1967 /***********************************************************************
1968 * WS2_async_recv (INTERNAL)
1970 * Handler for overlapped recv() operations.
1972 static NTSTATUS WS2_async_recv( void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1974 ws2_async* wsa = user;
1975 int result = 0, fd;
1977 switch (status)
1979 case STATUS_ALERTED:
1980 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
1981 break;
1983 result = WS2_recv( fd, wsa );
1984 wine_server_release_fd( wsa->hSocket, fd );
1985 if (result >= 0)
1987 status = STATUS_SUCCESS;
1988 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1990 else
1992 if (errno == EAGAIN)
1994 status = STATUS_PENDING;
1995 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1997 else
1999 result = 0;
2000 status = wsaErrStatus();
2003 break;
2005 if (status != STATUS_PENDING)
2007 iosb->u.Status = status;
2008 iosb->Information = result;
2009 *apc = ws2_async_apc;
2011 return status;
2014 /* user APC called upon async accept completion */
2015 static void WINAPI ws2_async_accept_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
2017 struct ws2_accept_async *wsa = arg;
2019 HeapFree( GetProcessHeap(), 0, wsa->read );
2020 HeapFree( GetProcessHeap(), 0, wsa );
2023 /***********************************************************************
2024 * WS2_async_accept_recv (INTERNAL)
2026 * This function is used to finish the read part of an accept request. It is
2027 * needed to place the completion on the correct socket (listener).
2029 static NTSTATUS WS2_async_accept_recv( void *arg, IO_STATUS_BLOCK *iosb, NTSTATUS status, void **apc )
2031 void *junk;
2032 struct ws2_accept_async *wsa = arg;
2034 status = WS2_async_recv( wsa->read, iosb, status, &junk );
2035 if (status == STATUS_PENDING)
2036 return status;
2038 if (wsa->user_overlapped->hEvent)
2039 SetEvent(wsa->user_overlapped->hEvent);
2040 if (wsa->cvalue)
2041 WS_AddCompletion( HANDLE2SOCKET(wsa->listen_socket), wsa->cvalue, iosb->u.Status, iosb->Information );
2043 *apc = ws2_async_accept_apc;
2044 return status;
2047 /***********************************************************************
2048 * WS2_async_accept (INTERNAL)
2050 * This is the function called to satisfy the AcceptEx callback
2052 static NTSTATUS WS2_async_accept( void *arg, IO_STATUS_BLOCK *iosb, NTSTATUS status, void **apc )
2054 struct ws2_accept_async *wsa = arg;
2055 int len;
2056 char *addr;
2058 TRACE("status: 0x%x listen: %p, accept: %p\n", status, wsa->listen_socket, wsa->accept_socket);
2060 if (status == STATUS_ALERTED)
2062 SERVER_START_REQ( accept_into_socket )
2064 req->lhandle = wine_server_obj_handle( wsa->listen_socket );
2065 req->ahandle = wine_server_obj_handle( wsa->accept_socket );
2066 status = wine_server_call( req );
2068 SERVER_END_REQ;
2070 if (status == STATUS_CANT_WAIT)
2071 return STATUS_PENDING;
2073 if (status == STATUS_INVALID_HANDLE)
2075 FIXME("AcceptEx accepting socket closed but request was not cancelled\n");
2076 status = STATUS_CANCELLED;
2079 else if (status == STATUS_HANDLES_CLOSED)
2080 status = STATUS_CANCELLED; /* strange windows behavior */
2082 if (status != STATUS_SUCCESS)
2083 goto finish;
2085 /* WS2 Spec says size param is extra 16 bytes long...what do we put in it? */
2086 addr = ((char *)wsa->buf) + wsa->data_len;
2087 len = wsa->local_len - sizeof(int);
2088 WS_getsockname(HANDLE2SOCKET(wsa->accept_socket),
2089 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
2090 *(int *)addr = len;
2092 addr += wsa->local_len;
2093 len = wsa->remote_len - sizeof(int);
2094 WS_getpeername(HANDLE2SOCKET(wsa->accept_socket),
2095 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
2096 *(int *)addr = len;
2098 if (!wsa->read)
2099 goto finish;
2101 SERVER_START_REQ( register_async )
2103 req->type = ASYNC_TYPE_READ;
2104 req->async.handle = wine_server_obj_handle( wsa->accept_socket );
2105 req->async.callback = wine_server_client_ptr( WS2_async_accept_recv );
2106 req->async.iosb = wine_server_client_ptr( iosb );
2107 req->async.arg = wine_server_client_ptr( wsa );
2108 status = wine_server_call( req );
2110 SERVER_END_REQ;
2112 if (status != STATUS_PENDING)
2113 goto finish;
2115 /* The APC has finished but no completion should be sent for the operation yet, additional processing
2116 * needs to be performed by WS2_async_accept_recv() first. */
2117 return STATUS_MORE_PROCESSING_REQUIRED;
2119 finish:
2120 iosb->u.Status = status;
2121 iosb->Information = 0;
2123 if (wsa->user_overlapped->hEvent)
2124 SetEvent(wsa->user_overlapped->hEvent);
2126 *apc = ws2_async_accept_apc;
2127 return status;
2130 /***********************************************************************
2131 * WS2_send (INTERNAL)
2133 * Workhorse for both synchronous and asynchronous send() operations.
2135 static int WS2_send( int fd, struct ws2_async *wsa )
2137 struct msghdr hdr;
2138 union generic_unix_sockaddr unix_addr;
2139 int n, ret;
2141 hdr.msg_name = NULL;
2142 hdr.msg_namelen = 0;
2144 if (wsa->addr)
2146 hdr.msg_name = &unix_addr;
2147 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
2148 if ( !hdr.msg_namelen )
2150 errno = EFAULT;
2151 return -1;
2154 #if defined(HAS_IPX) && defined(SOL_IPX)
2155 if(wsa->addr->sa_family == WS_AF_IPX)
2157 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
2158 int val=0;
2159 socklen_t len = sizeof(int);
2161 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
2162 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
2163 * the packet type and then we can retrieve it using getsockopt. After that we can set the
2164 * ipx type in the sockaddr_opx structure with the stored value.
2166 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
2167 uipx->sipx_type = val;
2169 #endif
2172 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
2173 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
2174 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2175 hdr.msg_accrights = NULL;
2176 hdr.msg_accrightslen = 0;
2177 #else
2178 hdr.msg_control = NULL;
2179 hdr.msg_controllen = 0;
2180 hdr.msg_flags = 0;
2181 #endif
2183 while ((ret = sendmsg(fd, &hdr, wsa->flags)) == -1)
2185 if (errno != EINTR)
2186 return -1;
2189 n = ret;
2190 while (wsa->first_iovec < wsa->n_iovecs && wsa->iovec[wsa->first_iovec].iov_len <= n)
2191 n -= wsa->iovec[wsa->first_iovec++].iov_len;
2192 if (wsa->first_iovec < wsa->n_iovecs)
2194 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
2195 wsa->iovec[wsa->first_iovec].iov_len -= n;
2197 return ret;
2200 /***********************************************************************
2201 * WS2_async_send (INTERNAL)
2203 * Handler for overlapped send() operations.
2205 static NTSTATUS WS2_async_send(void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
2207 ws2_async* wsa = user;
2208 int result = 0, fd;
2210 switch (status)
2212 case STATUS_ALERTED:
2213 if ( wsa->n_iovecs <= wsa->first_iovec )
2215 /* Nothing to do */
2216 status = STATUS_SUCCESS;
2217 break;
2219 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
2220 break;
2222 /* check to see if the data is ready (non-blocking) */
2223 result = WS2_send( fd, wsa );
2224 wine_server_release_fd( wsa->hSocket, fd );
2226 if (result >= 0)
2228 if (wsa->first_iovec < wsa->n_iovecs)
2229 status = STATUS_PENDING;
2230 else
2231 status = STATUS_SUCCESS;
2233 iosb->Information += result;
2235 else if (errno == EAGAIN)
2237 status = STATUS_PENDING;
2239 else
2241 status = wsaErrStatus();
2243 break;
2245 if (status != STATUS_PENDING)
2247 iosb->u.Status = status;
2248 *apc = ws2_async_apc;
2250 return status;
2253 /***********************************************************************
2254 * WS2_async_shutdown (INTERNAL)
2256 * Handler for shutdown() operations on overlapped sockets.
2258 static NTSTATUS WS2_async_shutdown( void* user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc )
2260 ws2_async* wsa = user;
2261 int fd, err = 1;
2263 switch (status)
2265 case STATUS_ALERTED:
2266 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
2267 break;
2269 switch ( wsa->type )
2271 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
2272 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
2274 status = err ? wsaErrStatus() : STATUS_SUCCESS;
2275 wine_server_release_fd( wsa->hSocket, fd );
2276 break;
2278 iosb->u.Status = status;
2279 iosb->Information = 0;
2280 *apc = ws2_async_apc;
2281 return status;
2284 /***********************************************************************
2285 * WS2_register_async_shutdown (INTERNAL)
2287 * Helper function for WS_shutdown() on overlapped sockets.
2289 static int WS2_register_async_shutdown( SOCKET s, int type )
2291 struct ws2_async *wsa;
2292 NTSTATUS status;
2294 TRACE("s %ld type %d\n", s, type);
2296 wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( struct ws2_async, iovec[1] ));
2297 if ( !wsa )
2298 return WSAEFAULT;
2300 wsa->hSocket = SOCKET2HANDLE(s);
2301 wsa->type = type;
2302 wsa->completion_func = NULL;
2304 SERVER_START_REQ( register_async )
2306 req->type = type;
2307 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2308 req->async.callback = wine_server_client_ptr( WS2_async_shutdown );
2309 req->async.iosb = wine_server_client_ptr( &wsa->local_iosb );
2310 req->async.arg = wine_server_client_ptr( wsa );
2311 req->async.cvalue = 0;
2312 status = wine_server_call( req );
2314 SERVER_END_REQ;
2316 if (status != STATUS_PENDING)
2318 HeapFree( GetProcessHeap(), 0, wsa );
2319 return NtStatusToWSAError( status );
2321 return 0;
2324 /***********************************************************************
2325 * accept (WS2_32.1)
2327 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr, int *addrlen32)
2329 NTSTATUS status;
2330 SOCKET as;
2331 BOOL is_blocking;
2333 TRACE("socket %04lx\n", s );
2334 status = _is_blocking(s, &is_blocking);
2335 if (status)
2337 set_error(status);
2338 return INVALID_SOCKET;
2341 do {
2342 /* try accepting first (if there is a deferred connection) */
2343 SERVER_START_REQ( accept_socket )
2345 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
2346 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
2347 req->attributes = OBJ_INHERIT;
2348 status = wine_server_call( req );
2349 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
2351 SERVER_END_REQ;
2352 if (!status)
2354 if (addr && WS_getpeername(as, addr, addrlen32))
2356 WS_closesocket(as);
2357 return SOCKET_ERROR;
2359 return as;
2361 if (is_blocking && status == STATUS_CANT_WAIT)
2363 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2364 /* block here */
2365 do_block(fd, POLLIN, -1);
2366 _sync_sock_state(s); /* let wineserver notice connection */
2367 release_sock_fd( s, fd );
2369 } while (is_blocking && status == STATUS_CANT_WAIT);
2371 set_error(status);
2372 return INVALID_SOCKET;
2375 /***********************************************************************
2376 * AcceptEx
2378 static BOOL WINAPI WS2_AcceptEx(SOCKET listener, SOCKET acceptor, PVOID dest, DWORD dest_len,
2379 DWORD local_addr_len, DWORD rem_addr_len, LPDWORD received,
2380 LPOVERLAPPED overlapped)
2382 DWORD status;
2383 struct ws2_accept_async *wsa;
2384 int fd;
2385 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
2387 TRACE("(%lx, %lx, %p, %d, %d, %d, %p, %p)\n", listener, acceptor, dest, dest_len, local_addr_len,
2388 rem_addr_len, received, overlapped);
2390 if (!dest)
2392 SetLastError(WSAEINVAL);
2393 return FALSE;
2396 if (!overlapped)
2398 SetLastError(WSA_INVALID_PARAMETER);
2399 return FALSE;
2402 if (!rem_addr_len)
2404 SetLastError(WSAEFAULT);
2405 return FALSE;
2408 fd = get_sock_fd( listener, FILE_READ_DATA, NULL );
2409 if (fd == -1)
2411 SetLastError(WSAENOTSOCK);
2412 return FALSE;
2414 release_sock_fd( listener, fd );
2416 fd = get_sock_fd( acceptor, FILE_READ_DATA, NULL );
2417 if (fd == -1)
2419 SetLastError(WSAENOTSOCK);
2420 return FALSE;
2422 release_sock_fd( acceptor, fd );
2424 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
2425 if(!wsa)
2427 SetLastError(WSAEFAULT);
2428 return FALSE;
2431 wsa->listen_socket = SOCKET2HANDLE(listener);
2432 wsa->accept_socket = SOCKET2HANDLE(acceptor);
2433 wsa->user_overlapped = overlapped;
2434 wsa->cvalue = cvalue;
2435 wsa->buf = dest;
2436 wsa->data_len = dest_len;
2437 wsa->local_len = local_addr_len;
2438 wsa->remote_len = rem_addr_len;
2439 wsa->read = NULL;
2441 if (wsa->data_len)
2443 /* set up a read request if we need it */
2444 wsa->read = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[1]) );
2445 if (!wsa->read)
2447 HeapFree( GetProcessHeap(), 0, wsa );
2448 SetLastError(WSAEFAULT);
2449 return FALSE;
2452 wsa->read->hSocket = wsa->accept_socket;
2453 wsa->read->flags = 0;
2454 wsa->read->lpFlags = &wsa->read->flags;
2455 wsa->read->addr = NULL;
2456 wsa->read->addrlen.ptr = NULL;
2457 wsa->read->control = NULL;
2458 wsa->read->n_iovecs = 1;
2459 wsa->read->first_iovec = 0;
2460 wsa->read->iovec[0].iov_base = wsa->buf;
2461 wsa->read->iovec[0].iov_len = wsa->data_len;
2464 SERVER_START_REQ( register_async )
2466 req->type = ASYNC_TYPE_READ;
2467 req->async.handle = wine_server_obj_handle( SOCKET2HANDLE(listener) );
2468 req->async.callback = wine_server_client_ptr( WS2_async_accept );
2469 req->async.iosb = wine_server_client_ptr( overlapped );
2470 req->async.arg = wine_server_client_ptr( wsa );
2471 req->async.cvalue = cvalue;
2472 /* We don't set event since we may also have to read */
2473 status = wine_server_call( req );
2475 SERVER_END_REQ;
2477 if(status != STATUS_PENDING)
2479 HeapFree( GetProcessHeap(), 0, wsa->read );
2480 HeapFree( GetProcessHeap(), 0, wsa );
2483 SetLastError( NtStatusToWSAError(status) );
2484 return FALSE;
2487 /***********************************************************************
2488 * GetAcceptExSockaddrs
2490 static void WINAPI WS2_GetAcceptExSockaddrs(PVOID buffer, DWORD data_size, DWORD local_size, DWORD remote_size,
2491 struct WS_sockaddr **local_addr, LPINT local_addr_len,
2492 struct WS_sockaddr **remote_addr, LPINT remote_addr_len)
2494 char *cbuf = buffer;
2495 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer, data_size, local_size, remote_size, local_addr,
2496 local_addr_len, remote_addr, remote_addr_len );
2497 cbuf += data_size;
2499 *local_addr_len = *(int *) cbuf;
2500 *local_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2502 cbuf += local_size;
2504 *remote_addr_len = *(int *) cbuf;
2505 *remote_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2508 /***********************************************************************
2509 * WSASendMsg
2511 int WINAPI WSASendMsg( SOCKET s, LPWSAMSG msg, DWORD dwFlags, LPDWORD lpNumberOfBytesSent,
2512 LPWSAOVERLAPPED lpOverlapped,
2513 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
2515 if (!msg)
2517 SetLastError( WSAEFAULT );
2518 return SOCKET_ERROR;
2521 return WS2_sendto( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesSent,
2522 dwFlags, msg->name, msg->namelen,
2523 lpOverlapped, lpCompletionRoutine );
2526 /***********************************************************************
2527 * WSARecvMsg
2529 * Perform a receive operation that is capable of returning message
2530 * control headers. It is important to note that the WSAMSG parameter
2531 * must remain valid throughout the operation, even when an overlapped
2532 * receive is performed.
2534 static int WINAPI WS2_WSARecvMsg( SOCKET s, LPWSAMSG msg, LPDWORD lpNumberOfBytesRecvd,
2535 LPWSAOVERLAPPED lpOverlapped,
2536 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2538 if (!msg)
2540 SetLastError( WSAEFAULT );
2541 return SOCKET_ERROR;
2544 return WS2_recv_base( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesRecvd,
2545 &msg->dwFlags, msg->name, &msg->namelen,
2546 lpOverlapped, lpCompletionRoutine, &msg->Control );
2549 /***********************************************************************
2550 * interface_bind (INTERNAL)
2552 * Take bind() calls on any name corresponding to a local network adapter and restrict the given socket to
2553 * operating only on the specified interface. This restriction consists of two components:
2554 * 1) An outgoing packet restriction suggesting the egress interface for all packets.
2555 * 2) An incoming packet restriction dropping packets not meant for the interface.
2556 * If the function succeeds in placing these restrictions (returns TRUE) then the name for the bind() may
2557 * safely be changed to INADDR_ANY, permitting the transmission and receipt of broadcast packets on the
2558 * socket. This behavior is only relevant to UDP sockets and is needed for applications that expect to be able
2559 * to receive broadcast packets on a socket that is bound to a specific network interface.
2561 static BOOL interface_bind( SOCKET s, int fd, struct sockaddr *addr )
2563 struct sockaddr_in *in_sock = (struct sockaddr_in *) addr;
2564 unsigned int sock_type = 0;
2565 socklen_t optlen = sizeof(sock_type);
2566 in_addr_t bind_addr = in_sock->sin_addr.s_addr;
2567 PIP_ADAPTER_INFO adapters = NULL, adapter;
2568 BOOL ret = FALSE;
2569 DWORD adap_size;
2570 int enable = 1;
2572 if (bind_addr == htonl(INADDR_ANY) || bind_addr == htonl(INADDR_LOOPBACK))
2573 return FALSE; /* Not binding to a network adapter, special interface binding unnecessary. */
2574 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &sock_type, &optlen) == -1 || sock_type != SOCK_DGRAM)
2575 return FALSE; /* Special interface binding is only necessary for UDP datagrams. */
2576 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
2577 goto cleanup;
2578 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
2579 if (adapters == NULL || GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
2580 goto cleanup;
2581 /* Search the IPv4 adapter list for the appropriate binding interface */
2582 for (adapter = adapters; adapter != NULL; adapter = adapter->Next)
2584 in_addr_t adapter_addr = (in_addr_t) inet_addr(adapter->IpAddressList.IpAddress.String);
2586 if (bind_addr == adapter_addr)
2588 #if defined(IP_BOUND_IF)
2589 /* IP_BOUND_IF sets both the incoming and outgoing restriction at once */
2590 if (setsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &adapter->Index, sizeof(adapter->Index)) != 0)
2591 goto cleanup;
2592 ret = TRUE;
2593 #elif defined(LINUX_BOUND_IF)
2594 in_addr_t ifindex = (in_addr_t) htonl(adapter->Index);
2595 struct interface_filter specific_interface_filter;
2596 struct sock_fprog filter_prog;
2598 if (setsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex, sizeof(ifindex)) != 0)
2599 goto cleanup; /* Failed to suggest egress interface */
2600 specific_interface_filter = generic_interface_filter;
2601 specific_interface_filter.iface_rule.k = adapter->Index;
2602 specific_interface_filter.ip_rule.k = htonl(adapter_addr);
2603 filter_prog.len = sizeof(generic_interface_filter)/sizeof(struct sock_filter);
2604 filter_prog.filter = (struct sock_filter *) &specific_interface_filter;
2605 if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog, sizeof(filter_prog)) != 0)
2606 goto cleanup; /* Failed to specify incoming packet filter */
2607 ret = TRUE;
2608 #else
2609 FIXME("Broadcast packets on interface-bound sockets are not currently supported on this platform, "
2610 "receiving broadcast packets will not work on socket %04lx.\n", s);
2611 #endif
2612 break;
2615 /* Will soon be switching to INADDR_ANY: permit address reuse */
2616 if (ret && setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) == 0)
2617 TRACE("Socket %04lx bound to interface index %d\n", s, adapter->Index);
2618 else
2619 ret = FALSE;
2621 cleanup:
2622 if(!ret)
2623 ERR("Failed to bind to interface, receiving broadcast packets will not work on socket %04lx.\n", s);
2624 HeapFree(GetProcessHeap(), 0, adapters);
2625 return ret;
2628 /***********************************************************************
2629 * bind (WS2_32.2)
2631 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
2633 int fd = get_sock_fd( s, 0, NULL );
2634 int res = SOCKET_ERROR;
2636 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2638 if (fd != -1)
2640 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
2642 SetLastError(WSAEAFNOSUPPORT);
2644 else
2646 union generic_unix_sockaddr uaddr;
2647 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2648 if (!uaddrlen)
2650 SetLastError(WSAEFAULT);
2652 else
2654 #ifdef IPV6_V6ONLY
2655 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
2656 if (name->sa_family == WS_AF_INET6 &&
2657 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
2659 int enable = 1;
2660 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
2662 release_sock_fd( s, fd );
2663 SetLastError(WSAEAFNOSUPPORT);
2664 return SOCKET_ERROR;
2667 #endif
2668 if (name->sa_family == WS_AF_INET)
2670 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2671 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2673 /* Trying to bind to the default host interface, using
2674 * INADDR_ANY instead*/
2675 WARN("Trying to bind to magic IP address, using "
2676 "INADDR_ANY instead.\n");
2677 in4->sin_addr.s_addr = htonl(INADDR_ANY);
2679 else if (interface_bind(s, fd, &uaddr.addr))
2680 in4->sin_addr.s_addr = htonl(INADDR_ANY);
2682 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
2684 int loc_errno = errno;
2685 WARN("\tfailure - errno = %i\n", errno);
2686 errno = loc_errno;
2687 switch (errno)
2689 case EBADF:
2690 SetLastError(WSAENOTSOCK);
2691 break;
2692 case EADDRNOTAVAIL:
2693 SetLastError(WSAEINVAL);
2694 break;
2695 case EADDRINUSE:
2697 int optval = 0;
2698 socklen_t optlen = sizeof(optval);
2699 /* Windows >= 2003 will return different results depending on
2700 * SO_REUSEADDR, WSAEACCES may be returned representing that
2701 * the socket hijacking protection prevented the bind */
2702 if (!getsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&optval, &optlen) && optval)
2704 SetLastError(WSAEACCES);
2705 break;
2707 /* fall through */
2709 default:
2710 SetLastError(wsaErrno());
2711 break;
2714 else
2716 res=0; /* success */
2720 release_sock_fd( s, fd );
2722 return res;
2725 /***********************************************************************
2726 * closesocket (WS2_32.3)
2728 int WINAPI WS_closesocket(SOCKET s)
2730 TRACE("socket %04lx\n", s);
2731 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
2732 return SOCKET_ERROR;
2735 static int do_connect(int fd, const struct WS_sockaddr* name, int namelen)
2737 union generic_unix_sockaddr uaddr;
2738 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2740 if (!uaddrlen)
2741 return WSAEFAULT;
2743 if (name->sa_family == WS_AF_INET)
2745 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2746 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2748 /* Trying to connect to magic replace-loopback address,
2749 * assuming we really want to connect to localhost */
2750 TRACE("Trying to connect to magic IP address, using "
2751 "INADDR_LOOPBACK instead.\n");
2752 in4->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
2756 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
2757 return 0;
2759 return wsaErrno();
2762 /***********************************************************************
2763 * connect (WS2_32.4)
2765 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
2767 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2769 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2771 if (fd != -1)
2773 NTSTATUS status;
2774 BOOL is_blocking;
2775 int ret = do_connect(fd, name, namelen);
2776 if (ret == 0)
2777 goto connect_success;
2779 if (ret == WSAEINPROGRESS)
2781 /* tell wineserver that a connection is in progress */
2782 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2783 FD_CONNECT,
2784 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2785 status = _is_blocking( s, &is_blocking );
2786 if (status)
2788 release_sock_fd( s, fd );
2789 set_error( status );
2790 return SOCKET_ERROR;
2792 if (is_blocking)
2794 int result;
2795 /* block here */
2796 do_block(fd, POLLIN | POLLOUT, -1);
2797 _sync_sock_state(s); /* let wineserver notice connection */
2798 /* retrieve any error codes from it */
2799 result = _get_sock_error(s, FD_CONNECT_BIT);
2800 if (result)
2801 SetLastError(NtStatusToWSAError(result));
2802 else
2804 goto connect_success;
2807 else
2809 SetLastError(WSAEWOULDBLOCK);
2812 else
2814 SetLastError(ret);
2816 release_sock_fd( s, fd );
2818 return SOCKET_ERROR;
2820 connect_success:
2821 release_sock_fd( s, fd );
2822 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2823 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2824 FD_CONNECT|FD_WINE_LISTENING);
2825 return 0;
2828 /***********************************************************************
2829 * WSAConnect (WS2_32.30)
2831 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
2832 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
2833 LPQOS lpSQOS, LPQOS lpGQOS )
2835 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
2836 FIXME("unsupported parameters!\n");
2837 return WS_connect( s, name, namelen );
2840 /***********************************************************************
2841 * ConnectEx
2843 static BOOL WINAPI WS2_ConnectEx(SOCKET s, const struct WS_sockaddr* name, int namelen,
2844 PVOID sendBuf, DWORD sendBufLen, LPDWORD sent, LPOVERLAPPED ov)
2846 int fd, ret, status;
2847 union generic_unix_sockaddr uaddr;
2848 socklen_t uaddrlen = sizeof(uaddr);
2850 if (!ov)
2852 SetLastError( ERROR_INVALID_PARAMETER );
2853 return FALSE;
2856 fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2857 if (fd == -1)
2859 SetLastError( WSAENOTSOCK );
2860 return FALSE;
2863 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
2864 s, name, debugstr_sockaddr(name), namelen, sendBuf, sendBufLen, ov);
2866 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
2868 SetLastError(wsaErrno());
2869 return FALSE;
2871 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
2873 SetLastError(WSAEINVAL);
2874 return FALSE;
2877 ret = do_connect(fd, name, namelen);
2878 if (ret == 0)
2880 WSABUF wsabuf;
2882 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2883 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2884 FD_CONNECT|FD_WINE_LISTENING);
2886 wsabuf.len = sendBufLen;
2887 wsabuf.buf = (char*) sendBuf;
2889 /* WSASend takes care of completion if need be */
2890 if (WSASend(s, &wsabuf, sendBuf ? 1 : 0, sent, 0, ov, NULL) != SOCKET_ERROR)
2891 goto connection_success;
2893 else if (ret == WSAEINPROGRESS)
2895 struct ws2_async *wsa;
2896 ULONG_PTR cvalue = (((ULONG_PTR)ov->hEvent & 1) == 0) ? (ULONG_PTR)ov : 0;
2898 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2899 FD_CONNECT,
2900 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2902 /* Indirectly call WSASend */
2903 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( struct ws2_async, iovec[1] ))))
2905 SetLastError(WSAEFAULT);
2907 else
2909 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)ov;
2910 iosb->u.Status = STATUS_PENDING;
2911 iosb->Information = 0;
2913 wsa->hSocket = SOCKET2HANDLE(s);
2914 wsa->addr = NULL;
2915 wsa->addrlen.val = 0;
2916 wsa->flags = 0;
2917 wsa->lpFlags = &wsa->flags;
2918 wsa->control = NULL;
2919 wsa->n_iovecs = sendBuf ? 1 : 0;
2920 wsa->first_iovec = 0;
2921 wsa->completion_func = NULL;
2922 wsa->iovec[0].iov_base = sendBuf;
2923 wsa->iovec[0].iov_len = sendBufLen;
2925 SERVER_START_REQ( register_async )
2927 req->type = ASYNC_TYPE_WRITE;
2928 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2929 req->async.callback = wine_server_client_ptr( WS2_async_send );
2930 req->async.iosb = wine_server_client_ptr( iosb );
2931 req->async.arg = wine_server_client_ptr( wsa );
2932 req->async.event = wine_server_obj_handle( ov->hEvent );
2933 req->async.cvalue = cvalue;
2934 status = wine_server_call( req );
2936 SERVER_END_REQ;
2938 if (status != STATUS_PENDING) HeapFree(GetProcessHeap(), 0, wsa);
2940 /* If the connect already failed */
2941 if (status == STATUS_PIPE_DISCONNECTED)
2942 status = _get_sock_error(s, FD_CONNECT_BIT);
2943 SetLastError( NtStatusToWSAError(status) );
2946 else
2948 SetLastError(ret);
2951 release_sock_fd( s, fd );
2952 return FALSE;
2954 connection_success:
2955 release_sock_fd( s, fd );
2956 return TRUE;
2960 /***********************************************************************
2961 * getpeername (WS2_32.5)
2963 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
2965 int fd;
2966 int res;
2968 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
2970 fd = get_sock_fd( s, 0, NULL );
2971 res = SOCKET_ERROR;
2973 if (fd != -1)
2975 union generic_unix_sockaddr uaddr;
2976 socklen_t uaddrlen = sizeof(uaddr);
2978 if (getpeername(fd, &uaddr.addr, &uaddrlen) == 0)
2980 if (!name || !namelen)
2981 SetLastError(WSAEFAULT);
2982 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
2983 /* The buffer was too small */
2984 SetLastError(WSAEFAULT);
2985 else
2986 res = 0;
2988 else
2989 SetLastError(wsaErrno());
2990 release_sock_fd( s, fd );
2992 return res;
2995 /***********************************************************************
2996 * getsockname (WS2_32.6)
2998 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
3000 int fd;
3001 int res;
3003 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
3005 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
3006 if( (name == NULL) || (namelen == NULL) )
3008 SetLastError( WSAEFAULT );
3009 return SOCKET_ERROR;
3012 fd = get_sock_fd( s, 0, NULL );
3013 res = SOCKET_ERROR;
3015 if (fd != -1)
3017 union generic_unix_sockaddr uaddr;
3018 socklen_t uaddrlen = sizeof(uaddr);
3020 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
3022 SetLastError(wsaErrno());
3024 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
3026 SetLastError(WSAEINVAL);
3028 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3030 /* The buffer was too small */
3031 SetLastError(WSAEFAULT);
3033 else
3035 res=0;
3036 TRACE("=> %s\n", debugstr_sockaddr(name));
3038 release_sock_fd( s, fd );
3040 return res;
3043 /***********************************************************************
3044 * getsockopt (WS2_32.7)
3046 INT WINAPI WS_getsockopt(SOCKET s, INT level,
3047 INT optname, char *optval, INT *optlen)
3049 int fd;
3050 INT ret = 0;
3052 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
3053 s, level, optname, optval, optlen ? *optlen : 0);
3055 switch(level)
3057 case WS_SOL_SOCKET:
3059 switch(optname)
3061 /* Handle common cases. The special cases are below, sorted
3062 * alphabetically */
3063 case WS_SO_BROADCAST:
3064 case WS_SO_DEBUG:
3065 case WS_SO_ERROR:
3066 case WS_SO_KEEPALIVE:
3067 case WS_SO_OOBINLINE:
3068 case WS_SO_RCVBUF:
3069 case WS_SO_REUSEADDR:
3070 case WS_SO_SNDBUF:
3071 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3072 return SOCKET_ERROR;
3073 convert_sockopt(&level, &optname);
3074 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3076 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3077 ret = SOCKET_ERROR;
3079 release_sock_fd( s, fd );
3080 return ret;
3081 case WS_SO_ACCEPTCONN:
3082 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3083 return SOCKET_ERROR;
3084 if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, optval, (socklen_t *)optlen) != 0 )
3086 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3087 ret = SOCKET_ERROR;
3089 else
3091 /* BSD returns != 0 while Windows return exact == 1 */
3092 if (*(int *)optval) *(int *)optval = 1;
3094 release_sock_fd( s, fd );
3095 return ret;
3096 case WS_SO_DONTLINGER:
3098 struct linger lingval;
3099 socklen_t len = sizeof(struct linger);
3101 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
3103 SetLastError(WSAEFAULT);
3104 return SOCKET_ERROR;
3106 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3107 return SOCKET_ERROR;
3109 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
3111 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3112 ret = SOCKET_ERROR;
3114 else
3116 *(BOOL *)optval = !lingval.l_onoff;
3117 *optlen = sizeof(BOOL);
3120 release_sock_fd( s, fd );
3121 return ret;
3124 case WS_SO_CONNECT_TIME:
3126 static int pretendtime = 0;
3127 struct WS_sockaddr addr;
3128 int len = sizeof(addr);
3130 if (!optlen || *optlen < sizeof(DWORD) || !optval)
3132 SetLastError(WSAEFAULT);
3133 return SOCKET_ERROR;
3135 if (WS_getpeername(s, &addr, &len) == SOCKET_ERROR)
3136 *(DWORD *)optval = ~0u;
3137 else
3139 if (!pretendtime) FIXME("WS_SO_CONNECT_TIME - faking results\n");
3140 *(DWORD *)optval = pretendtime++;
3142 *optlen = sizeof(DWORD);
3143 return ret;
3145 /* As mentioned in setsockopt, Windows ignores this, so we
3146 * always return true here */
3147 case WS_SO_DONTROUTE:
3148 if (!optlen || *optlen < sizeof(BOOL) || !optval)
3150 SetLastError(WSAEFAULT);
3151 return SOCKET_ERROR;
3153 *(BOOL *)optval = TRUE;
3154 *optlen = sizeof(BOOL);
3155 return 0;
3157 case WS_SO_LINGER:
3159 struct linger lingval;
3160 int so_type;
3161 socklen_t len = sizeof(struct linger), slen = sizeof(int);
3163 /* struct linger and LINGER have different sizes */
3164 if (!optlen || *optlen < sizeof(LINGER) || !optval)
3166 SetLastError(WSAEFAULT);
3167 return SOCKET_ERROR;
3169 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3170 return SOCKET_ERROR;
3172 if ((getsockopt(fd, SOL_SOCKET, SO_TYPE, &so_type, &slen) == 0 && so_type == SOCK_DGRAM))
3174 SetLastError(WSAENOPROTOOPT);
3175 ret = SOCKET_ERROR;
3177 else if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0)
3179 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3180 ret = SOCKET_ERROR;
3182 else
3184 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
3185 ((LINGER *)optval)->l_linger = lingval.l_linger;
3186 *optlen = sizeof(struct linger);
3189 release_sock_fd( s, fd );
3190 return ret;
3193 case WS_SO_MAX_MSG_SIZE:
3194 if (!optlen || *optlen < sizeof(int) || !optval)
3196 SetLastError(WSAEFAULT);
3197 return SOCKET_ERROR;
3199 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
3200 *(int *)optval = 65507;
3201 *optlen = sizeof(int);
3202 return 0;
3204 /* SO_OPENTYPE does not require a valid socket handle. */
3205 case WS_SO_OPENTYPE:
3206 if (!optlen || *optlen < sizeof(int) || !optval)
3208 SetLastError(WSAEFAULT);
3209 return SOCKET_ERROR;
3211 *(int *)optval = get_per_thread_data()->opentype;
3212 *optlen = sizeof(int);
3213 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
3214 return 0;
3215 case WS_SO_PROTOCOL_INFOA:
3216 case WS_SO_PROTOCOL_INFOW:
3218 int size;
3219 WSAPROTOCOL_INFOW infow;
3221 ret = ws_protocol_info(s, optname == WS_SO_PROTOCOL_INFOW, &infow, &size);
3222 if (ret)
3224 if (!optlen || !optval || *optlen < size)
3226 if(optlen) *optlen = size;
3227 ret = 0;
3228 SetLastError(WSAEFAULT);
3230 else
3231 memcpy(optval, &infow, size);
3233 return ret ? 0 : SOCKET_ERROR;
3235 #ifdef SO_RCVTIMEO
3236 case WS_SO_RCVTIMEO:
3237 #endif
3238 #ifdef SO_SNDTIMEO
3239 case WS_SO_SNDTIMEO:
3240 #endif
3241 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
3243 struct timeval tv;
3244 socklen_t len = sizeof(struct timeval);
3246 if (!optlen || *optlen < sizeof(int)|| !optval)
3248 SetLastError(WSAEFAULT);
3249 return SOCKET_ERROR;
3251 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3252 return SOCKET_ERROR;
3254 convert_sockopt(&level, &optname);
3255 if (getsockopt(fd, level, optname, &tv, &len) != 0 )
3257 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3258 ret = SOCKET_ERROR;
3260 else
3262 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
3263 *optlen = sizeof(int);
3266 release_sock_fd( s, fd );
3267 return ret;
3269 #endif
3270 case WS_SO_TYPE:
3272 if (!optlen || *optlen < sizeof(int) || !optval)
3274 SetLastError(WSAEFAULT);
3275 return SOCKET_ERROR;
3277 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3278 return SOCKET_ERROR;
3280 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, optval, (socklen_t *)optlen) != 0 )
3282 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3283 ret = SOCKET_ERROR;
3285 else
3286 (*(int *)optval) = convert_socktype_u2w(*(int *)optval);
3288 release_sock_fd( s, fd );
3289 return ret;
3291 default:
3292 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
3293 SetLastError(WSAENOPROTOOPT);
3294 return SOCKET_ERROR;
3295 } /* end switch(optname) */
3296 }/* end case WS_SOL_SOCKET */
3297 #ifdef HAS_IPX
3298 case WS_NSPROTO_IPX:
3300 struct WS_sockaddr_ipx addr;
3301 IPX_ADDRESS_DATA *data;
3302 int namelen;
3303 switch(optname)
3305 case IPX_PTYPE:
3306 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3307 #ifdef SOL_IPX
3308 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (socklen_t *)optlen) == -1)
3310 ret = SOCKET_ERROR;
3312 #else
3314 struct ipx val;
3315 socklen_t len=sizeof(struct ipx);
3316 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
3317 ret = SOCKET_ERROR;
3318 else
3319 *optval = (int)val.ipx_pt;
3321 #endif
3322 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
3323 release_sock_fd( s, fd );
3324 return ret;
3326 case IPX_ADDRESS:
3328 * On a Win2000 system with one network card there are usually
3329 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
3330 * Using this call you can then retrieve info about this all.
3331 * In case of Linux it is a bit different. Usually you have
3332 * only "one" device active and further it is not possible to
3333 * query things like the linkspeed.
3335 FIXME("IPX_ADDRESS\n");
3336 namelen = sizeof(struct WS_sockaddr_ipx);
3337 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
3338 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
3340 data = (IPX_ADDRESS_DATA*)optval;
3341 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
3342 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
3343 data->adapternum = 0;
3344 data->wan = FALSE; /* We are not on a wan for now .. */
3345 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
3346 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
3347 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
3348 * note 1MB = 1000kB in this case */
3349 return 0;
3351 case IPX_MAX_ADAPTER_NUM:
3352 FIXME("IPX_MAX_ADAPTER_NUM\n");
3353 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
3354 return 0;
3356 default:
3357 FIXME("IPX optname:%x\n", optname);
3358 return SOCKET_ERROR;
3359 }/* end switch(optname) */
3360 } /* end case WS_NSPROTO_IPX */
3361 #endif
3363 #ifdef HAS_IRDA
3364 #define MAX_IRDA_DEVICES 10
3366 case WS_SOL_IRLMP:
3367 switch(optname)
3369 case WS_IRLMP_ENUMDEVICES:
3371 char buf[sizeof(struct irda_device_list) +
3372 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
3373 int res;
3374 socklen_t len = sizeof(buf);
3376 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3377 return SOCKET_ERROR;
3378 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
3379 release_sock_fd( s, fd );
3380 if (res < 0)
3382 SetLastError(wsaErrno());
3383 return SOCKET_ERROR;
3385 else
3387 struct irda_device_list *src = (struct irda_device_list *)buf;
3388 DEVICELIST *dst = (DEVICELIST *)optval;
3389 INT needed = sizeof(DEVICELIST);
3390 unsigned int i;
3392 if (src->len > 0)
3393 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
3394 if (*optlen < needed)
3396 SetLastError(WSAEFAULT);
3397 return SOCKET_ERROR;
3399 *optlen = needed;
3400 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
3401 dst->numDevice = src->len;
3402 for (i = 0; i < src->len; i++)
3404 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
3405 src->dev[i].saddr, src->dev[i].daddr,
3406 src->dev[i].info, src->dev[i].hints[0],
3407 src->dev[i].hints[1]);
3408 memcpy( dst->Device[i].irdaDeviceID,
3409 &src->dev[i].daddr,
3410 sizeof(dst->Device[i].irdaDeviceID) ) ;
3411 memcpy( dst->Device[i].irdaDeviceName,
3412 src->dev[i].info,
3413 sizeof(dst->Device[i].irdaDeviceName) ) ;
3414 memcpy( &dst->Device[i].irdaDeviceHints1,
3415 &src->dev[i].hints[0],
3416 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
3417 memcpy( &dst->Device[i].irdaDeviceHints2,
3418 &src->dev[i].hints[1],
3419 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
3420 dst->Device[i].irdaCharSet = src->dev[i].charset;
3422 return 0;
3425 default:
3426 FIXME("IrDA optname:0x%x\n", optname);
3427 return SOCKET_ERROR;
3429 break; /* case WS_SOL_IRLMP */
3430 #undef MAX_IRDA_DEVICES
3431 #endif
3433 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3434 case WS_IPPROTO_TCP:
3435 switch(optname)
3437 case WS_TCP_NODELAY:
3438 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3439 return SOCKET_ERROR;
3440 convert_sockopt(&level, &optname);
3441 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3443 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3444 ret = SOCKET_ERROR;
3446 release_sock_fd( s, fd );
3447 return ret;
3449 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
3450 return SOCKET_ERROR;
3452 case WS_IPPROTO_IP:
3453 switch(optname)
3455 case WS_IP_ADD_MEMBERSHIP:
3456 case WS_IP_DROP_MEMBERSHIP:
3457 #ifdef IP_HDRINCL
3458 case WS_IP_HDRINCL:
3459 #endif
3460 case WS_IP_MULTICAST_IF:
3461 case WS_IP_MULTICAST_LOOP:
3462 case WS_IP_MULTICAST_TTL:
3463 case WS_IP_OPTIONS:
3464 #ifdef IP_PKTINFO
3465 case WS_IP_PKTINFO:
3466 #endif
3467 case WS_IP_TOS:
3468 case WS_IP_TTL:
3469 #ifdef IP_UNICAST_IF
3470 case WS_IP_UNICAST_IF:
3471 #endif
3472 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3473 return SOCKET_ERROR;
3474 convert_sockopt(&level, &optname);
3475 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3477 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3478 ret = SOCKET_ERROR;
3480 release_sock_fd( s, fd );
3481 return ret;
3482 case WS_IP_DONTFRAGMENT:
3483 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
3484 *(BOOL*)optval = FALSE;
3485 return 0;
3487 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
3488 return SOCKET_ERROR;
3490 case WS_IPPROTO_IPV6:
3491 switch(optname)
3493 #ifdef IPV6_ADD_MEMBERSHIP
3494 case WS_IPV6_ADD_MEMBERSHIP:
3495 #endif
3496 #ifdef IPV6_DROP_MEMBERSHIP
3497 case WS_IPV6_DROP_MEMBERSHIP:
3498 #endif
3499 case WS_IPV6_MULTICAST_IF:
3500 case WS_IPV6_MULTICAST_HOPS:
3501 case WS_IPV6_MULTICAST_LOOP:
3502 case WS_IPV6_UNICAST_HOPS:
3503 case WS_IPV6_V6ONLY:
3504 #ifdef IPV6_UNICAST_IF
3505 case WS_IPV6_UNICAST_IF:
3506 #endif
3507 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3508 return SOCKET_ERROR;
3509 convert_sockopt(&level, &optname);
3510 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3512 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3513 ret = SOCKET_ERROR;
3515 release_sock_fd( s, fd );
3516 return ret;
3517 case WS_IPV6_DONTFRAG:
3518 FIXME("WS_IPV6_DONTFRAG is always false!\n");
3519 *(BOOL*)optval = FALSE;
3520 return 0;
3522 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
3523 return SOCKET_ERROR;
3525 default:
3526 WARN("Unknown level: 0x%08x\n", level);
3527 SetLastError(WSAEINVAL);
3528 return SOCKET_ERROR;
3529 } /* end switch(level) */
3532 /***********************************************************************
3533 * htonl (WS2_32.8)
3535 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
3537 return htonl(hostlong);
3541 /***********************************************************************
3542 * htons (WS2_32.9)
3544 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
3546 return htons(hostshort);
3549 /***********************************************************************
3550 * WSAHtonl (WS2_32.46)
3551 * From MSDN description of error codes, this function should also
3552 * check if WinSock has been initialized and the socket is a valid
3553 * socket. But why? This function only translates a host byte order
3554 * u_long into a network byte order u_long...
3556 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
3558 if (lpnetlong)
3560 *lpnetlong = htonl(hostlong);
3561 return 0;
3563 WSASetLastError(WSAEFAULT);
3564 return SOCKET_ERROR;
3567 /***********************************************************************
3568 * WSAHtons (WS2_32.47)
3569 * From MSDN description of error codes, this function should also
3570 * check if WinSock has been initialized and the socket is a valid
3571 * socket. But why? This function only translates a host byte order
3572 * u_short into a network byte order u_short...
3574 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
3577 if (lpnetshort)
3579 *lpnetshort = htons(hostshort);
3580 return 0;
3582 WSASetLastError(WSAEFAULT);
3583 return SOCKET_ERROR;
3587 /***********************************************************************
3588 * inet_addr (WS2_32.11)
3590 WS_u_long WINAPI WS_inet_addr(const char *cp)
3592 if (!cp) return INADDR_NONE;
3593 return inet_addr(cp);
3597 /***********************************************************************
3598 * ntohl (WS2_32.14)
3600 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
3602 return ntohl(netlong);
3606 /***********************************************************************
3607 * ntohs (WS2_32.15)
3609 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
3611 return ntohs(netshort);
3615 /***********************************************************************
3616 * inet_ntoa (WS2_32.12)
3618 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
3620 char* s = inet_ntoa(*((struct in_addr*)&in));
3621 if( s )
3623 struct per_thread_data *data = get_per_thread_data();
3624 strcpy(data->ntoa_buffer, s);
3625 return data->ntoa_buffer;
3627 SetLastError(wsaErrno());
3628 return NULL;
3631 static const char *debugstr_wsaioctl(DWORD ioctl)
3633 const char *buf_type, *family;
3635 switch(ioctl & 0x18000000)
3637 case WS_IOC_WS2:
3638 family = "IOC_WS2";
3639 break;
3640 case WS_IOC_PROTOCOL:
3641 family = "IOC_PROTOCOL";
3642 break;
3643 case WS_IOC_VENDOR:
3644 family = "IOC_VENDOR";
3645 break;
3646 default: /* WS_IOC_UNIX */
3648 BYTE size = (ioctl >> 16) & WS_IOCPARM_MASK;
3649 char x = (ioctl & 0xff00) >> 8;
3650 BYTE y = ioctl & 0xff;
3651 char args[14];
3653 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3655 case WS_IOC_VOID:
3656 buf_type = "_IO";
3657 sprintf(args, "%d, %d", x, y);
3658 break;
3659 case WS_IOC_IN:
3660 buf_type = "_IOW";
3661 sprintf(args, "'%c', %d, %d", x, y, size);
3662 break;
3663 case WS_IOC_OUT:
3664 buf_type = "_IOR";
3665 sprintf(args, "'%c', %d, %d", x, y, size);
3666 break;
3667 default:
3668 buf_type = "?";
3669 sprintf(args, "'%c', %d, %d", x, y, size);
3670 break;
3672 return wine_dbg_sprintf("%s(%s)", buf_type, args);
3676 /* We are different from WS_IOC_UNIX. */
3677 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3679 case WS_IOC_VOID:
3680 buf_type = "_WSAIO";
3681 break;
3682 case WS_IOC_INOUT:
3683 buf_type = "_WSAIORW";
3684 break;
3685 case WS_IOC_IN:
3686 buf_type = "_WSAIOW";
3687 break;
3688 case WS_IOC_OUT:
3689 buf_type = "_WSAIOR";
3690 break;
3691 default:
3692 buf_type = "?";
3693 break;
3696 return wine_dbg_sprintf("%s(%s, %d)", buf_type, family,
3697 (USHORT)(ioctl & 0xffff));
3700 /* do an ioctl call through the server */
3701 static DWORD server_ioctl_sock( SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size,
3702 LPVOID out_buff, DWORD out_size, LPDWORD ret_size,
3703 LPWSAOVERLAPPED overlapped,
3704 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
3706 HANDLE event = overlapped ? overlapped->hEvent : 0;
3707 HANDLE handle = SOCKET2HANDLE( s );
3708 struct ws2_async *wsa;
3709 NTSTATUS status;
3710 PIO_STATUS_BLOCK io;
3712 if (!(wsa = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wsa) )))
3713 return WSA_NOT_ENOUGH_MEMORY;
3714 wsa->hSocket = handle;
3715 wsa->user_overlapped = overlapped;
3716 wsa->completion_func = completion;
3717 io = (overlapped ? (PIO_STATUS_BLOCK)overlapped : &wsa->local_iosb);
3719 status = NtDeviceIoControlFile( handle, event, (PIO_APC_ROUTINE)ws2_async_apc, wsa, io, code,
3720 in_buff, in_size, out_buff, out_size );
3721 if (status == STATUS_NOT_SUPPORTED)
3723 FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
3724 code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
3726 else if (status == STATUS_SUCCESS)
3727 *ret_size = io->Information; /* "Information" is the size written to the output buffer */
3729 if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, wsa );
3731 return NtStatusToWSAError( status );
3734 /**********************************************************************
3735 * WSAIoctl (WS2_32.50)
3738 INT WINAPI WSAIoctl(SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size, LPVOID out_buff,
3739 DWORD out_size, LPDWORD ret_size, LPWSAOVERLAPPED overlapped,
3740 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
3742 int fd;
3743 DWORD status = 0, total = 0;
3745 TRACE("%ld, %s, %p, %d, %p, %d, %p, %p, %p\n",
3746 s, debugstr_wsaioctl(code), in_buff, in_size, out_buff, out_size, ret_size, overlapped, completion);
3748 switch (code)
3750 case WS_FIONBIO:
3751 if (in_size != sizeof(WS_u_long) || IS_INTRESOURCE(in_buff))
3753 WSASetLastError(WSAEFAULT);
3754 return SOCKET_ERROR;
3756 TRACE("-> FIONBIO (%x)\n", *(WS_u_long*)in_buff);
3757 if (_get_sock_mask(s))
3759 /* AsyncSelect()'ed sockets are always nonblocking */
3760 if (!*(WS_u_long *)in_buff) status = WSAEINVAL;
3761 break;
3763 if (*(WS_u_long *)in_buff)
3764 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
3765 else
3766 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
3767 break;
3769 case WS_FIONREAD:
3771 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
3773 WSASetLastError(WSAEFAULT);
3774 return SOCKET_ERROR;
3776 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3777 if (ioctl(fd, FIONREAD, out_buff ) == -1)
3778 status = (errno == EBADF) ? WSAENOTSOCK : wsaErrno();
3779 release_sock_fd( s, fd );
3780 break;
3783 case WS_SIOCATMARK:
3785 unsigned int oob = 0, atmark = 0;
3786 socklen_t oobsize = sizeof(int);
3787 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
3789 WSASetLastError(WSAEFAULT);
3790 return SOCKET_ERROR;
3792 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3793 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
3794 if ((getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &oob, &oobsize ) == -1)
3795 || (!oob && ioctl(fd, SIOCATMARK, &atmark ) == -1))
3796 status = (errno == EBADF) ? WSAENOTSOCK : wsaErrno();
3797 else
3799 /* The SIOCATMARK value read from ioctl() is reversed
3800 * because BSD returns TRUE if it's in the OOB mark
3801 * while Windows returns TRUE if there are NO OOB bytes.
3803 (*(WS_u_long *) out_buff) = oob | !atmark;
3806 release_sock_fd( s, fd );
3807 break;
3810 case WS_FIOASYNC:
3811 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
3812 SetLastError(WSAEINVAL);
3813 return SOCKET_ERROR;
3815 case WS_SIO_GET_INTERFACE_LIST:
3817 INTERFACE_INFO* intArray = out_buff;
3818 DWORD size, numInt = 0, apiReturn;
3820 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
3822 if (!out_buff || !ret_size)
3824 WSASetLastError(WSAEFAULT);
3825 return SOCKET_ERROR;
3828 fd = get_sock_fd( s, 0, NULL );
3829 if (fd == -1) return SOCKET_ERROR;
3831 apiReturn = GetAdaptersInfo(NULL, &size);
3832 if (apiReturn == ERROR_BUFFER_OVERFLOW)
3834 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
3836 if (table)
3838 if (GetAdaptersInfo(table, &size) == NO_ERROR)
3840 PIP_ADAPTER_INFO ptr;
3842 for (ptr = table, numInt = 0; ptr; ptr = ptr->Next)
3844 unsigned int addr, mask, bcast;
3845 struct ifreq ifInfo;
3847 /* Skip interfaces without an IPv4 address. */
3848 if (ptr->IpAddressList.IpAddress.String[0] == '\0')
3849 continue;
3851 if ((numInt + 1)*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > out_size)
3853 WARN("Buffer too small = %u, out_size = %u\n", numInt + 1, out_size);
3854 status = WSAEFAULT;
3855 break;
3858 /* Socket Status Flags */
3859 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
3860 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
3862 ERR("Error obtaining status flags for socket!\n");
3863 status = WSAEINVAL;
3864 break;
3866 else
3868 /* set flags; the values of IFF_* are not the same
3869 under Linux and Windows, therefore must generate
3870 new flags */
3871 intArray->iiFlags = 0;
3872 if (ifInfo.ifr_flags & IFF_BROADCAST)
3873 intArray->iiFlags |= WS_IFF_BROADCAST;
3874 #ifdef IFF_POINTOPOINT
3875 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
3876 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
3877 #endif
3878 if (ifInfo.ifr_flags & IFF_LOOPBACK)
3879 intArray->iiFlags |= WS_IFF_LOOPBACK;
3880 if (ifInfo.ifr_flags & IFF_UP)
3881 intArray->iiFlags |= WS_IFF_UP;
3882 if (ifInfo.ifr_flags & IFF_MULTICAST)
3883 intArray->iiFlags |= WS_IFF_MULTICAST;
3886 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
3887 mask = inet_addr(ptr->IpAddressList.IpMask.String);
3888 bcast = addr | ~mask;
3889 intArray->iiAddress.AddressIn.sin_family = AF_INET;
3890 intArray->iiAddress.AddressIn.sin_port = 0;
3891 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
3892 addr;
3893 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
3894 intArray->iiNetmask.AddressIn.sin_port = 0;
3895 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
3896 mask;
3897 intArray->iiBroadcastAddress.AddressIn.sin_family =
3898 AF_INET;
3899 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
3900 intArray->iiBroadcastAddress.AddressIn.sin_addr.
3901 WS_s_addr = bcast;
3902 intArray++;
3903 numInt++;
3906 else
3908 ERR("Unable to get interface table!\n");
3909 status = WSAEINVAL;
3911 HeapFree(GetProcessHeap(),0,table);
3913 else status = WSAEINVAL;
3915 else if (apiReturn != ERROR_NO_DATA)
3917 ERR("Unable to get interface table!\n");
3918 status = WSAEINVAL;
3920 /* Calculate the size of the array being returned */
3921 total = sizeof(INTERFACE_INFO) * numInt;
3922 release_sock_fd( s, fd );
3923 break;
3926 case WS_SIO_ADDRESS_LIST_QUERY:
3928 DWORD size;
3930 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
3932 if (!ret_size)
3934 WSASetLastError(WSAEFAULT);
3935 return SOCKET_ERROR;
3938 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
3940 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
3941 DWORD num;
3943 if (!table || GetAdaptersInfo(table, &size))
3945 HeapFree(GetProcessHeap(), 0, table);
3946 status = WSAEINVAL;
3947 break;
3950 for (p = table, num = 0; p; p = p->Next)
3951 if (p->IpAddressList.IpAddress.String[0]) num++;
3953 total = sizeof(SOCKET_ADDRESS_LIST) + sizeof(SOCKET_ADDRESS) * (num - 1);
3954 total += sizeof(SOCKADDR) * num;
3956 if (total > out_size)
3958 HeapFree(GetProcessHeap(), 0, table);
3959 status = WSAEFAULT;
3960 break;
3963 if (out_buff)
3965 unsigned int i;
3966 SOCKET_ADDRESS *sa;
3967 SOCKET_ADDRESS_LIST *sa_list = out_buff;
3968 SOCKADDR_IN *sockaddr;
3970 sa = sa_list->Address;
3971 sockaddr = (SOCKADDR_IN *)((char *)sa + num * sizeof(SOCKET_ADDRESS));
3972 sa_list->iAddressCount = num;
3974 for (p = table, i = 0; p; p = p->Next)
3976 if (!p->IpAddressList.IpAddress.String[0]) continue;
3978 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
3979 sa[i].iSockaddrLength = sizeof(SOCKADDR);
3981 sockaddr[i].sin_family = AF_INET;
3982 sockaddr[i].sin_port = 0;
3983 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
3984 i++;
3988 HeapFree(GetProcessHeap(), 0, table);
3990 else
3992 WARN("unable to get IP address list\n");
3993 status = WSAEINVAL;
3995 break;
3998 case WS_SIO_FLUSH:
3999 FIXME("SIO_FLUSH: stub.\n");
4000 break;
4002 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
4004 static const GUID connectex_guid = WSAID_CONNECTEX;
4005 static const GUID disconnectex_guid = WSAID_DISCONNECTEX;
4006 static const GUID acceptex_guid = WSAID_ACCEPTEX;
4007 static const GUID getaccepexsockaddrs_guid = WSAID_GETACCEPTEXSOCKADDRS;
4008 static const GUID transmitfile_guid = WSAID_TRANSMITFILE;
4009 static const GUID transmitpackets_guid = WSAID_TRANSMITPACKETS;
4010 static const GUID wsarecvmsg_guid = WSAID_WSARECVMSG;
4011 static const GUID wsasendmsg_guid = WSAID_WSASENDMSG;
4013 if ( IsEqualGUID(&connectex_guid, in_buff) )
4015 *(LPFN_CONNECTEX *)out_buff = WS2_ConnectEx;
4016 break;
4018 else if ( IsEqualGUID(&disconnectex_guid, in_buff) )
4020 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented DisconnectEx\n");
4022 else if ( IsEqualGUID(&acceptex_guid, in_buff) )
4024 *(LPFN_ACCEPTEX *)out_buff = WS2_AcceptEx;
4025 break;
4027 else if ( IsEqualGUID(&getaccepexsockaddrs_guid, in_buff) )
4029 *(LPFN_GETACCEPTEXSOCKADDRS *)out_buff = WS2_GetAcceptExSockaddrs;
4030 break;
4032 else if ( IsEqualGUID(&transmitfile_guid, in_buff) )
4034 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitFile\n");
4036 else if ( IsEqualGUID(&transmitpackets_guid, in_buff) )
4038 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitPackets\n");
4040 else if ( IsEqualGUID(&wsarecvmsg_guid, in_buff) )
4042 *(LPFN_WSARECVMSG *)out_buff = WS2_WSARecvMsg;
4043 break;
4045 else if ( IsEqualGUID(&wsasendmsg_guid, in_buff) )
4047 *(LPFN_WSASENDMSG *)out_buff = WSASendMsg;
4048 break;
4050 else
4051 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff));
4053 status = WSAEOPNOTSUPP;
4054 break;
4056 case WS_SIO_KEEPALIVE_VALS:
4058 struct tcp_keepalive *k;
4059 int keepalive, keepidle, keepintvl;
4061 if (!in_buff || in_size < sizeof(struct tcp_keepalive))
4063 WSASetLastError(WSAEFAULT);
4064 return SOCKET_ERROR;
4067 k = in_buff;
4068 keepalive = k->onoff ? 1 : 0;
4069 keepidle = max( 1, (k->keepalivetime + 500) / 1000 );
4070 keepintvl = max( 1, (k->keepaliveinterval + 500) / 1000 );
4072 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
4074 fd = get_sock_fd(s, 0, NULL);
4075 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
4076 status = WSAEINVAL;
4077 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
4078 /* these values need to be set only if SO_KEEPALIVE is enabled */
4079 else if(keepalive)
4081 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
4082 status = WSAEINVAL;
4083 else if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
4084 status = WSAEINVAL;
4086 #else
4087 else
4088 FIXME("ignoring keepalive interval and timeout\n");
4089 #endif
4090 release_sock_fd(s, fd);
4091 break;
4093 case WS_SIO_ROUTING_INTERFACE_QUERY:
4095 struct WS_sockaddr *daddr = (struct WS_sockaddr *)in_buff;
4096 struct WS_sockaddr_in *daddr_in = (struct WS_sockaddr_in *)daddr;
4097 struct WS_sockaddr_in *saddr_in = out_buff;
4098 MIB_IPFORWARDROW row;
4099 PMIB_IPADDRTABLE ipAddrTable = NULL;
4100 DWORD size, i, found_index;
4102 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
4104 if (!in_buff || in_size < sizeof(struct WS_sockaddr) ||
4105 !out_buff || out_size < sizeof(struct WS_sockaddr_in) || !ret_size)
4107 WSASetLastError(WSAEFAULT);
4108 return SOCKET_ERROR;
4110 if (daddr->sa_family != AF_INET)
4112 FIXME("unsupported address family %d\n", daddr->sa_family);
4113 status = WSAEAFNOSUPPORT;
4114 break;
4116 if (GetBestRoute(daddr_in->sin_addr.S_un.S_addr, 0, &row) != NOERROR ||
4117 GetIpAddrTable(NULL, &size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
4119 status = WSAEFAULT;
4120 break;
4122 ipAddrTable = HeapAlloc(GetProcessHeap(), 0, size);
4123 if (GetIpAddrTable(ipAddrTable, &size, FALSE))
4125 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4126 status = WSAEFAULT;
4127 break;
4129 for (i = 0, found_index = ipAddrTable->dwNumEntries;
4130 i < ipAddrTable->dwNumEntries; i++)
4132 if (ipAddrTable->table[i].dwIndex == row.dwForwardIfIndex)
4133 found_index = i;
4135 if (found_index == ipAddrTable->dwNumEntries)
4137 ERR("no matching IP address for interface %d\n",
4138 row.dwForwardIfIndex);
4139 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4140 status = WSAEFAULT;
4141 break;
4143 saddr_in->sin_family = AF_INET;
4144 saddr_in->sin_addr.S_un.S_addr = ipAddrTable->table[found_index].dwAddr;
4145 saddr_in->sin_port = 0;
4146 total = sizeof(struct WS_sockaddr_in);
4147 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4148 break;
4150 case WS_SIO_SET_COMPATIBILITY_MODE:
4151 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
4152 status = WSAEOPNOTSUPP;
4153 break;
4154 case WS_SIO_UDP_CONNRESET:
4155 FIXME("WS_SIO_UDP_CONNRESET stub\n");
4156 break;
4157 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
4158 WSASetLastError(WSAEOPNOTSUPP);
4159 return SOCKET_ERROR;
4160 default:
4161 status = WSAEOPNOTSUPP;
4162 break;
4165 if (status == WSAEOPNOTSUPP)
4167 status = server_ioctl_sock(s, code, in_buff, in_size, out_buff, out_size, &total,
4168 overlapped, completion);
4169 if (status != WSAEOPNOTSUPP)
4171 if (status == 0 || status == WSA_IO_PENDING)
4172 TRACE("-> %s request\n", debugstr_wsaioctl(code));
4173 else
4174 ERR("-> %s request failed with status 0x%x\n", debugstr_wsaioctl(code), status);
4176 /* overlapped and completion operations will be handled by the server */
4177 completion = NULL;
4178 overlapped = NULL;
4180 else
4181 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code));
4184 if (completion)
4186 FIXME( "completion routine %p not supported\n", completion );
4188 else if (overlapped)
4190 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
4191 overlapped->Internal = status;
4192 overlapped->InternalHigh = total;
4193 if (overlapped->hEvent) NtSetEvent( overlapped->hEvent, NULL );
4194 if (cvalue) WS_AddCompletion( HANDLE2SOCKET(s), cvalue, status, total );
4197 if (!status)
4199 if (ret_size) *ret_size = total;
4200 return 0;
4202 SetLastError( status );
4203 return SOCKET_ERROR;
4207 /***********************************************************************
4208 * ioctlsocket (WS2_32.10)
4210 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
4212 DWORD ret_size;
4213 return WSAIoctl( s, cmd, argp, sizeof(WS_u_long), argp, sizeof(WS_u_long), &ret_size, NULL, NULL );
4216 /***********************************************************************
4217 * listen (WS2_32.13)
4219 int WINAPI WS_listen(SOCKET s, int backlog)
4221 int fd = get_sock_fd( s, FILE_READ_DATA, NULL ), ret = SOCKET_ERROR;
4223 TRACE("socket %04lx, backlog %d\n", s, backlog);
4224 if (fd != -1)
4226 union generic_unix_sockaddr uaddr;
4227 socklen_t uaddrlen = sizeof(uaddr);
4229 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
4231 SetLastError(wsaErrno());
4233 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
4235 SetLastError(WSAEINVAL);
4237 else if (listen(fd, backlog) == 0)
4239 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
4240 FD_WINE_LISTENING,
4241 FD_CONNECT|FD_WINE_CONNECTED);
4242 ret = 0;
4244 else
4245 SetLastError(wsaErrno());
4246 release_sock_fd( s, fd );
4248 else
4249 SetLastError(WSAENOTSOCK);
4250 return ret;
4253 /***********************************************************************
4254 * recv (WS2_32.16)
4256 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
4258 DWORD n, dwFlags = flags;
4259 WSABUF wsabuf;
4261 wsabuf.len = len;
4262 wsabuf.buf = buf;
4264 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
4265 return SOCKET_ERROR;
4266 else
4267 return n;
4270 /***********************************************************************
4271 * recvfrom (WS2_32.17)
4273 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
4274 struct WS_sockaddr *from, int *fromlen)
4276 DWORD n, dwFlags = flags;
4277 WSABUF wsabuf;
4279 wsabuf.len = len;
4280 wsabuf.buf = buf;
4282 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL, NULL) == SOCKET_ERROR )
4283 return SOCKET_ERROR;
4284 else
4285 return n;
4288 /* allocate a poll array for the corresponding fd sets */
4289 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
4290 const WS_fd_set *exceptfds, int *count_ptr )
4292 unsigned int i, j = 0, count = 0;
4293 struct pollfd *fds;
4295 if (readfds) count += readfds->fd_count;
4296 if (writefds) count += writefds->fd_count;
4297 if (exceptfds) count += exceptfds->fd_count;
4298 *count_ptr = count;
4299 if (!count)
4301 SetLastError(WSAEINVAL);
4302 return NULL;
4304 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0]))))
4306 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
4307 return NULL;
4309 if (readfds)
4310 for (i = 0; i < readfds->fd_count; i++, j++)
4312 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
4313 if (fds[j].fd == -1) goto failed;
4314 fds[j].events = POLLIN;
4315 fds[j].revents = 0;
4317 if (writefds)
4318 for (i = 0; i < writefds->fd_count; i++, j++)
4320 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
4321 if (fds[j].fd == -1) goto failed;
4322 fds[j].events = POLLOUT;
4323 fds[j].revents = 0;
4325 if (exceptfds)
4326 for (i = 0; i < exceptfds->fd_count; i++, j++)
4328 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
4329 if (fds[j].fd == -1) goto failed;
4330 fds[j].events = POLLHUP;
4331 fds[j].revents = 0;
4333 return fds;
4335 failed:
4336 count = j;
4337 j = 0;
4338 if (readfds)
4339 for (i = 0; i < readfds->fd_count && j < count; i++, j++)
4340 release_sock_fd( readfds->fd_array[i], fds[j].fd );
4341 if (writefds)
4342 for (i = 0; i < writefds->fd_count && j < count; i++, j++)
4343 release_sock_fd( writefds->fd_array[i], fds[j].fd );
4344 if (exceptfds)
4345 for (i = 0; i < exceptfds->fd_count && j < count; i++, j++)
4346 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
4347 HeapFree( GetProcessHeap(), 0, fds );
4348 return NULL;
4351 /* release the file descriptor obtained in fd_sets_to_poll */
4352 /* must be called with the original fd_set arrays, before calling get_poll_results */
4353 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
4354 const WS_fd_set *exceptfds, struct pollfd *fds )
4356 unsigned int i, j = 0;
4358 if (readfds)
4360 for (i = 0; i < readfds->fd_count; i++, j++)
4361 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
4363 if (writefds)
4365 for (i = 0; i < writefds->fd_count; i++, j++)
4366 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
4368 if (exceptfds)
4370 for (i = 0; i < exceptfds->fd_count; i++, j++)
4371 if (fds[j].fd != -1)
4373 /* make sure we have a real error before releasing the fd */
4374 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
4375 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
4380 /* map the poll results back into the Windows fd sets */
4381 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
4382 const struct pollfd *fds )
4384 unsigned int i, j = 0, k, total = 0;
4386 if (readfds)
4388 for (i = k = 0; i < readfds->fd_count; i++, j++)
4389 if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
4390 readfds->fd_count = k;
4391 total += k;
4393 if (writefds)
4395 for (i = k = 0; i < writefds->fd_count; i++, j++)
4396 if ((fds[j].revents & POLLOUT) && !(fds[j].revents & POLLHUP))
4397 writefds->fd_array[k++] = writefds->fd_array[i];
4398 writefds->fd_count = k;
4399 total += k;
4401 if (exceptfds)
4403 for (i = k = 0; i < exceptfds->fd_count; i++, j++)
4404 if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
4405 exceptfds->fd_count = k;
4406 total += k;
4408 return total;
4412 /***********************************************************************
4413 * select (WS2_32.18)
4415 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
4416 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
4417 const struct WS_timeval* ws_timeout)
4419 struct pollfd *pollfds;
4420 struct timeval tv1, tv2;
4421 int torig = 0;
4422 int count, ret, timeout = -1;
4424 TRACE("read %p, write %p, excp %p timeout %p\n",
4425 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
4427 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )))
4428 return SOCKET_ERROR;
4430 if (ws_timeout)
4432 torig = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
4433 timeout = torig;
4434 gettimeofday( &tv1, 0 );
4437 while ((ret = poll( pollfds, count, timeout )) < 0)
4439 if (errno == EINTR)
4441 if (!ws_timeout) continue;
4442 gettimeofday( &tv2, 0 );
4444 tv2.tv_sec -= tv1.tv_sec;
4445 tv2.tv_usec -= tv1.tv_usec;
4446 if (tv2.tv_usec < 0)
4448 tv2.tv_usec += 1000000;
4449 tv2.tv_sec -= 1;
4452 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
4453 if (timeout <= 0) break;
4454 } else break;
4456 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
4458 if (ret == -1) SetLastError(wsaErrno());
4459 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
4460 HeapFree( GetProcessHeap(), 0, pollfds );
4461 return ret;
4464 /* helper to send completion messages for client-only i/o operation case */
4465 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
4466 ULONG Information )
4468 SERVER_START_REQ( add_fd_completion )
4470 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
4471 req->cvalue = CompletionValue;
4472 req->status = CompletionStatus;
4473 req->information = Information;
4474 wine_server_call( req );
4476 SERVER_END_REQ;
4480 /***********************************************************************
4481 * send (WS2_32.19)
4483 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
4485 DWORD n;
4486 WSABUF wsabuf;
4488 wsabuf.len = len;
4489 wsabuf.buf = (char*) buf;
4491 if ( WS2_sendto( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
4492 return SOCKET_ERROR;
4493 else
4494 return n;
4497 /***********************************************************************
4498 * WSASend (WS2_32.72)
4500 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4501 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4502 LPWSAOVERLAPPED lpOverlapped,
4503 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4505 return WS2_sendto( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
4506 NULL, 0, lpOverlapped, lpCompletionRoutine );
4509 /***********************************************************************
4510 * WSASendDisconnect (WS2_32.73)
4512 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
4514 return WS_shutdown( s, SD_SEND );
4518 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4519 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4520 const struct WS_sockaddr *to, int tolen,
4521 LPWSAOVERLAPPED lpOverlapped,
4522 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4524 unsigned int i, options;
4525 int n, fd, err, overlapped;
4526 struct ws2_async *wsa = NULL, localwsa;
4527 int totalLength = 0;
4528 DWORD bytes_sent;
4529 BOOL is_blocking;
4531 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
4532 s, lpBuffers, dwBufferCount, dwFlags,
4533 to, tolen, lpOverlapped, lpCompletionRoutine);
4535 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
4536 TRACE( "fd=%d, options=%x\n", fd, options );
4538 if ( fd == -1 ) return SOCKET_ERROR;
4540 if (!lpOverlapped && !lpNumberOfBytesSent)
4542 err = WSAEFAULT;
4543 goto error;
4546 overlapped = (lpOverlapped || lpCompletionRoutine) &&
4547 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
4548 if (overlapped || dwBufferCount > 1)
4550 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
4552 err = WSAEFAULT;
4553 goto error;
4556 else
4557 wsa = &localwsa;
4559 wsa->hSocket = SOCKET2HANDLE(s);
4560 wsa->addr = (struct WS_sockaddr *)to;
4561 wsa->addrlen.val = tolen;
4562 wsa->flags = dwFlags;
4563 wsa->lpFlags = &wsa->flags;
4564 wsa->control = NULL;
4565 wsa->n_iovecs = dwBufferCount;
4566 wsa->first_iovec = 0;
4567 for ( i = 0; i < dwBufferCount; i++ )
4569 wsa->iovec[i].iov_base = lpBuffers[i].buf;
4570 wsa->iovec[i].iov_len = lpBuffers[i].len;
4571 totalLength += lpBuffers[i].len;
4574 n = WS2_send( fd, wsa );
4575 if (n == -1 && errno != EAGAIN)
4577 err = wsaErrno();
4578 goto error;
4581 if (overlapped)
4583 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
4584 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
4586 wsa->user_overlapped = lpOverlapped;
4587 wsa->completion_func = lpCompletionRoutine;
4588 release_sock_fd( s, fd );
4590 if (n == -1 || n < totalLength)
4592 iosb->u.Status = STATUS_PENDING;
4593 iosb->Information = n == -1 ? 0 : n;
4595 SERVER_START_REQ( register_async )
4597 req->type = ASYNC_TYPE_WRITE;
4598 req->async.handle = wine_server_obj_handle( wsa->hSocket );
4599 req->async.callback = wine_server_client_ptr( WS2_async_send );
4600 req->async.iosb = wine_server_client_ptr( iosb );
4601 req->async.arg = wine_server_client_ptr( wsa );
4602 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
4603 req->async.cvalue = cvalue;
4604 err = wine_server_call( req );
4606 SERVER_END_REQ;
4608 /* Enable the event only after starting the async. The server will deliver it as soon as
4609 the async is done. */
4610 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
4612 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
4613 WSASetLastError( NtStatusToWSAError( err ));
4614 return SOCKET_ERROR;
4617 iosb->u.Status = STATUS_SUCCESS;
4618 iosb->Information = n;
4619 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = n;
4620 if (!wsa->completion_func)
4622 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
4623 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
4624 HeapFree( GetProcessHeap(), 0, wsa );
4626 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
4627 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
4628 WSASetLastError(0);
4629 return 0;
4632 if ((err = _is_blocking( s, &is_blocking )))
4634 err = NtStatusToWSAError( err );
4635 goto error;
4638 if ( is_blocking )
4640 /* On a blocking non-overlapped stream socket,
4641 * sending blocks until the entire buffer is sent. */
4642 DWORD timeout_start = GetTickCount();
4644 bytes_sent = n == -1 ? 0 : n;
4646 while (wsa->first_iovec < wsa->n_iovecs)
4648 struct pollfd pfd;
4649 int timeout = GET_SNDTIMEO(fd);
4651 if (timeout != -1)
4653 timeout -= GetTickCount() - timeout_start;
4654 if (timeout < 0) timeout = 0;
4657 pfd.fd = fd;
4658 pfd.events = POLLOUT;
4660 if (!timeout || !poll( &pfd, 1, timeout ))
4662 err = WSAETIMEDOUT;
4663 goto error; /* msdn says a timeout in send is fatal */
4666 n = WS2_send( fd, wsa );
4667 if (n == -1 && errno != EAGAIN)
4669 err = wsaErrno();
4670 goto error;
4673 if (n >= 0)
4674 bytes_sent += n;
4677 else /* non-blocking */
4679 if (n < totalLength)
4680 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
4681 if (n == -1)
4683 err = WSAEWOULDBLOCK;
4684 goto error;
4686 bytes_sent = n;
4689 TRACE(" -> %i bytes\n", bytes_sent);
4691 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = bytes_sent;
4692 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
4693 release_sock_fd( s, fd );
4694 WSASetLastError(0);
4695 return 0;
4697 error:
4698 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
4699 release_sock_fd( s, fd );
4700 WARN(" -> ERROR %d\n", err);
4701 WSASetLastError(err);
4702 return SOCKET_ERROR;
4705 /***********************************************************************
4706 * WSASendTo (WS2_32.74)
4708 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4709 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4710 const struct WS_sockaddr *to, int tolen,
4711 LPWSAOVERLAPPED lpOverlapped,
4712 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4714 return WS2_sendto( s, lpBuffers, dwBufferCount,
4715 lpNumberOfBytesSent, dwFlags,
4716 to, tolen,
4717 lpOverlapped, lpCompletionRoutine );
4720 /***********************************************************************
4721 * sendto (WS2_32.20)
4723 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
4724 const struct WS_sockaddr *to, int tolen)
4726 DWORD n;
4727 WSABUF wsabuf;
4729 wsabuf.len = len;
4730 wsabuf.buf = (char*) buf;
4732 if ( WS2_sendto(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
4733 return SOCKET_ERROR;
4734 else
4735 return n;
4738 /***********************************************************************
4739 * setsockopt (WS2_32.21)
4741 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
4742 const char *optval, int optlen)
4744 int fd;
4745 int woptval;
4746 struct linger linger;
4747 struct timeval tval;
4749 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
4750 s, level, optname, optval, optlen);
4752 /* some broken apps pass the value directly instead of a pointer to it */
4753 if(optlen && IS_INTRESOURCE(optval))
4755 SetLastError(WSAEFAULT);
4756 return SOCKET_ERROR;
4759 switch(level)
4761 case WS_SOL_SOCKET:
4762 switch(optname)
4764 /* Some options need some conversion before they can be sent to
4765 * setsockopt. The conversions are done here, then they will fall through
4766 * to the general case. Special options that are not passed to
4767 * setsockopt follow below that.*/
4769 case WS_SO_DONTLINGER:
4770 if (!optval)
4772 SetLastError(WSAEFAULT);
4773 return SOCKET_ERROR;
4775 linger.l_onoff = *(const int*)optval == 0;
4776 linger.l_linger = 0;
4777 level = SOL_SOCKET;
4778 optname = SO_LINGER;
4779 optval = (char*)&linger;
4780 optlen = sizeof(struct linger);
4781 break;
4783 case WS_SO_LINGER:
4784 if (!optval)
4786 SetLastError(WSAEFAULT);
4787 return SOCKET_ERROR;
4789 linger.l_onoff = ((LINGER*)optval)->l_onoff;
4790 linger.l_linger = ((LINGER*)optval)->l_linger;
4791 level = SOL_SOCKET;
4792 optname = SO_LINGER;
4793 optval = (char*)&linger;
4794 optlen = sizeof(struct linger);
4795 break;
4797 case WS_SO_RCVBUF:
4798 if (*(const int*)optval < 2048)
4800 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
4801 return 0;
4803 /* Fall through */
4805 /* The options listed here don't need any special handling. Thanks to
4806 * the conversion happening above, options from there will fall through
4807 * to this, too.*/
4808 case WS_SO_ACCEPTCONN:
4809 case WS_SO_BROADCAST:
4810 case WS_SO_ERROR:
4811 case WS_SO_KEEPALIVE:
4812 case WS_SO_OOBINLINE:
4813 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
4814 * however, using it the BSD way fixes bug 8513 and seems to be what
4815 * most programmers assume, anyway */
4816 case WS_SO_REUSEADDR:
4817 case WS_SO_SNDBUF:
4818 case WS_SO_TYPE:
4819 convert_sockopt(&level, &optname);
4820 break;
4822 /* SO_DEBUG is a privileged operation, ignore it. */
4823 case WS_SO_DEBUG:
4824 TRACE("Ignoring SO_DEBUG\n");
4825 return 0;
4827 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
4828 * socket. According to MSDN, this option is silently ignored.*/
4829 case WS_SO_DONTROUTE:
4830 TRACE("Ignoring SO_DONTROUTE\n");
4831 return 0;
4833 /* Stops two sockets from being bound to the same port. Always happens
4834 * on unix systems, so just drop it. */
4835 case WS_SO_EXCLUSIVEADDRUSE:
4836 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
4837 return 0;
4839 /* After a ConnectEx call succeeds, the socket can't be used with half of the
4840 * normal winsock functions on windows. We don't have that problem. */
4841 case WS_SO_UPDATE_CONNECT_CONTEXT:
4842 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
4843 return 0;
4845 /* After a AcceptEx call succeeds, the socket can't be used with half of the
4846 * normal winsock functions on windows. We don't have that problem. */
4847 case WS_SO_UPDATE_ACCEPT_CONTEXT:
4848 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
4849 return 0;
4851 /* SO_OPENTYPE does not require a valid socket handle. */
4852 case WS_SO_OPENTYPE:
4853 if (!optlen || optlen < sizeof(int) || !optval)
4855 SetLastError(WSAEFAULT);
4856 return SOCKET_ERROR;
4858 get_per_thread_data()->opentype = *(const int *)optval;
4859 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
4860 return 0;
4862 #ifdef SO_RCVTIMEO
4863 case WS_SO_RCVTIMEO:
4864 #endif
4865 #ifdef SO_SNDTIMEO
4866 case WS_SO_SNDTIMEO:
4867 #endif
4868 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
4869 if (optval && optlen == sizeof(UINT32)) {
4870 /* WinSock passes milliseconds instead of struct timeval */
4871 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
4872 tval.tv_sec = *(const UINT32*)optval / 1000;
4873 /* min of 500 milliseconds */
4874 if (tval.tv_sec == 0 && tval.tv_usec && tval.tv_usec < 500000)
4875 tval.tv_usec = 500000;
4876 optlen = sizeof(struct timeval);
4877 optval = (char*)&tval;
4878 } else if (optlen == sizeof(struct timeval)) {
4879 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
4880 } else {
4881 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
4882 return 0;
4884 convert_sockopt(&level, &optname);
4885 break;
4886 #endif
4888 default:
4889 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
4890 SetLastError(WSAENOPROTOOPT);
4891 return SOCKET_ERROR;
4893 break; /* case WS_SOL_SOCKET */
4895 #ifdef HAS_IPX
4896 case WS_NSPROTO_IPX:
4897 switch(optname)
4899 case IPX_PTYPE:
4900 return set_ipx_packettype(s, *(int*)optval);
4902 case IPX_FILTERPTYPE:
4903 /* Sets the receive filter packet type, at the moment we don't support it */
4904 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
4905 /* Returning 0 is better for now than returning a SOCKET_ERROR */
4906 return 0;
4908 default:
4909 FIXME("opt_name:%x\n", optname);
4910 return SOCKET_ERROR;
4912 break; /* case WS_NSPROTO_IPX */
4913 #endif
4915 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
4916 case WS_IPPROTO_TCP:
4917 switch(optname)
4919 case WS_TCP_NODELAY:
4920 convert_sockopt(&level, &optname);
4921 break;
4922 default:
4923 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
4924 return SOCKET_ERROR;
4926 break;
4928 case WS_IPPROTO_IP:
4929 switch(optname)
4931 case WS_IP_ADD_MEMBERSHIP:
4932 case WS_IP_DROP_MEMBERSHIP:
4933 #ifdef IP_HDRINCL
4934 case WS_IP_HDRINCL:
4935 #endif
4936 case WS_IP_MULTICAST_IF:
4937 case WS_IP_MULTICAST_LOOP:
4938 case WS_IP_MULTICAST_TTL:
4939 case WS_IP_OPTIONS:
4940 #ifdef IP_PKTINFO
4941 case WS_IP_PKTINFO:
4942 #endif
4943 case WS_IP_TOS:
4944 case WS_IP_TTL:
4945 #ifdef IP_UNICAST_IF
4946 case WS_IP_UNICAST_IF:
4947 #endif
4948 convert_sockopt(&level, &optname);
4949 break;
4950 case WS_IP_DONTFRAGMENT:
4951 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
4952 return 0;
4953 default:
4954 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
4955 return SOCKET_ERROR;
4957 break;
4959 case WS_IPPROTO_IPV6:
4960 switch(optname)
4962 #ifdef IPV6_ADD_MEMBERSHIP
4963 case WS_IPV6_ADD_MEMBERSHIP:
4964 #endif
4965 #ifdef IPV6_DROP_MEMBERSHIP
4966 case WS_IPV6_DROP_MEMBERSHIP:
4967 #endif
4968 case WS_IPV6_MULTICAST_IF:
4969 case WS_IPV6_MULTICAST_HOPS:
4970 case WS_IPV6_MULTICAST_LOOP:
4971 case WS_IPV6_UNICAST_HOPS:
4972 case WS_IPV6_V6ONLY:
4973 #ifdef IPV6_UNICAST_IF
4974 case WS_IPV6_UNICAST_IF:
4975 #endif
4976 convert_sockopt(&level, &optname);
4977 break;
4978 case WS_IPV6_DONTFRAG:
4979 FIXME("IPV6_DONTFRAG is silently ignored!\n");
4980 return 0;
4981 case WS_IPV6_PROTECTION_LEVEL:
4982 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
4983 return 0;
4984 default:
4985 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
4986 return SOCKET_ERROR;
4988 break;
4990 default:
4991 WARN("Unknown level: 0x%08x\n", level);
4992 SetLastError(WSAEINVAL);
4993 return SOCKET_ERROR;
4994 } /* end switch(level) */
4996 /* avoid endianness issues if argument is a 16-bit int */
4997 if (optval && optlen < sizeof(int))
4999 woptval= *((const INT16 *) optval);
5000 optval= (char*) &woptval;
5001 optlen=sizeof(int);
5003 fd = get_sock_fd( s, 0, NULL );
5004 if (fd == -1) return SOCKET_ERROR;
5006 if (setsockopt(fd, level, optname, optval, optlen) == 0)
5008 #ifdef __APPLE__
5009 if (level == SOL_SOCKET && optname == SO_REUSEADDR &&
5010 setsockopt(fd, level, SO_REUSEPORT, optval, optlen) != 0)
5012 SetLastError(wsaErrno());
5013 release_sock_fd( s, fd );
5014 return SOCKET_ERROR;
5016 #endif
5017 release_sock_fd( s, fd );
5018 return 0;
5020 TRACE("Setting socket error, %d\n", wsaErrno());
5021 SetLastError(wsaErrno());
5022 release_sock_fd( s, fd );
5024 return SOCKET_ERROR;
5027 /***********************************************************************
5028 * shutdown (WS2_32.22)
5030 int WINAPI WS_shutdown(SOCKET s, int how)
5032 int fd, err = WSAENOTSOCK;
5033 unsigned int options, clear_flags = 0;
5035 fd = get_sock_fd( s, 0, &options );
5036 TRACE("socket %04lx, how %i %x\n", s, how, options );
5038 if (fd == -1)
5039 return SOCKET_ERROR;
5041 switch( how )
5043 case SD_RECEIVE: /* drop receives */
5044 clear_flags |= FD_READ;
5045 break;
5046 case SD_SEND: /* drop sends */
5047 clear_flags |= FD_WRITE;
5048 break;
5049 case SD_BOTH: /* drop all */
5050 clear_flags |= FD_READ|FD_WRITE;
5051 /*fall through */
5052 default:
5053 clear_flags |= FD_WINE_LISTENING;
5056 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
5058 switch ( how )
5060 case SD_RECEIVE:
5061 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
5062 break;
5063 case SD_SEND:
5064 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
5065 break;
5066 case SD_BOTH:
5067 default:
5068 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
5069 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
5070 break;
5072 if (err) goto error;
5074 else /* non-overlapped mode */
5076 if ( shutdown( fd, how ) )
5078 err = wsaErrno();
5079 goto error;
5083 release_sock_fd( s, fd );
5084 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
5085 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
5086 return 0;
5088 error:
5089 release_sock_fd( s, fd );
5090 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
5091 WSASetLastError( err );
5092 return SOCKET_ERROR;
5095 /***********************************************************************
5096 * socket (WS2_32.23)
5098 SOCKET WINAPI WS_socket(int af, int type, int protocol)
5100 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
5102 return WSASocketA( af, type, protocol, NULL, 0,
5103 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
5107 /***********************************************************************
5108 * gethostbyaddr (WS2_32.51)
5110 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
5112 struct WS_hostent *retval = NULL;
5113 struct hostent* host;
5114 int unixtype = convert_af_w2u(type);
5115 const char *paddr = addr;
5116 unsigned long loopback;
5117 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5118 char *extrabuf;
5119 int ebufsize = 1024;
5120 struct hostent hostentry;
5121 int locerr = ENOBUFS;
5122 #endif
5124 /* convert back the magic loopback address if necessary */
5125 if (unixtype == AF_INET && len == 4 && !memcmp(addr, magic_loopback_addr, 4))
5127 loopback = htonl(INADDR_LOOPBACK);
5128 paddr = (char*) &loopback;
5131 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5132 host = NULL;
5133 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
5134 while(extrabuf) {
5135 int res = gethostbyaddr_r(paddr, len, unixtype,
5136 &hostentry, extrabuf, ebufsize, &host, &locerr);
5137 if (res != ERANGE) break;
5138 ebufsize *=2;
5139 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
5141 if (host) retval = WS_dup_he(host);
5142 else SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
5143 HeapFree(GetProcessHeap(),0,extrabuf);
5144 #else
5145 EnterCriticalSection( &csWSgetXXXbyYYY );
5146 host = gethostbyaddr(paddr, len, unixtype);
5147 if (host) retval = WS_dup_he(host);
5148 else SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
5149 LeaveCriticalSection( &csWSgetXXXbyYYY );
5150 #endif
5151 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
5152 return retval;
5155 /***********************************************************************
5156 * WS_get_local_ips (INTERNAL)
5158 * Returns the list of local IP addresses by going through the network
5159 * adapters and using the local routing table to sort the addresses
5160 * from highest routing priority to lowest routing priority. This
5161 * functionality is inferred from the description for obtaining local
5162 * IP addresses given in the Knowledge Base Article Q160215.
5164 * Please note that the returned hostent is only freed when the thread
5165 * closes and is replaced if another hostent is requested.
5167 static struct WS_hostent* WS_get_local_ips( char *hostname )
5169 int last_metric, numroutes = 0, i, j;
5170 DWORD n;
5171 PIP_ADAPTER_INFO adapters = NULL, k;
5172 struct WS_hostent *hostlist = NULL;
5173 PMIB_IPFORWARDTABLE routes = NULL;
5174 struct route *route_addrs = NULL;
5175 DWORD adap_size, route_size;
5177 /* Obtain the size of the adapter list and routing table, also allocate memory */
5178 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
5179 return NULL;
5180 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
5181 return NULL;
5182 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
5183 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
5184 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
5185 if (adapters == NULL || routes == NULL || route_addrs == NULL)
5186 goto cleanup;
5187 /* Obtain the adapter list and the full routing table */
5188 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
5189 goto cleanup;
5190 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
5191 goto cleanup;
5192 /* Store the interface associated with each route */
5193 for (n = 0; n < routes->dwNumEntries; n++)
5195 IF_INDEX ifindex;
5196 DWORD ifmetric;
5197 BOOL exists = FALSE;
5199 if (routes->table[n].u1.ForwardType != MIB_IPROUTE_TYPE_DIRECT)
5200 continue;
5201 ifindex = routes->table[n].dwForwardIfIndex;
5202 ifmetric = routes->table[n].dwForwardMetric1;
5203 /* Only store the lowest valued metric for an interface */
5204 for (j = 0; j < numroutes; j++)
5206 if (route_addrs[j].interface == ifindex)
5208 if (route_addrs[j].metric > ifmetric)
5209 route_addrs[j].metric = ifmetric;
5210 exists = TRUE;
5213 if (exists)
5214 continue;
5215 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
5216 if (route_addrs == NULL)
5217 goto cleanup; /* Memory allocation error, fail gracefully */
5218 route_addrs[numroutes].interface = ifindex;
5219 route_addrs[numroutes].metric = ifmetric;
5220 /* If no IP is found in the next step (for whatever reason)
5221 * then fall back to the magic loopback address.
5223 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
5224 numroutes++;
5226 if (numroutes == 0)
5227 goto cleanup; /* No routes, fall back to the Magic IP */
5228 /* Find the IP address associated with each found interface */
5229 for (i = 0; i < numroutes; i++)
5231 for (k = adapters; k != NULL; k = k->Next)
5233 char *ip = k->IpAddressList.IpAddress.String;
5235 if (route_addrs[i].interface == k->Index)
5236 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
5239 /* Allocate a hostent and enough memory for all the IPs,
5240 * including the NULL at the end of the list.
5242 hostlist = WS_create_he(hostname, 1, 0, numroutes+1, sizeof(struct in_addr));
5243 if (hostlist == NULL)
5244 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
5245 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
5246 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
5247 hostlist->h_addrtype = AF_INET;
5248 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
5249 /* Reorder the entries when placing them in the host list, Windows expects
5250 * the IP list in order from highest priority to lowest (the critical thing
5251 * is that most applications expect the first IP to be the default route).
5253 last_metric = -1;
5254 for (i = 0; i < numroutes; i++)
5256 struct in_addr addr;
5257 int metric = 0xFFFF;
5259 memcpy(&addr, magic_loopback_addr, 4);
5260 for (j = 0; j < numroutes; j++)
5262 int this_metric = route_addrs[j].metric;
5264 if (this_metric > last_metric && this_metric < metric)
5266 addr = route_addrs[j].addr;
5267 metric = this_metric;
5270 last_metric = metric;
5271 (*(struct in_addr *) hostlist->h_addr_list[i]) = addr;
5274 /* Cleanup all allocated memory except the address list,
5275 * the address list is used by the calling app.
5277 cleanup:
5278 HeapFree(GetProcessHeap(), 0, route_addrs);
5279 HeapFree(GetProcessHeap(), 0, adapters);
5280 HeapFree(GetProcessHeap(), 0, routes);
5281 return hostlist;
5284 /***********************************************************************
5285 * gethostbyname (WS2_32.52)
5287 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
5289 struct WS_hostent *retval = NULL;
5290 struct hostent* host;
5291 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5292 char *extrabuf;
5293 int ebufsize=1024;
5294 struct hostent hostentry;
5295 int locerr = ENOBUFS;
5296 #endif
5297 char hostname[100];
5298 if(!num_startup) {
5299 SetLastError(WSANOTINITIALISED);
5300 return NULL;
5302 if( gethostname( hostname, 100) == -1) {
5303 SetLastError( WSAENOBUFS); /* appropriate ? */
5304 return retval;
5306 if( !name || !name[0]) {
5307 name = hostname;
5309 /* If the hostname of the local machine is requested then return the
5310 * complete list of local IP addresses */
5311 if(strcmp(name, hostname) == 0)
5312 retval = WS_get_local_ips(hostname);
5313 /* If any other hostname was requested (or the routing table lookup failed)
5314 * then return the IP found by the host OS */
5315 if(retval == NULL)
5317 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5318 host = NULL;
5319 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
5320 while(extrabuf) {
5321 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
5322 if( res != ERANGE) break;
5323 ebufsize *=2;
5324 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
5326 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
5327 #else
5328 EnterCriticalSection( &csWSgetXXXbyYYY );
5329 host = gethostbyname(name);
5330 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
5331 #endif
5332 if (host) retval = WS_dup_he(host);
5333 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5334 HeapFree(GetProcessHeap(),0,extrabuf);
5335 #else
5336 LeaveCriticalSection( &csWSgetXXXbyYYY );
5337 #endif
5339 if (retval && retval->h_addr_list[0][0] == 127 &&
5340 strcmp(name, "localhost") != 0)
5342 /* hostname != "localhost" but has loopback address. replace by our
5343 * special address.*/
5344 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
5346 TRACE( "%s ret %p\n", debugstr_a(name), retval );
5347 return retval;
5351 /***********************************************************************
5352 * getprotobyname (WS2_32.53)
5354 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
5356 struct WS_protoent* retval = NULL;
5357 #ifdef HAVE_GETPROTOBYNAME
5358 struct protoent* proto;
5359 EnterCriticalSection( &csWSgetXXXbyYYY );
5360 if( (proto = getprotobyname(name)) != NULL )
5362 retval = WS_dup_pe(proto);
5364 else {
5365 MESSAGE("protocol %s not found; You might want to add "
5366 "this to /etc/protocols\n", debugstr_a(name) );
5367 SetLastError(WSANO_DATA);
5369 LeaveCriticalSection( &csWSgetXXXbyYYY );
5370 #endif
5371 TRACE( "%s ret %p\n", debugstr_a(name), retval );
5372 return retval;
5376 /***********************************************************************
5377 * getprotobynumber (WS2_32.54)
5379 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
5381 struct WS_protoent* retval = NULL;
5382 #ifdef HAVE_GETPROTOBYNUMBER
5383 struct protoent* proto;
5384 EnterCriticalSection( &csWSgetXXXbyYYY );
5385 if( (proto = getprotobynumber(number)) != NULL )
5387 retval = WS_dup_pe(proto);
5389 else {
5390 MESSAGE("protocol number %d not found; You might want to add "
5391 "this to /etc/protocols\n", number );
5392 SetLastError(WSANO_DATA);
5394 LeaveCriticalSection( &csWSgetXXXbyYYY );
5395 #endif
5396 TRACE("%i ret %p\n", number, retval);
5397 return retval;
5401 /***********************************************************************
5402 * getservbyname (WS2_32.55)
5404 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
5406 struct WS_servent* retval = NULL;
5407 struct servent* serv;
5408 char *name_str;
5409 char *proto_str = NULL;
5411 if (!(name_str = strdup_lower(name))) return NULL;
5413 if (proto && *proto)
5415 if (!(proto_str = strdup_lower(proto)))
5417 HeapFree( GetProcessHeap(), 0, name_str );
5418 return NULL;
5422 EnterCriticalSection( &csWSgetXXXbyYYY );
5423 serv = getservbyname(name_str, proto_str);
5424 if( serv != NULL )
5426 retval = WS_dup_se(serv);
5428 else SetLastError(WSANO_DATA);
5429 LeaveCriticalSection( &csWSgetXXXbyYYY );
5430 HeapFree( GetProcessHeap(), 0, proto_str );
5431 HeapFree( GetProcessHeap(), 0, name_str );
5432 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
5433 return retval;
5436 /***********************************************************************
5437 * freeaddrinfo (WS2_32.@)
5439 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
5441 while (res) {
5442 struct WS_addrinfo *next;
5444 HeapFree(GetProcessHeap(),0,res->ai_canonname);
5445 HeapFree(GetProcessHeap(),0,res->ai_addr);
5446 next = res->ai_next;
5447 HeapFree(GetProcessHeap(),0,res);
5448 res = next;
5452 /* helper functions for getaddrinfo()/getnameinfo() */
5453 static int convert_aiflag_w2u(int winflags) {
5454 unsigned int i;
5455 int unixflags = 0;
5457 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
5458 if (ws_aiflag_map[i][0] & winflags) {
5459 unixflags |= ws_aiflag_map[i][1];
5460 winflags &= ~ws_aiflag_map[i][0];
5462 if (winflags)
5463 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
5464 return unixflags;
5467 static int convert_niflag_w2u(int winflags) {
5468 unsigned int i;
5469 int unixflags = 0;
5471 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
5472 if (ws_niflag_map[i][0] & winflags) {
5473 unixflags |= ws_niflag_map[i][1];
5474 winflags &= ~ws_niflag_map[i][0];
5476 if (winflags)
5477 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
5478 return unixflags;
5481 static int convert_aiflag_u2w(int unixflags) {
5482 unsigned int i;
5483 int winflags = 0;
5485 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
5486 if (ws_aiflag_map[i][1] & unixflags) {
5487 winflags |= ws_aiflag_map[i][0];
5488 unixflags &= ~ws_aiflag_map[i][1];
5490 if (unixflags) /* will warn usually */
5491 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
5492 return winflags;
5495 static int convert_eai_u2w(int unixret) {
5496 int i;
5498 if (!unixret) return 0;
5500 for (i=0;ws_eai_map[i][0];i++)
5501 if (ws_eai_map[i][1] == unixret)
5502 return ws_eai_map[i][0];
5504 if (unixret == EAI_SYSTEM)
5505 /* There are broken versions of glibc which return EAI_SYSTEM
5506 * and set errno to 0 instead of returning EAI_NONAME.
5508 return errno ? sock_get_error( errno ) : WS_EAI_NONAME;
5510 FIXME("Unhandled unix EAI_xxx ret %d\n", unixret);
5511 return unixret;
5514 static char *get_hostname(void)
5516 char *ret;
5517 DWORD size = 0;
5519 GetComputerNameExA( ComputerNamePhysicalDnsHostname, NULL, &size );
5520 if (GetLastError() != ERROR_MORE_DATA) return NULL;
5521 if (!(ret = HeapAlloc( GetProcessHeap(), 0, size ))) return NULL;
5522 if (!GetComputerNameExA( ComputerNamePhysicalDnsHostname, ret, &size ))
5524 HeapFree( GetProcessHeap(), 0, ret );
5525 return NULL;
5527 return ret;
5530 /***********************************************************************
5531 * getaddrinfo (WS2_32.@)
5533 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
5535 #ifdef HAVE_GETADDRINFO
5536 struct addrinfo *unixaires = NULL;
5537 int result;
5538 struct addrinfo unixhints, *punixhints = NULL;
5539 char *hostname = NULL;
5540 const char *node;
5542 *res = NULL;
5543 if (!nodename && !servname) return WSAHOST_NOT_FOUND;
5545 if (!nodename)
5546 node = NULL;
5547 else if (!nodename[0])
5549 node = hostname = get_hostname();
5550 if (!node) return WSA_NOT_ENOUGH_MEMORY;
5552 else
5553 node = nodename;
5555 /* servname tweak required by OSX and BSD kernels */
5556 if (servname && !servname[0]) servname = "0";
5558 if (hints) {
5559 punixhints = &unixhints;
5561 memset(&unixhints, 0, sizeof(unixhints));
5562 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
5564 /* zero is a wildcard, no need to convert */
5565 if (hints->ai_family)
5566 punixhints->ai_family = convert_af_w2u(hints->ai_family);
5567 if (hints->ai_socktype)
5568 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
5569 if (hints->ai_protocol)
5570 punixhints->ai_protocol = max(convert_proto_w2u(hints->ai_protocol), 0);
5572 if (punixhints->ai_socktype < 0)
5574 WSASetLastError(WSAESOCKTNOSUPPORT);
5575 HeapFree(GetProcessHeap(), 0, hostname);
5576 return SOCKET_ERROR;
5579 /* windows allows invalid combinations of socket type and protocol, unix does not.
5580 * fix the parameters here to make getaddrinfo call always work */
5581 if (punixhints->ai_protocol == IPPROTO_TCP &&
5582 punixhints->ai_socktype != SOCK_STREAM && punixhints->ai_socktype != SOCK_SEQPACKET)
5583 punixhints->ai_socktype = 0;
5585 else if (punixhints->ai_protocol == IPPROTO_UDP && punixhints->ai_socktype != SOCK_DGRAM)
5586 punixhints->ai_socktype = 0;
5588 else if (IS_IPX_PROTO(punixhints->ai_protocol) && punixhints->ai_socktype != SOCK_DGRAM)
5589 punixhints->ai_socktype = 0;
5592 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
5593 result = getaddrinfo(node, servname, punixhints, &unixaires);
5595 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
5596 HeapFree(GetProcessHeap(), 0, hostname);
5598 if (!result) {
5599 struct addrinfo *xuai = unixaires;
5600 struct WS_addrinfo **xai = res;
5602 *xai = NULL;
5603 while (xuai) {
5604 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
5605 SIZE_T len;
5607 if (!ai)
5608 goto outofmem;
5610 *xai = ai;xai = &ai->ai_next;
5611 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
5612 ai->ai_family = convert_af_u2w(xuai->ai_family);
5613 /* copy whatever was sent in the hints */
5614 if(hints) {
5615 ai->ai_socktype = hints->ai_socktype;
5616 ai->ai_protocol = hints->ai_protocol;
5617 } else {
5618 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
5619 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
5621 if (xuai->ai_canonname) {
5622 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
5623 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
5624 if (!ai->ai_canonname)
5625 goto outofmem;
5626 strcpy(ai->ai_canonname,xuai->ai_canonname);
5628 len = xuai->ai_addrlen;
5629 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
5630 if (!ai->ai_addr)
5631 goto outofmem;
5632 ai->ai_addrlen = len;
5633 do {
5634 int winlen = ai->ai_addrlen;
5636 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
5637 ai->ai_addrlen = winlen;
5638 break;
5640 len = 2*len;
5641 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
5642 if (!ai->ai_addr)
5643 goto outofmem;
5644 ai->ai_addrlen = len;
5645 } while (1);
5646 xuai = xuai->ai_next;
5648 freeaddrinfo(unixaires);
5650 if (TRACE_ON(winsock))
5652 struct WS_addrinfo *ai = *res;
5653 while (ai)
5655 TRACE("=> %p, flags %#x, family %d, type %d, protocol %d, len %ld, name %s, addr %s\n",
5656 ai, ai->ai_flags, ai->ai_family, ai->ai_socktype, ai->ai_protocol, ai->ai_addrlen,
5657 ai->ai_canonname, debugstr_sockaddr(ai->ai_addr));
5658 ai = ai->ai_next;
5661 } else
5662 result = convert_eai_u2w(result);
5664 return result;
5666 outofmem:
5667 if (*res) WS_freeaddrinfo(*res);
5668 if (unixaires) freeaddrinfo(unixaires);
5669 return WSA_NOT_ENOUGH_MEMORY;
5670 #else
5671 FIXME("getaddrinfo() failed, not found during buildtime.\n");
5672 return EAI_FAIL;
5673 #endif
5676 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
5678 struct WS_addrinfoW *ret;
5680 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
5681 ret->ai_flags = ai->ai_flags;
5682 ret->ai_family = ai->ai_family;
5683 ret->ai_socktype = ai->ai_socktype;
5684 ret->ai_protocol = ai->ai_protocol;
5685 ret->ai_addrlen = ai->ai_addrlen;
5686 ret->ai_canonname = NULL;
5687 ret->ai_addr = NULL;
5688 ret->ai_next = NULL;
5689 if (ai->ai_canonname)
5691 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
5692 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
5694 HeapFree(GetProcessHeap(), 0, ret);
5695 return NULL;
5697 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
5699 if (ai->ai_addr)
5701 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, ai->ai_addrlen)))
5703 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
5704 HeapFree(GetProcessHeap(), 0, ret);
5705 return NULL;
5707 memcpy(ret->ai_addr, ai->ai_addr, ai->ai_addrlen);
5709 return ret;
5712 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
5714 struct WS_addrinfoW *ret, *infoW;
5716 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
5717 while (info->ai_next)
5719 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
5721 FreeAddrInfoW(ret);
5722 return NULL;
5724 infoW = infoW->ai_next;
5725 info = info->ai_next;
5727 return ret;
5730 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
5732 struct WS_addrinfo *ret;
5734 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
5735 ret->ai_flags = ai->ai_flags;
5736 ret->ai_family = ai->ai_family;
5737 ret->ai_socktype = ai->ai_socktype;
5738 ret->ai_protocol = ai->ai_protocol;
5739 ret->ai_addrlen = ai->ai_addrlen;
5740 ret->ai_canonname = NULL;
5741 ret->ai_addr = NULL;
5742 ret->ai_next = NULL;
5743 if (ai->ai_canonname)
5745 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
5746 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
5748 HeapFree(GetProcessHeap(), 0, ret);
5749 return NULL;
5751 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
5753 if (ai->ai_addr)
5755 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
5757 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
5758 HeapFree(GetProcessHeap(), 0, ret);
5759 return NULL;
5761 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
5763 return ret;
5766 /***********************************************************************
5767 * GetAddrInfoW (WS2_32.@)
5769 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
5771 int ret, len;
5772 char *nodenameA = NULL, *servnameA = NULL;
5773 struct WS_addrinfo *resA, *hintsA = NULL;
5775 *res = NULL;
5776 if (nodename)
5778 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
5779 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
5780 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
5782 if (servname)
5784 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
5785 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
5787 HeapFree(GetProcessHeap(), 0, nodenameA);
5788 return EAI_MEMORY;
5790 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
5793 if (hints) hintsA = addrinfo_WtoA(hints);
5794 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
5795 WS_freeaddrinfo(hintsA);
5797 if (!ret)
5799 *res = addrinfo_list_AtoW(resA);
5800 WS_freeaddrinfo(resA);
5803 HeapFree(GetProcessHeap(), 0, nodenameA);
5804 HeapFree(GetProcessHeap(), 0, servnameA);
5805 return ret;
5808 /***********************************************************************
5809 * FreeAddrInfoW (WS2_32.@)
5811 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
5813 while (ai)
5815 ADDRINFOW *next;
5816 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
5817 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
5818 next = ai->ai_next;
5819 HeapFree(GetProcessHeap(), 0, ai);
5820 ai = next;
5824 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
5825 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
5827 #ifdef HAVE_GETNAMEINFO
5828 int ret;
5829 union generic_unix_sockaddr sa_u;
5830 unsigned int size;
5832 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
5833 serv, servlen, flags);
5835 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
5836 if (!size)
5838 WSASetLastError(WSAEFAULT);
5839 return WSA_NOT_ENOUGH_MEMORY;
5841 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
5842 return convert_eai_u2w(ret);
5843 #else
5844 FIXME("getnameinfo() failed, not found during buildtime.\n");
5845 return EAI_FAIL;
5846 #endif
5849 int WINAPI GetNameInfoW(const SOCKADDR *sa, WS_socklen_t salen, PWCHAR host,
5850 DWORD hostlen, PWCHAR serv, DWORD servlen, INT flags)
5852 int ret;
5853 char *hostA = NULL, *servA = NULL;
5855 if (host && (!(hostA = HeapAlloc(GetProcessHeap(), 0, hostlen)))) return EAI_MEMORY;
5856 if (serv && (!(servA = HeapAlloc(GetProcessHeap(), 0, servlen))))
5858 HeapFree(GetProcessHeap(), 0, hostA);
5859 return EAI_MEMORY;
5862 ret = WS_getnameinfo(sa, salen, hostA, hostlen, servA, servlen, flags);
5863 if (!ret)
5865 if (host) MultiByteToWideChar(CP_ACP, 0, hostA, -1, host, hostlen);
5866 if (serv) MultiByteToWideChar(CP_ACP, 0, servA, -1, serv, servlen);
5869 HeapFree(GetProcessHeap(), 0, hostA);
5870 HeapFree(GetProcessHeap(), 0, servA);
5871 return ret;
5874 /***********************************************************************
5875 * getservbyport (WS2_32.56)
5877 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
5879 struct WS_servent* retval = NULL;
5880 #ifdef HAVE_GETSERVBYPORT
5881 struct servent* serv;
5882 char *proto_str = NULL;
5884 if (proto && *proto)
5886 if (!(proto_str = strdup_lower(proto))) return NULL;
5888 EnterCriticalSection( &csWSgetXXXbyYYY );
5889 if( (serv = getservbyport(port, proto_str)) != NULL ) {
5890 retval = WS_dup_se(serv);
5892 else SetLastError(WSANO_DATA);
5893 LeaveCriticalSection( &csWSgetXXXbyYYY );
5894 HeapFree( GetProcessHeap(), 0, proto_str );
5895 #endif
5896 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
5897 return retval;
5901 /***********************************************************************
5902 * gethostname (WS2_32.57)
5904 int WINAPI WS_gethostname(char *name, int namelen)
5906 TRACE("name %p, len %d\n", name, namelen);
5908 if (gethostname(name, namelen) == 0)
5910 TRACE("<- '%s'\n", name);
5911 return 0;
5913 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
5914 TRACE("<- ERROR !\n");
5915 return SOCKET_ERROR;
5919 /* ------------------------------------- Windows sockets extensions -- *
5921 * ------------------------------------------------------------------- */
5923 /***********************************************************************
5924 * WSAEnumNetworkEvents (WS2_32.36)
5926 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
5928 int ret;
5929 int i;
5930 int errors[FD_MAX_EVENTS];
5932 TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
5934 SERVER_START_REQ( get_socket_event )
5936 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5937 req->service = TRUE;
5938 req->c_event = wine_server_obj_handle( hEvent );
5939 wine_server_set_reply( req, errors, sizeof(errors) );
5940 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
5942 SERVER_END_REQ;
5943 if (!ret)
5945 for (i = 0; i < FD_MAX_EVENTS; i++)
5946 lpEvent->iErrorCode[i] = NtStatusToWSAError(errors[i]);
5947 return 0;
5949 SetLastError(WSAEINVAL);
5950 return SOCKET_ERROR;
5953 /***********************************************************************
5954 * WSAEventSelect (WS2_32.39)
5956 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
5958 int ret;
5960 TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
5962 SERVER_START_REQ( set_socket_event )
5964 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5965 req->mask = lEvent;
5966 req->event = wine_server_obj_handle( hEvent );
5967 req->window = 0;
5968 req->msg = 0;
5969 ret = wine_server_call( req );
5971 SERVER_END_REQ;
5972 if (!ret) return 0;
5973 SetLastError(WSAEINVAL);
5974 return SOCKET_ERROR;
5977 /**********************************************************************
5978 * WSAGetOverlappedResult (WS2_32.40)
5980 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
5981 LPDWORD lpcbTransfer, BOOL fWait,
5982 LPDWORD lpdwFlags )
5984 NTSTATUS status;
5986 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
5987 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
5989 if ( lpOverlapped == NULL )
5991 ERR( "Invalid pointer\n" );
5992 WSASetLastError(WSA_INVALID_PARAMETER);
5993 return FALSE;
5996 status = lpOverlapped->Internal;
5997 if (status == STATUS_PENDING)
5999 if (!fWait)
6001 SetLastError( WSA_IO_INCOMPLETE );
6002 return FALSE;
6005 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
6006 INFINITE ) == WAIT_FAILED)
6007 return FALSE;
6008 status = lpOverlapped->Internal;
6011 if ( lpcbTransfer )
6012 *lpcbTransfer = lpOverlapped->InternalHigh;
6014 if ( lpdwFlags )
6015 *lpdwFlags = lpOverlapped->u.s.Offset;
6017 if (status) SetLastError( RtlNtStatusToDosError(status) );
6018 return !status;
6022 /***********************************************************************
6023 * WSAAsyncSelect (WS2_32.101)
6025 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
6027 int ret;
6029 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
6031 SERVER_START_REQ( set_socket_event )
6033 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6034 req->mask = lEvent;
6035 req->event = 0;
6036 req->window = wine_server_user_handle( hWnd );
6037 req->msg = uMsg;
6038 ret = wine_server_call( req );
6040 SERVER_END_REQ;
6041 if (!ret) return 0;
6042 SetLastError(WSAEINVAL);
6043 return SOCKET_ERROR;
6046 /***********************************************************************
6047 * WSACreateEvent (WS2_32.31)
6050 WSAEVENT WINAPI WSACreateEvent(void)
6052 /* Create a manual-reset event, with initial state: unsignaled */
6053 TRACE("\n");
6055 return CreateEventW(NULL, TRUE, FALSE, NULL);
6058 /***********************************************************************
6059 * WSACloseEvent (WS2_32.29)
6062 BOOL WINAPI WSACloseEvent(WSAEVENT event)
6064 TRACE ("event=%p\n", event);
6066 return CloseHandle(event);
6069 /***********************************************************************
6070 * WSASocketA (WS2_32.78)
6073 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
6074 LPWSAPROTOCOL_INFOA lpProtocolInfo,
6075 GROUP g, DWORD dwFlags)
6077 INT len;
6078 WSAPROTOCOL_INFOW info;
6080 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
6081 af, type, protocol, lpProtocolInfo, g, dwFlags);
6083 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
6085 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
6086 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
6087 info.szProtocol, WSAPROTOCOL_LEN + 1);
6089 if (!len)
6091 WSASetLastError( WSAEINVAL);
6092 return SOCKET_ERROR;
6095 return WSASocketW(af, type, protocol, &info, g, dwFlags);
6098 /***********************************************************************
6099 * WSASocketW (WS2_32.79)
6102 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
6103 LPWSAPROTOCOL_INFOW lpProtocolInfo,
6104 GROUP g, DWORD dwFlags)
6106 SOCKET ret;
6107 DWORD err;
6108 int unixaf, unixtype, ipxptype = -1;
6111 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
6112 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
6115 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
6116 af, type, protocol, lpProtocolInfo, g, dwFlags );
6118 if (!num_startup)
6120 err = WSANOTINITIALISED;
6121 goto done;
6124 /* hack for WSADuplicateSocket */
6125 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
6126 ret = lpProtocolInfo->dwServiceFlags3;
6127 TRACE("\tgot duplicate %04lx\n", ret);
6128 return ret;
6131 if (lpProtocolInfo)
6133 if (af == FROM_PROTOCOL_INFO || !af)
6134 af = lpProtocolInfo->iAddressFamily;
6135 if (type == FROM_PROTOCOL_INFO || !type)
6136 type = lpProtocolInfo->iSocketType;
6137 if (protocol == FROM_PROTOCOL_INFO || !protocol)
6138 protocol = lpProtocolInfo->iProtocol;
6141 if (!type && (af || protocol))
6143 int autoproto = protocol;
6144 WSAPROTOCOL_INFOW infow;
6146 /* default to the first valid protocol */
6147 if (!autoproto)
6148 autoproto = valid_protocols[0];
6149 else if(IS_IPX_PROTO(autoproto))
6150 autoproto = WS_NSPROTO_IPX;
6152 if (WS_EnterSingleProtocolW(autoproto, &infow))
6154 type = infow.iSocketType;
6156 /* after win2003 it's no longer possible to pass AF_UNSPEC
6157 using the protocol info struct */
6158 if (!lpProtocolInfo && af == WS_AF_UNSPEC)
6159 af = infow.iAddressFamily;
6164 Windows has an extension to the IPX protocol that allows one to create sockets
6165 and set the IPX packet type at the same time, to do that a caller will use
6166 a protocol like NSPROTO_IPX + <PACKET TYPE>
6168 if (IS_IPX_PROTO(protocol))
6169 ipxptype = protocol - WS_NSPROTO_IPX;
6171 /* convert the socket family, type and protocol */
6172 unixaf = convert_af_w2u(af);
6173 unixtype = convert_socktype_w2u(type);
6174 protocol = convert_proto_w2u(protocol);
6175 if (unixaf == AF_UNSPEC) unixaf = -1;
6177 /* filter invalid parameters */
6178 if (protocol < 0)
6180 /* the type could not be converted */
6181 if (type && unixtype < 0)
6183 err = WSAESOCKTNOSUPPORT;
6184 goto done;
6187 err = WSAEPROTONOSUPPORT;
6188 goto done;
6190 if (unixaf < 0)
6192 /* both family and protocol can't be invalid */
6193 if (protocol <= 0)
6195 err = WSAEINVAL;
6196 goto done;
6199 /* family could not be converted and neither socket type */
6200 if (unixtype < 0 && af >= 0)
6203 err = WSAESOCKTNOSUPPORT;
6204 goto done;
6207 err = WSAEAFNOSUPPORT;
6208 goto done;
6211 SERVER_START_REQ( create_socket )
6213 req->family = unixaf;
6214 req->type = unixtype;
6215 req->protocol = protocol;
6216 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
6217 req->attributes = OBJ_INHERIT;
6218 req->flags = dwFlags;
6219 set_error( wine_server_call( req ) );
6220 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
6222 SERVER_END_REQ;
6223 if (ret)
6225 TRACE("\tcreated %04lx\n", ret );
6226 if (ipxptype > 0)
6227 set_ipx_packettype(ret, ipxptype);
6228 return ret;
6231 err = GetLastError();
6232 if (err == WSAEACCES) /* raw socket denied */
6234 if (type == SOCK_RAW)
6235 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
6236 else
6237 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
6239 else
6241 /* invalid combination of valid parameters, like SOCK_STREAM + IPPROTO_UDP */
6242 if (err == WSAEINVAL)
6243 err = WSAESOCKTNOSUPPORT;
6244 else if (err == WSAEOPNOTSUPP)
6245 err = WSAEPROTONOSUPPORT;
6248 done:
6249 WARN("\t\tfailed, error %d!\n", err);
6250 SetLastError(err);
6251 return INVALID_SOCKET;
6254 /***********************************************************************
6255 * WSAJoinLeaf (WS2_32.58)
6258 SOCKET WINAPI WSAJoinLeaf(
6259 SOCKET s,
6260 const struct WS_sockaddr *addr,
6261 int addrlen,
6262 LPWSABUF lpCallerData,
6263 LPWSABUF lpCalleeData,
6264 LPQOS lpSQOS,
6265 LPQOS lpGQOS,
6266 DWORD dwFlags)
6268 FIXME("stub.\n");
6269 return INVALID_SOCKET;
6272 /***********************************************************************
6273 * __WSAFDIsSet (WS2_32.151)
6275 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
6277 int i = set->fd_count;
6279 TRACE("(%ld,%p(%i))\n", s, set, i);
6281 while (i--)
6282 if (set->fd_array[i] == s) return 1;
6283 return 0;
6286 /***********************************************************************
6287 * WSAIsBlocking (WS2_32.114)
6289 BOOL WINAPI WSAIsBlocking(void)
6291 /* By default WinSock should set all its sockets to non-blocking mode
6292 * and poll in PeekMessage loop when processing "blocking" ones. This
6293 * function is supposed to tell if the program is in this loop. Our
6294 * blocking calls are truly blocking so we always return FALSE.
6296 * Note: It is allowed to call this function without prior WSAStartup().
6299 TRACE("\n");
6300 return FALSE;
6303 /***********************************************************************
6304 * WSACancelBlockingCall (WS2_32.113)
6306 INT WINAPI WSACancelBlockingCall(void)
6308 TRACE("\n");
6309 return 0;
6312 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
6314 FIXME("How was this called?\n");
6315 return x();
6319 /***********************************************************************
6320 * WSASetBlockingHook (WS2_32.109)
6322 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
6324 FARPROC prev = blocking_hook;
6325 blocking_hook = lpBlockFunc;
6326 TRACE("hook %p\n", lpBlockFunc);
6327 return prev;
6331 /***********************************************************************
6332 * WSAUnhookBlockingHook (WS2_32.110)
6334 INT WINAPI WSAUnhookBlockingHook(void)
6336 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
6337 return 0;
6341 /* ----------------------------------- end of API stuff */
6343 /* ----------------------------------- helper functions -
6345 * TODO: Merge WS_dup_..() stuff into one function that
6346 * would operate with a generic structure containing internal
6347 * pointers (via a template of some kind).
6350 static int list_size(char** l, int item_size)
6352 int i,j = 0;
6353 if(l)
6354 { for(i=0;l[i];i++)
6355 j += (item_size) ? item_size : strlen(l[i]) + 1;
6356 j += (i + 1) * sizeof(char*); }
6357 return j;
6360 static int list_dup(char** l_src, char** l_to, int item_size)
6362 char *p;
6363 int i;
6365 for (i = 0; l_src[i]; i++) ;
6366 p = (char *)(l_to + i + 1);
6367 for (i = 0; l_src[i]; i++)
6369 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
6370 memcpy(p, l_src[i], count);
6371 l_to[i] = p;
6372 p += count;
6374 l_to[i] = NULL;
6375 return p - (char *)l_to;
6378 /* ----- hostent */
6380 /* create a hostent entry
6382 * Creates the entry with enough memory for the name, aliases
6383 * addresses, and the address pointers. Also copies the name
6384 * and sets up all the pointers.
6386 * NOTE: The alias and address lists must be allocated with room
6387 * for the NULL item terminating the list. This is true even if
6388 * the list has no items ("aliases" and "addresses" must be
6389 * at least "1", a truly empty list is invalid).
6391 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length)
6393 struct WS_hostent *p_to;
6394 char *p;
6395 int size = (sizeof(struct WS_hostent) +
6396 strlen(name) + 1 +
6397 sizeof(char *) * aliases +
6398 aliases_size +
6399 sizeof(char *) * addresses +
6400 address_length * (addresses - 1)), i;
6402 if (!(p_to = check_buffer_he(size))) return NULL;
6403 memset(p_to, 0, size);
6405 /* Use the memory in the same way winsock does.
6406 * First set the pointer for aliases, second set the pointers for addresses.
6407 * Third fill the addresses indexes, fourth jump aliases names size.
6408 * Fifth fill the hostname.
6409 * NOTE: This method is valid for OS version's >= XP.
6411 p = (char *)(p_to + 1);
6412 p_to->h_aliases = (char **)p;
6413 p += sizeof(char *)*aliases;
6415 p_to->h_addr_list = (char **)p;
6416 p += sizeof(char *)*addresses;
6418 for (i = 0, addresses--; i < addresses; i++, p += address_length)
6419 p_to->h_addr_list[i] = p;
6421 /* NOTE: h_aliases must be filled in manually because we don't know each string
6422 * size, leave these pointers NULL (already set to NULL by memset earlier).
6424 p += aliases_size;
6426 p_to->h_name = p;
6427 strcpy(p, name);
6429 return p_to;
6432 /* duplicate hostent entry
6433 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
6434 * Ditto for protoent and servent.
6436 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
6438 int i, addresses = 0, alias_size = 0;
6439 struct WS_hostent *p_to;
6440 char *p;
6442 for( i = 0; p_he->h_aliases[i]; i++) alias_size += strlen(p_he->h_aliases[i]) + 1;
6443 while (p_he->h_addr_list[addresses]) addresses++;
6445 p_to = WS_create_he(p_he->h_name, i + 1, alias_size, addresses + 1, p_he->h_length);
6447 if (!p_to) return NULL;
6448 p_to->h_addrtype = convert_af_u2w(p_he->h_addrtype);
6449 p_to->h_length = p_he->h_length;
6451 for(i = 0, p = p_to->h_addr_list[0]; p_he->h_addr_list[i]; i++, p += p_to->h_length)
6452 memcpy(p, p_he->h_addr_list[i], p_to->h_length);
6454 /* Fill the aliases after the IP data */
6455 for(i = 0; p_he->h_aliases[i]; i++)
6457 p_to->h_aliases[i] = p;
6458 strcpy(p, p_he->h_aliases[i]);
6459 p += strlen(p) + 1;
6462 return p_to;
6465 /* ----- protoent */
6467 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
6469 char *p;
6470 struct WS_protoent *p_to;
6472 int size = (sizeof(*p_pe) +
6473 strlen(p_pe->p_name) + 1 +
6474 list_size(p_pe->p_aliases, 0));
6476 if (!(p_to = check_buffer_pe(size))) return NULL;
6477 p_to->p_proto = p_pe->p_proto;
6479 p = (char *)(p_to + 1);
6480 p_to->p_name = p;
6481 strcpy(p, p_pe->p_name);
6482 p += strlen(p) + 1;
6484 p_to->p_aliases = (char **)p;
6485 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
6486 return p_to;
6489 /* ----- servent */
6491 static struct WS_servent *WS_dup_se(const struct servent* p_se)
6493 char *p;
6494 struct WS_servent *p_to;
6496 int size = (sizeof(*p_se) +
6497 strlen(p_se->s_proto) + 1 +
6498 strlen(p_se->s_name) + 1 +
6499 list_size(p_se->s_aliases, 0));
6501 if (!(p_to = check_buffer_se(size))) return NULL;
6502 p_to->s_port = p_se->s_port;
6504 p = (char *)(p_to + 1);
6505 p_to->s_name = p;
6506 strcpy(p, p_se->s_name);
6507 p += strlen(p) + 1;
6509 p_to->s_proto = p;
6510 strcpy(p, p_se->s_proto);
6511 p += strlen(p) + 1;
6513 p_to->s_aliases = (char **)p;
6514 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
6515 return p_to;
6519 /***********************************************************************
6520 * WSARecv (WS2_32.67)
6522 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6523 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
6524 LPWSAOVERLAPPED lpOverlapped,
6525 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
6527 return WS2_recv_base(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
6528 NULL, NULL, lpOverlapped, lpCompletionRoutine, NULL);
6531 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6532 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
6533 struct WS_sockaddr *lpFrom,
6534 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
6535 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
6536 LPWSABUF lpControlBuffer )
6538 unsigned int i, options;
6539 int n, fd, err, overlapped;
6540 struct ws2_async *wsa, localwsa;
6541 BOOL is_blocking;
6542 DWORD timeout_start = GetTickCount();
6543 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
6545 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
6546 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
6547 (lpFromlen ? *lpFromlen : -1),
6548 lpOverlapped, lpCompletionRoutine);
6550 fd = get_sock_fd( s, FILE_READ_DATA, &options );
6551 TRACE( "fd=%d, options=%x\n", fd, options );
6553 if (fd == -1) return SOCKET_ERROR;
6555 overlapped = (lpOverlapped || lpCompletionRoutine) &&
6556 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
6557 if (overlapped || dwBufferCount > 1)
6559 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
6561 err = WSAEFAULT;
6562 goto error;
6565 else
6566 wsa = &localwsa;
6568 wsa->hSocket = SOCKET2HANDLE(s);
6569 wsa->flags = *lpFlags;
6570 wsa->lpFlags = lpFlags;
6571 wsa->addr = lpFrom;
6572 wsa->addrlen.ptr = lpFromlen;
6573 wsa->control = lpControlBuffer;
6574 wsa->n_iovecs = dwBufferCount;
6575 wsa->first_iovec = 0;
6576 for (i = 0; i < dwBufferCount; i++)
6578 /* check buffer first to trigger write watches */
6579 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
6581 err = WSAEFAULT;
6582 goto error;
6584 wsa->iovec[i].iov_base = lpBuffers[i].buf;
6585 wsa->iovec[i].iov_len = lpBuffers[i].len;
6588 for (;;)
6590 n = WS2_recv( fd, wsa );
6591 if (n == -1)
6593 if (errno != EAGAIN)
6595 int loc_errno = errno;
6596 err = wsaErrno();
6597 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
6598 goto error;
6601 else if (lpNumberOfBytesRecvd) *lpNumberOfBytesRecvd = n;
6603 if (overlapped)
6605 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
6607 wsa->user_overlapped = lpOverlapped;
6608 wsa->completion_func = lpCompletionRoutine;
6609 release_sock_fd( s, fd );
6611 if (n == -1)
6613 iosb->u.Status = STATUS_PENDING;
6614 iosb->Information = 0;
6616 SERVER_START_REQ( register_async )
6618 req->type = ASYNC_TYPE_READ;
6619 req->async.handle = wine_server_obj_handle( wsa->hSocket );
6620 req->async.callback = wine_server_client_ptr( WS2_async_recv );
6621 req->async.iosb = wine_server_client_ptr( iosb );
6622 req->async.arg = wine_server_client_ptr( wsa );
6623 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
6624 req->async.cvalue = cvalue;
6625 err = wine_server_call( req );
6627 SERVER_END_REQ;
6629 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
6630 WSASetLastError( NtStatusToWSAError( err ));
6631 return SOCKET_ERROR;
6634 iosb->u.Status = STATUS_SUCCESS;
6635 iosb->Information = n;
6636 if (!wsa->completion_func)
6638 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
6639 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
6640 HeapFree( GetProcessHeap(), 0, wsa );
6642 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
6643 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
6644 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6645 return 0;
6648 if (n != -1) break;
6650 if ((err = _is_blocking( s, &is_blocking )))
6652 err = NtStatusToWSAError( err );
6653 goto error;
6656 if ( is_blocking )
6658 struct pollfd pfd;
6659 int timeout = GET_RCVTIMEO(fd);
6660 if (timeout != -1)
6662 timeout -= GetTickCount() - timeout_start;
6663 if (timeout < 0) timeout = 0;
6666 pfd.fd = fd;
6667 pfd.events = POLLIN;
6668 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
6670 if (!timeout || !poll( &pfd, 1, timeout ))
6672 err = WSAETIMEDOUT;
6673 /* a timeout is not fatal */
6674 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6675 goto error;
6678 else
6680 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6681 err = WSAEWOULDBLOCK;
6682 goto error;
6686 TRACE(" -> %i bytes\n", n);
6687 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
6688 release_sock_fd( s, fd );
6689 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6691 return 0;
6693 error:
6694 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
6695 release_sock_fd( s, fd );
6696 WARN(" -> ERROR %d\n", err);
6697 WSASetLastError( err );
6698 return SOCKET_ERROR;
6701 /***********************************************************************
6702 * WSARecvFrom (WS2_32.69)
6704 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6705 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
6706 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
6707 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
6710 return WS2_recv_base( s, lpBuffers, dwBufferCount,
6711 lpNumberOfBytesRecvd, lpFlags,
6712 lpFrom, lpFromlen,
6713 lpOverlapped, lpCompletionRoutine, NULL );
6716 /***********************************************************************
6717 * WSCInstallProvider (WS2_32.88)
6719 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
6720 LPCWSTR lpszProviderDllPath,
6721 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
6722 DWORD dwNumberOfEntries,
6723 LPINT lpErrno )
6725 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
6726 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
6727 dwNumberOfEntries, lpErrno);
6728 *lpErrno = 0;
6729 return 0;
6733 /***********************************************************************
6734 * WSCDeinstallProvider (WS2_32.83)
6736 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
6738 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
6739 *lpErrno = 0;
6740 return 0;
6744 /***********************************************************************
6745 * WSAAccept (WS2_32.26)
6747 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
6748 LPCONDITIONPROC lpfnCondition, DWORD_PTR dwCallbackData)
6751 int ret = 0, size;
6752 WSABUF CallerId, CallerData, CalleeId, CalleeData;
6753 /* QOS SQOS, GQOS; */
6754 GROUP g;
6755 SOCKET cs;
6756 SOCKADDR src_addr, dst_addr;
6758 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
6759 s, addr, addrlen, lpfnCondition, dwCallbackData);
6761 cs = WS_accept(s, addr, addrlen);
6762 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
6763 if (!lpfnCondition) return cs;
6765 if (addr && addrlen)
6767 CallerId.buf = (char *)addr;
6768 CallerId.len = *addrlen;
6770 else
6772 size = sizeof(src_addr);
6773 WS_getpeername(cs, &src_addr, &size);
6774 CallerId.buf = (char *)&src_addr;
6775 CallerId.len = size;
6777 CallerData.buf = NULL;
6778 CallerData.len = 0;
6780 size = sizeof(dst_addr);
6781 WS_getsockname(cs, &dst_addr, &size);
6783 CalleeId.buf = (char *)&dst_addr;
6784 CalleeId.len = sizeof(dst_addr);
6786 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
6787 &CalleeId, &CalleeData, &g, dwCallbackData);
6789 switch (ret)
6791 case CF_ACCEPT:
6792 return cs;
6793 case CF_DEFER:
6794 SERVER_START_REQ( set_socket_deferred )
6796 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6797 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
6798 if ( !wine_server_call_err ( req ) )
6800 SetLastError( WSATRY_AGAIN );
6801 WS_closesocket( cs );
6804 SERVER_END_REQ;
6805 return SOCKET_ERROR;
6806 case CF_REJECT:
6807 WS_closesocket(cs);
6808 SetLastError(WSAECONNREFUSED);
6809 return SOCKET_ERROR;
6810 default:
6811 FIXME("Unknown return type from Condition function\n");
6812 SetLastError(WSAENOTSOCK);
6813 return SOCKET_ERROR;
6817 /***********************************************************************
6818 * WSADuplicateSocketA (WS2_32.32)
6820 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
6822 return WS_DuplicateSocket(FALSE, s, dwProcessId, (LPWSAPROTOCOL_INFOW) lpProtocolInfo);
6825 /***********************************************************************
6826 * WSADuplicateSocketW (WS2_32.33)
6828 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
6830 return WS_DuplicateSocket(TRUE, s, dwProcessId, lpProtocolInfo);
6833 /***********************************************************************
6834 * WSAInstallServiceClassA (WS2_32.48)
6836 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
6838 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
6839 WSASetLastError(WSAEACCES);
6840 return SOCKET_ERROR;
6843 /***********************************************************************
6844 * WSAInstallServiceClassW (WS2_32.49)
6846 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
6848 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
6849 WSASetLastError(WSAEACCES);
6850 return SOCKET_ERROR;
6853 /***********************************************************************
6854 * WSARemoveServiceClass (WS2_32.70)
6856 int WINAPI WSARemoveServiceClass(LPGUID info)
6858 FIXME("Request to remove service %p\n",info);
6859 WSASetLastError(WSATYPE_NOT_FOUND);
6860 return SOCKET_ERROR;
6863 /***********************************************************************
6864 * inet_ntop (WS2_32.@)
6866 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
6868 #ifdef HAVE_INET_NTOP
6869 struct WS_in6_addr *in6;
6870 struct WS_in_addr *in;
6871 PCSTR pdst;
6873 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
6874 if (!buffer)
6876 WSASetLastError( STATUS_INVALID_PARAMETER );
6877 return NULL;
6880 switch (family)
6882 case WS_AF_INET:
6884 in = addr;
6885 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
6886 break;
6888 case WS_AF_INET6:
6890 in6 = addr;
6891 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
6892 break;
6894 default:
6895 WSASetLastError( WSAEAFNOSUPPORT );
6896 return NULL;
6899 if (!pdst) WSASetLastError( STATUS_INVALID_PARAMETER );
6900 return pdst;
6901 #else
6902 FIXME( "not supported on this platform\n" );
6903 WSASetLastError( WSAEAFNOSUPPORT );
6904 return NULL;
6905 #endif
6908 /***********************************************************************
6909 * WSAStringToAddressA (WS2_32.80)
6911 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
6912 INT AddressFamily,
6913 LPWSAPROTOCOL_INFOA lpProtocolInfo,
6914 LPSOCKADDR lpAddress,
6915 LPINT lpAddressLength)
6917 INT res=0;
6918 LPSTR workBuffer=NULL,ptrPort;
6920 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
6921 lpProtocolInfo, lpAddress, lpAddressLength );
6923 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
6925 if (!AddressString)
6927 WSASetLastError(WSAEINVAL);
6928 return SOCKET_ERROR;
6931 if (lpProtocolInfo)
6932 FIXME("ProtocolInfo not implemented.\n");
6934 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
6935 strlen(AddressString) + 1);
6936 if (!workBuffer)
6938 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6939 return SOCKET_ERROR;
6942 strcpy(workBuffer, AddressString);
6944 switch(AddressFamily)
6946 case WS_AF_INET:
6948 struct in_addr inetaddr;
6950 /* If lpAddressLength is too small, tell caller the size we need */
6951 if (*lpAddressLength < sizeof(SOCKADDR_IN))
6953 *lpAddressLength = sizeof(SOCKADDR_IN);
6954 res = WSAEFAULT;
6955 break;
6957 *lpAddressLength = sizeof(SOCKADDR_IN);
6958 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
6960 ((LPSOCKADDR_IN)lpAddress)->sin_family = WS_AF_INET;
6962 ptrPort = strchr(workBuffer, ':');
6963 if(ptrPort)
6965 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
6966 *ptrPort = '\0';
6968 else
6970 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
6973 if(inet_aton(workBuffer, &inetaddr) > 0)
6975 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
6976 res = 0;
6978 else
6979 res = WSAEINVAL;
6981 break;
6984 case WS_AF_INET6:
6986 struct in6_addr inetaddr;
6987 /* If lpAddressLength is too small, tell caller the size we need */
6988 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
6990 *lpAddressLength = sizeof(SOCKADDR_IN6);
6991 res = WSAEFAULT;
6992 break;
6994 #ifdef HAVE_INET_PTON
6995 *lpAddressLength = sizeof(SOCKADDR_IN6);
6996 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
6998 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
7000 /* This one is a bit tricky. An IPv6 address contains colons, so the
7001 * check from IPv4 doesn't work like that. However, IPv6 addresses that
7002 * contain a port are written with braces like [fd12:3456:7890::1]:12345
7003 * so what we will do is to look for ']', check if the next char is a
7004 * colon, and if it is, parse the port as in IPv4. */
7006 ptrPort = strchr(workBuffer, ']');
7007 if(ptrPort && *(++ptrPort) == ':')
7009 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort+1));
7010 *ptrPort = '\0';
7012 else
7014 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
7017 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
7019 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
7020 sizeof(struct in6_addr));
7021 res = 0;
7023 else
7024 #endif /* HAVE_INET_PTON */
7025 res = WSAEINVAL;
7027 break;
7029 default:
7030 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
7031 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
7032 res = WSAEINVAL;
7035 HeapFree(GetProcessHeap(), 0, workBuffer);
7037 if (!res) return 0;
7038 WSASetLastError(res);
7039 return SOCKET_ERROR;
7042 /***********************************************************************
7043 * WSAStringToAddressW (WS2_32.81)
7045 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
7046 * If this should be the case, it would be required to map these digits
7047 * to Unicode digits (0-9) using FoldString first.
7049 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
7050 INT AddressFamily,
7051 LPWSAPROTOCOL_INFOW lpProtocolInfo,
7052 LPSOCKADDR lpAddress,
7053 LPINT lpAddressLength)
7055 INT sBuffer,res=0;
7056 LPSTR workBuffer=NULL;
7057 WSAPROTOCOL_INFOA infoA;
7058 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
7060 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
7061 lpAddress, lpAddressLength );
7063 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
7065 /* if ProtocolInfo is available - convert to ANSI variant */
7066 if (lpProtocolInfo)
7068 lpProtoInfoA = &infoA;
7069 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
7071 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
7072 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
7074 WSASetLastError( WSAEINVAL);
7075 return SOCKET_ERROR;
7079 if (AddressString)
7081 /* Translate AddressString to ANSI code page - assumes that only
7082 standard digits 0-9 are used with this API call */
7083 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
7084 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
7086 if (workBuffer)
7088 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
7089 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
7090 lpAddress,lpAddressLength);
7091 HeapFree( GetProcessHeap(), 0, workBuffer );
7092 return res;
7094 else
7095 res = WSA_NOT_ENOUGH_MEMORY;
7097 else
7098 res = WSAEINVAL;
7100 WSASetLastError(res);
7101 return SOCKET_ERROR;
7104 /***********************************************************************
7105 * WSAAddressToStringA (WS2_32.27)
7107 * See WSAAddressToStringW
7109 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
7110 LPWSAPROTOCOL_INFOA info, LPSTR string,
7111 LPDWORD lenstr )
7113 DWORD size;
7114 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
7115 CHAR *p;
7117 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
7119 if (!sockaddr) return SOCKET_ERROR;
7120 if (!string || !lenstr) return SOCKET_ERROR;
7122 switch(sockaddr->sa_family)
7124 case WS_AF_INET:
7125 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
7126 sprintf( buffer, "%u.%u.%u.%u:%u",
7127 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
7128 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
7129 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
7130 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
7131 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
7133 p = strchr( buffer, ':' );
7134 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
7135 break;
7137 case WS_AF_INET6:
7139 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
7141 buffer[0] = 0;
7142 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
7143 if ((sockaddr6->sin6_port))
7144 strcpy(buffer, "[");
7145 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, buffer+strlen(buffer), sizeof(buffer)))
7147 WSASetLastError(WSAEINVAL);
7148 return SOCKET_ERROR;
7150 if ((sockaddr6->sin6_scope_id))
7151 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
7152 if ((sockaddr6->sin6_port))
7153 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
7154 break;
7157 default:
7158 WSASetLastError(WSAEINVAL);
7159 return SOCKET_ERROR;
7162 size = strlen( buffer ) + 1;
7164 if (*lenstr < size)
7166 *lenstr = size;
7167 WSASetLastError(WSAEFAULT);
7168 return SOCKET_ERROR;
7171 TRACE("=> %s,%u bytes\n", debugstr_a(buffer), size);
7172 *lenstr = size;
7173 strcpy( string, buffer );
7174 return 0;
7177 /***********************************************************************
7178 * WSAAddressToStringW (WS2_32.28)
7180 * Convert a sockaddr address into a readable address string.
7182 * PARAMS
7183 * sockaddr [I] Pointer to a sockaddr structure.
7184 * len [I] Size of the sockaddr structure.
7185 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
7186 * string [I/O] Pointer to a buffer to receive the address string.
7187 * lenstr [I/O] Size of the receive buffer in WCHARs.
7189 * RETURNS
7190 * Success: 0
7191 * Failure: SOCKET_ERROR
7193 * NOTES
7194 * The 'info' parameter is ignored.
7196 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
7197 LPWSAPROTOCOL_INFOW info, LPWSTR string,
7198 LPDWORD lenstr )
7200 INT ret;
7201 DWORD size;
7202 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
7203 CHAR bufAddr[54];
7205 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
7207 size = *lenstr;
7208 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
7210 if (ret) return ret;
7212 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
7214 if (*lenstr < size)
7216 *lenstr = size;
7217 WSASetLastError(WSAEFAULT);
7218 return SOCKET_ERROR;
7221 TRACE("=> %s,%u bytes\n", debugstr_w(buffer), size);
7222 *lenstr = size;
7223 lstrcpyW( string, buffer );
7224 return 0;
7227 /***********************************************************************
7228 * WSAEnumNameSpaceProvidersA (WS2_32.34)
7230 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
7232 FIXME( "(%p %p) Stub!\n", len, buffer );
7233 return 0;
7236 /***********************************************************************
7237 * WSAEnumNameSpaceProvidersW (WS2_32.35)
7239 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
7241 FIXME( "(%p %p) Stub!\n", len, buffer );
7242 return 0;
7245 /***********************************************************************
7246 * WSAGetQOSByName (WS2_32.41)
7248 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
7250 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
7251 return FALSE;
7254 /***********************************************************************
7255 * WSAGetServiceClassInfoA (WS2_32.42)
7257 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
7258 LPWSASERVICECLASSINFOA info )
7260 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
7261 len, info );
7262 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7263 return SOCKET_ERROR;
7266 /***********************************************************************
7267 * WSAGetServiceClassInfoW (WS2_32.43)
7269 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
7270 LPWSASERVICECLASSINFOW info )
7272 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
7273 len, info );
7274 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7275 return SOCKET_ERROR;
7278 /***********************************************************************
7279 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
7281 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
7283 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
7284 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7285 return SOCKET_ERROR;
7288 /***********************************************************************
7289 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
7291 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
7293 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
7294 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7295 return SOCKET_ERROR;
7298 /***********************************************************************
7299 * WSALookupServiceBeginA (WS2_32.59)
7301 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
7302 DWORD dwControlFlags,
7303 LPHANDLE lphLookup)
7305 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
7306 lphLookup);
7307 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7308 return SOCKET_ERROR;
7311 /***********************************************************************
7312 * WSALookupServiceBeginW (WS2_32.60)
7314 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
7315 DWORD dwControlFlags,
7316 LPHANDLE lphLookup)
7318 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
7319 lphLookup);
7320 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7321 return SOCKET_ERROR;
7324 /***********************************************************************
7325 * WSALookupServiceEnd (WS2_32.61)
7327 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
7329 FIXME("(%p) Stub!\n", lookup );
7330 return 0;
7333 /***********************************************************************
7334 * WSALookupServiceNextA (WS2_32.62)
7336 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
7338 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
7339 WSASetLastError(WSA_E_NO_MORE);
7340 return SOCKET_ERROR;
7343 /***********************************************************************
7344 * WSALookupServiceNextW (WS2_32.63)
7346 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
7348 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
7349 WSASetLastError(WSA_E_NO_MORE);
7350 return SOCKET_ERROR;
7353 /***********************************************************************
7354 * WSANtohl (WS2_32.64)
7356 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
7358 TRACE( "(0x%04lx 0x%08x %p)\n", s, netlong, lphostlong );
7360 if (!lphostlong) return WSAEFAULT;
7362 *lphostlong = ntohl( netlong );
7363 return 0;
7366 /***********************************************************************
7367 * WSANtohs (WS2_32.65)
7369 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
7371 TRACE( "(0x%04lx 0x%08x %p)\n", s, netshort, lphostshort );
7373 if (!lphostshort) return WSAEFAULT;
7375 *lphostshort = ntohs( netshort );
7376 return 0;
7379 /***********************************************************************
7380 * WSAProviderConfigChange (WS2_32.66)
7382 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
7383 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
7385 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
7386 return SOCKET_ERROR;
7389 /***********************************************************************
7390 * WSARecvDisconnect (WS2_32.68)
7392 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
7394 TRACE( "(0x%04lx %p)\n", s, disconnectdata );
7396 return WS_shutdown( s, SD_RECEIVE );
7399 /***********************************************************************
7400 * WSASetServiceA (WS2_32.76)
7402 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
7404 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
7405 return 0;
7408 /***********************************************************************
7409 * WSASetServiceW (WS2_32.77)
7411 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
7413 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
7414 return 0;
7417 /***********************************************************************
7418 * WSCEnableNSProvider (WS2_32.84)
7420 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
7422 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
7423 return 0;
7426 /***********************************************************************
7427 * WSCGetProviderPath (WS2_32.86)
7429 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
7431 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
7433 if (!errcode || !provider || !len) return WSAEFAULT;
7435 *errcode = WSAEINVAL;
7436 return SOCKET_ERROR;
7439 /***********************************************************************
7440 * WSCInstallNameSpace (WS2_32.87)
7442 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
7443 DWORD version, LPGUID provider )
7445 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
7446 namespace, version, debugstr_guid(provider) );
7447 return 0;
7450 /***********************************************************************
7451 * WSCUnInstallNameSpace (WS2_32.89)
7453 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
7455 FIXME("(%p) Stub!\n", lpProviderId);
7456 return NO_ERROR;
7459 /***********************************************************************
7460 * WSCWriteProviderOrder (WS2_32.91)
7462 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
7464 FIXME("(%p 0x%08x) Stub!\n", entry, number);
7465 return 0;
7468 /***********************************************************************
7469 * WSANSPIoctl (WS2_32.91)
7471 INT WINAPI WSANSPIoctl( HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer,
7472 DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer,
7473 LPDWORD lpcbBytesReturned, LPWSACOMPLETION lpCompletion )
7475 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup, dwControlCode,
7476 lpvInBuffer, cbInBuffer, lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpCompletion);
7477 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7478 return SOCKET_ERROR;
7481 /*****************************************************************************
7482 * WSAEnumProtocolsA [WS2_32.@]
7484 * see function WSAEnumProtocolsW
7486 INT WINAPI WSAEnumProtocolsA( LPINT protocols, LPWSAPROTOCOL_INFOA buffer, LPDWORD len )
7488 return WS_EnumProtocols( FALSE, protocols, (LPWSAPROTOCOL_INFOW) buffer, len);
7491 /*****************************************************************************
7492 * WSAEnumProtocolsW [WS2_32.@]
7494 * Retrieves information about specified set of active network protocols.
7496 * PARAMS
7497 * protocols [I] Pointer to null-terminated array of protocol id's. NULL
7498 * retrieves information on all available protocols.
7499 * buffer [I] Pointer to a buffer to be filled with WSAPROTOCOL_INFO
7500 * structures.
7501 * len [I/O] Pointer to a variable specifying buffer size. On output
7502 * the variable holds the number of bytes needed when the
7503 * specified size is too small.
7505 * RETURNS
7506 * Success: number of WSAPROTOCOL_INFO structures in buffer.
7507 * Failure: SOCKET_ERROR
7509 * NOTES
7510 * NT4SP5 does not return SPX if protocols == NULL
7512 * BUGS
7513 * - NT4SP5 returns in addition these list of NETBIOS protocols
7514 * (address family 17), each entry two times one for socket type 2 and 5
7516 * iProtocol szProtocol
7517 * 0x80000000 \Device\NwlnkNb
7518 * 0xfffffffa \Device\NetBT_CBENT7
7519 * 0xfffffffb \Device\Nbf_CBENT7
7520 * 0xfffffffc \Device\NetBT_NdisWan5
7521 * 0xfffffffd \Device\NetBT_El9202
7522 * 0xfffffffe \Device\Nbf_El9202
7523 * 0xffffffff \Device\Nbf_NdisWan4
7525 * - there is no check that the operating system supports the returned
7526 * protocols
7528 INT WINAPI WSAEnumProtocolsW( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
7530 return WS_EnumProtocols( TRUE, protocols, buffer, len);
7533 /*****************************************************************************
7534 * WSCEnumProtocols [WS2_32.@]
7536 * PARAMS
7537 * protocols [I] Null-terminated array of iProtocol values.
7538 * buffer [O] Buffer of WSAPROTOCOL_INFOW structures.
7539 * len [I/O] Size of buffer on input/output.
7540 * errno [O] Error code.
7542 * RETURNS
7543 * Success: number of protocols to be reported on.
7544 * Failure: SOCKET_ERROR. error is in errno.
7546 * BUGS
7547 * Doesn't supply info on layered protocols.
7550 INT WINAPI WSCEnumProtocols( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len, LPINT err )
7552 INT ret = WSAEnumProtocolsW( protocols, buffer, len );
7554 if (ret == SOCKET_ERROR) *err = WSAENOBUFS;
7556 return ret;