wininet: Added support for INTERNET_COOKIE_HTTPONLY flag to InternetSetCookieEx.
[wine/multimedia.git] / dlls / ws2_32 / socket.c
blob5900c8f51944d40ba9c0f5a4cfa9630d92d3ebb7
1 /*
2 * based on Windows Sockets 1.1 specs
4 * Copyright (C) 1993,1994,1996,1997 John Brezak, Erik Bos, Alex Korobka.
5 * Copyright (C) 2001 Stefan Leichter
6 * Copyright (C) 2004 Hans Leidekker
7 * Copyright (C) 2005 Marcus Meissner
8 * Copyright (C) 2006-2008 Kai Blin
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24 * NOTE: If you make any changes to fix a particular app, make sure
25 * they don't break something else like Netscape or telnet and ftp
26 * clients and servers (www.winsite.com got a lot of those).
29 #include "config.h"
30 #include "wine/port.h"
32 #include <stdarg.h>
33 #include <stdio.h>
34 #include <string.h>
35 #include <sys/types.h>
36 #ifdef HAVE_SYS_IPC_H
37 # include <sys/ipc.h>
38 #endif
39 #ifdef HAVE_SYS_IOCTL_H
40 # include <sys/ioctl.h>
41 #endif
42 #ifdef HAVE_SYS_FILIO_H
43 # include <sys/filio.h>
44 #endif
45 #ifdef HAVE_SYS_SOCKIO_H
46 # include <sys/sockio.h>
47 #endif
49 #if defined(__EMX__)
50 # include <sys/so_ioctl.h>
51 #endif
53 #ifdef HAVE_SYS_PARAM_H
54 # include <sys/param.h>
55 #endif
57 #ifdef HAVE_SYS_MSG_H
58 # include <sys/msg.h>
59 #endif
60 #ifdef HAVE_SYS_WAIT_H
61 # include <sys/wait.h>
62 #endif
63 #ifdef HAVE_SYS_UIO_H
64 # include <sys/uio.h>
65 #endif
66 #ifdef HAVE_SYS_SOCKET_H
67 #include <sys/socket.h>
68 #endif
69 #ifdef HAVE_NETINET_IN_H
70 # include <netinet/in.h>
71 #endif
72 #ifdef HAVE_NETINET_TCP_H
73 # include <netinet/tcp.h>
74 #endif
75 #ifdef HAVE_ARPA_INET_H
76 # include <arpa/inet.h>
77 #endif
78 #include <ctype.h>
79 #include <fcntl.h>
80 #include <errno.h>
81 #ifdef HAVE_NETDB_H
82 #include <netdb.h>
83 #endif
84 #ifdef HAVE_UNISTD_H
85 # include <unistd.h>
86 #endif
87 #include <stdlib.h>
88 #ifdef HAVE_ARPA_NAMESER_H
89 # include <arpa/nameser.h>
90 #endif
91 #ifdef HAVE_RESOLV_H
92 # include <resolv.h>
93 #endif
94 #ifdef HAVE_NET_IF_H
95 # include <net/if.h>
96 #endif
97 #ifdef HAVE_LINUX_FILTER_H
98 # include <linux/filter.h>
99 #endif
101 #ifdef HAVE_NETIPX_IPX_H
102 # include <netipx/ipx.h>
103 #elif defined(HAVE_LINUX_IPX_H)
104 # ifdef HAVE_ASM_TYPES_H
105 # include <asm/types.h>
106 # endif
107 # ifdef HAVE_LINUX_TYPES_H
108 # include <linux/types.h>
109 # endif
110 # include <linux/ipx.h>
111 #endif
112 #if defined(SOL_IPX) || defined(SO_DEFAULT_HEADERS)
113 # define HAS_IPX
114 #endif
116 #ifdef HAVE_LINUX_IRDA_H
117 # ifdef HAVE_LINUX_TYPES_H
118 # include <linux/types.h>
119 # endif
120 # include <linux/irda.h>
121 # define HAS_IRDA
122 #endif
124 #ifdef HAVE_POLL_H
125 #include <poll.h>
126 #endif
127 #ifdef HAVE_SYS_POLL_H
128 # include <sys/poll.h>
129 #endif
130 #ifdef HAVE_SYS_TIME_H
131 # include <sys/time.h>
132 #endif
134 #define NONAMELESSUNION
135 #define NONAMELESSSTRUCT
136 #include "ntstatus.h"
137 #define WIN32_NO_STATUS
138 #include "windef.h"
139 #include "winbase.h"
140 #include "wingdi.h"
141 #include "winuser.h"
142 #include "winerror.h"
143 #include "winnls.h"
144 #include "winsock2.h"
145 #include "mswsock.h"
146 #include "ws2tcpip.h"
147 #include "ws2spi.h"
148 #include "wsipx.h"
149 #include "wshisotp.h"
150 #include "mstcpip.h"
151 #include "af_irda.h"
152 #include "winnt.h"
153 #define USE_WC_PREFIX /* For CMSG_DATA */
154 #include "iphlpapi.h"
155 #include "wine/server.h"
156 #include "wine/debug.h"
157 #include "wine/exception.h"
158 #include "wine/unicode.h"
160 #ifdef HAS_IPX
161 # include "wsnwlink.h"
162 #endif
164 #if defined(linux) && !defined(IP_UNICAST_IF)
165 #define IP_UNICAST_IF 50
166 #endif
168 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
169 # define sipx_network sipx_addr.x_net
170 # define sipx_node sipx_addr.x_host.c_host
171 #endif /* __FreeBSD__ */
173 #ifndef INADDR_NONE
174 #define INADDR_NONE ~0UL
175 #endif
177 WINE_DEFAULT_DEBUG_CHANNEL(winsock);
178 WINE_DECLARE_DEBUG_CHANNEL(winediag);
180 /* names of the protocols */
181 static const WCHAR NameIpxW[] = {'I', 'P', 'X', '\0'};
182 static const WCHAR NameSpxW[] = {'S', 'P', 'X', '\0'};
183 static const WCHAR NameSpxIIW[] = {'S', 'P', 'X', ' ', 'I', 'I', '\0'};
184 static const WCHAR NameTcpW[] = {'T', 'C', 'P', '/', 'I', 'P', '\0'};
185 static const WCHAR NameUdpW[] = {'U', 'D', 'P', '/', 'I', 'P', '\0'};
187 /* Taken from Win2k */
188 static const GUID ProviderIdIP = { 0xe70f1aa0, 0xab8b, 0x11cf,
189 { 0x8c, 0xa3, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
190 static const GUID ProviderIdIPX = { 0x11058240, 0xbe47, 0x11cf,
191 { 0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
192 static const GUID ProviderIdSPX = { 0x11058241, 0xbe47, 0x11cf,
193 { 0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
195 static const INT valid_protocols[] =
197 WS_IPPROTO_TCP,
198 WS_IPPROTO_UDP,
199 WS_NSPROTO_IPX,
200 WS_NSPROTO_SPX,
201 WS_NSPROTO_SPXII,
205 #define IS_IPX_PROTO(X) ((X) >= WS_NSPROTO_IPX && (X) <= WS_NSPROTO_IPX + 255)
207 #if defined(IP_UNICAST_IF) && defined(SO_ATTACH_FILTER)
208 # define LINUX_BOUND_IF
209 struct interface_filter {
210 struct sock_filter iface_memaddr;
211 struct sock_filter iface_rule;
212 struct sock_filter ip_memaddr;
213 struct sock_filter ip_rule;
214 struct sock_filter return_keep;
215 struct sock_filter return_dump;
217 # define FILTER_JUMP_DUMP(here) (u_char)(offsetof(struct interface_filter, return_dump) \
218 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
219 /sizeof(struct sock_filter)
220 # define FILTER_JUMP_KEEP(here) (u_char)(offsetof(struct interface_filter, return_keep) \
221 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
222 /sizeof(struct sock_filter)
223 # define FILTER_JUMP_NEXT() (u_char)(0)
224 # define SKF_NET_DESTIP 16 /* offset in the network header to the destination IP */
225 static struct interface_filter generic_interface_filter = {
226 /* This filter rule allows incoming packets on the specified interface, which works for all
227 * remotely generated packets and for locally generated broadcast packets. */
228 BPF_STMT(BPF_LD+BPF_W+BPF_ABS, SKF_AD_OFF+SKF_AD_IFINDEX),
229 BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0xdeadbeef, FILTER_JUMP_KEEP(iface_rule), FILTER_JUMP_NEXT()),
230 /* This rule allows locally generated packets targeted at the specific IP address of the chosen
231 * adapter (local packets not destined for the broadcast address do not have IFINDEX set) */
232 BPF_STMT(BPF_LD+BPF_W+BPF_ABS, SKF_NET_OFF+SKF_NET_DESTIP),
233 BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0xdeadbeef, FILTER_JUMP_KEEP(ip_rule), FILTER_JUMP_DUMP(ip_rule)),
234 BPF_STMT(BPF_RET+BPF_K, (u_int)-1), /* keep packet */
235 BPF_STMT(BPF_RET+BPF_K, 0) /* dump packet */
237 #endif /* LINUX_BOUND_IF */
240 * The actual definition of WSASendTo, wrapped in a different function name
241 * so that internal calls from ws2_32 itself will not trigger programs like
242 * Garena, which hooks WSASendTo/WSARecvFrom calls.
244 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
245 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
246 const struct WS_sockaddr *to, int tolen,
247 LPWSAOVERLAPPED lpOverlapped,
248 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine );
251 * Internal fundamental receive function, essentially WSARecvFrom with an
252 * additional parameter to support message control headers.
254 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
255 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
256 struct WS_sockaddr *lpFrom,
257 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
258 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
259 LPWSABUF lpControlBuffer );
261 /* critical section to protect some non-reentrant net function */
262 static CRITICAL_SECTION csWSgetXXXbyYYY;
263 static CRITICAL_SECTION_DEBUG critsect_debug =
265 0, 0, &csWSgetXXXbyYYY,
266 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
267 0, 0, { (DWORD_PTR)(__FILE__ ": csWSgetXXXbyYYY") }
269 static CRITICAL_SECTION csWSgetXXXbyYYY = { &critsect_debug, -1, 0, 0, 0, 0 };
271 union generic_unix_sockaddr
273 struct sockaddr addr;
274 char data[128]; /* should be big enough for all families */
277 static inline const char *debugstr_sockaddr( const struct WS_sockaddr *a )
279 if (!a) return "(nil)";
280 switch (a->sa_family)
282 case WS_AF_INET:
283 return wine_dbg_sprintf("{ family AF_INET, address %s, port %d }",
284 inet_ntoa(((const struct sockaddr_in *)a)->sin_addr),
285 ntohs(((const struct sockaddr_in *)a)->sin_port));
286 case WS_AF_INET6:
288 char buf[46];
289 const char *p;
290 struct WS_sockaddr_in6 *sin = (struct WS_sockaddr_in6 *)a;
292 p = WS_inet_ntop( WS_AF_INET6, &sin->sin6_addr, buf, sizeof(buf) );
293 if (!p)
294 p = "(unknown IPv6 address)";
295 return wine_dbg_sprintf("{ family AF_INET6, address %s, port %d }",
296 p, ntohs(sin->sin6_port));
298 case WS_AF_IPX:
300 int i;
301 char netnum[16], nodenum[16];
302 struct WS_sockaddr_ipx *sin = (struct WS_sockaddr_ipx *)a;
304 for (i = 0;i < 4; i++) sprintf(netnum + i * 2, "%02X", (unsigned char) sin->sa_netnum[i]);
305 for (i = 0;i < 6; i++) sprintf(nodenum + i * 2, "%02X", (unsigned char) sin->sa_nodenum[i]);
307 return wine_dbg_sprintf("{ family AF_IPX, address %s.%s, ipx socket %d }",
308 netnum, nodenum, sin->sa_socket);
310 case WS_AF_IRDA:
312 DWORD addr;
314 memcpy( &addr, ((const SOCKADDR_IRDA *)a)->irdaDeviceID, sizeof(addr) );
315 addr = ntohl( addr );
316 return wine_dbg_sprintf("{ family AF_IRDA, addr %08x, name %s }",
317 addr,
318 ((const SOCKADDR_IRDA *)a)->irdaServiceName);
320 default:
321 return wine_dbg_sprintf("{ family %d }", a->sa_family);
325 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
326 #define SOCKET2HANDLE(s) ((HANDLE)(s))
327 #define HANDLE2SOCKET(h) ((SOCKET)(h))
329 /****************************************************************
330 * Async IO declarations
331 ****************************************************************/
333 typedef struct ws2_async
335 HANDLE hSocket;
336 int type;
337 LPWSAOVERLAPPED user_overlapped;
338 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
339 IO_STATUS_BLOCK local_iosb;
340 struct WS_sockaddr *addr;
341 union
343 int val; /* for send operations */
344 int *ptr; /* for recv operations */
345 } addrlen;
346 DWORD flags;
347 DWORD *lpFlags;
348 WSABUF *control;
349 unsigned int n_iovecs;
350 unsigned int first_iovec;
351 struct iovec iovec[1];
352 } ws2_async;
354 typedef struct ws2_accept_async
356 HANDLE listen_socket;
357 HANDLE accept_socket;
358 LPOVERLAPPED user_overlapped;
359 ULONG_PTR cvalue;
360 PVOID buf; /* buffer to write data to */
361 int data_len;
362 int local_len;
363 int remote_len;
364 struct ws2_async *read;
365 } ws2_accept_async;
367 /****************************************************************/
369 /* ----------------------------------- internal data */
371 /* ws_... struct conversion flags */
373 typedef struct /* WSAAsyncSelect() control struct */
375 HANDLE service, event, sock;
376 HWND hWnd;
377 UINT uMsg;
378 LONG lEvent;
379 } ws_select_info;
381 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
382 #define WS_MAX_UDP_DATAGRAM 1024
383 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
385 /* hostent's, servent's and protent's are stored in one buffer per thread,
386 * as documented on MSDN for the functions that return any of the buffers */
387 struct per_thread_data
389 int opentype;
390 struct WS_hostent *he_buffer;
391 struct WS_servent *se_buffer;
392 struct WS_protoent *pe_buffer;
393 int he_len;
394 int se_len;
395 int pe_len;
396 char ntoa_buffer[16]; /* 4*3 digits + 3 '.' + 1 '\0' */
399 /* internal: routing description information */
400 struct route {
401 struct in_addr addr;
402 IF_INDEX interface;
403 DWORD metric;
406 static INT num_startup; /* reference counter */
407 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
409 /* function prototypes */
410 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length);
411 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
412 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
413 static struct WS_servent *WS_dup_se(const struct servent* p_se);
414 static int ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size);
416 int WSAIOCTL_GetInterfaceCount(void);
417 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
419 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus, ULONG Information );
421 #define MAP_OPTION(opt) { WS_##opt, opt }
423 static const int ws_sock_map[][2] =
425 MAP_OPTION( SO_DEBUG ),
426 MAP_OPTION( SO_ACCEPTCONN ),
427 MAP_OPTION( SO_REUSEADDR ),
428 MAP_OPTION( SO_KEEPALIVE ),
429 MAP_OPTION( SO_DONTROUTE ),
430 MAP_OPTION( SO_BROADCAST ),
431 MAP_OPTION( SO_LINGER ),
432 MAP_OPTION( SO_OOBINLINE ),
433 MAP_OPTION( SO_SNDBUF ),
434 MAP_OPTION( SO_RCVBUF ),
435 MAP_OPTION( SO_ERROR ),
436 MAP_OPTION( SO_TYPE ),
437 #ifdef SO_RCVTIMEO
438 MAP_OPTION( SO_RCVTIMEO ),
439 #endif
440 #ifdef SO_SNDTIMEO
441 MAP_OPTION( SO_SNDTIMEO ),
442 #endif
445 static const int ws_tcp_map[][2] =
447 #ifdef TCP_NODELAY
448 MAP_OPTION( TCP_NODELAY ),
449 #endif
452 static const int ws_ip_map[][2] =
454 MAP_OPTION( IP_MULTICAST_IF ),
455 MAP_OPTION( IP_MULTICAST_TTL ),
456 MAP_OPTION( IP_MULTICAST_LOOP ),
457 MAP_OPTION( IP_ADD_MEMBERSHIP ),
458 MAP_OPTION( IP_DROP_MEMBERSHIP ),
459 MAP_OPTION( IP_OPTIONS ),
460 #ifdef IP_HDRINCL
461 MAP_OPTION( IP_HDRINCL ),
462 #endif
463 MAP_OPTION( IP_TOS ),
464 MAP_OPTION( IP_TTL ),
465 #ifdef IP_PKTINFO
466 MAP_OPTION( IP_PKTINFO ),
467 #endif
468 #ifdef IP_UNICAST_IF
469 MAP_OPTION( IP_UNICAST_IF ),
470 #endif
473 static const int ws_ipv6_map[][2] =
475 #ifdef IPV6_ADD_MEMBERSHIP
476 MAP_OPTION( IPV6_ADD_MEMBERSHIP ),
477 #endif
478 #ifdef IPV6_DROP_MEMBERSHIP
479 MAP_OPTION( IPV6_DROP_MEMBERSHIP ),
480 #endif
481 MAP_OPTION( IPV6_MULTICAST_IF ),
482 MAP_OPTION( IPV6_MULTICAST_HOPS ),
483 MAP_OPTION( IPV6_MULTICAST_LOOP ),
484 MAP_OPTION( IPV6_UNICAST_HOPS ),
485 MAP_OPTION( IPV6_V6ONLY ),
486 #ifdef IPV6_UNICAST_IF
487 MAP_OPTION( IPV6_UNICAST_IF ),
488 #endif
491 static const int ws_af_map[][2] =
493 MAP_OPTION( AF_UNSPEC ),
494 MAP_OPTION( AF_INET ),
495 MAP_OPTION( AF_INET6 ),
496 #ifdef HAS_IPX
497 MAP_OPTION( AF_IPX ),
498 #endif
499 #ifdef AF_IRDA
500 MAP_OPTION( AF_IRDA ),
501 #endif
502 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
505 static const int ws_socktype_map[][2] =
507 MAP_OPTION( SOCK_DGRAM ),
508 MAP_OPTION( SOCK_STREAM ),
509 MAP_OPTION( SOCK_RAW ),
510 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
513 static const int ws_proto_map[][2] =
515 MAP_OPTION( IPPROTO_IP ),
516 MAP_OPTION( IPPROTO_TCP ),
517 MAP_OPTION( IPPROTO_UDP ),
518 MAP_OPTION( IPPROTO_ICMP ),
519 MAP_OPTION( IPPROTO_IGMP ),
520 MAP_OPTION( IPPROTO_RAW ),
521 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
524 static const int ws_aiflag_map[][2] =
526 MAP_OPTION( AI_PASSIVE ),
527 MAP_OPTION( AI_CANONNAME ),
528 MAP_OPTION( AI_NUMERICHOST ),
529 #ifdef AI_NUMERICSERV
530 MAP_OPTION( AI_NUMERICSERV ),
531 #endif
532 MAP_OPTION( AI_V4MAPPED ),
533 MAP_OPTION( AI_ADDRCONFIG ),
536 static const int ws_niflag_map[][2] =
538 MAP_OPTION( NI_NOFQDN ),
539 MAP_OPTION( NI_NUMERICHOST ),
540 MAP_OPTION( NI_NAMEREQD ),
541 MAP_OPTION( NI_NUMERICSERV ),
542 MAP_OPTION( NI_DGRAM ),
545 static const int ws_eai_map[][2] =
547 MAP_OPTION( EAI_AGAIN ),
548 MAP_OPTION( EAI_BADFLAGS ),
549 MAP_OPTION( EAI_FAIL ),
550 MAP_OPTION( EAI_FAMILY ),
551 MAP_OPTION( EAI_MEMORY ),
552 /* Note: EAI_NODATA is deprecated, but still
553 * used by Windows and Linux... We map the newer
554 * EAI_NONAME to EAI_NODATA for now until Windows
555 * changes too.
557 #ifdef EAI_NODATA
558 MAP_OPTION( EAI_NODATA ),
559 #endif
560 #ifdef EAI_NONAME
561 { WS_EAI_NODATA, EAI_NONAME },
562 #endif
564 MAP_OPTION( EAI_SERVICE ),
565 MAP_OPTION( EAI_SOCKTYPE ),
566 { 0, 0 }
569 static const char magic_loopback_addr[] = {127, 12, 34, 56};
571 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
572 static inline WSACMSGHDR *fill_control_message(int level, int type, WSACMSGHDR *current, ULONG *maxsize, void *data, int len)
574 ULONG msgsize = sizeof(WSACMSGHDR) + WSA_CMSG_ALIGN(len);
575 char *ptr = (char *) current + sizeof(WSACMSGHDR);
577 /* Make sure there is at least enough room for this entry */
578 if (msgsize > *maxsize)
579 return NULL;
580 *maxsize -= msgsize;
581 /* Fill in the entry */
582 current->cmsg_len = sizeof(WSACMSGHDR) + len;
583 current->cmsg_level = level;
584 current->cmsg_type = type;
585 memcpy(ptr, data, len);
586 /* Return the pointer to where next entry should go */
587 return (WSACMSGHDR *) (ptr + WSA_CMSG_ALIGN(len));
590 static inline int convert_control_headers(struct msghdr *hdr, WSABUF *control)
592 #ifdef IP_PKTINFO
593 WSACMSGHDR *cmsg_win = (WSACMSGHDR *) control->buf, *ptr;
594 ULONG ctlsize = control->len;
595 struct cmsghdr *cmsg_unix;
597 ptr = cmsg_win;
598 /* Loop over all the headers, converting as appropriate */
599 for (cmsg_unix = CMSG_FIRSTHDR(hdr); cmsg_unix != NULL; cmsg_unix = CMSG_NXTHDR(hdr, cmsg_unix))
601 switch(cmsg_unix->cmsg_level)
603 case IPPROTO_IP:
604 switch(cmsg_unix->cmsg_type)
606 case IP_PKTINFO:
608 /* Convert the Unix IP_PKTINFO structure to the Windows version */
609 struct in_pktinfo *data_unix = (struct in_pktinfo *) CMSG_DATA(cmsg_unix);
610 struct WS_in_pktinfo data_win;
612 memcpy(&data_win.ipi_addr,&data_unix->ipi_addr.s_addr,4); /* 4 bytes = 32 address bits */
613 data_win.ipi_ifindex = data_unix->ipi_ifindex;
614 ptr = fill_control_message(WS_IPPROTO_IP, WS_IP_PKTINFO, ptr, &ctlsize,
615 (void*)&data_win, sizeof(data_win));
616 if (!ptr) goto error;
617 } break;
618 default:
619 FIXME("Unhandled IPPROTO_IP message header type %d\n", cmsg_unix->cmsg_type);
620 break;
622 break;
623 default:
624 FIXME("Unhandled message header level %d\n", cmsg_unix->cmsg_level);
625 break;
629 error:
630 /* Set the length of the returned control headers */
631 control->len = (ptr == NULL ? 0 : (char*)ptr - (char*)cmsg_win);
632 return (ptr != NULL);
633 #else /* IP_PKTINFO */
634 control->len = 0;
635 return 1;
636 #endif /* IP_PKTINFO */
638 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
640 /* ----------------------------------- error handling */
642 static NTSTATUS sock_get_ntstatus( int err )
644 switch ( err )
646 case EBADF: return STATUS_INVALID_HANDLE;
647 case EBUSY: return STATUS_DEVICE_BUSY;
648 case EPERM:
649 case EACCES: return STATUS_ACCESS_DENIED;
650 case EFAULT: return STATUS_NO_MEMORY;
651 case EINVAL: return STATUS_INVALID_PARAMETER;
652 case ENFILE:
653 case EMFILE: return STATUS_TOO_MANY_OPENED_FILES;
654 case EWOULDBLOCK: return STATUS_CANT_WAIT;
655 case EINPROGRESS: return STATUS_PENDING;
656 case EALREADY: return STATUS_NETWORK_BUSY;
657 case ENOTSOCK: return STATUS_OBJECT_TYPE_MISMATCH;
658 case EDESTADDRREQ: return STATUS_INVALID_PARAMETER;
659 case EMSGSIZE: return STATUS_BUFFER_OVERFLOW;
660 case EPROTONOSUPPORT:
661 case ESOCKTNOSUPPORT:
662 case EPFNOSUPPORT:
663 case EAFNOSUPPORT:
664 case EPROTOTYPE: return STATUS_NOT_SUPPORTED;
665 case ENOPROTOOPT: return STATUS_INVALID_PARAMETER;
666 case EOPNOTSUPP: return STATUS_NOT_SUPPORTED;
667 case EADDRINUSE: return STATUS_ADDRESS_ALREADY_ASSOCIATED;
668 case EADDRNOTAVAIL: return STATUS_INVALID_PARAMETER;
669 case ECONNREFUSED: return STATUS_CONNECTION_REFUSED;
670 case ESHUTDOWN: return STATUS_PIPE_DISCONNECTED;
671 case ENOTCONN: return STATUS_CONNECTION_DISCONNECTED;
672 case ETIMEDOUT: return STATUS_IO_TIMEOUT;
673 case ENETUNREACH: return STATUS_NETWORK_UNREACHABLE;
674 case ENETDOWN: return STATUS_NETWORK_BUSY;
675 case EPIPE:
676 case ECONNRESET: return STATUS_CONNECTION_RESET;
677 case ECONNABORTED: return STATUS_CONNECTION_ABORTED;
679 case 0: return STATUS_SUCCESS;
680 default:
681 WARN("Unknown errno %d!\n", err);
682 return STATUS_UNSUCCESSFUL;
686 static UINT sock_get_error( int err )
688 switch(err)
690 case EINTR: return WSAEINTR;
691 case EBADF: return WSAEBADF;
692 case EPERM:
693 case EACCES: return WSAEACCES;
694 case EFAULT: return WSAEFAULT;
695 case EINVAL: return WSAEINVAL;
696 case EMFILE: return WSAEMFILE;
697 case EWOULDBLOCK: return WSAEWOULDBLOCK;
698 case EINPROGRESS: return WSAEINPROGRESS;
699 case EALREADY: return WSAEALREADY;
700 case ENOTSOCK: return WSAENOTSOCK;
701 case EDESTADDRREQ: return WSAEDESTADDRREQ;
702 case EMSGSIZE: return WSAEMSGSIZE;
703 case EPROTOTYPE: return WSAEPROTOTYPE;
704 case ENOPROTOOPT: return WSAENOPROTOOPT;
705 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
706 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
707 case EOPNOTSUPP: return WSAEOPNOTSUPP;
708 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
709 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
710 case EADDRINUSE: return WSAEADDRINUSE;
711 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
712 case ENETDOWN: return WSAENETDOWN;
713 case ENETUNREACH: return WSAENETUNREACH;
714 case ENETRESET: return WSAENETRESET;
715 case ECONNABORTED: return WSAECONNABORTED;
716 case EPIPE:
717 case ECONNRESET: return WSAECONNRESET;
718 case ENOBUFS: return WSAENOBUFS;
719 case EISCONN: return WSAEISCONN;
720 case ENOTCONN: return WSAENOTCONN;
721 case ESHUTDOWN: return WSAESHUTDOWN;
722 case ETOOMANYREFS: return WSAETOOMANYREFS;
723 case ETIMEDOUT: return WSAETIMEDOUT;
724 case ECONNREFUSED: return WSAECONNREFUSED;
725 case ELOOP: return WSAELOOP;
726 case ENAMETOOLONG: return WSAENAMETOOLONG;
727 case EHOSTDOWN: return WSAEHOSTDOWN;
728 case EHOSTUNREACH: return WSAEHOSTUNREACH;
729 case ENOTEMPTY: return WSAENOTEMPTY;
730 #ifdef EPROCLIM
731 case EPROCLIM: return WSAEPROCLIM;
732 #endif
733 #ifdef EUSERS
734 case EUSERS: return WSAEUSERS;
735 #endif
736 #ifdef EDQUOT
737 case EDQUOT: return WSAEDQUOT;
738 #endif
739 #ifdef ESTALE
740 case ESTALE: return WSAESTALE;
741 #endif
742 #ifdef EREMOTE
743 case EREMOTE: return WSAEREMOTE;
744 #endif
746 /* just in case we ever get here and there are no problems */
747 case 0: return 0;
748 default:
749 WARN("Unknown errno %d!\n", err);
750 return WSAEOPNOTSUPP;
754 static UINT wsaErrno(void)
756 int loc_errno = errno;
757 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
759 return sock_get_error( loc_errno );
762 /* most ws2 overlapped functions return an ntstatus-based error code */
763 static NTSTATUS wsaErrStatus(void)
765 int loc_errno = errno;
766 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
768 return sock_get_ntstatus(loc_errno);
771 static UINT wsaHerrno(int loc_errno)
773 WARN("h_errno %d.\n", loc_errno);
775 switch(loc_errno)
777 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
778 case TRY_AGAIN: return WSATRY_AGAIN;
779 case NO_RECOVERY: return WSANO_RECOVERY;
780 case NO_DATA: return WSANO_DATA;
781 case ENOBUFS: return WSAENOBUFS;
783 case 0: return 0;
784 default:
785 WARN("Unknown h_errno %d!\n", loc_errno);
786 return WSAEOPNOTSUPP;
790 static inline DWORD NtStatusToWSAError( const DWORD status )
792 /* We only need to cover the status codes set by server async request handling */
793 DWORD wserr;
794 switch ( status )
796 case STATUS_SUCCESS: wserr = 0; break;
797 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
798 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
799 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
800 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
801 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
802 case STATUS_NETWORK_BUSY: wserr = WSAEALREADY; break;
803 case STATUS_NETWORK_UNREACHABLE: wserr = WSAENETUNREACH; break;
804 case STATUS_CONNECTION_REFUSED: wserr = WSAECONNREFUSED; break;
805 case STATUS_CONNECTION_DISCONNECTED: wserr = WSAENOTCONN; break;
806 case STATUS_CONNECTION_RESET: wserr = WSAECONNRESET; break;
807 case STATUS_CONNECTION_ABORTED: wserr = WSAECONNABORTED; break;
808 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
809 case STATUS_ADDRESS_ALREADY_ASSOCIATED: wserr = WSAEADDRINUSE; break;
810 case STATUS_IO_TIMEOUT:
811 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
812 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
813 case STATUS_ACCESS_DENIED: wserr = WSAEACCES; break;
814 case STATUS_TOO_MANY_OPENED_FILES: wserr = WSAEMFILE; break;
815 case STATUS_CANT_WAIT: wserr = WSAEWOULDBLOCK; break;
816 case STATUS_BUFFER_OVERFLOW: wserr = WSAEMSGSIZE; break;
817 case STATUS_NOT_SUPPORTED: wserr = WSAEOPNOTSUPP; break;
818 case STATUS_HOST_UNREACHABLE: wserr = WSAEHOSTUNREACH; break;
820 default:
821 wserr = RtlNtStatusToDosError( status );
822 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
824 return wserr;
827 /* set last error code from NT status without mapping WSA errors */
828 static inline unsigned int set_error( unsigned int err )
830 if (err)
832 err = NtStatusToWSAError( err );
833 SetLastError( err );
835 return err;
838 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
840 int fd;
841 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
842 return -1;
843 return fd;
846 static inline void release_sock_fd( SOCKET s, int fd )
848 wine_server_release_fd( SOCKET2HANDLE(s), fd );
851 static void _enable_event( HANDLE s, unsigned int event,
852 unsigned int sstate, unsigned int cstate )
854 SERVER_START_REQ( enable_socket_event )
856 req->handle = wine_server_obj_handle( s );
857 req->mask = event;
858 req->sstate = sstate;
859 req->cstate = cstate;
860 wine_server_call( req );
862 SERVER_END_REQ;
865 static NTSTATUS _is_blocking(SOCKET s, BOOL *ret)
867 NTSTATUS status;
868 SERVER_START_REQ( get_socket_event )
870 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
871 req->service = FALSE;
872 req->c_event = 0;
873 status = wine_server_call( req );
874 *ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
876 SERVER_END_REQ;
877 return status;
880 static unsigned int _get_sock_mask(SOCKET s)
882 unsigned int ret;
883 SERVER_START_REQ( get_socket_event )
885 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
886 req->service = FALSE;
887 req->c_event = 0;
888 wine_server_call( req );
889 ret = reply->mask;
891 SERVER_END_REQ;
892 return ret;
895 static void _sync_sock_state(SOCKET s)
897 BOOL dummy;
898 /* do a dummy wineserver request in order to let
899 the wineserver run through its select loop once */
900 (void)_is_blocking(s, &dummy);
903 static int _get_sock_error(SOCKET s, unsigned int bit)
905 int events[FD_MAX_EVENTS];
907 SERVER_START_REQ( get_socket_event )
909 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
910 req->service = FALSE;
911 req->c_event = 0;
912 wine_server_set_reply( req, events, sizeof(events) );
913 wine_server_call( req );
915 SERVER_END_REQ;
916 return events[bit];
919 static struct per_thread_data *get_per_thread_data(void)
921 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
922 /* lazy initialization */
923 if (!ptb)
925 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
926 NtCurrentTeb()->WinSockData = ptb;
928 return ptb;
931 static void free_per_thread_data(void)
933 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
935 if (!ptb) return;
937 /* delete scratch buffers */
938 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
939 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
940 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
941 ptb->he_buffer = NULL;
942 ptb->se_buffer = NULL;
943 ptb->pe_buffer = NULL;
945 HeapFree( GetProcessHeap(), 0, ptb );
946 NtCurrentTeb()->WinSockData = NULL;
949 /***********************************************************************
950 * DllMain (WS2_32.init)
952 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
954 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
955 switch (fdwReason) {
956 case DLL_PROCESS_ATTACH:
957 break;
958 case DLL_PROCESS_DETACH:
959 if (fImpLoad) break;
960 free_per_thread_data();
961 DeleteCriticalSection(&csWSgetXXXbyYYY);
962 break;
963 case DLL_THREAD_DETACH:
964 free_per_thread_data();
965 break;
967 return TRUE;
970 /***********************************************************************
971 * convert_sockopt()
973 * Converts socket flags from Windows format.
974 * Return 1 if converted, 0 if not (error).
976 static int convert_sockopt(INT *level, INT *optname)
978 unsigned int i;
979 switch (*level)
981 case WS_SOL_SOCKET:
982 *level = SOL_SOCKET;
983 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
984 if( ws_sock_map[i][0] == *optname )
986 *optname = ws_sock_map[i][1];
987 return 1;
990 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
991 break;
992 case WS_IPPROTO_TCP:
993 *level = IPPROTO_TCP;
994 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
995 if ( ws_tcp_map[i][0] == *optname )
997 *optname = ws_tcp_map[i][1];
998 return 1;
1001 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
1002 break;
1003 case WS_IPPROTO_IP:
1004 *level = IPPROTO_IP;
1005 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
1006 if (ws_ip_map[i][0] == *optname )
1008 *optname = ws_ip_map[i][1];
1009 return 1;
1012 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
1013 break;
1014 case WS_IPPROTO_IPV6:
1015 *level = IPPROTO_IPV6;
1016 for(i=0; i<sizeof(ws_ipv6_map)/sizeof(ws_ipv6_map[0]); i++) {
1017 if (ws_ipv6_map[i][0] == *optname )
1019 *optname = ws_ipv6_map[i][1];
1020 return 1;
1023 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname);
1024 break;
1025 default: FIXME("Unimplemented or unknown socket level\n");
1027 return 0;
1030 /* ----------------------------------- Per-thread info (or per-process?) */
1032 static char *strdup_lower(const char *str)
1034 int i;
1035 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
1037 if (ret)
1039 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
1040 ret[i] = 0;
1042 else SetLastError(WSAENOBUFS);
1043 return ret;
1046 static inline int sock_error_p(int s)
1048 unsigned int optval;
1049 socklen_t optlen = sizeof(optval);
1050 getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
1051 if (optval) WARN("\t[%i] error: %d\n", s, optval);
1052 return optval != 0;
1055 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
1056 * from an fd and return the value converted to milli seconds
1057 * or -1 if there is an infinite time out */
1058 static inline int get_rcvsnd_timeo( int fd, int optname)
1060 struct timeval tv;
1061 socklen_t len = sizeof(tv);
1062 int ret = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
1063 if( ret >= 0)
1064 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
1065 if( ret <= 0 ) /* tv == {0,0} means infinite time out */
1066 return -1;
1067 return ret;
1070 /* macro wrappers for portability */
1071 #ifdef SO_RCVTIMEO
1072 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
1073 #else
1074 #define GET_RCVTIMEO(fd) (-1)
1075 #endif
1077 #ifdef SO_SNDTIMEO
1078 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
1079 #else
1080 #define GET_SNDTIMEO(fd) (-1)
1081 #endif
1083 /* utility: given an fd, will block until one of the events occurs */
1084 static inline int do_block( int fd, int events, int timeout )
1086 struct pollfd pfd;
1087 int ret;
1089 pfd.fd = fd;
1090 pfd.events = events;
1092 while ((ret = poll(&pfd, 1, timeout)) < 0)
1094 if (errno != EINTR)
1095 return -1;
1097 if( ret == 0 )
1098 return 0;
1099 return pfd.revents;
1102 static int
1103 convert_af_w2u(int windowsaf) {
1104 unsigned int i;
1106 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1107 if (ws_af_map[i][0] == windowsaf)
1108 return ws_af_map[i][1];
1109 FIXME("unhandled Windows address family %d\n", windowsaf);
1110 return -1;
1113 static int
1114 convert_af_u2w(int unixaf) {
1115 unsigned int i;
1117 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1118 if (ws_af_map[i][1] == unixaf)
1119 return ws_af_map[i][0];
1120 FIXME("unhandled UNIX address family %d\n", unixaf);
1121 return -1;
1124 static int
1125 convert_proto_w2u(int windowsproto) {
1126 unsigned int i;
1128 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1129 if (ws_proto_map[i][0] == windowsproto)
1130 return ws_proto_map[i][1];
1132 /* check for extended IPX */
1133 if (IS_IPX_PROTO(windowsproto))
1134 return windowsproto;
1136 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
1137 return -1;
1140 static int
1141 convert_proto_u2w(int unixproto) {
1142 unsigned int i;
1144 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1145 if (ws_proto_map[i][1] == unixproto)
1146 return ws_proto_map[i][0];
1148 /* if value is inside IPX range just return it - the kernel simply
1149 * echoes the value used in the socket() function */
1150 if (IS_IPX_PROTO(unixproto))
1151 return unixproto;
1153 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
1154 return -1;
1157 static int
1158 convert_socktype_w2u(int windowssocktype) {
1159 unsigned int i;
1161 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1162 if (ws_socktype_map[i][0] == windowssocktype)
1163 return ws_socktype_map[i][1];
1164 FIXME("unhandled Windows socket type %d\n", windowssocktype);
1165 return -1;
1168 static int
1169 convert_socktype_u2w(int unixsocktype) {
1170 unsigned int i;
1172 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1173 if (ws_socktype_map[i][1] == unixsocktype)
1174 return ws_socktype_map[i][0];
1175 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
1176 return -1;
1179 static int set_ipx_packettype(int sock, int ptype)
1181 #ifdef HAS_IPX
1182 int fd = get_sock_fd( sock, 0, NULL ), ret = 0;
1183 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", ptype, fd);
1185 if (fd == -1) return SOCKET_ERROR;
1187 /* We try to set the ipx type on ipx socket level. */
1188 #ifdef SOL_IPX
1189 if(setsockopt(fd, SOL_IPX, IPX_TYPE, &ptype, sizeof(ptype)) == -1)
1191 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
1192 ret = SOCKET_ERROR;
1194 #else
1196 struct ipx val;
1197 /* Should we retrieve val using a getsockopt call and then
1198 * set the modified one? */
1199 val.ipx_pt = ptype;
1200 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
1202 #endif
1203 release_sock_fd( sock, fd );
1204 return ret;
1205 #else
1206 WARN("IPX support is not enabled, can't set packet type\n");
1207 return SOCKET_ERROR;
1208 #endif
1211 /* ----------------------------------- API -----
1213 * Init / cleanup / error checking.
1216 /***********************************************************************
1217 * WSAStartup (WS2_32.115)
1219 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
1221 TRACE("verReq=%x\n", wVersionRequested);
1223 if (LOBYTE(wVersionRequested) < 1)
1224 return WSAVERNOTSUPPORTED;
1226 if (!lpWSAData) return WSAEINVAL;
1228 num_startup++;
1230 /* that's the whole of the negotiation for now */
1231 lpWSAData->wVersion = wVersionRequested;
1232 /* return winsock information */
1233 lpWSAData->wHighVersion = 0x0202;
1234 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
1235 strcpy(lpWSAData->szSystemStatus, "Running" );
1236 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
1237 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
1238 /* don't do anything with lpWSAData->lpVendorInfo */
1239 /* (some apps don't allocate the space for this field) */
1241 TRACE("succeeded starts: %d\n", num_startup);
1242 return 0;
1246 /***********************************************************************
1247 * WSACleanup (WS2_32.116)
1249 INT WINAPI WSACleanup(void)
1251 if (num_startup) {
1252 num_startup--;
1253 TRACE("pending cleanups: %d\n", num_startup);
1254 return 0;
1256 SetLastError(WSANOTINITIALISED);
1257 return SOCKET_ERROR;
1261 /***********************************************************************
1262 * WSAGetLastError (WS2_32.111)
1264 INT WINAPI WSAGetLastError(void)
1266 return GetLastError();
1269 /***********************************************************************
1270 * WSASetLastError (WS2_32.112)
1272 void WINAPI WSASetLastError(INT iError) {
1273 SetLastError(iError);
1276 static struct WS_hostent *check_buffer_he(int size)
1278 struct per_thread_data * ptb = get_per_thread_data();
1279 if (ptb->he_buffer)
1281 if (ptb->he_len >= size ) return ptb->he_buffer;
1282 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1284 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
1285 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
1286 return ptb->he_buffer;
1289 static struct WS_servent *check_buffer_se(int size)
1291 struct per_thread_data * ptb = get_per_thread_data();
1292 if (ptb->se_buffer)
1294 if (ptb->se_len >= size ) return ptb->se_buffer;
1295 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1297 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
1298 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
1299 return ptb->se_buffer;
1302 static struct WS_protoent *check_buffer_pe(int size)
1304 struct per_thread_data * ptb = get_per_thread_data();
1305 if (ptb->pe_buffer)
1307 if (ptb->pe_len >= size ) return ptb->pe_buffer;
1308 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1310 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
1311 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
1312 return ptb->pe_buffer;
1315 /* ----------------------------------- i/o APIs */
1317 static inline BOOL supported_pf(int pf)
1319 switch (pf)
1321 case WS_AF_INET:
1322 case WS_AF_INET6:
1323 return TRUE;
1324 #ifdef HAS_IPX
1325 case WS_AF_IPX:
1326 return TRUE;
1327 #endif
1328 #ifdef HAS_IRDA
1329 case WS_AF_IRDA:
1330 return TRUE;
1331 #endif
1332 default:
1333 return FALSE;
1337 static inline BOOL supported_protocol(int protocol)
1339 int i;
1340 for (i = 0; i < sizeof(valid_protocols) / sizeof(valid_protocols[0]); i++)
1341 if (protocol == valid_protocols[i])
1342 return TRUE;
1343 return FALSE;
1346 /**********************************************************************/
1348 /* Returns the length of the converted address if successful, 0 if it was too small to
1349 * start with.
1351 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
1352 union generic_unix_sockaddr *uaddr)
1354 unsigned int uaddrlen = 0;
1356 switch (wsaddr->sa_family)
1358 #ifdef HAS_IPX
1359 case WS_AF_IPX:
1361 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
1362 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
1364 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
1365 return 0;
1367 uaddrlen = sizeof(struct sockaddr_ipx);
1368 memset( uaddr, 0, uaddrlen );
1369 uipx->sipx_family=AF_IPX;
1370 uipx->sipx_port=wsipx->sa_socket;
1371 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1372 * in one go
1374 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
1375 #ifdef IPX_FRAME_NONE
1376 uipx->sipx_type=IPX_FRAME_NONE;
1377 #endif
1378 break;
1380 #endif
1381 case WS_AF_INET6: {
1382 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
1383 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
1385 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1386 * scope_id, one without.
1388 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
1389 uaddrlen = sizeof(struct sockaddr_in6);
1390 memset( uaddr, 0, uaddrlen );
1391 uin6->sin6_family = AF_INET6;
1392 uin6->sin6_port = win6->sin6_port;
1393 uin6->sin6_flowinfo = win6->sin6_flowinfo;
1394 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1395 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
1396 #endif
1397 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
1398 break;
1400 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
1401 return 0;
1403 case WS_AF_INET: {
1404 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
1405 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
1407 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
1408 return 0;
1409 uaddrlen = sizeof(struct sockaddr_in);
1410 memset( uaddr, 0, uaddrlen );
1411 uin->sin_family = AF_INET;
1412 uin->sin_port = win->sin_port;
1413 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
1414 break;
1416 #ifdef HAS_IRDA
1417 case WS_AF_IRDA: {
1418 struct sockaddr_irda *uin = (struct sockaddr_irda *)uaddr;
1419 const SOCKADDR_IRDA *win = (const SOCKADDR_IRDA *)wsaddr;
1421 if (wsaddrlen < sizeof(SOCKADDR_IRDA))
1422 return 0;
1423 uaddrlen = sizeof(struct sockaddr_irda);
1424 memset( uaddr, 0, uaddrlen );
1425 uin->sir_family = AF_IRDA;
1426 if (!strncmp( win->irdaServiceName, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1428 unsigned int lsap_sel = 0;
1430 sscanf( win->irdaServiceName, "LSAP-SEL%u", &lsap_sel );
1431 uin->sir_lsap_sel = lsap_sel;
1433 else
1435 uin->sir_lsap_sel = LSAP_ANY;
1436 memcpy( uin->sir_name, win->irdaServiceName, 25 );
1438 memcpy( &uin->sir_addr, win->irdaDeviceID, sizeof(uin->sir_addr) );
1439 break;
1441 #endif
1442 case WS_AF_UNSPEC: {
1443 /* Try to determine the needed space by the passed windows sockaddr space */
1444 switch (wsaddrlen) {
1445 default: /* likely an ipv4 address */
1446 case sizeof(struct WS_sockaddr_in):
1447 uaddrlen = sizeof(struct sockaddr_in);
1448 break;
1449 #ifdef HAS_IPX
1450 case sizeof(struct WS_sockaddr_ipx):
1451 uaddrlen = sizeof(struct sockaddr_ipx);
1452 break;
1453 #endif
1454 #ifdef HAS_IRDA
1455 case sizeof(SOCKADDR_IRDA):
1456 uaddrlen = sizeof(struct sockaddr_irda);
1457 break;
1458 #endif
1459 case sizeof(struct WS_sockaddr_in6):
1460 case sizeof(struct WS_sockaddr_in6_old):
1461 uaddrlen = sizeof(struct sockaddr_in6);
1462 break;
1464 memset( uaddr, 0, uaddrlen );
1465 break;
1467 default:
1468 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
1469 return 0;
1471 return uaddrlen;
1474 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
1476 switch (uaddr->sa_family)
1478 #ifdef HAS_IPX
1479 case AF_IPX:
1481 static const struct sockaddr_ipx emptyAddr;
1482 struct sockaddr_ipx *ipx = (struct sockaddr_ipx*) uaddr;
1483 return ipx->sipx_port
1484 || memcmp(&ipx->sipx_network, &emptyAddr.sipx_network, sizeof(emptyAddr.sipx_network))
1485 || memcmp(&ipx->sipx_node, &emptyAddr.sipx_node, sizeof(emptyAddr.sipx_node));
1487 #endif
1488 case AF_INET6:
1490 static const struct sockaddr_in6 emptyAddr;
1491 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
1492 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
1494 case AF_INET:
1496 static const struct sockaddr_in emptyAddr;
1497 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
1498 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
1500 case AF_UNSPEC:
1501 return FALSE;
1502 default:
1503 FIXME("unknown address family %d\n", uaddr->sa_family);
1504 return TRUE;
1508 /* Returns 0 if successful, -1 if the buffer is too small */
1509 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
1511 int res;
1513 switch(uaddr->sa_family)
1515 #ifdef HAS_IPX
1516 case AF_IPX:
1518 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
1519 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
1521 res=-1;
1522 switch (*wsaddrlen) /* how much can we copy? */
1524 default:
1525 res=0; /* enough */
1526 *wsaddrlen = sizeof(*wsipx);
1527 wsipx->sa_socket=uipx->sipx_port;
1528 /* fall through */
1529 case 13:
1530 case 12:
1531 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
1532 /* fall through */
1533 case 11:
1534 case 10:
1535 case 9:
1536 case 8:
1537 case 7:
1538 case 6:
1539 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1540 /* fall through */
1541 case 5:
1542 case 4:
1543 case 3:
1544 case 2:
1545 wsipx->sa_family=WS_AF_IPX;
1546 /* fall through */
1547 case 1:
1548 case 0:
1549 /* way too small */
1550 break;
1553 break;
1554 #endif
1555 #ifdef HAS_IRDA
1556 case AF_IRDA: {
1557 const struct sockaddr_irda *uin = (const struct sockaddr_irda *)uaddr;
1558 SOCKADDR_IRDA *win = (SOCKADDR_IRDA *)wsaddr;
1560 if (*wsaddrlen < sizeof(SOCKADDR_IRDA))
1561 return -1;
1562 win->irdaAddressFamily = WS_AF_IRDA;
1563 memcpy( win->irdaDeviceID, &uin->sir_addr, sizeof(win->irdaDeviceID) );
1564 if (uin->sir_lsap_sel != LSAP_ANY)
1565 sprintf( win->irdaServiceName, "LSAP-SEL%u", uin->sir_lsap_sel );
1566 else
1567 memcpy( win->irdaServiceName, uin->sir_name,
1568 sizeof(win->irdaServiceName) );
1569 return 0;
1571 #endif
1572 case AF_INET6: {
1573 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1574 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1576 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1577 return -1;
1578 win6old->sin6_family = WS_AF_INET6;
1579 win6old->sin6_port = uin6->sin6_port;
1580 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1581 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1582 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1583 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1584 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1585 win6->sin6_scope_id = uin6->sin6_scope_id;
1586 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1588 else
1589 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1590 #else
1591 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1592 #endif
1593 return 0;
1595 case AF_INET: {
1596 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1597 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1599 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1600 return -1;
1601 win->sin_family = WS_AF_INET;
1602 win->sin_port = uin->sin_port;
1603 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1604 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1605 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1606 return 0;
1608 case AF_UNSPEC: {
1609 memset(wsaddr,0,*wsaddrlen);
1610 return 0;
1612 default:
1613 FIXME("Unknown address family %d\n", uaddr->sa_family);
1614 return -1;
1616 return res;
1619 static INT WS_DuplicateSocket(BOOL unicode, SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo)
1621 HANDLE hProcess;
1622 int size;
1623 WSAPROTOCOL_INFOW infow;
1625 TRACE("(unicode %d, socket %04lx, processid %x, buffer %p)\n",
1626 unicode, s, dwProcessId, lpProtocolInfo);
1628 if (!ws_protocol_info(s, unicode, &infow, &size))
1629 return SOCKET_ERROR;
1631 if (!(hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId)))
1633 SetLastError(WSAEINVAL);
1634 return SOCKET_ERROR;
1637 if (!lpProtocolInfo)
1639 CloseHandle(hProcess);
1640 SetLastError(WSAEFAULT);
1641 return SOCKET_ERROR;
1644 /* I don't know what the real Windoze does next, this is a hack */
1645 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
1646 * the target use the global duplicate, or we could copy a reference to us to the structure
1647 * and let the target duplicate it from us, but let's do it as simple as possible */
1648 memcpy(lpProtocolInfo, &infow, size);
1649 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
1650 hProcess, (LPHANDLE)&lpProtocolInfo->dwServiceFlags3,
1651 0, FALSE, DUPLICATE_SAME_ACCESS);
1652 CloseHandle(hProcess);
1653 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
1654 return 0;
1657 /*****************************************************************************
1658 * WS_EnterSingleProtocolW [internal]
1660 * enters the protocol information of one given protocol into the given
1661 * buffer.
1663 * RETURNS
1664 * TRUE if a protocol was entered into the buffer.
1666 * BUGS
1667 * - only implemented for IPX, SPX, SPXII, TCP, UDP
1668 * - there is no check that the operating system supports the returned
1669 * protocols
1671 static BOOL WS_EnterSingleProtocolW( INT protocol, WSAPROTOCOL_INFOW* info )
1673 memset( info, 0, sizeof(WSAPROTOCOL_INFOW) );
1674 info->iProtocol = protocol;
1676 switch (protocol)
1678 case WS_IPPROTO_TCP:
1679 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_EXPEDITED_DATA |
1680 XP1_GRACEFUL_CLOSE | XP1_GUARANTEED_ORDER |
1681 XP1_GUARANTEED_DELIVERY;
1682 info->ProviderId = ProviderIdIP;
1683 info->dwCatalogEntryId = 0x3e9;
1684 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1685 info->ProtocolChain.ChainLen = 1;
1686 info->iVersion = 2;
1687 info->iAddressFamily = WS_AF_INET;
1688 info->iMaxSockAddr = 0x10;
1689 info->iMinSockAddr = 0x10;
1690 info->iSocketType = WS_SOCK_STREAM;
1691 strcpyW( info->szProtocol, NameTcpW );
1692 break;
1694 case WS_IPPROTO_UDP:
1695 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_SUPPORT_BROADCAST |
1696 XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED |
1697 XP1_CONNECTIONLESS;
1698 info->ProviderId = ProviderIdIP;
1699 info->dwCatalogEntryId = 0x3ea;
1700 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1701 info->ProtocolChain.ChainLen = 1;
1702 info->iVersion = 2;
1703 info->iAddressFamily = WS_AF_INET;
1704 info->iMaxSockAddr = 0x10;
1705 info->iMinSockAddr = 0x10;
1706 info->iSocketType = WS_SOCK_DGRAM;
1707 info->dwMessageSize = 0xffbb;
1708 strcpyW( info->szProtocol, NameUdpW );
1709 break;
1711 case WS_NSPROTO_IPX:
1712 info->dwServiceFlags1 = XP1_PARTIAL_MESSAGE | XP1_SUPPORT_BROADCAST |
1713 XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED |
1714 XP1_CONNECTIONLESS;
1715 info->ProviderId = ProviderIdIPX;
1716 info->dwCatalogEntryId = 0x406;
1717 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1718 info->ProtocolChain.ChainLen = 1;
1719 info->iVersion = 2;
1720 info->iAddressFamily = WS_AF_IPX;
1721 info->iMaxSockAddr = 0x10;
1722 info->iMinSockAddr = 0x0e;
1723 info->iSocketType = WS_SOCK_DGRAM;
1724 info->iProtocolMaxOffset = 0xff;
1725 info->dwMessageSize = 0x240;
1726 strcpyW( info->szProtocol, NameIpxW );
1727 break;
1729 case WS_NSPROTO_SPX:
1730 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_PSEUDO_STREAM |
1731 XP1_MESSAGE_ORIENTED | XP1_GUARANTEED_ORDER |
1732 XP1_GUARANTEED_DELIVERY;
1733 info->ProviderId = ProviderIdSPX;
1734 info->dwCatalogEntryId = 0x407;
1735 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1736 info->ProtocolChain.ChainLen = 1;
1737 info->iVersion = 2;
1738 info->iAddressFamily = WS_AF_IPX;
1739 info->iMaxSockAddr = 0x10;
1740 info->iMinSockAddr = 0x0e;
1741 info->iSocketType = WS_SOCK_SEQPACKET;
1742 info->dwMessageSize = 0xffffffff;
1743 strcpyW( info->szProtocol, NameSpxW );
1744 break;
1746 case WS_NSPROTO_SPXII:
1747 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_GRACEFUL_CLOSE |
1748 XP1_PSEUDO_STREAM | XP1_MESSAGE_ORIENTED |
1749 XP1_GUARANTEED_ORDER | XP1_GUARANTEED_DELIVERY;
1750 info->ProviderId = ProviderIdSPX;
1751 info->dwCatalogEntryId = 0x409;
1752 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1753 info->ProtocolChain.ChainLen = 1;
1754 info->iVersion = 2;
1755 info->iAddressFamily = WS_AF_IPX;
1756 info->iMaxSockAddr = 0x10;
1757 info->iMinSockAddr = 0x0e;
1758 info->iSocketType = WS_SOCK_SEQPACKET;
1759 info->dwMessageSize = 0xffffffff;
1760 strcpyW( info->szProtocol, NameSpxIIW );
1761 break;
1763 default:
1764 FIXME("unknown Protocol <0x%08x>\n", protocol);
1765 return FALSE;
1767 return TRUE;
1770 /*****************************************************************************
1771 * WS_EnterSingleProtocolA [internal]
1773 * see function WS_EnterSingleProtocolW
1776 static BOOL WS_EnterSingleProtocolA( INT protocol, WSAPROTOCOL_INFOA* info )
1778 WSAPROTOCOL_INFOW infow;
1779 INT ret;
1780 memset( info, 0, sizeof(WSAPROTOCOL_INFOA) );
1782 ret = WS_EnterSingleProtocolW( protocol, &infow );
1783 if (ret)
1785 /* convert the structure from W to A */
1786 memcpy( info, &infow, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
1787 WideCharToMultiByte( CP_ACP, 0, infow.szProtocol, -1,
1788 info->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL );
1791 return ret;
1794 static INT WS_EnumProtocols( BOOL unicode, const INT *protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
1796 INT i = 0, items = 0;
1797 DWORD size = 0;
1798 union _info
1800 LPWSAPROTOCOL_INFOA a;
1801 LPWSAPROTOCOL_INFOW w;
1802 } info;
1803 info.w = buffer;
1805 if (!protocols) protocols = valid_protocols;
1807 while (protocols[i])
1809 if(supported_protocol(protocols[i++]))
1810 items++;
1813 size = items * (unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA));
1815 TRACE("unicode %d, protocols %p, buffer %p, length %p %d, items %d, required %d\n",
1816 unicode, protocols, buffer, len, len ? *len : 0, items, size);
1818 if (*len < size || !buffer)
1820 *len = size;
1821 WSASetLastError(WSAENOBUFS);
1822 return SOCKET_ERROR;
1825 for (i = items = 0; protocols[i]; i++)
1827 if (!supported_protocol(protocols[i])) continue;
1828 if (unicode)
1830 if (WS_EnterSingleProtocolW( protocols[i], &info.w[items] ))
1831 items++;
1833 else
1835 if (WS_EnterSingleProtocolA( protocols[i], &info.a[items] ))
1836 items++;
1839 return items;
1842 static BOOL ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size)
1844 NTSTATUS status;
1846 *size = unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA);
1847 memset(buffer, 0, *size);
1849 SERVER_START_REQ( get_socket_info )
1851 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1852 status = wine_server_call( req );
1853 if (!status)
1855 buffer->iAddressFamily = convert_af_u2w(reply->family);
1856 buffer->iSocketType = convert_socktype_u2w(reply->type);
1857 buffer->iProtocol = convert_proto_u2w(reply->protocol);
1860 SERVER_END_REQ;
1862 if (status)
1864 unsigned int err = NtStatusToWSAError( status );
1865 SetLastError( err == WSAEBADF ? WSAENOTSOCK : err );
1866 return FALSE;
1869 if (unicode)
1870 WS_EnterSingleProtocolW( buffer->iProtocol, buffer);
1871 else
1872 WS_EnterSingleProtocolA( buffer->iProtocol, (WSAPROTOCOL_INFOA *)buffer);
1874 return TRUE;
1877 /**************************************************************************
1878 * Functions for handling overlapped I/O
1879 **************************************************************************/
1881 /* user APC called upon async completion */
1882 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1884 ws2_async *wsa = arg;
1886 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
1887 iosb->Information, wsa->user_overlapped,
1888 wsa->flags );
1889 HeapFree( GetProcessHeap(), 0, wsa );
1892 /***********************************************************************
1893 * WS2_recv (INTERNAL)
1895 * Workhorse for both synchronous and asynchronous recv() operations.
1897 static int WS2_recv( int fd, struct ws2_async *wsa )
1899 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1900 char pktbuf[512];
1901 #endif
1902 struct msghdr hdr;
1903 union generic_unix_sockaddr unix_sockaddr;
1904 int n;
1906 hdr.msg_name = NULL;
1908 if (wsa->addr)
1910 hdr.msg_namelen = sizeof(unix_sockaddr);
1911 hdr.msg_name = &unix_sockaddr;
1913 else
1914 hdr.msg_namelen = 0;
1916 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1917 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1918 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1919 hdr.msg_accrights = NULL;
1920 hdr.msg_accrightslen = 0;
1921 #else
1922 hdr.msg_control = pktbuf;
1923 hdr.msg_controllen = sizeof(pktbuf);
1924 hdr.msg_flags = 0;
1925 #endif
1927 while ((n = recvmsg(fd, &hdr, wsa->flags)) == -1)
1929 if (errno != EINTR)
1930 return -1;
1933 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1934 if (wsa->control)
1936 ERR("Message control headers cannot be properly supported on this system.\n");
1937 wsa->control->len = 0;
1939 #else
1940 if (wsa->control && !convert_control_headers(&hdr, wsa->control))
1942 WARN("Application passed insufficient room for control headers.\n");
1943 *wsa->lpFlags |= WS_MSG_CTRUNC;
1944 errno = EMSGSIZE;
1945 return -1;
1947 #endif
1949 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
1950 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
1952 * quoting linux 2.6 net/ipv4/tcp.c:
1953 * "According to UNIX98, msg_name/msg_namelen are ignored
1954 * on connected socket. I was just happy when found this 8) --ANK"
1956 * likewise MSDN says that lpFrom and lpFromlen are ignored for
1957 * connection-oriented sockets, so don't try to update lpFrom.
1959 if (wsa->addr && hdr.msg_namelen)
1960 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
1962 return n;
1965 /***********************************************************************
1966 * WS2_async_recv (INTERNAL)
1968 * Handler for overlapped recv() operations.
1970 static NTSTATUS WS2_async_recv( void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1972 ws2_async* wsa = user;
1973 int result = 0, fd;
1975 switch (status)
1977 case STATUS_ALERTED:
1978 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
1979 break;
1981 result = WS2_recv( fd, wsa );
1982 wine_server_release_fd( wsa->hSocket, fd );
1983 if (result >= 0)
1985 status = STATUS_SUCCESS;
1986 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1988 else
1990 if (errno == EAGAIN)
1992 status = STATUS_PENDING;
1993 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1995 else
1997 result = 0;
1998 status = wsaErrStatus();
2001 break;
2003 if (status != STATUS_PENDING)
2005 iosb->u.Status = status;
2006 iosb->Information = result;
2007 *apc = ws2_async_apc;
2009 return status;
2012 /* user APC called upon async accept completion */
2013 static void WINAPI ws2_async_accept_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
2015 struct ws2_accept_async *wsa = arg;
2017 HeapFree( GetProcessHeap(), 0, wsa->read );
2018 HeapFree( GetProcessHeap(), 0, wsa );
2021 /***********************************************************************
2022 * WS2_async_accept_recv (INTERNAL)
2024 * This function is used to finish the read part of an accept request. It is
2025 * needed to place the completion on the correct socket (listener).
2027 static NTSTATUS WS2_async_accept_recv( void *arg, IO_STATUS_BLOCK *iosb, NTSTATUS status, void **apc )
2029 void *junk;
2030 struct ws2_accept_async *wsa = arg;
2032 status = WS2_async_recv( wsa->read, iosb, status, &junk );
2033 if (status == STATUS_PENDING)
2034 return status;
2036 if (wsa->user_overlapped->hEvent)
2037 SetEvent(wsa->user_overlapped->hEvent);
2038 if (wsa->cvalue)
2039 WS_AddCompletion( HANDLE2SOCKET(wsa->listen_socket), wsa->cvalue, iosb->u.Status, iosb->Information );
2041 *apc = ws2_async_accept_apc;
2042 return status;
2045 /***********************************************************************
2046 * WS2_async_accept (INTERNAL)
2048 * This is the function called to satisfy the AcceptEx callback
2050 static NTSTATUS WS2_async_accept( void *arg, IO_STATUS_BLOCK *iosb, NTSTATUS status, void **apc )
2052 struct ws2_accept_async *wsa = arg;
2053 int len;
2054 char *addr;
2056 TRACE("status: 0x%x listen: %p, accept: %p\n", status, wsa->listen_socket, wsa->accept_socket);
2058 if (status == STATUS_ALERTED)
2060 SERVER_START_REQ( accept_into_socket )
2062 req->lhandle = wine_server_obj_handle( wsa->listen_socket );
2063 req->ahandle = wine_server_obj_handle( wsa->accept_socket );
2064 status = wine_server_call( req );
2066 SERVER_END_REQ;
2068 if (status == STATUS_CANT_WAIT)
2069 return STATUS_PENDING;
2071 if (status == STATUS_INVALID_HANDLE)
2073 FIXME("AcceptEx accepting socket closed but request was not cancelled\n");
2074 status = STATUS_CANCELLED;
2077 else if (status == STATUS_HANDLES_CLOSED)
2078 status = STATUS_CANCELLED; /* strange windows behavior */
2080 if (status != STATUS_SUCCESS)
2081 goto finish;
2083 /* WS2 Spec says size param is extra 16 bytes long...what do we put in it? */
2084 addr = ((char *)wsa->buf) + wsa->data_len;
2085 len = wsa->local_len - sizeof(int);
2086 WS_getsockname(HANDLE2SOCKET(wsa->accept_socket),
2087 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
2088 *(int *)addr = len;
2090 addr += wsa->local_len;
2091 len = wsa->remote_len - sizeof(int);
2092 WS_getpeername(HANDLE2SOCKET(wsa->accept_socket),
2093 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
2094 *(int *)addr = len;
2096 if (!wsa->read)
2097 goto finish;
2099 SERVER_START_REQ( register_async )
2101 req->type = ASYNC_TYPE_READ;
2102 req->async.handle = wine_server_obj_handle( wsa->accept_socket );
2103 req->async.callback = wine_server_client_ptr( WS2_async_accept_recv );
2104 req->async.iosb = wine_server_client_ptr( iosb );
2105 req->async.arg = wine_server_client_ptr( wsa );
2106 status = wine_server_call( req );
2108 SERVER_END_REQ;
2110 if (status != STATUS_PENDING)
2111 goto finish;
2113 /* The APC has finished but no completion should be sent for the operation yet, additional processing
2114 * needs to be performed by WS2_async_accept_recv() first. */
2115 return STATUS_MORE_PROCESSING_REQUIRED;
2117 finish:
2118 iosb->u.Status = status;
2119 iosb->Information = 0;
2121 if (wsa->user_overlapped->hEvent)
2122 SetEvent(wsa->user_overlapped->hEvent);
2124 *apc = ws2_async_accept_apc;
2125 return status;
2128 /***********************************************************************
2129 * WS2_send (INTERNAL)
2131 * Workhorse for both synchronous and asynchronous send() operations.
2133 static int WS2_send( int fd, struct ws2_async *wsa )
2135 struct msghdr hdr;
2136 union generic_unix_sockaddr unix_addr;
2137 int n, ret;
2139 hdr.msg_name = NULL;
2140 hdr.msg_namelen = 0;
2142 if (wsa->addr)
2144 hdr.msg_name = &unix_addr;
2145 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
2146 if ( !hdr.msg_namelen )
2148 errno = EFAULT;
2149 return -1;
2152 #if defined(HAS_IPX) && defined(SOL_IPX)
2153 if(wsa->addr->sa_family == WS_AF_IPX)
2155 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
2156 int val=0;
2157 socklen_t len = sizeof(int);
2159 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
2160 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
2161 * the packet type and then we can retrieve it using getsockopt. After that we can set the
2162 * ipx type in the sockaddr_opx structure with the stored value.
2164 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
2165 uipx->sipx_type = val;
2167 #endif
2170 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
2171 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
2172 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2173 hdr.msg_accrights = NULL;
2174 hdr.msg_accrightslen = 0;
2175 #else
2176 hdr.msg_control = NULL;
2177 hdr.msg_controllen = 0;
2178 hdr.msg_flags = 0;
2179 #endif
2181 while ((ret = sendmsg(fd, &hdr, wsa->flags)) == -1)
2183 if (errno != EINTR)
2184 return -1;
2187 n = ret;
2188 while (wsa->first_iovec < wsa->n_iovecs && wsa->iovec[wsa->first_iovec].iov_len <= n)
2189 n -= wsa->iovec[wsa->first_iovec++].iov_len;
2190 if (wsa->first_iovec < wsa->n_iovecs)
2192 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
2193 wsa->iovec[wsa->first_iovec].iov_len -= n;
2195 return ret;
2198 /***********************************************************************
2199 * WS2_async_send (INTERNAL)
2201 * Handler for overlapped send() operations.
2203 static NTSTATUS WS2_async_send(void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
2205 ws2_async* wsa = user;
2206 int result = 0, fd;
2208 switch (status)
2210 case STATUS_ALERTED:
2211 if ( wsa->n_iovecs <= wsa->first_iovec )
2213 /* Nothing to do */
2214 status = STATUS_SUCCESS;
2215 break;
2217 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
2218 break;
2220 /* check to see if the data is ready (non-blocking) */
2221 result = WS2_send( fd, wsa );
2222 wine_server_release_fd( wsa->hSocket, fd );
2224 if (result >= 0)
2226 if (wsa->first_iovec < wsa->n_iovecs)
2227 status = STATUS_PENDING;
2228 else
2229 status = STATUS_SUCCESS;
2231 iosb->Information += result;
2233 else if (errno == EAGAIN)
2235 status = STATUS_PENDING;
2237 else
2239 status = wsaErrStatus();
2241 break;
2243 if (status != STATUS_PENDING)
2245 iosb->u.Status = status;
2246 *apc = ws2_async_apc;
2248 return status;
2251 /***********************************************************************
2252 * WS2_async_shutdown (INTERNAL)
2254 * Handler for shutdown() operations on overlapped sockets.
2256 static NTSTATUS WS2_async_shutdown( void* user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc )
2258 ws2_async* wsa = user;
2259 int fd, err = 1;
2261 switch (status)
2263 case STATUS_ALERTED:
2264 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
2265 break;
2267 switch ( wsa->type )
2269 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
2270 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
2272 status = err ? wsaErrStatus() : STATUS_SUCCESS;
2273 wine_server_release_fd( wsa->hSocket, fd );
2274 break;
2276 iosb->u.Status = status;
2277 iosb->Information = 0;
2278 *apc = ws2_async_apc;
2279 return status;
2282 /***********************************************************************
2283 * WS2_register_async_shutdown (INTERNAL)
2285 * Helper function for WS_shutdown() on overlapped sockets.
2287 static int WS2_register_async_shutdown( SOCKET s, int type )
2289 struct ws2_async *wsa;
2290 NTSTATUS status;
2292 TRACE("s %ld type %d\n", s, type);
2294 wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( struct ws2_async, iovec[1] ));
2295 if ( !wsa )
2296 return WSAEFAULT;
2298 wsa->hSocket = SOCKET2HANDLE(s);
2299 wsa->type = type;
2300 wsa->completion_func = NULL;
2302 SERVER_START_REQ( register_async )
2304 req->type = type;
2305 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2306 req->async.callback = wine_server_client_ptr( WS2_async_shutdown );
2307 req->async.iosb = wine_server_client_ptr( &wsa->local_iosb );
2308 req->async.arg = wine_server_client_ptr( wsa );
2309 req->async.cvalue = 0;
2310 status = wine_server_call( req );
2312 SERVER_END_REQ;
2314 if (status != STATUS_PENDING)
2316 HeapFree( GetProcessHeap(), 0, wsa );
2317 return NtStatusToWSAError( status );
2319 return 0;
2322 /***********************************************************************
2323 * accept (WS2_32.1)
2325 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr, int *addrlen32)
2327 NTSTATUS status;
2328 SOCKET as;
2329 BOOL is_blocking;
2331 TRACE("socket %04lx\n", s );
2332 status = _is_blocking(s, &is_blocking);
2333 if (status)
2335 set_error(status);
2336 return INVALID_SOCKET;
2339 do {
2340 /* try accepting first (if there is a deferred connection) */
2341 SERVER_START_REQ( accept_socket )
2343 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
2344 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
2345 req->attributes = OBJ_INHERIT;
2346 status = wine_server_call( req );
2347 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
2349 SERVER_END_REQ;
2350 if (!status)
2352 if (addr && WS_getpeername(as, addr, addrlen32))
2354 WS_closesocket(as);
2355 return SOCKET_ERROR;
2357 return as;
2359 if (is_blocking && status == STATUS_CANT_WAIT)
2361 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2362 /* block here */
2363 do_block(fd, POLLIN, -1);
2364 _sync_sock_state(s); /* let wineserver notice connection */
2365 release_sock_fd( s, fd );
2367 } while (is_blocking && status == STATUS_CANT_WAIT);
2369 set_error(status);
2370 return INVALID_SOCKET;
2373 /***********************************************************************
2374 * AcceptEx
2376 static BOOL WINAPI WS2_AcceptEx(SOCKET listener, SOCKET acceptor, PVOID dest, DWORD dest_len,
2377 DWORD local_addr_len, DWORD rem_addr_len, LPDWORD received,
2378 LPOVERLAPPED overlapped)
2380 DWORD status;
2381 struct ws2_accept_async *wsa;
2382 int fd;
2383 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
2385 TRACE("(%lx, %lx, %p, %d, %d, %d, %p, %p)\n", listener, acceptor, dest, dest_len, local_addr_len,
2386 rem_addr_len, received, overlapped);
2388 if (!dest)
2390 SetLastError(WSAEINVAL);
2391 return FALSE;
2394 if (!overlapped)
2396 SetLastError(WSA_INVALID_PARAMETER);
2397 return FALSE;
2400 if (!rem_addr_len)
2402 SetLastError(WSAEFAULT);
2403 return FALSE;
2406 fd = get_sock_fd( listener, FILE_READ_DATA, NULL );
2407 if (fd == -1)
2409 SetLastError(WSAENOTSOCK);
2410 return FALSE;
2412 release_sock_fd( listener, fd );
2414 fd = get_sock_fd( acceptor, FILE_READ_DATA, NULL );
2415 if (fd == -1)
2417 SetLastError(WSAENOTSOCK);
2418 return FALSE;
2420 release_sock_fd( acceptor, fd );
2422 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
2423 if(!wsa)
2425 SetLastError(WSAEFAULT);
2426 return FALSE;
2429 wsa->listen_socket = SOCKET2HANDLE(listener);
2430 wsa->accept_socket = SOCKET2HANDLE(acceptor);
2431 wsa->user_overlapped = overlapped;
2432 wsa->cvalue = cvalue;
2433 wsa->buf = dest;
2434 wsa->data_len = dest_len;
2435 wsa->local_len = local_addr_len;
2436 wsa->remote_len = rem_addr_len;
2437 wsa->read = NULL;
2439 if (wsa->data_len)
2441 /* set up a read request if we need it */
2442 wsa->read = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[1]) );
2443 if (!wsa->read)
2445 HeapFree( GetProcessHeap(), 0, wsa );
2446 SetLastError(WSAEFAULT);
2447 return FALSE;
2450 wsa->read->hSocket = wsa->accept_socket;
2451 wsa->read->flags = 0;
2452 wsa->read->lpFlags = &wsa->read->flags;
2453 wsa->read->addr = NULL;
2454 wsa->read->addrlen.ptr = NULL;
2455 wsa->read->control = NULL;
2456 wsa->read->n_iovecs = 1;
2457 wsa->read->first_iovec = 0;
2458 wsa->read->iovec[0].iov_base = wsa->buf;
2459 wsa->read->iovec[0].iov_len = wsa->data_len;
2462 SERVER_START_REQ( register_async )
2464 req->type = ASYNC_TYPE_READ;
2465 req->async.handle = wine_server_obj_handle( SOCKET2HANDLE(listener) );
2466 req->async.callback = wine_server_client_ptr( WS2_async_accept );
2467 req->async.iosb = wine_server_client_ptr( overlapped );
2468 req->async.arg = wine_server_client_ptr( wsa );
2469 req->async.cvalue = cvalue;
2470 /* We don't set event since we may also have to read */
2471 status = wine_server_call( req );
2473 SERVER_END_REQ;
2475 if(status != STATUS_PENDING)
2477 HeapFree( GetProcessHeap(), 0, wsa->read );
2478 HeapFree( GetProcessHeap(), 0, wsa );
2481 SetLastError( NtStatusToWSAError(status) );
2482 return FALSE;
2485 /***********************************************************************
2486 * GetAcceptExSockaddrs
2488 static void WINAPI WS2_GetAcceptExSockaddrs(PVOID buffer, DWORD data_size, DWORD local_size, DWORD remote_size,
2489 struct WS_sockaddr **local_addr, LPINT local_addr_len,
2490 struct WS_sockaddr **remote_addr, LPINT remote_addr_len)
2492 char *cbuf = buffer;
2493 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer, data_size, local_size, remote_size, local_addr,
2494 local_addr_len, remote_addr, remote_addr_len );
2495 cbuf += data_size;
2497 *local_addr_len = *(int *) cbuf;
2498 *local_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2500 cbuf += local_size;
2502 *remote_addr_len = *(int *) cbuf;
2503 *remote_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2506 /***********************************************************************
2507 * WSASendMsg
2509 int WINAPI WSASendMsg( SOCKET s, LPWSAMSG msg, DWORD dwFlags, LPDWORD lpNumberOfBytesSent,
2510 LPWSAOVERLAPPED lpOverlapped,
2511 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
2513 if (!msg)
2515 SetLastError( WSAEFAULT );
2516 return SOCKET_ERROR;
2519 return WS2_sendto( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesSent,
2520 dwFlags, msg->name, msg->namelen,
2521 lpOverlapped, lpCompletionRoutine );
2524 /***********************************************************************
2525 * WSARecvMsg
2527 * Perform a receive operation that is capable of returning message
2528 * control headers. It is important to note that the WSAMSG parameter
2529 * must remain valid throughout the operation, even when an overlapped
2530 * receive is performed.
2532 static int WINAPI WS2_WSARecvMsg( SOCKET s, LPWSAMSG msg, LPDWORD lpNumberOfBytesRecvd,
2533 LPWSAOVERLAPPED lpOverlapped,
2534 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2536 if (!msg)
2538 SetLastError( WSAEFAULT );
2539 return SOCKET_ERROR;
2542 return WS2_recv_base( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesRecvd,
2543 &msg->dwFlags, msg->name, &msg->namelen,
2544 lpOverlapped, lpCompletionRoutine, &msg->Control );
2547 /***********************************************************************
2548 * interface_bind (INTERNAL)
2550 * Take bind() calls on any name corresponding to a local network adapter and restrict the given socket to
2551 * operating only on the specified interface. This restriction consists of two components:
2552 * 1) An outgoing packet restriction suggesting the egress interface for all packets.
2553 * 2) An incoming packet restriction dropping packets not meant for the interface.
2554 * If the function succeeds in placing these restrictions (returns TRUE) then the name for the bind() may
2555 * safely be changed to INADDR_ANY, permitting the transmission and receipt of broadcast packets on the
2556 * socket. This behavior is only relevant to UDP sockets and is needed for applications that expect to be able
2557 * to receive broadcast packets on a socket that is bound to a specific network interface.
2559 static BOOL interface_bind( SOCKET s, int fd, struct sockaddr *addr )
2561 struct sockaddr_in *in_sock = (struct sockaddr_in *) addr;
2562 unsigned int sock_type = 0;
2563 socklen_t optlen = sizeof(sock_type);
2564 in_addr_t bind_addr = in_sock->sin_addr.s_addr;
2565 PIP_ADAPTER_INFO adapters = NULL, adapter;
2566 BOOL ret = FALSE;
2567 DWORD adap_size;
2568 int enable = 1;
2570 if (bind_addr == htonl(INADDR_ANY) || bind_addr == htonl(INADDR_LOOPBACK))
2571 return FALSE; /* Not binding to a network adapter, special interface binding unnecessary. */
2572 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &sock_type, &optlen) == -1 || sock_type != SOCK_DGRAM)
2573 return FALSE; /* Special interface binding is only necessary for UDP datagrams. */
2574 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
2575 goto cleanup;
2576 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
2577 if (adapters == NULL || GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
2578 goto cleanup;
2579 /* Search the IPv4 adapter list for the appropriate binding interface */
2580 for (adapter = adapters; adapter != NULL; adapter = adapter->Next)
2582 in_addr_t adapter_addr = (in_addr_t) inet_addr(adapter->IpAddressList.IpAddress.String);
2584 if (bind_addr == adapter_addr)
2586 #if defined(IP_BOUND_IF)
2587 /* IP_BOUND_IF sets both the incoming and outgoing restriction at once */
2588 if (setsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &adapter->Index, sizeof(adapter->Index)) != 0)
2589 goto cleanup;
2590 ret = TRUE;
2591 #elif defined(LINUX_BOUND_IF)
2592 in_addr_t ifindex = (in_addr_t) htonl(adapter->Index);
2593 struct interface_filter specific_interface_filter;
2594 struct sock_fprog filter_prog;
2596 if (setsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex, sizeof(ifindex)) != 0)
2597 goto cleanup; /* Failed to suggest egress interface */
2598 specific_interface_filter = generic_interface_filter;
2599 specific_interface_filter.iface_rule.k = adapter->Index;
2600 specific_interface_filter.ip_rule.k = htonl(adapter_addr);
2601 filter_prog.len = sizeof(generic_interface_filter)/sizeof(struct sock_filter);
2602 filter_prog.filter = (struct sock_filter *) &specific_interface_filter;
2603 if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog, sizeof(filter_prog)) != 0)
2604 goto cleanup; /* Failed to specify incoming packet filter */
2605 ret = TRUE;
2606 #else
2607 FIXME("Broadcast packets on interface-bound sockets are not currently supported on this platform, "
2608 "receiving broadcast packets will not work on socket %04lx.\n", s);
2609 #endif
2610 break;
2613 /* Will soon be switching to INADDR_ANY: permit address reuse */
2614 if (ret && setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) == 0)
2615 TRACE("Socket %04lx bound to interface index %d\n", s, adapter->Index);
2616 else
2617 ret = FALSE;
2619 cleanup:
2620 if(!ret)
2621 ERR("Failed to bind to interface, receiving broadcast packets will not work on socket %04lx.\n", s);
2622 HeapFree(GetProcessHeap(), 0, adapters);
2623 return ret;
2626 /***********************************************************************
2627 * bind (WS2_32.2)
2629 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
2631 int fd = get_sock_fd( s, 0, NULL );
2632 int res = SOCKET_ERROR;
2634 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2636 if (fd != -1)
2638 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
2640 SetLastError(WSAEAFNOSUPPORT);
2642 else
2644 union generic_unix_sockaddr uaddr;
2645 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2646 if (!uaddrlen)
2648 SetLastError(WSAEFAULT);
2650 else
2652 #ifdef IPV6_V6ONLY
2653 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
2654 if (name->sa_family == WS_AF_INET6 &&
2655 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
2657 int enable = 1;
2658 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
2660 release_sock_fd( s, fd );
2661 SetLastError(WSAEAFNOSUPPORT);
2662 return SOCKET_ERROR;
2665 #endif
2666 if (name->sa_family == WS_AF_INET)
2668 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2669 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2671 /* Trying to bind to the default host interface, using
2672 * INADDR_ANY instead*/
2673 WARN("Trying to bind to magic IP address, using "
2674 "INADDR_ANY instead.\n");
2675 in4->sin_addr.s_addr = htonl(INADDR_ANY);
2677 else if (interface_bind(s, fd, &uaddr.addr))
2678 in4->sin_addr.s_addr = htonl(INADDR_ANY);
2680 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
2682 int loc_errno = errno;
2683 WARN("\tfailure - errno = %i\n", errno);
2684 errno = loc_errno;
2685 switch (errno)
2687 case EBADF:
2688 SetLastError(WSAENOTSOCK);
2689 break;
2690 case EADDRNOTAVAIL:
2691 SetLastError(WSAEINVAL);
2692 break;
2693 case EADDRINUSE:
2695 int optval = 0;
2696 socklen_t optlen = sizeof(optval);
2697 /* Windows >= 2003 will return different results depending on
2698 * SO_REUSEADDR, WSAEACCES may be returned representing that
2699 * the socket hijacking protection prevented the bind */
2700 if (!getsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&optval, &optlen) && optval)
2702 SetLastError(WSAEACCES);
2703 break;
2705 /* fall through */
2707 default:
2708 SetLastError(wsaErrno());
2709 break;
2712 else
2714 res=0; /* success */
2718 release_sock_fd( s, fd );
2720 return res;
2723 /***********************************************************************
2724 * closesocket (WS2_32.3)
2726 int WINAPI WS_closesocket(SOCKET s)
2728 TRACE("socket %04lx\n", s);
2729 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
2730 return SOCKET_ERROR;
2733 static int do_connect(int fd, const struct WS_sockaddr* name, int namelen)
2735 union generic_unix_sockaddr uaddr;
2736 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2738 if (!uaddrlen)
2739 return WSAEFAULT;
2741 if (name->sa_family == WS_AF_INET)
2743 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2744 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2746 /* Trying to connect to magic replace-loopback address,
2747 * assuming we really want to connect to localhost */
2748 TRACE("Trying to connect to magic IP address, using "
2749 "INADDR_LOOPBACK instead.\n");
2750 in4->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
2754 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
2755 return 0;
2757 return wsaErrno();
2760 /***********************************************************************
2761 * connect (WS2_32.4)
2763 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
2765 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2767 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2769 if (fd != -1)
2771 NTSTATUS status;
2772 BOOL is_blocking;
2773 int ret = do_connect(fd, name, namelen);
2774 if (ret == 0)
2775 goto connect_success;
2777 if (ret == WSAEINPROGRESS)
2779 /* tell wineserver that a connection is in progress */
2780 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2781 FD_CONNECT,
2782 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2783 status = _is_blocking( s, &is_blocking );
2784 if (status)
2786 release_sock_fd( s, fd );
2787 set_error( status );
2788 return SOCKET_ERROR;
2790 if (is_blocking)
2792 int result;
2793 /* block here */
2794 do_block(fd, POLLIN | POLLOUT, -1);
2795 _sync_sock_state(s); /* let wineserver notice connection */
2796 /* retrieve any error codes from it */
2797 result = _get_sock_error(s, FD_CONNECT_BIT);
2798 if (result)
2799 SetLastError(NtStatusToWSAError(result));
2800 else
2802 goto connect_success;
2805 else
2807 SetLastError(WSAEWOULDBLOCK);
2810 else
2812 SetLastError(ret);
2814 release_sock_fd( s, fd );
2816 return SOCKET_ERROR;
2818 connect_success:
2819 release_sock_fd( s, fd );
2820 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2821 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2822 FD_CONNECT|FD_WINE_LISTENING);
2823 return 0;
2826 /***********************************************************************
2827 * WSAConnect (WS2_32.30)
2829 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
2830 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
2831 LPQOS lpSQOS, LPQOS lpGQOS )
2833 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
2834 FIXME("unsupported parameters!\n");
2835 return WS_connect( s, name, namelen );
2838 /***********************************************************************
2839 * ConnectEx
2841 static BOOL WINAPI WS2_ConnectEx(SOCKET s, const struct WS_sockaddr* name, int namelen,
2842 PVOID sendBuf, DWORD sendBufLen, LPDWORD sent, LPOVERLAPPED ov)
2844 int fd, ret, status;
2845 union generic_unix_sockaddr uaddr;
2846 socklen_t uaddrlen = sizeof(uaddr);
2848 if (!ov)
2850 SetLastError( ERROR_INVALID_PARAMETER );
2851 return FALSE;
2854 fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2855 if (fd == -1)
2857 SetLastError( WSAENOTSOCK );
2858 return FALSE;
2861 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
2862 s, name, debugstr_sockaddr(name), namelen, sendBuf, sendBufLen, ov);
2864 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
2866 SetLastError(wsaErrno());
2867 return FALSE;
2869 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
2871 SetLastError(WSAEINVAL);
2872 return FALSE;
2875 ret = do_connect(fd, name, namelen);
2876 if (ret == 0)
2878 WSABUF wsabuf;
2880 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2881 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2882 FD_CONNECT|FD_WINE_LISTENING);
2884 wsabuf.len = sendBufLen;
2885 wsabuf.buf = (char*) sendBuf;
2887 /* WSASend takes care of completion if need be */
2888 if (WSASend(s, &wsabuf, sendBuf ? 1 : 0, sent, 0, ov, NULL) != SOCKET_ERROR)
2889 goto connection_success;
2891 else if (ret == WSAEINPROGRESS)
2893 struct ws2_async *wsa;
2894 ULONG_PTR cvalue = (((ULONG_PTR)ov->hEvent & 1) == 0) ? (ULONG_PTR)ov : 0;
2896 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2897 FD_CONNECT,
2898 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2900 /* Indirectly call WSASend */
2901 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( struct ws2_async, iovec[1] ))))
2903 SetLastError(WSAEFAULT);
2905 else
2907 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)ov;
2908 iosb->u.Status = STATUS_PENDING;
2909 iosb->Information = 0;
2911 wsa->hSocket = SOCKET2HANDLE(s);
2912 wsa->addr = NULL;
2913 wsa->addrlen.val = 0;
2914 wsa->flags = 0;
2915 wsa->lpFlags = &wsa->flags;
2916 wsa->control = NULL;
2917 wsa->n_iovecs = sendBuf ? 1 : 0;
2918 wsa->first_iovec = 0;
2919 wsa->completion_func = NULL;
2920 wsa->iovec[0].iov_base = sendBuf;
2921 wsa->iovec[0].iov_len = sendBufLen;
2923 SERVER_START_REQ( register_async )
2925 req->type = ASYNC_TYPE_WRITE;
2926 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2927 req->async.callback = wine_server_client_ptr( WS2_async_send );
2928 req->async.iosb = wine_server_client_ptr( iosb );
2929 req->async.arg = wine_server_client_ptr( wsa );
2930 req->async.event = wine_server_obj_handle( ov->hEvent );
2931 req->async.cvalue = cvalue;
2932 status = wine_server_call( req );
2934 SERVER_END_REQ;
2936 if (status != STATUS_PENDING) HeapFree(GetProcessHeap(), 0, wsa);
2938 /* If the connect already failed */
2939 if (status == STATUS_PIPE_DISCONNECTED)
2940 status = _get_sock_error(s, FD_CONNECT_BIT);
2941 SetLastError( NtStatusToWSAError(status) );
2944 else
2946 SetLastError(ret);
2949 release_sock_fd( s, fd );
2950 return FALSE;
2952 connection_success:
2953 release_sock_fd( s, fd );
2954 return TRUE;
2958 /***********************************************************************
2959 * getpeername (WS2_32.5)
2961 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
2963 int fd;
2964 int res;
2966 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
2968 fd = get_sock_fd( s, 0, NULL );
2969 res = SOCKET_ERROR;
2971 if (fd != -1)
2973 union generic_unix_sockaddr uaddr;
2974 socklen_t uaddrlen = sizeof(uaddr);
2976 if (getpeername(fd, &uaddr.addr, &uaddrlen) == 0)
2978 if (!name || !namelen)
2979 SetLastError(WSAEFAULT);
2980 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
2981 /* The buffer was too small */
2982 SetLastError(WSAEFAULT);
2983 else
2984 res = 0;
2986 else
2987 SetLastError(wsaErrno());
2988 release_sock_fd( s, fd );
2990 return res;
2993 /***********************************************************************
2994 * getsockname (WS2_32.6)
2996 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
2998 int fd;
2999 int res;
3001 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
3003 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
3004 if( (name == NULL) || (namelen == NULL) )
3006 SetLastError( WSAEFAULT );
3007 return SOCKET_ERROR;
3010 fd = get_sock_fd( s, 0, NULL );
3011 res = SOCKET_ERROR;
3013 if (fd != -1)
3015 union generic_unix_sockaddr uaddr;
3016 socklen_t uaddrlen = sizeof(uaddr);
3018 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
3020 SetLastError(wsaErrno());
3022 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
3024 SetLastError(WSAEINVAL);
3026 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3028 /* The buffer was too small */
3029 SetLastError(WSAEFAULT);
3031 else
3033 res=0;
3034 TRACE("=> %s\n", debugstr_sockaddr(name));
3036 release_sock_fd( s, fd );
3038 return res;
3041 /***********************************************************************
3042 * getsockopt (WS2_32.7)
3044 INT WINAPI WS_getsockopt(SOCKET s, INT level,
3045 INT optname, char *optval, INT *optlen)
3047 int fd;
3048 INT ret = 0;
3050 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
3051 s, level, optname, optval, optlen ? *optlen : 0);
3053 switch(level)
3055 case WS_SOL_SOCKET:
3057 switch(optname)
3059 /* Handle common cases. The special cases are below, sorted
3060 * alphabetically */
3061 case WS_SO_BROADCAST:
3062 case WS_SO_DEBUG:
3063 case WS_SO_ERROR:
3064 case WS_SO_KEEPALIVE:
3065 case WS_SO_OOBINLINE:
3066 case WS_SO_RCVBUF:
3067 case WS_SO_REUSEADDR:
3068 case WS_SO_SNDBUF:
3069 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3070 return SOCKET_ERROR;
3071 convert_sockopt(&level, &optname);
3072 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3074 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3075 ret = SOCKET_ERROR;
3077 release_sock_fd( s, fd );
3078 return ret;
3079 case WS_SO_ACCEPTCONN:
3080 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3081 return SOCKET_ERROR;
3082 if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, optval, (socklen_t *)optlen) != 0 )
3084 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3085 ret = SOCKET_ERROR;
3087 else
3089 /* BSD returns != 0 while Windows return exact == 1 */
3090 if (*(int *)optval) *(int *)optval = 1;
3092 release_sock_fd( s, fd );
3093 return ret;
3094 case WS_SO_DONTLINGER:
3096 struct linger lingval;
3097 socklen_t len = sizeof(struct linger);
3099 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
3101 SetLastError(WSAEFAULT);
3102 return SOCKET_ERROR;
3104 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3105 return SOCKET_ERROR;
3107 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
3109 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3110 ret = SOCKET_ERROR;
3112 else
3114 *(BOOL *)optval = !lingval.l_onoff;
3115 *optlen = sizeof(BOOL);
3118 release_sock_fd( s, fd );
3119 return ret;
3122 case WS_SO_CONNECT_TIME:
3124 static int pretendtime = 0;
3125 struct WS_sockaddr addr;
3126 int len = sizeof(addr);
3128 if (!optlen || *optlen < sizeof(DWORD) || !optval)
3130 SetLastError(WSAEFAULT);
3131 return SOCKET_ERROR;
3133 if (WS_getpeername(s, &addr, &len) == SOCKET_ERROR)
3134 *(DWORD *)optval = ~0u;
3135 else
3137 if (!pretendtime) FIXME("WS_SO_CONNECT_TIME - faking results\n");
3138 *(DWORD *)optval = pretendtime++;
3140 *optlen = sizeof(DWORD);
3141 return ret;
3143 /* As mentioned in setsockopt, Windows ignores this, so we
3144 * always return true here */
3145 case WS_SO_DONTROUTE:
3146 if (!optlen || *optlen < sizeof(BOOL) || !optval)
3148 SetLastError(WSAEFAULT);
3149 return SOCKET_ERROR;
3151 *(BOOL *)optval = TRUE;
3152 *optlen = sizeof(BOOL);
3153 return 0;
3155 case WS_SO_LINGER:
3157 struct linger lingval;
3158 int so_type;
3159 socklen_t len = sizeof(struct linger), slen = sizeof(int);
3161 /* struct linger and LINGER have different sizes */
3162 if (!optlen || *optlen < sizeof(LINGER) || !optval)
3164 SetLastError(WSAEFAULT);
3165 return SOCKET_ERROR;
3167 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3168 return SOCKET_ERROR;
3170 if ((getsockopt(fd, SOL_SOCKET, SO_TYPE, &so_type, &slen) == 0 && so_type == SOCK_DGRAM))
3172 SetLastError(WSAENOPROTOOPT);
3173 ret = SOCKET_ERROR;
3175 else if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0)
3177 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3178 ret = SOCKET_ERROR;
3180 else
3182 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
3183 ((LINGER *)optval)->l_linger = lingval.l_linger;
3184 *optlen = sizeof(struct linger);
3187 release_sock_fd( s, fd );
3188 return ret;
3191 case WS_SO_MAX_MSG_SIZE:
3192 if (!optlen || *optlen < sizeof(int) || !optval)
3194 SetLastError(WSAEFAULT);
3195 return SOCKET_ERROR;
3197 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
3198 *(int *)optval = 65507;
3199 *optlen = sizeof(int);
3200 return 0;
3202 /* SO_OPENTYPE does not require a valid socket handle. */
3203 case WS_SO_OPENTYPE:
3204 if (!optlen || *optlen < sizeof(int) || !optval)
3206 SetLastError(WSAEFAULT);
3207 return SOCKET_ERROR;
3209 *(int *)optval = get_per_thread_data()->opentype;
3210 *optlen = sizeof(int);
3211 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
3212 return 0;
3213 case WS_SO_PROTOCOL_INFOA:
3214 case WS_SO_PROTOCOL_INFOW:
3216 int size;
3217 WSAPROTOCOL_INFOW infow;
3219 ret = ws_protocol_info(s, optname == WS_SO_PROTOCOL_INFOW, &infow, &size);
3220 if (ret)
3222 if (!optlen || !optval || *optlen < size)
3224 if(optlen) *optlen = size;
3225 ret = 0;
3226 SetLastError(WSAEFAULT);
3228 else
3229 memcpy(optval, &infow, size);
3231 return ret ? 0 : SOCKET_ERROR;
3233 #ifdef SO_RCVTIMEO
3234 case WS_SO_RCVTIMEO:
3235 #endif
3236 #ifdef SO_SNDTIMEO
3237 case WS_SO_SNDTIMEO:
3238 #endif
3239 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
3241 struct timeval tv;
3242 socklen_t len = sizeof(struct timeval);
3244 if (!optlen || *optlen < sizeof(int)|| !optval)
3246 SetLastError(WSAEFAULT);
3247 return SOCKET_ERROR;
3249 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3250 return SOCKET_ERROR;
3252 convert_sockopt(&level, &optname);
3253 if (getsockopt(fd, level, optname, &tv, &len) != 0 )
3255 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3256 ret = SOCKET_ERROR;
3258 else
3260 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
3261 *optlen = sizeof(int);
3264 release_sock_fd( s, fd );
3265 return ret;
3267 #endif
3268 case WS_SO_TYPE:
3270 if (!optlen || *optlen < sizeof(int) || !optval)
3272 SetLastError(WSAEFAULT);
3273 return SOCKET_ERROR;
3275 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3276 return SOCKET_ERROR;
3278 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, optval, (socklen_t *)optlen) != 0 )
3280 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3281 ret = SOCKET_ERROR;
3283 else
3284 (*(int *)optval) = convert_socktype_u2w(*(int *)optval);
3286 release_sock_fd( s, fd );
3287 return ret;
3289 default:
3290 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
3291 SetLastError(WSAENOPROTOOPT);
3292 return SOCKET_ERROR;
3293 } /* end switch(optname) */
3294 }/* end case WS_SOL_SOCKET */
3295 #ifdef HAS_IPX
3296 case WS_NSPROTO_IPX:
3298 struct WS_sockaddr_ipx addr;
3299 IPX_ADDRESS_DATA *data;
3300 int namelen;
3301 switch(optname)
3303 case IPX_PTYPE:
3304 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3305 #ifdef SOL_IPX
3306 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (socklen_t *)optlen) == -1)
3308 ret = SOCKET_ERROR;
3310 #else
3312 struct ipx val;
3313 socklen_t len=sizeof(struct ipx);
3314 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
3315 ret = SOCKET_ERROR;
3316 else
3317 *optval = (int)val.ipx_pt;
3319 #endif
3320 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
3321 release_sock_fd( s, fd );
3322 return ret;
3324 case IPX_ADDRESS:
3326 * On a Win2000 system with one network card there are usually
3327 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
3328 * Using this call you can then retrieve info about this all.
3329 * In case of Linux it is a bit different. Usually you have
3330 * only "one" device active and further it is not possible to
3331 * query things like the linkspeed.
3333 FIXME("IPX_ADDRESS\n");
3334 namelen = sizeof(struct WS_sockaddr_ipx);
3335 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
3336 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
3338 data = (IPX_ADDRESS_DATA*)optval;
3339 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
3340 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
3341 data->adapternum = 0;
3342 data->wan = FALSE; /* We are not on a wan for now .. */
3343 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
3344 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
3345 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
3346 * note 1MB = 1000kB in this case */
3347 return 0;
3349 case IPX_MAX_ADAPTER_NUM:
3350 FIXME("IPX_MAX_ADAPTER_NUM\n");
3351 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
3352 return 0;
3354 default:
3355 FIXME("IPX optname:%x\n", optname);
3356 return SOCKET_ERROR;
3357 }/* end switch(optname) */
3358 } /* end case WS_NSPROTO_IPX */
3359 #endif
3361 #ifdef HAS_IRDA
3362 #define MAX_IRDA_DEVICES 10
3364 case WS_SOL_IRLMP:
3365 switch(optname)
3367 case WS_IRLMP_ENUMDEVICES:
3369 char buf[sizeof(struct irda_device_list) +
3370 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
3371 int res;
3372 socklen_t len = sizeof(buf);
3374 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3375 return SOCKET_ERROR;
3376 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
3377 release_sock_fd( s, fd );
3378 if (res < 0)
3380 SetLastError(wsaErrno());
3381 return SOCKET_ERROR;
3383 else
3385 struct irda_device_list *src = (struct irda_device_list *)buf;
3386 DEVICELIST *dst = (DEVICELIST *)optval;
3387 INT needed = sizeof(DEVICELIST);
3388 unsigned int i;
3390 if (src->len > 0)
3391 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
3392 if (*optlen < needed)
3394 SetLastError(WSAEFAULT);
3395 return SOCKET_ERROR;
3397 *optlen = needed;
3398 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
3399 dst->numDevice = src->len;
3400 for (i = 0; i < src->len; i++)
3402 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
3403 src->dev[i].saddr, src->dev[i].daddr,
3404 src->dev[i].info, src->dev[i].hints[0],
3405 src->dev[i].hints[1]);
3406 memcpy( dst->Device[i].irdaDeviceID,
3407 &src->dev[i].daddr,
3408 sizeof(dst->Device[i].irdaDeviceID) ) ;
3409 memcpy( dst->Device[i].irdaDeviceName,
3410 src->dev[i].info,
3411 sizeof(dst->Device[i].irdaDeviceName) ) ;
3412 memcpy( &dst->Device[i].irdaDeviceHints1,
3413 &src->dev[i].hints[0],
3414 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
3415 memcpy( &dst->Device[i].irdaDeviceHints2,
3416 &src->dev[i].hints[1],
3417 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
3418 dst->Device[i].irdaCharSet = src->dev[i].charset;
3420 return 0;
3423 default:
3424 FIXME("IrDA optname:0x%x\n", optname);
3425 return SOCKET_ERROR;
3427 break; /* case WS_SOL_IRLMP */
3428 #undef MAX_IRDA_DEVICES
3429 #endif
3431 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3432 case WS_IPPROTO_TCP:
3433 switch(optname)
3435 case WS_TCP_NODELAY:
3436 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3437 return SOCKET_ERROR;
3438 convert_sockopt(&level, &optname);
3439 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3441 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3442 ret = SOCKET_ERROR;
3444 release_sock_fd( s, fd );
3445 return ret;
3447 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
3448 return SOCKET_ERROR;
3450 case WS_IPPROTO_IP:
3451 switch(optname)
3453 case WS_IP_ADD_MEMBERSHIP:
3454 case WS_IP_DROP_MEMBERSHIP:
3455 #ifdef IP_HDRINCL
3456 case WS_IP_HDRINCL:
3457 #endif
3458 case WS_IP_MULTICAST_IF:
3459 case WS_IP_MULTICAST_LOOP:
3460 case WS_IP_MULTICAST_TTL:
3461 case WS_IP_OPTIONS:
3462 #ifdef IP_PKTINFO
3463 case WS_IP_PKTINFO:
3464 #endif
3465 case WS_IP_TOS:
3466 case WS_IP_TTL:
3467 #ifdef IP_UNICAST_IF
3468 case WS_IP_UNICAST_IF:
3469 #endif
3470 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3471 return SOCKET_ERROR;
3472 convert_sockopt(&level, &optname);
3473 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3475 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3476 ret = SOCKET_ERROR;
3478 release_sock_fd( s, fd );
3479 return ret;
3480 case WS_IP_DONTFRAGMENT:
3481 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
3482 *(BOOL*)optval = FALSE;
3483 return 0;
3485 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
3486 return SOCKET_ERROR;
3488 case WS_IPPROTO_IPV6:
3489 switch(optname)
3491 #ifdef IPV6_ADD_MEMBERSHIP
3492 case WS_IPV6_ADD_MEMBERSHIP:
3493 #endif
3494 #ifdef IPV6_DROP_MEMBERSHIP
3495 case WS_IPV6_DROP_MEMBERSHIP:
3496 #endif
3497 case WS_IPV6_MULTICAST_IF:
3498 case WS_IPV6_MULTICAST_HOPS:
3499 case WS_IPV6_MULTICAST_LOOP:
3500 case WS_IPV6_UNICAST_HOPS:
3501 case WS_IPV6_V6ONLY:
3502 #ifdef IPV6_UNICAST_IF
3503 case WS_IPV6_UNICAST_IF:
3504 #endif
3505 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3506 return SOCKET_ERROR;
3507 convert_sockopt(&level, &optname);
3508 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3510 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3511 ret = SOCKET_ERROR;
3513 release_sock_fd( s, fd );
3514 return ret;
3515 case WS_IPV6_DONTFRAG:
3516 FIXME("WS_IPV6_DONTFRAG is always false!\n");
3517 *(BOOL*)optval = FALSE;
3518 return 0;
3520 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
3521 return SOCKET_ERROR;
3523 default:
3524 WARN("Unknown level: 0x%08x\n", level);
3525 SetLastError(WSAEINVAL);
3526 return SOCKET_ERROR;
3527 } /* end switch(level) */
3530 /***********************************************************************
3531 * htonl (WS2_32.8)
3533 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
3535 return htonl(hostlong);
3539 /***********************************************************************
3540 * htons (WS2_32.9)
3542 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
3544 return htons(hostshort);
3547 /***********************************************************************
3548 * WSAHtonl (WS2_32.46)
3549 * From MSDN description of error codes, this function should also
3550 * check if WinSock has been initialized and the socket is a valid
3551 * socket. But why? This function only translates a host byte order
3552 * u_long into a network byte order u_long...
3554 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
3556 if (lpnetlong)
3558 *lpnetlong = htonl(hostlong);
3559 return 0;
3561 WSASetLastError(WSAEFAULT);
3562 return SOCKET_ERROR;
3565 /***********************************************************************
3566 * WSAHtons (WS2_32.47)
3567 * From MSDN description of error codes, this function should also
3568 * check if WinSock has been initialized and the socket is a valid
3569 * socket. But why? This function only translates a host byte order
3570 * u_short into a network byte order u_short...
3572 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
3575 if (lpnetshort)
3577 *lpnetshort = htons(hostshort);
3578 return 0;
3580 WSASetLastError(WSAEFAULT);
3581 return SOCKET_ERROR;
3585 /***********************************************************************
3586 * inet_addr (WS2_32.11)
3588 WS_u_long WINAPI WS_inet_addr(const char *cp)
3590 if (!cp) return INADDR_NONE;
3591 return inet_addr(cp);
3595 /***********************************************************************
3596 * ntohl (WS2_32.14)
3598 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
3600 return ntohl(netlong);
3604 /***********************************************************************
3605 * ntohs (WS2_32.15)
3607 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
3609 return ntohs(netshort);
3613 /***********************************************************************
3614 * inet_ntoa (WS2_32.12)
3616 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
3618 char* s = inet_ntoa(*((struct in_addr*)&in));
3619 if( s )
3621 struct per_thread_data *data = get_per_thread_data();
3622 strcpy(data->ntoa_buffer, s);
3623 return data->ntoa_buffer;
3625 SetLastError(wsaErrno());
3626 return NULL;
3629 static const char *debugstr_wsaioctl(DWORD ioctl)
3631 const char *buf_type, *family;
3633 switch(ioctl & 0x18000000)
3635 case WS_IOC_WS2:
3636 family = "IOC_WS2";
3637 break;
3638 case WS_IOC_PROTOCOL:
3639 family = "IOC_PROTOCOL";
3640 break;
3641 case WS_IOC_VENDOR:
3642 family = "IOC_VENDOR";
3643 break;
3644 default: /* WS_IOC_UNIX */
3646 BYTE size = (ioctl >> 16) & WS_IOCPARM_MASK;
3647 char x = (ioctl & 0xff00) >> 8;
3648 BYTE y = ioctl & 0xff;
3649 char args[14];
3651 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3653 case WS_IOC_VOID:
3654 buf_type = "_IO";
3655 sprintf(args, "%d, %d", x, y);
3656 break;
3657 case WS_IOC_IN:
3658 buf_type = "_IOW";
3659 sprintf(args, "'%c', %d, %d", x, y, size);
3660 break;
3661 case WS_IOC_OUT:
3662 buf_type = "_IOR";
3663 sprintf(args, "'%c', %d, %d", x, y, size);
3664 break;
3665 default:
3666 buf_type = "?";
3667 sprintf(args, "'%c', %d, %d", x, y, size);
3668 break;
3670 return wine_dbg_sprintf("%s(%s)", buf_type, args);
3674 /* We are different from WS_IOC_UNIX. */
3675 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3677 case WS_IOC_VOID:
3678 buf_type = "_WSAIO";
3679 break;
3680 case WS_IOC_INOUT:
3681 buf_type = "_WSAIORW";
3682 break;
3683 case WS_IOC_IN:
3684 buf_type = "_WSAIOW";
3685 break;
3686 case WS_IOC_OUT:
3687 buf_type = "_WSAIOR";
3688 break;
3689 default:
3690 buf_type = "?";
3691 break;
3694 return wine_dbg_sprintf("%s(%s, %d)", buf_type, family,
3695 (USHORT)(ioctl & 0xffff));
3698 /* do an ioctl call through the server */
3699 static DWORD server_ioctl_sock( SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size,
3700 LPVOID out_buff, DWORD out_size, LPDWORD ret_size,
3701 LPWSAOVERLAPPED overlapped,
3702 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
3704 HANDLE event = overlapped ? overlapped->hEvent : 0;
3705 HANDLE handle = SOCKET2HANDLE( s );
3706 struct ws2_async *wsa;
3707 NTSTATUS status;
3708 PIO_STATUS_BLOCK io;
3710 if (!(wsa = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wsa) )))
3711 return WSA_NOT_ENOUGH_MEMORY;
3712 wsa->hSocket = handle;
3713 wsa->user_overlapped = overlapped;
3714 wsa->completion_func = completion;
3715 io = (overlapped ? (PIO_STATUS_BLOCK)overlapped : &wsa->local_iosb);
3717 status = NtDeviceIoControlFile( handle, event, (PIO_APC_ROUTINE)ws2_async_apc, wsa, io, code,
3718 in_buff, in_size, out_buff, out_size );
3719 if (status == STATUS_NOT_SUPPORTED)
3721 FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
3722 code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
3724 else if (status == STATUS_SUCCESS)
3725 *ret_size = io->Information; /* "Information" is the size written to the output buffer */
3727 if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, wsa );
3729 return NtStatusToWSAError( status );
3732 /**********************************************************************
3733 * WSAIoctl (WS2_32.50)
3736 INT WINAPI WSAIoctl(SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size, LPVOID out_buff,
3737 DWORD out_size, LPDWORD ret_size, LPWSAOVERLAPPED overlapped,
3738 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
3740 int fd;
3741 DWORD status = 0, total = 0;
3743 TRACE("%ld, %s, %p, %d, %p, %d, %p, %p, %p\n",
3744 s, debugstr_wsaioctl(code), in_buff, in_size, out_buff, out_size, ret_size, overlapped, completion);
3746 switch (code)
3748 case WS_FIONBIO:
3749 if (in_size != sizeof(WS_u_long) || IS_INTRESOURCE(in_buff))
3751 WSASetLastError(WSAEFAULT);
3752 return SOCKET_ERROR;
3754 TRACE("-> FIONBIO (%x)\n", *(WS_u_long*)in_buff);
3755 if (_get_sock_mask(s))
3757 /* AsyncSelect()'ed sockets are always nonblocking */
3758 if (!*(WS_u_long *)in_buff) status = WSAEINVAL;
3759 break;
3761 if (*(WS_u_long *)in_buff)
3762 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
3763 else
3764 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
3765 break;
3767 case WS_FIONREAD:
3769 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
3771 WSASetLastError(WSAEFAULT);
3772 return SOCKET_ERROR;
3774 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3775 if (ioctl(fd, FIONREAD, out_buff ) == -1)
3776 status = (errno == EBADF) ? WSAENOTSOCK : wsaErrno();
3777 release_sock_fd( s, fd );
3778 break;
3781 case WS_SIOCATMARK:
3783 unsigned int oob = 0, atmark = 0;
3784 socklen_t oobsize = sizeof(int);
3785 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
3787 WSASetLastError(WSAEFAULT);
3788 return SOCKET_ERROR;
3790 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3791 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
3792 if ((getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &oob, &oobsize ) == -1)
3793 || (!oob && ioctl(fd, SIOCATMARK, &atmark ) == -1))
3794 status = (errno == EBADF) ? WSAENOTSOCK : wsaErrno();
3795 else
3797 /* The SIOCATMARK value read from ioctl() is reversed
3798 * because BSD returns TRUE if it's in the OOB mark
3799 * while Windows returns TRUE if there are NO OOB bytes.
3801 (*(WS_u_long *) out_buff) = oob | !atmark;
3804 release_sock_fd( s, fd );
3805 break;
3808 case WS_FIOASYNC:
3809 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
3810 SetLastError(WSAEINVAL);
3811 return SOCKET_ERROR;
3813 case WS_SIO_GET_INTERFACE_LIST:
3815 INTERFACE_INFO* intArray = out_buff;
3816 DWORD size, numInt = 0, apiReturn;
3818 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
3820 if (!out_buff || !ret_size)
3822 WSASetLastError(WSAEFAULT);
3823 return SOCKET_ERROR;
3826 fd = get_sock_fd( s, 0, NULL );
3827 if (fd == -1) return SOCKET_ERROR;
3829 apiReturn = GetAdaptersInfo(NULL, &size);
3830 if (apiReturn == ERROR_BUFFER_OVERFLOW)
3832 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
3834 if (table)
3836 if (GetAdaptersInfo(table, &size) == NO_ERROR)
3838 PIP_ADAPTER_INFO ptr;
3840 for (ptr = table, numInt = 0; ptr; ptr = ptr->Next)
3842 unsigned int addr, mask, bcast;
3843 struct ifreq ifInfo;
3845 /* Skip interfaces without an IPv4 address. */
3846 if (ptr->IpAddressList.IpAddress.String[0] == '\0')
3847 continue;
3849 if ((numInt + 1)*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > out_size)
3851 WARN("Buffer too small = %u, out_size = %u\n", numInt + 1, out_size);
3852 status = WSAEFAULT;
3853 break;
3856 /* Socket Status Flags */
3857 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
3858 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
3860 ERR("Error obtaining status flags for socket!\n");
3861 status = WSAEINVAL;
3862 break;
3864 else
3866 /* set flags; the values of IFF_* are not the same
3867 under Linux and Windows, therefore must generate
3868 new flags */
3869 intArray->iiFlags = 0;
3870 if (ifInfo.ifr_flags & IFF_BROADCAST)
3871 intArray->iiFlags |= WS_IFF_BROADCAST;
3872 #ifdef IFF_POINTOPOINT
3873 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
3874 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
3875 #endif
3876 if (ifInfo.ifr_flags & IFF_LOOPBACK)
3877 intArray->iiFlags |= WS_IFF_LOOPBACK;
3878 if (ifInfo.ifr_flags & IFF_UP)
3879 intArray->iiFlags |= WS_IFF_UP;
3880 if (ifInfo.ifr_flags & IFF_MULTICAST)
3881 intArray->iiFlags |= WS_IFF_MULTICAST;
3884 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
3885 mask = inet_addr(ptr->IpAddressList.IpMask.String);
3886 bcast = addr | ~mask;
3887 intArray->iiAddress.AddressIn.sin_family = AF_INET;
3888 intArray->iiAddress.AddressIn.sin_port = 0;
3889 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
3890 addr;
3891 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
3892 intArray->iiNetmask.AddressIn.sin_port = 0;
3893 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
3894 mask;
3895 intArray->iiBroadcastAddress.AddressIn.sin_family =
3896 AF_INET;
3897 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
3898 intArray->iiBroadcastAddress.AddressIn.sin_addr.
3899 WS_s_addr = bcast;
3900 intArray++;
3901 numInt++;
3904 else
3906 ERR("Unable to get interface table!\n");
3907 status = WSAEINVAL;
3909 HeapFree(GetProcessHeap(),0,table);
3911 else status = WSAEINVAL;
3913 else if (apiReturn != ERROR_NO_DATA)
3915 ERR("Unable to get interface table!\n");
3916 status = WSAEINVAL;
3918 /* Calculate the size of the array being returned */
3919 total = sizeof(INTERFACE_INFO) * numInt;
3920 release_sock_fd( s, fd );
3921 break;
3924 case WS_SIO_ADDRESS_LIST_QUERY:
3926 DWORD size;
3928 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
3930 if (!ret_size)
3932 WSASetLastError(WSAEFAULT);
3933 return SOCKET_ERROR;
3936 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
3938 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
3939 DWORD num;
3941 if (!table || GetAdaptersInfo(table, &size))
3943 HeapFree(GetProcessHeap(), 0, table);
3944 status = WSAEINVAL;
3945 break;
3948 for (p = table, num = 0; p; p = p->Next)
3949 if (p->IpAddressList.IpAddress.String[0]) num++;
3951 total = sizeof(SOCKET_ADDRESS_LIST) + sizeof(SOCKET_ADDRESS) * (num - 1);
3952 total += sizeof(SOCKADDR) * num;
3954 if (total > out_size)
3956 HeapFree(GetProcessHeap(), 0, table);
3957 status = WSAEFAULT;
3958 break;
3961 if (out_buff)
3963 unsigned int i;
3964 SOCKET_ADDRESS *sa;
3965 SOCKET_ADDRESS_LIST *sa_list = out_buff;
3966 SOCKADDR_IN *sockaddr;
3968 sa = sa_list->Address;
3969 sockaddr = (SOCKADDR_IN *)((char *)sa + num * sizeof(SOCKET_ADDRESS));
3970 sa_list->iAddressCount = num;
3972 for (p = table, i = 0; p; p = p->Next)
3974 if (!p->IpAddressList.IpAddress.String[0]) continue;
3976 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
3977 sa[i].iSockaddrLength = sizeof(SOCKADDR);
3979 sockaddr[i].sin_family = AF_INET;
3980 sockaddr[i].sin_port = 0;
3981 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
3982 i++;
3986 HeapFree(GetProcessHeap(), 0, table);
3988 else
3990 WARN("unable to get IP address list\n");
3991 status = WSAEINVAL;
3993 break;
3996 case WS_SIO_FLUSH:
3997 FIXME("SIO_FLUSH: stub.\n");
3998 break;
4000 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
4002 static const GUID connectex_guid = WSAID_CONNECTEX;
4003 static const GUID disconnectex_guid = WSAID_DISCONNECTEX;
4004 static const GUID acceptex_guid = WSAID_ACCEPTEX;
4005 static const GUID getaccepexsockaddrs_guid = WSAID_GETACCEPTEXSOCKADDRS;
4006 static const GUID transmitfile_guid = WSAID_TRANSMITFILE;
4007 static const GUID transmitpackets_guid = WSAID_TRANSMITPACKETS;
4008 static const GUID wsarecvmsg_guid = WSAID_WSARECVMSG;
4009 static const GUID wsasendmsg_guid = WSAID_WSASENDMSG;
4011 if ( IsEqualGUID(&connectex_guid, in_buff) )
4013 *(LPFN_CONNECTEX *)out_buff = WS2_ConnectEx;
4014 break;
4016 else if ( IsEqualGUID(&disconnectex_guid, in_buff) )
4018 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented DisconnectEx\n");
4020 else if ( IsEqualGUID(&acceptex_guid, in_buff) )
4022 *(LPFN_ACCEPTEX *)out_buff = WS2_AcceptEx;
4023 break;
4025 else if ( IsEqualGUID(&getaccepexsockaddrs_guid, in_buff) )
4027 *(LPFN_GETACCEPTEXSOCKADDRS *)out_buff = WS2_GetAcceptExSockaddrs;
4028 break;
4030 else if ( IsEqualGUID(&transmitfile_guid, in_buff) )
4032 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitFile\n");
4034 else if ( IsEqualGUID(&transmitpackets_guid, in_buff) )
4036 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitPackets\n");
4038 else if ( IsEqualGUID(&wsarecvmsg_guid, in_buff) )
4040 *(LPFN_WSARECVMSG *)out_buff = WS2_WSARecvMsg;
4041 break;
4043 else if ( IsEqualGUID(&wsasendmsg_guid, in_buff) )
4045 *(LPFN_WSASENDMSG *)out_buff = WSASendMsg;
4046 break;
4048 else
4049 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff));
4051 status = WSAEOPNOTSUPP;
4052 break;
4054 case WS_SIO_KEEPALIVE_VALS:
4056 struct tcp_keepalive *k;
4057 int keepalive, keepidle, keepintvl;
4059 if (!in_buff || in_size < sizeof(struct tcp_keepalive))
4061 WSASetLastError(WSAEFAULT);
4062 return SOCKET_ERROR;
4065 k = in_buff;
4066 keepalive = k->onoff ? 1 : 0;
4067 keepidle = max( 1, (k->keepalivetime + 500) / 1000 );
4068 keepintvl = max( 1, (k->keepaliveinterval + 500) / 1000 );
4070 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
4072 fd = get_sock_fd(s, 0, NULL);
4073 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
4074 status = WSAEINVAL;
4075 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
4076 /* these values need to be set only if SO_KEEPALIVE is enabled */
4077 else if(keepalive)
4079 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
4080 status = WSAEINVAL;
4081 else if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
4082 status = WSAEINVAL;
4084 #else
4085 else
4086 FIXME("ignoring keepalive interval and timeout\n");
4087 #endif
4088 release_sock_fd(s, fd);
4089 break;
4091 case WS_SIO_ROUTING_INTERFACE_QUERY:
4093 struct WS_sockaddr *daddr = (struct WS_sockaddr *)in_buff;
4094 struct WS_sockaddr_in *daddr_in = (struct WS_sockaddr_in *)daddr;
4095 struct WS_sockaddr_in *saddr_in = out_buff;
4096 MIB_IPFORWARDROW row;
4097 PMIB_IPADDRTABLE ipAddrTable = NULL;
4098 DWORD size, i, found_index;
4100 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
4102 if (!in_buff || in_size < sizeof(struct WS_sockaddr) ||
4103 !out_buff || out_size < sizeof(struct WS_sockaddr_in) || !ret_size)
4105 WSASetLastError(WSAEFAULT);
4106 return SOCKET_ERROR;
4108 if (daddr->sa_family != AF_INET)
4110 FIXME("unsupported address family %d\n", daddr->sa_family);
4111 status = WSAEAFNOSUPPORT;
4112 break;
4114 if (GetBestRoute(daddr_in->sin_addr.S_un.S_addr, 0, &row) != NOERROR ||
4115 GetIpAddrTable(NULL, &size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
4117 status = WSAEFAULT;
4118 break;
4120 ipAddrTable = HeapAlloc(GetProcessHeap(), 0, size);
4121 if (GetIpAddrTable(ipAddrTable, &size, FALSE))
4123 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4124 status = WSAEFAULT;
4125 break;
4127 for (i = 0, found_index = ipAddrTable->dwNumEntries;
4128 i < ipAddrTable->dwNumEntries; i++)
4130 if (ipAddrTable->table[i].dwIndex == row.dwForwardIfIndex)
4131 found_index = i;
4133 if (found_index == ipAddrTable->dwNumEntries)
4135 ERR("no matching IP address for interface %d\n",
4136 row.dwForwardIfIndex);
4137 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4138 status = WSAEFAULT;
4139 break;
4141 saddr_in->sin_family = AF_INET;
4142 saddr_in->sin_addr.S_un.S_addr = ipAddrTable->table[found_index].dwAddr;
4143 saddr_in->sin_port = 0;
4144 total = sizeof(struct WS_sockaddr_in);
4145 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4146 break;
4148 case WS_SIO_SET_COMPATIBILITY_MODE:
4149 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
4150 status = WSAEOPNOTSUPP;
4151 break;
4152 case WS_SIO_UDP_CONNRESET:
4153 FIXME("WS_SIO_UDP_CONNRESET stub\n");
4154 break;
4155 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
4156 WSASetLastError(WSAEOPNOTSUPP);
4157 return SOCKET_ERROR;
4158 default:
4159 status = WSAEOPNOTSUPP;
4160 break;
4163 if (status == WSAEOPNOTSUPP)
4165 status = server_ioctl_sock(s, code, in_buff, in_size, out_buff, out_size, &total,
4166 overlapped, completion);
4167 if (status != WSAEOPNOTSUPP)
4169 if (status == 0 || status == WSA_IO_PENDING)
4170 TRACE("-> %s request\n", debugstr_wsaioctl(code));
4171 else
4172 ERR("-> %s request failed with status 0x%x\n", debugstr_wsaioctl(code), status);
4174 /* overlapped and completion operations will be handled by the server */
4175 completion = NULL;
4176 overlapped = NULL;
4178 else
4179 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code));
4182 if (completion)
4184 FIXME( "completion routine %p not supported\n", completion );
4186 else if (overlapped)
4188 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
4189 overlapped->Internal = status;
4190 overlapped->InternalHigh = total;
4191 if (overlapped->hEvent) NtSetEvent( overlapped->hEvent, NULL );
4192 if (cvalue) WS_AddCompletion( HANDLE2SOCKET(s), cvalue, status, total );
4195 if (!status)
4197 if (ret_size) *ret_size = total;
4198 return 0;
4200 SetLastError( status );
4201 return SOCKET_ERROR;
4205 /***********************************************************************
4206 * ioctlsocket (WS2_32.10)
4208 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
4210 DWORD ret_size;
4211 return WSAIoctl( s, cmd, argp, sizeof(WS_u_long), argp, sizeof(WS_u_long), &ret_size, NULL, NULL );
4214 /***********************************************************************
4215 * listen (WS2_32.13)
4217 int WINAPI WS_listen(SOCKET s, int backlog)
4219 int fd = get_sock_fd( s, FILE_READ_DATA, NULL ), ret = SOCKET_ERROR;
4221 TRACE("socket %04lx, backlog %d\n", s, backlog);
4222 if (fd != -1)
4224 union generic_unix_sockaddr uaddr;
4225 socklen_t uaddrlen = sizeof(uaddr);
4227 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
4229 SetLastError(wsaErrno());
4231 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
4233 SetLastError(WSAEINVAL);
4235 else if (listen(fd, backlog) == 0)
4237 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
4238 FD_WINE_LISTENING,
4239 FD_CONNECT|FD_WINE_CONNECTED);
4240 ret = 0;
4242 else
4243 SetLastError(wsaErrno());
4244 release_sock_fd( s, fd );
4246 else
4247 SetLastError(WSAENOTSOCK);
4248 return ret;
4251 /***********************************************************************
4252 * recv (WS2_32.16)
4254 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
4256 DWORD n, dwFlags = flags;
4257 WSABUF wsabuf;
4259 wsabuf.len = len;
4260 wsabuf.buf = buf;
4262 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
4263 return SOCKET_ERROR;
4264 else
4265 return n;
4268 /***********************************************************************
4269 * recvfrom (WS2_32.17)
4271 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
4272 struct WS_sockaddr *from, int *fromlen)
4274 DWORD n, dwFlags = flags;
4275 WSABUF wsabuf;
4277 wsabuf.len = len;
4278 wsabuf.buf = buf;
4280 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL, NULL) == SOCKET_ERROR )
4281 return SOCKET_ERROR;
4282 else
4283 return n;
4286 /* allocate a poll array for the corresponding fd sets */
4287 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
4288 const WS_fd_set *exceptfds, int *count_ptr )
4290 unsigned int i, j = 0, count = 0;
4291 struct pollfd *fds;
4293 if (readfds) count += readfds->fd_count;
4294 if (writefds) count += writefds->fd_count;
4295 if (exceptfds) count += exceptfds->fd_count;
4296 *count_ptr = count;
4297 if (!count)
4299 SetLastError(WSAEINVAL);
4300 return NULL;
4302 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0]))))
4304 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
4305 return NULL;
4307 if (readfds)
4308 for (i = 0; i < readfds->fd_count; i++, j++)
4310 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
4311 if (fds[j].fd == -1) goto failed;
4312 fds[j].events = POLLIN;
4313 fds[j].revents = 0;
4315 if (writefds)
4316 for (i = 0; i < writefds->fd_count; i++, j++)
4318 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
4319 if (fds[j].fd == -1) goto failed;
4320 fds[j].events = POLLOUT;
4321 fds[j].revents = 0;
4323 if (exceptfds)
4324 for (i = 0; i < exceptfds->fd_count; i++, j++)
4326 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
4327 if (fds[j].fd == -1) goto failed;
4328 fds[j].events = POLLHUP;
4329 fds[j].revents = 0;
4331 return fds;
4333 failed:
4334 count = j;
4335 j = 0;
4336 if (readfds)
4337 for (i = 0; i < readfds->fd_count && j < count; i++, j++)
4338 release_sock_fd( readfds->fd_array[i], fds[j].fd );
4339 if (writefds)
4340 for (i = 0; i < writefds->fd_count && j < count; i++, j++)
4341 release_sock_fd( writefds->fd_array[i], fds[j].fd );
4342 if (exceptfds)
4343 for (i = 0; i < exceptfds->fd_count && j < count; i++, j++)
4344 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
4345 HeapFree( GetProcessHeap(), 0, fds );
4346 return NULL;
4349 /* release the file descriptor obtained in fd_sets_to_poll */
4350 /* must be called with the original fd_set arrays, before calling get_poll_results */
4351 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
4352 const WS_fd_set *exceptfds, struct pollfd *fds )
4354 unsigned int i, j = 0;
4356 if (readfds)
4358 for (i = 0; i < readfds->fd_count; i++, j++)
4359 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
4361 if (writefds)
4363 for (i = 0; i < writefds->fd_count; i++, j++)
4364 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
4366 if (exceptfds)
4368 for (i = 0; i < exceptfds->fd_count; i++, j++)
4369 if (fds[j].fd != -1)
4371 /* make sure we have a real error before releasing the fd */
4372 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
4373 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
4378 /* map the poll results back into the Windows fd sets */
4379 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
4380 const struct pollfd *fds )
4382 unsigned int i, j = 0, k, total = 0;
4384 if (readfds)
4386 for (i = k = 0; i < readfds->fd_count; i++, j++)
4387 if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
4388 readfds->fd_count = k;
4389 total += k;
4391 if (writefds)
4393 for (i = k = 0; i < writefds->fd_count; i++, j++)
4394 if ((fds[j].revents & POLLOUT) && !(fds[j].revents & POLLHUP))
4395 writefds->fd_array[k++] = writefds->fd_array[i];
4396 writefds->fd_count = k;
4397 total += k;
4399 if (exceptfds)
4401 for (i = k = 0; i < exceptfds->fd_count; i++, j++)
4402 if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
4403 exceptfds->fd_count = k;
4404 total += k;
4406 return total;
4410 /***********************************************************************
4411 * select (WS2_32.18)
4413 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
4414 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
4415 const struct WS_timeval* ws_timeout)
4417 struct pollfd *pollfds;
4418 struct timeval tv1, tv2;
4419 int torig = 0;
4420 int count, ret, timeout = -1;
4422 TRACE("read %p, write %p, excp %p timeout %p\n",
4423 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
4425 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )))
4426 return SOCKET_ERROR;
4428 if (ws_timeout)
4430 torig = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
4431 timeout = torig;
4432 gettimeofday( &tv1, 0 );
4435 while ((ret = poll( pollfds, count, timeout )) < 0)
4437 if (errno == EINTR)
4439 if (!ws_timeout) continue;
4440 gettimeofday( &tv2, 0 );
4442 tv2.tv_sec -= tv1.tv_sec;
4443 tv2.tv_usec -= tv1.tv_usec;
4444 if (tv2.tv_usec < 0)
4446 tv2.tv_usec += 1000000;
4447 tv2.tv_sec -= 1;
4450 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
4451 if (timeout <= 0) break;
4452 } else break;
4454 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
4456 if (ret == -1) SetLastError(wsaErrno());
4457 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
4458 HeapFree( GetProcessHeap(), 0, pollfds );
4459 return ret;
4462 /* helper to send completion messages for client-only i/o operation case */
4463 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
4464 ULONG Information )
4466 SERVER_START_REQ( add_fd_completion )
4468 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
4469 req->cvalue = CompletionValue;
4470 req->status = CompletionStatus;
4471 req->information = Information;
4472 wine_server_call( req );
4474 SERVER_END_REQ;
4478 /***********************************************************************
4479 * send (WS2_32.19)
4481 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
4483 DWORD n;
4484 WSABUF wsabuf;
4486 wsabuf.len = len;
4487 wsabuf.buf = (char*) buf;
4489 if ( WS2_sendto( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
4490 return SOCKET_ERROR;
4491 else
4492 return n;
4495 /***********************************************************************
4496 * WSASend (WS2_32.72)
4498 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4499 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4500 LPWSAOVERLAPPED lpOverlapped,
4501 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4503 return WS2_sendto( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
4504 NULL, 0, lpOverlapped, lpCompletionRoutine );
4507 /***********************************************************************
4508 * WSASendDisconnect (WS2_32.73)
4510 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
4512 return WS_shutdown( s, SD_SEND );
4516 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4517 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4518 const struct WS_sockaddr *to, int tolen,
4519 LPWSAOVERLAPPED lpOverlapped,
4520 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4522 unsigned int i, options;
4523 int n, fd, err, overlapped;
4524 struct ws2_async *wsa = NULL, localwsa;
4525 int totalLength = 0;
4526 DWORD bytes_sent;
4527 BOOL is_blocking;
4529 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
4530 s, lpBuffers, dwBufferCount, dwFlags,
4531 to, tolen, lpOverlapped, lpCompletionRoutine);
4533 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
4534 TRACE( "fd=%d, options=%x\n", fd, options );
4536 if ( fd == -1 ) return SOCKET_ERROR;
4538 if (!lpOverlapped && !lpNumberOfBytesSent)
4540 err = WSAEFAULT;
4541 goto error;
4544 overlapped = (lpOverlapped || lpCompletionRoutine) &&
4545 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
4546 if (overlapped || dwBufferCount > 1)
4548 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
4550 err = WSAEFAULT;
4551 goto error;
4554 else
4555 wsa = &localwsa;
4557 wsa->hSocket = SOCKET2HANDLE(s);
4558 wsa->addr = (struct WS_sockaddr *)to;
4559 wsa->addrlen.val = tolen;
4560 wsa->flags = dwFlags;
4561 wsa->lpFlags = &wsa->flags;
4562 wsa->control = NULL;
4563 wsa->n_iovecs = dwBufferCount;
4564 wsa->first_iovec = 0;
4565 for ( i = 0; i < dwBufferCount; i++ )
4567 wsa->iovec[i].iov_base = lpBuffers[i].buf;
4568 wsa->iovec[i].iov_len = lpBuffers[i].len;
4569 totalLength += lpBuffers[i].len;
4572 n = WS2_send( fd, wsa );
4573 if (n == -1 && errno != EAGAIN)
4575 err = wsaErrno();
4576 goto error;
4579 if (overlapped)
4581 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
4582 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
4584 wsa->user_overlapped = lpOverlapped;
4585 wsa->completion_func = lpCompletionRoutine;
4586 release_sock_fd( s, fd );
4588 if (n == -1 || n < totalLength)
4590 iosb->u.Status = STATUS_PENDING;
4591 iosb->Information = n == -1 ? 0 : n;
4593 SERVER_START_REQ( register_async )
4595 req->type = ASYNC_TYPE_WRITE;
4596 req->async.handle = wine_server_obj_handle( wsa->hSocket );
4597 req->async.callback = wine_server_client_ptr( WS2_async_send );
4598 req->async.iosb = wine_server_client_ptr( iosb );
4599 req->async.arg = wine_server_client_ptr( wsa );
4600 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
4601 req->async.cvalue = cvalue;
4602 err = wine_server_call( req );
4604 SERVER_END_REQ;
4606 /* Enable the event only after starting the async. The server will deliver it as soon as
4607 the async is done. */
4608 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
4610 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
4611 WSASetLastError( NtStatusToWSAError( err ));
4612 return SOCKET_ERROR;
4615 iosb->u.Status = STATUS_SUCCESS;
4616 iosb->Information = n;
4617 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = n;
4618 if (!wsa->completion_func)
4620 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
4621 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
4622 HeapFree( GetProcessHeap(), 0, wsa );
4624 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
4625 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
4626 WSASetLastError(0);
4627 return 0;
4630 if ((err = _is_blocking( s, &is_blocking )))
4632 err = NtStatusToWSAError( err );
4633 goto error;
4636 if ( is_blocking )
4638 /* On a blocking non-overlapped stream socket,
4639 * sending blocks until the entire buffer is sent. */
4640 DWORD timeout_start = GetTickCount();
4642 bytes_sent = n == -1 ? 0 : n;
4644 while (wsa->first_iovec < wsa->n_iovecs)
4646 struct pollfd pfd;
4647 int timeout = GET_SNDTIMEO(fd);
4649 if (timeout != -1)
4651 timeout -= GetTickCount() - timeout_start;
4652 if (timeout < 0) timeout = 0;
4655 pfd.fd = fd;
4656 pfd.events = POLLOUT;
4658 if (!timeout || !poll( &pfd, 1, timeout ))
4660 err = WSAETIMEDOUT;
4661 goto error; /* msdn says a timeout in send is fatal */
4664 n = WS2_send( fd, wsa );
4665 if (n == -1 && errno != EAGAIN)
4667 err = wsaErrno();
4668 goto error;
4671 if (n >= 0)
4672 bytes_sent += n;
4675 else /* non-blocking */
4677 if (n < totalLength)
4678 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
4679 if (n == -1)
4681 err = WSAEWOULDBLOCK;
4682 goto error;
4684 bytes_sent = n;
4687 TRACE(" -> %i bytes\n", bytes_sent);
4689 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = bytes_sent;
4690 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
4691 release_sock_fd( s, fd );
4692 WSASetLastError(0);
4693 return 0;
4695 error:
4696 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
4697 release_sock_fd( s, fd );
4698 WARN(" -> ERROR %d\n", err);
4699 WSASetLastError(err);
4700 return SOCKET_ERROR;
4703 /***********************************************************************
4704 * WSASendTo (WS2_32.74)
4706 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4707 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4708 const struct WS_sockaddr *to, int tolen,
4709 LPWSAOVERLAPPED lpOverlapped,
4710 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4712 return WS2_sendto( s, lpBuffers, dwBufferCount,
4713 lpNumberOfBytesSent, dwFlags,
4714 to, tolen,
4715 lpOverlapped, lpCompletionRoutine );
4718 /***********************************************************************
4719 * sendto (WS2_32.20)
4721 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
4722 const struct WS_sockaddr *to, int tolen)
4724 DWORD n;
4725 WSABUF wsabuf;
4727 wsabuf.len = len;
4728 wsabuf.buf = (char*) buf;
4730 if ( WS2_sendto(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
4731 return SOCKET_ERROR;
4732 else
4733 return n;
4736 /***********************************************************************
4737 * setsockopt (WS2_32.21)
4739 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
4740 const char *optval, int optlen)
4742 int fd;
4743 int woptval;
4744 struct linger linger;
4745 struct timeval tval;
4747 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
4748 s, level, optname, optval, optlen);
4750 /* some broken apps pass the value directly instead of a pointer to it */
4751 if(optlen && IS_INTRESOURCE(optval))
4753 SetLastError(WSAEFAULT);
4754 return SOCKET_ERROR;
4757 switch(level)
4759 case WS_SOL_SOCKET:
4760 switch(optname)
4762 /* Some options need some conversion before they can be sent to
4763 * setsockopt. The conversions are done here, then they will fall through
4764 * to the general case. Special options that are not passed to
4765 * setsockopt follow below that.*/
4767 case WS_SO_DONTLINGER:
4768 if (!optval)
4770 SetLastError(WSAEFAULT);
4771 return SOCKET_ERROR;
4773 linger.l_onoff = *(const int*)optval == 0;
4774 linger.l_linger = 0;
4775 level = SOL_SOCKET;
4776 optname = SO_LINGER;
4777 optval = (char*)&linger;
4778 optlen = sizeof(struct linger);
4779 break;
4781 case WS_SO_LINGER:
4782 if (!optval)
4784 SetLastError(WSAEFAULT);
4785 return SOCKET_ERROR;
4787 linger.l_onoff = ((LINGER*)optval)->l_onoff;
4788 linger.l_linger = ((LINGER*)optval)->l_linger;
4789 level = SOL_SOCKET;
4790 optname = SO_LINGER;
4791 optval = (char*)&linger;
4792 optlen = sizeof(struct linger);
4793 break;
4795 case WS_SO_RCVBUF:
4796 if (*(const int*)optval < 2048)
4798 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
4799 return 0;
4801 /* Fall through */
4803 /* The options listed here don't need any special handling. Thanks to
4804 * the conversion happening above, options from there will fall through
4805 * to this, too.*/
4806 case WS_SO_ACCEPTCONN:
4807 case WS_SO_BROADCAST:
4808 case WS_SO_ERROR:
4809 case WS_SO_KEEPALIVE:
4810 case WS_SO_OOBINLINE:
4811 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
4812 * however, using it the BSD way fixes bug 8513 and seems to be what
4813 * most programmers assume, anyway */
4814 case WS_SO_REUSEADDR:
4815 case WS_SO_SNDBUF:
4816 case WS_SO_TYPE:
4817 convert_sockopt(&level, &optname);
4818 break;
4820 /* SO_DEBUG is a privileged operation, ignore it. */
4821 case WS_SO_DEBUG:
4822 TRACE("Ignoring SO_DEBUG\n");
4823 return 0;
4825 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
4826 * socket. According to MSDN, this option is silently ignored.*/
4827 case WS_SO_DONTROUTE:
4828 TRACE("Ignoring SO_DONTROUTE\n");
4829 return 0;
4831 /* Stops two sockets from being bound to the same port. Always happens
4832 * on unix systems, so just drop it. */
4833 case WS_SO_EXCLUSIVEADDRUSE:
4834 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
4835 return 0;
4837 /* After a ConnectEx call succeeds, the socket can't be used with half of the
4838 * normal winsock functions on windows. We don't have that problem. */
4839 case WS_SO_UPDATE_CONNECT_CONTEXT:
4840 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
4841 return 0;
4843 /* After a AcceptEx call succeeds, the socket can't be used with half of the
4844 * normal winsock functions on windows. We don't have that problem. */
4845 case WS_SO_UPDATE_ACCEPT_CONTEXT:
4846 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
4847 return 0;
4849 /* SO_OPENTYPE does not require a valid socket handle. */
4850 case WS_SO_OPENTYPE:
4851 if (!optlen || optlen < sizeof(int) || !optval)
4853 SetLastError(WSAEFAULT);
4854 return SOCKET_ERROR;
4856 get_per_thread_data()->opentype = *(const int *)optval;
4857 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
4858 return 0;
4860 #ifdef SO_RCVTIMEO
4861 case WS_SO_RCVTIMEO:
4862 #endif
4863 #ifdef SO_SNDTIMEO
4864 case WS_SO_SNDTIMEO:
4865 #endif
4866 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
4867 if (optval && optlen == sizeof(UINT32)) {
4868 /* WinSock passes milliseconds instead of struct timeval */
4869 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
4870 tval.tv_sec = *(const UINT32*)optval / 1000;
4871 /* min of 500 milliseconds */
4872 if (tval.tv_sec == 0 && tval.tv_usec && tval.tv_usec < 500000)
4873 tval.tv_usec = 500000;
4874 optlen = sizeof(struct timeval);
4875 optval = (char*)&tval;
4876 } else if (optlen == sizeof(struct timeval)) {
4877 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
4878 } else {
4879 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
4880 return 0;
4882 convert_sockopt(&level, &optname);
4883 break;
4884 #endif
4886 default:
4887 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
4888 SetLastError(WSAENOPROTOOPT);
4889 return SOCKET_ERROR;
4891 break; /* case WS_SOL_SOCKET */
4893 #ifdef HAS_IPX
4894 case WS_NSPROTO_IPX:
4895 switch(optname)
4897 case IPX_PTYPE:
4898 return set_ipx_packettype(s, *(int*)optval);
4900 case IPX_FILTERPTYPE:
4901 /* Sets the receive filter packet type, at the moment we don't support it */
4902 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
4903 /* Returning 0 is better for now than returning a SOCKET_ERROR */
4904 return 0;
4906 default:
4907 FIXME("opt_name:%x\n", optname);
4908 return SOCKET_ERROR;
4910 break; /* case WS_NSPROTO_IPX */
4911 #endif
4913 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
4914 case WS_IPPROTO_TCP:
4915 switch(optname)
4917 case WS_TCP_NODELAY:
4918 convert_sockopt(&level, &optname);
4919 break;
4920 default:
4921 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
4922 return SOCKET_ERROR;
4924 break;
4926 case WS_IPPROTO_IP:
4927 switch(optname)
4929 case WS_IP_ADD_MEMBERSHIP:
4930 case WS_IP_DROP_MEMBERSHIP:
4931 #ifdef IP_HDRINCL
4932 case WS_IP_HDRINCL:
4933 #endif
4934 case WS_IP_MULTICAST_IF:
4935 case WS_IP_MULTICAST_LOOP:
4936 case WS_IP_MULTICAST_TTL:
4937 case WS_IP_OPTIONS:
4938 #ifdef IP_PKTINFO
4939 case WS_IP_PKTINFO:
4940 #endif
4941 case WS_IP_TOS:
4942 case WS_IP_TTL:
4943 #ifdef IP_UNICAST_IF
4944 case WS_IP_UNICAST_IF:
4945 #endif
4946 convert_sockopt(&level, &optname);
4947 break;
4948 case WS_IP_DONTFRAGMENT:
4949 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
4950 return 0;
4951 default:
4952 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
4953 return SOCKET_ERROR;
4955 break;
4957 case WS_IPPROTO_IPV6:
4958 switch(optname)
4960 #ifdef IPV6_ADD_MEMBERSHIP
4961 case WS_IPV6_ADD_MEMBERSHIP:
4962 #endif
4963 #ifdef IPV6_DROP_MEMBERSHIP
4964 case WS_IPV6_DROP_MEMBERSHIP:
4965 #endif
4966 case WS_IPV6_MULTICAST_IF:
4967 case WS_IPV6_MULTICAST_HOPS:
4968 case WS_IPV6_MULTICAST_LOOP:
4969 case WS_IPV6_UNICAST_HOPS:
4970 case WS_IPV6_V6ONLY:
4971 #ifdef IPV6_UNICAST_IF
4972 case WS_IPV6_UNICAST_IF:
4973 #endif
4974 convert_sockopt(&level, &optname);
4975 break;
4976 case WS_IPV6_DONTFRAG:
4977 FIXME("IPV6_DONTFRAG is silently ignored!\n");
4978 return 0;
4979 case WS_IPV6_PROTECTION_LEVEL:
4980 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
4981 return 0;
4982 default:
4983 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
4984 return SOCKET_ERROR;
4986 break;
4988 default:
4989 WARN("Unknown level: 0x%08x\n", level);
4990 SetLastError(WSAEINVAL);
4991 return SOCKET_ERROR;
4992 } /* end switch(level) */
4994 /* avoid endianness issues if argument is a 16-bit int */
4995 if (optval && optlen < sizeof(int))
4997 woptval= *((const INT16 *) optval);
4998 optval= (char*) &woptval;
4999 optlen=sizeof(int);
5001 fd = get_sock_fd( s, 0, NULL );
5002 if (fd == -1) return SOCKET_ERROR;
5004 if (setsockopt(fd, level, optname, optval, optlen) == 0)
5006 #ifdef __APPLE__
5007 if (level == SOL_SOCKET && optname == SO_REUSEADDR &&
5008 setsockopt(fd, level, SO_REUSEPORT, optval, optlen) != 0)
5010 SetLastError(wsaErrno());
5011 release_sock_fd( s, fd );
5012 return SOCKET_ERROR;
5014 #endif
5015 release_sock_fd( s, fd );
5016 return 0;
5018 TRACE("Setting socket error, %d\n", wsaErrno());
5019 SetLastError(wsaErrno());
5020 release_sock_fd( s, fd );
5022 return SOCKET_ERROR;
5025 /***********************************************************************
5026 * shutdown (WS2_32.22)
5028 int WINAPI WS_shutdown(SOCKET s, int how)
5030 int fd, err = WSAENOTSOCK;
5031 unsigned int options, clear_flags = 0;
5033 fd = get_sock_fd( s, 0, &options );
5034 TRACE("socket %04lx, how %i %x\n", s, how, options );
5036 if (fd == -1)
5037 return SOCKET_ERROR;
5039 switch( how )
5041 case SD_RECEIVE: /* drop receives */
5042 clear_flags |= FD_READ;
5043 break;
5044 case SD_SEND: /* drop sends */
5045 clear_flags |= FD_WRITE;
5046 break;
5047 case SD_BOTH: /* drop all */
5048 clear_flags |= FD_READ|FD_WRITE;
5049 /*fall through */
5050 default:
5051 clear_flags |= FD_WINE_LISTENING;
5054 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
5056 switch ( how )
5058 case SD_RECEIVE:
5059 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
5060 break;
5061 case SD_SEND:
5062 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
5063 break;
5064 case SD_BOTH:
5065 default:
5066 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
5067 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
5068 break;
5070 if (err) goto error;
5072 else /* non-overlapped mode */
5074 if ( shutdown( fd, how ) )
5076 err = wsaErrno();
5077 goto error;
5081 release_sock_fd( s, fd );
5082 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
5083 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
5084 return 0;
5086 error:
5087 release_sock_fd( s, fd );
5088 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
5089 WSASetLastError( err );
5090 return SOCKET_ERROR;
5093 /***********************************************************************
5094 * socket (WS2_32.23)
5096 SOCKET WINAPI WS_socket(int af, int type, int protocol)
5098 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
5100 return WSASocketA( af, type, protocol, NULL, 0,
5101 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
5105 /***********************************************************************
5106 * gethostbyaddr (WS2_32.51)
5108 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
5110 struct WS_hostent *retval = NULL;
5111 struct hostent* host;
5112 int unixtype = convert_af_w2u(type);
5113 const char *paddr = addr;
5114 unsigned long loopback;
5115 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5116 char *extrabuf;
5117 int ebufsize = 1024;
5118 struct hostent hostentry;
5119 int locerr = ENOBUFS;
5120 #endif
5122 /* convert back the magic loopback address if necessary */
5123 if (unixtype == AF_INET && len == 4 && !memcmp(addr, magic_loopback_addr, 4))
5125 loopback = htonl(INADDR_LOOPBACK);
5126 paddr = (char*) &loopback;
5129 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5130 host = NULL;
5131 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
5132 while(extrabuf) {
5133 int res = gethostbyaddr_r(paddr, len, unixtype,
5134 &hostentry, extrabuf, ebufsize, &host, &locerr);
5135 if (res != ERANGE) break;
5136 ebufsize *=2;
5137 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
5139 if (host) retval = WS_dup_he(host);
5140 else SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
5141 HeapFree(GetProcessHeap(),0,extrabuf);
5142 #else
5143 EnterCriticalSection( &csWSgetXXXbyYYY );
5144 host = gethostbyaddr(paddr, len, unixtype);
5145 if (host) retval = WS_dup_he(host);
5146 else SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
5147 LeaveCriticalSection( &csWSgetXXXbyYYY );
5148 #endif
5149 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
5150 return retval;
5153 /***********************************************************************
5154 * WS_get_local_ips (INTERNAL)
5156 * Returns the list of local IP addresses by going through the network
5157 * adapters and using the local routing table to sort the addresses
5158 * from highest routing priority to lowest routing priority. This
5159 * functionality is inferred from the description for obtaining local
5160 * IP addresses given in the Knowledge Base Article Q160215.
5162 * Please note that the returned hostent is only freed when the thread
5163 * closes and is replaced if another hostent is requested.
5165 static struct WS_hostent* WS_get_local_ips( char *hostname )
5167 int last_metric, numroutes = 0, i, j;
5168 DWORD n;
5169 PIP_ADAPTER_INFO adapters = NULL, k;
5170 struct WS_hostent *hostlist = NULL;
5171 PMIB_IPFORWARDTABLE routes = NULL;
5172 struct route *route_addrs = NULL;
5173 DWORD adap_size, route_size;
5175 /* Obtain the size of the adapter list and routing table, also allocate memory */
5176 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
5177 return NULL;
5178 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
5179 return NULL;
5180 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
5181 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
5182 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
5183 if (adapters == NULL || routes == NULL || route_addrs == NULL)
5184 goto cleanup;
5185 /* Obtain the adapter list and the full routing table */
5186 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
5187 goto cleanup;
5188 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
5189 goto cleanup;
5190 /* Store the interface associated with each route */
5191 for (n = 0; n < routes->dwNumEntries; n++)
5193 IF_INDEX ifindex;
5194 DWORD ifmetric;
5195 BOOL exists = FALSE;
5197 if (routes->table[n].u1.ForwardType != MIB_IPROUTE_TYPE_DIRECT)
5198 continue;
5199 ifindex = routes->table[n].dwForwardIfIndex;
5200 ifmetric = routes->table[n].dwForwardMetric1;
5201 /* Only store the lowest valued metric for an interface */
5202 for (j = 0; j < numroutes; j++)
5204 if (route_addrs[j].interface == ifindex)
5206 if (route_addrs[j].metric > ifmetric)
5207 route_addrs[j].metric = ifmetric;
5208 exists = TRUE;
5211 if (exists)
5212 continue;
5213 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
5214 if (route_addrs == NULL)
5215 goto cleanup; /* Memory allocation error, fail gracefully */
5216 route_addrs[numroutes].interface = ifindex;
5217 route_addrs[numroutes].metric = ifmetric;
5218 /* If no IP is found in the next step (for whatever reason)
5219 * then fall back to the magic loopback address.
5221 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
5222 numroutes++;
5224 if (numroutes == 0)
5225 goto cleanup; /* No routes, fall back to the Magic IP */
5226 /* Find the IP address associated with each found interface */
5227 for (i = 0; i < numroutes; i++)
5229 for (k = adapters; k != NULL; k = k->Next)
5231 char *ip = k->IpAddressList.IpAddress.String;
5233 if (route_addrs[i].interface == k->Index)
5234 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
5237 /* Allocate a hostent and enough memory for all the IPs,
5238 * including the NULL at the end of the list.
5240 hostlist = WS_create_he(hostname, 1, 0, numroutes+1, sizeof(struct in_addr));
5241 if (hostlist == NULL)
5242 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
5243 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
5244 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
5245 hostlist->h_addrtype = AF_INET;
5246 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
5247 /* Reorder the entries when placing them in the host list, Windows expects
5248 * the IP list in order from highest priority to lowest (the critical thing
5249 * is that most applications expect the first IP to be the default route).
5251 last_metric = -1;
5252 for (i = 0; i < numroutes; i++)
5254 struct in_addr addr;
5255 int metric = 0xFFFF;
5257 memcpy(&addr, magic_loopback_addr, 4);
5258 for (j = 0; j < numroutes; j++)
5260 int this_metric = route_addrs[j].metric;
5262 if (this_metric > last_metric && this_metric < metric)
5264 addr = route_addrs[j].addr;
5265 metric = this_metric;
5268 last_metric = metric;
5269 (*(struct in_addr *) hostlist->h_addr_list[i]) = addr;
5272 /* Cleanup all allocated memory except the address list,
5273 * the address list is used by the calling app.
5275 cleanup:
5276 HeapFree(GetProcessHeap(), 0, route_addrs);
5277 HeapFree(GetProcessHeap(), 0, adapters);
5278 HeapFree(GetProcessHeap(), 0, routes);
5279 return hostlist;
5282 /***********************************************************************
5283 * gethostbyname (WS2_32.52)
5285 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
5287 struct WS_hostent *retval = NULL;
5288 struct hostent* host;
5289 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5290 char *extrabuf;
5291 int ebufsize=1024;
5292 struct hostent hostentry;
5293 int locerr = ENOBUFS;
5294 #endif
5295 char hostname[100];
5296 if(!num_startup) {
5297 SetLastError(WSANOTINITIALISED);
5298 return NULL;
5300 if( gethostname( hostname, 100) == -1) {
5301 SetLastError( WSAENOBUFS); /* appropriate ? */
5302 return retval;
5304 if( !name || !name[0]) {
5305 name = hostname;
5307 /* If the hostname of the local machine is requested then return the
5308 * complete list of local IP addresses */
5309 if(strcmp(name, hostname) == 0)
5310 retval = WS_get_local_ips(hostname);
5311 /* If any other hostname was requested (or the routing table lookup failed)
5312 * then return the IP found by the host OS */
5313 if(retval == NULL)
5315 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5316 host = NULL;
5317 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
5318 while(extrabuf) {
5319 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
5320 if( res != ERANGE) break;
5321 ebufsize *=2;
5322 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
5324 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
5325 #else
5326 EnterCriticalSection( &csWSgetXXXbyYYY );
5327 host = gethostbyname(name);
5328 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
5329 #endif
5330 if (host) retval = WS_dup_he(host);
5331 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5332 HeapFree(GetProcessHeap(),0,extrabuf);
5333 #else
5334 LeaveCriticalSection( &csWSgetXXXbyYYY );
5335 #endif
5337 if (retval && retval->h_addr_list[0][0] == 127 &&
5338 strcmp(name, "localhost") != 0)
5340 /* hostname != "localhost" but has loopback address. replace by our
5341 * special address.*/
5342 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
5344 TRACE( "%s ret %p\n", debugstr_a(name), retval );
5345 return retval;
5349 /***********************************************************************
5350 * getprotobyname (WS2_32.53)
5352 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
5354 struct WS_protoent* retval = NULL;
5355 #ifdef HAVE_GETPROTOBYNAME
5356 struct protoent* proto;
5357 EnterCriticalSection( &csWSgetXXXbyYYY );
5358 if( (proto = getprotobyname(name)) != NULL )
5360 retval = WS_dup_pe(proto);
5362 else {
5363 MESSAGE("protocol %s not found; You might want to add "
5364 "this to /etc/protocols\n", debugstr_a(name) );
5365 SetLastError(WSANO_DATA);
5367 LeaveCriticalSection( &csWSgetXXXbyYYY );
5368 #endif
5369 TRACE( "%s ret %p\n", debugstr_a(name), retval );
5370 return retval;
5374 /***********************************************************************
5375 * getprotobynumber (WS2_32.54)
5377 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
5379 struct WS_protoent* retval = NULL;
5380 #ifdef HAVE_GETPROTOBYNUMBER
5381 struct protoent* proto;
5382 EnterCriticalSection( &csWSgetXXXbyYYY );
5383 if( (proto = getprotobynumber(number)) != NULL )
5385 retval = WS_dup_pe(proto);
5387 else {
5388 MESSAGE("protocol number %d not found; You might want to add "
5389 "this to /etc/protocols\n", number );
5390 SetLastError(WSANO_DATA);
5392 LeaveCriticalSection( &csWSgetXXXbyYYY );
5393 #endif
5394 TRACE("%i ret %p\n", number, retval);
5395 return retval;
5399 /***********************************************************************
5400 * getservbyname (WS2_32.55)
5402 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
5404 struct WS_servent* retval = NULL;
5405 struct servent* serv;
5406 char *name_str;
5407 char *proto_str = NULL;
5409 if (!(name_str = strdup_lower(name))) return NULL;
5411 if (proto && *proto)
5413 if (!(proto_str = strdup_lower(proto)))
5415 HeapFree( GetProcessHeap(), 0, name_str );
5416 return NULL;
5420 EnterCriticalSection( &csWSgetXXXbyYYY );
5421 serv = getservbyname(name_str, proto_str);
5422 if( serv != NULL )
5424 retval = WS_dup_se(serv);
5426 else SetLastError(WSANO_DATA);
5427 LeaveCriticalSection( &csWSgetXXXbyYYY );
5428 HeapFree( GetProcessHeap(), 0, proto_str );
5429 HeapFree( GetProcessHeap(), 0, name_str );
5430 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
5431 return retval;
5434 /***********************************************************************
5435 * freeaddrinfo (WS2_32.@)
5437 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
5439 while (res) {
5440 struct WS_addrinfo *next;
5442 HeapFree(GetProcessHeap(),0,res->ai_canonname);
5443 HeapFree(GetProcessHeap(),0,res->ai_addr);
5444 next = res->ai_next;
5445 HeapFree(GetProcessHeap(),0,res);
5446 res = next;
5450 /* helper functions for getaddrinfo()/getnameinfo() */
5451 static int convert_aiflag_w2u(int winflags) {
5452 unsigned int i;
5453 int unixflags = 0;
5455 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
5456 if (ws_aiflag_map[i][0] & winflags) {
5457 unixflags |= ws_aiflag_map[i][1];
5458 winflags &= ~ws_aiflag_map[i][0];
5460 if (winflags)
5461 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
5462 return unixflags;
5465 static int convert_niflag_w2u(int winflags) {
5466 unsigned int i;
5467 int unixflags = 0;
5469 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
5470 if (ws_niflag_map[i][0] & winflags) {
5471 unixflags |= ws_niflag_map[i][1];
5472 winflags &= ~ws_niflag_map[i][0];
5474 if (winflags)
5475 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
5476 return unixflags;
5479 static int convert_aiflag_u2w(int unixflags) {
5480 unsigned int i;
5481 int winflags = 0;
5483 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
5484 if (ws_aiflag_map[i][1] & unixflags) {
5485 winflags |= ws_aiflag_map[i][0];
5486 unixflags &= ~ws_aiflag_map[i][1];
5488 if (unixflags) /* will warn usually */
5489 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
5490 return winflags;
5493 static int convert_eai_u2w(int unixret) {
5494 int i;
5496 if (!unixret) return 0;
5498 for (i=0;ws_eai_map[i][0];i++)
5499 if (ws_eai_map[i][1] == unixret)
5500 return ws_eai_map[i][0];
5502 if (unixret == EAI_SYSTEM)
5503 /* There are broken versions of glibc which return EAI_SYSTEM
5504 * and set errno to 0 instead of returning EAI_NONAME.
5506 return errno ? sock_get_error( errno ) : WS_EAI_NONAME;
5508 FIXME("Unhandled unix EAI_xxx ret %d\n", unixret);
5509 return unixret;
5512 static char *get_hostname(void)
5514 char *ret;
5515 DWORD size = 0;
5517 GetComputerNameExA( ComputerNamePhysicalDnsHostname, NULL, &size );
5518 if (GetLastError() != ERROR_MORE_DATA) return NULL;
5519 if (!(ret = HeapAlloc( GetProcessHeap(), 0, size ))) return NULL;
5520 if (!GetComputerNameExA( ComputerNamePhysicalDnsHostname, ret, &size ))
5522 HeapFree( GetProcessHeap(), 0, ret );
5523 return NULL;
5525 return ret;
5528 /***********************************************************************
5529 * getaddrinfo (WS2_32.@)
5531 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
5533 #ifdef HAVE_GETADDRINFO
5534 struct addrinfo *unixaires = NULL;
5535 int result;
5536 struct addrinfo unixhints, *punixhints = NULL;
5537 char *hostname = NULL;
5538 const char *node;
5540 *res = NULL;
5541 if (!nodename && !servname) return WSAHOST_NOT_FOUND;
5543 if (!nodename)
5544 node = NULL;
5545 else if (!nodename[0])
5547 node = hostname = get_hostname();
5548 if (!node) return WSA_NOT_ENOUGH_MEMORY;
5550 else
5551 node = nodename;
5553 /* servname tweak required by OSX and BSD kernels */
5554 if (servname && !servname[0]) servname = "0";
5556 if (hints) {
5557 punixhints = &unixhints;
5559 memset(&unixhints, 0, sizeof(unixhints));
5560 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
5562 /* zero is a wildcard, no need to convert */
5563 if (hints->ai_family)
5564 punixhints->ai_family = convert_af_w2u(hints->ai_family);
5565 if (hints->ai_socktype)
5566 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
5567 if (hints->ai_protocol)
5568 punixhints->ai_protocol = max(convert_proto_w2u(hints->ai_protocol), 0);
5570 if (punixhints->ai_socktype < 0)
5572 WSASetLastError(WSAESOCKTNOSUPPORT);
5573 HeapFree(GetProcessHeap(), 0, hostname);
5574 return SOCKET_ERROR;
5577 /* windows allows invalid combinations of socket type and protocol, unix does not.
5578 * fix the parameters here to make getaddrinfo call always work */
5579 if (punixhints->ai_protocol == IPPROTO_TCP &&
5580 punixhints->ai_socktype != SOCK_STREAM && punixhints->ai_socktype != SOCK_SEQPACKET)
5581 punixhints->ai_socktype = 0;
5583 else if (punixhints->ai_protocol == IPPROTO_UDP && punixhints->ai_socktype != SOCK_DGRAM)
5584 punixhints->ai_socktype = 0;
5586 else if (IS_IPX_PROTO(punixhints->ai_protocol) && punixhints->ai_socktype != SOCK_DGRAM)
5587 punixhints->ai_socktype = 0;
5590 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
5591 result = getaddrinfo(node, servname, punixhints, &unixaires);
5593 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
5594 HeapFree(GetProcessHeap(), 0, hostname);
5596 if (!result) {
5597 struct addrinfo *xuai = unixaires;
5598 struct WS_addrinfo **xai = res;
5600 *xai = NULL;
5601 while (xuai) {
5602 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
5603 SIZE_T len;
5605 if (!ai)
5606 goto outofmem;
5608 *xai = ai;xai = &ai->ai_next;
5609 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
5610 ai->ai_family = convert_af_u2w(xuai->ai_family);
5611 /* copy whatever was sent in the hints */
5612 if(hints) {
5613 ai->ai_socktype = hints->ai_socktype;
5614 ai->ai_protocol = hints->ai_protocol;
5615 } else {
5616 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
5617 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
5619 if (xuai->ai_canonname) {
5620 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
5621 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
5622 if (!ai->ai_canonname)
5623 goto outofmem;
5624 strcpy(ai->ai_canonname,xuai->ai_canonname);
5626 len = xuai->ai_addrlen;
5627 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
5628 if (!ai->ai_addr)
5629 goto outofmem;
5630 ai->ai_addrlen = len;
5631 do {
5632 int winlen = ai->ai_addrlen;
5634 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
5635 ai->ai_addrlen = winlen;
5636 break;
5638 len = 2*len;
5639 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
5640 if (!ai->ai_addr)
5641 goto outofmem;
5642 ai->ai_addrlen = len;
5643 } while (1);
5644 xuai = xuai->ai_next;
5646 freeaddrinfo(unixaires);
5648 if (TRACE_ON(winsock))
5650 struct WS_addrinfo *ai = *res;
5651 while (ai)
5653 TRACE("=> %p, flags %#x, family %d, type %d, protocol %d, len %ld, name %s, addr %s\n",
5654 ai, ai->ai_flags, ai->ai_family, ai->ai_socktype, ai->ai_protocol, ai->ai_addrlen,
5655 ai->ai_canonname, debugstr_sockaddr(ai->ai_addr));
5656 ai = ai->ai_next;
5659 } else
5660 result = convert_eai_u2w(result);
5662 return result;
5664 outofmem:
5665 if (*res) WS_freeaddrinfo(*res);
5666 if (unixaires) freeaddrinfo(unixaires);
5667 return WSA_NOT_ENOUGH_MEMORY;
5668 #else
5669 FIXME("getaddrinfo() failed, not found during buildtime.\n");
5670 return EAI_FAIL;
5671 #endif
5674 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
5676 struct WS_addrinfoW *ret;
5678 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
5679 ret->ai_flags = ai->ai_flags;
5680 ret->ai_family = ai->ai_family;
5681 ret->ai_socktype = ai->ai_socktype;
5682 ret->ai_protocol = ai->ai_protocol;
5683 ret->ai_addrlen = ai->ai_addrlen;
5684 ret->ai_canonname = NULL;
5685 ret->ai_addr = NULL;
5686 ret->ai_next = NULL;
5687 if (ai->ai_canonname)
5689 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
5690 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
5692 HeapFree(GetProcessHeap(), 0, ret);
5693 return NULL;
5695 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
5697 if (ai->ai_addr)
5699 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, ai->ai_addrlen)))
5701 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
5702 HeapFree(GetProcessHeap(), 0, ret);
5703 return NULL;
5705 memcpy(ret->ai_addr, ai->ai_addr, ai->ai_addrlen);
5707 return ret;
5710 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
5712 struct WS_addrinfoW *ret, *infoW;
5714 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
5715 while (info->ai_next)
5717 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
5719 FreeAddrInfoW(ret);
5720 return NULL;
5722 infoW = infoW->ai_next;
5723 info = info->ai_next;
5725 return ret;
5728 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
5730 struct WS_addrinfo *ret;
5732 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
5733 ret->ai_flags = ai->ai_flags;
5734 ret->ai_family = ai->ai_family;
5735 ret->ai_socktype = ai->ai_socktype;
5736 ret->ai_protocol = ai->ai_protocol;
5737 ret->ai_addrlen = ai->ai_addrlen;
5738 ret->ai_canonname = NULL;
5739 ret->ai_addr = NULL;
5740 ret->ai_next = NULL;
5741 if (ai->ai_canonname)
5743 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
5744 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
5746 HeapFree(GetProcessHeap(), 0, ret);
5747 return NULL;
5749 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
5751 if (ai->ai_addr)
5753 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
5755 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
5756 HeapFree(GetProcessHeap(), 0, ret);
5757 return NULL;
5759 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
5761 return ret;
5764 /***********************************************************************
5765 * GetAddrInfoW (WS2_32.@)
5767 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
5769 int ret, len;
5770 char *nodenameA = NULL, *servnameA = NULL;
5771 struct WS_addrinfo *resA, *hintsA = NULL;
5773 *res = NULL;
5774 if (nodename)
5776 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
5777 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
5778 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
5780 if (servname)
5782 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
5783 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
5785 HeapFree(GetProcessHeap(), 0, nodenameA);
5786 return EAI_MEMORY;
5788 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
5791 if (hints) hintsA = addrinfo_WtoA(hints);
5792 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
5793 WS_freeaddrinfo(hintsA);
5795 if (!ret)
5797 *res = addrinfo_list_AtoW(resA);
5798 WS_freeaddrinfo(resA);
5801 HeapFree(GetProcessHeap(), 0, nodenameA);
5802 HeapFree(GetProcessHeap(), 0, servnameA);
5803 return ret;
5806 /***********************************************************************
5807 * FreeAddrInfoW (WS2_32.@)
5809 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
5811 while (ai)
5813 ADDRINFOW *next;
5814 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
5815 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
5816 next = ai->ai_next;
5817 HeapFree(GetProcessHeap(), 0, ai);
5818 ai = next;
5822 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
5823 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
5825 #ifdef HAVE_GETNAMEINFO
5826 int ret;
5827 union generic_unix_sockaddr sa_u;
5828 unsigned int size;
5830 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
5831 serv, servlen, flags);
5833 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
5834 if (!size)
5836 WSASetLastError(WSAEFAULT);
5837 return WSA_NOT_ENOUGH_MEMORY;
5839 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
5840 return convert_eai_u2w(ret);
5841 #else
5842 FIXME("getnameinfo() failed, not found during buildtime.\n");
5843 return EAI_FAIL;
5844 #endif
5847 int WINAPI GetNameInfoW(const SOCKADDR *sa, WS_socklen_t salen, PWCHAR host,
5848 DWORD hostlen, PWCHAR serv, DWORD servlen, INT flags)
5850 int ret;
5851 char *hostA = NULL, *servA = NULL;
5853 if (host && (!(hostA = HeapAlloc(GetProcessHeap(), 0, hostlen)))) return EAI_MEMORY;
5854 if (serv && (!(servA = HeapAlloc(GetProcessHeap(), 0, servlen))))
5856 HeapFree(GetProcessHeap(), 0, hostA);
5857 return EAI_MEMORY;
5860 ret = WS_getnameinfo(sa, salen, hostA, hostlen, servA, servlen, flags);
5861 if (!ret)
5863 if (host) MultiByteToWideChar(CP_ACP, 0, hostA, -1, host, hostlen);
5864 if (serv) MultiByteToWideChar(CP_ACP, 0, servA, -1, serv, servlen);
5867 HeapFree(GetProcessHeap(), 0, hostA);
5868 HeapFree(GetProcessHeap(), 0, servA);
5869 return ret;
5872 /***********************************************************************
5873 * getservbyport (WS2_32.56)
5875 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
5877 struct WS_servent* retval = NULL;
5878 #ifdef HAVE_GETSERVBYPORT
5879 struct servent* serv;
5880 char *proto_str = NULL;
5882 if (proto && *proto)
5884 if (!(proto_str = strdup_lower(proto))) return NULL;
5886 EnterCriticalSection( &csWSgetXXXbyYYY );
5887 if( (serv = getservbyport(port, proto_str)) != NULL ) {
5888 retval = WS_dup_se(serv);
5890 else SetLastError(WSANO_DATA);
5891 LeaveCriticalSection( &csWSgetXXXbyYYY );
5892 HeapFree( GetProcessHeap(), 0, proto_str );
5893 #endif
5894 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
5895 return retval;
5899 /***********************************************************************
5900 * gethostname (WS2_32.57)
5902 int WINAPI WS_gethostname(char *name, int namelen)
5904 TRACE("name %p, len %d\n", name, namelen);
5906 if (gethostname(name, namelen) == 0)
5908 TRACE("<- '%s'\n", name);
5909 return 0;
5911 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
5912 TRACE("<- ERROR !\n");
5913 return SOCKET_ERROR;
5917 /* ------------------------------------- Windows sockets extensions -- *
5919 * ------------------------------------------------------------------- */
5921 /***********************************************************************
5922 * WSAEnumNetworkEvents (WS2_32.36)
5924 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
5926 int ret;
5927 int i;
5928 int errors[FD_MAX_EVENTS];
5930 TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
5932 SERVER_START_REQ( get_socket_event )
5934 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5935 req->service = TRUE;
5936 req->c_event = wine_server_obj_handle( hEvent );
5937 wine_server_set_reply( req, errors, sizeof(errors) );
5938 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
5940 SERVER_END_REQ;
5941 if (!ret)
5943 for (i = 0; i < FD_MAX_EVENTS; i++)
5944 lpEvent->iErrorCode[i] = NtStatusToWSAError(errors[i]);
5945 return 0;
5947 SetLastError(WSAEINVAL);
5948 return SOCKET_ERROR;
5951 /***********************************************************************
5952 * WSAEventSelect (WS2_32.39)
5954 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
5956 int ret;
5958 TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
5960 SERVER_START_REQ( set_socket_event )
5962 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5963 req->mask = lEvent;
5964 req->event = wine_server_obj_handle( hEvent );
5965 req->window = 0;
5966 req->msg = 0;
5967 ret = wine_server_call( req );
5969 SERVER_END_REQ;
5970 if (!ret) return 0;
5971 SetLastError(WSAEINVAL);
5972 return SOCKET_ERROR;
5975 /**********************************************************************
5976 * WSAGetOverlappedResult (WS2_32.40)
5978 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
5979 LPDWORD lpcbTransfer, BOOL fWait,
5980 LPDWORD lpdwFlags )
5982 NTSTATUS status;
5984 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
5985 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
5987 if ( lpOverlapped == NULL )
5989 ERR( "Invalid pointer\n" );
5990 WSASetLastError(WSA_INVALID_PARAMETER);
5991 return FALSE;
5994 status = lpOverlapped->Internal;
5995 if (status == STATUS_PENDING)
5997 if (!fWait)
5999 SetLastError( WSA_IO_INCOMPLETE );
6000 return FALSE;
6003 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
6004 INFINITE ) == WAIT_FAILED)
6005 return FALSE;
6006 status = lpOverlapped->Internal;
6009 if ( lpcbTransfer )
6010 *lpcbTransfer = lpOverlapped->InternalHigh;
6012 if ( lpdwFlags )
6013 *lpdwFlags = lpOverlapped->u.s.Offset;
6015 if (status) SetLastError( RtlNtStatusToDosError(status) );
6016 return !status;
6020 /***********************************************************************
6021 * WSAAsyncSelect (WS2_32.101)
6023 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
6025 int ret;
6027 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
6029 SERVER_START_REQ( set_socket_event )
6031 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6032 req->mask = lEvent;
6033 req->event = 0;
6034 req->window = wine_server_user_handle( hWnd );
6035 req->msg = uMsg;
6036 ret = wine_server_call( req );
6038 SERVER_END_REQ;
6039 if (!ret) return 0;
6040 SetLastError(WSAEINVAL);
6041 return SOCKET_ERROR;
6044 /***********************************************************************
6045 * WSACreateEvent (WS2_32.31)
6048 WSAEVENT WINAPI WSACreateEvent(void)
6050 /* Create a manual-reset event, with initial state: unsignaled */
6051 TRACE("\n");
6053 return CreateEventW(NULL, TRUE, FALSE, NULL);
6056 /***********************************************************************
6057 * WSACloseEvent (WS2_32.29)
6060 BOOL WINAPI WSACloseEvent(WSAEVENT event)
6062 TRACE ("event=%p\n", event);
6064 return CloseHandle(event);
6067 /***********************************************************************
6068 * WSASocketA (WS2_32.78)
6071 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
6072 LPWSAPROTOCOL_INFOA lpProtocolInfo,
6073 GROUP g, DWORD dwFlags)
6075 INT len;
6076 WSAPROTOCOL_INFOW info;
6078 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
6079 af, type, protocol, lpProtocolInfo, g, dwFlags);
6081 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
6083 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
6084 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
6085 info.szProtocol, WSAPROTOCOL_LEN + 1);
6087 if (!len)
6089 WSASetLastError( WSAEINVAL);
6090 return SOCKET_ERROR;
6093 return WSASocketW(af, type, protocol, &info, g, dwFlags);
6096 /***********************************************************************
6097 * WSASocketW (WS2_32.79)
6100 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
6101 LPWSAPROTOCOL_INFOW lpProtocolInfo,
6102 GROUP g, DWORD dwFlags)
6104 SOCKET ret;
6105 DWORD err;
6106 int unixaf, unixtype, ipxptype = -1;
6109 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
6110 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
6113 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
6114 af, type, protocol, lpProtocolInfo, g, dwFlags );
6116 if (!num_startup)
6118 err = WSANOTINITIALISED;
6119 goto done;
6122 /* hack for WSADuplicateSocket */
6123 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
6124 ret = lpProtocolInfo->dwServiceFlags3;
6125 TRACE("\tgot duplicate %04lx\n", ret);
6126 return ret;
6129 if (lpProtocolInfo)
6131 if (af == FROM_PROTOCOL_INFO || !af)
6132 af = lpProtocolInfo->iAddressFamily;
6133 if (type == FROM_PROTOCOL_INFO || !type)
6134 type = lpProtocolInfo->iSocketType;
6135 if (protocol == FROM_PROTOCOL_INFO || !protocol)
6136 protocol = lpProtocolInfo->iProtocol;
6139 if (!type && (af || protocol))
6141 int autoproto = protocol;
6142 WSAPROTOCOL_INFOW infow;
6144 /* default to the first valid protocol */
6145 if (!autoproto)
6146 autoproto = valid_protocols[0];
6147 else if(IS_IPX_PROTO(autoproto))
6148 autoproto = WS_NSPROTO_IPX;
6150 if (WS_EnterSingleProtocolW(autoproto, &infow))
6152 type = infow.iSocketType;
6154 /* after win2003 it's no longer possible to pass AF_UNSPEC
6155 using the protocol info struct */
6156 if (!lpProtocolInfo && af == WS_AF_UNSPEC)
6157 af = infow.iAddressFamily;
6162 Windows has an extension to the IPX protocol that allows one to create sockets
6163 and set the IPX packet type at the same time, to do that a caller will use
6164 a protocol like NSPROTO_IPX + <PACKET TYPE>
6166 if (IS_IPX_PROTO(protocol))
6167 ipxptype = protocol - WS_NSPROTO_IPX;
6169 /* convert the socket family, type and protocol */
6170 unixaf = convert_af_w2u(af);
6171 unixtype = convert_socktype_w2u(type);
6172 protocol = convert_proto_w2u(protocol);
6173 if (unixaf == AF_UNSPEC) unixaf = -1;
6175 /* filter invalid parameters */
6176 if (protocol < 0)
6178 /* the type could not be converted */
6179 if (type && unixtype < 0)
6181 err = WSAESOCKTNOSUPPORT;
6182 goto done;
6185 err = WSAEPROTONOSUPPORT;
6186 goto done;
6188 if (unixaf < 0)
6190 /* both family and protocol can't be invalid */
6191 if (protocol <= 0)
6193 err = WSAEINVAL;
6194 goto done;
6197 /* family could not be converted and neither socket type */
6198 if (unixtype < 0 && af >= 0)
6201 err = WSAESOCKTNOSUPPORT;
6202 goto done;
6205 err = WSAEAFNOSUPPORT;
6206 goto done;
6209 SERVER_START_REQ( create_socket )
6211 req->family = unixaf;
6212 req->type = unixtype;
6213 req->protocol = protocol;
6214 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
6215 req->attributes = OBJ_INHERIT;
6216 req->flags = dwFlags;
6217 set_error( wine_server_call( req ) );
6218 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
6220 SERVER_END_REQ;
6221 if (ret)
6223 TRACE("\tcreated %04lx\n", ret );
6224 if (ipxptype > 0)
6225 set_ipx_packettype(ret, ipxptype);
6226 return ret;
6229 err = GetLastError();
6230 if (err == WSAEACCES) /* raw socket denied */
6232 if (type == SOCK_RAW)
6233 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
6234 else
6235 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
6237 else
6239 /* invalid combination of valid parameters, like SOCK_STREAM + IPPROTO_UDP */
6240 if (err == WSAEINVAL)
6241 err = WSAESOCKTNOSUPPORT;
6242 else if (err == WSAEOPNOTSUPP)
6243 err = WSAEPROTONOSUPPORT;
6246 done:
6247 WARN("\t\tfailed, error %d!\n", err);
6248 SetLastError(err);
6249 return INVALID_SOCKET;
6252 /***********************************************************************
6253 * WSAJoinLeaf (WS2_32.58)
6256 SOCKET WINAPI WSAJoinLeaf(
6257 SOCKET s,
6258 const struct WS_sockaddr *addr,
6259 int addrlen,
6260 LPWSABUF lpCallerData,
6261 LPWSABUF lpCalleeData,
6262 LPQOS lpSQOS,
6263 LPQOS lpGQOS,
6264 DWORD dwFlags)
6266 FIXME("stub.\n");
6267 return INVALID_SOCKET;
6270 /***********************************************************************
6271 * __WSAFDIsSet (WS2_32.151)
6273 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
6275 int i = set->fd_count;
6277 TRACE("(%ld,%p(%i))\n", s, set, i);
6279 while (i--)
6280 if (set->fd_array[i] == s) return 1;
6281 return 0;
6284 /***********************************************************************
6285 * WSAIsBlocking (WS2_32.114)
6287 BOOL WINAPI WSAIsBlocking(void)
6289 /* By default WinSock should set all its sockets to non-blocking mode
6290 * and poll in PeekMessage loop when processing "blocking" ones. This
6291 * function is supposed to tell if the program is in this loop. Our
6292 * blocking calls are truly blocking so we always return FALSE.
6294 * Note: It is allowed to call this function without prior WSAStartup().
6297 TRACE("\n");
6298 return FALSE;
6301 /***********************************************************************
6302 * WSACancelBlockingCall (WS2_32.113)
6304 INT WINAPI WSACancelBlockingCall(void)
6306 TRACE("\n");
6307 return 0;
6310 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
6312 FIXME("How was this called?\n");
6313 return x();
6317 /***********************************************************************
6318 * WSASetBlockingHook (WS2_32.109)
6320 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
6322 FARPROC prev = blocking_hook;
6323 blocking_hook = lpBlockFunc;
6324 TRACE("hook %p\n", lpBlockFunc);
6325 return prev;
6329 /***********************************************************************
6330 * WSAUnhookBlockingHook (WS2_32.110)
6332 INT WINAPI WSAUnhookBlockingHook(void)
6334 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
6335 return 0;
6339 /* ----------------------------------- end of API stuff */
6341 /* ----------------------------------- helper functions -
6343 * TODO: Merge WS_dup_..() stuff into one function that
6344 * would operate with a generic structure containing internal
6345 * pointers (via a template of some kind).
6348 static int list_size(char** l, int item_size)
6350 int i,j = 0;
6351 if(l)
6352 { for(i=0;l[i];i++)
6353 j += (item_size) ? item_size : strlen(l[i]) + 1;
6354 j += (i + 1) * sizeof(char*); }
6355 return j;
6358 static int list_dup(char** l_src, char** l_to, int item_size)
6360 char *p;
6361 int i;
6363 for (i = 0; l_src[i]; i++) ;
6364 p = (char *)(l_to + i + 1);
6365 for (i = 0; l_src[i]; i++)
6367 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
6368 memcpy(p, l_src[i], count);
6369 l_to[i] = p;
6370 p += count;
6372 l_to[i] = NULL;
6373 return p - (char *)l_to;
6376 /* ----- hostent */
6378 /* create a hostent entry
6380 * Creates the entry with enough memory for the name, aliases
6381 * addresses, and the address pointers. Also copies the name
6382 * and sets up all the pointers.
6384 * NOTE: The alias and address lists must be allocated with room
6385 * for the NULL item terminating the list. This is true even if
6386 * the list has no items ("aliases" and "addresses" must be
6387 * at least "1", a truly empty list is invalid).
6389 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length)
6391 struct WS_hostent *p_to;
6392 char *p;
6393 int size = (sizeof(struct WS_hostent) +
6394 strlen(name) + 1 +
6395 sizeof(char *) * aliases +
6396 aliases_size +
6397 sizeof(char *) * addresses +
6398 address_length * (addresses - 1)), i;
6400 if (!(p_to = check_buffer_he(size))) return NULL;
6401 memset(p_to, 0, size);
6403 /* Use the memory in the same way winsock does.
6404 * First set the pointer for aliases, second set the pointers for addresses.
6405 * Third fill the addresses indexes, fourth jump aliases names size.
6406 * Fifth fill the hostname.
6407 * NOTE: This method is valid for OS version's >= XP.
6409 p = (char *)(p_to + 1);
6410 p_to->h_aliases = (char **)p;
6411 p += sizeof(char *)*aliases;
6413 p_to->h_addr_list = (char **)p;
6414 p += sizeof(char *)*addresses;
6416 for (i = 0, addresses--; i < addresses; i++, p += address_length)
6417 p_to->h_addr_list[i] = p;
6419 /* NOTE: h_aliases must be filled in manually because we don't know each string
6420 * size, leave these pointers NULL (already set to NULL by memset earlier).
6422 p += aliases_size;
6424 p_to->h_name = p;
6425 strcpy(p, name);
6427 return p_to;
6430 /* duplicate hostent entry
6431 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
6432 * Ditto for protoent and servent.
6434 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
6436 int i, addresses = 0, alias_size = 0;
6437 struct WS_hostent *p_to;
6438 char *p;
6440 for( i = 0; p_he->h_aliases[i]; i++) alias_size += strlen(p_he->h_aliases[i]) + 1;
6441 while (p_he->h_addr_list[addresses]) addresses++;
6443 p_to = WS_create_he(p_he->h_name, i + 1, alias_size, addresses + 1, p_he->h_length);
6445 if (!p_to) return NULL;
6446 p_to->h_addrtype = convert_af_u2w(p_he->h_addrtype);
6447 p_to->h_length = p_he->h_length;
6449 for(i = 0, p = p_to->h_addr_list[0]; p_he->h_addr_list[i]; i++, p += p_to->h_length)
6450 memcpy(p, p_he->h_addr_list[i], p_to->h_length);
6452 /* Fill the aliases after the IP data */
6453 for(i = 0; p_he->h_aliases[i]; i++)
6455 p_to->h_aliases[i] = p;
6456 strcpy(p, p_he->h_aliases[i]);
6457 p += strlen(p) + 1;
6460 return p_to;
6463 /* ----- protoent */
6465 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
6467 char *p;
6468 struct WS_protoent *p_to;
6470 int size = (sizeof(*p_pe) +
6471 strlen(p_pe->p_name) + 1 +
6472 list_size(p_pe->p_aliases, 0));
6474 if (!(p_to = check_buffer_pe(size))) return NULL;
6475 p_to->p_proto = p_pe->p_proto;
6477 p = (char *)(p_to + 1);
6478 p_to->p_name = p;
6479 strcpy(p, p_pe->p_name);
6480 p += strlen(p) + 1;
6482 p_to->p_aliases = (char **)p;
6483 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
6484 return p_to;
6487 /* ----- servent */
6489 static struct WS_servent *WS_dup_se(const struct servent* p_se)
6491 char *p;
6492 struct WS_servent *p_to;
6494 int size = (sizeof(*p_se) +
6495 strlen(p_se->s_proto) + 1 +
6496 strlen(p_se->s_name) + 1 +
6497 list_size(p_se->s_aliases, 0));
6499 if (!(p_to = check_buffer_se(size))) return NULL;
6500 p_to->s_port = p_se->s_port;
6502 p = (char *)(p_to + 1);
6503 p_to->s_name = p;
6504 strcpy(p, p_se->s_name);
6505 p += strlen(p) + 1;
6507 p_to->s_proto = p;
6508 strcpy(p, p_se->s_proto);
6509 p += strlen(p) + 1;
6511 p_to->s_aliases = (char **)p;
6512 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
6513 return p_to;
6517 /***********************************************************************
6518 * WSARecv (WS2_32.67)
6520 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6521 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
6522 LPWSAOVERLAPPED lpOverlapped,
6523 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
6525 return WS2_recv_base(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
6526 NULL, NULL, lpOverlapped, lpCompletionRoutine, NULL);
6529 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6530 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
6531 struct WS_sockaddr *lpFrom,
6532 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
6533 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
6534 LPWSABUF lpControlBuffer )
6536 unsigned int i, options;
6537 int n, fd, err, overlapped;
6538 struct ws2_async *wsa, localwsa;
6539 BOOL is_blocking;
6540 DWORD timeout_start = GetTickCount();
6541 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
6543 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
6544 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
6545 (lpFromlen ? *lpFromlen : -1),
6546 lpOverlapped, lpCompletionRoutine);
6548 fd = get_sock_fd( s, FILE_READ_DATA, &options );
6549 TRACE( "fd=%d, options=%x\n", fd, options );
6551 if (fd == -1) return SOCKET_ERROR;
6553 overlapped = (lpOverlapped || lpCompletionRoutine) &&
6554 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
6555 if (overlapped || dwBufferCount > 1)
6557 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
6559 err = WSAEFAULT;
6560 goto error;
6563 else
6564 wsa = &localwsa;
6566 wsa->hSocket = SOCKET2HANDLE(s);
6567 wsa->flags = *lpFlags;
6568 wsa->lpFlags = lpFlags;
6569 wsa->addr = lpFrom;
6570 wsa->addrlen.ptr = lpFromlen;
6571 wsa->control = lpControlBuffer;
6572 wsa->n_iovecs = dwBufferCount;
6573 wsa->first_iovec = 0;
6574 for (i = 0; i < dwBufferCount; i++)
6576 /* check buffer first to trigger write watches */
6577 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
6579 err = WSAEFAULT;
6580 goto error;
6582 wsa->iovec[i].iov_base = lpBuffers[i].buf;
6583 wsa->iovec[i].iov_len = lpBuffers[i].len;
6586 for (;;)
6588 n = WS2_recv( fd, wsa );
6589 if (n == -1)
6591 if (errno != EAGAIN)
6593 int loc_errno = errno;
6594 err = wsaErrno();
6595 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
6596 goto error;
6599 else if (lpNumberOfBytesRecvd) *lpNumberOfBytesRecvd = n;
6601 if (overlapped)
6603 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
6605 wsa->user_overlapped = lpOverlapped;
6606 wsa->completion_func = lpCompletionRoutine;
6607 release_sock_fd( s, fd );
6609 if (n == -1)
6611 iosb->u.Status = STATUS_PENDING;
6612 iosb->Information = 0;
6614 SERVER_START_REQ( register_async )
6616 req->type = ASYNC_TYPE_READ;
6617 req->async.handle = wine_server_obj_handle( wsa->hSocket );
6618 req->async.callback = wine_server_client_ptr( WS2_async_recv );
6619 req->async.iosb = wine_server_client_ptr( iosb );
6620 req->async.arg = wine_server_client_ptr( wsa );
6621 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
6622 req->async.cvalue = cvalue;
6623 err = wine_server_call( req );
6625 SERVER_END_REQ;
6627 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
6628 WSASetLastError( NtStatusToWSAError( err ));
6629 return SOCKET_ERROR;
6632 iosb->u.Status = STATUS_SUCCESS;
6633 iosb->Information = n;
6634 if (!wsa->completion_func)
6636 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
6637 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
6638 HeapFree( GetProcessHeap(), 0, wsa );
6640 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
6641 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
6642 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6643 return 0;
6646 if (n != -1) break;
6648 if ((err = _is_blocking( s, &is_blocking )))
6650 err = NtStatusToWSAError( err );
6651 goto error;
6654 if ( is_blocking )
6656 struct pollfd pfd;
6657 int timeout = GET_RCVTIMEO(fd);
6658 if (timeout != -1)
6660 timeout -= GetTickCount() - timeout_start;
6661 if (timeout < 0) timeout = 0;
6664 pfd.fd = fd;
6665 pfd.events = POLLIN;
6666 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
6668 if (!timeout || !poll( &pfd, 1, timeout ))
6670 err = WSAETIMEDOUT;
6671 /* a timeout is not fatal */
6672 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6673 goto error;
6676 else
6678 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6679 err = WSAEWOULDBLOCK;
6680 goto error;
6684 TRACE(" -> %i bytes\n", n);
6685 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
6686 release_sock_fd( s, fd );
6687 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6689 return 0;
6691 error:
6692 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
6693 release_sock_fd( s, fd );
6694 WARN(" -> ERROR %d\n", err);
6695 WSASetLastError( err );
6696 return SOCKET_ERROR;
6699 /***********************************************************************
6700 * WSARecvFrom (WS2_32.69)
6702 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6703 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
6704 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
6705 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
6708 return WS2_recv_base( s, lpBuffers, dwBufferCount,
6709 lpNumberOfBytesRecvd, lpFlags,
6710 lpFrom, lpFromlen,
6711 lpOverlapped, lpCompletionRoutine, NULL );
6714 /***********************************************************************
6715 * WSCInstallProvider (WS2_32.88)
6717 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
6718 LPCWSTR lpszProviderDllPath,
6719 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
6720 DWORD dwNumberOfEntries,
6721 LPINT lpErrno )
6723 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
6724 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
6725 dwNumberOfEntries, lpErrno);
6726 *lpErrno = 0;
6727 return 0;
6731 /***********************************************************************
6732 * WSCDeinstallProvider (WS2_32.83)
6734 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
6736 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
6737 *lpErrno = 0;
6738 return 0;
6742 /***********************************************************************
6743 * WSAAccept (WS2_32.26)
6745 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
6746 LPCONDITIONPROC lpfnCondition, DWORD_PTR dwCallbackData)
6749 int ret = 0, size;
6750 WSABUF CallerId, CallerData, CalleeId, CalleeData;
6751 /* QOS SQOS, GQOS; */
6752 GROUP g;
6753 SOCKET cs;
6754 SOCKADDR src_addr, dst_addr;
6756 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
6757 s, addr, addrlen, lpfnCondition, dwCallbackData);
6759 cs = WS_accept(s, addr, addrlen);
6760 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
6761 if (!lpfnCondition) return cs;
6763 if (addr && addrlen)
6765 CallerId.buf = (char *)addr;
6766 CallerId.len = *addrlen;
6768 else
6770 size = sizeof(src_addr);
6771 WS_getpeername(cs, &src_addr, &size);
6772 CallerId.buf = (char *)&src_addr;
6773 CallerId.len = size;
6775 CallerData.buf = NULL;
6776 CallerData.len = 0;
6778 size = sizeof(dst_addr);
6779 WS_getsockname(cs, &dst_addr, &size);
6781 CalleeId.buf = (char *)&dst_addr;
6782 CalleeId.len = sizeof(dst_addr);
6784 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
6785 &CalleeId, &CalleeData, &g, dwCallbackData);
6787 switch (ret)
6789 case CF_ACCEPT:
6790 return cs;
6791 case CF_DEFER:
6792 SERVER_START_REQ( set_socket_deferred )
6794 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6795 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
6796 if ( !wine_server_call_err ( req ) )
6798 SetLastError( WSATRY_AGAIN );
6799 WS_closesocket( cs );
6802 SERVER_END_REQ;
6803 return SOCKET_ERROR;
6804 case CF_REJECT:
6805 WS_closesocket(cs);
6806 SetLastError(WSAECONNREFUSED);
6807 return SOCKET_ERROR;
6808 default:
6809 FIXME("Unknown return type from Condition function\n");
6810 SetLastError(WSAENOTSOCK);
6811 return SOCKET_ERROR;
6815 /***********************************************************************
6816 * WSADuplicateSocketA (WS2_32.32)
6818 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
6820 return WS_DuplicateSocket(FALSE, s, dwProcessId, (LPWSAPROTOCOL_INFOW) lpProtocolInfo);
6823 /***********************************************************************
6824 * WSADuplicateSocketW (WS2_32.33)
6826 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
6828 return WS_DuplicateSocket(TRUE, s, dwProcessId, lpProtocolInfo);
6831 /***********************************************************************
6832 * WSAInstallServiceClassA (WS2_32.48)
6834 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
6836 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
6837 WSASetLastError(WSAEACCES);
6838 return SOCKET_ERROR;
6841 /***********************************************************************
6842 * WSAInstallServiceClassW (WS2_32.49)
6844 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
6846 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
6847 WSASetLastError(WSAEACCES);
6848 return SOCKET_ERROR;
6851 /***********************************************************************
6852 * WSARemoveServiceClass (WS2_32.70)
6854 int WINAPI WSARemoveServiceClass(LPGUID info)
6856 FIXME("Request to remove service %p\n",info);
6857 WSASetLastError(WSATYPE_NOT_FOUND);
6858 return SOCKET_ERROR;
6861 /***********************************************************************
6862 * inet_ntop (WS2_32.@)
6864 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
6866 #ifdef HAVE_INET_NTOP
6867 struct WS_in6_addr *in6;
6868 struct WS_in_addr *in;
6869 PCSTR pdst;
6871 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
6872 if (!buffer)
6874 WSASetLastError( STATUS_INVALID_PARAMETER );
6875 return NULL;
6878 switch (family)
6880 case WS_AF_INET:
6882 in = addr;
6883 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
6884 break;
6886 case WS_AF_INET6:
6888 in6 = addr;
6889 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
6890 break;
6892 default:
6893 WSASetLastError( WSAEAFNOSUPPORT );
6894 return NULL;
6897 if (!pdst) WSASetLastError( STATUS_INVALID_PARAMETER );
6898 return pdst;
6899 #else
6900 FIXME( "not supported on this platform\n" );
6901 WSASetLastError( WSAEAFNOSUPPORT );
6902 return NULL;
6903 #endif
6906 /***********************************************************************
6907 * WSAStringToAddressA (WS2_32.80)
6909 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
6910 INT AddressFamily,
6911 LPWSAPROTOCOL_INFOA lpProtocolInfo,
6912 LPSOCKADDR lpAddress,
6913 LPINT lpAddressLength)
6915 INT res=0;
6916 LPSTR workBuffer=NULL,ptrPort;
6918 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
6919 lpProtocolInfo, lpAddress, lpAddressLength );
6921 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
6923 if (!AddressString)
6925 WSASetLastError(WSAEINVAL);
6926 return SOCKET_ERROR;
6929 if (lpProtocolInfo)
6930 FIXME("ProtocolInfo not implemented.\n");
6932 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
6933 strlen(AddressString) + 1);
6934 if (!workBuffer)
6936 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6937 return SOCKET_ERROR;
6940 strcpy(workBuffer, AddressString);
6942 switch(AddressFamily)
6944 case WS_AF_INET:
6946 struct in_addr inetaddr;
6948 /* If lpAddressLength is too small, tell caller the size we need */
6949 if (*lpAddressLength < sizeof(SOCKADDR_IN))
6951 *lpAddressLength = sizeof(SOCKADDR_IN);
6952 res = WSAEFAULT;
6953 break;
6955 *lpAddressLength = sizeof(SOCKADDR_IN);
6956 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
6958 ((LPSOCKADDR_IN)lpAddress)->sin_family = WS_AF_INET;
6960 ptrPort = strchr(workBuffer, ':');
6961 if(ptrPort)
6963 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
6964 *ptrPort = '\0';
6966 else
6968 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
6971 if(inet_aton(workBuffer, &inetaddr) > 0)
6973 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
6974 res = 0;
6976 else
6977 res = WSAEINVAL;
6979 break;
6982 case WS_AF_INET6:
6984 struct in6_addr inetaddr;
6985 /* If lpAddressLength is too small, tell caller the size we need */
6986 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
6988 *lpAddressLength = sizeof(SOCKADDR_IN6);
6989 res = WSAEFAULT;
6990 break;
6992 #ifdef HAVE_INET_PTON
6993 *lpAddressLength = sizeof(SOCKADDR_IN6);
6994 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
6996 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
6998 /* This one is a bit tricky. An IPv6 address contains colons, so the
6999 * check from IPv4 doesn't work like that. However, IPv6 addresses that
7000 * contain a port are written with braces like [fd12:3456:7890::1]:12345
7001 * so what we will do is to look for ']', check if the next char is a
7002 * colon, and if it is, parse the port as in IPv4. */
7004 ptrPort = strchr(workBuffer, ']');
7005 if(ptrPort && *(++ptrPort) == ':')
7007 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort+1));
7008 *ptrPort = '\0';
7010 else
7012 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
7015 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
7017 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
7018 sizeof(struct in6_addr));
7019 res = 0;
7021 else
7022 #endif /* HAVE_INET_PTON */
7023 res = WSAEINVAL;
7025 break;
7027 default:
7028 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
7029 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
7030 res = WSAEINVAL;
7033 HeapFree(GetProcessHeap(), 0, workBuffer);
7035 if (!res) return 0;
7036 WSASetLastError(res);
7037 return SOCKET_ERROR;
7040 /***********************************************************************
7041 * WSAStringToAddressW (WS2_32.81)
7043 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
7044 * If this should be the case, it would be required to map these digits
7045 * to Unicode digits (0-9) using FoldString first.
7047 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
7048 INT AddressFamily,
7049 LPWSAPROTOCOL_INFOW lpProtocolInfo,
7050 LPSOCKADDR lpAddress,
7051 LPINT lpAddressLength)
7053 INT sBuffer,res=0;
7054 LPSTR workBuffer=NULL;
7055 WSAPROTOCOL_INFOA infoA;
7056 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
7058 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
7059 lpAddress, lpAddressLength );
7061 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
7063 /* if ProtocolInfo is available - convert to ANSI variant */
7064 if (lpProtocolInfo)
7066 lpProtoInfoA = &infoA;
7067 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
7069 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
7070 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
7072 WSASetLastError( WSAEINVAL);
7073 return SOCKET_ERROR;
7077 if (AddressString)
7079 /* Translate AddressString to ANSI code page - assumes that only
7080 standard digits 0-9 are used with this API call */
7081 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
7082 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
7084 if (workBuffer)
7086 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
7087 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
7088 lpAddress,lpAddressLength);
7089 HeapFree( GetProcessHeap(), 0, workBuffer );
7090 return res;
7092 else
7093 res = WSA_NOT_ENOUGH_MEMORY;
7095 else
7096 res = WSAEINVAL;
7098 WSASetLastError(res);
7099 return SOCKET_ERROR;
7102 /***********************************************************************
7103 * WSAAddressToStringA (WS2_32.27)
7105 * See WSAAddressToStringW
7107 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
7108 LPWSAPROTOCOL_INFOA info, LPSTR string,
7109 LPDWORD lenstr )
7111 DWORD size;
7112 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
7113 CHAR *p;
7115 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
7117 if (!sockaddr) return SOCKET_ERROR;
7118 if (!string || !lenstr) return SOCKET_ERROR;
7120 switch(sockaddr->sa_family)
7122 case WS_AF_INET:
7123 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
7124 sprintf( buffer, "%u.%u.%u.%u:%u",
7125 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
7126 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
7127 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
7128 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
7129 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
7131 p = strchr( buffer, ':' );
7132 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
7133 break;
7135 case WS_AF_INET6:
7137 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
7139 buffer[0] = 0;
7140 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
7141 if ((sockaddr6->sin6_port))
7142 strcpy(buffer, "[");
7143 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, buffer+strlen(buffer), sizeof(buffer)))
7145 WSASetLastError(WSAEINVAL);
7146 return SOCKET_ERROR;
7148 if ((sockaddr6->sin6_scope_id))
7149 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
7150 if ((sockaddr6->sin6_port))
7151 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
7152 break;
7155 default:
7156 WSASetLastError(WSAEINVAL);
7157 return SOCKET_ERROR;
7160 size = strlen( buffer ) + 1;
7162 if (*lenstr < size)
7164 *lenstr = size;
7165 WSASetLastError(WSAEFAULT);
7166 return SOCKET_ERROR;
7169 TRACE("=> %s,%u bytes\n", debugstr_a(buffer), size);
7170 *lenstr = size;
7171 strcpy( string, buffer );
7172 return 0;
7175 /***********************************************************************
7176 * WSAAddressToStringW (WS2_32.28)
7178 * Convert a sockaddr address into a readable address string.
7180 * PARAMS
7181 * sockaddr [I] Pointer to a sockaddr structure.
7182 * len [I] Size of the sockaddr structure.
7183 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
7184 * string [I/O] Pointer to a buffer to receive the address string.
7185 * lenstr [I/O] Size of the receive buffer in WCHARs.
7187 * RETURNS
7188 * Success: 0
7189 * Failure: SOCKET_ERROR
7191 * NOTES
7192 * The 'info' parameter is ignored.
7194 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
7195 LPWSAPROTOCOL_INFOW info, LPWSTR string,
7196 LPDWORD lenstr )
7198 INT ret;
7199 DWORD size;
7200 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
7201 CHAR bufAddr[54];
7203 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
7205 size = *lenstr;
7206 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
7208 if (ret) return ret;
7210 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
7212 if (*lenstr < size)
7214 *lenstr = size;
7215 WSASetLastError(WSAEFAULT);
7216 return SOCKET_ERROR;
7219 TRACE("=> %s,%u bytes\n", debugstr_w(buffer), size);
7220 *lenstr = size;
7221 lstrcpyW( string, buffer );
7222 return 0;
7225 /***********************************************************************
7226 * WSAEnumNameSpaceProvidersA (WS2_32.34)
7228 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
7230 FIXME( "(%p %p) Stub!\n", len, buffer );
7231 return 0;
7234 /***********************************************************************
7235 * WSAEnumNameSpaceProvidersW (WS2_32.35)
7237 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
7239 FIXME( "(%p %p) Stub!\n", len, buffer );
7240 return 0;
7243 /***********************************************************************
7244 * WSAGetQOSByName (WS2_32.41)
7246 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
7248 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
7249 return FALSE;
7252 /***********************************************************************
7253 * WSAGetServiceClassInfoA (WS2_32.42)
7255 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
7256 LPWSASERVICECLASSINFOA info )
7258 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
7259 len, info );
7260 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7261 return SOCKET_ERROR;
7264 /***********************************************************************
7265 * WSAGetServiceClassInfoW (WS2_32.43)
7267 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
7268 LPWSASERVICECLASSINFOW info )
7270 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
7271 len, info );
7272 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7273 return SOCKET_ERROR;
7276 /***********************************************************************
7277 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
7279 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
7281 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
7282 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7283 return SOCKET_ERROR;
7286 /***********************************************************************
7287 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
7289 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
7291 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
7292 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7293 return SOCKET_ERROR;
7296 /***********************************************************************
7297 * WSALookupServiceBeginA (WS2_32.59)
7299 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
7300 DWORD dwControlFlags,
7301 LPHANDLE lphLookup)
7303 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
7304 lphLookup);
7305 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7306 return SOCKET_ERROR;
7309 /***********************************************************************
7310 * WSALookupServiceBeginW (WS2_32.60)
7312 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
7313 DWORD dwControlFlags,
7314 LPHANDLE lphLookup)
7316 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
7317 lphLookup);
7318 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7319 return SOCKET_ERROR;
7322 /***********************************************************************
7323 * WSALookupServiceEnd (WS2_32.61)
7325 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
7327 FIXME("(%p) Stub!\n", lookup );
7328 return 0;
7331 /***********************************************************************
7332 * WSALookupServiceNextA (WS2_32.62)
7334 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
7336 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
7337 WSASetLastError(WSA_E_NO_MORE);
7338 return SOCKET_ERROR;
7341 /***********************************************************************
7342 * WSALookupServiceNextW (WS2_32.63)
7344 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
7346 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
7347 WSASetLastError(WSA_E_NO_MORE);
7348 return SOCKET_ERROR;
7351 /***********************************************************************
7352 * WSANtohl (WS2_32.64)
7354 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
7356 TRACE( "(0x%04lx 0x%08x %p)\n", s, netlong, lphostlong );
7358 if (!lphostlong) return WSAEFAULT;
7360 *lphostlong = ntohl( netlong );
7361 return 0;
7364 /***********************************************************************
7365 * WSANtohs (WS2_32.65)
7367 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
7369 TRACE( "(0x%04lx 0x%08x %p)\n", s, netshort, lphostshort );
7371 if (!lphostshort) return WSAEFAULT;
7373 *lphostshort = ntohs( netshort );
7374 return 0;
7377 /***********************************************************************
7378 * WSAProviderConfigChange (WS2_32.66)
7380 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
7381 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
7383 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
7384 return SOCKET_ERROR;
7387 /***********************************************************************
7388 * WSARecvDisconnect (WS2_32.68)
7390 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
7392 TRACE( "(0x%04lx %p)\n", s, disconnectdata );
7394 return WS_shutdown( s, SD_RECEIVE );
7397 /***********************************************************************
7398 * WSASetServiceA (WS2_32.76)
7400 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
7402 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
7403 return 0;
7406 /***********************************************************************
7407 * WSASetServiceW (WS2_32.77)
7409 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
7411 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
7412 return 0;
7415 /***********************************************************************
7416 * WSCEnableNSProvider (WS2_32.84)
7418 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
7420 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
7421 return 0;
7424 /***********************************************************************
7425 * WSCGetProviderPath (WS2_32.86)
7427 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
7429 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
7431 if (!errcode || !provider || !len) return WSAEFAULT;
7433 *errcode = WSAEINVAL;
7434 return SOCKET_ERROR;
7437 /***********************************************************************
7438 * WSCInstallNameSpace (WS2_32.87)
7440 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
7441 DWORD version, LPGUID provider )
7443 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
7444 namespace, version, debugstr_guid(provider) );
7445 return 0;
7448 /***********************************************************************
7449 * WSCUnInstallNameSpace (WS2_32.89)
7451 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
7453 FIXME("(%p) Stub!\n", lpProviderId);
7454 return NO_ERROR;
7457 /***********************************************************************
7458 * WSCWriteProviderOrder (WS2_32.91)
7460 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
7462 FIXME("(%p 0x%08x) Stub!\n", entry, number);
7463 return 0;
7466 /***********************************************************************
7467 * WSANSPIoctl (WS2_32.91)
7469 INT WINAPI WSANSPIoctl( HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer,
7470 DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer,
7471 LPDWORD lpcbBytesReturned, LPWSACOMPLETION lpCompletion )
7473 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup, dwControlCode,
7474 lpvInBuffer, cbInBuffer, lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpCompletion);
7475 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7476 return SOCKET_ERROR;
7479 /*****************************************************************************
7480 * WSAEnumProtocolsA [WS2_32.@]
7482 * see function WSAEnumProtocolsW
7484 INT WINAPI WSAEnumProtocolsA( LPINT protocols, LPWSAPROTOCOL_INFOA buffer, LPDWORD len )
7486 return WS_EnumProtocols( FALSE, protocols, (LPWSAPROTOCOL_INFOW) buffer, len);
7489 /*****************************************************************************
7490 * WSAEnumProtocolsW [WS2_32.@]
7492 * Retrieves information about specified set of active network protocols.
7494 * PARAMS
7495 * protocols [I] Pointer to null-terminated array of protocol id's. NULL
7496 * retrieves information on all available protocols.
7497 * buffer [I] Pointer to a buffer to be filled with WSAPROTOCOL_INFO
7498 * structures.
7499 * len [I/O] Pointer to a variable specifying buffer size. On output
7500 * the variable holds the number of bytes needed when the
7501 * specified size is too small.
7503 * RETURNS
7504 * Success: number of WSAPROTOCOL_INFO structures in buffer.
7505 * Failure: SOCKET_ERROR
7507 * NOTES
7508 * NT4SP5 does not return SPX if protocols == NULL
7510 * BUGS
7511 * - NT4SP5 returns in addition these list of NETBIOS protocols
7512 * (address family 17), each entry two times one for socket type 2 and 5
7514 * iProtocol szProtocol
7515 * 0x80000000 \Device\NwlnkNb
7516 * 0xfffffffa \Device\NetBT_CBENT7
7517 * 0xfffffffb \Device\Nbf_CBENT7
7518 * 0xfffffffc \Device\NetBT_NdisWan5
7519 * 0xfffffffd \Device\NetBT_El9202
7520 * 0xfffffffe \Device\Nbf_El9202
7521 * 0xffffffff \Device\Nbf_NdisWan4
7523 * - there is no check that the operating system supports the returned
7524 * protocols
7526 INT WINAPI WSAEnumProtocolsW( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
7528 return WS_EnumProtocols( TRUE, protocols, buffer, len);
7531 /*****************************************************************************
7532 * WSCEnumProtocols [WS2_32.@]
7534 * PARAMS
7535 * protocols [I] Null-terminated array of iProtocol values.
7536 * buffer [O] Buffer of WSAPROTOCOL_INFOW structures.
7537 * len [I/O] Size of buffer on input/output.
7538 * errno [O] Error code.
7540 * RETURNS
7541 * Success: number of protocols to be reported on.
7542 * Failure: SOCKET_ERROR. error is in errno.
7544 * BUGS
7545 * Doesn't supply info on layered protocols.
7548 INT WINAPI WSCEnumProtocols( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len, LPINT err )
7550 INT ret = WSAEnumProtocolsW( protocols, buffer, len );
7552 if (ret == SOCKET_ERROR) *err = WSAENOBUFS;
7554 return ret;