ws2_32: Add tests and implement inet_pton.
[wine/multimedia.git] / dlls / ws2_32 / socket.c
blobb3db3061044187ed1edca7fc1d97ccfd66b7a500
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 #ifdef AI_V4MAPPED
533 MAP_OPTION( AI_V4MAPPED ),
534 #endif
535 MAP_OPTION( AI_ADDRCONFIG ),
538 static const int ws_niflag_map[][2] =
540 MAP_OPTION( NI_NOFQDN ),
541 MAP_OPTION( NI_NUMERICHOST ),
542 MAP_OPTION( NI_NAMEREQD ),
543 MAP_OPTION( NI_NUMERICSERV ),
544 MAP_OPTION( NI_DGRAM ),
547 static const int ws_eai_map[][2] =
549 MAP_OPTION( EAI_AGAIN ),
550 MAP_OPTION( EAI_BADFLAGS ),
551 MAP_OPTION( EAI_FAIL ),
552 MAP_OPTION( EAI_FAMILY ),
553 MAP_OPTION( EAI_MEMORY ),
554 /* Note: EAI_NODATA is deprecated, but still
555 * used by Windows and Linux... We map the newer
556 * EAI_NONAME to EAI_NODATA for now until Windows
557 * changes too.
559 #ifdef EAI_NODATA
560 MAP_OPTION( EAI_NODATA ),
561 #endif
562 #ifdef EAI_NONAME
563 { WS_EAI_NODATA, EAI_NONAME },
564 #endif
566 MAP_OPTION( EAI_SERVICE ),
567 MAP_OPTION( EAI_SOCKTYPE ),
568 { 0, 0 }
571 static const char magic_loopback_addr[] = {127, 12, 34, 56};
573 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
574 #ifdef IP_PKTINFO
575 static inline WSACMSGHDR *fill_control_message(int level, int type, WSACMSGHDR *current, ULONG *maxsize, void *data, int len)
577 ULONG msgsize = sizeof(WSACMSGHDR) + WSA_CMSG_ALIGN(len);
578 char *ptr = (char *) current + sizeof(WSACMSGHDR);
580 /* Make sure there is at least enough room for this entry */
581 if (msgsize > *maxsize)
582 return NULL;
583 *maxsize -= msgsize;
584 /* Fill in the entry */
585 current->cmsg_len = sizeof(WSACMSGHDR) + len;
586 current->cmsg_level = level;
587 current->cmsg_type = type;
588 memcpy(ptr, data, len);
589 /* Return the pointer to where next entry should go */
590 return (WSACMSGHDR *) (ptr + WSA_CMSG_ALIGN(len));
592 #endif /* IP_PKTINFO */
594 static inline int convert_control_headers(struct msghdr *hdr, WSABUF *control)
596 #ifdef IP_PKTINFO
597 WSACMSGHDR *cmsg_win = (WSACMSGHDR *) control->buf, *ptr;
598 ULONG ctlsize = control->len;
599 struct cmsghdr *cmsg_unix;
601 ptr = cmsg_win;
602 /* Loop over all the headers, converting as appropriate */
603 for (cmsg_unix = CMSG_FIRSTHDR(hdr); cmsg_unix != NULL; cmsg_unix = CMSG_NXTHDR(hdr, cmsg_unix))
605 switch(cmsg_unix->cmsg_level)
607 case IPPROTO_IP:
608 switch(cmsg_unix->cmsg_type)
610 case IP_PKTINFO:
612 /* Convert the Unix IP_PKTINFO structure to the Windows version */
613 struct in_pktinfo *data_unix = (struct in_pktinfo *) CMSG_DATA(cmsg_unix);
614 struct WS_in_pktinfo data_win;
616 memcpy(&data_win.ipi_addr,&data_unix->ipi_addr.s_addr,4); /* 4 bytes = 32 address bits */
617 data_win.ipi_ifindex = data_unix->ipi_ifindex;
618 ptr = fill_control_message(WS_IPPROTO_IP, WS_IP_PKTINFO, ptr, &ctlsize,
619 (void*)&data_win, sizeof(data_win));
620 if (!ptr) goto error;
621 } break;
622 default:
623 FIXME("Unhandled IPPROTO_IP message header type %d\n", cmsg_unix->cmsg_type);
624 break;
626 break;
627 default:
628 FIXME("Unhandled message header level %d\n", cmsg_unix->cmsg_level);
629 break;
633 error:
634 /* Set the length of the returned control headers */
635 control->len = (ptr == NULL ? 0 : (char*)ptr - (char*)cmsg_win);
636 return (ptr != NULL);
637 #else /* IP_PKTINFO */
638 control->len = 0;
639 return 1;
640 #endif /* IP_PKTINFO */
642 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
644 /* ----------------------------------- error handling */
646 static NTSTATUS sock_get_ntstatus( int err )
648 switch ( err )
650 case EBADF: return STATUS_INVALID_HANDLE;
651 case EBUSY: return STATUS_DEVICE_BUSY;
652 case EPERM:
653 case EACCES: return STATUS_ACCESS_DENIED;
654 case EFAULT: return STATUS_NO_MEMORY;
655 case EINVAL: return STATUS_INVALID_PARAMETER;
656 case ENFILE:
657 case EMFILE: return STATUS_TOO_MANY_OPENED_FILES;
658 case EWOULDBLOCK: return STATUS_CANT_WAIT;
659 case EINPROGRESS: return STATUS_PENDING;
660 case EALREADY: return STATUS_NETWORK_BUSY;
661 case ENOTSOCK: return STATUS_OBJECT_TYPE_MISMATCH;
662 case EDESTADDRREQ: return STATUS_INVALID_PARAMETER;
663 case EMSGSIZE: return STATUS_BUFFER_OVERFLOW;
664 case EPROTONOSUPPORT:
665 case ESOCKTNOSUPPORT:
666 case EPFNOSUPPORT:
667 case EAFNOSUPPORT:
668 case EPROTOTYPE: return STATUS_NOT_SUPPORTED;
669 case ENOPROTOOPT: return STATUS_INVALID_PARAMETER;
670 case EOPNOTSUPP: return STATUS_NOT_SUPPORTED;
671 case EADDRINUSE: return STATUS_ADDRESS_ALREADY_ASSOCIATED;
672 case EADDRNOTAVAIL: return STATUS_INVALID_PARAMETER;
673 case ECONNREFUSED: return STATUS_CONNECTION_REFUSED;
674 case ESHUTDOWN: return STATUS_PIPE_DISCONNECTED;
675 case ENOTCONN: return STATUS_CONNECTION_DISCONNECTED;
676 case ETIMEDOUT: return STATUS_IO_TIMEOUT;
677 case ENETUNREACH: return STATUS_NETWORK_UNREACHABLE;
678 case ENETDOWN: return STATUS_NETWORK_BUSY;
679 case EPIPE:
680 case ECONNRESET: return STATUS_CONNECTION_RESET;
681 case ECONNABORTED: return STATUS_CONNECTION_ABORTED;
683 case 0: return STATUS_SUCCESS;
684 default:
685 WARN("Unknown errno %d!\n", err);
686 return STATUS_UNSUCCESSFUL;
690 static UINT sock_get_error( int err )
692 switch(err)
694 case EINTR: return WSAEINTR;
695 case EBADF: return WSAEBADF;
696 case EPERM:
697 case EACCES: return WSAEACCES;
698 case EFAULT: return WSAEFAULT;
699 case EINVAL: return WSAEINVAL;
700 case EMFILE: return WSAEMFILE;
701 case EWOULDBLOCK: return WSAEWOULDBLOCK;
702 case EINPROGRESS: return WSAEINPROGRESS;
703 case EALREADY: return WSAEALREADY;
704 case ENOTSOCK: return WSAENOTSOCK;
705 case EDESTADDRREQ: return WSAEDESTADDRREQ;
706 case EMSGSIZE: return WSAEMSGSIZE;
707 case EPROTOTYPE: return WSAEPROTOTYPE;
708 case ENOPROTOOPT: return WSAENOPROTOOPT;
709 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
710 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
711 case EOPNOTSUPP: return WSAEOPNOTSUPP;
712 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
713 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
714 case EADDRINUSE: return WSAEADDRINUSE;
715 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
716 case ENETDOWN: return WSAENETDOWN;
717 case ENETUNREACH: return WSAENETUNREACH;
718 case ENETRESET: return WSAENETRESET;
719 case ECONNABORTED: return WSAECONNABORTED;
720 case EPIPE:
721 case ECONNRESET: return WSAECONNRESET;
722 case ENOBUFS: return WSAENOBUFS;
723 case EISCONN: return WSAEISCONN;
724 case ENOTCONN: return WSAENOTCONN;
725 case ESHUTDOWN: return WSAESHUTDOWN;
726 case ETOOMANYREFS: return WSAETOOMANYREFS;
727 case ETIMEDOUT: return WSAETIMEDOUT;
728 case ECONNREFUSED: return WSAECONNREFUSED;
729 case ELOOP: return WSAELOOP;
730 case ENAMETOOLONG: return WSAENAMETOOLONG;
731 case EHOSTDOWN: return WSAEHOSTDOWN;
732 case EHOSTUNREACH: return WSAEHOSTUNREACH;
733 case ENOTEMPTY: return WSAENOTEMPTY;
734 #ifdef EPROCLIM
735 case EPROCLIM: return WSAEPROCLIM;
736 #endif
737 #ifdef EUSERS
738 case EUSERS: return WSAEUSERS;
739 #endif
740 #ifdef EDQUOT
741 case EDQUOT: return WSAEDQUOT;
742 #endif
743 #ifdef ESTALE
744 case ESTALE: return WSAESTALE;
745 #endif
746 #ifdef EREMOTE
747 case EREMOTE: return WSAEREMOTE;
748 #endif
750 /* just in case we ever get here and there are no problems */
751 case 0: return 0;
752 default:
753 WARN("Unknown errno %d!\n", err);
754 return WSAEOPNOTSUPP;
758 static UINT wsaErrno(void)
760 int loc_errno = errno;
761 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
763 return sock_get_error( loc_errno );
766 /* most ws2 overlapped functions return an ntstatus-based error code */
767 static NTSTATUS wsaErrStatus(void)
769 int loc_errno = errno;
770 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
772 return sock_get_ntstatus(loc_errno);
775 static UINT wsaHerrno(int loc_errno)
777 WARN("h_errno %d.\n", loc_errno);
779 switch(loc_errno)
781 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
782 case TRY_AGAIN: return WSATRY_AGAIN;
783 case NO_RECOVERY: return WSANO_RECOVERY;
784 case NO_DATA: return WSANO_DATA;
785 case ENOBUFS: return WSAENOBUFS;
787 case 0: return 0;
788 default:
789 WARN("Unknown h_errno %d!\n", loc_errno);
790 return WSAEOPNOTSUPP;
794 static inline DWORD NtStatusToWSAError( const DWORD status )
796 /* We only need to cover the status codes set by server async request handling */
797 DWORD wserr;
798 switch ( status )
800 case STATUS_SUCCESS: wserr = 0; break;
801 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
802 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
803 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
804 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
805 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
806 case STATUS_NETWORK_BUSY: wserr = WSAEALREADY; break;
807 case STATUS_NETWORK_UNREACHABLE: wserr = WSAENETUNREACH; break;
808 case STATUS_CONNECTION_REFUSED: wserr = WSAECONNREFUSED; break;
809 case STATUS_CONNECTION_DISCONNECTED: wserr = WSAENOTCONN; break;
810 case STATUS_CONNECTION_RESET: wserr = WSAECONNRESET; break;
811 case STATUS_CONNECTION_ABORTED: wserr = WSAECONNABORTED; break;
812 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
813 case STATUS_ADDRESS_ALREADY_ASSOCIATED: wserr = WSAEADDRINUSE; break;
814 case STATUS_IO_TIMEOUT:
815 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
816 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
817 case STATUS_ACCESS_DENIED: wserr = WSAEACCES; break;
818 case STATUS_TOO_MANY_OPENED_FILES: wserr = WSAEMFILE; break;
819 case STATUS_CANT_WAIT: wserr = WSAEWOULDBLOCK; break;
820 case STATUS_BUFFER_OVERFLOW: wserr = WSAEMSGSIZE; break;
821 case STATUS_NOT_SUPPORTED: wserr = WSAEOPNOTSUPP; break;
822 case STATUS_HOST_UNREACHABLE: wserr = WSAEHOSTUNREACH; break;
824 default:
825 wserr = RtlNtStatusToDosError( status );
826 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
828 return wserr;
831 /* set last error code from NT status without mapping WSA errors */
832 static inline unsigned int set_error( unsigned int err )
834 if (err)
836 err = NtStatusToWSAError( err );
837 SetLastError( err );
839 return err;
842 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
844 int fd;
845 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
846 return -1;
847 return fd;
850 static inline void release_sock_fd( SOCKET s, int fd )
852 wine_server_release_fd( SOCKET2HANDLE(s), fd );
855 static void _enable_event( HANDLE s, unsigned int event,
856 unsigned int sstate, unsigned int cstate )
858 SERVER_START_REQ( enable_socket_event )
860 req->handle = wine_server_obj_handle( s );
861 req->mask = event;
862 req->sstate = sstate;
863 req->cstate = cstate;
864 wine_server_call( req );
866 SERVER_END_REQ;
869 static NTSTATUS _is_blocking(SOCKET s, BOOL *ret)
871 NTSTATUS status;
872 SERVER_START_REQ( get_socket_event )
874 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
875 req->service = FALSE;
876 req->c_event = 0;
877 status = wine_server_call( req );
878 *ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
880 SERVER_END_REQ;
881 return status;
884 static unsigned int _get_sock_mask(SOCKET s)
886 unsigned int ret;
887 SERVER_START_REQ( get_socket_event )
889 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
890 req->service = FALSE;
891 req->c_event = 0;
892 wine_server_call( req );
893 ret = reply->mask;
895 SERVER_END_REQ;
896 return ret;
899 static void _sync_sock_state(SOCKET s)
901 BOOL dummy;
902 /* do a dummy wineserver request in order to let
903 the wineserver run through its select loop once */
904 (void)_is_blocking(s, &dummy);
907 static int _get_sock_error(SOCKET s, unsigned int bit)
909 int events[FD_MAX_EVENTS];
911 SERVER_START_REQ( get_socket_event )
913 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
914 req->service = FALSE;
915 req->c_event = 0;
916 wine_server_set_reply( req, events, sizeof(events) );
917 wine_server_call( req );
919 SERVER_END_REQ;
920 return events[bit];
923 static struct per_thread_data *get_per_thread_data(void)
925 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
926 /* lazy initialization */
927 if (!ptb)
929 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
930 NtCurrentTeb()->WinSockData = ptb;
932 return ptb;
935 static void free_per_thread_data(void)
937 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
939 if (!ptb) return;
941 /* delete scratch buffers */
942 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
943 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
944 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
945 ptb->he_buffer = NULL;
946 ptb->se_buffer = NULL;
947 ptb->pe_buffer = NULL;
949 HeapFree( GetProcessHeap(), 0, ptb );
950 NtCurrentTeb()->WinSockData = NULL;
953 /***********************************************************************
954 * DllMain (WS2_32.init)
956 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
958 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
959 switch (fdwReason) {
960 case DLL_PROCESS_ATTACH:
961 break;
962 case DLL_PROCESS_DETACH:
963 if (fImpLoad) break;
964 free_per_thread_data();
965 DeleteCriticalSection(&csWSgetXXXbyYYY);
966 break;
967 case DLL_THREAD_DETACH:
968 free_per_thread_data();
969 break;
971 return TRUE;
974 /***********************************************************************
975 * convert_sockopt()
977 * Converts socket flags from Windows format.
978 * Return 1 if converted, 0 if not (error).
980 static int convert_sockopt(INT *level, INT *optname)
982 unsigned int i;
983 switch (*level)
985 case WS_SOL_SOCKET:
986 *level = SOL_SOCKET;
987 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
988 if( ws_sock_map[i][0] == *optname )
990 *optname = ws_sock_map[i][1];
991 return 1;
994 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
995 break;
996 case WS_IPPROTO_TCP:
997 *level = IPPROTO_TCP;
998 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
999 if ( ws_tcp_map[i][0] == *optname )
1001 *optname = ws_tcp_map[i][1];
1002 return 1;
1005 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
1006 break;
1007 case WS_IPPROTO_IP:
1008 *level = IPPROTO_IP;
1009 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
1010 if (ws_ip_map[i][0] == *optname )
1012 *optname = ws_ip_map[i][1];
1013 return 1;
1016 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
1017 break;
1018 case WS_IPPROTO_IPV6:
1019 *level = IPPROTO_IPV6;
1020 for(i=0; i<sizeof(ws_ipv6_map)/sizeof(ws_ipv6_map[0]); i++) {
1021 if (ws_ipv6_map[i][0] == *optname )
1023 *optname = ws_ipv6_map[i][1];
1024 return 1;
1027 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname);
1028 break;
1029 default: FIXME("Unimplemented or unknown socket level\n");
1031 return 0;
1034 /* ----------------------------------- Per-thread info (or per-process?) */
1036 static char *strdup_lower(const char *str)
1038 int i;
1039 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
1041 if (ret)
1043 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
1044 ret[i] = 0;
1046 else SetLastError(WSAENOBUFS);
1047 return ret;
1050 static inline int sock_error_p(int s)
1052 unsigned int optval;
1053 socklen_t optlen = sizeof(optval);
1054 getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
1055 if (optval) WARN("\t[%i] error: %d\n", s, optval);
1056 return optval != 0;
1059 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
1060 * from an fd and return the value converted to milli seconds
1061 * or -1 if there is an infinite time out */
1062 static inline int get_rcvsnd_timeo( int fd, int optname)
1064 struct timeval tv;
1065 socklen_t len = sizeof(tv);
1066 int ret = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
1067 if( ret >= 0)
1068 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
1069 if( ret <= 0 ) /* tv == {0,0} means infinite time out */
1070 return -1;
1071 return ret;
1074 /* macro wrappers for portability */
1075 #ifdef SO_RCVTIMEO
1076 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
1077 #else
1078 #define GET_RCVTIMEO(fd) (-1)
1079 #endif
1081 #ifdef SO_SNDTIMEO
1082 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
1083 #else
1084 #define GET_SNDTIMEO(fd) (-1)
1085 #endif
1087 /* utility: given an fd, will block until one of the events occurs */
1088 static inline int do_block( int fd, int events, int timeout )
1090 struct pollfd pfd;
1091 int ret;
1093 pfd.fd = fd;
1094 pfd.events = events;
1096 while ((ret = poll(&pfd, 1, timeout)) < 0)
1098 if (errno != EINTR)
1099 return -1;
1101 if( ret == 0 )
1102 return 0;
1103 return pfd.revents;
1106 static int
1107 convert_af_w2u(int windowsaf) {
1108 unsigned int i;
1110 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1111 if (ws_af_map[i][0] == windowsaf)
1112 return ws_af_map[i][1];
1113 FIXME("unhandled Windows address family %d\n", windowsaf);
1114 return -1;
1117 static int
1118 convert_af_u2w(int unixaf) {
1119 unsigned int i;
1121 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1122 if (ws_af_map[i][1] == unixaf)
1123 return ws_af_map[i][0];
1124 FIXME("unhandled UNIX address family %d\n", unixaf);
1125 return -1;
1128 static int
1129 convert_proto_w2u(int windowsproto) {
1130 unsigned int i;
1132 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1133 if (ws_proto_map[i][0] == windowsproto)
1134 return ws_proto_map[i][1];
1136 /* check for extended IPX */
1137 if (IS_IPX_PROTO(windowsproto))
1138 return windowsproto;
1140 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
1141 return -1;
1144 static int
1145 convert_proto_u2w(int unixproto) {
1146 unsigned int i;
1148 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1149 if (ws_proto_map[i][1] == unixproto)
1150 return ws_proto_map[i][0];
1152 /* if value is inside IPX range just return it - the kernel simply
1153 * echoes the value used in the socket() function */
1154 if (IS_IPX_PROTO(unixproto))
1155 return unixproto;
1157 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
1158 return -1;
1161 static int
1162 convert_socktype_w2u(int windowssocktype) {
1163 unsigned int i;
1165 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1166 if (ws_socktype_map[i][0] == windowssocktype)
1167 return ws_socktype_map[i][1];
1168 FIXME("unhandled Windows socket type %d\n", windowssocktype);
1169 return -1;
1172 static int
1173 convert_socktype_u2w(int unixsocktype) {
1174 unsigned int i;
1176 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1177 if (ws_socktype_map[i][1] == unixsocktype)
1178 return ws_socktype_map[i][0];
1179 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
1180 return -1;
1183 static int set_ipx_packettype(int sock, int ptype)
1185 #ifdef HAS_IPX
1186 int fd = get_sock_fd( sock, 0, NULL ), ret = 0;
1187 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", ptype, fd);
1189 if (fd == -1) return SOCKET_ERROR;
1191 /* We try to set the ipx type on ipx socket level. */
1192 #ifdef SOL_IPX
1193 if(setsockopt(fd, SOL_IPX, IPX_TYPE, &ptype, sizeof(ptype)) == -1)
1195 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
1196 ret = SOCKET_ERROR;
1198 #else
1200 struct ipx val;
1201 /* Should we retrieve val using a getsockopt call and then
1202 * set the modified one? */
1203 val.ipx_pt = ptype;
1204 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
1206 #endif
1207 release_sock_fd( sock, fd );
1208 return ret;
1209 #else
1210 WARN("IPX support is not enabled, can't set packet type\n");
1211 return SOCKET_ERROR;
1212 #endif
1215 /* ----------------------------------- API -----
1217 * Init / cleanup / error checking.
1220 /***********************************************************************
1221 * WSAStartup (WS2_32.115)
1223 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
1225 TRACE("verReq=%x\n", wVersionRequested);
1227 if (LOBYTE(wVersionRequested) < 1)
1228 return WSAVERNOTSUPPORTED;
1230 if (!lpWSAData) return WSAEINVAL;
1232 num_startup++;
1234 /* that's the whole of the negotiation for now */
1235 lpWSAData->wVersion = wVersionRequested;
1236 /* return winsock information */
1237 lpWSAData->wHighVersion = 0x0202;
1238 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
1239 strcpy(lpWSAData->szSystemStatus, "Running" );
1240 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
1241 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
1242 /* don't do anything with lpWSAData->lpVendorInfo */
1243 /* (some apps don't allocate the space for this field) */
1245 TRACE("succeeded starts: %d\n", num_startup);
1246 return 0;
1250 /***********************************************************************
1251 * WSACleanup (WS2_32.116)
1253 INT WINAPI WSACleanup(void)
1255 if (num_startup) {
1256 num_startup--;
1257 TRACE("pending cleanups: %d\n", num_startup);
1258 return 0;
1260 SetLastError(WSANOTINITIALISED);
1261 return SOCKET_ERROR;
1265 /***********************************************************************
1266 * WSAGetLastError (WS2_32.111)
1268 INT WINAPI WSAGetLastError(void)
1270 return GetLastError();
1273 /***********************************************************************
1274 * WSASetLastError (WS2_32.112)
1276 void WINAPI WSASetLastError(INT iError) {
1277 SetLastError(iError);
1280 static struct WS_hostent *check_buffer_he(int size)
1282 struct per_thread_data * ptb = get_per_thread_data();
1283 if (ptb->he_buffer)
1285 if (ptb->he_len >= size ) return ptb->he_buffer;
1286 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1288 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
1289 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
1290 return ptb->he_buffer;
1293 static struct WS_servent *check_buffer_se(int size)
1295 struct per_thread_data * ptb = get_per_thread_data();
1296 if (ptb->se_buffer)
1298 if (ptb->se_len >= size ) return ptb->se_buffer;
1299 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1301 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
1302 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
1303 return ptb->se_buffer;
1306 static struct WS_protoent *check_buffer_pe(int size)
1308 struct per_thread_data * ptb = get_per_thread_data();
1309 if (ptb->pe_buffer)
1311 if (ptb->pe_len >= size ) return ptb->pe_buffer;
1312 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1314 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
1315 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
1316 return ptb->pe_buffer;
1319 /* ----------------------------------- i/o APIs */
1321 static inline BOOL supported_pf(int pf)
1323 switch (pf)
1325 case WS_AF_INET:
1326 case WS_AF_INET6:
1327 return TRUE;
1328 #ifdef HAS_IPX
1329 case WS_AF_IPX:
1330 return TRUE;
1331 #endif
1332 #ifdef HAS_IRDA
1333 case WS_AF_IRDA:
1334 return TRUE;
1335 #endif
1336 default:
1337 return FALSE;
1341 static inline BOOL supported_protocol(int protocol)
1343 int i;
1344 for (i = 0; i < sizeof(valid_protocols) / sizeof(valid_protocols[0]); i++)
1345 if (protocol == valid_protocols[i])
1346 return TRUE;
1347 return FALSE;
1350 /**********************************************************************/
1352 /* Returns the length of the converted address if successful, 0 if it was too small to
1353 * start with.
1355 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
1356 union generic_unix_sockaddr *uaddr)
1358 unsigned int uaddrlen = 0;
1360 switch (wsaddr->sa_family)
1362 #ifdef HAS_IPX
1363 case WS_AF_IPX:
1365 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
1366 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
1368 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
1369 return 0;
1371 uaddrlen = sizeof(struct sockaddr_ipx);
1372 memset( uaddr, 0, uaddrlen );
1373 uipx->sipx_family=AF_IPX;
1374 uipx->sipx_port=wsipx->sa_socket;
1375 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1376 * in one go
1378 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
1379 #ifdef IPX_FRAME_NONE
1380 uipx->sipx_type=IPX_FRAME_NONE;
1381 #endif
1382 break;
1384 #endif
1385 case WS_AF_INET6: {
1386 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
1387 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
1389 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1390 * scope_id, one without.
1392 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
1393 uaddrlen = sizeof(struct sockaddr_in6);
1394 memset( uaddr, 0, uaddrlen );
1395 uin6->sin6_family = AF_INET6;
1396 uin6->sin6_port = win6->sin6_port;
1397 uin6->sin6_flowinfo = win6->sin6_flowinfo;
1398 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1399 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
1400 #endif
1401 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
1402 break;
1404 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
1405 return 0;
1407 case WS_AF_INET: {
1408 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
1409 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
1411 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
1412 return 0;
1413 uaddrlen = sizeof(struct sockaddr_in);
1414 memset( uaddr, 0, uaddrlen );
1415 uin->sin_family = AF_INET;
1416 uin->sin_port = win->sin_port;
1417 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
1418 break;
1420 #ifdef HAS_IRDA
1421 case WS_AF_IRDA: {
1422 struct sockaddr_irda *uin = (struct sockaddr_irda *)uaddr;
1423 const SOCKADDR_IRDA *win = (const SOCKADDR_IRDA *)wsaddr;
1425 if (wsaddrlen < sizeof(SOCKADDR_IRDA))
1426 return 0;
1427 uaddrlen = sizeof(struct sockaddr_irda);
1428 memset( uaddr, 0, uaddrlen );
1429 uin->sir_family = AF_IRDA;
1430 if (!strncmp( win->irdaServiceName, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1432 unsigned int lsap_sel = 0;
1434 sscanf( win->irdaServiceName, "LSAP-SEL%u", &lsap_sel );
1435 uin->sir_lsap_sel = lsap_sel;
1437 else
1439 uin->sir_lsap_sel = LSAP_ANY;
1440 memcpy( uin->sir_name, win->irdaServiceName, 25 );
1442 memcpy( &uin->sir_addr, win->irdaDeviceID, sizeof(uin->sir_addr) );
1443 break;
1445 #endif
1446 case WS_AF_UNSPEC: {
1447 /* Try to determine the needed space by the passed windows sockaddr space */
1448 switch (wsaddrlen) {
1449 default: /* likely an ipv4 address */
1450 case sizeof(struct WS_sockaddr_in):
1451 uaddrlen = sizeof(struct sockaddr_in);
1452 break;
1453 #ifdef HAS_IPX
1454 case sizeof(struct WS_sockaddr_ipx):
1455 uaddrlen = sizeof(struct sockaddr_ipx);
1456 break;
1457 #endif
1458 #ifdef HAS_IRDA
1459 case sizeof(SOCKADDR_IRDA):
1460 uaddrlen = sizeof(struct sockaddr_irda);
1461 break;
1462 #endif
1463 case sizeof(struct WS_sockaddr_in6):
1464 case sizeof(struct WS_sockaddr_in6_old):
1465 uaddrlen = sizeof(struct sockaddr_in6);
1466 break;
1468 memset( uaddr, 0, uaddrlen );
1469 break;
1471 default:
1472 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
1473 return 0;
1475 return uaddrlen;
1478 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
1480 switch (uaddr->sa_family)
1482 #ifdef HAS_IPX
1483 case AF_IPX:
1485 static const struct sockaddr_ipx emptyAddr;
1486 struct sockaddr_ipx *ipx = (struct sockaddr_ipx*) uaddr;
1487 return ipx->sipx_port
1488 || memcmp(&ipx->sipx_network, &emptyAddr.sipx_network, sizeof(emptyAddr.sipx_network))
1489 || memcmp(&ipx->sipx_node, &emptyAddr.sipx_node, sizeof(emptyAddr.sipx_node));
1491 #endif
1492 case AF_INET6:
1494 static const struct sockaddr_in6 emptyAddr;
1495 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
1496 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
1498 case AF_INET:
1500 static const struct sockaddr_in emptyAddr;
1501 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
1502 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
1504 case AF_UNSPEC:
1505 return FALSE;
1506 default:
1507 FIXME("unknown address family %d\n", uaddr->sa_family);
1508 return TRUE;
1512 /* Returns 0 if successful, -1 if the buffer is too small */
1513 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
1515 int res;
1517 switch(uaddr->sa_family)
1519 #ifdef HAS_IPX
1520 case AF_IPX:
1522 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
1523 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
1525 res=-1;
1526 switch (*wsaddrlen) /* how much can we copy? */
1528 default:
1529 res=0; /* enough */
1530 *wsaddrlen = sizeof(*wsipx);
1531 wsipx->sa_socket=uipx->sipx_port;
1532 /* fall through */
1533 case 13:
1534 case 12:
1535 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
1536 /* fall through */
1537 case 11:
1538 case 10:
1539 case 9:
1540 case 8:
1541 case 7:
1542 case 6:
1543 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1544 /* fall through */
1545 case 5:
1546 case 4:
1547 case 3:
1548 case 2:
1549 wsipx->sa_family=WS_AF_IPX;
1550 /* fall through */
1551 case 1:
1552 case 0:
1553 /* way too small */
1554 break;
1557 break;
1558 #endif
1559 #ifdef HAS_IRDA
1560 case AF_IRDA: {
1561 const struct sockaddr_irda *uin = (const struct sockaddr_irda *)uaddr;
1562 SOCKADDR_IRDA *win = (SOCKADDR_IRDA *)wsaddr;
1564 if (*wsaddrlen < sizeof(SOCKADDR_IRDA))
1565 return -1;
1566 win->irdaAddressFamily = WS_AF_IRDA;
1567 memcpy( win->irdaDeviceID, &uin->sir_addr, sizeof(win->irdaDeviceID) );
1568 if (uin->sir_lsap_sel != LSAP_ANY)
1569 sprintf( win->irdaServiceName, "LSAP-SEL%u", uin->sir_lsap_sel );
1570 else
1571 memcpy( win->irdaServiceName, uin->sir_name,
1572 sizeof(win->irdaServiceName) );
1573 return 0;
1575 #endif
1576 case AF_INET6: {
1577 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1578 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1580 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1581 return -1;
1582 win6old->sin6_family = WS_AF_INET6;
1583 win6old->sin6_port = uin6->sin6_port;
1584 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1585 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1586 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1587 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1588 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1589 win6->sin6_scope_id = uin6->sin6_scope_id;
1590 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1592 else
1593 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1594 #else
1595 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1596 #endif
1597 return 0;
1599 case AF_INET: {
1600 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1601 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1603 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1604 return -1;
1605 win->sin_family = WS_AF_INET;
1606 win->sin_port = uin->sin_port;
1607 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1608 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1609 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1610 return 0;
1612 case AF_UNSPEC: {
1613 memset(wsaddr,0,*wsaddrlen);
1614 return 0;
1616 default:
1617 FIXME("Unknown address family %d\n", uaddr->sa_family);
1618 return -1;
1620 return res;
1623 static INT WS_DuplicateSocket(BOOL unicode, SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo)
1625 HANDLE hProcess;
1626 int size;
1627 WSAPROTOCOL_INFOW infow;
1629 TRACE("(unicode %d, socket %04lx, processid %x, buffer %p)\n",
1630 unicode, s, dwProcessId, lpProtocolInfo);
1632 if (!ws_protocol_info(s, unicode, &infow, &size))
1633 return SOCKET_ERROR;
1635 if (!(hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId)))
1637 SetLastError(WSAEINVAL);
1638 return SOCKET_ERROR;
1641 if (!lpProtocolInfo)
1643 CloseHandle(hProcess);
1644 SetLastError(WSAEFAULT);
1645 return SOCKET_ERROR;
1648 /* I don't know what the real Windoze does next, this is a hack */
1649 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
1650 * the target use the global duplicate, or we could copy a reference to us to the structure
1651 * and let the target duplicate it from us, but let's do it as simple as possible */
1652 memcpy(lpProtocolInfo, &infow, size);
1653 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
1654 hProcess, (LPHANDLE)&lpProtocolInfo->dwServiceFlags3,
1655 0, FALSE, DUPLICATE_SAME_ACCESS);
1656 CloseHandle(hProcess);
1657 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
1658 return 0;
1661 /*****************************************************************************
1662 * WS_EnterSingleProtocolW [internal]
1664 * enters the protocol information of one given protocol into the given
1665 * buffer.
1667 * RETURNS
1668 * TRUE if a protocol was entered into the buffer.
1670 * BUGS
1671 * - only implemented for IPX, SPX, SPXII, TCP, UDP
1672 * - there is no check that the operating system supports the returned
1673 * protocols
1675 static BOOL WS_EnterSingleProtocolW( INT protocol, WSAPROTOCOL_INFOW* info )
1677 memset( info, 0, sizeof(WSAPROTOCOL_INFOW) );
1678 info->iProtocol = protocol;
1680 switch (protocol)
1682 case WS_IPPROTO_TCP:
1683 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_EXPEDITED_DATA |
1684 XP1_GRACEFUL_CLOSE | XP1_GUARANTEED_ORDER |
1685 XP1_GUARANTEED_DELIVERY;
1686 info->ProviderId = ProviderIdIP;
1687 info->dwCatalogEntryId = 0x3e9;
1688 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1689 info->ProtocolChain.ChainLen = 1;
1690 info->iVersion = 2;
1691 info->iAddressFamily = WS_AF_INET;
1692 info->iMaxSockAddr = 0x10;
1693 info->iMinSockAddr = 0x10;
1694 info->iSocketType = WS_SOCK_STREAM;
1695 strcpyW( info->szProtocol, NameTcpW );
1696 break;
1698 case WS_IPPROTO_UDP:
1699 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_SUPPORT_BROADCAST |
1700 XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED |
1701 XP1_CONNECTIONLESS;
1702 info->ProviderId = ProviderIdIP;
1703 info->dwCatalogEntryId = 0x3ea;
1704 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1705 info->ProtocolChain.ChainLen = 1;
1706 info->iVersion = 2;
1707 info->iAddressFamily = WS_AF_INET;
1708 info->iMaxSockAddr = 0x10;
1709 info->iMinSockAddr = 0x10;
1710 info->iSocketType = WS_SOCK_DGRAM;
1711 info->dwMessageSize = 0xffbb;
1712 strcpyW( info->szProtocol, NameUdpW );
1713 break;
1715 case WS_NSPROTO_IPX:
1716 info->dwServiceFlags1 = XP1_PARTIAL_MESSAGE | XP1_SUPPORT_BROADCAST |
1717 XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED |
1718 XP1_CONNECTIONLESS;
1719 info->ProviderId = ProviderIdIPX;
1720 info->dwCatalogEntryId = 0x406;
1721 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1722 info->ProtocolChain.ChainLen = 1;
1723 info->iVersion = 2;
1724 info->iAddressFamily = WS_AF_IPX;
1725 info->iMaxSockAddr = 0x10;
1726 info->iMinSockAddr = 0x0e;
1727 info->iSocketType = WS_SOCK_DGRAM;
1728 info->iProtocolMaxOffset = 0xff;
1729 info->dwMessageSize = 0x240;
1730 strcpyW( info->szProtocol, NameIpxW );
1731 break;
1733 case WS_NSPROTO_SPX:
1734 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_PSEUDO_STREAM |
1735 XP1_MESSAGE_ORIENTED | XP1_GUARANTEED_ORDER |
1736 XP1_GUARANTEED_DELIVERY;
1737 info->ProviderId = ProviderIdSPX;
1738 info->dwCatalogEntryId = 0x407;
1739 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1740 info->ProtocolChain.ChainLen = 1;
1741 info->iVersion = 2;
1742 info->iAddressFamily = WS_AF_IPX;
1743 info->iMaxSockAddr = 0x10;
1744 info->iMinSockAddr = 0x0e;
1745 info->iSocketType = WS_SOCK_SEQPACKET;
1746 info->dwMessageSize = 0xffffffff;
1747 strcpyW( info->szProtocol, NameSpxW );
1748 break;
1750 case WS_NSPROTO_SPXII:
1751 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_GRACEFUL_CLOSE |
1752 XP1_PSEUDO_STREAM | XP1_MESSAGE_ORIENTED |
1753 XP1_GUARANTEED_ORDER | XP1_GUARANTEED_DELIVERY;
1754 info->ProviderId = ProviderIdSPX;
1755 info->dwCatalogEntryId = 0x409;
1756 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1757 info->ProtocolChain.ChainLen = 1;
1758 info->iVersion = 2;
1759 info->iAddressFamily = WS_AF_IPX;
1760 info->iMaxSockAddr = 0x10;
1761 info->iMinSockAddr = 0x0e;
1762 info->iSocketType = WS_SOCK_SEQPACKET;
1763 info->dwMessageSize = 0xffffffff;
1764 strcpyW( info->szProtocol, NameSpxIIW );
1765 break;
1767 default:
1768 FIXME("unknown Protocol <0x%08x>\n", protocol);
1769 return FALSE;
1771 return TRUE;
1774 /*****************************************************************************
1775 * WS_EnterSingleProtocolA [internal]
1777 * see function WS_EnterSingleProtocolW
1780 static BOOL WS_EnterSingleProtocolA( INT protocol, WSAPROTOCOL_INFOA* info )
1782 WSAPROTOCOL_INFOW infow;
1783 INT ret;
1784 memset( info, 0, sizeof(WSAPROTOCOL_INFOA) );
1786 ret = WS_EnterSingleProtocolW( protocol, &infow );
1787 if (ret)
1789 /* convert the structure from W to A */
1790 memcpy( info, &infow, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
1791 WideCharToMultiByte( CP_ACP, 0, infow.szProtocol, -1,
1792 info->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL );
1795 return ret;
1798 static INT WS_EnumProtocols( BOOL unicode, const INT *protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
1800 INT i = 0, items = 0;
1801 DWORD size = 0;
1802 union _info
1804 LPWSAPROTOCOL_INFOA a;
1805 LPWSAPROTOCOL_INFOW w;
1806 } info;
1807 info.w = buffer;
1809 if (!protocols) protocols = valid_protocols;
1811 while (protocols[i])
1813 if(supported_protocol(protocols[i++]))
1814 items++;
1817 size = items * (unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA));
1819 TRACE("unicode %d, protocols %p, buffer %p, length %p %d, items %d, required %d\n",
1820 unicode, protocols, buffer, len, len ? *len : 0, items, size);
1822 if (*len < size || !buffer)
1824 *len = size;
1825 WSASetLastError(WSAENOBUFS);
1826 return SOCKET_ERROR;
1829 for (i = items = 0; protocols[i]; i++)
1831 if (!supported_protocol(protocols[i])) continue;
1832 if (unicode)
1834 if (WS_EnterSingleProtocolW( protocols[i], &info.w[items] ))
1835 items++;
1837 else
1839 if (WS_EnterSingleProtocolA( protocols[i], &info.a[items] ))
1840 items++;
1843 return items;
1846 static BOOL ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size)
1848 NTSTATUS status;
1850 *size = unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA);
1851 memset(buffer, 0, *size);
1853 SERVER_START_REQ( get_socket_info )
1855 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1856 status = wine_server_call( req );
1857 if (!status)
1859 buffer->iAddressFamily = convert_af_u2w(reply->family);
1860 buffer->iSocketType = convert_socktype_u2w(reply->type);
1861 buffer->iProtocol = convert_proto_u2w(reply->protocol);
1864 SERVER_END_REQ;
1866 if (status)
1868 unsigned int err = NtStatusToWSAError( status );
1869 SetLastError( err == WSAEBADF ? WSAENOTSOCK : err );
1870 return FALSE;
1873 if (unicode)
1874 WS_EnterSingleProtocolW( buffer->iProtocol, buffer);
1875 else
1876 WS_EnterSingleProtocolA( buffer->iProtocol, (WSAPROTOCOL_INFOA *)buffer);
1878 return TRUE;
1881 /**************************************************************************
1882 * Functions for handling overlapped I/O
1883 **************************************************************************/
1885 /* user APC called upon async completion */
1886 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1888 ws2_async *wsa = arg;
1890 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
1891 iosb->Information, wsa->user_overlapped,
1892 wsa->flags );
1893 HeapFree( GetProcessHeap(), 0, wsa );
1896 /***********************************************************************
1897 * WS2_recv (INTERNAL)
1899 * Workhorse for both synchronous and asynchronous recv() operations.
1901 static int WS2_recv( int fd, struct ws2_async *wsa )
1903 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1904 char pktbuf[512];
1905 #endif
1906 struct msghdr hdr;
1907 union generic_unix_sockaddr unix_sockaddr;
1908 int n;
1910 hdr.msg_name = NULL;
1912 if (wsa->addr)
1914 hdr.msg_namelen = sizeof(unix_sockaddr);
1915 hdr.msg_name = &unix_sockaddr;
1917 else
1918 hdr.msg_namelen = 0;
1920 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1921 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1922 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1923 hdr.msg_accrights = NULL;
1924 hdr.msg_accrightslen = 0;
1925 #else
1926 hdr.msg_control = pktbuf;
1927 hdr.msg_controllen = sizeof(pktbuf);
1928 hdr.msg_flags = 0;
1929 #endif
1931 while ((n = recvmsg(fd, &hdr, wsa->flags)) == -1)
1933 if (errno != EINTR)
1934 return -1;
1937 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1938 if (wsa->control)
1940 ERR("Message control headers cannot be properly supported on this system.\n");
1941 wsa->control->len = 0;
1943 #else
1944 if (wsa->control && !convert_control_headers(&hdr, wsa->control))
1946 WARN("Application passed insufficient room for control headers.\n");
1947 *wsa->lpFlags |= WS_MSG_CTRUNC;
1948 errno = EMSGSIZE;
1949 return -1;
1951 #endif
1953 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
1954 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
1956 * quoting linux 2.6 net/ipv4/tcp.c:
1957 * "According to UNIX98, msg_name/msg_namelen are ignored
1958 * on connected socket. I was just happy when found this 8) --ANK"
1960 * likewise MSDN says that lpFrom and lpFromlen are ignored for
1961 * connection-oriented sockets, so don't try to update lpFrom.
1963 if (wsa->addr && hdr.msg_namelen)
1964 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
1966 return n;
1969 /***********************************************************************
1970 * WS2_async_recv (INTERNAL)
1972 * Handler for overlapped recv() operations.
1974 static NTSTATUS WS2_async_recv( void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1976 ws2_async* wsa = user;
1977 int result = 0, fd;
1979 switch (status)
1981 case STATUS_ALERTED:
1982 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
1983 break;
1985 result = WS2_recv( fd, wsa );
1986 wine_server_release_fd( wsa->hSocket, fd );
1987 if (result >= 0)
1989 status = STATUS_SUCCESS;
1990 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1992 else
1994 if (errno == EAGAIN)
1996 status = STATUS_PENDING;
1997 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1999 else
2001 result = 0;
2002 status = wsaErrStatus();
2005 break;
2007 if (status != STATUS_PENDING)
2009 iosb->u.Status = status;
2010 iosb->Information = result;
2011 *apc = ws2_async_apc;
2013 return status;
2016 /* user APC called upon async accept completion */
2017 static void WINAPI ws2_async_accept_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
2019 struct ws2_accept_async *wsa = arg;
2021 HeapFree( GetProcessHeap(), 0, wsa->read );
2022 HeapFree( GetProcessHeap(), 0, wsa );
2025 /***********************************************************************
2026 * WS2_async_accept_recv (INTERNAL)
2028 * This function is used to finish the read part of an accept request. It is
2029 * needed to place the completion on the correct socket (listener).
2031 static NTSTATUS WS2_async_accept_recv( void *arg, IO_STATUS_BLOCK *iosb, NTSTATUS status, void **apc )
2033 void *junk;
2034 struct ws2_accept_async *wsa = arg;
2036 status = WS2_async_recv( wsa->read, iosb, status, &junk );
2037 if (status == STATUS_PENDING)
2038 return status;
2040 if (wsa->user_overlapped->hEvent)
2041 SetEvent(wsa->user_overlapped->hEvent);
2042 if (wsa->cvalue)
2043 WS_AddCompletion( HANDLE2SOCKET(wsa->listen_socket), wsa->cvalue, iosb->u.Status, iosb->Information );
2045 *apc = ws2_async_accept_apc;
2046 return status;
2049 /***********************************************************************
2050 * WS2_async_accept (INTERNAL)
2052 * This is the function called to satisfy the AcceptEx callback
2054 static NTSTATUS WS2_async_accept( void *arg, IO_STATUS_BLOCK *iosb, NTSTATUS status, void **apc )
2056 struct ws2_accept_async *wsa = arg;
2057 int len;
2058 char *addr;
2060 TRACE("status: 0x%x listen: %p, accept: %p\n", status, wsa->listen_socket, wsa->accept_socket);
2062 if (status == STATUS_ALERTED)
2064 SERVER_START_REQ( accept_into_socket )
2066 req->lhandle = wine_server_obj_handle( wsa->listen_socket );
2067 req->ahandle = wine_server_obj_handle( wsa->accept_socket );
2068 status = wine_server_call( req );
2070 SERVER_END_REQ;
2072 if (status == STATUS_CANT_WAIT)
2073 return STATUS_PENDING;
2075 if (status == STATUS_INVALID_HANDLE)
2077 FIXME("AcceptEx accepting socket closed but request was not cancelled\n");
2078 status = STATUS_CANCELLED;
2081 else if (status == STATUS_HANDLES_CLOSED)
2082 status = STATUS_CANCELLED; /* strange windows behavior */
2084 if (status != STATUS_SUCCESS)
2085 goto finish;
2087 /* WS2 Spec says size param is extra 16 bytes long...what do we put in it? */
2088 addr = ((char *)wsa->buf) + wsa->data_len;
2089 len = wsa->local_len - sizeof(int);
2090 WS_getsockname(HANDLE2SOCKET(wsa->accept_socket),
2091 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
2092 *(int *)addr = len;
2094 addr += wsa->local_len;
2095 len = wsa->remote_len - sizeof(int);
2096 WS_getpeername(HANDLE2SOCKET(wsa->accept_socket),
2097 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
2098 *(int *)addr = len;
2100 if (!wsa->read)
2101 goto finish;
2103 SERVER_START_REQ( register_async )
2105 req->type = ASYNC_TYPE_READ;
2106 req->async.handle = wine_server_obj_handle( wsa->accept_socket );
2107 req->async.callback = wine_server_client_ptr( WS2_async_accept_recv );
2108 req->async.iosb = wine_server_client_ptr( iosb );
2109 req->async.arg = wine_server_client_ptr( wsa );
2110 status = wine_server_call( req );
2112 SERVER_END_REQ;
2114 if (status != STATUS_PENDING)
2115 goto finish;
2117 /* The APC has finished but no completion should be sent for the operation yet, additional processing
2118 * needs to be performed by WS2_async_accept_recv() first. */
2119 return STATUS_MORE_PROCESSING_REQUIRED;
2121 finish:
2122 iosb->u.Status = status;
2123 iosb->Information = 0;
2125 if (wsa->user_overlapped->hEvent)
2126 SetEvent(wsa->user_overlapped->hEvent);
2128 *apc = ws2_async_accept_apc;
2129 return status;
2132 /***********************************************************************
2133 * WS2_send (INTERNAL)
2135 * Workhorse for both synchronous and asynchronous send() operations.
2137 static int WS2_send( int fd, struct ws2_async *wsa )
2139 struct msghdr hdr;
2140 union generic_unix_sockaddr unix_addr;
2141 int n, ret;
2143 hdr.msg_name = NULL;
2144 hdr.msg_namelen = 0;
2146 if (wsa->addr)
2148 hdr.msg_name = &unix_addr;
2149 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
2150 if ( !hdr.msg_namelen )
2152 errno = EFAULT;
2153 return -1;
2156 #if defined(HAS_IPX) && defined(SOL_IPX)
2157 if(wsa->addr->sa_family == WS_AF_IPX)
2159 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
2160 int val=0;
2161 socklen_t len = sizeof(int);
2163 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
2164 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
2165 * the packet type and then we can retrieve it using getsockopt. After that we can set the
2166 * ipx type in the sockaddr_opx structure with the stored value.
2168 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
2169 uipx->sipx_type = val;
2171 #endif
2174 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
2175 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
2176 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2177 hdr.msg_accrights = NULL;
2178 hdr.msg_accrightslen = 0;
2179 #else
2180 hdr.msg_control = NULL;
2181 hdr.msg_controllen = 0;
2182 hdr.msg_flags = 0;
2183 #endif
2185 while ((ret = sendmsg(fd, &hdr, wsa->flags)) == -1)
2187 if (errno != EINTR)
2188 return -1;
2191 n = ret;
2192 while (wsa->first_iovec < wsa->n_iovecs && wsa->iovec[wsa->first_iovec].iov_len <= n)
2193 n -= wsa->iovec[wsa->first_iovec++].iov_len;
2194 if (wsa->first_iovec < wsa->n_iovecs)
2196 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
2197 wsa->iovec[wsa->first_iovec].iov_len -= n;
2199 return ret;
2202 /***********************************************************************
2203 * WS2_async_send (INTERNAL)
2205 * Handler for overlapped send() operations.
2207 static NTSTATUS WS2_async_send(void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
2209 ws2_async* wsa = user;
2210 int result = 0, fd;
2212 switch (status)
2214 case STATUS_ALERTED:
2215 if ( wsa->n_iovecs <= wsa->first_iovec )
2217 /* Nothing to do */
2218 status = STATUS_SUCCESS;
2219 break;
2221 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
2222 break;
2224 /* check to see if the data is ready (non-blocking) */
2225 result = WS2_send( fd, wsa );
2226 wine_server_release_fd( wsa->hSocket, fd );
2228 if (result >= 0)
2230 if (wsa->first_iovec < wsa->n_iovecs)
2231 status = STATUS_PENDING;
2232 else
2233 status = STATUS_SUCCESS;
2235 iosb->Information += result;
2237 else if (errno == EAGAIN)
2239 status = STATUS_PENDING;
2241 else
2243 status = wsaErrStatus();
2245 break;
2247 if (status != STATUS_PENDING)
2249 iosb->u.Status = status;
2250 *apc = ws2_async_apc;
2252 return status;
2255 /***********************************************************************
2256 * WS2_async_shutdown (INTERNAL)
2258 * Handler for shutdown() operations on overlapped sockets.
2260 static NTSTATUS WS2_async_shutdown( void* user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc )
2262 ws2_async* wsa = user;
2263 int fd, err = 1;
2265 switch (status)
2267 case STATUS_ALERTED:
2268 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
2269 break;
2271 switch ( wsa->type )
2273 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
2274 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
2276 status = err ? wsaErrStatus() : STATUS_SUCCESS;
2277 wine_server_release_fd( wsa->hSocket, fd );
2278 break;
2280 iosb->u.Status = status;
2281 iosb->Information = 0;
2282 *apc = ws2_async_apc;
2283 return status;
2286 /***********************************************************************
2287 * WS2_register_async_shutdown (INTERNAL)
2289 * Helper function for WS_shutdown() on overlapped sockets.
2291 static int WS2_register_async_shutdown( SOCKET s, int type )
2293 struct ws2_async *wsa;
2294 NTSTATUS status;
2296 TRACE("s %04lx type %d\n", s, type);
2298 wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( struct ws2_async, iovec[1] ));
2299 if ( !wsa )
2300 return WSAEFAULT;
2302 wsa->hSocket = SOCKET2HANDLE(s);
2303 wsa->type = type;
2304 wsa->completion_func = NULL;
2306 SERVER_START_REQ( register_async )
2308 req->type = type;
2309 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2310 req->async.callback = wine_server_client_ptr( WS2_async_shutdown );
2311 req->async.iosb = wine_server_client_ptr( &wsa->local_iosb );
2312 req->async.arg = wine_server_client_ptr( wsa );
2313 req->async.cvalue = 0;
2314 status = wine_server_call( req );
2316 SERVER_END_REQ;
2318 if (status != STATUS_PENDING)
2320 HeapFree( GetProcessHeap(), 0, wsa );
2321 return NtStatusToWSAError( status );
2323 return 0;
2326 /***********************************************************************
2327 * accept (WS2_32.1)
2329 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr, int *addrlen32)
2331 NTSTATUS status;
2332 SOCKET as;
2333 BOOL is_blocking;
2335 TRACE("socket %04lx\n", s );
2336 status = _is_blocking(s, &is_blocking);
2337 if (status)
2339 set_error(status);
2340 return INVALID_SOCKET;
2343 do {
2344 /* try accepting first (if there is a deferred connection) */
2345 SERVER_START_REQ( accept_socket )
2347 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
2348 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
2349 req->attributes = OBJ_INHERIT;
2350 status = wine_server_call( req );
2351 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
2353 SERVER_END_REQ;
2354 if (!status)
2356 if (addr && WS_getpeername(as, addr, addrlen32))
2358 WS_closesocket(as);
2359 return SOCKET_ERROR;
2361 return as;
2363 if (is_blocking && status == STATUS_CANT_WAIT)
2365 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2366 /* block here */
2367 do_block(fd, POLLIN, -1);
2368 _sync_sock_state(s); /* let wineserver notice connection */
2369 release_sock_fd( s, fd );
2371 } while (is_blocking && status == STATUS_CANT_WAIT);
2373 set_error(status);
2374 return INVALID_SOCKET;
2377 /***********************************************************************
2378 * AcceptEx
2380 static BOOL WINAPI WS2_AcceptEx(SOCKET listener, SOCKET acceptor, PVOID dest, DWORD dest_len,
2381 DWORD local_addr_len, DWORD rem_addr_len, LPDWORD received,
2382 LPOVERLAPPED overlapped)
2384 DWORD status;
2385 struct ws2_accept_async *wsa;
2386 int fd;
2387 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
2389 TRACE("(%lx, %lx, %p, %d, %d, %d, %p, %p)\n", listener, acceptor, dest, dest_len, local_addr_len,
2390 rem_addr_len, received, overlapped);
2392 if (!dest)
2394 SetLastError(WSAEINVAL);
2395 return FALSE;
2398 if (!overlapped)
2400 SetLastError(WSA_INVALID_PARAMETER);
2401 return FALSE;
2404 if (!rem_addr_len)
2406 SetLastError(WSAEFAULT);
2407 return FALSE;
2410 fd = get_sock_fd( listener, FILE_READ_DATA, NULL );
2411 if (fd == -1)
2413 SetLastError(WSAENOTSOCK);
2414 return FALSE;
2416 release_sock_fd( listener, fd );
2418 fd = get_sock_fd( acceptor, FILE_READ_DATA, NULL );
2419 if (fd == -1)
2421 SetLastError(WSAENOTSOCK);
2422 return FALSE;
2424 release_sock_fd( acceptor, fd );
2426 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
2427 if(!wsa)
2429 SetLastError(WSAEFAULT);
2430 return FALSE;
2433 wsa->listen_socket = SOCKET2HANDLE(listener);
2434 wsa->accept_socket = SOCKET2HANDLE(acceptor);
2435 wsa->user_overlapped = overlapped;
2436 wsa->cvalue = cvalue;
2437 wsa->buf = dest;
2438 wsa->data_len = dest_len;
2439 wsa->local_len = local_addr_len;
2440 wsa->remote_len = rem_addr_len;
2441 wsa->read = NULL;
2443 if (wsa->data_len)
2445 /* set up a read request if we need it */
2446 wsa->read = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[1]) );
2447 if (!wsa->read)
2449 HeapFree( GetProcessHeap(), 0, wsa );
2450 SetLastError(WSAEFAULT);
2451 return FALSE;
2454 wsa->read->hSocket = wsa->accept_socket;
2455 wsa->read->flags = 0;
2456 wsa->read->lpFlags = &wsa->read->flags;
2457 wsa->read->addr = NULL;
2458 wsa->read->addrlen.ptr = NULL;
2459 wsa->read->control = NULL;
2460 wsa->read->n_iovecs = 1;
2461 wsa->read->first_iovec = 0;
2462 wsa->read->iovec[0].iov_base = wsa->buf;
2463 wsa->read->iovec[0].iov_len = wsa->data_len;
2466 SERVER_START_REQ( register_async )
2468 req->type = ASYNC_TYPE_READ;
2469 req->async.handle = wine_server_obj_handle( SOCKET2HANDLE(listener) );
2470 req->async.callback = wine_server_client_ptr( WS2_async_accept );
2471 req->async.iosb = wine_server_client_ptr( overlapped );
2472 req->async.arg = wine_server_client_ptr( wsa );
2473 req->async.cvalue = cvalue;
2474 /* We don't set event since we may also have to read */
2475 status = wine_server_call( req );
2477 SERVER_END_REQ;
2479 if(status != STATUS_PENDING)
2481 HeapFree( GetProcessHeap(), 0, wsa->read );
2482 HeapFree( GetProcessHeap(), 0, wsa );
2485 SetLastError( NtStatusToWSAError(status) );
2486 return FALSE;
2489 /***********************************************************************
2490 * GetAcceptExSockaddrs
2492 static void WINAPI WS2_GetAcceptExSockaddrs(PVOID buffer, DWORD data_size, DWORD local_size, DWORD remote_size,
2493 struct WS_sockaddr **local_addr, LPINT local_addr_len,
2494 struct WS_sockaddr **remote_addr, LPINT remote_addr_len)
2496 char *cbuf = buffer;
2497 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer, data_size, local_size, remote_size, local_addr,
2498 local_addr_len, remote_addr, remote_addr_len );
2499 cbuf += data_size;
2501 *local_addr_len = *(int *) cbuf;
2502 *local_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2504 cbuf += local_size;
2506 *remote_addr_len = *(int *) cbuf;
2507 *remote_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2510 /***********************************************************************
2511 * WSASendMsg
2513 int WINAPI WSASendMsg( SOCKET s, LPWSAMSG msg, DWORD dwFlags, LPDWORD lpNumberOfBytesSent,
2514 LPWSAOVERLAPPED lpOverlapped,
2515 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
2517 if (!msg)
2519 SetLastError( WSAEFAULT );
2520 return SOCKET_ERROR;
2523 return WS2_sendto( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesSent,
2524 dwFlags, msg->name, msg->namelen,
2525 lpOverlapped, lpCompletionRoutine );
2528 /***********************************************************************
2529 * WSARecvMsg
2531 * Perform a receive operation that is capable of returning message
2532 * control headers. It is important to note that the WSAMSG parameter
2533 * must remain valid throughout the operation, even when an overlapped
2534 * receive is performed.
2536 static int WINAPI WS2_WSARecvMsg( SOCKET s, LPWSAMSG msg, LPDWORD lpNumberOfBytesRecvd,
2537 LPWSAOVERLAPPED lpOverlapped,
2538 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2540 if (!msg)
2542 SetLastError( WSAEFAULT );
2543 return SOCKET_ERROR;
2546 return WS2_recv_base( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesRecvd,
2547 &msg->dwFlags, msg->name, &msg->namelen,
2548 lpOverlapped, lpCompletionRoutine, &msg->Control );
2551 /***********************************************************************
2552 * interface_bind (INTERNAL)
2554 * Take bind() calls on any name corresponding to a local network adapter and restrict the given socket to
2555 * operating only on the specified interface. This restriction consists of two components:
2556 * 1) An outgoing packet restriction suggesting the egress interface for all packets.
2557 * 2) An incoming packet restriction dropping packets not meant for the interface.
2558 * If the function succeeds in placing these restrictions (returns TRUE) then the name for the bind() may
2559 * safely be changed to INADDR_ANY, permitting the transmission and receipt of broadcast packets on the
2560 * socket. This behavior is only relevant to UDP sockets and is needed for applications that expect to be able
2561 * to receive broadcast packets on a socket that is bound to a specific network interface.
2563 static BOOL interface_bind( SOCKET s, int fd, struct sockaddr *addr )
2565 struct sockaddr_in *in_sock = (struct sockaddr_in *) addr;
2566 unsigned int sock_type = 0;
2567 socklen_t optlen = sizeof(sock_type);
2568 in_addr_t bind_addr = in_sock->sin_addr.s_addr;
2569 PIP_ADAPTER_INFO adapters = NULL, adapter;
2570 BOOL ret = FALSE;
2571 DWORD adap_size;
2572 int enable = 1;
2574 if (bind_addr == htonl(INADDR_ANY) || bind_addr == htonl(INADDR_LOOPBACK))
2575 return FALSE; /* Not binding to a network adapter, special interface binding unnecessary. */
2576 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &sock_type, &optlen) == -1 || sock_type != SOCK_DGRAM)
2577 return FALSE; /* Special interface binding is only necessary for UDP datagrams. */
2578 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
2579 goto cleanup;
2580 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
2581 if (adapters == NULL || GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
2582 goto cleanup;
2583 /* Search the IPv4 adapter list for the appropriate binding interface */
2584 for (adapter = adapters; adapter != NULL; adapter = adapter->Next)
2586 in_addr_t adapter_addr = (in_addr_t) inet_addr(adapter->IpAddressList.IpAddress.String);
2588 if (bind_addr == adapter_addr)
2590 #if defined(IP_BOUND_IF)
2591 /* IP_BOUND_IF sets both the incoming and outgoing restriction at once */
2592 if (setsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &adapter->Index, sizeof(adapter->Index)) != 0)
2593 goto cleanup;
2594 ret = TRUE;
2595 #elif defined(LINUX_BOUND_IF)
2596 in_addr_t ifindex = (in_addr_t) htonl(adapter->Index);
2597 struct interface_filter specific_interface_filter;
2598 struct sock_fprog filter_prog;
2600 if (setsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex, sizeof(ifindex)) != 0)
2601 goto cleanup; /* Failed to suggest egress interface */
2602 specific_interface_filter = generic_interface_filter;
2603 specific_interface_filter.iface_rule.k = adapter->Index;
2604 specific_interface_filter.ip_rule.k = htonl(adapter_addr);
2605 filter_prog.len = sizeof(generic_interface_filter)/sizeof(struct sock_filter);
2606 filter_prog.filter = (struct sock_filter *) &specific_interface_filter;
2607 if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog, sizeof(filter_prog)) != 0)
2608 goto cleanup; /* Failed to specify incoming packet filter */
2609 ret = TRUE;
2610 #else
2611 FIXME("Broadcast packets on interface-bound sockets are not currently supported on this platform, "
2612 "receiving broadcast packets will not work on socket %04lx.\n", s);
2613 #endif
2614 break;
2617 /* Will soon be switching to INADDR_ANY: permit address reuse */
2618 if (ret && setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) == 0)
2619 TRACE("Socket %04lx bound to interface index %d\n", s, adapter->Index);
2620 else
2621 ret = FALSE;
2623 cleanup:
2624 if(!ret)
2625 ERR("Failed to bind to interface, receiving broadcast packets will not work on socket %04lx.\n", s);
2626 HeapFree(GetProcessHeap(), 0, adapters);
2627 return ret;
2630 /***********************************************************************
2631 * bind (WS2_32.2)
2633 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
2635 int fd = get_sock_fd( s, 0, NULL );
2636 int res = SOCKET_ERROR;
2638 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2640 if (fd != -1)
2642 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
2644 SetLastError(WSAEAFNOSUPPORT);
2646 else
2648 union generic_unix_sockaddr uaddr;
2649 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2650 if (!uaddrlen)
2652 SetLastError(WSAEFAULT);
2654 else
2656 #ifdef IPV6_V6ONLY
2657 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
2658 if (name->sa_family == WS_AF_INET6 &&
2659 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
2661 int enable = 1;
2662 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
2664 release_sock_fd( s, fd );
2665 SetLastError(WSAEAFNOSUPPORT);
2666 return SOCKET_ERROR;
2669 #endif
2670 if (name->sa_family == WS_AF_INET)
2672 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2673 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2675 /* Trying to bind to the default host interface, using
2676 * INADDR_ANY instead*/
2677 WARN("Trying to bind to magic IP address, using "
2678 "INADDR_ANY instead.\n");
2679 in4->sin_addr.s_addr = htonl(INADDR_ANY);
2681 else if (interface_bind(s, fd, &uaddr.addr))
2682 in4->sin_addr.s_addr = htonl(INADDR_ANY);
2684 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
2686 int loc_errno = errno;
2687 WARN("\tfailure - errno = %i\n", errno);
2688 errno = loc_errno;
2689 switch (errno)
2691 case EBADF:
2692 SetLastError(WSAENOTSOCK);
2693 break;
2694 case EADDRNOTAVAIL:
2695 SetLastError(WSAEINVAL);
2696 break;
2697 case EADDRINUSE:
2699 int optval = 0;
2700 socklen_t optlen = sizeof(optval);
2701 /* Windows >= 2003 will return different results depending on
2702 * SO_REUSEADDR, WSAEACCES may be returned representing that
2703 * the socket hijacking protection prevented the bind */
2704 if (!getsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&optval, &optlen) && optval)
2706 SetLastError(WSAEACCES);
2707 break;
2709 /* fall through */
2711 default:
2712 SetLastError(wsaErrno());
2713 break;
2716 else
2718 res=0; /* success */
2722 release_sock_fd( s, fd );
2724 return res;
2727 /***********************************************************************
2728 * closesocket (WS2_32.3)
2730 int WINAPI WS_closesocket(SOCKET s)
2732 TRACE("socket %04lx\n", s);
2733 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
2734 return SOCKET_ERROR;
2737 static int do_connect(int fd, const struct WS_sockaddr* name, int namelen)
2739 union generic_unix_sockaddr uaddr;
2740 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2742 if (!uaddrlen)
2743 return WSAEFAULT;
2745 if (name->sa_family == WS_AF_INET)
2747 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2748 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2750 /* Trying to connect to magic replace-loopback address,
2751 * assuming we really want to connect to localhost */
2752 TRACE("Trying to connect to magic IP address, using "
2753 "INADDR_LOOPBACK instead.\n");
2754 in4->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
2758 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
2759 return 0;
2761 return wsaErrno();
2764 /***********************************************************************
2765 * connect (WS2_32.4)
2767 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
2769 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2771 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2773 if (fd != -1)
2775 NTSTATUS status;
2776 BOOL is_blocking;
2777 int ret = do_connect(fd, name, namelen);
2778 if (ret == 0)
2779 goto connect_success;
2781 if (ret == WSAEINPROGRESS)
2783 /* tell wineserver that a connection is in progress */
2784 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2785 FD_CONNECT,
2786 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2787 status = _is_blocking( s, &is_blocking );
2788 if (status)
2790 release_sock_fd( s, fd );
2791 set_error( status );
2792 return SOCKET_ERROR;
2794 if (is_blocking)
2796 int result;
2797 /* block here */
2798 do_block(fd, POLLIN | POLLOUT, -1);
2799 _sync_sock_state(s); /* let wineserver notice connection */
2800 /* retrieve any error codes from it */
2801 result = _get_sock_error(s, FD_CONNECT_BIT);
2802 if (result)
2803 SetLastError(NtStatusToWSAError(result));
2804 else
2806 goto connect_success;
2809 else
2811 SetLastError(WSAEWOULDBLOCK);
2814 else
2816 SetLastError(ret);
2818 release_sock_fd( s, fd );
2820 return SOCKET_ERROR;
2822 connect_success:
2823 release_sock_fd( s, fd );
2824 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2825 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2826 FD_CONNECT|FD_WINE_LISTENING);
2827 return 0;
2830 /***********************************************************************
2831 * WSAConnect (WS2_32.30)
2833 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
2834 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
2835 LPQOS lpSQOS, LPQOS lpGQOS )
2837 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
2838 FIXME("unsupported parameters!\n");
2839 return WS_connect( s, name, namelen );
2842 /***********************************************************************
2843 * ConnectEx
2845 static BOOL WINAPI WS2_ConnectEx(SOCKET s, const struct WS_sockaddr* name, int namelen,
2846 PVOID sendBuf, DWORD sendBufLen, LPDWORD sent, LPOVERLAPPED ov)
2848 int fd, ret, status;
2849 union generic_unix_sockaddr uaddr;
2850 socklen_t uaddrlen = sizeof(uaddr);
2852 if (!ov)
2854 SetLastError( ERROR_INVALID_PARAMETER );
2855 return FALSE;
2858 fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2859 if (fd == -1)
2861 SetLastError( WSAENOTSOCK );
2862 return FALSE;
2865 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
2866 s, name, debugstr_sockaddr(name), namelen, sendBuf, sendBufLen, ov);
2868 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
2870 SetLastError(wsaErrno());
2871 return FALSE;
2873 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
2875 SetLastError(WSAEINVAL);
2876 return FALSE;
2879 ret = do_connect(fd, name, namelen);
2880 if (ret == 0)
2882 WSABUF wsabuf;
2884 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2885 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2886 FD_CONNECT|FD_WINE_LISTENING);
2888 wsabuf.len = sendBufLen;
2889 wsabuf.buf = (char*) sendBuf;
2891 /* WSASend takes care of completion if need be */
2892 if (WSASend(s, &wsabuf, sendBuf ? 1 : 0, sent, 0, ov, NULL) != SOCKET_ERROR)
2893 goto connection_success;
2895 else if (ret == WSAEINPROGRESS)
2897 struct ws2_async *wsa;
2898 ULONG_PTR cvalue = (((ULONG_PTR)ov->hEvent & 1) == 0) ? (ULONG_PTR)ov : 0;
2900 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2901 FD_CONNECT,
2902 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2904 /* Indirectly call WSASend */
2905 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( struct ws2_async, iovec[1] ))))
2907 SetLastError(WSAEFAULT);
2909 else
2911 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)ov;
2912 iosb->u.Status = STATUS_PENDING;
2913 iosb->Information = 0;
2915 wsa->hSocket = SOCKET2HANDLE(s);
2916 wsa->addr = NULL;
2917 wsa->addrlen.val = 0;
2918 wsa->flags = 0;
2919 wsa->lpFlags = &wsa->flags;
2920 wsa->control = NULL;
2921 wsa->n_iovecs = sendBuf ? 1 : 0;
2922 wsa->first_iovec = 0;
2923 wsa->completion_func = NULL;
2924 wsa->iovec[0].iov_base = sendBuf;
2925 wsa->iovec[0].iov_len = sendBufLen;
2927 SERVER_START_REQ( register_async )
2929 req->type = ASYNC_TYPE_WRITE;
2930 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2931 req->async.callback = wine_server_client_ptr( WS2_async_send );
2932 req->async.iosb = wine_server_client_ptr( iosb );
2933 req->async.arg = wine_server_client_ptr( wsa );
2934 req->async.event = wine_server_obj_handle( ov->hEvent );
2935 req->async.cvalue = cvalue;
2936 status = wine_server_call( req );
2938 SERVER_END_REQ;
2940 if (status != STATUS_PENDING) HeapFree(GetProcessHeap(), 0, wsa);
2942 /* If the connect already failed */
2943 if (status == STATUS_PIPE_DISCONNECTED)
2944 status = _get_sock_error(s, FD_CONNECT_BIT);
2945 SetLastError( NtStatusToWSAError(status) );
2948 else
2950 SetLastError(ret);
2953 release_sock_fd( s, fd );
2954 return FALSE;
2956 connection_success:
2957 release_sock_fd( s, fd );
2958 return TRUE;
2962 /***********************************************************************
2963 * getpeername (WS2_32.5)
2965 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
2967 int fd;
2968 int res;
2970 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
2972 fd = get_sock_fd( s, 0, NULL );
2973 res = SOCKET_ERROR;
2975 if (fd != -1)
2977 union generic_unix_sockaddr uaddr;
2978 socklen_t uaddrlen = sizeof(uaddr);
2980 if (getpeername(fd, &uaddr.addr, &uaddrlen) == 0)
2982 if (!name || !namelen)
2983 SetLastError(WSAEFAULT);
2984 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
2985 /* The buffer was too small */
2986 SetLastError(WSAEFAULT);
2987 else
2988 res = 0;
2990 else
2991 SetLastError(wsaErrno());
2992 release_sock_fd( s, fd );
2994 return res;
2997 /***********************************************************************
2998 * getsockname (WS2_32.6)
3000 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
3002 int fd;
3003 int res;
3005 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
3007 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
3008 if( (name == NULL) || (namelen == NULL) )
3010 SetLastError( WSAEFAULT );
3011 return SOCKET_ERROR;
3014 fd = get_sock_fd( s, 0, NULL );
3015 res = SOCKET_ERROR;
3017 if (fd != -1)
3019 union generic_unix_sockaddr uaddr;
3020 socklen_t uaddrlen = sizeof(uaddr);
3022 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
3024 SetLastError(wsaErrno());
3026 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
3028 SetLastError(WSAEINVAL);
3030 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3032 /* The buffer was too small */
3033 SetLastError(WSAEFAULT);
3035 else
3037 res=0;
3038 TRACE("=> %s\n", debugstr_sockaddr(name));
3040 release_sock_fd( s, fd );
3042 return res;
3045 /***********************************************************************
3046 * getsockopt (WS2_32.7)
3048 INT WINAPI WS_getsockopt(SOCKET s, INT level,
3049 INT optname, char *optval, INT *optlen)
3051 int fd;
3052 INT ret = 0;
3054 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
3055 s, level, optname, optval, optlen ? *optlen : 0);
3057 switch(level)
3059 case WS_SOL_SOCKET:
3061 switch(optname)
3063 /* Handle common cases. The special cases are below, sorted
3064 * alphabetically */
3065 case WS_SO_BROADCAST:
3066 case WS_SO_DEBUG:
3067 case WS_SO_ERROR:
3068 case WS_SO_KEEPALIVE:
3069 case WS_SO_OOBINLINE:
3070 case WS_SO_RCVBUF:
3071 case WS_SO_REUSEADDR:
3072 case WS_SO_SNDBUF:
3073 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3074 return SOCKET_ERROR;
3075 convert_sockopt(&level, &optname);
3076 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3078 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3079 ret = SOCKET_ERROR;
3081 release_sock_fd( s, fd );
3082 return ret;
3083 case WS_SO_ACCEPTCONN:
3084 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3085 return SOCKET_ERROR;
3086 if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, optval, (socklen_t *)optlen) != 0 )
3088 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3089 ret = SOCKET_ERROR;
3091 else
3093 /* BSD returns != 0 while Windows return exact == 1 */
3094 if (*(int *)optval) *(int *)optval = 1;
3096 release_sock_fd( s, fd );
3097 return ret;
3098 case WS_SO_DONTLINGER:
3100 struct linger lingval;
3101 socklen_t len = sizeof(struct linger);
3103 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
3105 SetLastError(WSAEFAULT);
3106 return SOCKET_ERROR;
3108 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3109 return SOCKET_ERROR;
3111 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
3113 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3114 ret = SOCKET_ERROR;
3116 else
3118 *(BOOL *)optval = !lingval.l_onoff;
3119 *optlen = sizeof(BOOL);
3122 release_sock_fd( s, fd );
3123 return ret;
3126 case WS_SO_CONNECT_TIME:
3128 static int pretendtime = 0;
3129 struct WS_sockaddr addr;
3130 int len = sizeof(addr);
3132 if (!optlen || *optlen < sizeof(DWORD) || !optval)
3134 SetLastError(WSAEFAULT);
3135 return SOCKET_ERROR;
3137 if (WS_getpeername(s, &addr, &len) == SOCKET_ERROR)
3138 *(DWORD *)optval = ~0u;
3139 else
3141 if (!pretendtime) FIXME("WS_SO_CONNECT_TIME - faking results\n");
3142 *(DWORD *)optval = pretendtime++;
3144 *optlen = sizeof(DWORD);
3145 return ret;
3147 /* As mentioned in setsockopt, Windows ignores this, so we
3148 * always return true here */
3149 case WS_SO_DONTROUTE:
3150 if (!optlen || *optlen < sizeof(BOOL) || !optval)
3152 SetLastError(WSAEFAULT);
3153 return SOCKET_ERROR;
3155 *(BOOL *)optval = TRUE;
3156 *optlen = sizeof(BOOL);
3157 return 0;
3159 case WS_SO_LINGER:
3161 struct linger lingval;
3162 int so_type;
3163 socklen_t len = sizeof(struct linger), slen = sizeof(int);
3165 /* struct linger and LINGER have different sizes */
3166 if (!optlen || *optlen < sizeof(LINGER) || !optval)
3168 SetLastError(WSAEFAULT);
3169 return SOCKET_ERROR;
3171 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3172 return SOCKET_ERROR;
3174 if ((getsockopt(fd, SOL_SOCKET, SO_TYPE, &so_type, &slen) == 0 && so_type == SOCK_DGRAM))
3176 SetLastError(WSAENOPROTOOPT);
3177 ret = SOCKET_ERROR;
3179 else if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0)
3181 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3182 ret = SOCKET_ERROR;
3184 else
3186 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
3187 ((LINGER *)optval)->l_linger = lingval.l_linger;
3188 *optlen = sizeof(struct linger);
3191 release_sock_fd( s, fd );
3192 return ret;
3195 case WS_SO_MAX_MSG_SIZE:
3196 if (!optlen || *optlen < sizeof(int) || !optval)
3198 SetLastError(WSAEFAULT);
3199 return SOCKET_ERROR;
3201 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
3202 *(int *)optval = 65507;
3203 *optlen = sizeof(int);
3204 return 0;
3206 /* SO_OPENTYPE does not require a valid socket handle. */
3207 case WS_SO_OPENTYPE:
3208 if (!optlen || *optlen < sizeof(int) || !optval)
3210 SetLastError(WSAEFAULT);
3211 return SOCKET_ERROR;
3213 *(int *)optval = get_per_thread_data()->opentype;
3214 *optlen = sizeof(int);
3215 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
3216 return 0;
3217 case WS_SO_PROTOCOL_INFOA:
3218 case WS_SO_PROTOCOL_INFOW:
3220 int size;
3221 WSAPROTOCOL_INFOW infow;
3223 ret = ws_protocol_info(s, optname == WS_SO_PROTOCOL_INFOW, &infow, &size);
3224 if (ret)
3226 if (!optlen || !optval || *optlen < size)
3228 if(optlen) *optlen = size;
3229 ret = 0;
3230 SetLastError(WSAEFAULT);
3232 else
3233 memcpy(optval, &infow, size);
3235 return ret ? 0 : SOCKET_ERROR;
3237 #ifdef SO_RCVTIMEO
3238 case WS_SO_RCVTIMEO:
3239 #endif
3240 #ifdef SO_SNDTIMEO
3241 case WS_SO_SNDTIMEO:
3242 #endif
3243 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
3245 struct timeval tv;
3246 socklen_t len = sizeof(struct timeval);
3248 if (!optlen || *optlen < sizeof(int)|| !optval)
3250 SetLastError(WSAEFAULT);
3251 return SOCKET_ERROR;
3253 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3254 return SOCKET_ERROR;
3256 convert_sockopt(&level, &optname);
3257 if (getsockopt(fd, level, optname, &tv, &len) != 0 )
3259 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3260 ret = SOCKET_ERROR;
3262 else
3264 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
3265 *optlen = sizeof(int);
3268 release_sock_fd( s, fd );
3269 return ret;
3271 #endif
3272 case WS_SO_TYPE:
3274 if (!optlen || *optlen < sizeof(int) || !optval)
3276 SetLastError(WSAEFAULT);
3277 return SOCKET_ERROR;
3279 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3280 return SOCKET_ERROR;
3282 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, optval, (socklen_t *)optlen) != 0 )
3284 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3285 ret = SOCKET_ERROR;
3287 else
3288 (*(int *)optval) = convert_socktype_u2w(*(int *)optval);
3290 release_sock_fd( s, fd );
3291 return ret;
3293 default:
3294 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
3295 SetLastError(WSAENOPROTOOPT);
3296 return SOCKET_ERROR;
3297 } /* end switch(optname) */
3298 }/* end case WS_SOL_SOCKET */
3299 #ifdef HAS_IPX
3300 case WS_NSPROTO_IPX:
3302 struct WS_sockaddr_ipx addr;
3303 IPX_ADDRESS_DATA *data;
3304 int namelen;
3305 switch(optname)
3307 case IPX_PTYPE:
3308 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3309 #ifdef SOL_IPX
3310 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (socklen_t *)optlen) == -1)
3312 ret = SOCKET_ERROR;
3314 #else
3316 struct ipx val;
3317 socklen_t len=sizeof(struct ipx);
3318 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
3319 ret = SOCKET_ERROR;
3320 else
3321 *optval = (int)val.ipx_pt;
3323 #endif
3324 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
3325 release_sock_fd( s, fd );
3326 return ret;
3328 case IPX_ADDRESS:
3330 * On a Win2000 system with one network card there are usually
3331 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
3332 * Using this call you can then retrieve info about this all.
3333 * In case of Linux it is a bit different. Usually you have
3334 * only "one" device active and further it is not possible to
3335 * query things like the linkspeed.
3337 FIXME("IPX_ADDRESS\n");
3338 namelen = sizeof(struct WS_sockaddr_ipx);
3339 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
3340 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
3342 data = (IPX_ADDRESS_DATA*)optval;
3343 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
3344 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
3345 data->adapternum = 0;
3346 data->wan = FALSE; /* We are not on a wan for now .. */
3347 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
3348 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
3349 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
3350 * note 1MB = 1000kB in this case */
3351 return 0;
3353 case IPX_MAX_ADAPTER_NUM:
3354 FIXME("IPX_MAX_ADAPTER_NUM\n");
3355 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
3356 return 0;
3358 default:
3359 FIXME("IPX optname:%x\n", optname);
3360 return SOCKET_ERROR;
3361 }/* end switch(optname) */
3362 } /* end case WS_NSPROTO_IPX */
3363 #endif
3365 #ifdef HAS_IRDA
3366 #define MAX_IRDA_DEVICES 10
3368 case WS_SOL_IRLMP:
3369 switch(optname)
3371 case WS_IRLMP_ENUMDEVICES:
3373 char buf[sizeof(struct irda_device_list) +
3374 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
3375 int res;
3376 socklen_t len = sizeof(buf);
3378 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3379 return SOCKET_ERROR;
3380 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
3381 release_sock_fd( s, fd );
3382 if (res < 0)
3384 SetLastError(wsaErrno());
3385 return SOCKET_ERROR;
3387 else
3389 struct irda_device_list *src = (struct irda_device_list *)buf;
3390 DEVICELIST *dst = (DEVICELIST *)optval;
3391 INT needed = sizeof(DEVICELIST);
3392 unsigned int i;
3394 if (src->len > 0)
3395 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
3396 if (*optlen < needed)
3398 SetLastError(WSAEFAULT);
3399 return SOCKET_ERROR;
3401 *optlen = needed;
3402 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
3403 dst->numDevice = src->len;
3404 for (i = 0; i < src->len; i++)
3406 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
3407 src->dev[i].saddr, src->dev[i].daddr,
3408 src->dev[i].info, src->dev[i].hints[0],
3409 src->dev[i].hints[1]);
3410 memcpy( dst->Device[i].irdaDeviceID,
3411 &src->dev[i].daddr,
3412 sizeof(dst->Device[i].irdaDeviceID) ) ;
3413 memcpy( dst->Device[i].irdaDeviceName,
3414 src->dev[i].info,
3415 sizeof(dst->Device[i].irdaDeviceName) ) ;
3416 memcpy( &dst->Device[i].irdaDeviceHints1,
3417 &src->dev[i].hints[0],
3418 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
3419 memcpy( &dst->Device[i].irdaDeviceHints2,
3420 &src->dev[i].hints[1],
3421 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
3422 dst->Device[i].irdaCharSet = src->dev[i].charset;
3424 return 0;
3427 default:
3428 FIXME("IrDA optname:0x%x\n", optname);
3429 return SOCKET_ERROR;
3431 break; /* case WS_SOL_IRLMP */
3432 #undef MAX_IRDA_DEVICES
3433 #endif
3435 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3436 case WS_IPPROTO_TCP:
3437 switch(optname)
3439 case WS_TCP_NODELAY:
3440 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3441 return SOCKET_ERROR;
3442 convert_sockopt(&level, &optname);
3443 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3445 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3446 ret = SOCKET_ERROR;
3448 release_sock_fd( s, fd );
3449 return ret;
3451 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
3452 return SOCKET_ERROR;
3454 case WS_IPPROTO_IP:
3455 switch(optname)
3457 case WS_IP_ADD_MEMBERSHIP:
3458 case WS_IP_DROP_MEMBERSHIP:
3459 #ifdef IP_HDRINCL
3460 case WS_IP_HDRINCL:
3461 #endif
3462 case WS_IP_MULTICAST_IF:
3463 case WS_IP_MULTICAST_LOOP:
3464 case WS_IP_MULTICAST_TTL:
3465 case WS_IP_OPTIONS:
3466 #ifdef IP_PKTINFO
3467 case WS_IP_PKTINFO:
3468 #endif
3469 case WS_IP_TOS:
3470 case WS_IP_TTL:
3471 #ifdef IP_UNICAST_IF
3472 case WS_IP_UNICAST_IF:
3473 #endif
3474 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3475 return SOCKET_ERROR;
3476 convert_sockopt(&level, &optname);
3477 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3479 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3480 ret = SOCKET_ERROR;
3482 release_sock_fd( s, fd );
3483 return ret;
3484 case WS_IP_DONTFRAGMENT:
3485 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
3486 *(BOOL*)optval = FALSE;
3487 return 0;
3489 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
3490 return SOCKET_ERROR;
3492 case WS_IPPROTO_IPV6:
3493 switch(optname)
3495 #ifdef IPV6_ADD_MEMBERSHIP
3496 case WS_IPV6_ADD_MEMBERSHIP:
3497 #endif
3498 #ifdef IPV6_DROP_MEMBERSHIP
3499 case WS_IPV6_DROP_MEMBERSHIP:
3500 #endif
3501 case WS_IPV6_MULTICAST_IF:
3502 case WS_IPV6_MULTICAST_HOPS:
3503 case WS_IPV6_MULTICAST_LOOP:
3504 case WS_IPV6_UNICAST_HOPS:
3505 case WS_IPV6_V6ONLY:
3506 #ifdef IPV6_UNICAST_IF
3507 case WS_IPV6_UNICAST_IF:
3508 #endif
3509 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3510 return SOCKET_ERROR;
3511 convert_sockopt(&level, &optname);
3512 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3514 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3515 ret = SOCKET_ERROR;
3517 release_sock_fd( s, fd );
3518 return ret;
3519 case WS_IPV6_DONTFRAG:
3520 FIXME("WS_IPV6_DONTFRAG is always false!\n");
3521 *(BOOL*)optval = FALSE;
3522 return 0;
3524 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
3525 return SOCKET_ERROR;
3527 default:
3528 WARN("Unknown level: 0x%08x\n", level);
3529 SetLastError(WSAEINVAL);
3530 return SOCKET_ERROR;
3531 } /* end switch(level) */
3534 /***********************************************************************
3535 * htonl (WS2_32.8)
3537 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
3539 return htonl(hostlong);
3543 /***********************************************************************
3544 * htons (WS2_32.9)
3546 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
3548 return htons(hostshort);
3551 /***********************************************************************
3552 * WSAHtonl (WS2_32.46)
3553 * From MSDN description of error codes, this function should also
3554 * check if WinSock has been initialized and the socket is a valid
3555 * socket. But why? This function only translates a host byte order
3556 * u_long into a network byte order u_long...
3558 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
3560 if (lpnetlong)
3562 *lpnetlong = htonl(hostlong);
3563 return 0;
3565 WSASetLastError(WSAEFAULT);
3566 return SOCKET_ERROR;
3569 /***********************************************************************
3570 * WSAHtons (WS2_32.47)
3571 * From MSDN description of error codes, this function should also
3572 * check if WinSock has been initialized and the socket is a valid
3573 * socket. But why? This function only translates a host byte order
3574 * u_short into a network byte order u_short...
3576 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
3579 if (lpnetshort)
3581 *lpnetshort = htons(hostshort);
3582 return 0;
3584 WSASetLastError(WSAEFAULT);
3585 return SOCKET_ERROR;
3589 /***********************************************************************
3590 * inet_addr (WS2_32.11)
3592 WS_u_long WINAPI WS_inet_addr(const char *cp)
3594 if (!cp) return INADDR_NONE;
3595 return inet_addr(cp);
3599 /***********************************************************************
3600 * ntohl (WS2_32.14)
3602 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
3604 return ntohl(netlong);
3608 /***********************************************************************
3609 * ntohs (WS2_32.15)
3611 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
3613 return ntohs(netshort);
3617 /***********************************************************************
3618 * inet_ntoa (WS2_32.12)
3620 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
3622 char* s = inet_ntoa(*((struct in_addr*)&in));
3623 if( s )
3625 struct per_thread_data *data = get_per_thread_data();
3626 strcpy(data->ntoa_buffer, s);
3627 return data->ntoa_buffer;
3629 SetLastError(wsaErrno());
3630 return NULL;
3633 static const char *debugstr_wsaioctl(DWORD ioctl)
3635 const char *buf_type, *family;
3637 switch(ioctl & 0x18000000)
3639 case WS_IOC_WS2:
3640 family = "IOC_WS2";
3641 break;
3642 case WS_IOC_PROTOCOL:
3643 family = "IOC_PROTOCOL";
3644 break;
3645 case WS_IOC_VENDOR:
3646 family = "IOC_VENDOR";
3647 break;
3648 default: /* WS_IOC_UNIX */
3650 BYTE size = (ioctl >> 16) & WS_IOCPARM_MASK;
3651 char x = (ioctl & 0xff00) >> 8;
3652 BYTE y = ioctl & 0xff;
3653 char args[14];
3655 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3657 case WS_IOC_VOID:
3658 buf_type = "_IO";
3659 sprintf(args, "%d, %d", x, y);
3660 break;
3661 case WS_IOC_IN:
3662 buf_type = "_IOW";
3663 sprintf(args, "'%c', %d, %d", x, y, size);
3664 break;
3665 case WS_IOC_OUT:
3666 buf_type = "_IOR";
3667 sprintf(args, "'%c', %d, %d", x, y, size);
3668 break;
3669 default:
3670 buf_type = "?";
3671 sprintf(args, "'%c', %d, %d", x, y, size);
3672 break;
3674 return wine_dbg_sprintf("%s(%s)", buf_type, args);
3678 /* We are different from WS_IOC_UNIX. */
3679 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3681 case WS_IOC_VOID:
3682 buf_type = "_WSAIO";
3683 break;
3684 case WS_IOC_INOUT:
3685 buf_type = "_WSAIORW";
3686 break;
3687 case WS_IOC_IN:
3688 buf_type = "_WSAIOW";
3689 break;
3690 case WS_IOC_OUT:
3691 buf_type = "_WSAIOR";
3692 break;
3693 default:
3694 buf_type = "?";
3695 break;
3698 return wine_dbg_sprintf("%s(%s, %d)", buf_type, family,
3699 (USHORT)(ioctl & 0xffff));
3702 /* do an ioctl call through the server */
3703 static DWORD server_ioctl_sock( SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size,
3704 LPVOID out_buff, DWORD out_size, LPDWORD ret_size,
3705 LPWSAOVERLAPPED overlapped,
3706 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
3708 HANDLE event = overlapped ? overlapped->hEvent : 0;
3709 HANDLE handle = SOCKET2HANDLE( s );
3710 struct ws2_async *wsa;
3711 NTSTATUS status;
3712 PIO_STATUS_BLOCK io;
3714 if (!(wsa = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wsa) )))
3715 return WSA_NOT_ENOUGH_MEMORY;
3716 wsa->hSocket = handle;
3717 wsa->user_overlapped = overlapped;
3718 wsa->completion_func = completion;
3719 io = (overlapped ? (PIO_STATUS_BLOCK)overlapped : &wsa->local_iosb);
3721 status = NtDeviceIoControlFile( handle, event, (PIO_APC_ROUTINE)ws2_async_apc, wsa, io, code,
3722 in_buff, in_size, out_buff, out_size );
3723 if (status == STATUS_NOT_SUPPORTED)
3725 FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
3726 code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
3728 else if (status == STATUS_SUCCESS)
3729 *ret_size = io->Information; /* "Information" is the size written to the output buffer */
3731 if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, wsa );
3733 return NtStatusToWSAError( status );
3736 /**********************************************************************
3737 * WSAIoctl (WS2_32.50)
3740 INT WINAPI WSAIoctl(SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size, LPVOID out_buff,
3741 DWORD out_size, LPDWORD ret_size, LPWSAOVERLAPPED overlapped,
3742 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
3744 int fd;
3745 DWORD status = 0, total = 0;
3747 TRACE("%04lx, %s, %p, %d, %p, %d, %p, %p, %p\n",
3748 s, debugstr_wsaioctl(code), in_buff, in_size, out_buff, out_size, ret_size, overlapped, completion);
3750 switch (code)
3752 case WS_FIONBIO:
3753 if (in_size != sizeof(WS_u_long) || IS_INTRESOURCE(in_buff))
3755 WSASetLastError(WSAEFAULT);
3756 return SOCKET_ERROR;
3758 TRACE("-> FIONBIO (%x)\n", *(WS_u_long*)in_buff);
3759 if (_get_sock_mask(s))
3761 /* AsyncSelect()'ed sockets are always nonblocking */
3762 if (!*(WS_u_long *)in_buff) status = WSAEINVAL;
3763 break;
3765 if (*(WS_u_long *)in_buff)
3766 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
3767 else
3768 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
3769 break;
3771 case WS_FIONREAD:
3773 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
3775 WSASetLastError(WSAEFAULT);
3776 return SOCKET_ERROR;
3778 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3779 if (ioctl(fd, FIONREAD, out_buff ) == -1)
3780 status = (errno == EBADF) ? WSAENOTSOCK : wsaErrno();
3781 release_sock_fd( s, fd );
3782 break;
3785 case WS_SIOCATMARK:
3787 unsigned int oob = 0, atmark = 0;
3788 socklen_t oobsize = sizeof(int);
3789 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
3791 WSASetLastError(WSAEFAULT);
3792 return SOCKET_ERROR;
3794 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3795 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
3796 if ((getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &oob, &oobsize ) == -1)
3797 || (!oob && ioctl(fd, SIOCATMARK, &atmark ) == -1))
3798 status = (errno == EBADF) ? WSAENOTSOCK : wsaErrno();
3799 else
3801 /* The SIOCATMARK value read from ioctl() is reversed
3802 * because BSD returns TRUE if it's in the OOB mark
3803 * while Windows returns TRUE if there are NO OOB bytes.
3805 (*(WS_u_long *) out_buff) = oob | !atmark;
3808 release_sock_fd( s, fd );
3809 break;
3812 case WS_FIOASYNC:
3813 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
3814 SetLastError(WSAEINVAL);
3815 return SOCKET_ERROR;
3817 case WS_SIO_GET_INTERFACE_LIST:
3819 INTERFACE_INFO* intArray = out_buff;
3820 DWORD size, numInt = 0, apiReturn;
3822 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
3824 if (!out_buff || !ret_size)
3826 WSASetLastError(WSAEFAULT);
3827 return SOCKET_ERROR;
3830 fd = get_sock_fd( s, 0, NULL );
3831 if (fd == -1) return SOCKET_ERROR;
3833 apiReturn = GetAdaptersInfo(NULL, &size);
3834 if (apiReturn == ERROR_BUFFER_OVERFLOW)
3836 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
3838 if (table)
3840 if (GetAdaptersInfo(table, &size) == NO_ERROR)
3842 PIP_ADAPTER_INFO ptr;
3844 for (ptr = table, numInt = 0; ptr; ptr = ptr->Next)
3846 unsigned int addr, mask, bcast;
3847 struct ifreq ifInfo;
3849 /* Skip interfaces without an IPv4 address. */
3850 if (ptr->IpAddressList.IpAddress.String[0] == '\0')
3851 continue;
3853 if ((numInt + 1)*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > out_size)
3855 WARN("Buffer too small = %u, out_size = %u\n", numInt + 1, out_size);
3856 status = WSAEFAULT;
3857 break;
3860 /* Socket Status Flags */
3861 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
3862 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
3864 ERR("Error obtaining status flags for socket!\n");
3865 status = WSAEINVAL;
3866 break;
3868 else
3870 /* set flags; the values of IFF_* are not the same
3871 under Linux and Windows, therefore must generate
3872 new flags */
3873 intArray->iiFlags = 0;
3874 if (ifInfo.ifr_flags & IFF_BROADCAST)
3875 intArray->iiFlags |= WS_IFF_BROADCAST;
3876 #ifdef IFF_POINTOPOINT
3877 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
3878 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
3879 #endif
3880 if (ifInfo.ifr_flags & IFF_LOOPBACK)
3881 intArray->iiFlags |= WS_IFF_LOOPBACK;
3882 if (ifInfo.ifr_flags & IFF_UP)
3883 intArray->iiFlags |= WS_IFF_UP;
3884 if (ifInfo.ifr_flags & IFF_MULTICAST)
3885 intArray->iiFlags |= WS_IFF_MULTICAST;
3888 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
3889 mask = inet_addr(ptr->IpAddressList.IpMask.String);
3890 bcast = addr | ~mask;
3891 intArray->iiAddress.AddressIn.sin_family = AF_INET;
3892 intArray->iiAddress.AddressIn.sin_port = 0;
3893 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
3894 addr;
3895 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
3896 intArray->iiNetmask.AddressIn.sin_port = 0;
3897 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
3898 mask;
3899 intArray->iiBroadcastAddress.AddressIn.sin_family =
3900 AF_INET;
3901 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
3902 intArray->iiBroadcastAddress.AddressIn.sin_addr.
3903 WS_s_addr = bcast;
3904 intArray++;
3905 numInt++;
3908 else
3910 ERR("Unable to get interface table!\n");
3911 status = WSAEINVAL;
3913 HeapFree(GetProcessHeap(),0,table);
3915 else status = WSAEINVAL;
3917 else if (apiReturn != ERROR_NO_DATA)
3919 ERR("Unable to get interface table!\n");
3920 status = WSAEINVAL;
3922 /* Calculate the size of the array being returned */
3923 total = sizeof(INTERFACE_INFO) * numInt;
3924 release_sock_fd( s, fd );
3925 break;
3928 case WS_SIO_ADDRESS_LIST_QUERY:
3930 DWORD size;
3932 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
3934 if (!ret_size)
3936 WSASetLastError(WSAEFAULT);
3937 return SOCKET_ERROR;
3940 if (out_size && out_size < FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[0]))
3942 *ret_size = 0;
3943 WSASetLastError(WSAEINVAL);
3944 return SOCKET_ERROR;
3947 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
3949 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
3950 SOCKET_ADDRESS_LIST *sa_list;
3951 SOCKADDR_IN *sockaddr;
3952 SOCKET_ADDRESS *sa;
3953 unsigned int i;
3954 DWORD num;
3956 if (!table || GetAdaptersInfo(table, &size))
3958 HeapFree(GetProcessHeap(), 0, table);
3959 status = WSAEINVAL;
3960 break;
3963 for (p = table, num = 0; p; p = p->Next)
3964 if (p->IpAddressList.IpAddress.String[0]) num++;
3966 total = FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[num]) + num * sizeof(*sockaddr);
3967 if (total > out_size || !out_buff)
3969 *ret_size = total;
3970 HeapFree(GetProcessHeap(), 0, table);
3971 status = WSAEFAULT;
3972 break;
3975 sa_list = out_buff;
3976 sa = sa_list->Address;
3977 sockaddr = (SOCKADDR_IN *)&sa[num];
3978 sa_list->iAddressCount = num;
3980 for (p = table, i = 0; p; p = p->Next)
3982 if (!p->IpAddressList.IpAddress.String[0]) continue;
3984 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
3985 sa[i].iSockaddrLength = sizeof(SOCKADDR);
3987 sockaddr[i].sin_family = AF_INET;
3988 sockaddr[i].sin_port = 0;
3989 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
3990 i++;
3993 HeapFree(GetProcessHeap(), 0, table);
3995 else
3997 WARN("unable to get IP address list\n");
3998 status = WSAEINVAL;
4000 break;
4003 case WS_SIO_FLUSH:
4004 FIXME("SIO_FLUSH: stub.\n");
4005 break;
4007 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
4009 static const GUID connectex_guid = WSAID_CONNECTEX;
4010 static const GUID disconnectex_guid = WSAID_DISCONNECTEX;
4011 static const GUID acceptex_guid = WSAID_ACCEPTEX;
4012 static const GUID getaccepexsockaddrs_guid = WSAID_GETACCEPTEXSOCKADDRS;
4013 static const GUID transmitfile_guid = WSAID_TRANSMITFILE;
4014 static const GUID transmitpackets_guid = WSAID_TRANSMITPACKETS;
4015 static const GUID wsarecvmsg_guid = WSAID_WSARECVMSG;
4016 static const GUID wsasendmsg_guid = WSAID_WSASENDMSG;
4018 if ( IsEqualGUID(&connectex_guid, in_buff) )
4020 *(LPFN_CONNECTEX *)out_buff = WS2_ConnectEx;
4021 break;
4023 else if ( IsEqualGUID(&disconnectex_guid, in_buff) )
4025 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented DisconnectEx\n");
4027 else if ( IsEqualGUID(&acceptex_guid, in_buff) )
4029 *(LPFN_ACCEPTEX *)out_buff = WS2_AcceptEx;
4030 break;
4032 else if ( IsEqualGUID(&getaccepexsockaddrs_guid, in_buff) )
4034 *(LPFN_GETACCEPTEXSOCKADDRS *)out_buff = WS2_GetAcceptExSockaddrs;
4035 break;
4037 else if ( IsEqualGUID(&transmitfile_guid, in_buff) )
4039 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitFile\n");
4041 else if ( IsEqualGUID(&transmitpackets_guid, in_buff) )
4043 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitPackets\n");
4045 else if ( IsEqualGUID(&wsarecvmsg_guid, in_buff) )
4047 *(LPFN_WSARECVMSG *)out_buff = WS2_WSARecvMsg;
4048 break;
4050 else if ( IsEqualGUID(&wsasendmsg_guid, in_buff) )
4052 *(LPFN_WSASENDMSG *)out_buff = WSASendMsg;
4053 break;
4055 else
4056 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff));
4058 status = WSAEOPNOTSUPP;
4059 break;
4061 case WS_SIO_KEEPALIVE_VALS:
4063 struct tcp_keepalive *k;
4064 int keepalive, keepidle, keepintvl;
4066 if (!in_buff || in_size < sizeof(struct tcp_keepalive))
4068 WSASetLastError(WSAEFAULT);
4069 return SOCKET_ERROR;
4072 k = in_buff;
4073 keepalive = k->onoff ? 1 : 0;
4074 keepidle = max( 1, (k->keepalivetime + 500) / 1000 );
4075 keepintvl = max( 1, (k->keepaliveinterval + 500) / 1000 );
4077 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
4079 fd = get_sock_fd(s, 0, NULL);
4080 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
4081 status = WSAEINVAL;
4082 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
4083 /* these values need to be set only if SO_KEEPALIVE is enabled */
4084 else if(keepalive)
4086 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
4087 status = WSAEINVAL;
4088 else if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
4089 status = WSAEINVAL;
4091 #else
4092 else
4093 FIXME("ignoring keepalive interval and timeout\n");
4094 #endif
4095 release_sock_fd(s, fd);
4096 break;
4098 case WS_SIO_ROUTING_INTERFACE_QUERY:
4100 struct WS_sockaddr *daddr = (struct WS_sockaddr *)in_buff;
4101 struct WS_sockaddr_in *daddr_in = (struct WS_sockaddr_in *)daddr;
4102 struct WS_sockaddr_in *saddr_in = out_buff;
4103 MIB_IPFORWARDROW row;
4104 PMIB_IPADDRTABLE ipAddrTable = NULL;
4105 DWORD size, i, found_index;
4107 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
4109 if (!in_buff || in_size < sizeof(struct WS_sockaddr) ||
4110 !out_buff || out_size < sizeof(struct WS_sockaddr_in) || !ret_size)
4112 WSASetLastError(WSAEFAULT);
4113 return SOCKET_ERROR;
4115 if (daddr->sa_family != AF_INET)
4117 FIXME("unsupported address family %d\n", daddr->sa_family);
4118 status = WSAEAFNOSUPPORT;
4119 break;
4121 if (GetBestRoute(daddr_in->sin_addr.S_un.S_addr, 0, &row) != NOERROR ||
4122 GetIpAddrTable(NULL, &size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
4124 status = WSAEFAULT;
4125 break;
4127 ipAddrTable = HeapAlloc(GetProcessHeap(), 0, size);
4128 if (GetIpAddrTable(ipAddrTable, &size, FALSE))
4130 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4131 status = WSAEFAULT;
4132 break;
4134 for (i = 0, found_index = ipAddrTable->dwNumEntries;
4135 i < ipAddrTable->dwNumEntries; i++)
4137 if (ipAddrTable->table[i].dwIndex == row.dwForwardIfIndex)
4138 found_index = i;
4140 if (found_index == ipAddrTable->dwNumEntries)
4142 ERR("no matching IP address for interface %d\n",
4143 row.dwForwardIfIndex);
4144 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4145 status = WSAEFAULT;
4146 break;
4148 saddr_in->sin_family = AF_INET;
4149 saddr_in->sin_addr.S_un.S_addr = ipAddrTable->table[found_index].dwAddr;
4150 saddr_in->sin_port = 0;
4151 total = sizeof(struct WS_sockaddr_in);
4152 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4153 break;
4155 case WS_SIO_SET_COMPATIBILITY_MODE:
4156 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
4157 status = WSAEOPNOTSUPP;
4158 break;
4159 case WS_SIO_UDP_CONNRESET:
4160 FIXME("WS_SIO_UDP_CONNRESET stub\n");
4161 break;
4162 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
4163 WSASetLastError(WSAEOPNOTSUPP);
4164 return SOCKET_ERROR;
4165 default:
4166 status = WSAEOPNOTSUPP;
4167 break;
4170 if (status == WSAEOPNOTSUPP)
4172 status = server_ioctl_sock(s, code, in_buff, in_size, out_buff, out_size, &total,
4173 overlapped, completion);
4174 if (status != WSAEOPNOTSUPP)
4176 if (status == 0 || status == WSA_IO_PENDING)
4177 TRACE("-> %s request\n", debugstr_wsaioctl(code));
4178 else
4179 ERR("-> %s request failed with status 0x%x\n", debugstr_wsaioctl(code), status);
4181 /* overlapped and completion operations will be handled by the server */
4182 completion = NULL;
4183 overlapped = NULL;
4185 else
4186 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code));
4189 if (completion)
4191 FIXME( "completion routine %p not supported\n", completion );
4193 else if (overlapped)
4195 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
4196 overlapped->Internal = status;
4197 overlapped->InternalHigh = total;
4198 if (overlapped->hEvent) NtSetEvent( overlapped->hEvent, NULL );
4199 if (cvalue) WS_AddCompletion( HANDLE2SOCKET(s), cvalue, status, total );
4202 if (!status)
4204 if (ret_size) *ret_size = total;
4205 return 0;
4207 SetLastError( status );
4208 return SOCKET_ERROR;
4212 /***********************************************************************
4213 * ioctlsocket (WS2_32.10)
4215 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
4217 DWORD ret_size;
4218 return WSAIoctl( s, cmd, argp, sizeof(WS_u_long), argp, sizeof(WS_u_long), &ret_size, NULL, NULL );
4221 /***********************************************************************
4222 * listen (WS2_32.13)
4224 int WINAPI WS_listen(SOCKET s, int backlog)
4226 int fd = get_sock_fd( s, FILE_READ_DATA, NULL ), ret = SOCKET_ERROR;
4228 TRACE("socket %04lx, backlog %d\n", s, backlog);
4229 if (fd != -1)
4231 union generic_unix_sockaddr uaddr;
4232 socklen_t uaddrlen = sizeof(uaddr);
4234 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
4236 SetLastError(wsaErrno());
4238 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
4240 SetLastError(WSAEINVAL);
4242 else if (listen(fd, backlog) == 0)
4244 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
4245 FD_WINE_LISTENING,
4246 FD_CONNECT|FD_WINE_CONNECTED);
4247 ret = 0;
4249 else
4250 SetLastError(wsaErrno());
4251 release_sock_fd( s, fd );
4253 else
4254 SetLastError(WSAENOTSOCK);
4255 return ret;
4258 /***********************************************************************
4259 * recv (WS2_32.16)
4261 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
4263 DWORD n, dwFlags = flags;
4264 WSABUF wsabuf;
4266 wsabuf.len = len;
4267 wsabuf.buf = buf;
4269 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
4270 return SOCKET_ERROR;
4271 else
4272 return n;
4275 /***********************************************************************
4276 * recvfrom (WS2_32.17)
4278 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
4279 struct WS_sockaddr *from, int *fromlen)
4281 DWORD n, dwFlags = flags;
4282 WSABUF wsabuf;
4284 wsabuf.len = len;
4285 wsabuf.buf = buf;
4287 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL, NULL) == SOCKET_ERROR )
4288 return SOCKET_ERROR;
4289 else
4290 return n;
4293 /* allocate a poll array for the corresponding fd sets */
4294 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
4295 const WS_fd_set *exceptfds, int *count_ptr )
4297 unsigned int i, j = 0, count = 0;
4298 struct pollfd *fds;
4300 if (readfds) count += readfds->fd_count;
4301 if (writefds) count += writefds->fd_count;
4302 if (exceptfds) count += exceptfds->fd_count;
4303 *count_ptr = count;
4304 if (!count)
4306 SetLastError(WSAEINVAL);
4307 return NULL;
4309 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0]))))
4311 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
4312 return NULL;
4314 if (readfds)
4315 for (i = 0; i < readfds->fd_count; i++, j++)
4317 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
4318 if (fds[j].fd == -1) goto failed;
4319 fds[j].events = POLLIN;
4320 fds[j].revents = 0;
4322 if (writefds)
4323 for (i = 0; i < writefds->fd_count; i++, j++)
4325 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
4326 if (fds[j].fd == -1) goto failed;
4327 fds[j].events = POLLOUT;
4328 fds[j].revents = 0;
4330 if (exceptfds)
4331 for (i = 0; i < exceptfds->fd_count; i++, j++)
4333 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
4334 if (fds[j].fd == -1) goto failed;
4335 fds[j].events = POLLHUP;
4336 fds[j].revents = 0;
4338 return fds;
4340 failed:
4341 count = j;
4342 j = 0;
4343 if (readfds)
4344 for (i = 0; i < readfds->fd_count && j < count; i++, j++)
4345 release_sock_fd( readfds->fd_array[i], fds[j].fd );
4346 if (writefds)
4347 for (i = 0; i < writefds->fd_count && j < count; i++, j++)
4348 release_sock_fd( writefds->fd_array[i], fds[j].fd );
4349 if (exceptfds)
4350 for (i = 0; i < exceptfds->fd_count && j < count; i++, j++)
4351 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
4352 HeapFree( GetProcessHeap(), 0, fds );
4353 return NULL;
4356 /* release the file descriptor obtained in fd_sets_to_poll */
4357 /* must be called with the original fd_set arrays, before calling get_poll_results */
4358 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
4359 const WS_fd_set *exceptfds, struct pollfd *fds )
4361 unsigned int i, j = 0;
4363 if (readfds)
4365 for (i = 0; i < readfds->fd_count; i++, j++)
4366 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
4368 if (writefds)
4370 for (i = 0; i < writefds->fd_count; i++, j++)
4371 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
4373 if (exceptfds)
4375 for (i = 0; i < exceptfds->fd_count; i++, j++)
4376 if (fds[j].fd != -1)
4378 /* make sure we have a real error before releasing the fd */
4379 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
4380 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
4385 /* map the poll results back into the Windows fd sets */
4386 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
4387 const struct pollfd *fds )
4389 unsigned int i, j = 0, k, total = 0;
4391 if (readfds)
4393 for (i = k = 0; i < readfds->fd_count; i++, j++)
4394 if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
4395 readfds->fd_count = k;
4396 total += k;
4398 if (writefds)
4400 for (i = k = 0; i < writefds->fd_count; i++, j++)
4401 if ((fds[j].revents & POLLOUT) && !(fds[j].revents & POLLHUP))
4402 writefds->fd_array[k++] = writefds->fd_array[i];
4403 writefds->fd_count = k;
4404 total += k;
4406 if (exceptfds)
4408 for (i = k = 0; i < exceptfds->fd_count; i++, j++)
4409 if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
4410 exceptfds->fd_count = k;
4411 total += k;
4413 return total;
4417 /***********************************************************************
4418 * select (WS2_32.18)
4420 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
4421 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
4422 const struct WS_timeval* ws_timeout)
4424 struct pollfd *pollfds;
4425 struct timeval tv1, tv2;
4426 int torig = 0;
4427 int count, ret, timeout = -1;
4429 TRACE("read %p, write %p, excp %p timeout %p\n",
4430 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
4432 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )))
4433 return SOCKET_ERROR;
4435 if (ws_timeout)
4437 torig = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
4438 timeout = torig;
4439 gettimeofday( &tv1, 0 );
4442 while ((ret = poll( pollfds, count, timeout )) < 0)
4444 if (errno == EINTR)
4446 if (!ws_timeout) continue;
4447 gettimeofday( &tv2, 0 );
4449 tv2.tv_sec -= tv1.tv_sec;
4450 tv2.tv_usec -= tv1.tv_usec;
4451 if (tv2.tv_usec < 0)
4453 tv2.tv_usec += 1000000;
4454 tv2.tv_sec -= 1;
4457 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
4458 if (timeout <= 0) break;
4459 } else break;
4461 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
4463 if (ret == -1) SetLastError(wsaErrno());
4464 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
4465 HeapFree( GetProcessHeap(), 0, pollfds );
4466 return ret;
4469 /* helper to send completion messages for client-only i/o operation case */
4470 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
4471 ULONG Information )
4473 SERVER_START_REQ( add_fd_completion )
4475 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
4476 req->cvalue = CompletionValue;
4477 req->status = CompletionStatus;
4478 req->information = Information;
4479 wine_server_call( req );
4481 SERVER_END_REQ;
4485 /***********************************************************************
4486 * send (WS2_32.19)
4488 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
4490 DWORD n;
4491 WSABUF wsabuf;
4493 wsabuf.len = len;
4494 wsabuf.buf = (char*) buf;
4496 if ( WS2_sendto( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
4497 return SOCKET_ERROR;
4498 else
4499 return n;
4502 /***********************************************************************
4503 * WSASend (WS2_32.72)
4505 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4506 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4507 LPWSAOVERLAPPED lpOverlapped,
4508 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4510 return WS2_sendto( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
4511 NULL, 0, lpOverlapped, lpCompletionRoutine );
4514 /***********************************************************************
4515 * WSASendDisconnect (WS2_32.73)
4517 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
4519 return WS_shutdown( s, SD_SEND );
4523 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4524 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4525 const struct WS_sockaddr *to, int tolen,
4526 LPWSAOVERLAPPED lpOverlapped,
4527 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4529 unsigned int i, options;
4530 int n, fd, err, overlapped;
4531 struct ws2_async *wsa = NULL, localwsa;
4532 int totalLength = 0;
4533 DWORD bytes_sent;
4534 BOOL is_blocking;
4536 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
4537 s, lpBuffers, dwBufferCount, dwFlags,
4538 to, tolen, lpOverlapped, lpCompletionRoutine);
4540 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
4541 TRACE( "fd=%d, options=%x\n", fd, options );
4543 if ( fd == -1 ) return SOCKET_ERROR;
4545 if (!lpOverlapped && !lpNumberOfBytesSent)
4547 err = WSAEFAULT;
4548 goto error;
4551 overlapped = (lpOverlapped || lpCompletionRoutine) &&
4552 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
4553 if (overlapped || dwBufferCount > 1)
4555 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
4557 err = WSAEFAULT;
4558 goto error;
4561 else
4562 wsa = &localwsa;
4564 wsa->hSocket = SOCKET2HANDLE(s);
4565 wsa->addr = (struct WS_sockaddr *)to;
4566 wsa->addrlen.val = tolen;
4567 wsa->flags = dwFlags;
4568 wsa->lpFlags = &wsa->flags;
4569 wsa->control = NULL;
4570 wsa->n_iovecs = dwBufferCount;
4571 wsa->first_iovec = 0;
4572 for ( i = 0; i < dwBufferCount; i++ )
4574 wsa->iovec[i].iov_base = lpBuffers[i].buf;
4575 wsa->iovec[i].iov_len = lpBuffers[i].len;
4576 totalLength += lpBuffers[i].len;
4579 n = WS2_send( fd, wsa );
4580 if (n == -1 && errno != EAGAIN)
4582 err = wsaErrno();
4583 goto error;
4586 if (overlapped)
4588 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
4589 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
4591 wsa->user_overlapped = lpOverlapped;
4592 wsa->completion_func = lpCompletionRoutine;
4593 release_sock_fd( s, fd );
4595 if (n == -1 || n < totalLength)
4597 iosb->u.Status = STATUS_PENDING;
4598 iosb->Information = n == -1 ? 0 : n;
4600 SERVER_START_REQ( register_async )
4602 req->type = ASYNC_TYPE_WRITE;
4603 req->async.handle = wine_server_obj_handle( wsa->hSocket );
4604 req->async.callback = wine_server_client_ptr( WS2_async_send );
4605 req->async.iosb = wine_server_client_ptr( iosb );
4606 req->async.arg = wine_server_client_ptr( wsa );
4607 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
4608 req->async.cvalue = cvalue;
4609 err = wine_server_call( req );
4611 SERVER_END_REQ;
4613 /* Enable the event only after starting the async. The server will deliver it as soon as
4614 the async is done. */
4615 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
4617 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
4618 WSASetLastError( NtStatusToWSAError( err ));
4619 return SOCKET_ERROR;
4622 iosb->u.Status = STATUS_SUCCESS;
4623 iosb->Information = n;
4624 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = n;
4625 if (!wsa->completion_func)
4627 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
4628 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
4629 HeapFree( GetProcessHeap(), 0, wsa );
4631 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
4632 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
4633 WSASetLastError(0);
4634 return 0;
4637 if ((err = _is_blocking( s, &is_blocking )))
4639 err = NtStatusToWSAError( err );
4640 goto error;
4643 if ( is_blocking )
4645 /* On a blocking non-overlapped stream socket,
4646 * sending blocks until the entire buffer is sent. */
4647 DWORD timeout_start = GetTickCount();
4649 bytes_sent = n == -1 ? 0 : n;
4651 while (wsa->first_iovec < wsa->n_iovecs)
4653 struct pollfd pfd;
4654 int timeout = GET_SNDTIMEO(fd);
4656 if (timeout != -1)
4658 timeout -= GetTickCount() - timeout_start;
4659 if (timeout < 0) timeout = 0;
4662 pfd.fd = fd;
4663 pfd.events = POLLOUT;
4665 if (!timeout || !poll( &pfd, 1, timeout ))
4667 err = WSAETIMEDOUT;
4668 goto error; /* msdn says a timeout in send is fatal */
4671 n = WS2_send( fd, wsa );
4672 if (n == -1 && errno != EAGAIN)
4674 err = wsaErrno();
4675 goto error;
4678 if (n >= 0)
4679 bytes_sent += n;
4682 else /* non-blocking */
4684 if (n < totalLength)
4685 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
4686 if (n == -1)
4688 err = WSAEWOULDBLOCK;
4689 goto error;
4691 bytes_sent = n;
4694 TRACE(" -> %i bytes\n", bytes_sent);
4696 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = bytes_sent;
4697 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
4698 release_sock_fd( s, fd );
4699 WSASetLastError(0);
4700 return 0;
4702 error:
4703 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
4704 release_sock_fd( s, fd );
4705 WARN(" -> ERROR %d\n", err);
4706 WSASetLastError(err);
4707 return SOCKET_ERROR;
4710 /***********************************************************************
4711 * WSASendTo (WS2_32.74)
4713 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4714 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4715 const struct WS_sockaddr *to, int tolen,
4716 LPWSAOVERLAPPED lpOverlapped,
4717 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4719 return WS2_sendto( s, lpBuffers, dwBufferCount,
4720 lpNumberOfBytesSent, dwFlags,
4721 to, tolen,
4722 lpOverlapped, lpCompletionRoutine );
4725 /***********************************************************************
4726 * sendto (WS2_32.20)
4728 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
4729 const struct WS_sockaddr *to, int tolen)
4731 DWORD n;
4732 WSABUF wsabuf;
4734 wsabuf.len = len;
4735 wsabuf.buf = (char*) buf;
4737 if ( WS2_sendto(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
4738 return SOCKET_ERROR;
4739 else
4740 return n;
4743 /***********************************************************************
4744 * setsockopt (WS2_32.21)
4746 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
4747 const char *optval, int optlen)
4749 int fd;
4750 int woptval;
4751 struct linger linger;
4752 struct timeval tval;
4754 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
4755 s, level, optname, optval, optlen);
4757 /* some broken apps pass the value directly instead of a pointer to it */
4758 if(optlen && IS_INTRESOURCE(optval))
4760 SetLastError(WSAEFAULT);
4761 return SOCKET_ERROR;
4764 switch(level)
4766 case WS_SOL_SOCKET:
4767 switch(optname)
4769 /* Some options need some conversion before they can be sent to
4770 * setsockopt. The conversions are done here, then they will fall through
4771 * to the general case. Special options that are not passed to
4772 * setsockopt follow below that.*/
4774 case WS_SO_DONTLINGER:
4775 if (!optval)
4777 SetLastError(WSAEFAULT);
4778 return SOCKET_ERROR;
4780 linger.l_onoff = *(const int*)optval == 0;
4781 linger.l_linger = 0;
4782 level = SOL_SOCKET;
4783 optname = SO_LINGER;
4784 optval = (char*)&linger;
4785 optlen = sizeof(struct linger);
4786 break;
4788 case WS_SO_LINGER:
4789 if (!optval)
4791 SetLastError(WSAEFAULT);
4792 return SOCKET_ERROR;
4794 linger.l_onoff = ((LINGER*)optval)->l_onoff;
4795 linger.l_linger = ((LINGER*)optval)->l_linger;
4796 level = SOL_SOCKET;
4797 optname = SO_LINGER;
4798 optval = (char*)&linger;
4799 optlen = sizeof(struct linger);
4800 break;
4802 case WS_SO_RCVBUF:
4803 if (*(const int*)optval < 2048)
4805 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
4806 return 0;
4808 /* Fall through */
4810 /* The options listed here don't need any special handling. Thanks to
4811 * the conversion happening above, options from there will fall through
4812 * to this, too.*/
4813 case WS_SO_ACCEPTCONN:
4814 case WS_SO_BROADCAST:
4815 case WS_SO_ERROR:
4816 case WS_SO_KEEPALIVE:
4817 case WS_SO_OOBINLINE:
4818 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
4819 * however, using it the BSD way fixes bug 8513 and seems to be what
4820 * most programmers assume, anyway */
4821 case WS_SO_REUSEADDR:
4822 case WS_SO_SNDBUF:
4823 case WS_SO_TYPE:
4824 convert_sockopt(&level, &optname);
4825 break;
4827 /* SO_DEBUG is a privileged operation, ignore it. */
4828 case WS_SO_DEBUG:
4829 TRACE("Ignoring SO_DEBUG\n");
4830 return 0;
4832 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
4833 * socket. According to MSDN, this option is silently ignored.*/
4834 case WS_SO_DONTROUTE:
4835 TRACE("Ignoring SO_DONTROUTE\n");
4836 return 0;
4838 /* Stops two sockets from being bound to the same port. Always happens
4839 * on unix systems, so just drop it. */
4840 case WS_SO_EXCLUSIVEADDRUSE:
4841 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
4842 return 0;
4844 /* After a ConnectEx call succeeds, the socket can't be used with half of the
4845 * normal winsock functions on windows. We don't have that problem. */
4846 case WS_SO_UPDATE_CONNECT_CONTEXT:
4847 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
4848 return 0;
4850 /* After a AcceptEx call succeeds, the socket can't be used with half of the
4851 * normal winsock functions on windows. We don't have that problem. */
4852 case WS_SO_UPDATE_ACCEPT_CONTEXT:
4853 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
4854 return 0;
4856 /* SO_OPENTYPE does not require a valid socket handle. */
4857 case WS_SO_OPENTYPE:
4858 if (!optlen || optlen < sizeof(int) || !optval)
4860 SetLastError(WSAEFAULT);
4861 return SOCKET_ERROR;
4863 get_per_thread_data()->opentype = *(const int *)optval;
4864 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
4865 return 0;
4867 #ifdef SO_RCVTIMEO
4868 case WS_SO_RCVTIMEO:
4869 #endif
4870 #ifdef SO_SNDTIMEO
4871 case WS_SO_SNDTIMEO:
4872 #endif
4873 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
4874 if (optval && optlen == sizeof(UINT32)) {
4875 /* WinSock passes milliseconds instead of struct timeval */
4876 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
4877 tval.tv_sec = *(const UINT32*)optval / 1000;
4878 /* min of 500 milliseconds */
4879 if (tval.tv_sec == 0 && tval.tv_usec && tval.tv_usec < 500000)
4880 tval.tv_usec = 500000;
4881 optlen = sizeof(struct timeval);
4882 optval = (char*)&tval;
4883 } else if (optlen == sizeof(struct timeval)) {
4884 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
4885 } else {
4886 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
4887 return 0;
4889 convert_sockopt(&level, &optname);
4890 break;
4891 #endif
4893 default:
4894 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
4895 SetLastError(WSAENOPROTOOPT);
4896 return SOCKET_ERROR;
4898 break; /* case WS_SOL_SOCKET */
4900 #ifdef HAS_IPX
4901 case WS_NSPROTO_IPX:
4902 switch(optname)
4904 case IPX_PTYPE:
4905 return set_ipx_packettype(s, *(int*)optval);
4907 case IPX_FILTERPTYPE:
4908 /* Sets the receive filter packet type, at the moment we don't support it */
4909 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
4910 /* Returning 0 is better for now than returning a SOCKET_ERROR */
4911 return 0;
4913 default:
4914 FIXME("opt_name:%x\n", optname);
4915 return SOCKET_ERROR;
4917 break; /* case WS_NSPROTO_IPX */
4918 #endif
4920 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
4921 case WS_IPPROTO_TCP:
4922 switch(optname)
4924 case WS_TCP_NODELAY:
4925 convert_sockopt(&level, &optname);
4926 break;
4927 default:
4928 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
4929 return SOCKET_ERROR;
4931 break;
4933 case WS_IPPROTO_IP:
4934 switch(optname)
4936 case WS_IP_ADD_MEMBERSHIP:
4937 case WS_IP_DROP_MEMBERSHIP:
4938 #ifdef IP_HDRINCL
4939 case WS_IP_HDRINCL:
4940 #endif
4941 case WS_IP_MULTICAST_IF:
4942 case WS_IP_MULTICAST_LOOP:
4943 case WS_IP_MULTICAST_TTL:
4944 case WS_IP_OPTIONS:
4945 #ifdef IP_PKTINFO
4946 case WS_IP_PKTINFO:
4947 #endif
4948 case WS_IP_TOS:
4949 case WS_IP_TTL:
4950 #ifdef IP_UNICAST_IF
4951 case WS_IP_UNICAST_IF:
4952 #endif
4953 convert_sockopt(&level, &optname);
4954 break;
4955 case WS_IP_DONTFRAGMENT:
4956 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
4957 return 0;
4958 default:
4959 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
4960 return SOCKET_ERROR;
4962 break;
4964 case WS_IPPROTO_IPV6:
4965 switch(optname)
4967 #ifdef IPV6_ADD_MEMBERSHIP
4968 case WS_IPV6_ADD_MEMBERSHIP:
4969 #endif
4970 #ifdef IPV6_DROP_MEMBERSHIP
4971 case WS_IPV6_DROP_MEMBERSHIP:
4972 #endif
4973 case WS_IPV6_MULTICAST_IF:
4974 case WS_IPV6_MULTICAST_HOPS:
4975 case WS_IPV6_MULTICAST_LOOP:
4976 case WS_IPV6_UNICAST_HOPS:
4977 case WS_IPV6_V6ONLY:
4978 #ifdef IPV6_UNICAST_IF
4979 case WS_IPV6_UNICAST_IF:
4980 #endif
4981 convert_sockopt(&level, &optname);
4982 break;
4983 case WS_IPV6_DONTFRAG:
4984 FIXME("IPV6_DONTFRAG is silently ignored!\n");
4985 return 0;
4986 case WS_IPV6_PROTECTION_LEVEL:
4987 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
4988 return 0;
4989 default:
4990 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
4991 return SOCKET_ERROR;
4993 break;
4995 default:
4996 WARN("Unknown level: 0x%08x\n", level);
4997 SetLastError(WSAEINVAL);
4998 return SOCKET_ERROR;
4999 } /* end switch(level) */
5001 /* avoid endianness issues if argument is a 16-bit int */
5002 if (optval && optlen < sizeof(int))
5004 woptval= *((const INT16 *) optval);
5005 optval= (char*) &woptval;
5006 optlen=sizeof(int);
5008 fd = get_sock_fd( s, 0, NULL );
5009 if (fd == -1) return SOCKET_ERROR;
5011 if (setsockopt(fd, level, optname, optval, optlen) == 0)
5013 #ifdef __APPLE__
5014 if (level == SOL_SOCKET && optname == SO_REUSEADDR &&
5015 setsockopt(fd, level, SO_REUSEPORT, optval, optlen) != 0)
5017 SetLastError(wsaErrno());
5018 release_sock_fd( s, fd );
5019 return SOCKET_ERROR;
5021 #endif
5022 release_sock_fd( s, fd );
5023 return 0;
5025 TRACE("Setting socket error, %d\n", wsaErrno());
5026 SetLastError(wsaErrno());
5027 release_sock_fd( s, fd );
5029 return SOCKET_ERROR;
5032 /***********************************************************************
5033 * shutdown (WS2_32.22)
5035 int WINAPI WS_shutdown(SOCKET s, int how)
5037 int fd, err = WSAENOTSOCK;
5038 unsigned int options, clear_flags = 0;
5040 fd = get_sock_fd( s, 0, &options );
5041 TRACE("socket %04lx, how %i %x\n", s, how, options );
5043 if (fd == -1)
5044 return SOCKET_ERROR;
5046 switch( how )
5048 case SD_RECEIVE: /* drop receives */
5049 clear_flags |= FD_READ;
5050 break;
5051 case SD_SEND: /* drop sends */
5052 clear_flags |= FD_WRITE;
5053 break;
5054 case SD_BOTH: /* drop all */
5055 clear_flags |= FD_READ|FD_WRITE;
5056 /*fall through */
5057 default:
5058 clear_flags |= FD_WINE_LISTENING;
5061 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
5063 switch ( how )
5065 case SD_RECEIVE:
5066 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
5067 break;
5068 case SD_SEND:
5069 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
5070 break;
5071 case SD_BOTH:
5072 default:
5073 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
5074 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
5075 break;
5077 if (err) goto error;
5079 else /* non-overlapped mode */
5081 if ( shutdown( fd, how ) )
5083 err = wsaErrno();
5084 goto error;
5088 release_sock_fd( s, fd );
5089 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
5090 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
5091 return 0;
5093 error:
5094 release_sock_fd( s, fd );
5095 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
5096 WSASetLastError( err );
5097 return SOCKET_ERROR;
5100 /***********************************************************************
5101 * socket (WS2_32.23)
5103 SOCKET WINAPI WS_socket(int af, int type, int protocol)
5105 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
5107 return WSASocketA( af, type, protocol, NULL, 0,
5108 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
5112 /***********************************************************************
5113 * gethostbyaddr (WS2_32.51)
5115 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
5117 struct WS_hostent *retval = NULL;
5118 struct hostent* host;
5119 int unixtype = convert_af_w2u(type);
5120 const char *paddr = addr;
5121 unsigned long loopback;
5122 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5123 char *extrabuf;
5124 int ebufsize = 1024;
5125 struct hostent hostentry;
5126 int locerr = ENOBUFS;
5127 #endif
5129 /* convert back the magic loopback address if necessary */
5130 if (unixtype == AF_INET && len == 4 && !memcmp(addr, magic_loopback_addr, 4))
5132 loopback = htonl(INADDR_LOOPBACK);
5133 paddr = (char*) &loopback;
5136 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5137 host = NULL;
5138 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
5139 while(extrabuf) {
5140 int res = gethostbyaddr_r(paddr, len, unixtype,
5141 &hostentry, extrabuf, ebufsize, &host, &locerr);
5142 if (res != ERANGE) break;
5143 ebufsize *=2;
5144 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
5146 if (host) retval = WS_dup_he(host);
5147 else SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
5148 HeapFree(GetProcessHeap(),0,extrabuf);
5149 #else
5150 EnterCriticalSection( &csWSgetXXXbyYYY );
5151 host = gethostbyaddr(paddr, len, unixtype);
5152 if (host) retval = WS_dup_he(host);
5153 else SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
5154 LeaveCriticalSection( &csWSgetXXXbyYYY );
5155 #endif
5156 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
5157 return retval;
5160 /***********************************************************************
5161 * WS_get_local_ips (INTERNAL)
5163 * Returns the list of local IP addresses by going through the network
5164 * adapters and using the local routing table to sort the addresses
5165 * from highest routing priority to lowest routing priority. This
5166 * functionality is inferred from the description for obtaining local
5167 * IP addresses given in the Knowledge Base Article Q160215.
5169 * Please note that the returned hostent is only freed when the thread
5170 * closes and is replaced if another hostent is requested.
5172 static struct WS_hostent* WS_get_local_ips( char *hostname )
5174 int last_metric, numroutes = 0, i, j;
5175 DWORD n;
5176 PIP_ADAPTER_INFO adapters = NULL, k;
5177 struct WS_hostent *hostlist = NULL;
5178 PMIB_IPFORWARDTABLE routes = NULL;
5179 struct route *route_addrs = NULL;
5180 DWORD adap_size, route_size;
5182 /* Obtain the size of the adapter list and routing table, also allocate memory */
5183 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
5184 return NULL;
5185 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
5186 return NULL;
5187 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
5188 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
5189 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
5190 if (adapters == NULL || routes == NULL || route_addrs == NULL)
5191 goto cleanup;
5192 /* Obtain the adapter list and the full routing table */
5193 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
5194 goto cleanup;
5195 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
5196 goto cleanup;
5197 /* Store the interface associated with each route */
5198 for (n = 0; n < routes->dwNumEntries; n++)
5200 IF_INDEX ifindex;
5201 DWORD ifmetric;
5202 BOOL exists = FALSE;
5204 if (routes->table[n].u1.ForwardType != MIB_IPROUTE_TYPE_DIRECT)
5205 continue;
5206 ifindex = routes->table[n].dwForwardIfIndex;
5207 ifmetric = routes->table[n].dwForwardMetric1;
5208 /* Only store the lowest valued metric for an interface */
5209 for (j = 0; j < numroutes; j++)
5211 if (route_addrs[j].interface == ifindex)
5213 if (route_addrs[j].metric > ifmetric)
5214 route_addrs[j].metric = ifmetric;
5215 exists = TRUE;
5218 if (exists)
5219 continue;
5220 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
5221 if (route_addrs == NULL)
5222 goto cleanup; /* Memory allocation error, fail gracefully */
5223 route_addrs[numroutes].interface = ifindex;
5224 route_addrs[numroutes].metric = ifmetric;
5225 /* If no IP is found in the next step (for whatever reason)
5226 * then fall back to the magic loopback address.
5228 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
5229 numroutes++;
5231 if (numroutes == 0)
5232 goto cleanup; /* No routes, fall back to the Magic IP */
5233 /* Find the IP address associated with each found interface */
5234 for (i = 0; i < numroutes; i++)
5236 for (k = adapters; k != NULL; k = k->Next)
5238 char *ip = k->IpAddressList.IpAddress.String;
5240 if (route_addrs[i].interface == k->Index)
5241 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
5244 /* Allocate a hostent and enough memory for all the IPs,
5245 * including the NULL at the end of the list.
5247 hostlist = WS_create_he(hostname, 1, 0, numroutes+1, sizeof(struct in_addr));
5248 if (hostlist == NULL)
5249 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
5250 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
5251 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
5252 hostlist->h_addrtype = AF_INET;
5253 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
5254 /* Reorder the entries when placing them in the host list, Windows expects
5255 * the IP list in order from highest priority to lowest (the critical thing
5256 * is that most applications expect the first IP to be the default route).
5258 last_metric = -1;
5259 for (i = 0; i < numroutes; i++)
5261 struct in_addr addr;
5262 int metric = 0xFFFF;
5264 memcpy(&addr, magic_loopback_addr, 4);
5265 for (j = 0; j < numroutes; j++)
5267 int this_metric = route_addrs[j].metric;
5269 if (this_metric > last_metric && this_metric < metric)
5271 addr = route_addrs[j].addr;
5272 metric = this_metric;
5275 last_metric = metric;
5276 (*(struct in_addr *) hostlist->h_addr_list[i]) = addr;
5279 /* Cleanup all allocated memory except the address list,
5280 * the address list is used by the calling app.
5282 cleanup:
5283 HeapFree(GetProcessHeap(), 0, route_addrs);
5284 HeapFree(GetProcessHeap(), 0, adapters);
5285 HeapFree(GetProcessHeap(), 0, routes);
5286 return hostlist;
5289 /***********************************************************************
5290 * gethostbyname (WS2_32.52)
5292 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
5294 struct WS_hostent *retval = NULL;
5295 struct hostent* host;
5296 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5297 char *extrabuf;
5298 int ebufsize=1024;
5299 struct hostent hostentry;
5300 int locerr = ENOBUFS;
5301 #endif
5302 char hostname[100];
5303 if(!num_startup) {
5304 SetLastError(WSANOTINITIALISED);
5305 return NULL;
5307 if( gethostname( hostname, 100) == -1) {
5308 SetLastError( WSAENOBUFS); /* appropriate ? */
5309 return retval;
5311 if( !name || !name[0]) {
5312 name = hostname;
5314 /* If the hostname of the local machine is requested then return the
5315 * complete list of local IP addresses */
5316 if(strcmp(name, hostname) == 0)
5317 retval = WS_get_local_ips(hostname);
5318 /* If any other hostname was requested (or the routing table lookup failed)
5319 * then return the IP found by the host OS */
5320 if(retval == NULL)
5322 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5323 host = NULL;
5324 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
5325 while(extrabuf) {
5326 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
5327 if( res != ERANGE) break;
5328 ebufsize *=2;
5329 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
5331 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
5332 #else
5333 EnterCriticalSection( &csWSgetXXXbyYYY );
5334 host = gethostbyname(name);
5335 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
5336 #endif
5337 if (host) retval = WS_dup_he(host);
5338 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5339 HeapFree(GetProcessHeap(),0,extrabuf);
5340 #else
5341 LeaveCriticalSection( &csWSgetXXXbyYYY );
5342 #endif
5344 if (retval && retval->h_addr_list[0][0] == 127 &&
5345 strcmp(name, "localhost") != 0)
5347 /* hostname != "localhost" but has loopback address. replace by our
5348 * special address.*/
5349 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
5351 TRACE( "%s ret %p\n", debugstr_a(name), retval );
5352 return retval;
5356 /***********************************************************************
5357 * getprotobyname (WS2_32.53)
5359 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
5361 struct WS_protoent* retval = NULL;
5362 #ifdef HAVE_GETPROTOBYNAME
5363 struct protoent* proto;
5364 EnterCriticalSection( &csWSgetXXXbyYYY );
5365 if( (proto = getprotobyname(name)) != NULL )
5367 retval = WS_dup_pe(proto);
5369 else {
5370 MESSAGE("protocol %s not found; You might want to add "
5371 "this to /etc/protocols\n", debugstr_a(name) );
5372 SetLastError(WSANO_DATA);
5374 LeaveCriticalSection( &csWSgetXXXbyYYY );
5375 #endif
5376 TRACE( "%s ret %p\n", debugstr_a(name), retval );
5377 return retval;
5381 /***********************************************************************
5382 * getprotobynumber (WS2_32.54)
5384 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
5386 struct WS_protoent* retval = NULL;
5387 #ifdef HAVE_GETPROTOBYNUMBER
5388 struct protoent* proto;
5389 EnterCriticalSection( &csWSgetXXXbyYYY );
5390 if( (proto = getprotobynumber(number)) != NULL )
5392 retval = WS_dup_pe(proto);
5394 else {
5395 MESSAGE("protocol number %d not found; You might want to add "
5396 "this to /etc/protocols\n", number );
5397 SetLastError(WSANO_DATA);
5399 LeaveCriticalSection( &csWSgetXXXbyYYY );
5400 #endif
5401 TRACE("%i ret %p\n", number, retval);
5402 return retval;
5406 /***********************************************************************
5407 * getservbyname (WS2_32.55)
5409 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
5411 struct WS_servent* retval = NULL;
5412 struct servent* serv;
5413 char *name_str;
5414 char *proto_str = NULL;
5416 if (!(name_str = strdup_lower(name))) return NULL;
5418 if (proto && *proto)
5420 if (!(proto_str = strdup_lower(proto)))
5422 HeapFree( GetProcessHeap(), 0, name_str );
5423 return NULL;
5427 EnterCriticalSection( &csWSgetXXXbyYYY );
5428 serv = getservbyname(name_str, proto_str);
5429 if( serv != NULL )
5431 retval = WS_dup_se(serv);
5433 else SetLastError(WSANO_DATA);
5434 LeaveCriticalSection( &csWSgetXXXbyYYY );
5435 HeapFree( GetProcessHeap(), 0, proto_str );
5436 HeapFree( GetProcessHeap(), 0, name_str );
5437 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
5438 return retval;
5441 /***********************************************************************
5442 * freeaddrinfo (WS2_32.@)
5444 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
5446 while (res) {
5447 struct WS_addrinfo *next;
5449 HeapFree(GetProcessHeap(),0,res->ai_canonname);
5450 HeapFree(GetProcessHeap(),0,res->ai_addr);
5451 next = res->ai_next;
5452 HeapFree(GetProcessHeap(),0,res);
5453 res = next;
5457 /* helper functions for getaddrinfo()/getnameinfo() */
5458 static int convert_aiflag_w2u(int winflags) {
5459 unsigned int i;
5460 int unixflags = 0;
5462 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
5463 if (ws_aiflag_map[i][0] & winflags) {
5464 unixflags |= ws_aiflag_map[i][1];
5465 winflags &= ~ws_aiflag_map[i][0];
5467 if (winflags)
5468 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
5469 return unixflags;
5472 static int convert_niflag_w2u(int winflags) {
5473 unsigned int i;
5474 int unixflags = 0;
5476 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
5477 if (ws_niflag_map[i][0] & winflags) {
5478 unixflags |= ws_niflag_map[i][1];
5479 winflags &= ~ws_niflag_map[i][0];
5481 if (winflags)
5482 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
5483 return unixflags;
5486 static int convert_aiflag_u2w(int unixflags) {
5487 unsigned int i;
5488 int winflags = 0;
5490 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
5491 if (ws_aiflag_map[i][1] & unixflags) {
5492 winflags |= ws_aiflag_map[i][0];
5493 unixflags &= ~ws_aiflag_map[i][1];
5495 if (unixflags) /* will warn usually */
5496 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
5497 return winflags;
5500 static int convert_eai_u2w(int unixret) {
5501 int i;
5503 if (!unixret) return 0;
5505 for (i=0;ws_eai_map[i][0];i++)
5506 if (ws_eai_map[i][1] == unixret)
5507 return ws_eai_map[i][0];
5509 if (unixret == EAI_SYSTEM)
5510 /* There are broken versions of glibc which return EAI_SYSTEM
5511 * and set errno to 0 instead of returning EAI_NONAME.
5513 return errno ? sock_get_error( errno ) : WS_EAI_NONAME;
5515 FIXME("Unhandled unix EAI_xxx ret %d\n", unixret);
5516 return unixret;
5519 static char *get_hostname(void)
5521 char *ret;
5522 DWORD size = 0;
5524 GetComputerNameExA( ComputerNamePhysicalDnsHostname, NULL, &size );
5525 if (GetLastError() != ERROR_MORE_DATA) return NULL;
5526 if (!(ret = HeapAlloc( GetProcessHeap(), 0, size ))) return NULL;
5527 if (!GetComputerNameExA( ComputerNamePhysicalDnsHostname, ret, &size ))
5529 HeapFree( GetProcessHeap(), 0, ret );
5530 return NULL;
5532 return ret;
5535 /***********************************************************************
5536 * getaddrinfo (WS2_32.@)
5538 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
5540 #ifdef HAVE_GETADDRINFO
5541 struct addrinfo *unixaires = NULL;
5542 int result;
5543 struct addrinfo unixhints, *punixhints = NULL;
5544 char *hostname = NULL;
5545 const char *node;
5547 *res = NULL;
5548 if (!nodename && !servname) return WSAHOST_NOT_FOUND;
5550 if (!nodename)
5551 node = NULL;
5552 else if (!nodename[0])
5554 node = hostname = get_hostname();
5555 if (!node) return WSA_NOT_ENOUGH_MEMORY;
5557 else
5558 node = nodename;
5560 /* servname tweak required by OSX and BSD kernels */
5561 if (servname && !servname[0]) servname = "0";
5563 if (hints) {
5564 punixhints = &unixhints;
5566 memset(&unixhints, 0, sizeof(unixhints));
5567 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
5569 /* zero is a wildcard, no need to convert */
5570 if (hints->ai_family)
5571 punixhints->ai_family = convert_af_w2u(hints->ai_family);
5572 if (hints->ai_socktype)
5573 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
5574 if (hints->ai_protocol)
5575 punixhints->ai_protocol = max(convert_proto_w2u(hints->ai_protocol), 0);
5577 if (punixhints->ai_socktype < 0)
5579 WSASetLastError(WSAESOCKTNOSUPPORT);
5580 HeapFree(GetProcessHeap(), 0, hostname);
5581 return SOCKET_ERROR;
5584 /* windows allows invalid combinations of socket type and protocol, unix does not.
5585 * fix the parameters here to make getaddrinfo call always work */
5586 if (punixhints->ai_protocol == IPPROTO_TCP &&
5587 punixhints->ai_socktype != SOCK_STREAM && punixhints->ai_socktype != SOCK_SEQPACKET)
5588 punixhints->ai_socktype = 0;
5590 else if (punixhints->ai_protocol == IPPROTO_UDP && punixhints->ai_socktype != SOCK_DGRAM)
5591 punixhints->ai_socktype = 0;
5593 else if (IS_IPX_PROTO(punixhints->ai_protocol) && punixhints->ai_socktype != SOCK_DGRAM)
5594 punixhints->ai_socktype = 0;
5597 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
5598 result = getaddrinfo(node, servname, punixhints, &unixaires);
5600 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
5601 HeapFree(GetProcessHeap(), 0, hostname);
5603 if (!result) {
5604 struct addrinfo *xuai = unixaires;
5605 struct WS_addrinfo **xai = res;
5607 *xai = NULL;
5608 while (xuai) {
5609 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
5610 SIZE_T len;
5612 if (!ai)
5613 goto outofmem;
5615 *xai = ai;xai = &ai->ai_next;
5616 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
5617 ai->ai_family = convert_af_u2w(xuai->ai_family);
5618 /* copy whatever was sent in the hints */
5619 if(hints) {
5620 ai->ai_socktype = hints->ai_socktype;
5621 ai->ai_protocol = hints->ai_protocol;
5622 } else {
5623 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
5624 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
5626 if (xuai->ai_canonname) {
5627 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
5628 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
5629 if (!ai->ai_canonname)
5630 goto outofmem;
5631 strcpy(ai->ai_canonname,xuai->ai_canonname);
5633 len = xuai->ai_addrlen;
5634 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
5635 if (!ai->ai_addr)
5636 goto outofmem;
5637 ai->ai_addrlen = len;
5638 do {
5639 int winlen = ai->ai_addrlen;
5641 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
5642 ai->ai_addrlen = winlen;
5643 break;
5645 len = 2*len;
5646 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
5647 if (!ai->ai_addr)
5648 goto outofmem;
5649 ai->ai_addrlen = len;
5650 } while (1);
5651 xuai = xuai->ai_next;
5653 freeaddrinfo(unixaires);
5655 if (TRACE_ON(winsock))
5657 struct WS_addrinfo *ai = *res;
5658 while (ai)
5660 TRACE("=> %p, flags %#x, family %d, type %d, protocol %d, len %ld, name %s, addr %s\n",
5661 ai, ai->ai_flags, ai->ai_family, ai->ai_socktype, ai->ai_protocol, ai->ai_addrlen,
5662 ai->ai_canonname, debugstr_sockaddr(ai->ai_addr));
5663 ai = ai->ai_next;
5666 } else
5667 result = convert_eai_u2w(result);
5669 return result;
5671 outofmem:
5672 if (*res) WS_freeaddrinfo(*res);
5673 if (unixaires) freeaddrinfo(unixaires);
5674 return WSA_NOT_ENOUGH_MEMORY;
5675 #else
5676 FIXME("getaddrinfo() failed, not found during buildtime.\n");
5677 return EAI_FAIL;
5678 #endif
5681 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
5683 struct WS_addrinfoW *ret;
5685 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
5686 ret->ai_flags = ai->ai_flags;
5687 ret->ai_family = ai->ai_family;
5688 ret->ai_socktype = ai->ai_socktype;
5689 ret->ai_protocol = ai->ai_protocol;
5690 ret->ai_addrlen = ai->ai_addrlen;
5691 ret->ai_canonname = NULL;
5692 ret->ai_addr = NULL;
5693 ret->ai_next = NULL;
5694 if (ai->ai_canonname)
5696 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
5697 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
5699 HeapFree(GetProcessHeap(), 0, ret);
5700 return NULL;
5702 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
5704 if (ai->ai_addr)
5706 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, ai->ai_addrlen)))
5708 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
5709 HeapFree(GetProcessHeap(), 0, ret);
5710 return NULL;
5712 memcpy(ret->ai_addr, ai->ai_addr, ai->ai_addrlen);
5714 return ret;
5717 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
5719 struct WS_addrinfoW *ret, *infoW;
5721 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
5722 while (info->ai_next)
5724 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
5726 FreeAddrInfoW(ret);
5727 return NULL;
5729 infoW = infoW->ai_next;
5730 info = info->ai_next;
5732 return ret;
5735 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
5737 struct WS_addrinfo *ret;
5739 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
5740 ret->ai_flags = ai->ai_flags;
5741 ret->ai_family = ai->ai_family;
5742 ret->ai_socktype = ai->ai_socktype;
5743 ret->ai_protocol = ai->ai_protocol;
5744 ret->ai_addrlen = ai->ai_addrlen;
5745 ret->ai_canonname = NULL;
5746 ret->ai_addr = NULL;
5747 ret->ai_next = NULL;
5748 if (ai->ai_canonname)
5750 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
5751 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
5753 HeapFree(GetProcessHeap(), 0, ret);
5754 return NULL;
5756 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
5758 if (ai->ai_addr)
5760 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
5762 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
5763 HeapFree(GetProcessHeap(), 0, ret);
5764 return NULL;
5766 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
5768 return ret;
5771 /***********************************************************************
5772 * GetAddrInfoW (WS2_32.@)
5774 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
5776 int ret, len;
5777 char *nodenameA = NULL, *servnameA = NULL;
5778 struct WS_addrinfo *resA, *hintsA = NULL;
5780 *res = NULL;
5781 if (nodename)
5783 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
5784 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
5785 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
5787 if (servname)
5789 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
5790 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
5792 HeapFree(GetProcessHeap(), 0, nodenameA);
5793 return EAI_MEMORY;
5795 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
5798 if (hints) hintsA = addrinfo_WtoA(hints);
5799 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
5800 WS_freeaddrinfo(hintsA);
5802 if (!ret)
5804 *res = addrinfo_list_AtoW(resA);
5805 WS_freeaddrinfo(resA);
5808 HeapFree(GetProcessHeap(), 0, nodenameA);
5809 HeapFree(GetProcessHeap(), 0, servnameA);
5810 return ret;
5813 /***********************************************************************
5814 * FreeAddrInfoW (WS2_32.@)
5816 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
5818 while (ai)
5820 ADDRINFOW *next;
5821 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
5822 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
5823 next = ai->ai_next;
5824 HeapFree(GetProcessHeap(), 0, ai);
5825 ai = next;
5829 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
5830 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
5832 #ifdef HAVE_GETNAMEINFO
5833 int ret;
5834 union generic_unix_sockaddr sa_u;
5835 unsigned int size;
5837 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
5838 serv, servlen, flags);
5840 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
5841 if (!size)
5843 WSASetLastError(WSAEFAULT);
5844 return WSA_NOT_ENOUGH_MEMORY;
5846 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
5847 return convert_eai_u2w(ret);
5848 #else
5849 FIXME("getnameinfo() failed, not found during buildtime.\n");
5850 return EAI_FAIL;
5851 #endif
5854 int WINAPI GetNameInfoW(const SOCKADDR *sa, WS_socklen_t salen, PWCHAR host,
5855 DWORD hostlen, PWCHAR serv, DWORD servlen, INT flags)
5857 int ret;
5858 char *hostA = NULL, *servA = NULL;
5860 if (host && (!(hostA = HeapAlloc(GetProcessHeap(), 0, hostlen)))) return EAI_MEMORY;
5861 if (serv && (!(servA = HeapAlloc(GetProcessHeap(), 0, servlen))))
5863 HeapFree(GetProcessHeap(), 0, hostA);
5864 return EAI_MEMORY;
5867 ret = WS_getnameinfo(sa, salen, hostA, hostlen, servA, servlen, flags);
5868 if (!ret)
5870 if (host) MultiByteToWideChar(CP_ACP, 0, hostA, -1, host, hostlen);
5871 if (serv) MultiByteToWideChar(CP_ACP, 0, servA, -1, serv, servlen);
5874 HeapFree(GetProcessHeap(), 0, hostA);
5875 HeapFree(GetProcessHeap(), 0, servA);
5876 return ret;
5879 /***********************************************************************
5880 * getservbyport (WS2_32.56)
5882 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
5884 struct WS_servent* retval = NULL;
5885 #ifdef HAVE_GETSERVBYPORT
5886 struct servent* serv;
5887 char *proto_str = NULL;
5889 if (proto && *proto)
5891 if (!(proto_str = strdup_lower(proto))) return NULL;
5893 EnterCriticalSection( &csWSgetXXXbyYYY );
5894 if( (serv = getservbyport(port, proto_str)) != NULL ) {
5895 retval = WS_dup_se(serv);
5897 else SetLastError(WSANO_DATA);
5898 LeaveCriticalSection( &csWSgetXXXbyYYY );
5899 HeapFree( GetProcessHeap(), 0, proto_str );
5900 #endif
5901 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
5902 return retval;
5906 /***********************************************************************
5907 * gethostname (WS2_32.57)
5909 int WINAPI WS_gethostname(char *name, int namelen)
5911 TRACE("name %p, len %d\n", name, namelen);
5913 if (gethostname(name, namelen) == 0)
5915 TRACE("<- '%s'\n", name);
5916 return 0;
5918 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
5919 TRACE("<- ERROR !\n");
5920 return SOCKET_ERROR;
5924 /* ------------------------------------- Windows sockets extensions -- *
5926 * ------------------------------------------------------------------- */
5928 /***********************************************************************
5929 * WSAEnumNetworkEvents (WS2_32.36)
5931 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
5933 int ret;
5934 int i;
5935 int errors[FD_MAX_EVENTS];
5937 TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
5939 SERVER_START_REQ( get_socket_event )
5941 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5942 req->service = TRUE;
5943 req->c_event = wine_server_obj_handle( hEvent );
5944 wine_server_set_reply( req, errors, sizeof(errors) );
5945 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
5947 SERVER_END_REQ;
5948 if (!ret)
5950 for (i = 0; i < FD_MAX_EVENTS; i++)
5951 lpEvent->iErrorCode[i] = NtStatusToWSAError(errors[i]);
5952 return 0;
5954 SetLastError(WSAEINVAL);
5955 return SOCKET_ERROR;
5958 /***********************************************************************
5959 * WSAEventSelect (WS2_32.39)
5961 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
5963 int ret;
5965 TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
5967 SERVER_START_REQ( set_socket_event )
5969 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5970 req->mask = lEvent;
5971 req->event = wine_server_obj_handle( hEvent );
5972 req->window = 0;
5973 req->msg = 0;
5974 ret = wine_server_call( req );
5976 SERVER_END_REQ;
5977 if (!ret) return 0;
5978 SetLastError(WSAEINVAL);
5979 return SOCKET_ERROR;
5982 /**********************************************************************
5983 * WSAGetOverlappedResult (WS2_32.40)
5985 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
5986 LPDWORD lpcbTransfer, BOOL fWait,
5987 LPDWORD lpdwFlags )
5989 NTSTATUS status;
5991 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
5992 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
5994 if ( lpOverlapped == NULL )
5996 ERR( "Invalid pointer\n" );
5997 WSASetLastError(WSA_INVALID_PARAMETER);
5998 return FALSE;
6001 status = lpOverlapped->Internal;
6002 if (status == STATUS_PENDING)
6004 if (!fWait)
6006 SetLastError( WSA_IO_INCOMPLETE );
6007 return FALSE;
6010 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
6011 INFINITE ) == WAIT_FAILED)
6012 return FALSE;
6013 status = lpOverlapped->Internal;
6016 if ( lpcbTransfer )
6017 *lpcbTransfer = lpOverlapped->InternalHigh;
6019 if ( lpdwFlags )
6020 *lpdwFlags = lpOverlapped->u.s.Offset;
6022 if (status) SetLastError( RtlNtStatusToDosError(status) );
6023 return !status;
6027 /***********************************************************************
6028 * WSAAsyncSelect (WS2_32.101)
6030 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
6032 int ret;
6034 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
6036 SERVER_START_REQ( set_socket_event )
6038 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6039 req->mask = lEvent;
6040 req->event = 0;
6041 req->window = wine_server_user_handle( hWnd );
6042 req->msg = uMsg;
6043 ret = wine_server_call( req );
6045 SERVER_END_REQ;
6046 if (!ret) return 0;
6047 SetLastError(WSAEINVAL);
6048 return SOCKET_ERROR;
6051 /***********************************************************************
6052 * WSACreateEvent (WS2_32.31)
6055 WSAEVENT WINAPI WSACreateEvent(void)
6057 /* Create a manual-reset event, with initial state: unsignaled */
6058 TRACE("\n");
6060 return CreateEventW(NULL, TRUE, FALSE, NULL);
6063 /***********************************************************************
6064 * WSACloseEvent (WS2_32.29)
6067 BOOL WINAPI WSACloseEvent(WSAEVENT event)
6069 TRACE ("event=%p\n", event);
6071 return CloseHandle(event);
6074 /***********************************************************************
6075 * WSASocketA (WS2_32.78)
6078 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
6079 LPWSAPROTOCOL_INFOA lpProtocolInfo,
6080 GROUP g, DWORD dwFlags)
6082 INT len;
6083 WSAPROTOCOL_INFOW info;
6085 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
6086 af, type, protocol, lpProtocolInfo, g, dwFlags);
6088 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
6090 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
6091 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
6092 info.szProtocol, WSAPROTOCOL_LEN + 1);
6094 if (!len)
6096 WSASetLastError( WSAEINVAL);
6097 return SOCKET_ERROR;
6100 return WSASocketW(af, type, protocol, &info, g, dwFlags);
6103 /***********************************************************************
6104 * WSASocketW (WS2_32.79)
6107 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
6108 LPWSAPROTOCOL_INFOW lpProtocolInfo,
6109 GROUP g, DWORD dwFlags)
6111 SOCKET ret;
6112 DWORD err;
6113 int unixaf, unixtype, ipxptype = -1;
6116 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
6117 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
6120 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
6121 af, type, protocol, lpProtocolInfo, g, dwFlags );
6123 if (!num_startup)
6125 err = WSANOTINITIALISED;
6126 goto done;
6129 /* hack for WSADuplicateSocket */
6130 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
6131 ret = lpProtocolInfo->dwServiceFlags3;
6132 TRACE("\tgot duplicate %04lx\n", ret);
6133 return ret;
6136 if (lpProtocolInfo)
6138 if (af == FROM_PROTOCOL_INFO || !af)
6139 af = lpProtocolInfo->iAddressFamily;
6140 if (type == FROM_PROTOCOL_INFO || !type)
6141 type = lpProtocolInfo->iSocketType;
6142 if (protocol == FROM_PROTOCOL_INFO || !protocol)
6143 protocol = lpProtocolInfo->iProtocol;
6146 if (!type && (af || protocol))
6148 int autoproto = protocol;
6149 WSAPROTOCOL_INFOW infow;
6151 /* default to the first valid protocol */
6152 if (!autoproto)
6153 autoproto = valid_protocols[0];
6154 else if(IS_IPX_PROTO(autoproto))
6155 autoproto = WS_NSPROTO_IPX;
6157 if (WS_EnterSingleProtocolW(autoproto, &infow))
6159 type = infow.iSocketType;
6161 /* after win2003 it's no longer possible to pass AF_UNSPEC
6162 using the protocol info struct */
6163 if (!lpProtocolInfo && af == WS_AF_UNSPEC)
6164 af = infow.iAddressFamily;
6169 Windows has an extension to the IPX protocol that allows one to create sockets
6170 and set the IPX packet type at the same time, to do that a caller will use
6171 a protocol like NSPROTO_IPX + <PACKET TYPE>
6173 if (IS_IPX_PROTO(protocol))
6174 ipxptype = protocol - WS_NSPROTO_IPX;
6176 /* convert the socket family, type and protocol */
6177 unixaf = convert_af_w2u(af);
6178 unixtype = convert_socktype_w2u(type);
6179 protocol = convert_proto_w2u(protocol);
6180 if (unixaf == AF_UNSPEC) unixaf = -1;
6182 /* filter invalid parameters */
6183 if (protocol < 0)
6185 /* the type could not be converted */
6186 if (type && unixtype < 0)
6188 err = WSAESOCKTNOSUPPORT;
6189 goto done;
6192 err = WSAEPROTONOSUPPORT;
6193 goto done;
6195 if (unixaf < 0)
6197 /* both family and protocol can't be invalid */
6198 if (protocol <= 0)
6200 err = WSAEINVAL;
6201 goto done;
6204 /* family could not be converted and neither socket type */
6205 if (unixtype < 0 && af >= 0)
6208 err = WSAESOCKTNOSUPPORT;
6209 goto done;
6212 err = WSAEAFNOSUPPORT;
6213 goto done;
6216 SERVER_START_REQ( create_socket )
6218 req->family = unixaf;
6219 req->type = unixtype;
6220 req->protocol = protocol;
6221 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
6222 req->attributes = OBJ_INHERIT;
6223 req->flags = dwFlags;
6224 set_error( wine_server_call( req ) );
6225 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
6227 SERVER_END_REQ;
6228 if (ret)
6230 TRACE("\tcreated %04lx\n", ret );
6231 if (ipxptype > 0)
6232 set_ipx_packettype(ret, ipxptype);
6233 return ret;
6236 err = GetLastError();
6237 if (err == WSAEACCES) /* raw socket denied */
6239 if (type == SOCK_RAW)
6240 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
6241 else
6242 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
6244 else
6246 /* invalid combination of valid parameters, like SOCK_STREAM + IPPROTO_UDP */
6247 if (err == WSAEINVAL)
6248 err = WSAESOCKTNOSUPPORT;
6249 else if (err == WSAEOPNOTSUPP)
6250 err = WSAEPROTONOSUPPORT;
6253 done:
6254 WARN("\t\tfailed, error %d!\n", err);
6255 SetLastError(err);
6256 return INVALID_SOCKET;
6259 /***********************************************************************
6260 * WSAJoinLeaf (WS2_32.58)
6263 SOCKET WINAPI WSAJoinLeaf(
6264 SOCKET s,
6265 const struct WS_sockaddr *addr,
6266 int addrlen,
6267 LPWSABUF lpCallerData,
6268 LPWSABUF lpCalleeData,
6269 LPQOS lpSQOS,
6270 LPQOS lpGQOS,
6271 DWORD dwFlags)
6273 FIXME("stub.\n");
6274 return INVALID_SOCKET;
6277 /***********************************************************************
6278 * __WSAFDIsSet (WS2_32.151)
6280 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
6282 int i = set->fd_count;
6284 TRACE("(%ld,%p(%i))\n", s, set, i);
6286 while (i--)
6287 if (set->fd_array[i] == s) return 1;
6288 return 0;
6291 /***********************************************************************
6292 * WSAIsBlocking (WS2_32.114)
6294 BOOL WINAPI WSAIsBlocking(void)
6296 /* By default WinSock should set all its sockets to non-blocking mode
6297 * and poll in PeekMessage loop when processing "blocking" ones. This
6298 * function is supposed to tell if the program is in this loop. Our
6299 * blocking calls are truly blocking so we always return FALSE.
6301 * Note: It is allowed to call this function without prior WSAStartup().
6304 TRACE("\n");
6305 return FALSE;
6308 /***********************************************************************
6309 * WSACancelBlockingCall (WS2_32.113)
6311 INT WINAPI WSACancelBlockingCall(void)
6313 TRACE("\n");
6314 return 0;
6317 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
6319 FIXME("How was this called?\n");
6320 return x();
6324 /***********************************************************************
6325 * WSASetBlockingHook (WS2_32.109)
6327 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
6329 FARPROC prev = blocking_hook;
6330 blocking_hook = lpBlockFunc;
6331 TRACE("hook %p\n", lpBlockFunc);
6332 return prev;
6336 /***********************************************************************
6337 * WSAUnhookBlockingHook (WS2_32.110)
6339 INT WINAPI WSAUnhookBlockingHook(void)
6341 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
6342 return 0;
6346 /* ----------------------------------- end of API stuff */
6348 /* ----------------------------------- helper functions -
6350 * TODO: Merge WS_dup_..() stuff into one function that
6351 * would operate with a generic structure containing internal
6352 * pointers (via a template of some kind).
6355 static int list_size(char** l, int item_size)
6357 int i,j = 0;
6358 if(l)
6359 { for(i=0;l[i];i++)
6360 j += (item_size) ? item_size : strlen(l[i]) + 1;
6361 j += (i + 1) * sizeof(char*); }
6362 return j;
6365 static int list_dup(char** l_src, char** l_to, int item_size)
6367 char *p;
6368 int i;
6370 for (i = 0; l_src[i]; i++) ;
6371 p = (char *)(l_to + i + 1);
6372 for (i = 0; l_src[i]; i++)
6374 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
6375 memcpy(p, l_src[i], count);
6376 l_to[i] = p;
6377 p += count;
6379 l_to[i] = NULL;
6380 return p - (char *)l_to;
6383 /* ----- hostent */
6385 /* create a hostent entry
6387 * Creates the entry with enough memory for the name, aliases
6388 * addresses, and the address pointers. Also copies the name
6389 * and sets up all the pointers.
6391 * NOTE: The alias and address lists must be allocated with room
6392 * for the NULL item terminating the list. This is true even if
6393 * the list has no items ("aliases" and "addresses" must be
6394 * at least "1", a truly empty list is invalid).
6396 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length)
6398 struct WS_hostent *p_to;
6399 char *p;
6400 int size = (sizeof(struct WS_hostent) +
6401 strlen(name) + 1 +
6402 sizeof(char *) * aliases +
6403 aliases_size +
6404 sizeof(char *) * addresses +
6405 address_length * (addresses - 1)), i;
6407 if (!(p_to = check_buffer_he(size))) return NULL;
6408 memset(p_to, 0, size);
6410 /* Use the memory in the same way winsock does.
6411 * First set the pointer for aliases, second set the pointers for addresses.
6412 * Third fill the addresses indexes, fourth jump aliases names size.
6413 * Fifth fill the hostname.
6414 * NOTE: This method is valid for OS version's >= XP.
6416 p = (char *)(p_to + 1);
6417 p_to->h_aliases = (char **)p;
6418 p += sizeof(char *)*aliases;
6420 p_to->h_addr_list = (char **)p;
6421 p += sizeof(char *)*addresses;
6423 for (i = 0, addresses--; i < addresses; i++, p += address_length)
6424 p_to->h_addr_list[i] = p;
6426 /* NOTE: h_aliases must be filled in manually because we don't know each string
6427 * size, leave these pointers NULL (already set to NULL by memset earlier).
6429 p += aliases_size;
6431 p_to->h_name = p;
6432 strcpy(p, name);
6434 return p_to;
6437 /* duplicate hostent entry
6438 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
6439 * Ditto for protoent and servent.
6441 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
6443 int i, addresses = 0, alias_size = 0;
6444 struct WS_hostent *p_to;
6445 char *p;
6447 for( i = 0; p_he->h_aliases[i]; i++) alias_size += strlen(p_he->h_aliases[i]) + 1;
6448 while (p_he->h_addr_list[addresses]) addresses++;
6450 p_to = WS_create_he(p_he->h_name, i + 1, alias_size, addresses + 1, p_he->h_length);
6452 if (!p_to) return NULL;
6453 p_to->h_addrtype = convert_af_u2w(p_he->h_addrtype);
6454 p_to->h_length = p_he->h_length;
6456 for(i = 0, p = p_to->h_addr_list[0]; p_he->h_addr_list[i]; i++, p += p_to->h_length)
6457 memcpy(p, p_he->h_addr_list[i], p_to->h_length);
6459 /* Fill the aliases after the IP data */
6460 for(i = 0; p_he->h_aliases[i]; i++)
6462 p_to->h_aliases[i] = p;
6463 strcpy(p, p_he->h_aliases[i]);
6464 p += strlen(p) + 1;
6467 return p_to;
6470 /* ----- protoent */
6472 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
6474 char *p;
6475 struct WS_protoent *p_to;
6477 int size = (sizeof(*p_pe) +
6478 strlen(p_pe->p_name) + 1 +
6479 list_size(p_pe->p_aliases, 0));
6481 if (!(p_to = check_buffer_pe(size))) return NULL;
6482 p_to->p_proto = p_pe->p_proto;
6484 p = (char *)(p_to + 1);
6485 p_to->p_name = p;
6486 strcpy(p, p_pe->p_name);
6487 p += strlen(p) + 1;
6489 p_to->p_aliases = (char **)p;
6490 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
6491 return p_to;
6494 /* ----- servent */
6496 static struct WS_servent *WS_dup_se(const struct servent* p_se)
6498 char *p;
6499 struct WS_servent *p_to;
6501 int size = (sizeof(*p_se) +
6502 strlen(p_se->s_proto) + 1 +
6503 strlen(p_se->s_name) + 1 +
6504 list_size(p_se->s_aliases, 0));
6506 if (!(p_to = check_buffer_se(size))) return NULL;
6507 p_to->s_port = p_se->s_port;
6509 p = (char *)(p_to + 1);
6510 p_to->s_name = p;
6511 strcpy(p, p_se->s_name);
6512 p += strlen(p) + 1;
6514 p_to->s_proto = p;
6515 strcpy(p, p_se->s_proto);
6516 p += strlen(p) + 1;
6518 p_to->s_aliases = (char **)p;
6519 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
6520 return p_to;
6524 /***********************************************************************
6525 * WSARecv (WS2_32.67)
6527 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6528 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
6529 LPWSAOVERLAPPED lpOverlapped,
6530 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
6532 return WS2_recv_base(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
6533 NULL, NULL, lpOverlapped, lpCompletionRoutine, NULL);
6536 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6537 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
6538 struct WS_sockaddr *lpFrom,
6539 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
6540 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
6541 LPWSABUF lpControlBuffer )
6543 unsigned int i, options;
6544 int n, fd, err, overlapped;
6545 struct ws2_async *wsa, localwsa;
6546 BOOL is_blocking;
6547 DWORD timeout_start = GetTickCount();
6548 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
6550 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
6551 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
6552 (lpFromlen ? *lpFromlen : -1),
6553 lpOverlapped, lpCompletionRoutine);
6555 fd = get_sock_fd( s, FILE_READ_DATA, &options );
6556 TRACE( "fd=%d, options=%x\n", fd, options );
6558 if (fd == -1) return SOCKET_ERROR;
6560 overlapped = (lpOverlapped || lpCompletionRoutine) &&
6561 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
6562 if (overlapped || dwBufferCount > 1)
6564 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
6566 err = WSAEFAULT;
6567 goto error;
6570 else
6571 wsa = &localwsa;
6573 wsa->hSocket = SOCKET2HANDLE(s);
6574 wsa->flags = *lpFlags;
6575 wsa->lpFlags = lpFlags;
6576 wsa->addr = lpFrom;
6577 wsa->addrlen.ptr = lpFromlen;
6578 wsa->control = lpControlBuffer;
6579 wsa->n_iovecs = dwBufferCount;
6580 wsa->first_iovec = 0;
6581 for (i = 0; i < dwBufferCount; i++)
6583 /* check buffer first to trigger write watches */
6584 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
6586 err = WSAEFAULT;
6587 goto error;
6589 wsa->iovec[i].iov_base = lpBuffers[i].buf;
6590 wsa->iovec[i].iov_len = lpBuffers[i].len;
6593 for (;;)
6595 n = WS2_recv( fd, wsa );
6596 if (n == -1)
6598 if (errno != EAGAIN)
6600 int loc_errno = errno;
6601 err = wsaErrno();
6602 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
6603 goto error;
6606 else if (lpNumberOfBytesRecvd) *lpNumberOfBytesRecvd = n;
6608 if (overlapped)
6610 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
6612 wsa->user_overlapped = lpOverlapped;
6613 wsa->completion_func = lpCompletionRoutine;
6614 release_sock_fd( s, fd );
6616 if (n == -1)
6618 iosb->u.Status = STATUS_PENDING;
6619 iosb->Information = 0;
6621 SERVER_START_REQ( register_async )
6623 req->type = ASYNC_TYPE_READ;
6624 req->async.handle = wine_server_obj_handle( wsa->hSocket );
6625 req->async.callback = wine_server_client_ptr( WS2_async_recv );
6626 req->async.iosb = wine_server_client_ptr( iosb );
6627 req->async.arg = wine_server_client_ptr( wsa );
6628 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
6629 req->async.cvalue = cvalue;
6630 err = wine_server_call( req );
6632 SERVER_END_REQ;
6634 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
6635 WSASetLastError( NtStatusToWSAError( err ));
6636 return SOCKET_ERROR;
6639 iosb->u.Status = STATUS_SUCCESS;
6640 iosb->Information = n;
6641 if (!wsa->completion_func)
6643 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
6644 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
6645 HeapFree( GetProcessHeap(), 0, wsa );
6647 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
6648 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
6649 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6650 return 0;
6653 if (n != -1) break;
6655 if ((err = _is_blocking( s, &is_blocking )))
6657 err = NtStatusToWSAError( err );
6658 goto error;
6661 if ( is_blocking )
6663 struct pollfd pfd;
6664 int timeout = GET_RCVTIMEO(fd);
6665 if (timeout != -1)
6667 timeout -= GetTickCount() - timeout_start;
6668 if (timeout < 0) timeout = 0;
6671 pfd.fd = fd;
6672 pfd.events = POLLIN;
6673 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
6675 if (!timeout || !poll( &pfd, 1, timeout ))
6677 err = WSAETIMEDOUT;
6678 /* a timeout is not fatal */
6679 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6680 goto error;
6683 else
6685 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6686 err = WSAEWOULDBLOCK;
6687 goto error;
6691 TRACE(" -> %i bytes\n", n);
6692 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
6693 release_sock_fd( s, fd );
6694 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6696 return 0;
6698 error:
6699 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
6700 release_sock_fd( s, fd );
6701 WARN(" -> ERROR %d\n", err);
6702 WSASetLastError( err );
6703 return SOCKET_ERROR;
6706 /***********************************************************************
6707 * WSARecvFrom (WS2_32.69)
6709 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6710 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
6711 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
6712 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
6715 return WS2_recv_base( s, lpBuffers, dwBufferCount,
6716 lpNumberOfBytesRecvd, lpFlags,
6717 lpFrom, lpFromlen,
6718 lpOverlapped, lpCompletionRoutine, NULL );
6721 /***********************************************************************
6722 * WSCInstallProvider (WS2_32.88)
6724 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
6725 LPCWSTR lpszProviderDllPath,
6726 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
6727 DWORD dwNumberOfEntries,
6728 LPINT lpErrno )
6730 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
6731 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
6732 dwNumberOfEntries, lpErrno);
6733 *lpErrno = 0;
6734 return 0;
6738 /***********************************************************************
6739 * WSCDeinstallProvider (WS2_32.83)
6741 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
6743 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
6744 *lpErrno = 0;
6745 return 0;
6749 /***********************************************************************
6750 * WSAAccept (WS2_32.26)
6752 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
6753 LPCONDITIONPROC lpfnCondition, DWORD_PTR dwCallbackData)
6756 int ret = 0, size;
6757 WSABUF CallerId, CallerData, CalleeId, CalleeData;
6758 /* QOS SQOS, GQOS; */
6759 GROUP g;
6760 SOCKET cs;
6761 SOCKADDR src_addr, dst_addr;
6763 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
6764 s, addr, addrlen, lpfnCondition, dwCallbackData);
6766 cs = WS_accept(s, addr, addrlen);
6767 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
6768 if (!lpfnCondition) return cs;
6770 if (addr && addrlen)
6772 CallerId.buf = (char *)addr;
6773 CallerId.len = *addrlen;
6775 else
6777 size = sizeof(src_addr);
6778 WS_getpeername(cs, &src_addr, &size);
6779 CallerId.buf = (char *)&src_addr;
6780 CallerId.len = size;
6782 CallerData.buf = NULL;
6783 CallerData.len = 0;
6785 size = sizeof(dst_addr);
6786 WS_getsockname(cs, &dst_addr, &size);
6788 CalleeId.buf = (char *)&dst_addr;
6789 CalleeId.len = sizeof(dst_addr);
6791 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
6792 &CalleeId, &CalleeData, &g, dwCallbackData);
6794 switch (ret)
6796 case CF_ACCEPT:
6797 return cs;
6798 case CF_DEFER:
6799 SERVER_START_REQ( set_socket_deferred )
6801 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6802 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
6803 if ( !wine_server_call_err ( req ) )
6805 SetLastError( WSATRY_AGAIN );
6806 WS_closesocket( cs );
6809 SERVER_END_REQ;
6810 return SOCKET_ERROR;
6811 case CF_REJECT:
6812 WS_closesocket(cs);
6813 SetLastError(WSAECONNREFUSED);
6814 return SOCKET_ERROR;
6815 default:
6816 FIXME("Unknown return type from Condition function\n");
6817 SetLastError(WSAENOTSOCK);
6818 return SOCKET_ERROR;
6822 /***********************************************************************
6823 * WSADuplicateSocketA (WS2_32.32)
6825 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
6827 return WS_DuplicateSocket(FALSE, s, dwProcessId, (LPWSAPROTOCOL_INFOW) lpProtocolInfo);
6830 /***********************************************************************
6831 * WSADuplicateSocketW (WS2_32.33)
6833 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
6835 return WS_DuplicateSocket(TRUE, s, dwProcessId, lpProtocolInfo);
6838 /***********************************************************************
6839 * WSAInstallServiceClassA (WS2_32.48)
6841 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
6843 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
6844 WSASetLastError(WSAEACCES);
6845 return SOCKET_ERROR;
6848 /***********************************************************************
6849 * WSAInstallServiceClassW (WS2_32.49)
6851 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
6853 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
6854 WSASetLastError(WSAEACCES);
6855 return SOCKET_ERROR;
6858 /***********************************************************************
6859 * WSARemoveServiceClass (WS2_32.70)
6861 int WINAPI WSARemoveServiceClass(LPGUID info)
6863 FIXME("Request to remove service %p\n",info);
6864 WSASetLastError(WSATYPE_NOT_FOUND);
6865 return SOCKET_ERROR;
6868 /***********************************************************************
6869 * inet_ntop (WS2_32.@)
6871 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
6873 #ifdef HAVE_INET_NTOP
6874 struct WS_in6_addr *in6;
6875 struct WS_in_addr *in;
6876 PCSTR pdst;
6878 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
6879 if (!buffer)
6881 WSASetLastError( STATUS_INVALID_PARAMETER );
6882 return NULL;
6885 switch (family)
6887 case WS_AF_INET:
6889 in = addr;
6890 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
6891 break;
6893 case WS_AF_INET6:
6895 in6 = addr;
6896 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
6897 break;
6899 default:
6900 WSASetLastError( WSAEAFNOSUPPORT );
6901 return NULL;
6904 if (!pdst) WSASetLastError( STATUS_INVALID_PARAMETER );
6905 return pdst;
6906 #else
6907 FIXME( "not supported on this platform\n" );
6908 WSASetLastError( WSAEAFNOSUPPORT );
6909 return NULL;
6910 #endif
6913 /***********************************************************************
6914 * inet_pton (WS2_32.@)
6916 INT WINAPI WS_inet_pton( INT family, PCSTR addr, PVOID buffer)
6918 #ifdef HAVE_INET_PTON
6919 int unixaf, ret;
6921 TRACE("family %d, addr '%s', buffer (%p)\n", family, addr ? addr : "(null)", buffer);
6923 if (!addr || !buffer)
6925 SetLastError(WSAEFAULT);
6926 return SOCKET_ERROR;
6929 unixaf = convert_af_w2u(family);
6930 if (unixaf != AF_INET && unixaf != AF_INET6)
6932 SetLastError(WSAEAFNOSUPPORT);
6933 return SOCKET_ERROR;
6936 ret = inet_pton(unixaf, addr, buffer);
6937 if (ret == -1) SetLastError(wsaErrno());
6938 return ret;
6939 #else
6940 FIXME( "not supported on this platform\n" );
6941 WSASetLastError( WSAEAFNOSUPPORT );
6942 return SOCKET_ERROR;
6943 #endif
6947 /***********************************************************************
6948 * WSAStringToAddressA (WS2_32.80)
6950 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
6951 INT AddressFamily,
6952 LPWSAPROTOCOL_INFOA lpProtocolInfo,
6953 LPSOCKADDR lpAddress,
6954 LPINT lpAddressLength)
6956 INT res=0;
6957 LPSTR workBuffer=NULL,ptrPort;
6959 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
6960 lpProtocolInfo, lpAddress, lpAddressLength );
6962 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
6964 if (!AddressString)
6966 WSASetLastError(WSAEINVAL);
6967 return SOCKET_ERROR;
6970 if (lpProtocolInfo)
6971 FIXME("ProtocolInfo not implemented.\n");
6973 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
6974 strlen(AddressString) + 1);
6975 if (!workBuffer)
6977 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6978 return SOCKET_ERROR;
6981 strcpy(workBuffer, AddressString);
6983 switch(AddressFamily)
6985 case WS_AF_INET:
6987 struct in_addr inetaddr;
6989 /* If lpAddressLength is too small, tell caller the size we need */
6990 if (*lpAddressLength < sizeof(SOCKADDR_IN))
6992 *lpAddressLength = sizeof(SOCKADDR_IN);
6993 res = WSAEFAULT;
6994 break;
6996 *lpAddressLength = sizeof(SOCKADDR_IN);
6997 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
6999 ((LPSOCKADDR_IN)lpAddress)->sin_family = WS_AF_INET;
7001 ptrPort = strchr(workBuffer, ':');
7002 if(ptrPort)
7004 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
7005 *ptrPort = '\0';
7007 else
7009 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
7012 if(inet_aton(workBuffer, &inetaddr) > 0)
7014 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
7015 res = 0;
7017 else
7018 res = WSAEINVAL;
7020 break;
7023 case WS_AF_INET6:
7025 struct in6_addr inetaddr;
7026 /* If lpAddressLength is too small, tell caller the size we need */
7027 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
7029 *lpAddressLength = sizeof(SOCKADDR_IN6);
7030 res = WSAEFAULT;
7031 break;
7033 #ifdef HAVE_INET_PTON
7034 *lpAddressLength = sizeof(SOCKADDR_IN6);
7035 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
7037 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
7039 /* This one is a bit tricky. An IPv6 address contains colons, so the
7040 * check from IPv4 doesn't work like that. However, IPv6 addresses that
7041 * contain a port are written with braces like [fd12:3456:7890::1]:12345
7042 * so what we will do is to look for ']', check if the next char is a
7043 * colon, and if it is, parse the port as in IPv4. */
7045 ptrPort = strchr(workBuffer, ']');
7046 if(ptrPort && *(++ptrPort) == ':')
7048 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort+1));
7049 *ptrPort = '\0';
7051 else
7053 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
7056 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
7058 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
7059 sizeof(struct in6_addr));
7060 res = 0;
7062 else
7063 #endif /* HAVE_INET_PTON */
7064 res = WSAEINVAL;
7066 break;
7068 default:
7069 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
7070 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
7071 res = WSAEINVAL;
7074 HeapFree(GetProcessHeap(), 0, workBuffer);
7076 if (!res) return 0;
7077 WSASetLastError(res);
7078 return SOCKET_ERROR;
7081 /***********************************************************************
7082 * WSAStringToAddressW (WS2_32.81)
7084 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
7085 * If this should be the case, it would be required to map these digits
7086 * to Unicode digits (0-9) using FoldString first.
7088 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
7089 INT AddressFamily,
7090 LPWSAPROTOCOL_INFOW lpProtocolInfo,
7091 LPSOCKADDR lpAddress,
7092 LPINT lpAddressLength)
7094 INT sBuffer,res=0;
7095 LPSTR workBuffer=NULL;
7096 WSAPROTOCOL_INFOA infoA;
7097 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
7099 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
7100 lpAddress, lpAddressLength );
7102 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
7104 /* if ProtocolInfo is available - convert to ANSI variant */
7105 if (lpProtocolInfo)
7107 lpProtoInfoA = &infoA;
7108 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
7110 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
7111 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
7113 WSASetLastError( WSAEINVAL);
7114 return SOCKET_ERROR;
7118 if (AddressString)
7120 /* Translate AddressString to ANSI code page - assumes that only
7121 standard digits 0-9 are used with this API call */
7122 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
7123 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
7125 if (workBuffer)
7127 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
7128 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
7129 lpAddress,lpAddressLength);
7130 HeapFree( GetProcessHeap(), 0, workBuffer );
7131 return res;
7133 else
7134 res = WSA_NOT_ENOUGH_MEMORY;
7136 else
7137 res = WSAEINVAL;
7139 WSASetLastError(res);
7140 return SOCKET_ERROR;
7143 /***********************************************************************
7144 * WSAAddressToStringA (WS2_32.27)
7146 * See WSAAddressToStringW
7148 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
7149 LPWSAPROTOCOL_INFOA info, LPSTR string,
7150 LPDWORD lenstr )
7152 DWORD size;
7153 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
7154 CHAR *p;
7156 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
7158 if (!sockaddr) return SOCKET_ERROR;
7159 if (!string || !lenstr) return SOCKET_ERROR;
7161 switch(sockaddr->sa_family)
7163 case WS_AF_INET:
7164 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
7165 sprintf( buffer, "%u.%u.%u.%u:%u",
7166 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
7167 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
7168 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
7169 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
7170 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
7172 p = strchr( buffer, ':' );
7173 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
7174 break;
7176 case WS_AF_INET6:
7178 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
7180 buffer[0] = 0;
7181 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
7182 if ((sockaddr6->sin6_port))
7183 strcpy(buffer, "[");
7184 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, buffer+strlen(buffer), sizeof(buffer)))
7186 WSASetLastError(WSAEINVAL);
7187 return SOCKET_ERROR;
7189 if ((sockaddr6->sin6_scope_id))
7190 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
7191 if ((sockaddr6->sin6_port))
7192 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
7193 break;
7196 default:
7197 WSASetLastError(WSAEINVAL);
7198 return SOCKET_ERROR;
7201 size = strlen( buffer ) + 1;
7203 if (*lenstr < size)
7205 *lenstr = size;
7206 WSASetLastError(WSAEFAULT);
7207 return SOCKET_ERROR;
7210 TRACE("=> %s,%u bytes\n", debugstr_a(buffer), size);
7211 *lenstr = size;
7212 strcpy( string, buffer );
7213 return 0;
7216 /***********************************************************************
7217 * WSAAddressToStringW (WS2_32.28)
7219 * Convert a sockaddr address into a readable address string.
7221 * PARAMS
7222 * sockaddr [I] Pointer to a sockaddr structure.
7223 * len [I] Size of the sockaddr structure.
7224 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
7225 * string [I/O] Pointer to a buffer to receive the address string.
7226 * lenstr [I/O] Size of the receive buffer in WCHARs.
7228 * RETURNS
7229 * Success: 0
7230 * Failure: SOCKET_ERROR
7232 * NOTES
7233 * The 'info' parameter is ignored.
7235 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
7236 LPWSAPROTOCOL_INFOW info, LPWSTR string,
7237 LPDWORD lenstr )
7239 INT ret;
7240 DWORD size;
7241 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
7242 CHAR bufAddr[54];
7244 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
7246 size = *lenstr;
7247 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
7249 if (ret) return ret;
7251 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
7253 if (*lenstr < size)
7255 *lenstr = size;
7256 WSASetLastError(WSAEFAULT);
7257 return SOCKET_ERROR;
7260 TRACE("=> %s,%u bytes\n", debugstr_w(buffer), size);
7261 *lenstr = size;
7262 lstrcpyW( string, buffer );
7263 return 0;
7266 /***********************************************************************
7267 * WSAEnumNameSpaceProvidersA (WS2_32.34)
7269 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
7271 FIXME( "(%p %p) Stub!\n", len, buffer );
7272 return 0;
7275 /***********************************************************************
7276 * WSAEnumNameSpaceProvidersW (WS2_32.35)
7278 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
7280 FIXME( "(%p %p) Stub!\n", len, buffer );
7281 return 0;
7284 /***********************************************************************
7285 * WSAGetQOSByName (WS2_32.41)
7287 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
7289 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
7290 return FALSE;
7293 /***********************************************************************
7294 * WSAGetServiceClassInfoA (WS2_32.42)
7296 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
7297 LPWSASERVICECLASSINFOA info )
7299 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
7300 len, info );
7301 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7302 return SOCKET_ERROR;
7305 /***********************************************************************
7306 * WSAGetServiceClassInfoW (WS2_32.43)
7308 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
7309 LPWSASERVICECLASSINFOW info )
7311 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
7312 len, info );
7313 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7314 return SOCKET_ERROR;
7317 /***********************************************************************
7318 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
7320 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
7322 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
7323 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7324 return SOCKET_ERROR;
7327 /***********************************************************************
7328 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
7330 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
7332 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
7333 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7334 return SOCKET_ERROR;
7337 /***********************************************************************
7338 * WSALookupServiceBeginA (WS2_32.59)
7340 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
7341 DWORD dwControlFlags,
7342 LPHANDLE lphLookup)
7344 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
7345 lphLookup);
7346 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7347 return SOCKET_ERROR;
7350 /***********************************************************************
7351 * WSALookupServiceBeginW (WS2_32.60)
7353 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
7354 DWORD dwControlFlags,
7355 LPHANDLE lphLookup)
7357 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
7358 lphLookup);
7359 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7360 return SOCKET_ERROR;
7363 /***********************************************************************
7364 * WSALookupServiceEnd (WS2_32.61)
7366 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
7368 FIXME("(%p) Stub!\n", lookup );
7369 return 0;
7372 /***********************************************************************
7373 * WSALookupServiceNextA (WS2_32.62)
7375 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
7377 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
7378 WSASetLastError(WSA_E_NO_MORE);
7379 return SOCKET_ERROR;
7382 /***********************************************************************
7383 * WSALookupServiceNextW (WS2_32.63)
7385 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
7387 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
7388 WSASetLastError(WSA_E_NO_MORE);
7389 return SOCKET_ERROR;
7392 /***********************************************************************
7393 * WSANtohl (WS2_32.64)
7395 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
7397 TRACE( "(0x%04lx 0x%08x %p)\n", s, netlong, lphostlong );
7399 if (!lphostlong) return WSAEFAULT;
7401 *lphostlong = ntohl( netlong );
7402 return 0;
7405 /***********************************************************************
7406 * WSANtohs (WS2_32.65)
7408 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
7410 TRACE( "(0x%04lx 0x%08x %p)\n", s, netshort, lphostshort );
7412 if (!lphostshort) return WSAEFAULT;
7414 *lphostshort = ntohs( netshort );
7415 return 0;
7418 /***********************************************************************
7419 * WSAProviderConfigChange (WS2_32.66)
7421 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
7422 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
7424 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
7425 return SOCKET_ERROR;
7428 /***********************************************************************
7429 * WSARecvDisconnect (WS2_32.68)
7431 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
7433 TRACE( "(0x%04lx %p)\n", s, disconnectdata );
7435 return WS_shutdown( s, SD_RECEIVE );
7438 /***********************************************************************
7439 * WSASetServiceA (WS2_32.76)
7441 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
7443 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
7444 return 0;
7447 /***********************************************************************
7448 * WSASetServiceW (WS2_32.77)
7450 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
7452 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
7453 return 0;
7456 /***********************************************************************
7457 * WSCEnableNSProvider (WS2_32.84)
7459 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
7461 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
7462 return 0;
7465 /***********************************************************************
7466 * WSCGetProviderPath (WS2_32.86)
7468 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
7470 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
7472 if (!errcode || !provider || !len) return WSAEFAULT;
7474 *errcode = WSAEINVAL;
7475 return SOCKET_ERROR;
7478 /***********************************************************************
7479 * WSCInstallNameSpace (WS2_32.87)
7481 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
7482 DWORD version, LPGUID provider )
7484 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
7485 namespace, version, debugstr_guid(provider) );
7486 return 0;
7489 /***********************************************************************
7490 * WSCUnInstallNameSpace (WS2_32.89)
7492 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
7494 FIXME("(%p) Stub!\n", lpProviderId);
7495 return NO_ERROR;
7498 /***********************************************************************
7499 * WSCWriteProviderOrder (WS2_32.91)
7501 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
7503 FIXME("(%p 0x%08x) Stub!\n", entry, number);
7504 return 0;
7507 /***********************************************************************
7508 * WSANSPIoctl (WS2_32.91)
7510 INT WINAPI WSANSPIoctl( HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer,
7511 DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer,
7512 LPDWORD lpcbBytesReturned, LPWSACOMPLETION lpCompletion )
7514 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup, dwControlCode,
7515 lpvInBuffer, cbInBuffer, lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpCompletion);
7516 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7517 return SOCKET_ERROR;
7520 /*****************************************************************************
7521 * WSAEnumProtocolsA [WS2_32.@]
7523 * see function WSAEnumProtocolsW
7525 INT WINAPI WSAEnumProtocolsA( LPINT protocols, LPWSAPROTOCOL_INFOA buffer, LPDWORD len )
7527 return WS_EnumProtocols( FALSE, protocols, (LPWSAPROTOCOL_INFOW) buffer, len);
7530 /*****************************************************************************
7531 * WSAEnumProtocolsW [WS2_32.@]
7533 * Retrieves information about specified set of active network protocols.
7535 * PARAMS
7536 * protocols [I] Pointer to null-terminated array of protocol id's. NULL
7537 * retrieves information on all available protocols.
7538 * buffer [I] Pointer to a buffer to be filled with WSAPROTOCOL_INFO
7539 * structures.
7540 * len [I/O] Pointer to a variable specifying buffer size. On output
7541 * the variable holds the number of bytes needed when the
7542 * specified size is too small.
7544 * RETURNS
7545 * Success: number of WSAPROTOCOL_INFO structures in buffer.
7546 * Failure: SOCKET_ERROR
7548 * NOTES
7549 * NT4SP5 does not return SPX if protocols == NULL
7551 * BUGS
7552 * - NT4SP5 returns in addition these list of NETBIOS protocols
7553 * (address family 17), each entry two times one for socket type 2 and 5
7555 * iProtocol szProtocol
7556 * 0x80000000 \Device\NwlnkNb
7557 * 0xfffffffa \Device\NetBT_CBENT7
7558 * 0xfffffffb \Device\Nbf_CBENT7
7559 * 0xfffffffc \Device\NetBT_NdisWan5
7560 * 0xfffffffd \Device\NetBT_El9202
7561 * 0xfffffffe \Device\Nbf_El9202
7562 * 0xffffffff \Device\Nbf_NdisWan4
7564 * - there is no check that the operating system supports the returned
7565 * protocols
7567 INT WINAPI WSAEnumProtocolsW( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
7569 return WS_EnumProtocols( TRUE, protocols, buffer, len);
7572 /*****************************************************************************
7573 * WSCEnumProtocols [WS2_32.@]
7575 * PARAMS
7576 * protocols [I] Null-terminated array of iProtocol values.
7577 * buffer [O] Buffer of WSAPROTOCOL_INFOW structures.
7578 * len [I/O] Size of buffer on input/output.
7579 * errno [O] Error code.
7581 * RETURNS
7582 * Success: number of protocols to be reported on.
7583 * Failure: SOCKET_ERROR. error is in errno.
7585 * BUGS
7586 * Doesn't supply info on layered protocols.
7589 INT WINAPI WSCEnumProtocols( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len, LPINT err )
7591 INT ret = WSAEnumProtocolsW( protocols, buffer, len );
7593 if (ret == SOCKET_ERROR) *err = WSAENOBUFS;
7595 return ret;