dpvoice: Turn GetCompressionTypes into a semi-stub.
[wine.git] / dlls / ws2_32 / socket.c
blobfaf2ec11e9271a192a3bbbd57538f1b50d2c86aa
1 /*
2 * based on Windows Sockets 1.1 specs
4 * Copyright (C) 1993,1994,1996,1997 John Brezak, Erik Bos, Alex Korobka.
5 * Copyright (C) 2001 Stefan Leichter
6 * Copyright (C) 2004 Hans Leidekker
7 * Copyright (C) 2005 Marcus Meissner
8 * Copyright (C) 2006-2008 Kai Blin
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24 * NOTE: If you make any changes to fix a particular app, make sure
25 * they don't break something else like Netscape or telnet and ftp
26 * clients and servers (www.winsite.com got a lot of those).
29 #include "config.h"
30 #include "wine/port.h"
32 #include <stdarg.h>
33 #include <stdio.h>
34 #include <string.h>
35 #include <sys/types.h>
36 #ifdef HAVE_SYS_IPC_H
37 # include <sys/ipc.h>
38 #endif
39 #ifdef HAVE_SYS_IOCTL_H
40 # include <sys/ioctl.h>
41 #endif
42 #ifdef HAVE_SYS_FILIO_H
43 # include <sys/filio.h>
44 #endif
45 #ifdef HAVE_SYS_SOCKIO_H
46 # include <sys/sockio.h>
47 #endif
49 #if defined(__EMX__)
50 # include <sys/so_ioctl.h>
51 #endif
53 #ifdef HAVE_SYS_PARAM_H
54 # include <sys/param.h>
55 #endif
57 #ifdef HAVE_SYS_MSG_H
58 # include <sys/msg.h>
59 #endif
60 #ifdef HAVE_SYS_WAIT_H
61 # include <sys/wait.h>
62 #endif
63 #ifdef HAVE_SYS_UIO_H
64 # include <sys/uio.h>
65 #endif
66 #ifdef HAVE_SYS_SOCKET_H
67 #include <sys/socket.h>
68 #endif
69 #ifdef HAVE_NETINET_IN_H
70 # include <netinet/in.h>
71 #endif
72 #ifdef HAVE_NETINET_TCP_H
73 # include <netinet/tcp.h>
74 #endif
75 #ifdef HAVE_ARPA_INET_H
76 # include <arpa/inet.h>
77 #endif
78 #include <ctype.h>
79 #include <fcntl.h>
80 #include <errno.h>
81 #ifdef HAVE_NETDB_H
82 #include <netdb.h>
83 #endif
84 #ifdef HAVE_UNISTD_H
85 # include <unistd.h>
86 #endif
87 #include <stdlib.h>
88 #ifdef HAVE_ARPA_NAMESER_H
89 # include <arpa/nameser.h>
90 #endif
91 #ifdef HAVE_RESOLV_H
92 # include <resolv.h>
93 #endif
94 #ifdef HAVE_NET_IF_H
95 # include <net/if.h>
96 #endif
97 #ifdef HAVE_LINUX_FILTER_H
98 # include <linux/filter.h>
99 #endif
101 #ifdef HAVE_NETIPX_IPX_H
102 # include <netipx/ipx.h>
103 #elif defined(HAVE_LINUX_IPX_H)
104 # ifdef HAVE_ASM_TYPES_H
105 # include <asm/types.h>
106 # endif
107 # ifdef HAVE_LINUX_TYPES_H
108 # include <linux/types.h>
109 # endif
110 # include <linux/ipx.h>
111 #endif
112 #if defined(SOL_IPX) || defined(SO_DEFAULT_HEADERS)
113 # define HAS_IPX
114 #endif
116 #ifdef HAVE_LINUX_IRDA_H
117 # ifdef HAVE_LINUX_TYPES_H
118 # include <linux/types.h>
119 # endif
120 # include <linux/irda.h>
121 # define HAS_IRDA
122 #endif
124 #ifdef HAVE_POLL_H
125 #include <poll.h>
126 #endif
127 #ifdef HAVE_SYS_POLL_H
128 # include <sys/poll.h>
129 #endif
130 #ifdef HAVE_SYS_TIME_H
131 # include <sys/time.h>
132 #endif
134 #define NONAMELESSUNION
135 #define NONAMELESSSTRUCT
136 #include "ntstatus.h"
137 #define WIN32_NO_STATUS
138 #include "windef.h"
139 #include "winbase.h"
140 #include "wingdi.h"
141 #include "winuser.h"
142 #include "winerror.h"
143 #include "winnls.h"
144 #include "winsock2.h"
145 #include "mswsock.h"
146 #include "ws2tcpip.h"
147 #include "ws2spi.h"
148 #include "wsipx.h"
149 #include "wshisotp.h"
150 #include "mstcpip.h"
151 #include "af_irda.h"
152 #include "winnt.h"
153 #define USE_WC_PREFIX /* For CMSG_DATA */
154 #include "iphlpapi.h"
155 #include "wine/server.h"
156 #include "wine/debug.h"
157 #include "wine/exception.h"
158 #include "wine/unicode.h"
160 #ifdef HAS_IPX
161 # include "wsnwlink.h"
162 #endif
164 #if defined(linux) && !defined(IP_UNICAST_IF)
165 #define IP_UNICAST_IF 50
166 #endif
168 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
169 # define sipx_network sipx_addr.x_net
170 # define sipx_node sipx_addr.x_host.c_host
171 #endif /* __FreeBSD__ */
173 #ifndef INADDR_NONE
174 #define INADDR_NONE ~0UL
175 #endif
177 WINE_DEFAULT_DEBUG_CHANNEL(winsock);
178 WINE_DECLARE_DEBUG_CHANNEL(winediag);
180 /* names of the protocols */
181 static const WCHAR NameIpxW[] = {'I', 'P', 'X', '\0'};
182 static const WCHAR NameSpxW[] = {'S', 'P', 'X', '\0'};
183 static const WCHAR NameSpxIIW[] = {'S', 'P', 'X', ' ', 'I', 'I', '\0'};
184 static const WCHAR NameTcpW[] = {'T', 'C', 'P', '/', 'I', 'P', '\0'};
185 static const WCHAR NameUdpW[] = {'U', 'D', 'P', '/', 'I', 'P', '\0'};
187 /* Taken from Win2k */
188 static const GUID ProviderIdIP = { 0xe70f1aa0, 0xab8b, 0x11cf,
189 { 0x8c, 0xa3, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
190 static const GUID ProviderIdIPX = { 0x11058240, 0xbe47, 0x11cf,
191 { 0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
192 static const GUID ProviderIdSPX = { 0x11058241, 0xbe47, 0x11cf,
193 { 0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
195 static const INT valid_protocols[] =
197 WS_IPPROTO_TCP,
198 WS_IPPROTO_UDP,
199 WS_NSPROTO_IPX,
200 WS_NSPROTO_SPX,
201 WS_NSPROTO_SPXII,
205 #define IS_IPX_PROTO(X) ((X) >= WS_NSPROTO_IPX && (X) <= WS_NSPROTO_IPX + 255)
207 #if defined(IP_UNICAST_IF) && defined(SO_ATTACH_FILTER)
208 # define LINUX_BOUND_IF
209 struct interface_filter {
210 struct sock_filter iface_memaddr;
211 struct sock_filter iface_rule;
212 struct sock_filter ip_memaddr;
213 struct sock_filter ip_rule;
214 struct sock_filter return_keep;
215 struct sock_filter return_dump;
217 # define FILTER_JUMP_DUMP(here) (u_char)(offsetof(struct interface_filter, return_dump) \
218 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
219 /sizeof(struct sock_filter)
220 # define FILTER_JUMP_KEEP(here) (u_char)(offsetof(struct interface_filter, return_keep) \
221 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
222 /sizeof(struct sock_filter)
223 # define FILTER_JUMP_NEXT() (u_char)(0)
224 # define SKF_NET_DESTIP 16 /* offset in the network header to the destination IP */
225 static struct interface_filter generic_interface_filter = {
226 /* This filter rule allows incoming packets on the specified interface, which works for all
227 * remotely generated packets and for locally generated broadcast packets. */
228 BPF_STMT(BPF_LD+BPF_W+BPF_ABS, SKF_AD_OFF+SKF_AD_IFINDEX),
229 BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0xdeadbeef, FILTER_JUMP_KEEP(iface_rule), FILTER_JUMP_NEXT()),
230 /* This rule allows locally generated packets targeted at the specific IP address of the chosen
231 * adapter (local packets not destined for the broadcast address do not have IFINDEX set) */
232 BPF_STMT(BPF_LD+BPF_W+BPF_ABS, SKF_NET_OFF+SKF_NET_DESTIP),
233 BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0xdeadbeef, FILTER_JUMP_KEEP(ip_rule), FILTER_JUMP_DUMP(ip_rule)),
234 BPF_STMT(BPF_RET+BPF_K, (u_int)-1), /* keep packet */
235 BPF_STMT(BPF_RET+BPF_K, 0) /* dump packet */
237 #endif /* LINUX_BOUND_IF */
240 * The actual definition of WSASendTo, wrapped in a different function name
241 * so that internal calls from ws2_32 itself will not trigger programs like
242 * Garena, which hooks WSASendTo/WSARecvFrom calls.
244 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
245 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
246 const struct WS_sockaddr *to, int tolen,
247 LPWSAOVERLAPPED lpOverlapped,
248 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine );
251 * Internal fundamental receive function, essentially WSARecvFrom with an
252 * additional parameter to support message control headers.
254 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
255 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
256 struct WS_sockaddr *lpFrom,
257 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
258 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
259 LPWSABUF lpControlBuffer );
261 /* critical section to protect some non-reentrant net function */
262 static CRITICAL_SECTION csWSgetXXXbyYYY;
263 static CRITICAL_SECTION_DEBUG critsect_debug =
265 0, 0, &csWSgetXXXbyYYY,
266 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
267 0, 0, { (DWORD_PTR)(__FILE__ ": csWSgetXXXbyYYY") }
269 static CRITICAL_SECTION csWSgetXXXbyYYY = { &critsect_debug, -1, 0, 0, 0, 0 };
271 union generic_unix_sockaddr
273 struct sockaddr addr;
274 char data[128]; /* should be big enough for all families */
277 static inline const char *debugstr_sockaddr( const struct WS_sockaddr *a )
279 if (!a) return "(nil)";
280 switch (a->sa_family)
282 case WS_AF_INET:
283 return wine_dbg_sprintf("{ family AF_INET, address %s, port %d }",
284 inet_ntoa(((const struct sockaddr_in *)a)->sin_addr),
285 ntohs(((const struct sockaddr_in *)a)->sin_port));
286 case WS_AF_INET6:
288 char buf[46];
289 const char *p;
290 struct WS_sockaddr_in6 *sin = (struct WS_sockaddr_in6 *)a;
292 p = WS_inet_ntop( WS_AF_INET6, &sin->sin6_addr, buf, sizeof(buf) );
293 if (!p)
294 p = "(unknown IPv6 address)";
295 return wine_dbg_sprintf("{ family AF_INET6, address %s, port %d }",
296 p, ntohs(sin->sin6_port));
298 case WS_AF_IPX:
300 int i;
301 char netnum[16], nodenum[16];
302 struct WS_sockaddr_ipx *sin = (struct WS_sockaddr_ipx *)a;
304 for (i = 0;i < 4; i++) sprintf(netnum + i * 2, "%02X", (unsigned char) sin->sa_netnum[i]);
305 for (i = 0;i < 6; i++) sprintf(nodenum + i * 2, "%02X", (unsigned char) sin->sa_nodenum[i]);
307 return wine_dbg_sprintf("{ family AF_IPX, address %s.%s, ipx socket %d }",
308 netnum, nodenum, sin->sa_socket);
310 case WS_AF_IRDA:
312 DWORD addr;
314 memcpy( &addr, ((const SOCKADDR_IRDA *)a)->irdaDeviceID, sizeof(addr) );
315 addr = ntohl( addr );
316 return wine_dbg_sprintf("{ family AF_IRDA, addr %08x, name %s }",
317 addr,
318 ((const SOCKADDR_IRDA *)a)->irdaServiceName);
320 default:
321 return wine_dbg_sprintf("{ family %d }", a->sa_family);
325 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
326 #define SOCKET2HANDLE(s) ((HANDLE)(s))
327 #define HANDLE2SOCKET(h) ((SOCKET)(h))
329 /****************************************************************
330 * Async IO declarations
331 ****************************************************************/
333 typedef struct ws2_async
335 HANDLE hSocket;
336 int type;
337 LPWSAOVERLAPPED user_overlapped;
338 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
339 IO_STATUS_BLOCK local_iosb;
340 struct WS_sockaddr *addr;
341 union
343 int val; /* for send operations */
344 int *ptr; /* for recv operations */
345 } addrlen;
346 DWORD flags;
347 DWORD *lpFlags;
348 WSABUF *control;
349 unsigned int n_iovecs;
350 unsigned int first_iovec;
351 struct iovec iovec[1];
352 } ws2_async;
354 typedef struct ws2_accept_async
356 HANDLE listen_socket;
357 HANDLE accept_socket;
358 LPOVERLAPPED user_overlapped;
359 ULONG_PTR cvalue;
360 PVOID buf; /* buffer to write data to */
361 int data_len;
362 int local_len;
363 int remote_len;
364 struct ws2_async *read;
365 } ws2_accept_async;
367 /****************************************************************/
369 /* ----------------------------------- internal data */
371 /* ws_... struct conversion flags */
373 typedef struct /* WSAAsyncSelect() control struct */
375 HANDLE service, event, sock;
376 HWND hWnd;
377 UINT uMsg;
378 LONG lEvent;
379 } ws_select_info;
381 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
382 #define WS_MAX_UDP_DATAGRAM 1024
383 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
385 /* hostent's, servent's and protent's are stored in one buffer per thread,
386 * as documented on MSDN for the functions that return any of the buffers */
387 struct per_thread_data
389 int opentype;
390 struct WS_hostent *he_buffer;
391 struct WS_servent *se_buffer;
392 struct WS_protoent *pe_buffer;
393 int he_len;
394 int se_len;
395 int pe_len;
396 char ntoa_buffer[16]; /* 4*3 digits + 3 '.' + 1 '\0' */
399 /* internal: routing description information */
400 struct route {
401 struct in_addr addr;
402 IF_INDEX interface;
403 DWORD metric;
406 static INT num_startup; /* reference counter */
407 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
409 /* function prototypes */
410 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length);
411 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
412 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
413 static struct WS_servent *WS_dup_se(const struct servent* p_se);
414 static int ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size);
416 int WSAIOCTL_GetInterfaceCount(void);
417 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
419 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus, ULONG Information );
421 #define MAP_OPTION(opt) { WS_##opt, opt }
423 static const int ws_sock_map[][2] =
425 MAP_OPTION( SO_DEBUG ),
426 MAP_OPTION( SO_ACCEPTCONN ),
427 MAP_OPTION( SO_REUSEADDR ),
428 MAP_OPTION( SO_KEEPALIVE ),
429 MAP_OPTION( SO_DONTROUTE ),
430 MAP_OPTION( SO_BROADCAST ),
431 MAP_OPTION( SO_LINGER ),
432 MAP_OPTION( SO_OOBINLINE ),
433 MAP_OPTION( SO_SNDBUF ),
434 MAP_OPTION( SO_RCVBUF ),
435 MAP_OPTION( SO_ERROR ),
436 MAP_OPTION( SO_TYPE ),
437 #ifdef SO_RCVTIMEO
438 MAP_OPTION( SO_RCVTIMEO ),
439 #endif
440 #ifdef SO_SNDTIMEO
441 MAP_OPTION( SO_SNDTIMEO ),
442 #endif
445 static const int ws_tcp_map[][2] =
447 #ifdef TCP_NODELAY
448 MAP_OPTION( TCP_NODELAY ),
449 #endif
452 static const int ws_ip_map[][2] =
454 MAP_OPTION( IP_MULTICAST_IF ),
455 MAP_OPTION( IP_MULTICAST_TTL ),
456 MAP_OPTION( IP_MULTICAST_LOOP ),
457 MAP_OPTION( IP_ADD_MEMBERSHIP ),
458 MAP_OPTION( IP_DROP_MEMBERSHIP ),
459 MAP_OPTION( IP_OPTIONS ),
460 #ifdef IP_HDRINCL
461 MAP_OPTION( IP_HDRINCL ),
462 #endif
463 MAP_OPTION( IP_TOS ),
464 MAP_OPTION( IP_TTL ),
465 #ifdef IP_PKTINFO
466 MAP_OPTION( IP_PKTINFO ),
467 #endif
468 #ifdef IP_UNICAST_IF
469 MAP_OPTION( IP_UNICAST_IF ),
470 #endif
473 static const int ws_ipv6_map[][2] =
475 #ifdef IPV6_ADD_MEMBERSHIP
476 MAP_OPTION( IPV6_ADD_MEMBERSHIP ),
477 #endif
478 #ifdef IPV6_DROP_MEMBERSHIP
479 MAP_OPTION( IPV6_DROP_MEMBERSHIP ),
480 #endif
481 MAP_OPTION( IPV6_MULTICAST_IF ),
482 MAP_OPTION( IPV6_MULTICAST_HOPS ),
483 MAP_OPTION( IPV6_MULTICAST_LOOP ),
484 MAP_OPTION( IPV6_UNICAST_HOPS ),
485 MAP_OPTION( IPV6_V6ONLY ),
486 #ifdef IPV6_UNICAST_IF
487 MAP_OPTION( IPV6_UNICAST_IF ),
488 #endif
491 static const int ws_af_map[][2] =
493 MAP_OPTION( AF_UNSPEC ),
494 MAP_OPTION( AF_INET ),
495 MAP_OPTION( AF_INET6 ),
496 #ifdef HAS_IPX
497 MAP_OPTION( AF_IPX ),
498 #endif
499 #ifdef AF_IRDA
500 MAP_OPTION( AF_IRDA ),
501 #endif
502 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
505 static const int ws_socktype_map[][2] =
507 MAP_OPTION( SOCK_DGRAM ),
508 MAP_OPTION( SOCK_STREAM ),
509 MAP_OPTION( SOCK_RAW ),
510 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
513 static const int ws_proto_map[][2] =
515 MAP_OPTION( IPPROTO_IP ),
516 MAP_OPTION( IPPROTO_TCP ),
517 MAP_OPTION( IPPROTO_UDP ),
518 MAP_OPTION( IPPROTO_ICMP ),
519 MAP_OPTION( IPPROTO_IGMP ),
520 MAP_OPTION( IPPROTO_RAW ),
521 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
524 static const int ws_aiflag_map[][2] =
526 MAP_OPTION( AI_PASSIVE ),
527 MAP_OPTION( AI_CANONNAME ),
528 MAP_OPTION( AI_NUMERICHOST ),
529 #ifdef AI_NUMERICSERV
530 MAP_OPTION( AI_NUMERICSERV ),
531 #endif
532 #ifdef AI_V4MAPPED
533 MAP_OPTION( AI_V4MAPPED ),
534 #endif
535 MAP_OPTION( AI_ADDRCONFIG ),
538 static const int ws_niflag_map[][2] =
540 MAP_OPTION( NI_NOFQDN ),
541 MAP_OPTION( NI_NUMERICHOST ),
542 MAP_OPTION( NI_NAMEREQD ),
543 MAP_OPTION( NI_NUMERICSERV ),
544 MAP_OPTION( NI_DGRAM ),
547 static const int ws_eai_map[][2] =
549 MAP_OPTION( EAI_AGAIN ),
550 MAP_OPTION( EAI_BADFLAGS ),
551 MAP_OPTION( EAI_FAIL ),
552 MAP_OPTION( EAI_FAMILY ),
553 MAP_OPTION( EAI_MEMORY ),
554 /* Note: EAI_NODATA is deprecated, but still
555 * used by Windows and Linux... We map the newer
556 * EAI_NONAME to EAI_NODATA for now until Windows
557 * changes too.
559 #ifdef EAI_NODATA
560 MAP_OPTION( EAI_NODATA ),
561 #endif
562 #ifdef EAI_NONAME
563 { WS_EAI_NODATA, EAI_NONAME },
564 #endif
566 MAP_OPTION( EAI_SERVICE ),
567 MAP_OPTION( EAI_SOCKTYPE ),
568 { 0, 0 }
571 static const char magic_loopback_addr[] = {127, 12, 34, 56};
573 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
574 #ifdef IP_PKTINFO
575 static inline WSACMSGHDR *fill_control_message(int level, int type, WSACMSGHDR *current, ULONG *maxsize, void *data, int len)
577 ULONG msgsize = sizeof(WSACMSGHDR) + WSA_CMSG_ALIGN(len);
578 char *ptr = (char *) current + sizeof(WSACMSGHDR);
580 /* Make sure there is at least enough room for this entry */
581 if (msgsize > *maxsize)
582 return NULL;
583 *maxsize -= msgsize;
584 /* Fill in the entry */
585 current->cmsg_len = sizeof(WSACMSGHDR) + len;
586 current->cmsg_level = level;
587 current->cmsg_type = type;
588 memcpy(ptr, data, len);
589 /* Return the pointer to where next entry should go */
590 return (WSACMSGHDR *) (ptr + WSA_CMSG_ALIGN(len));
592 #endif /* IP_PKTINFO */
594 static inline int convert_control_headers(struct msghdr *hdr, WSABUF *control)
596 #ifdef IP_PKTINFO
597 WSACMSGHDR *cmsg_win = (WSACMSGHDR *) control->buf, *ptr;
598 ULONG ctlsize = control->len;
599 struct cmsghdr *cmsg_unix;
601 ptr = cmsg_win;
602 /* Loop over all the headers, converting as appropriate */
603 for (cmsg_unix = CMSG_FIRSTHDR(hdr); cmsg_unix != NULL; cmsg_unix = CMSG_NXTHDR(hdr, cmsg_unix))
605 switch(cmsg_unix->cmsg_level)
607 case IPPROTO_IP:
608 switch(cmsg_unix->cmsg_type)
610 case IP_PKTINFO:
612 /* Convert the Unix IP_PKTINFO structure to the Windows version */
613 struct in_pktinfo *data_unix = (struct in_pktinfo *) CMSG_DATA(cmsg_unix);
614 struct WS_in_pktinfo data_win;
616 memcpy(&data_win.ipi_addr,&data_unix->ipi_addr.s_addr,4); /* 4 bytes = 32 address bits */
617 data_win.ipi_ifindex = data_unix->ipi_ifindex;
618 ptr = fill_control_message(WS_IPPROTO_IP, WS_IP_PKTINFO, ptr, &ctlsize,
619 (void*)&data_win, sizeof(data_win));
620 if (!ptr) goto error;
621 } break;
622 default:
623 FIXME("Unhandled IPPROTO_IP message header type %d\n", cmsg_unix->cmsg_type);
624 break;
626 break;
627 default:
628 FIXME("Unhandled message header level %d\n", cmsg_unix->cmsg_level);
629 break;
633 error:
634 /* Set the length of the returned control headers */
635 control->len = (ptr == NULL ? 0 : (char*)ptr - (char*)cmsg_win);
636 return (ptr != NULL);
637 #else /* IP_PKTINFO */
638 control->len = 0;
639 return 1;
640 #endif /* IP_PKTINFO */
642 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
644 /* ----------------------------------- error handling */
646 static NTSTATUS sock_get_ntstatus( int err )
648 switch ( err )
650 case EBADF: return STATUS_INVALID_HANDLE;
651 case EBUSY: return STATUS_DEVICE_BUSY;
652 case EPERM:
653 case EACCES: return STATUS_ACCESS_DENIED;
654 case EFAULT: return STATUS_NO_MEMORY;
655 case EINVAL: return STATUS_INVALID_PARAMETER;
656 case ENFILE:
657 case EMFILE: return STATUS_TOO_MANY_OPENED_FILES;
658 case EWOULDBLOCK: return STATUS_CANT_WAIT;
659 case EINPROGRESS: return STATUS_PENDING;
660 case EALREADY: return STATUS_NETWORK_BUSY;
661 case ENOTSOCK: return STATUS_OBJECT_TYPE_MISMATCH;
662 case EDESTADDRREQ: return STATUS_INVALID_PARAMETER;
663 case EMSGSIZE: return STATUS_BUFFER_OVERFLOW;
664 case EPROTONOSUPPORT:
665 case ESOCKTNOSUPPORT:
666 case EPFNOSUPPORT:
667 case EAFNOSUPPORT:
668 case EPROTOTYPE: return STATUS_NOT_SUPPORTED;
669 case ENOPROTOOPT: return STATUS_INVALID_PARAMETER;
670 case EOPNOTSUPP: return STATUS_NOT_SUPPORTED;
671 case EADDRINUSE: return STATUS_ADDRESS_ALREADY_ASSOCIATED;
672 case EADDRNOTAVAIL: return STATUS_INVALID_PARAMETER;
673 case ECONNREFUSED: return STATUS_CONNECTION_REFUSED;
674 case ESHUTDOWN: return STATUS_PIPE_DISCONNECTED;
675 case ENOTCONN: return STATUS_CONNECTION_DISCONNECTED;
676 case ETIMEDOUT: return STATUS_IO_TIMEOUT;
677 case ENETUNREACH: return STATUS_NETWORK_UNREACHABLE;
678 case ENETDOWN: return STATUS_NETWORK_BUSY;
679 case EPIPE:
680 case ECONNRESET: return STATUS_CONNECTION_RESET;
681 case ECONNABORTED: return STATUS_CONNECTION_ABORTED;
683 case 0: return STATUS_SUCCESS;
684 default:
685 WARN("Unknown errno %d!\n", err);
686 return STATUS_UNSUCCESSFUL;
690 static UINT sock_get_error( int err )
692 switch(err)
694 case EINTR: return WSAEINTR;
695 case EBADF: return WSAEBADF;
696 case EPERM:
697 case EACCES: return WSAEACCES;
698 case EFAULT: return WSAEFAULT;
699 case EINVAL: return WSAEINVAL;
700 case EMFILE: return WSAEMFILE;
701 case EWOULDBLOCK: return WSAEWOULDBLOCK;
702 case EINPROGRESS: return WSAEINPROGRESS;
703 case EALREADY: return WSAEALREADY;
704 case ENOTSOCK: return WSAENOTSOCK;
705 case EDESTADDRREQ: return WSAEDESTADDRREQ;
706 case EMSGSIZE: return WSAEMSGSIZE;
707 case EPROTOTYPE: return WSAEPROTOTYPE;
708 case ENOPROTOOPT: return WSAENOPROTOOPT;
709 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
710 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
711 case EOPNOTSUPP: return WSAEOPNOTSUPP;
712 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
713 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
714 case EADDRINUSE: return WSAEADDRINUSE;
715 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
716 case ENETDOWN: return WSAENETDOWN;
717 case ENETUNREACH: return WSAENETUNREACH;
718 case ENETRESET: return WSAENETRESET;
719 case ECONNABORTED: return WSAECONNABORTED;
720 case EPIPE:
721 case ECONNRESET: return WSAECONNRESET;
722 case ENOBUFS: return WSAENOBUFS;
723 case EISCONN: return WSAEISCONN;
724 case ENOTCONN: return WSAENOTCONN;
725 case ESHUTDOWN: return WSAESHUTDOWN;
726 case ETOOMANYREFS: return WSAETOOMANYREFS;
727 case ETIMEDOUT: return WSAETIMEDOUT;
728 case ECONNREFUSED: return WSAECONNREFUSED;
729 case ELOOP: return WSAELOOP;
730 case ENAMETOOLONG: return WSAENAMETOOLONG;
731 case EHOSTDOWN: return WSAEHOSTDOWN;
732 case EHOSTUNREACH: return WSAEHOSTUNREACH;
733 case ENOTEMPTY: return WSAENOTEMPTY;
734 #ifdef EPROCLIM
735 case EPROCLIM: return WSAEPROCLIM;
736 #endif
737 #ifdef EUSERS
738 case EUSERS: return WSAEUSERS;
739 #endif
740 #ifdef EDQUOT
741 case EDQUOT: return WSAEDQUOT;
742 #endif
743 #ifdef ESTALE
744 case ESTALE: return WSAESTALE;
745 #endif
746 #ifdef EREMOTE
747 case EREMOTE: return WSAEREMOTE;
748 #endif
750 /* just in case we ever get here and there are no problems */
751 case 0: return 0;
752 default:
753 WARN("Unknown errno %d!\n", err);
754 return WSAEOPNOTSUPP;
758 static UINT wsaErrno(void)
760 int loc_errno = errno;
761 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
763 return sock_get_error( loc_errno );
766 /* most ws2 overlapped functions return an ntstatus-based error code */
767 static NTSTATUS wsaErrStatus(void)
769 int loc_errno = errno;
770 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
772 return sock_get_ntstatus(loc_errno);
775 static UINT wsaHerrno(int loc_errno)
777 WARN("h_errno %d.\n", loc_errno);
779 switch(loc_errno)
781 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
782 case TRY_AGAIN: return WSATRY_AGAIN;
783 case NO_RECOVERY: return WSANO_RECOVERY;
784 case NO_DATA: return WSANO_DATA;
785 case ENOBUFS: return WSAENOBUFS;
787 case 0: return 0;
788 default:
789 WARN("Unknown h_errno %d!\n", loc_errno);
790 return WSAEOPNOTSUPP;
794 static inline DWORD NtStatusToWSAError( const DWORD status )
796 /* We only need to cover the status codes set by server async request handling */
797 DWORD wserr;
798 switch ( status )
800 case STATUS_SUCCESS: wserr = 0; break;
801 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
802 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
803 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
804 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
805 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
806 case STATUS_NETWORK_BUSY: wserr = WSAEALREADY; break;
807 case STATUS_NETWORK_UNREACHABLE: wserr = WSAENETUNREACH; break;
808 case STATUS_CONNECTION_REFUSED: wserr = WSAECONNREFUSED; break;
809 case STATUS_CONNECTION_DISCONNECTED: wserr = WSAENOTCONN; break;
810 case STATUS_CONNECTION_RESET: wserr = WSAECONNRESET; break;
811 case STATUS_CONNECTION_ABORTED: wserr = WSAECONNABORTED; break;
812 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
813 case STATUS_ADDRESS_ALREADY_ASSOCIATED: wserr = WSAEADDRINUSE; break;
814 case STATUS_IO_TIMEOUT:
815 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
816 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
817 case STATUS_ACCESS_DENIED: wserr = WSAEACCES; break;
818 case STATUS_TOO_MANY_OPENED_FILES: wserr = WSAEMFILE; break;
819 case STATUS_CANT_WAIT: wserr = WSAEWOULDBLOCK; break;
820 case STATUS_BUFFER_OVERFLOW: wserr = WSAEMSGSIZE; break;
821 case STATUS_NOT_SUPPORTED: wserr = WSAEOPNOTSUPP; break;
822 case STATUS_HOST_UNREACHABLE: wserr = WSAEHOSTUNREACH; break;
824 default:
825 wserr = RtlNtStatusToDosError( status );
826 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
828 return wserr;
831 /* set last error code from NT status without mapping WSA errors */
832 static inline unsigned int set_error( unsigned int err )
834 if (err)
836 err = NtStatusToWSAError( err );
837 SetLastError( err );
839 return err;
842 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
844 int fd;
845 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
846 return -1;
847 return fd;
850 static inline void release_sock_fd( SOCKET s, int fd )
852 wine_server_release_fd( SOCKET2HANDLE(s), fd );
855 static void _enable_event( HANDLE s, unsigned int event,
856 unsigned int sstate, unsigned int cstate )
858 SERVER_START_REQ( enable_socket_event )
860 req->handle = wine_server_obj_handle( s );
861 req->mask = event;
862 req->sstate = sstate;
863 req->cstate = cstate;
864 wine_server_call( req );
866 SERVER_END_REQ;
869 static NTSTATUS _is_blocking(SOCKET s, BOOL *ret)
871 NTSTATUS status;
872 SERVER_START_REQ( get_socket_event )
874 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
875 req->service = FALSE;
876 req->c_event = 0;
877 status = wine_server_call( req );
878 *ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
880 SERVER_END_REQ;
881 return status;
884 static unsigned int _get_sock_mask(SOCKET s)
886 unsigned int ret;
887 SERVER_START_REQ( get_socket_event )
889 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
890 req->service = FALSE;
891 req->c_event = 0;
892 wine_server_call( req );
893 ret = reply->mask;
895 SERVER_END_REQ;
896 return ret;
899 static void _sync_sock_state(SOCKET s)
901 BOOL dummy;
902 /* do a dummy wineserver request in order to let
903 the wineserver run through its select loop once */
904 (void)_is_blocking(s, &dummy);
907 static int _get_sock_error(SOCKET s, unsigned int bit)
909 int events[FD_MAX_EVENTS];
911 SERVER_START_REQ( get_socket_event )
913 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
914 req->service = FALSE;
915 req->c_event = 0;
916 wine_server_set_reply( req, events, sizeof(events) );
917 wine_server_call( req );
919 SERVER_END_REQ;
920 return events[bit];
923 static struct per_thread_data *get_per_thread_data(void)
925 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
926 /* lazy initialization */
927 if (!ptb)
929 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
930 NtCurrentTeb()->WinSockData = ptb;
932 return ptb;
935 static void free_per_thread_data(void)
937 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
939 if (!ptb) return;
941 /* delete scratch buffers */
942 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
943 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
944 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
945 ptb->he_buffer = NULL;
946 ptb->se_buffer = NULL;
947 ptb->pe_buffer = NULL;
949 HeapFree( GetProcessHeap(), 0, ptb );
950 NtCurrentTeb()->WinSockData = NULL;
953 /***********************************************************************
954 * DllMain (WS2_32.init)
956 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
958 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
959 switch (fdwReason) {
960 case DLL_PROCESS_ATTACH:
961 break;
962 case DLL_PROCESS_DETACH:
963 if (fImpLoad) break;
964 free_per_thread_data();
965 DeleteCriticalSection(&csWSgetXXXbyYYY);
966 break;
967 case DLL_THREAD_DETACH:
968 free_per_thread_data();
969 break;
971 return TRUE;
974 /***********************************************************************
975 * convert_sockopt()
977 * Converts socket flags from Windows format.
978 * Return 1 if converted, 0 if not (error).
980 static int convert_sockopt(INT *level, INT *optname)
982 unsigned int i;
983 switch (*level)
985 case WS_SOL_SOCKET:
986 *level = SOL_SOCKET;
987 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
988 if( ws_sock_map[i][0] == *optname )
990 *optname = ws_sock_map[i][1];
991 return 1;
994 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
995 break;
996 case WS_IPPROTO_TCP:
997 *level = IPPROTO_TCP;
998 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
999 if ( ws_tcp_map[i][0] == *optname )
1001 *optname = ws_tcp_map[i][1];
1002 return 1;
1005 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
1006 break;
1007 case WS_IPPROTO_IP:
1008 *level = IPPROTO_IP;
1009 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
1010 if (ws_ip_map[i][0] == *optname )
1012 *optname = ws_ip_map[i][1];
1013 return 1;
1016 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
1017 break;
1018 case WS_IPPROTO_IPV6:
1019 *level = IPPROTO_IPV6;
1020 for(i=0; i<sizeof(ws_ipv6_map)/sizeof(ws_ipv6_map[0]); i++) {
1021 if (ws_ipv6_map[i][0] == *optname )
1023 *optname = ws_ipv6_map[i][1];
1024 return 1;
1027 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname);
1028 break;
1029 default: FIXME("Unimplemented or unknown socket level\n");
1031 return 0;
1034 /* ----------------------------------- Per-thread info (or per-process?) */
1036 static char *strdup_lower(const char *str)
1038 int i;
1039 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
1041 if (ret)
1043 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
1044 ret[i] = 0;
1046 else SetLastError(WSAENOBUFS);
1047 return ret;
1050 static inline int sock_error_p(int s)
1052 unsigned int optval;
1053 socklen_t optlen = sizeof(optval);
1054 getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
1055 if (optval) WARN("\t[%i] error: %d\n", s, optval);
1056 return optval != 0;
1059 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
1060 * from an fd and return the value converted to milli seconds
1061 * or -1 if there is an infinite time out */
1062 static inline int get_rcvsnd_timeo( int fd, int optname)
1064 struct timeval tv;
1065 socklen_t len = sizeof(tv);
1066 int ret = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
1067 if( ret >= 0)
1068 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
1069 if( ret <= 0 ) /* tv == {0,0} means infinite time out */
1070 return -1;
1071 return ret;
1074 /* macro wrappers for portability */
1075 #ifdef SO_RCVTIMEO
1076 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
1077 #else
1078 #define GET_RCVTIMEO(fd) (-1)
1079 #endif
1081 #ifdef SO_SNDTIMEO
1082 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
1083 #else
1084 #define GET_SNDTIMEO(fd) (-1)
1085 #endif
1087 /* utility: given an fd, will block until one of the events occurs */
1088 static inline int do_block( int fd, int events, int timeout )
1090 struct pollfd pfd;
1091 int ret;
1093 pfd.fd = fd;
1094 pfd.events = events;
1096 while ((ret = poll(&pfd, 1, timeout)) < 0)
1098 if (errno != EINTR)
1099 return -1;
1101 if( ret == 0 )
1102 return 0;
1103 return pfd.revents;
1106 static int
1107 convert_af_w2u(int windowsaf) {
1108 unsigned int i;
1110 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1111 if (ws_af_map[i][0] == windowsaf)
1112 return ws_af_map[i][1];
1113 FIXME("unhandled Windows address family %d\n", windowsaf);
1114 return -1;
1117 static int
1118 convert_af_u2w(int unixaf) {
1119 unsigned int i;
1121 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1122 if (ws_af_map[i][1] == unixaf)
1123 return ws_af_map[i][0];
1124 FIXME("unhandled UNIX address family %d\n", unixaf);
1125 return -1;
1128 static int
1129 convert_proto_w2u(int windowsproto) {
1130 unsigned int i;
1132 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1133 if (ws_proto_map[i][0] == windowsproto)
1134 return ws_proto_map[i][1];
1136 /* check for extended IPX */
1137 if (IS_IPX_PROTO(windowsproto))
1138 return windowsproto;
1140 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
1141 return -1;
1144 static int
1145 convert_proto_u2w(int unixproto) {
1146 unsigned int i;
1148 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1149 if (ws_proto_map[i][1] == unixproto)
1150 return ws_proto_map[i][0];
1152 /* if value is inside IPX range just return it - the kernel simply
1153 * echoes the value used in the socket() function */
1154 if (IS_IPX_PROTO(unixproto))
1155 return unixproto;
1157 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
1158 return -1;
1161 static int
1162 convert_socktype_w2u(int windowssocktype) {
1163 unsigned int i;
1165 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1166 if (ws_socktype_map[i][0] == windowssocktype)
1167 return ws_socktype_map[i][1];
1168 FIXME("unhandled Windows socket type %d\n", windowssocktype);
1169 return -1;
1172 static int
1173 convert_socktype_u2w(int unixsocktype) {
1174 unsigned int i;
1176 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1177 if (ws_socktype_map[i][1] == unixsocktype)
1178 return ws_socktype_map[i][0];
1179 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
1180 return -1;
1183 static int set_ipx_packettype(int sock, int ptype)
1185 #ifdef HAS_IPX
1186 int fd = get_sock_fd( sock, 0, NULL ), ret = 0;
1187 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", ptype, fd);
1189 if (fd == -1) return SOCKET_ERROR;
1191 /* We try to set the ipx type on ipx socket level. */
1192 #ifdef SOL_IPX
1193 if(setsockopt(fd, SOL_IPX, IPX_TYPE, &ptype, sizeof(ptype)) == -1)
1195 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
1196 ret = SOCKET_ERROR;
1198 #else
1200 struct ipx val;
1201 /* Should we retrieve val using a getsockopt call and then
1202 * set the modified one? */
1203 val.ipx_pt = ptype;
1204 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
1206 #endif
1207 release_sock_fd( sock, fd );
1208 return ret;
1209 #else
1210 WARN("IPX support is not enabled, can't set packet type\n");
1211 return SOCKET_ERROR;
1212 #endif
1215 /* ----------------------------------- API -----
1217 * Init / cleanup / error checking.
1220 /***********************************************************************
1221 * WSAStartup (WS2_32.115)
1223 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
1225 TRACE("verReq=%x\n", wVersionRequested);
1227 if (LOBYTE(wVersionRequested) < 1)
1228 return WSAVERNOTSUPPORTED;
1230 if (!lpWSAData) return WSAEINVAL;
1232 num_startup++;
1234 /* that's the whole of the negotiation for now */
1235 lpWSAData->wVersion = wVersionRequested;
1236 /* return winsock information */
1237 lpWSAData->wHighVersion = 0x0202;
1238 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
1239 strcpy(lpWSAData->szSystemStatus, "Running" );
1240 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
1241 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
1242 /* don't do anything with lpWSAData->lpVendorInfo */
1243 /* (some apps don't allocate the space for this field) */
1245 TRACE("succeeded starts: %d\n", num_startup);
1246 return 0;
1250 /***********************************************************************
1251 * WSACleanup (WS2_32.116)
1253 INT WINAPI WSACleanup(void)
1255 if (num_startup) {
1256 num_startup--;
1257 TRACE("pending cleanups: %d\n", num_startup);
1258 return 0;
1260 SetLastError(WSANOTINITIALISED);
1261 return SOCKET_ERROR;
1265 /***********************************************************************
1266 * WSAGetLastError (WS2_32.111)
1268 INT WINAPI WSAGetLastError(void)
1270 return GetLastError();
1273 /***********************************************************************
1274 * WSASetLastError (WS2_32.112)
1276 void WINAPI WSASetLastError(INT iError) {
1277 SetLastError(iError);
1280 static struct WS_hostent *check_buffer_he(int size)
1282 struct per_thread_data * ptb = get_per_thread_data();
1283 if (ptb->he_buffer)
1285 if (ptb->he_len >= size ) return ptb->he_buffer;
1286 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1288 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
1289 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
1290 return ptb->he_buffer;
1293 static struct WS_servent *check_buffer_se(int size)
1295 struct per_thread_data * ptb = get_per_thread_data();
1296 if (ptb->se_buffer)
1298 if (ptb->se_len >= size ) return ptb->se_buffer;
1299 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1301 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
1302 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
1303 return ptb->se_buffer;
1306 static struct WS_protoent *check_buffer_pe(int size)
1308 struct per_thread_data * ptb = get_per_thread_data();
1309 if (ptb->pe_buffer)
1311 if (ptb->pe_len >= size ) return ptb->pe_buffer;
1312 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1314 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
1315 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
1316 return ptb->pe_buffer;
1319 /* ----------------------------------- i/o APIs */
1321 static inline BOOL supported_pf(int pf)
1323 switch (pf)
1325 case WS_AF_INET:
1326 case WS_AF_INET6:
1327 return TRUE;
1328 #ifdef HAS_IPX
1329 case WS_AF_IPX:
1330 return TRUE;
1331 #endif
1332 #ifdef HAS_IRDA
1333 case WS_AF_IRDA:
1334 return TRUE;
1335 #endif
1336 default:
1337 return FALSE;
1341 static inline BOOL supported_protocol(int protocol)
1343 int i;
1344 for (i = 0; i < sizeof(valid_protocols) / sizeof(valid_protocols[0]); i++)
1345 if (protocol == valid_protocols[i])
1346 return TRUE;
1347 return FALSE;
1350 /**********************************************************************/
1352 /* Returns the length of the converted address if successful, 0 if it was too small to
1353 * start with.
1355 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
1356 union generic_unix_sockaddr *uaddr)
1358 unsigned int uaddrlen = 0;
1360 switch (wsaddr->sa_family)
1362 #ifdef HAS_IPX
1363 case WS_AF_IPX:
1365 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
1366 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
1368 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
1369 return 0;
1371 uaddrlen = sizeof(struct sockaddr_ipx);
1372 memset( uaddr, 0, uaddrlen );
1373 uipx->sipx_family=AF_IPX;
1374 uipx->sipx_port=wsipx->sa_socket;
1375 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1376 * in one go
1378 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
1379 #ifdef IPX_FRAME_NONE
1380 uipx->sipx_type=IPX_FRAME_NONE;
1381 #endif
1382 break;
1384 #endif
1385 case WS_AF_INET6: {
1386 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
1387 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
1389 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1390 * scope_id, one without.
1392 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
1393 uaddrlen = sizeof(struct sockaddr_in6);
1394 memset( uaddr, 0, uaddrlen );
1395 uin6->sin6_family = AF_INET6;
1396 uin6->sin6_port = win6->sin6_port;
1397 uin6->sin6_flowinfo = win6->sin6_flowinfo;
1398 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1399 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
1400 #endif
1401 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
1402 break;
1404 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
1405 return 0;
1407 case WS_AF_INET: {
1408 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
1409 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
1411 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
1412 return 0;
1413 uaddrlen = sizeof(struct sockaddr_in);
1414 memset( uaddr, 0, uaddrlen );
1415 uin->sin_family = AF_INET;
1416 uin->sin_port = win->sin_port;
1417 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
1418 break;
1420 #ifdef HAS_IRDA
1421 case WS_AF_IRDA: {
1422 struct sockaddr_irda *uin = (struct sockaddr_irda *)uaddr;
1423 const SOCKADDR_IRDA *win = (const SOCKADDR_IRDA *)wsaddr;
1425 if (wsaddrlen < sizeof(SOCKADDR_IRDA))
1426 return 0;
1427 uaddrlen = sizeof(struct sockaddr_irda);
1428 memset( uaddr, 0, uaddrlen );
1429 uin->sir_family = AF_IRDA;
1430 if (!strncmp( win->irdaServiceName, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1432 unsigned int lsap_sel = 0;
1434 sscanf( win->irdaServiceName, "LSAP-SEL%u", &lsap_sel );
1435 uin->sir_lsap_sel = lsap_sel;
1437 else
1439 uin->sir_lsap_sel = LSAP_ANY;
1440 memcpy( uin->sir_name, win->irdaServiceName, 25 );
1442 memcpy( &uin->sir_addr, win->irdaDeviceID, sizeof(uin->sir_addr) );
1443 break;
1445 #endif
1446 case WS_AF_UNSPEC: {
1447 /* Try to determine the needed space by the passed windows sockaddr space */
1448 switch (wsaddrlen) {
1449 default: /* likely an ipv4 address */
1450 case sizeof(struct WS_sockaddr_in):
1451 uaddrlen = sizeof(struct sockaddr_in);
1452 break;
1453 #ifdef HAS_IPX
1454 case sizeof(struct WS_sockaddr_ipx):
1455 uaddrlen = sizeof(struct sockaddr_ipx);
1456 break;
1457 #endif
1458 #ifdef HAS_IRDA
1459 case sizeof(SOCKADDR_IRDA):
1460 uaddrlen = sizeof(struct sockaddr_irda);
1461 break;
1462 #endif
1463 case sizeof(struct WS_sockaddr_in6):
1464 case sizeof(struct WS_sockaddr_in6_old):
1465 uaddrlen = sizeof(struct sockaddr_in6);
1466 break;
1468 memset( uaddr, 0, uaddrlen );
1469 break;
1471 default:
1472 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
1473 return 0;
1475 return uaddrlen;
1478 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
1480 switch (uaddr->sa_family)
1482 #ifdef HAS_IPX
1483 case AF_IPX:
1485 static const struct sockaddr_ipx emptyAddr;
1486 struct sockaddr_ipx *ipx = (struct sockaddr_ipx*) uaddr;
1487 return ipx->sipx_port
1488 || memcmp(&ipx->sipx_network, &emptyAddr.sipx_network, sizeof(emptyAddr.sipx_network))
1489 || memcmp(&ipx->sipx_node, &emptyAddr.sipx_node, sizeof(emptyAddr.sipx_node));
1491 #endif
1492 case AF_INET6:
1494 static const struct sockaddr_in6 emptyAddr;
1495 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
1496 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
1498 case AF_INET:
1500 static const struct sockaddr_in emptyAddr;
1501 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
1502 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
1504 case AF_UNSPEC:
1505 return FALSE;
1506 default:
1507 FIXME("unknown address family %d\n", uaddr->sa_family);
1508 return TRUE;
1512 /* Returns 0 if successful, -1 if the buffer is too small */
1513 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
1515 int res;
1517 switch(uaddr->sa_family)
1519 #ifdef HAS_IPX
1520 case AF_IPX:
1522 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
1523 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
1525 res=-1;
1526 switch (*wsaddrlen) /* how much can we copy? */
1528 default:
1529 res=0; /* enough */
1530 *wsaddrlen = sizeof(*wsipx);
1531 wsipx->sa_socket=uipx->sipx_port;
1532 /* fall through */
1533 case 13:
1534 case 12:
1535 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
1536 /* fall through */
1537 case 11:
1538 case 10:
1539 case 9:
1540 case 8:
1541 case 7:
1542 case 6:
1543 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1544 /* fall through */
1545 case 5:
1546 case 4:
1547 case 3:
1548 case 2:
1549 wsipx->sa_family=WS_AF_IPX;
1550 /* fall through */
1551 case 1:
1552 case 0:
1553 /* way too small */
1554 break;
1557 break;
1558 #endif
1559 #ifdef HAS_IRDA
1560 case AF_IRDA: {
1561 const struct sockaddr_irda *uin = (const struct sockaddr_irda *)uaddr;
1562 SOCKADDR_IRDA *win = (SOCKADDR_IRDA *)wsaddr;
1564 if (*wsaddrlen < sizeof(SOCKADDR_IRDA))
1565 return -1;
1566 win->irdaAddressFamily = WS_AF_IRDA;
1567 memcpy( win->irdaDeviceID, &uin->sir_addr, sizeof(win->irdaDeviceID) );
1568 if (uin->sir_lsap_sel != LSAP_ANY)
1569 sprintf( win->irdaServiceName, "LSAP-SEL%u", uin->sir_lsap_sel );
1570 else
1571 memcpy( win->irdaServiceName, uin->sir_name,
1572 sizeof(win->irdaServiceName) );
1573 return 0;
1575 #endif
1576 case AF_INET6: {
1577 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1578 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1580 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1581 return -1;
1582 win6old->sin6_family = WS_AF_INET6;
1583 win6old->sin6_port = uin6->sin6_port;
1584 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1585 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1586 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1587 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1588 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1589 win6->sin6_scope_id = uin6->sin6_scope_id;
1590 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1592 else
1593 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1594 #else
1595 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1596 #endif
1597 return 0;
1599 case AF_INET: {
1600 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1601 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1603 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1604 return -1;
1605 win->sin_family = WS_AF_INET;
1606 win->sin_port = uin->sin_port;
1607 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1608 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1609 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1610 return 0;
1612 case AF_UNSPEC: {
1613 memset(wsaddr,0,*wsaddrlen);
1614 return 0;
1616 default:
1617 FIXME("Unknown address family %d\n", uaddr->sa_family);
1618 return -1;
1620 return res;
1623 static INT WS_DuplicateSocket(BOOL unicode, SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo)
1625 HANDLE hProcess;
1626 int size;
1627 WSAPROTOCOL_INFOW infow;
1629 TRACE("(unicode %d, socket %04lx, processid %x, buffer %p)\n",
1630 unicode, s, dwProcessId, lpProtocolInfo);
1632 if (!ws_protocol_info(s, unicode, &infow, &size))
1633 return SOCKET_ERROR;
1635 if (!(hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId)))
1637 SetLastError(WSAEINVAL);
1638 return SOCKET_ERROR;
1641 if (!lpProtocolInfo)
1643 CloseHandle(hProcess);
1644 SetLastError(WSAEFAULT);
1645 return SOCKET_ERROR;
1648 /* I don't know what the real Windoze does next, this is a hack */
1649 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
1650 * the target use the global duplicate, or we could copy a reference to us to the structure
1651 * and let the target duplicate it from us, but let's do it as simple as possible */
1652 memcpy(lpProtocolInfo, &infow, size);
1653 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
1654 hProcess, (LPHANDLE)&lpProtocolInfo->dwServiceFlags3,
1655 0, FALSE, DUPLICATE_SAME_ACCESS);
1656 CloseHandle(hProcess);
1657 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
1658 return 0;
1661 /*****************************************************************************
1662 * WS_EnterSingleProtocolW [internal]
1664 * enters the protocol information of one given protocol into the given
1665 * buffer.
1667 * RETURNS
1668 * TRUE if a protocol was entered into the buffer.
1670 * BUGS
1671 * - only implemented for IPX, SPX, SPXII, TCP, UDP
1672 * - there is no check that the operating system supports the returned
1673 * protocols
1675 static BOOL WS_EnterSingleProtocolW( INT protocol, WSAPROTOCOL_INFOW* info )
1677 memset( info, 0, sizeof(WSAPROTOCOL_INFOW) );
1678 info->iProtocol = protocol;
1680 switch (protocol)
1682 case WS_IPPROTO_TCP:
1683 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_EXPEDITED_DATA |
1684 XP1_GRACEFUL_CLOSE | XP1_GUARANTEED_ORDER |
1685 XP1_GUARANTEED_DELIVERY;
1686 info->ProviderId = ProviderIdIP;
1687 info->dwCatalogEntryId = 0x3e9;
1688 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1689 info->ProtocolChain.ChainLen = 1;
1690 info->iVersion = 2;
1691 info->iAddressFamily = WS_AF_INET;
1692 info->iMaxSockAddr = 0x10;
1693 info->iMinSockAddr = 0x10;
1694 info->iSocketType = WS_SOCK_STREAM;
1695 strcpyW( info->szProtocol, NameTcpW );
1696 break;
1698 case WS_IPPROTO_UDP:
1699 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_SUPPORT_BROADCAST |
1700 XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED |
1701 XP1_CONNECTIONLESS;
1702 info->ProviderId = ProviderIdIP;
1703 info->dwCatalogEntryId = 0x3ea;
1704 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1705 info->ProtocolChain.ChainLen = 1;
1706 info->iVersion = 2;
1707 info->iAddressFamily = WS_AF_INET;
1708 info->iMaxSockAddr = 0x10;
1709 info->iMinSockAddr = 0x10;
1710 info->iSocketType = WS_SOCK_DGRAM;
1711 info->dwMessageSize = 0xffbb;
1712 strcpyW( info->szProtocol, NameUdpW );
1713 break;
1715 case WS_NSPROTO_IPX:
1716 info->dwServiceFlags1 = XP1_PARTIAL_MESSAGE | XP1_SUPPORT_BROADCAST |
1717 XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED |
1718 XP1_CONNECTIONLESS;
1719 info->ProviderId = ProviderIdIPX;
1720 info->dwCatalogEntryId = 0x406;
1721 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1722 info->ProtocolChain.ChainLen = 1;
1723 info->iVersion = 2;
1724 info->iAddressFamily = WS_AF_IPX;
1725 info->iMaxSockAddr = 0x10;
1726 info->iMinSockAddr = 0x0e;
1727 info->iSocketType = WS_SOCK_DGRAM;
1728 info->iProtocolMaxOffset = 0xff;
1729 info->dwMessageSize = 0x240;
1730 strcpyW( info->szProtocol, NameIpxW );
1731 break;
1733 case WS_NSPROTO_SPX:
1734 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_PSEUDO_STREAM |
1735 XP1_MESSAGE_ORIENTED | XP1_GUARANTEED_ORDER |
1736 XP1_GUARANTEED_DELIVERY;
1737 info->ProviderId = ProviderIdSPX;
1738 info->dwCatalogEntryId = 0x407;
1739 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1740 info->ProtocolChain.ChainLen = 1;
1741 info->iVersion = 2;
1742 info->iAddressFamily = WS_AF_IPX;
1743 info->iMaxSockAddr = 0x10;
1744 info->iMinSockAddr = 0x0e;
1745 info->iSocketType = WS_SOCK_SEQPACKET;
1746 info->dwMessageSize = 0xffffffff;
1747 strcpyW( info->szProtocol, NameSpxW );
1748 break;
1750 case WS_NSPROTO_SPXII:
1751 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_GRACEFUL_CLOSE |
1752 XP1_PSEUDO_STREAM | XP1_MESSAGE_ORIENTED |
1753 XP1_GUARANTEED_ORDER | XP1_GUARANTEED_DELIVERY;
1754 info->ProviderId = ProviderIdSPX;
1755 info->dwCatalogEntryId = 0x409;
1756 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1757 info->ProtocolChain.ChainLen = 1;
1758 info->iVersion = 2;
1759 info->iAddressFamily = WS_AF_IPX;
1760 info->iMaxSockAddr = 0x10;
1761 info->iMinSockAddr = 0x0e;
1762 info->iSocketType = WS_SOCK_SEQPACKET;
1763 info->dwMessageSize = 0xffffffff;
1764 strcpyW( info->szProtocol, NameSpxIIW );
1765 break;
1767 default:
1768 FIXME("unknown Protocol <0x%08x>\n", protocol);
1769 return FALSE;
1771 return TRUE;
1774 /*****************************************************************************
1775 * WS_EnterSingleProtocolA [internal]
1777 * see function WS_EnterSingleProtocolW
1780 static BOOL WS_EnterSingleProtocolA( INT protocol, WSAPROTOCOL_INFOA* info )
1782 WSAPROTOCOL_INFOW infow;
1783 INT ret;
1784 memset( info, 0, sizeof(WSAPROTOCOL_INFOA) );
1786 ret = WS_EnterSingleProtocolW( protocol, &infow );
1787 if (ret)
1789 /* convert the structure from W to A */
1790 memcpy( info, &infow, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
1791 WideCharToMultiByte( CP_ACP, 0, infow.szProtocol, -1,
1792 info->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL );
1795 return ret;
1798 static INT WS_EnumProtocols( BOOL unicode, const INT *protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
1800 INT i = 0, items = 0;
1801 DWORD size = 0;
1802 union _info
1804 LPWSAPROTOCOL_INFOA a;
1805 LPWSAPROTOCOL_INFOW w;
1806 } info;
1807 info.w = buffer;
1809 if (!protocols) protocols = valid_protocols;
1811 while (protocols[i])
1813 if(supported_protocol(protocols[i++]))
1814 items++;
1817 size = items * (unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA));
1819 TRACE("unicode %d, protocols %p, buffer %p, length %p %d, items %d, required %d\n",
1820 unicode, protocols, buffer, len, len ? *len : 0, items, size);
1822 if (*len < size || !buffer)
1824 *len = size;
1825 SetLastError(WSAENOBUFS);
1826 return SOCKET_ERROR;
1829 for (i = items = 0; protocols[i]; i++)
1831 if (!supported_protocol(protocols[i])) continue;
1832 if (unicode)
1834 if (WS_EnterSingleProtocolW( protocols[i], &info.w[items] ))
1835 items++;
1837 else
1839 if (WS_EnterSingleProtocolA( protocols[i], &info.a[items] ))
1840 items++;
1843 return items;
1846 static BOOL ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size)
1848 NTSTATUS status;
1850 *size = unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA);
1851 memset(buffer, 0, *size);
1853 SERVER_START_REQ( get_socket_info )
1855 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1856 status = wine_server_call( req );
1857 if (!status)
1859 buffer->iAddressFamily = convert_af_u2w(reply->family);
1860 buffer->iSocketType = convert_socktype_u2w(reply->type);
1861 buffer->iProtocol = convert_proto_u2w(reply->protocol);
1864 SERVER_END_REQ;
1866 if (status)
1868 unsigned int err = NtStatusToWSAError( status );
1869 SetLastError( err == WSAEBADF ? WSAENOTSOCK : err );
1870 return FALSE;
1873 if (unicode)
1874 WS_EnterSingleProtocolW( buffer->iProtocol, buffer);
1875 else
1876 WS_EnterSingleProtocolA( buffer->iProtocol, (WSAPROTOCOL_INFOA *)buffer);
1878 return TRUE;
1881 /**************************************************************************
1882 * Functions for handling overlapped I/O
1883 **************************************************************************/
1885 /* user APC called upon async completion */
1886 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1888 ws2_async *wsa = arg;
1890 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
1891 iosb->Information, wsa->user_overlapped,
1892 wsa->flags );
1893 HeapFree( GetProcessHeap(), 0, wsa );
1896 /***********************************************************************
1897 * WS2_recv (INTERNAL)
1899 * Workhorse for both synchronous and asynchronous recv() operations.
1901 static int WS2_recv( int fd, struct ws2_async *wsa )
1903 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1904 char pktbuf[512];
1905 #endif
1906 struct msghdr hdr;
1907 union generic_unix_sockaddr unix_sockaddr;
1908 int n;
1910 hdr.msg_name = NULL;
1912 if (wsa->addr)
1914 hdr.msg_namelen = sizeof(unix_sockaddr);
1915 hdr.msg_name = &unix_sockaddr;
1917 else
1918 hdr.msg_namelen = 0;
1920 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1921 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1922 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1923 hdr.msg_accrights = NULL;
1924 hdr.msg_accrightslen = 0;
1925 #else
1926 hdr.msg_control = pktbuf;
1927 hdr.msg_controllen = sizeof(pktbuf);
1928 hdr.msg_flags = 0;
1929 #endif
1931 while ((n = recvmsg(fd, &hdr, wsa->flags)) == -1)
1933 if (errno != EINTR)
1934 return -1;
1937 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1938 if (wsa->control)
1940 ERR("Message control headers cannot be properly supported on this system.\n");
1941 wsa->control->len = 0;
1943 #else
1944 if (wsa->control && !convert_control_headers(&hdr, wsa->control))
1946 WARN("Application passed insufficient room for control headers.\n");
1947 *wsa->lpFlags |= WS_MSG_CTRUNC;
1948 errno = EMSGSIZE;
1949 return -1;
1951 #endif
1953 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
1954 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
1956 * quoting linux 2.6 net/ipv4/tcp.c:
1957 * "According to UNIX98, msg_name/msg_namelen are ignored
1958 * on connected socket. I was just happy when found this 8) --ANK"
1960 * likewise MSDN says that lpFrom and lpFromlen are ignored for
1961 * connection-oriented sockets, so don't try to update lpFrom.
1963 if (wsa->addr && hdr.msg_namelen)
1964 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
1966 return n;
1969 /***********************************************************************
1970 * WS2_async_recv (INTERNAL)
1972 * Handler for overlapped recv() operations.
1974 static NTSTATUS WS2_async_recv( void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1976 ws2_async* wsa = user;
1977 int result = 0, fd;
1979 switch (status)
1981 case STATUS_ALERTED:
1982 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
1983 break;
1985 result = WS2_recv( fd, wsa );
1986 wine_server_release_fd( wsa->hSocket, fd );
1987 if (result >= 0)
1989 status = STATUS_SUCCESS;
1990 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1992 else
1994 if (errno == EAGAIN)
1996 status = STATUS_PENDING;
1997 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1999 else
2001 result = 0;
2002 status = wsaErrStatus();
2005 break;
2007 if (status != STATUS_PENDING)
2009 iosb->u.Status = status;
2010 iosb->Information = result;
2011 *apc = ws2_async_apc;
2013 return status;
2016 /* user APC called upon async accept completion */
2017 static void WINAPI ws2_async_accept_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
2019 struct ws2_accept_async *wsa = arg;
2021 HeapFree( GetProcessHeap(), 0, wsa->read );
2022 HeapFree( GetProcessHeap(), 0, wsa );
2025 /***********************************************************************
2026 * WS2_async_accept_recv (INTERNAL)
2028 * This function is used to finish the read part of an accept request. It is
2029 * needed to place the completion on the correct socket (listener).
2031 static NTSTATUS WS2_async_accept_recv( void *arg, IO_STATUS_BLOCK *iosb, NTSTATUS status, void **apc )
2033 void *junk;
2034 struct ws2_accept_async *wsa = arg;
2036 status = WS2_async_recv( wsa->read, iosb, status, &junk );
2037 if (status == STATUS_PENDING)
2038 return status;
2040 if (wsa->user_overlapped->hEvent)
2041 SetEvent(wsa->user_overlapped->hEvent);
2042 if (wsa->cvalue)
2043 WS_AddCompletion( HANDLE2SOCKET(wsa->listen_socket), wsa->cvalue, iosb->u.Status, iosb->Information );
2045 *apc = ws2_async_accept_apc;
2046 return status;
2049 /***********************************************************************
2050 * WS2_async_accept (INTERNAL)
2052 * This is the function called to satisfy the AcceptEx callback
2054 static NTSTATUS WS2_async_accept( void *arg, IO_STATUS_BLOCK *iosb, NTSTATUS status, void **apc )
2056 struct ws2_accept_async *wsa = arg;
2057 int len;
2058 char *addr;
2060 TRACE("status: 0x%x listen: %p, accept: %p\n", status, wsa->listen_socket, wsa->accept_socket);
2062 if (status == STATUS_ALERTED)
2064 SERVER_START_REQ( accept_into_socket )
2066 req->lhandle = wine_server_obj_handle( wsa->listen_socket );
2067 req->ahandle = wine_server_obj_handle( wsa->accept_socket );
2068 status = wine_server_call( req );
2070 SERVER_END_REQ;
2072 if (status == STATUS_CANT_WAIT)
2073 return STATUS_PENDING;
2075 if (status == STATUS_INVALID_HANDLE)
2077 FIXME("AcceptEx accepting socket closed but request was not cancelled\n");
2078 status = STATUS_CANCELLED;
2081 else if (status == STATUS_HANDLES_CLOSED)
2082 status = STATUS_CANCELLED; /* strange windows behavior */
2084 if (status != STATUS_SUCCESS)
2085 goto finish;
2087 /* WS2 Spec says size param is extra 16 bytes long...what do we put in it? */
2088 addr = ((char *)wsa->buf) + wsa->data_len;
2089 len = wsa->local_len - sizeof(int);
2090 WS_getsockname(HANDLE2SOCKET(wsa->accept_socket),
2091 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
2092 *(int *)addr = len;
2094 addr += wsa->local_len;
2095 len = wsa->remote_len - sizeof(int);
2096 WS_getpeername(HANDLE2SOCKET(wsa->accept_socket),
2097 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
2098 *(int *)addr = len;
2100 if (!wsa->read)
2101 goto finish;
2103 SERVER_START_REQ( register_async )
2105 req->type = ASYNC_TYPE_READ;
2106 req->async.handle = wine_server_obj_handle( wsa->accept_socket );
2107 req->async.callback = wine_server_client_ptr( WS2_async_accept_recv );
2108 req->async.iosb = wine_server_client_ptr( iosb );
2109 req->async.arg = wine_server_client_ptr( wsa );
2110 status = wine_server_call( req );
2112 SERVER_END_REQ;
2114 if (status != STATUS_PENDING)
2115 goto finish;
2117 /* The APC has finished but no completion should be sent for the operation yet, additional processing
2118 * needs to be performed by WS2_async_accept_recv() first. */
2119 return STATUS_MORE_PROCESSING_REQUIRED;
2121 finish:
2122 iosb->u.Status = status;
2123 iosb->Information = 0;
2125 if (wsa->user_overlapped->hEvent)
2126 SetEvent(wsa->user_overlapped->hEvent);
2128 *apc = ws2_async_accept_apc;
2129 return status;
2132 /***********************************************************************
2133 * WS2_send (INTERNAL)
2135 * Workhorse for both synchronous and asynchronous send() operations.
2137 static int WS2_send( int fd, struct ws2_async *wsa )
2139 struct msghdr hdr;
2140 union generic_unix_sockaddr unix_addr;
2141 int n, ret;
2143 hdr.msg_name = NULL;
2144 hdr.msg_namelen = 0;
2146 if (wsa->addr)
2148 hdr.msg_name = &unix_addr;
2149 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
2150 if ( !hdr.msg_namelen )
2152 errno = EFAULT;
2153 return -1;
2156 #if defined(HAS_IPX) && defined(SOL_IPX)
2157 if(wsa->addr->sa_family == WS_AF_IPX)
2159 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
2160 int val=0;
2161 socklen_t len = sizeof(int);
2163 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
2164 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
2165 * the packet type and then we can retrieve it using getsockopt. After that we can set the
2166 * ipx type in the sockaddr_opx structure with the stored value.
2168 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
2169 uipx->sipx_type = val;
2171 #endif
2174 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
2175 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
2176 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2177 hdr.msg_accrights = NULL;
2178 hdr.msg_accrightslen = 0;
2179 #else
2180 hdr.msg_control = NULL;
2181 hdr.msg_controllen = 0;
2182 hdr.msg_flags = 0;
2183 #endif
2185 while ((ret = sendmsg(fd, &hdr, wsa->flags)) == -1)
2187 if (errno != EINTR)
2188 return -1;
2191 n = ret;
2192 while (wsa->first_iovec < wsa->n_iovecs && wsa->iovec[wsa->first_iovec].iov_len <= n)
2193 n -= wsa->iovec[wsa->first_iovec++].iov_len;
2194 if (wsa->first_iovec < wsa->n_iovecs)
2196 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
2197 wsa->iovec[wsa->first_iovec].iov_len -= n;
2199 return ret;
2202 /***********************************************************************
2203 * WS2_async_send (INTERNAL)
2205 * Handler for overlapped send() operations.
2207 static NTSTATUS WS2_async_send(void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
2209 ws2_async* wsa = user;
2210 int result = 0, fd;
2212 switch (status)
2214 case STATUS_ALERTED:
2215 if ( wsa->n_iovecs <= wsa->first_iovec )
2217 /* Nothing to do */
2218 status = STATUS_SUCCESS;
2219 break;
2221 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
2222 break;
2224 /* check to see if the data is ready (non-blocking) */
2225 result = WS2_send( fd, wsa );
2226 wine_server_release_fd( wsa->hSocket, fd );
2228 if (result >= 0)
2230 if (wsa->first_iovec < wsa->n_iovecs)
2231 status = STATUS_PENDING;
2232 else
2233 status = STATUS_SUCCESS;
2235 iosb->Information += result;
2237 else if (errno == EAGAIN)
2239 status = STATUS_PENDING;
2241 else
2243 status = wsaErrStatus();
2245 break;
2247 if (status != STATUS_PENDING)
2249 iosb->u.Status = status;
2250 *apc = ws2_async_apc;
2252 return status;
2255 /***********************************************************************
2256 * WS2_async_shutdown (INTERNAL)
2258 * Handler for shutdown() operations on overlapped sockets.
2260 static NTSTATUS WS2_async_shutdown( void* user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc )
2262 ws2_async* wsa = user;
2263 int fd, err = 1;
2265 switch (status)
2267 case STATUS_ALERTED:
2268 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
2269 break;
2271 switch ( wsa->type )
2273 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
2274 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
2276 status = err ? wsaErrStatus() : STATUS_SUCCESS;
2277 wine_server_release_fd( wsa->hSocket, fd );
2278 break;
2280 iosb->u.Status = status;
2281 iosb->Information = 0;
2282 *apc = ws2_async_apc;
2283 return status;
2286 /***********************************************************************
2287 * WS2_register_async_shutdown (INTERNAL)
2289 * Helper function for WS_shutdown() on overlapped sockets.
2291 static int WS2_register_async_shutdown( SOCKET s, int type )
2293 struct ws2_async *wsa;
2294 NTSTATUS status;
2296 TRACE("s %04lx type %d\n", s, type);
2298 wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( struct ws2_async, iovec[1] ));
2299 if ( !wsa )
2300 return WSAEFAULT;
2302 wsa->hSocket = SOCKET2HANDLE(s);
2303 wsa->type = type;
2304 wsa->completion_func = NULL;
2306 SERVER_START_REQ( register_async )
2308 req->type = type;
2309 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2310 req->async.callback = wine_server_client_ptr( WS2_async_shutdown );
2311 req->async.iosb = wine_server_client_ptr( &wsa->local_iosb );
2312 req->async.arg = wine_server_client_ptr( wsa );
2313 req->async.cvalue = 0;
2314 status = wine_server_call( req );
2316 SERVER_END_REQ;
2318 if (status != STATUS_PENDING)
2320 HeapFree( GetProcessHeap(), 0, wsa );
2321 return NtStatusToWSAError( status );
2323 return 0;
2326 /***********************************************************************
2327 * accept (WS2_32.1)
2329 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr, int *addrlen32)
2331 NTSTATUS status;
2332 SOCKET as;
2333 BOOL is_blocking;
2335 TRACE("socket %04lx\n", s );
2336 status = _is_blocking(s, &is_blocking);
2337 if (status)
2339 set_error(status);
2340 return INVALID_SOCKET;
2343 do {
2344 /* try accepting first (if there is a deferred connection) */
2345 SERVER_START_REQ( accept_socket )
2347 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
2348 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
2349 req->attributes = OBJ_INHERIT;
2350 status = wine_server_call( req );
2351 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
2353 SERVER_END_REQ;
2354 if (!status)
2356 if (addr && WS_getpeername(as, addr, addrlen32))
2358 WS_closesocket(as);
2359 return SOCKET_ERROR;
2361 return as;
2363 if (is_blocking && status == STATUS_CANT_WAIT)
2365 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2366 /* block here */
2367 do_block(fd, POLLIN, -1);
2368 _sync_sock_state(s); /* let wineserver notice connection */
2369 release_sock_fd( s, fd );
2371 } while (is_blocking && status == STATUS_CANT_WAIT);
2373 set_error(status);
2374 return INVALID_SOCKET;
2377 /***********************************************************************
2378 * AcceptEx
2380 static BOOL WINAPI WS2_AcceptEx(SOCKET listener, SOCKET acceptor, PVOID dest, DWORD dest_len,
2381 DWORD local_addr_len, DWORD rem_addr_len, LPDWORD received,
2382 LPOVERLAPPED overlapped)
2384 DWORD status;
2385 struct ws2_accept_async *wsa;
2386 int fd;
2387 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
2389 TRACE("(%lx, %lx, %p, %d, %d, %d, %p, %p)\n", listener, acceptor, dest, dest_len, local_addr_len,
2390 rem_addr_len, received, overlapped);
2392 if (!dest)
2394 SetLastError(WSAEINVAL);
2395 return FALSE;
2398 if (!overlapped)
2400 SetLastError(WSA_INVALID_PARAMETER);
2401 return FALSE;
2404 if (!rem_addr_len)
2406 SetLastError(WSAEFAULT);
2407 return FALSE;
2410 fd = get_sock_fd( listener, FILE_READ_DATA, NULL );
2411 if (fd == -1)
2413 SetLastError(WSAENOTSOCK);
2414 return FALSE;
2416 release_sock_fd( listener, fd );
2418 fd = get_sock_fd( acceptor, FILE_READ_DATA, NULL );
2419 if (fd == -1)
2421 SetLastError(WSAENOTSOCK);
2422 return FALSE;
2424 release_sock_fd( acceptor, fd );
2426 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
2427 if(!wsa)
2429 SetLastError(WSAEFAULT);
2430 return FALSE;
2433 wsa->listen_socket = SOCKET2HANDLE(listener);
2434 wsa->accept_socket = SOCKET2HANDLE(acceptor);
2435 wsa->user_overlapped = overlapped;
2436 wsa->cvalue = cvalue;
2437 wsa->buf = dest;
2438 wsa->data_len = dest_len;
2439 wsa->local_len = local_addr_len;
2440 wsa->remote_len = rem_addr_len;
2441 wsa->read = NULL;
2443 if (wsa->data_len)
2445 /* set up a read request if we need it */
2446 wsa->read = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[1]) );
2447 if (!wsa->read)
2449 HeapFree( GetProcessHeap(), 0, wsa );
2450 SetLastError(WSAEFAULT);
2451 return FALSE;
2454 wsa->read->hSocket = wsa->accept_socket;
2455 wsa->read->flags = 0;
2456 wsa->read->lpFlags = &wsa->read->flags;
2457 wsa->read->addr = NULL;
2458 wsa->read->addrlen.ptr = NULL;
2459 wsa->read->control = NULL;
2460 wsa->read->n_iovecs = 1;
2461 wsa->read->first_iovec = 0;
2462 wsa->read->iovec[0].iov_base = wsa->buf;
2463 wsa->read->iovec[0].iov_len = wsa->data_len;
2466 SERVER_START_REQ( register_async )
2468 req->type = ASYNC_TYPE_READ;
2469 req->async.handle = wine_server_obj_handle( SOCKET2HANDLE(listener) );
2470 req->async.callback = wine_server_client_ptr( WS2_async_accept );
2471 req->async.iosb = wine_server_client_ptr( overlapped );
2472 req->async.arg = wine_server_client_ptr( wsa );
2473 req->async.cvalue = cvalue;
2474 /* We don't set event since we may also have to read */
2475 status = wine_server_call( req );
2477 SERVER_END_REQ;
2479 if(status != STATUS_PENDING)
2481 HeapFree( GetProcessHeap(), 0, wsa->read );
2482 HeapFree( GetProcessHeap(), 0, wsa );
2485 SetLastError( NtStatusToWSAError(status) );
2486 return FALSE;
2489 /***********************************************************************
2490 * GetAcceptExSockaddrs
2492 static void WINAPI WS2_GetAcceptExSockaddrs(PVOID buffer, DWORD data_size, DWORD local_size, DWORD remote_size,
2493 struct WS_sockaddr **local_addr, LPINT local_addr_len,
2494 struct WS_sockaddr **remote_addr, LPINT remote_addr_len)
2496 char *cbuf = buffer;
2497 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer, data_size, local_size, remote_size, local_addr,
2498 local_addr_len, remote_addr, remote_addr_len );
2499 cbuf += data_size;
2501 *local_addr_len = *(int *) cbuf;
2502 *local_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2504 cbuf += local_size;
2506 *remote_addr_len = *(int *) cbuf;
2507 *remote_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2510 /***********************************************************************
2511 * WSASendMsg
2513 int WINAPI WSASendMsg( SOCKET s, LPWSAMSG msg, DWORD dwFlags, LPDWORD lpNumberOfBytesSent,
2514 LPWSAOVERLAPPED lpOverlapped,
2515 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
2517 if (!msg)
2519 SetLastError( WSAEFAULT );
2520 return SOCKET_ERROR;
2523 return WS2_sendto( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesSent,
2524 dwFlags, msg->name, msg->namelen,
2525 lpOverlapped, lpCompletionRoutine );
2528 /***********************************************************************
2529 * WSARecvMsg
2531 * Perform a receive operation that is capable of returning message
2532 * control headers. It is important to note that the WSAMSG parameter
2533 * must remain valid throughout the operation, even when an overlapped
2534 * receive is performed.
2536 static int WINAPI WS2_WSARecvMsg( SOCKET s, LPWSAMSG msg, LPDWORD lpNumberOfBytesRecvd,
2537 LPWSAOVERLAPPED lpOverlapped,
2538 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2540 if (!msg)
2542 SetLastError( WSAEFAULT );
2543 return SOCKET_ERROR;
2546 return WS2_recv_base( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesRecvd,
2547 &msg->dwFlags, msg->name, &msg->namelen,
2548 lpOverlapped, lpCompletionRoutine, &msg->Control );
2551 /***********************************************************************
2552 * interface_bind (INTERNAL)
2554 * Take bind() calls on any name corresponding to a local network adapter and restrict the given socket to
2555 * operating only on the specified interface. This restriction consists of two components:
2556 * 1) An outgoing packet restriction suggesting the egress interface for all packets.
2557 * 2) An incoming packet restriction dropping packets not meant for the interface.
2558 * If the function succeeds in placing these restrictions (returns TRUE) then the name for the bind() may
2559 * safely be changed to INADDR_ANY, permitting the transmission and receipt of broadcast packets on the
2560 * socket. This behavior is only relevant to UDP sockets and is needed for applications that expect to be able
2561 * to receive broadcast packets on a socket that is bound to a specific network interface.
2563 static BOOL interface_bind( SOCKET s, int fd, struct sockaddr *addr )
2565 struct sockaddr_in *in_sock = (struct sockaddr_in *) addr;
2566 unsigned int sock_type = 0;
2567 socklen_t optlen = sizeof(sock_type);
2568 in_addr_t bind_addr = in_sock->sin_addr.s_addr;
2569 PIP_ADAPTER_INFO adapters = NULL, adapter;
2570 BOOL ret = FALSE;
2571 DWORD adap_size;
2572 int enable = 1;
2574 if (bind_addr == htonl(INADDR_ANY) || bind_addr == htonl(INADDR_LOOPBACK))
2575 return FALSE; /* Not binding to a network adapter, special interface binding unnecessary. */
2576 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &sock_type, &optlen) == -1 || sock_type != SOCK_DGRAM)
2577 return FALSE; /* Special interface binding is only necessary for UDP datagrams. */
2578 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
2579 goto cleanup;
2580 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
2581 if (adapters == NULL || GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
2582 goto cleanup;
2583 /* Search the IPv4 adapter list for the appropriate binding interface */
2584 for (adapter = adapters; adapter != NULL; adapter = adapter->Next)
2586 in_addr_t adapter_addr = (in_addr_t) inet_addr(adapter->IpAddressList.IpAddress.String);
2588 if (bind_addr == adapter_addr)
2590 #if defined(IP_BOUND_IF)
2591 /* IP_BOUND_IF sets both the incoming and outgoing restriction at once */
2592 if (setsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &adapter->Index, sizeof(adapter->Index)) != 0)
2593 goto cleanup;
2594 ret = TRUE;
2595 #elif defined(LINUX_BOUND_IF)
2596 in_addr_t ifindex = (in_addr_t) htonl(adapter->Index);
2597 struct interface_filter specific_interface_filter;
2598 struct sock_fprog filter_prog;
2600 if (setsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex, sizeof(ifindex)) != 0)
2601 goto cleanup; /* Failed to suggest egress interface */
2602 specific_interface_filter = generic_interface_filter;
2603 specific_interface_filter.iface_rule.k = adapter->Index;
2604 specific_interface_filter.ip_rule.k = htonl(adapter_addr);
2605 filter_prog.len = sizeof(generic_interface_filter)/sizeof(struct sock_filter);
2606 filter_prog.filter = (struct sock_filter *) &specific_interface_filter;
2607 if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog, sizeof(filter_prog)) != 0)
2608 goto cleanup; /* Failed to specify incoming packet filter */
2609 ret = TRUE;
2610 #else
2611 FIXME("Broadcast packets on interface-bound sockets are not currently supported on this platform, "
2612 "receiving broadcast packets will not work on socket %04lx.\n", s);
2613 #endif
2614 break;
2617 /* Will soon be switching to INADDR_ANY: permit address reuse */
2618 if (ret && setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) == 0)
2619 TRACE("Socket %04lx bound to interface index %d\n", s, adapter->Index);
2620 else
2621 ret = FALSE;
2623 cleanup:
2624 if(!ret)
2625 ERR("Failed to bind to interface, receiving broadcast packets will not work on socket %04lx.\n", s);
2626 HeapFree(GetProcessHeap(), 0, adapters);
2627 return ret;
2630 /***********************************************************************
2631 * bind (WS2_32.2)
2633 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
2635 int fd = get_sock_fd( s, 0, NULL );
2636 int res = SOCKET_ERROR;
2638 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2640 if (fd != -1)
2642 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
2644 SetLastError(WSAEAFNOSUPPORT);
2646 else
2648 union generic_unix_sockaddr uaddr;
2649 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2650 if (!uaddrlen)
2652 SetLastError(WSAEFAULT);
2654 else
2656 #ifdef IPV6_V6ONLY
2657 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
2658 if (name->sa_family == WS_AF_INET6 &&
2659 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
2661 int enable = 1;
2662 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
2664 release_sock_fd( s, fd );
2665 SetLastError(WSAEAFNOSUPPORT);
2666 return SOCKET_ERROR;
2669 #endif
2670 if (name->sa_family == WS_AF_INET)
2672 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2673 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2675 /* Trying to bind to the default host interface, using
2676 * INADDR_ANY instead*/
2677 WARN("Trying to bind to magic IP address, using "
2678 "INADDR_ANY instead.\n");
2679 in4->sin_addr.s_addr = htonl(INADDR_ANY);
2681 else if (interface_bind(s, fd, &uaddr.addr))
2682 in4->sin_addr.s_addr = htonl(INADDR_ANY);
2684 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
2686 int loc_errno = errno;
2687 WARN("\tfailure - errno = %i\n", errno);
2688 errno = loc_errno;
2689 switch (errno)
2691 case EBADF:
2692 SetLastError(WSAENOTSOCK);
2693 break;
2694 case EADDRNOTAVAIL:
2695 SetLastError(WSAEINVAL);
2696 break;
2697 case EADDRINUSE:
2699 int optval = 0;
2700 socklen_t optlen = sizeof(optval);
2701 /* Windows >= 2003 will return different results depending on
2702 * SO_REUSEADDR, WSAEACCES may be returned representing that
2703 * the socket hijacking protection prevented the bind */
2704 if (!getsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&optval, &optlen) && optval)
2706 SetLastError(WSAEACCES);
2707 break;
2709 /* fall through */
2711 default:
2712 SetLastError(wsaErrno());
2713 break;
2716 else
2718 res=0; /* success */
2722 release_sock_fd( s, fd );
2724 return res;
2727 /***********************************************************************
2728 * closesocket (WS2_32.3)
2730 int WINAPI WS_closesocket(SOCKET s)
2732 TRACE("socket %04lx\n", s);
2733 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
2734 return SOCKET_ERROR;
2737 static int do_connect(int fd, const struct WS_sockaddr* name, int namelen)
2739 union generic_unix_sockaddr uaddr;
2740 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2742 if (!uaddrlen)
2743 return WSAEFAULT;
2745 if (name->sa_family == WS_AF_INET)
2747 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2748 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2750 /* Trying to connect to magic replace-loopback address,
2751 * assuming we really want to connect to localhost */
2752 TRACE("Trying to connect to magic IP address, using "
2753 "INADDR_LOOPBACK instead.\n");
2754 in4->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
2758 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
2759 return 0;
2761 return wsaErrno();
2764 /***********************************************************************
2765 * connect (WS2_32.4)
2767 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
2769 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2771 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2773 if (fd != -1)
2775 NTSTATUS status;
2776 BOOL is_blocking;
2777 int ret = do_connect(fd, name, namelen);
2778 if (ret == 0)
2779 goto connect_success;
2781 if (ret == WSAEINPROGRESS)
2783 /* tell wineserver that a connection is in progress */
2784 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2785 FD_CONNECT,
2786 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2787 status = _is_blocking( s, &is_blocking );
2788 if (status)
2790 release_sock_fd( s, fd );
2791 set_error( status );
2792 return SOCKET_ERROR;
2794 if (is_blocking)
2796 int result;
2797 /* block here */
2798 do_block(fd, POLLIN | POLLOUT, -1);
2799 _sync_sock_state(s); /* let wineserver notice connection */
2800 /* retrieve any error codes from it */
2801 result = _get_sock_error(s, FD_CONNECT_BIT);
2802 if (result)
2803 SetLastError(NtStatusToWSAError(result));
2804 else
2806 goto connect_success;
2809 else
2811 SetLastError(WSAEWOULDBLOCK);
2814 else
2816 SetLastError(ret);
2818 release_sock_fd( s, fd );
2820 return SOCKET_ERROR;
2822 connect_success:
2823 release_sock_fd( s, fd );
2824 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2825 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2826 FD_CONNECT|FD_WINE_LISTENING);
2827 return 0;
2830 /***********************************************************************
2831 * WSAConnect (WS2_32.30)
2833 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
2834 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
2835 LPQOS lpSQOS, LPQOS lpGQOS )
2837 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
2838 FIXME("unsupported parameters!\n");
2839 return WS_connect( s, name, namelen );
2842 /***********************************************************************
2843 * ConnectEx
2845 static BOOL WINAPI WS2_ConnectEx(SOCKET s, const struct WS_sockaddr* name, int namelen,
2846 PVOID sendBuf, DWORD sendBufLen, LPDWORD sent, LPOVERLAPPED ov)
2848 int fd, ret, status;
2849 union generic_unix_sockaddr uaddr;
2850 socklen_t uaddrlen = sizeof(uaddr);
2852 if (!ov)
2854 SetLastError( ERROR_INVALID_PARAMETER );
2855 return FALSE;
2858 fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2859 if (fd == -1)
2861 SetLastError( WSAENOTSOCK );
2862 return FALSE;
2865 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
2866 s, name, debugstr_sockaddr(name), namelen, sendBuf, sendBufLen, ov);
2868 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
2870 SetLastError(wsaErrno());
2871 return FALSE;
2873 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
2875 SetLastError(WSAEINVAL);
2876 return FALSE;
2879 ret = do_connect(fd, name, namelen);
2880 if (ret == 0)
2882 WSABUF wsabuf;
2884 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2885 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2886 FD_CONNECT|FD_WINE_LISTENING);
2888 wsabuf.len = sendBufLen;
2889 wsabuf.buf = (char*) sendBuf;
2891 /* WSASend takes care of completion if need be */
2892 if (WSASend(s, &wsabuf, sendBuf ? 1 : 0, sent, 0, ov, NULL) != SOCKET_ERROR)
2893 goto connection_success;
2895 else if (ret == WSAEINPROGRESS)
2897 struct ws2_async *wsa;
2898 ULONG_PTR cvalue = (((ULONG_PTR)ov->hEvent & 1) == 0) ? (ULONG_PTR)ov : 0;
2900 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2901 FD_CONNECT,
2902 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2904 /* Indirectly call WSASend */
2905 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( struct ws2_async, iovec[1] ))))
2907 SetLastError(WSAEFAULT);
2909 else
2911 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)ov;
2912 iosb->u.Status = STATUS_PENDING;
2913 iosb->Information = 0;
2915 wsa->hSocket = SOCKET2HANDLE(s);
2916 wsa->addr = NULL;
2917 wsa->addrlen.val = 0;
2918 wsa->flags = 0;
2919 wsa->lpFlags = &wsa->flags;
2920 wsa->control = NULL;
2921 wsa->n_iovecs = sendBuf ? 1 : 0;
2922 wsa->first_iovec = 0;
2923 wsa->completion_func = NULL;
2924 wsa->iovec[0].iov_base = sendBuf;
2925 wsa->iovec[0].iov_len = sendBufLen;
2927 SERVER_START_REQ( register_async )
2929 req->type = ASYNC_TYPE_WRITE;
2930 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2931 req->async.callback = wine_server_client_ptr( WS2_async_send );
2932 req->async.iosb = wine_server_client_ptr( iosb );
2933 req->async.arg = wine_server_client_ptr( wsa );
2934 req->async.event = wine_server_obj_handle( ov->hEvent );
2935 req->async.cvalue = cvalue;
2936 status = wine_server_call( req );
2938 SERVER_END_REQ;
2940 if (status != STATUS_PENDING) HeapFree(GetProcessHeap(), 0, wsa);
2942 /* If the connect already failed */
2943 if (status == STATUS_PIPE_DISCONNECTED)
2944 status = _get_sock_error(s, FD_CONNECT_BIT);
2945 SetLastError( NtStatusToWSAError(status) );
2948 else
2950 SetLastError(ret);
2953 release_sock_fd( s, fd );
2954 return FALSE;
2956 connection_success:
2957 release_sock_fd( s, fd );
2958 return TRUE;
2962 /***********************************************************************
2963 * getpeername (WS2_32.5)
2965 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
2967 int fd;
2968 int res;
2970 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
2972 fd = get_sock_fd( s, 0, NULL );
2973 res = SOCKET_ERROR;
2975 if (fd != -1)
2977 union generic_unix_sockaddr uaddr;
2978 socklen_t uaddrlen = sizeof(uaddr);
2980 if (getpeername(fd, &uaddr.addr, &uaddrlen) == 0)
2982 if (!name || !namelen)
2983 SetLastError(WSAEFAULT);
2984 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
2985 /* The buffer was too small */
2986 SetLastError(WSAEFAULT);
2987 else
2989 res = 0;
2990 TRACE("=> %s\n", debugstr_sockaddr(name));
2993 else
2994 SetLastError(wsaErrno());
2995 release_sock_fd( s, fd );
2997 return res;
3000 /***********************************************************************
3001 * getsockname (WS2_32.6)
3003 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
3005 int fd;
3006 int res;
3008 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
3010 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
3011 if( (name == NULL) || (namelen == NULL) )
3013 SetLastError( WSAEFAULT );
3014 return SOCKET_ERROR;
3017 fd = get_sock_fd( s, 0, NULL );
3018 res = SOCKET_ERROR;
3020 if (fd != -1)
3022 union generic_unix_sockaddr uaddr;
3023 socklen_t uaddrlen = sizeof(uaddr);
3025 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
3027 SetLastError(wsaErrno());
3029 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
3031 SetLastError(WSAEINVAL);
3033 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3035 /* The buffer was too small */
3036 SetLastError(WSAEFAULT);
3038 else
3040 res=0;
3041 TRACE("=> %s\n", debugstr_sockaddr(name));
3043 release_sock_fd( s, fd );
3045 return res;
3048 /***********************************************************************
3049 * getsockopt (WS2_32.7)
3051 INT WINAPI WS_getsockopt(SOCKET s, INT level,
3052 INT optname, char *optval, INT *optlen)
3054 int fd;
3055 INT ret = 0;
3057 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
3058 s, level, optname, optval, optlen ? *optlen : 0);
3060 switch(level)
3062 case WS_SOL_SOCKET:
3064 switch(optname)
3066 /* Handle common cases. The special cases are below, sorted
3067 * alphabetically */
3068 case WS_SO_BROADCAST:
3069 case WS_SO_DEBUG:
3070 case WS_SO_ERROR:
3071 case WS_SO_KEEPALIVE:
3072 case WS_SO_OOBINLINE:
3073 case WS_SO_RCVBUF:
3074 case WS_SO_REUSEADDR:
3075 case WS_SO_SNDBUF:
3076 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3077 return SOCKET_ERROR;
3078 convert_sockopt(&level, &optname);
3079 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3081 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3082 ret = SOCKET_ERROR;
3084 release_sock_fd( s, fd );
3085 return ret;
3086 case WS_SO_ACCEPTCONN:
3087 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3088 return SOCKET_ERROR;
3089 if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, optval, (socklen_t *)optlen) != 0 )
3091 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3092 ret = SOCKET_ERROR;
3094 else
3096 /* BSD returns != 0 while Windows return exact == 1 */
3097 if (*(int *)optval) *(int *)optval = 1;
3099 release_sock_fd( s, fd );
3100 return ret;
3101 case WS_SO_BSP_STATE:
3103 int req_size, addr_size;
3104 WSAPROTOCOL_INFOW infow;
3105 CSADDR_INFO *csinfo;
3107 ret = ws_protocol_info(s, TRUE, &infow, &addr_size);
3108 if (ret)
3110 if (infow.iAddressFamily == WS_AF_INET)
3111 addr_size = sizeof(struct sockaddr_in);
3112 else if (infow.iAddressFamily == WS_AF_INET6)
3113 addr_size = sizeof(struct sockaddr_in6);
3114 else
3116 FIXME("Family %d is unsupported for SO_BSP_STATE\n", infow.iAddressFamily);
3117 SetLastError(WSAEAFNOSUPPORT);
3118 return SOCKET_ERROR;
3121 req_size = sizeof(CSADDR_INFO) + addr_size * 2;
3122 if (*optlen < req_size)
3124 ret = 0;
3125 SetLastError(WSAEFAULT);
3127 else
3129 union generic_unix_sockaddr uaddr;
3130 socklen_t uaddrlen = sizeof(uaddr);
3132 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3133 return SOCKET_ERROR;
3135 csinfo = (CSADDR_INFO*) optval;
3137 /* Check if the sock is bound */
3138 if (!getsockname(fd, &uaddr.addr, &uaddrlen) &&
3139 is_sockaddr_bound(&uaddr.addr, uaddrlen))
3141 csinfo->LocalAddr.lpSockaddr =
3142 (LPSOCKADDR) (optval + sizeof(CSADDR_INFO));
3143 ws_sockaddr_u2ws(&uaddr.addr, csinfo->LocalAddr.lpSockaddr, &addr_size);
3144 csinfo->LocalAddr.iSockaddrLength = addr_size;
3146 else
3148 csinfo->LocalAddr.lpSockaddr = NULL;
3149 csinfo->LocalAddr.iSockaddrLength = 0;
3152 /* Check if the sock is connected */
3153 if (!getpeername(fd, &uaddr.addr, &uaddrlen) &&
3154 is_sockaddr_bound(&uaddr.addr, uaddrlen))
3156 csinfo->RemoteAddr.lpSockaddr =
3157 (LPSOCKADDR) (optval + sizeof(CSADDR_INFO) + addr_size);
3158 ws_sockaddr_u2ws(&uaddr.addr, csinfo->RemoteAddr.lpSockaddr, &addr_size);
3159 csinfo->RemoteAddr.iSockaddrLength = addr_size;
3161 else
3163 csinfo->RemoteAddr.lpSockaddr = NULL;
3164 csinfo->RemoteAddr.iSockaddrLength = 0;
3167 csinfo->iSocketType = infow.iSocketType;
3168 csinfo->iProtocol = infow.iProtocol;
3169 release_sock_fd( s, fd );
3172 return ret ? 0 : SOCKET_ERROR;
3174 case WS_SO_DONTLINGER:
3176 struct linger lingval;
3177 socklen_t len = sizeof(struct linger);
3179 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
3181 SetLastError(WSAEFAULT);
3182 return SOCKET_ERROR;
3184 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3185 return SOCKET_ERROR;
3187 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
3189 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3190 ret = SOCKET_ERROR;
3192 else
3194 *(BOOL *)optval = !lingval.l_onoff;
3195 *optlen = sizeof(BOOL);
3198 release_sock_fd( s, fd );
3199 return ret;
3202 case WS_SO_CONNECT_TIME:
3204 static int pretendtime = 0;
3205 struct WS_sockaddr addr;
3206 int len = sizeof(addr);
3208 if (!optlen || *optlen < sizeof(DWORD) || !optval)
3210 SetLastError(WSAEFAULT);
3211 return SOCKET_ERROR;
3213 if (WS_getpeername(s, &addr, &len) == SOCKET_ERROR)
3214 *(DWORD *)optval = ~0u;
3215 else
3217 if (!pretendtime) FIXME("WS_SO_CONNECT_TIME - faking results\n");
3218 *(DWORD *)optval = pretendtime++;
3220 *optlen = sizeof(DWORD);
3221 return ret;
3223 /* As mentioned in setsockopt, Windows ignores this, so we
3224 * always return true here */
3225 case WS_SO_DONTROUTE:
3226 if (!optlen || *optlen < sizeof(BOOL) || !optval)
3228 SetLastError(WSAEFAULT);
3229 return SOCKET_ERROR;
3231 *(BOOL *)optval = TRUE;
3232 *optlen = sizeof(BOOL);
3233 return 0;
3235 case WS_SO_LINGER:
3237 struct linger lingval;
3238 int so_type;
3239 socklen_t len = sizeof(struct linger), slen = sizeof(int);
3241 /* struct linger and LINGER have different sizes */
3242 if (!optlen || *optlen < sizeof(LINGER) || !optval)
3244 SetLastError(WSAEFAULT);
3245 return SOCKET_ERROR;
3247 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3248 return SOCKET_ERROR;
3250 if ((getsockopt(fd, SOL_SOCKET, SO_TYPE, &so_type, &slen) == 0 && so_type == SOCK_DGRAM))
3252 SetLastError(WSAENOPROTOOPT);
3253 ret = SOCKET_ERROR;
3255 else if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0)
3257 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3258 ret = SOCKET_ERROR;
3260 else
3262 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
3263 ((LINGER *)optval)->l_linger = lingval.l_linger;
3264 *optlen = sizeof(struct linger);
3267 release_sock_fd( s, fd );
3268 return ret;
3271 case WS_SO_MAX_MSG_SIZE:
3272 if (!optlen || *optlen < sizeof(int) || !optval)
3274 SetLastError(WSAEFAULT);
3275 return SOCKET_ERROR;
3277 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
3278 *(int *)optval = 65507;
3279 *optlen = sizeof(int);
3280 return 0;
3282 /* SO_OPENTYPE does not require a valid socket handle. */
3283 case WS_SO_OPENTYPE:
3284 if (!optlen || *optlen < sizeof(int) || !optval)
3286 SetLastError(WSAEFAULT);
3287 return SOCKET_ERROR;
3289 *(int *)optval = get_per_thread_data()->opentype;
3290 *optlen = sizeof(int);
3291 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
3292 return 0;
3293 case WS_SO_PROTOCOL_INFOA:
3294 case WS_SO_PROTOCOL_INFOW:
3296 int size;
3297 WSAPROTOCOL_INFOW infow;
3299 ret = ws_protocol_info(s, optname == WS_SO_PROTOCOL_INFOW, &infow, &size);
3300 if (ret)
3302 if (!optlen || !optval || *optlen < size)
3304 if(optlen) *optlen = size;
3305 ret = 0;
3306 SetLastError(WSAEFAULT);
3308 else
3309 memcpy(optval, &infow, size);
3311 return ret ? 0 : SOCKET_ERROR;
3313 #ifdef SO_RCVTIMEO
3314 case WS_SO_RCVTIMEO:
3315 #endif
3316 #ifdef SO_SNDTIMEO
3317 case WS_SO_SNDTIMEO:
3318 #endif
3319 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
3321 struct timeval tv;
3322 socklen_t len = sizeof(struct timeval);
3324 if (!optlen || *optlen < sizeof(int)|| !optval)
3326 SetLastError(WSAEFAULT);
3327 return SOCKET_ERROR;
3329 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3330 return SOCKET_ERROR;
3332 convert_sockopt(&level, &optname);
3333 if (getsockopt(fd, level, optname, &tv, &len) != 0 )
3335 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3336 ret = SOCKET_ERROR;
3338 else
3340 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
3341 *optlen = sizeof(int);
3344 release_sock_fd( s, fd );
3345 return ret;
3347 #endif
3348 case WS_SO_TYPE:
3350 if (!optlen || *optlen < sizeof(int) || !optval)
3352 SetLastError(WSAEFAULT);
3353 return SOCKET_ERROR;
3355 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3356 return SOCKET_ERROR;
3358 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, optval, (socklen_t *)optlen) != 0 )
3360 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3361 ret = SOCKET_ERROR;
3363 else
3364 (*(int *)optval) = convert_socktype_u2w(*(int *)optval);
3366 release_sock_fd( s, fd );
3367 return ret;
3369 default:
3370 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
3371 SetLastError(WSAENOPROTOOPT);
3372 return SOCKET_ERROR;
3373 } /* end switch(optname) */
3374 }/* end case WS_SOL_SOCKET */
3375 #ifdef HAS_IPX
3376 case WS_NSPROTO_IPX:
3378 struct WS_sockaddr_ipx addr;
3379 IPX_ADDRESS_DATA *data;
3380 int namelen;
3381 switch(optname)
3383 case WS_IPX_PTYPE:
3384 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3385 #ifdef SOL_IPX
3386 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (socklen_t *)optlen) == -1)
3388 ret = SOCKET_ERROR;
3390 #else
3392 struct ipx val;
3393 socklen_t len=sizeof(struct ipx);
3394 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
3395 ret = SOCKET_ERROR;
3396 else
3397 *optval = (int)val.ipx_pt;
3399 #endif
3400 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
3401 release_sock_fd( s, fd );
3402 return ret;
3404 case WS_IPX_ADDRESS:
3406 * On a Win2000 system with one network card there are usually
3407 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
3408 * Using this call you can then retrieve info about this all.
3409 * In case of Linux it is a bit different. Usually you have
3410 * only "one" device active and further it is not possible to
3411 * query things like the linkspeed.
3413 FIXME("IPX_ADDRESS\n");
3414 namelen = sizeof(struct WS_sockaddr_ipx);
3415 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
3416 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
3418 data = (IPX_ADDRESS_DATA*)optval;
3419 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
3420 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
3421 data->adapternum = 0;
3422 data->wan = FALSE; /* We are not on a wan for now .. */
3423 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
3424 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
3425 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
3426 * note 1MB = 1000kB in this case */
3427 return 0;
3429 case WS_IPX_MAX_ADAPTER_NUM:
3430 FIXME("IPX_MAX_ADAPTER_NUM\n");
3431 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
3432 return 0;
3434 default:
3435 FIXME("IPX optname:%x\n", optname);
3436 return SOCKET_ERROR;
3437 }/* end switch(optname) */
3438 } /* end case WS_NSPROTO_IPX */
3439 #endif
3441 #ifdef HAS_IRDA
3442 #define MAX_IRDA_DEVICES 10
3444 case WS_SOL_IRLMP:
3445 switch(optname)
3447 case WS_IRLMP_ENUMDEVICES:
3449 char buf[sizeof(struct irda_device_list) +
3450 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
3451 int res;
3452 socklen_t len = sizeof(buf);
3454 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3455 return SOCKET_ERROR;
3456 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
3457 release_sock_fd( s, fd );
3458 if (res < 0)
3460 SetLastError(wsaErrno());
3461 return SOCKET_ERROR;
3463 else
3465 struct irda_device_list *src = (struct irda_device_list *)buf;
3466 DEVICELIST *dst = (DEVICELIST *)optval;
3467 INT needed = sizeof(DEVICELIST);
3468 unsigned int i;
3470 if (src->len > 0)
3471 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
3472 if (*optlen < needed)
3474 SetLastError(WSAEFAULT);
3475 return SOCKET_ERROR;
3477 *optlen = needed;
3478 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
3479 dst->numDevice = src->len;
3480 for (i = 0; i < src->len; i++)
3482 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
3483 src->dev[i].saddr, src->dev[i].daddr,
3484 src->dev[i].info, src->dev[i].hints[0],
3485 src->dev[i].hints[1]);
3486 memcpy( dst->Device[i].irdaDeviceID,
3487 &src->dev[i].daddr,
3488 sizeof(dst->Device[i].irdaDeviceID) ) ;
3489 memcpy( dst->Device[i].irdaDeviceName,
3490 src->dev[i].info,
3491 sizeof(dst->Device[i].irdaDeviceName) ) ;
3492 memcpy( &dst->Device[i].irdaDeviceHints1,
3493 &src->dev[i].hints[0],
3494 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
3495 memcpy( &dst->Device[i].irdaDeviceHints2,
3496 &src->dev[i].hints[1],
3497 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
3498 dst->Device[i].irdaCharSet = src->dev[i].charset;
3500 return 0;
3503 default:
3504 FIXME("IrDA optname:0x%x\n", optname);
3505 return SOCKET_ERROR;
3507 break; /* case WS_SOL_IRLMP */
3508 #undef MAX_IRDA_DEVICES
3509 #endif
3511 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3512 case WS_IPPROTO_TCP:
3513 switch(optname)
3515 case WS_TCP_NODELAY:
3516 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3517 return SOCKET_ERROR;
3518 convert_sockopt(&level, &optname);
3519 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3521 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3522 ret = SOCKET_ERROR;
3524 release_sock_fd( s, fd );
3525 return ret;
3527 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
3528 return SOCKET_ERROR;
3530 case WS_IPPROTO_IP:
3531 switch(optname)
3533 case WS_IP_ADD_MEMBERSHIP:
3534 case WS_IP_DROP_MEMBERSHIP:
3535 #ifdef IP_HDRINCL
3536 case WS_IP_HDRINCL:
3537 #endif
3538 case WS_IP_MULTICAST_IF:
3539 case WS_IP_MULTICAST_LOOP:
3540 case WS_IP_MULTICAST_TTL:
3541 case WS_IP_OPTIONS:
3542 #ifdef IP_PKTINFO
3543 case WS_IP_PKTINFO:
3544 #endif
3545 case WS_IP_TOS:
3546 case WS_IP_TTL:
3547 #ifdef IP_UNICAST_IF
3548 case WS_IP_UNICAST_IF:
3549 #endif
3550 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3551 return SOCKET_ERROR;
3552 convert_sockopt(&level, &optname);
3553 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3555 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3556 ret = SOCKET_ERROR;
3558 release_sock_fd( s, fd );
3559 return ret;
3560 case WS_IP_DONTFRAGMENT:
3561 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
3562 *(BOOL*)optval = FALSE;
3563 return 0;
3565 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
3566 return SOCKET_ERROR;
3568 case WS_IPPROTO_IPV6:
3569 switch(optname)
3571 #ifdef IPV6_ADD_MEMBERSHIP
3572 case WS_IPV6_ADD_MEMBERSHIP:
3573 #endif
3574 #ifdef IPV6_DROP_MEMBERSHIP
3575 case WS_IPV6_DROP_MEMBERSHIP:
3576 #endif
3577 case WS_IPV6_MULTICAST_IF:
3578 case WS_IPV6_MULTICAST_HOPS:
3579 case WS_IPV6_MULTICAST_LOOP:
3580 case WS_IPV6_UNICAST_HOPS:
3581 case WS_IPV6_V6ONLY:
3582 #ifdef IPV6_UNICAST_IF
3583 case WS_IPV6_UNICAST_IF:
3584 #endif
3585 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3586 return SOCKET_ERROR;
3587 convert_sockopt(&level, &optname);
3588 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3590 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3591 ret = SOCKET_ERROR;
3593 release_sock_fd( s, fd );
3594 return ret;
3595 case WS_IPV6_DONTFRAG:
3596 FIXME("WS_IPV6_DONTFRAG is always false!\n");
3597 *(BOOL*)optval = FALSE;
3598 return 0;
3600 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
3601 return SOCKET_ERROR;
3603 default:
3604 WARN("Unknown level: 0x%08x\n", level);
3605 SetLastError(WSAEINVAL);
3606 return SOCKET_ERROR;
3607 } /* end switch(level) */
3610 /***********************************************************************
3611 * htonl (WS2_32.8)
3613 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
3615 return htonl(hostlong);
3619 /***********************************************************************
3620 * htons (WS2_32.9)
3622 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
3624 return htons(hostshort);
3627 /***********************************************************************
3628 * WSAHtonl (WS2_32.46)
3629 * From MSDN description of error codes, this function should also
3630 * check if WinSock has been initialized and the socket is a valid
3631 * socket. But why? This function only translates a host byte order
3632 * u_long into a network byte order u_long...
3634 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
3636 if (lpnetlong)
3638 *lpnetlong = htonl(hostlong);
3639 return 0;
3641 SetLastError(WSAEFAULT);
3642 return SOCKET_ERROR;
3645 /***********************************************************************
3646 * WSAHtons (WS2_32.47)
3647 * From MSDN description of error codes, this function should also
3648 * check if WinSock has been initialized and the socket is a valid
3649 * socket. But why? This function only translates a host byte order
3650 * u_short into a network byte order u_short...
3652 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
3655 if (lpnetshort)
3657 *lpnetshort = htons(hostshort);
3658 return 0;
3660 SetLastError(WSAEFAULT);
3661 return SOCKET_ERROR;
3665 /***********************************************************************
3666 * inet_addr (WS2_32.11)
3668 WS_u_long WINAPI WS_inet_addr(const char *cp)
3670 if (!cp) return INADDR_NONE;
3671 return inet_addr(cp);
3675 /***********************************************************************
3676 * ntohl (WS2_32.14)
3678 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
3680 return ntohl(netlong);
3684 /***********************************************************************
3685 * ntohs (WS2_32.15)
3687 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
3689 return ntohs(netshort);
3693 /***********************************************************************
3694 * inet_ntoa (WS2_32.12)
3696 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
3698 char* s = inet_ntoa(*((struct in_addr*)&in));
3699 if( s )
3701 struct per_thread_data *data = get_per_thread_data();
3702 strcpy(data->ntoa_buffer, s);
3703 return data->ntoa_buffer;
3705 SetLastError(wsaErrno());
3706 return NULL;
3709 static const char *debugstr_wsaioctl(DWORD ioctl)
3711 const char *buf_type, *family;
3713 switch(ioctl & 0x18000000)
3715 case WS_IOC_WS2:
3716 family = "IOC_WS2";
3717 break;
3718 case WS_IOC_PROTOCOL:
3719 family = "IOC_PROTOCOL";
3720 break;
3721 case WS_IOC_VENDOR:
3722 family = "IOC_VENDOR";
3723 break;
3724 default: /* WS_IOC_UNIX */
3726 BYTE size = (ioctl >> 16) & WS_IOCPARM_MASK;
3727 char x = (ioctl & 0xff00) >> 8;
3728 BYTE y = ioctl & 0xff;
3729 char args[14];
3731 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3733 case WS_IOC_VOID:
3734 buf_type = "_IO";
3735 sprintf(args, "%d, %d", x, y);
3736 break;
3737 case WS_IOC_IN:
3738 buf_type = "_IOW";
3739 sprintf(args, "'%c', %d, %d", x, y, size);
3740 break;
3741 case WS_IOC_OUT:
3742 buf_type = "_IOR";
3743 sprintf(args, "'%c', %d, %d", x, y, size);
3744 break;
3745 default:
3746 buf_type = "?";
3747 sprintf(args, "'%c', %d, %d", x, y, size);
3748 break;
3750 return wine_dbg_sprintf("%s(%s)", buf_type, args);
3754 /* We are different from WS_IOC_UNIX. */
3755 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3757 case WS_IOC_VOID:
3758 buf_type = "_WSAIO";
3759 break;
3760 case WS_IOC_INOUT:
3761 buf_type = "_WSAIORW";
3762 break;
3763 case WS_IOC_IN:
3764 buf_type = "_WSAIOW";
3765 break;
3766 case WS_IOC_OUT:
3767 buf_type = "_WSAIOR";
3768 break;
3769 default:
3770 buf_type = "?";
3771 break;
3774 return wine_dbg_sprintf("%s(%s, %d)", buf_type, family,
3775 (USHORT)(ioctl & 0xffff));
3778 /* do an ioctl call through the server */
3779 static DWORD server_ioctl_sock( SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size,
3780 LPVOID out_buff, DWORD out_size, LPDWORD ret_size,
3781 LPWSAOVERLAPPED overlapped,
3782 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
3784 HANDLE event = overlapped ? overlapped->hEvent : 0;
3785 HANDLE handle = SOCKET2HANDLE( s );
3786 struct ws2_async *wsa;
3787 NTSTATUS status;
3788 PIO_STATUS_BLOCK io;
3790 if (!(wsa = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wsa) )))
3791 return WSA_NOT_ENOUGH_MEMORY;
3792 wsa->hSocket = handle;
3793 wsa->user_overlapped = overlapped;
3794 wsa->completion_func = completion;
3795 io = (overlapped ? (PIO_STATUS_BLOCK)overlapped : &wsa->local_iosb);
3797 status = NtDeviceIoControlFile( handle, event, (PIO_APC_ROUTINE)ws2_async_apc, wsa, io, code,
3798 in_buff, in_size, out_buff, out_size );
3799 if (status == STATUS_NOT_SUPPORTED)
3801 FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
3802 code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
3804 else if (status == STATUS_SUCCESS)
3805 *ret_size = io->Information; /* "Information" is the size written to the output buffer */
3807 if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, wsa );
3809 return NtStatusToWSAError( status );
3812 /**********************************************************************
3813 * WSAIoctl (WS2_32.50)
3816 INT WINAPI WSAIoctl(SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size, LPVOID out_buff,
3817 DWORD out_size, LPDWORD ret_size, LPWSAOVERLAPPED overlapped,
3818 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
3820 int fd;
3821 DWORD status = 0, total = 0;
3823 TRACE("%04lx, %s, %p, %d, %p, %d, %p, %p, %p\n",
3824 s, debugstr_wsaioctl(code), in_buff, in_size, out_buff, out_size, ret_size, overlapped, completion);
3826 switch (code)
3828 case WS_FIONBIO:
3829 if (in_size != sizeof(WS_u_long) || IS_INTRESOURCE(in_buff))
3831 SetLastError(WSAEFAULT);
3832 return SOCKET_ERROR;
3834 TRACE("-> FIONBIO (%x)\n", *(WS_u_long*)in_buff);
3835 if (_get_sock_mask(s))
3837 /* AsyncSelect()'ed sockets are always nonblocking */
3838 if (!*(WS_u_long *)in_buff) status = WSAEINVAL;
3839 break;
3841 if (*(WS_u_long *)in_buff)
3842 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
3843 else
3844 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
3845 break;
3847 case WS_FIONREAD:
3849 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
3851 SetLastError(WSAEFAULT);
3852 return SOCKET_ERROR;
3854 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3855 if (ioctl(fd, FIONREAD, out_buff ) == -1)
3856 status = (errno == EBADF) ? WSAENOTSOCK : wsaErrno();
3857 release_sock_fd( s, fd );
3858 break;
3861 case WS_SIOCATMARK:
3863 unsigned int oob = 0, atmark = 0;
3864 socklen_t oobsize = sizeof(int);
3865 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
3867 SetLastError(WSAEFAULT);
3868 return SOCKET_ERROR;
3870 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3871 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
3872 if ((getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &oob, &oobsize ) == -1)
3873 || (!oob && ioctl(fd, SIOCATMARK, &atmark ) == -1))
3874 status = (errno == EBADF) ? WSAENOTSOCK : wsaErrno();
3875 else
3877 /* The SIOCATMARK value read from ioctl() is reversed
3878 * because BSD returns TRUE if it's in the OOB mark
3879 * while Windows returns TRUE if there are NO OOB bytes.
3881 (*(WS_u_long *) out_buff) = oob | !atmark;
3884 release_sock_fd( s, fd );
3885 break;
3888 case WS_FIOASYNC:
3889 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
3890 SetLastError(WSAEINVAL);
3891 return SOCKET_ERROR;
3893 case WS_SIO_GET_INTERFACE_LIST:
3895 INTERFACE_INFO* intArray = out_buff;
3896 DWORD size, numInt = 0, apiReturn;
3898 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
3900 if (!out_buff || !ret_size)
3902 SetLastError(WSAEFAULT);
3903 return SOCKET_ERROR;
3906 fd = get_sock_fd( s, 0, NULL );
3907 if (fd == -1) return SOCKET_ERROR;
3909 apiReturn = GetAdaptersInfo(NULL, &size);
3910 if (apiReturn == ERROR_BUFFER_OVERFLOW)
3912 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
3914 if (table)
3916 if (GetAdaptersInfo(table, &size) == NO_ERROR)
3918 PIP_ADAPTER_INFO ptr;
3920 for (ptr = table, numInt = 0; ptr; ptr = ptr->Next)
3922 unsigned int addr, mask, bcast;
3923 struct ifreq ifInfo;
3925 /* Skip interfaces without an IPv4 address. */
3926 if (ptr->IpAddressList.IpAddress.String[0] == '\0')
3927 continue;
3929 if ((numInt + 1)*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > out_size)
3931 WARN("Buffer too small = %u, out_size = %u\n", numInt + 1, out_size);
3932 status = WSAEFAULT;
3933 break;
3936 /* Socket Status Flags */
3937 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
3938 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
3940 ERR("Error obtaining status flags for socket!\n");
3941 status = WSAEINVAL;
3942 break;
3944 else
3946 /* set flags; the values of IFF_* are not the same
3947 under Linux and Windows, therefore must generate
3948 new flags */
3949 intArray->iiFlags = 0;
3950 if (ifInfo.ifr_flags & IFF_BROADCAST)
3951 intArray->iiFlags |= WS_IFF_BROADCAST;
3952 #ifdef IFF_POINTOPOINT
3953 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
3954 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
3955 #endif
3956 if (ifInfo.ifr_flags & IFF_LOOPBACK)
3957 intArray->iiFlags |= WS_IFF_LOOPBACK;
3958 if (ifInfo.ifr_flags & IFF_UP)
3959 intArray->iiFlags |= WS_IFF_UP;
3960 if (ifInfo.ifr_flags & IFF_MULTICAST)
3961 intArray->iiFlags |= WS_IFF_MULTICAST;
3964 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
3965 mask = inet_addr(ptr->IpAddressList.IpMask.String);
3966 bcast = addr | ~mask;
3967 intArray->iiAddress.AddressIn.sin_family = AF_INET;
3968 intArray->iiAddress.AddressIn.sin_port = 0;
3969 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
3970 addr;
3971 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
3972 intArray->iiNetmask.AddressIn.sin_port = 0;
3973 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
3974 mask;
3975 intArray->iiBroadcastAddress.AddressIn.sin_family =
3976 AF_INET;
3977 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
3978 intArray->iiBroadcastAddress.AddressIn.sin_addr.
3979 WS_s_addr = bcast;
3980 intArray++;
3981 numInt++;
3984 else
3986 ERR("Unable to get interface table!\n");
3987 status = WSAEINVAL;
3989 HeapFree(GetProcessHeap(),0,table);
3991 else status = WSAEINVAL;
3993 else if (apiReturn != ERROR_NO_DATA)
3995 ERR("Unable to get interface table!\n");
3996 status = WSAEINVAL;
3998 /* Calculate the size of the array being returned */
3999 total = sizeof(INTERFACE_INFO) * numInt;
4000 release_sock_fd( s, fd );
4001 break;
4004 case WS_SIO_ADDRESS_LIST_QUERY:
4006 DWORD size;
4008 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
4010 if (!ret_size)
4012 SetLastError(WSAEFAULT);
4013 return SOCKET_ERROR;
4016 if (out_size && out_size < FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[0]))
4018 *ret_size = 0;
4019 SetLastError(WSAEINVAL);
4020 return SOCKET_ERROR;
4023 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
4025 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
4026 SOCKET_ADDRESS_LIST *sa_list;
4027 SOCKADDR_IN *sockaddr;
4028 SOCKET_ADDRESS *sa;
4029 unsigned int i;
4030 DWORD num;
4032 if (!table || GetAdaptersInfo(table, &size))
4034 HeapFree(GetProcessHeap(), 0, table);
4035 status = WSAEINVAL;
4036 break;
4039 for (p = table, num = 0; p; p = p->Next)
4040 if (p->IpAddressList.IpAddress.String[0]) num++;
4042 total = FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[num]) + num * sizeof(*sockaddr);
4043 if (total > out_size || !out_buff)
4045 *ret_size = total;
4046 HeapFree(GetProcessHeap(), 0, table);
4047 status = WSAEFAULT;
4048 break;
4051 sa_list = out_buff;
4052 sa = sa_list->Address;
4053 sockaddr = (SOCKADDR_IN *)&sa[num];
4054 sa_list->iAddressCount = num;
4056 for (p = table, i = 0; p; p = p->Next)
4058 if (!p->IpAddressList.IpAddress.String[0]) continue;
4060 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
4061 sa[i].iSockaddrLength = sizeof(SOCKADDR);
4063 sockaddr[i].sin_family = AF_INET;
4064 sockaddr[i].sin_port = 0;
4065 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
4066 i++;
4069 HeapFree(GetProcessHeap(), 0, table);
4071 else
4073 WARN("unable to get IP address list\n");
4074 status = WSAEINVAL;
4076 break;
4079 case WS_SIO_FLUSH:
4080 FIXME("SIO_FLUSH: stub.\n");
4081 break;
4083 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
4085 static const GUID connectex_guid = WSAID_CONNECTEX;
4086 static const GUID disconnectex_guid = WSAID_DISCONNECTEX;
4087 static const GUID acceptex_guid = WSAID_ACCEPTEX;
4088 static const GUID getaccepexsockaddrs_guid = WSAID_GETACCEPTEXSOCKADDRS;
4089 static const GUID transmitfile_guid = WSAID_TRANSMITFILE;
4090 static const GUID transmitpackets_guid = WSAID_TRANSMITPACKETS;
4091 static const GUID wsarecvmsg_guid = WSAID_WSARECVMSG;
4092 static const GUID wsasendmsg_guid = WSAID_WSASENDMSG;
4094 if ( IsEqualGUID(&connectex_guid, in_buff) )
4096 *(LPFN_CONNECTEX *)out_buff = WS2_ConnectEx;
4097 break;
4099 else if ( IsEqualGUID(&disconnectex_guid, in_buff) )
4101 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented DisconnectEx\n");
4103 else if ( IsEqualGUID(&acceptex_guid, in_buff) )
4105 *(LPFN_ACCEPTEX *)out_buff = WS2_AcceptEx;
4106 break;
4108 else if ( IsEqualGUID(&getaccepexsockaddrs_guid, in_buff) )
4110 *(LPFN_GETACCEPTEXSOCKADDRS *)out_buff = WS2_GetAcceptExSockaddrs;
4111 break;
4113 else if ( IsEqualGUID(&transmitfile_guid, in_buff) )
4115 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitFile\n");
4117 else if ( IsEqualGUID(&transmitpackets_guid, in_buff) )
4119 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitPackets\n");
4121 else if ( IsEqualGUID(&wsarecvmsg_guid, in_buff) )
4123 *(LPFN_WSARECVMSG *)out_buff = WS2_WSARecvMsg;
4124 break;
4126 else if ( IsEqualGUID(&wsasendmsg_guid, in_buff) )
4128 *(LPFN_WSASENDMSG *)out_buff = WSASendMsg;
4129 break;
4131 else
4132 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff));
4134 status = WSAEOPNOTSUPP;
4135 break;
4137 case WS_SIO_KEEPALIVE_VALS:
4139 struct tcp_keepalive *k;
4140 int keepalive, keepidle, keepintvl;
4142 if (!in_buff || in_size < sizeof(struct tcp_keepalive))
4144 SetLastError(WSAEFAULT);
4145 return SOCKET_ERROR;
4148 k = in_buff;
4149 keepalive = k->onoff ? 1 : 0;
4150 keepidle = max( 1, (k->keepalivetime + 500) / 1000 );
4151 keepintvl = max( 1, (k->keepaliveinterval + 500) / 1000 );
4153 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
4155 fd = get_sock_fd(s, 0, NULL);
4156 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
4157 status = WSAEINVAL;
4158 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
4159 /* these values need to be set only if SO_KEEPALIVE is enabled */
4160 else if(keepalive)
4162 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
4163 status = WSAEINVAL;
4164 else if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
4165 status = WSAEINVAL;
4167 #else
4168 else
4169 FIXME("ignoring keepalive interval and timeout\n");
4170 #endif
4171 release_sock_fd(s, fd);
4172 break;
4174 case WS_SIO_ROUTING_INTERFACE_QUERY:
4176 struct WS_sockaddr *daddr = (struct WS_sockaddr *)in_buff;
4177 struct WS_sockaddr_in *daddr_in = (struct WS_sockaddr_in *)daddr;
4178 struct WS_sockaddr_in *saddr_in = out_buff;
4179 MIB_IPFORWARDROW row;
4180 PMIB_IPADDRTABLE ipAddrTable = NULL;
4181 DWORD size, i, found_index;
4183 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
4185 if (!in_buff || in_size < sizeof(struct WS_sockaddr) ||
4186 !out_buff || out_size < sizeof(struct WS_sockaddr_in) || !ret_size)
4188 SetLastError(WSAEFAULT);
4189 return SOCKET_ERROR;
4191 if (daddr->sa_family != AF_INET)
4193 FIXME("unsupported address family %d\n", daddr->sa_family);
4194 status = WSAEAFNOSUPPORT;
4195 break;
4197 if (GetBestRoute(daddr_in->sin_addr.S_un.S_addr, 0, &row) != NOERROR ||
4198 GetIpAddrTable(NULL, &size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
4200 status = WSAEFAULT;
4201 break;
4203 ipAddrTable = HeapAlloc(GetProcessHeap(), 0, size);
4204 if (GetIpAddrTable(ipAddrTable, &size, FALSE))
4206 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4207 status = WSAEFAULT;
4208 break;
4210 for (i = 0, found_index = ipAddrTable->dwNumEntries;
4211 i < ipAddrTable->dwNumEntries; i++)
4213 if (ipAddrTable->table[i].dwIndex == row.dwForwardIfIndex)
4214 found_index = i;
4216 if (found_index == ipAddrTable->dwNumEntries)
4218 ERR("no matching IP address for interface %d\n",
4219 row.dwForwardIfIndex);
4220 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4221 status = WSAEFAULT;
4222 break;
4224 saddr_in->sin_family = AF_INET;
4225 saddr_in->sin_addr.S_un.S_addr = ipAddrTable->table[found_index].dwAddr;
4226 saddr_in->sin_port = 0;
4227 total = sizeof(struct WS_sockaddr_in);
4228 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4229 break;
4231 case WS_SIO_SET_COMPATIBILITY_MODE:
4232 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
4233 status = WSAEOPNOTSUPP;
4234 break;
4235 case WS_SIO_UDP_CONNRESET:
4236 FIXME("WS_SIO_UDP_CONNRESET stub\n");
4237 break;
4238 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
4239 SetLastError(WSAEOPNOTSUPP);
4240 return SOCKET_ERROR;
4241 default:
4242 status = WSAEOPNOTSUPP;
4243 break;
4246 if (status == WSAEOPNOTSUPP)
4248 status = server_ioctl_sock(s, code, in_buff, in_size, out_buff, out_size, &total,
4249 overlapped, completion);
4250 if (status != WSAEOPNOTSUPP)
4252 if (status == 0 || status == WSA_IO_PENDING)
4253 TRACE("-> %s request\n", debugstr_wsaioctl(code));
4254 else
4255 ERR("-> %s request failed with status 0x%x\n", debugstr_wsaioctl(code), status);
4257 /* overlapped and completion operations will be handled by the server */
4258 completion = NULL;
4259 overlapped = NULL;
4261 else
4262 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code));
4265 if (completion)
4267 FIXME( "completion routine %p not supported\n", completion );
4269 else if (overlapped)
4271 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
4272 overlapped->Internal = status;
4273 overlapped->InternalHigh = total;
4274 if (overlapped->hEvent) NtSetEvent( overlapped->hEvent, NULL );
4275 if (cvalue) WS_AddCompletion( HANDLE2SOCKET(s), cvalue, status, total );
4278 if (!status)
4280 if (ret_size) *ret_size = total;
4281 return 0;
4283 SetLastError( status );
4284 return SOCKET_ERROR;
4288 /***********************************************************************
4289 * ioctlsocket (WS2_32.10)
4291 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
4293 DWORD ret_size;
4294 return WSAIoctl( s, cmd, argp, sizeof(WS_u_long), argp, sizeof(WS_u_long), &ret_size, NULL, NULL );
4297 /***********************************************************************
4298 * listen (WS2_32.13)
4300 int WINAPI WS_listen(SOCKET s, int backlog)
4302 int fd = get_sock_fd( s, FILE_READ_DATA, NULL ), ret = SOCKET_ERROR;
4304 TRACE("socket %04lx, backlog %d\n", s, backlog);
4305 if (fd != -1)
4307 union generic_unix_sockaddr uaddr;
4308 socklen_t uaddrlen = sizeof(uaddr);
4310 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
4312 SetLastError(wsaErrno());
4314 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
4316 SetLastError(WSAEINVAL);
4318 else if (listen(fd, backlog) == 0)
4320 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
4321 FD_WINE_LISTENING,
4322 FD_CONNECT|FD_WINE_CONNECTED);
4323 ret = 0;
4325 else
4326 SetLastError(wsaErrno());
4327 release_sock_fd( s, fd );
4329 else
4330 SetLastError(WSAENOTSOCK);
4331 return ret;
4334 /***********************************************************************
4335 * recv (WS2_32.16)
4337 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
4339 DWORD n, dwFlags = flags;
4340 WSABUF wsabuf;
4342 wsabuf.len = len;
4343 wsabuf.buf = buf;
4345 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
4346 return SOCKET_ERROR;
4347 else
4348 return n;
4351 /***********************************************************************
4352 * recvfrom (WS2_32.17)
4354 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
4355 struct WS_sockaddr *from, int *fromlen)
4357 DWORD n, dwFlags = flags;
4358 WSABUF wsabuf;
4360 wsabuf.len = len;
4361 wsabuf.buf = buf;
4363 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL, NULL) == SOCKET_ERROR )
4364 return SOCKET_ERROR;
4365 else
4366 return n;
4369 /* allocate a poll array for the corresponding fd sets */
4370 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
4371 const WS_fd_set *exceptfds, int *count_ptr )
4373 unsigned int i, j = 0, count = 0;
4374 struct pollfd *fds;
4376 if (readfds) count += readfds->fd_count;
4377 if (writefds) count += writefds->fd_count;
4378 if (exceptfds) count += exceptfds->fd_count;
4379 *count_ptr = count;
4380 if (!count)
4382 SetLastError(WSAEINVAL);
4383 return NULL;
4385 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0]))))
4387 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
4388 return NULL;
4390 if (readfds)
4391 for (i = 0; i < readfds->fd_count; i++, j++)
4393 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
4394 if (fds[j].fd == -1) goto failed;
4395 fds[j].events = POLLIN;
4396 fds[j].revents = 0;
4398 if (writefds)
4399 for (i = 0; i < writefds->fd_count; i++, j++)
4401 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
4402 if (fds[j].fd == -1) goto failed;
4403 fds[j].events = POLLOUT;
4404 fds[j].revents = 0;
4406 if (exceptfds)
4407 for (i = 0; i < exceptfds->fd_count; i++, j++)
4409 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
4410 if (fds[j].fd == -1) goto failed;
4411 fds[j].events = POLLHUP;
4412 fds[j].revents = 0;
4414 return fds;
4416 failed:
4417 count = j;
4418 j = 0;
4419 if (readfds)
4420 for (i = 0; i < readfds->fd_count && j < count; i++, j++)
4421 release_sock_fd( readfds->fd_array[i], fds[j].fd );
4422 if (writefds)
4423 for (i = 0; i < writefds->fd_count && j < count; i++, j++)
4424 release_sock_fd( writefds->fd_array[i], fds[j].fd );
4425 if (exceptfds)
4426 for (i = 0; i < exceptfds->fd_count && j < count; i++, j++)
4427 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
4428 HeapFree( GetProcessHeap(), 0, fds );
4429 return NULL;
4432 /* release the file descriptor obtained in fd_sets_to_poll */
4433 /* must be called with the original fd_set arrays, before calling get_poll_results */
4434 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
4435 const WS_fd_set *exceptfds, struct pollfd *fds )
4437 unsigned int i, j = 0;
4439 if (readfds)
4441 for (i = 0; i < readfds->fd_count; i++, j++)
4442 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
4444 if (writefds)
4446 for (i = 0; i < writefds->fd_count; i++, j++)
4447 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
4449 if (exceptfds)
4451 for (i = 0; i < exceptfds->fd_count; i++, j++)
4452 if (fds[j].fd != -1)
4454 /* make sure we have a real error before releasing the fd */
4455 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
4456 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
4461 /* map the poll results back into the Windows fd sets */
4462 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
4463 const struct pollfd *fds )
4465 const struct pollfd *poll_writefds = fds + (readfds ? readfds->fd_count : 0);
4466 const struct pollfd *poll_exceptfds = poll_writefds + (writefds ? writefds->fd_count : 0);
4467 unsigned int i, k, total = 0;
4469 if (readfds)
4471 for (i = k = 0; i < readfds->fd_count; i++)
4473 if (fds[i].revents ||
4474 (readfds == writefds && (poll_writefds[i].revents & POLLOUT) && !(poll_writefds[i].revents & POLLHUP)) ||
4475 (readfds == exceptfds && poll_exceptfds[i].revents))
4476 readfds->fd_array[k++] = readfds->fd_array[i];
4478 readfds->fd_count = k;
4479 total += k;
4481 if (writefds && writefds != readfds)
4483 for (i = k = 0; i < writefds->fd_count; i++)
4485 if (((poll_writefds[i].revents & POLLOUT) && !(poll_writefds[i].revents & POLLHUP)) ||
4486 (writefds == exceptfds && poll_exceptfds[i].revents))
4487 writefds->fd_array[k++] = writefds->fd_array[i];
4489 writefds->fd_count = k;
4490 total += k;
4492 if (exceptfds && exceptfds != readfds && exceptfds != writefds)
4494 for (i = k = 0; i < exceptfds->fd_count; i++)
4495 if (poll_exceptfds[i].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
4496 exceptfds->fd_count = k;
4497 total += k;
4499 return total;
4503 /***********************************************************************
4504 * select (WS2_32.18)
4506 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
4507 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
4508 const struct WS_timeval* ws_timeout)
4510 struct pollfd *pollfds;
4511 struct timeval tv1, tv2;
4512 int torig = 0;
4513 int count, ret, timeout = -1;
4515 TRACE("read %p, write %p, excp %p timeout %p\n",
4516 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
4518 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )))
4519 return SOCKET_ERROR;
4521 if (ws_timeout)
4523 torig = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
4524 timeout = torig;
4525 gettimeofday( &tv1, 0 );
4528 while ((ret = poll( pollfds, count, timeout )) < 0)
4530 if (errno == EINTR)
4532 if (!ws_timeout) continue;
4533 gettimeofday( &tv2, 0 );
4535 tv2.tv_sec -= tv1.tv_sec;
4536 tv2.tv_usec -= tv1.tv_usec;
4537 if (tv2.tv_usec < 0)
4539 tv2.tv_usec += 1000000;
4540 tv2.tv_sec -= 1;
4543 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
4544 if (timeout <= 0) break;
4545 } else break;
4547 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
4549 if (ret == -1) SetLastError(wsaErrno());
4550 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
4551 HeapFree( GetProcessHeap(), 0, pollfds );
4552 return ret;
4555 /* helper to send completion messages for client-only i/o operation case */
4556 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
4557 ULONG Information )
4559 SERVER_START_REQ( add_fd_completion )
4561 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
4562 req->cvalue = CompletionValue;
4563 req->status = CompletionStatus;
4564 req->information = Information;
4565 wine_server_call( req );
4567 SERVER_END_REQ;
4571 /***********************************************************************
4572 * send (WS2_32.19)
4574 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
4576 DWORD n;
4577 WSABUF wsabuf;
4579 wsabuf.len = len;
4580 wsabuf.buf = (char*) buf;
4582 if ( WS2_sendto( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
4583 return SOCKET_ERROR;
4584 else
4585 return n;
4588 /***********************************************************************
4589 * WSASend (WS2_32.72)
4591 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4592 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4593 LPWSAOVERLAPPED lpOverlapped,
4594 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4596 return WS2_sendto( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
4597 NULL, 0, lpOverlapped, lpCompletionRoutine );
4600 /***********************************************************************
4601 * WSASendDisconnect (WS2_32.73)
4603 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
4605 return WS_shutdown( s, SD_SEND );
4609 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4610 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4611 const struct WS_sockaddr *to, int tolen,
4612 LPWSAOVERLAPPED lpOverlapped,
4613 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4615 unsigned int i, options;
4616 int n, fd, err, overlapped;
4617 struct ws2_async *wsa = NULL, localwsa;
4618 int totalLength = 0;
4619 DWORD bytes_sent;
4620 BOOL is_blocking;
4622 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
4623 s, lpBuffers, dwBufferCount, dwFlags,
4624 to, tolen, lpOverlapped, lpCompletionRoutine);
4626 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
4627 TRACE( "fd=%d, options=%x\n", fd, options );
4629 if ( fd == -1 ) return SOCKET_ERROR;
4631 if (!lpOverlapped && !lpNumberOfBytesSent)
4633 err = WSAEFAULT;
4634 goto error;
4637 overlapped = (lpOverlapped || lpCompletionRoutine) &&
4638 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
4639 if (overlapped || dwBufferCount > 1)
4641 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
4643 err = WSAEFAULT;
4644 goto error;
4647 else
4648 wsa = &localwsa;
4650 wsa->hSocket = SOCKET2HANDLE(s);
4651 wsa->addr = (struct WS_sockaddr *)to;
4652 wsa->addrlen.val = tolen;
4653 wsa->flags = dwFlags;
4654 wsa->lpFlags = &wsa->flags;
4655 wsa->control = NULL;
4656 wsa->n_iovecs = dwBufferCount;
4657 wsa->first_iovec = 0;
4658 for ( i = 0; i < dwBufferCount; i++ )
4660 wsa->iovec[i].iov_base = lpBuffers[i].buf;
4661 wsa->iovec[i].iov_len = lpBuffers[i].len;
4662 totalLength += lpBuffers[i].len;
4665 n = WS2_send( fd, wsa );
4666 if (n == -1 && errno != EAGAIN)
4668 err = wsaErrno();
4669 goto error;
4672 if (overlapped)
4674 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
4675 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
4677 wsa->user_overlapped = lpOverlapped;
4678 wsa->completion_func = lpCompletionRoutine;
4679 release_sock_fd( s, fd );
4681 if (n == -1 || n < totalLength)
4683 iosb->u.Status = STATUS_PENDING;
4684 iosb->Information = n == -1 ? 0 : n;
4686 SERVER_START_REQ( register_async )
4688 req->type = ASYNC_TYPE_WRITE;
4689 req->async.handle = wine_server_obj_handle( wsa->hSocket );
4690 req->async.callback = wine_server_client_ptr( WS2_async_send );
4691 req->async.iosb = wine_server_client_ptr( iosb );
4692 req->async.arg = wine_server_client_ptr( wsa );
4693 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
4694 req->async.cvalue = cvalue;
4695 err = wine_server_call( req );
4697 SERVER_END_REQ;
4699 /* Enable the event only after starting the async. The server will deliver it as soon as
4700 the async is done. */
4701 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
4703 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
4704 SetLastError(NtStatusToWSAError( err ));
4705 return SOCKET_ERROR;
4708 iosb->u.Status = STATUS_SUCCESS;
4709 iosb->Information = n;
4710 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = n;
4711 if (!wsa->completion_func)
4713 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
4714 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
4715 HeapFree( GetProcessHeap(), 0, wsa );
4717 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
4718 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
4719 SetLastError(ERROR_SUCCESS);
4720 return 0;
4723 if ((err = _is_blocking( s, &is_blocking )))
4725 err = NtStatusToWSAError( err );
4726 goto error;
4729 if ( is_blocking )
4731 /* On a blocking non-overlapped stream socket,
4732 * sending blocks until the entire buffer is sent. */
4733 DWORD timeout_start = GetTickCount();
4735 bytes_sent = n == -1 ? 0 : n;
4737 while (wsa->first_iovec < wsa->n_iovecs)
4739 struct pollfd pfd;
4740 int timeout = GET_SNDTIMEO(fd);
4742 if (timeout != -1)
4744 timeout -= GetTickCount() - timeout_start;
4745 if (timeout < 0) timeout = 0;
4748 pfd.fd = fd;
4749 pfd.events = POLLOUT;
4751 if (!timeout || !poll( &pfd, 1, timeout ))
4753 err = WSAETIMEDOUT;
4754 goto error; /* msdn says a timeout in send is fatal */
4757 n = WS2_send( fd, wsa );
4758 if (n == -1 && errno != EAGAIN)
4760 err = wsaErrno();
4761 goto error;
4764 if (n >= 0)
4765 bytes_sent += n;
4768 else /* non-blocking */
4770 if (n < totalLength)
4771 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
4772 if (n == -1)
4774 err = WSAEWOULDBLOCK;
4775 goto error;
4777 bytes_sent = n;
4780 TRACE(" -> %i bytes\n", bytes_sent);
4782 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = bytes_sent;
4783 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
4784 release_sock_fd( s, fd );
4785 SetLastError(ERROR_SUCCESS);
4786 return 0;
4788 error:
4789 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
4790 release_sock_fd( s, fd );
4791 WARN(" -> ERROR %d\n", err);
4792 SetLastError(err);
4793 return SOCKET_ERROR;
4796 /***********************************************************************
4797 * WSASendTo (WS2_32.74)
4799 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4800 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4801 const struct WS_sockaddr *to, int tolen,
4802 LPWSAOVERLAPPED lpOverlapped,
4803 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4805 return WS2_sendto( s, lpBuffers, dwBufferCount,
4806 lpNumberOfBytesSent, dwFlags,
4807 to, tolen,
4808 lpOverlapped, lpCompletionRoutine );
4811 /***********************************************************************
4812 * sendto (WS2_32.20)
4814 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
4815 const struct WS_sockaddr *to, int tolen)
4817 DWORD n;
4818 WSABUF wsabuf;
4820 wsabuf.len = len;
4821 wsabuf.buf = (char*) buf;
4823 if ( WS2_sendto(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
4824 return SOCKET_ERROR;
4825 else
4826 return n;
4829 /***********************************************************************
4830 * setsockopt (WS2_32.21)
4832 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
4833 const char *optval, int optlen)
4835 int fd;
4836 int woptval;
4837 struct linger linger;
4838 struct timeval tval;
4840 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
4841 s, level, optname, optval, optlen);
4843 /* some broken apps pass the value directly instead of a pointer to it */
4844 if(optlen && IS_INTRESOURCE(optval))
4846 SetLastError(WSAEFAULT);
4847 return SOCKET_ERROR;
4850 switch(level)
4852 case WS_SOL_SOCKET:
4853 switch(optname)
4855 /* Some options need some conversion before they can be sent to
4856 * setsockopt. The conversions are done here, then they will fall through
4857 * to the general case. Special options that are not passed to
4858 * setsockopt follow below that.*/
4860 case WS_SO_DONTLINGER:
4861 if (!optval)
4863 SetLastError(WSAEFAULT);
4864 return SOCKET_ERROR;
4866 linger.l_onoff = *(const int*)optval == 0;
4867 linger.l_linger = 0;
4868 level = SOL_SOCKET;
4869 optname = SO_LINGER;
4870 optval = (char*)&linger;
4871 optlen = sizeof(struct linger);
4872 break;
4874 case WS_SO_LINGER:
4875 if (!optval)
4877 SetLastError(WSAEFAULT);
4878 return SOCKET_ERROR;
4880 linger.l_onoff = ((LINGER*)optval)->l_onoff;
4881 linger.l_linger = ((LINGER*)optval)->l_linger;
4882 level = SOL_SOCKET;
4883 optname = SO_LINGER;
4884 optval = (char*)&linger;
4885 optlen = sizeof(struct linger);
4886 break;
4888 case WS_SO_RCVBUF:
4889 if (*(const int*)optval < 2048)
4891 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
4892 return 0;
4894 /* Fall through */
4896 /* The options listed here don't need any special handling. Thanks to
4897 * the conversion happening above, options from there will fall through
4898 * to this, too.*/
4899 case WS_SO_ACCEPTCONN:
4900 case WS_SO_BROADCAST:
4901 case WS_SO_ERROR:
4902 case WS_SO_KEEPALIVE:
4903 case WS_SO_OOBINLINE:
4904 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
4905 * however, using it the BSD way fixes bug 8513 and seems to be what
4906 * most programmers assume, anyway */
4907 case WS_SO_REUSEADDR:
4908 case WS_SO_SNDBUF:
4909 case WS_SO_TYPE:
4910 convert_sockopt(&level, &optname);
4911 break;
4913 /* SO_DEBUG is a privileged operation, ignore it. */
4914 case WS_SO_DEBUG:
4915 TRACE("Ignoring SO_DEBUG\n");
4916 return 0;
4918 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
4919 * socket. According to MSDN, this option is silently ignored.*/
4920 case WS_SO_DONTROUTE:
4921 TRACE("Ignoring SO_DONTROUTE\n");
4922 return 0;
4924 /* Stops two sockets from being bound to the same port. Always happens
4925 * on unix systems, so just drop it. */
4926 case WS_SO_EXCLUSIVEADDRUSE:
4927 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
4928 return 0;
4930 /* After a ConnectEx call succeeds, the socket can't be used with half of the
4931 * normal winsock functions on windows. We don't have that problem. */
4932 case WS_SO_UPDATE_CONNECT_CONTEXT:
4933 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
4934 return 0;
4936 /* After a AcceptEx call succeeds, the socket can't be used with half of the
4937 * normal winsock functions on windows. We don't have that problem. */
4938 case WS_SO_UPDATE_ACCEPT_CONTEXT:
4939 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
4940 return 0;
4942 /* SO_OPENTYPE does not require a valid socket handle. */
4943 case WS_SO_OPENTYPE:
4944 if (!optlen || optlen < sizeof(int) || !optval)
4946 SetLastError(WSAEFAULT);
4947 return SOCKET_ERROR;
4949 get_per_thread_data()->opentype = *(const int *)optval;
4950 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
4951 return 0;
4953 #ifdef SO_RCVTIMEO
4954 case WS_SO_RCVTIMEO:
4955 #endif
4956 #ifdef SO_SNDTIMEO
4957 case WS_SO_SNDTIMEO:
4958 #endif
4959 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
4960 if (optval && optlen == sizeof(UINT32)) {
4961 /* WinSock passes milliseconds instead of struct timeval */
4962 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
4963 tval.tv_sec = *(const UINT32*)optval / 1000;
4964 /* min of 500 milliseconds */
4965 if (tval.tv_sec == 0 && tval.tv_usec && tval.tv_usec < 500000)
4966 tval.tv_usec = 500000;
4967 optlen = sizeof(struct timeval);
4968 optval = (char*)&tval;
4969 } else if (optlen == sizeof(struct timeval)) {
4970 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
4971 } else {
4972 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
4973 return 0;
4975 convert_sockopt(&level, &optname);
4976 break;
4977 #endif
4979 default:
4980 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
4981 SetLastError(WSAENOPROTOOPT);
4982 return SOCKET_ERROR;
4984 break; /* case WS_SOL_SOCKET */
4986 #ifdef HAS_IPX
4987 case WS_NSPROTO_IPX:
4988 switch(optname)
4990 case WS_IPX_PTYPE:
4991 return set_ipx_packettype(s, *(int*)optval);
4993 case WS_IPX_FILTERPTYPE:
4994 /* Sets the receive filter packet type, at the moment we don't support it */
4995 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
4996 /* Returning 0 is better for now than returning a SOCKET_ERROR */
4997 return 0;
4999 default:
5000 FIXME("opt_name:%x\n", optname);
5001 return SOCKET_ERROR;
5003 break; /* case WS_NSPROTO_IPX */
5004 #endif
5006 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
5007 case WS_IPPROTO_TCP:
5008 switch(optname)
5010 case WS_TCP_NODELAY:
5011 convert_sockopt(&level, &optname);
5012 break;
5013 default:
5014 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
5015 return SOCKET_ERROR;
5017 break;
5019 case WS_IPPROTO_IP:
5020 switch(optname)
5022 case WS_IP_ADD_MEMBERSHIP:
5023 case WS_IP_DROP_MEMBERSHIP:
5024 #ifdef IP_HDRINCL
5025 case WS_IP_HDRINCL:
5026 #endif
5027 case WS_IP_MULTICAST_IF:
5028 case WS_IP_MULTICAST_LOOP:
5029 case WS_IP_MULTICAST_TTL:
5030 case WS_IP_OPTIONS:
5031 #ifdef IP_PKTINFO
5032 case WS_IP_PKTINFO:
5033 #endif
5034 case WS_IP_TOS:
5035 case WS_IP_TTL:
5036 #ifdef IP_UNICAST_IF
5037 case WS_IP_UNICAST_IF:
5038 #endif
5039 convert_sockopt(&level, &optname);
5040 break;
5041 case WS_IP_DONTFRAGMENT:
5042 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
5043 return 0;
5044 default:
5045 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
5046 return SOCKET_ERROR;
5048 break;
5050 case WS_IPPROTO_IPV6:
5051 switch(optname)
5053 #ifdef IPV6_ADD_MEMBERSHIP
5054 case WS_IPV6_ADD_MEMBERSHIP:
5055 #endif
5056 #ifdef IPV6_DROP_MEMBERSHIP
5057 case WS_IPV6_DROP_MEMBERSHIP:
5058 #endif
5059 case WS_IPV6_MULTICAST_IF:
5060 case WS_IPV6_MULTICAST_HOPS:
5061 case WS_IPV6_MULTICAST_LOOP:
5062 case WS_IPV6_UNICAST_HOPS:
5063 case WS_IPV6_V6ONLY:
5064 #ifdef IPV6_UNICAST_IF
5065 case WS_IPV6_UNICAST_IF:
5066 #endif
5067 convert_sockopt(&level, &optname);
5068 break;
5069 case WS_IPV6_DONTFRAG:
5070 FIXME("IPV6_DONTFRAG is silently ignored!\n");
5071 return 0;
5072 case WS_IPV6_PROTECTION_LEVEL:
5073 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
5074 return 0;
5075 default:
5076 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
5077 return SOCKET_ERROR;
5079 break;
5081 default:
5082 WARN("Unknown level: 0x%08x\n", level);
5083 SetLastError(WSAEINVAL);
5084 return SOCKET_ERROR;
5085 } /* end switch(level) */
5087 /* avoid endianness issues if argument is a 16-bit int */
5088 if (optval && optlen < sizeof(int))
5090 woptval= *((const INT16 *) optval);
5091 optval= (char*) &woptval;
5092 woptval&= (1 << optlen * 8) - 1;
5093 optlen=sizeof(int);
5095 fd = get_sock_fd( s, 0, NULL );
5096 if (fd == -1) return SOCKET_ERROR;
5098 if (setsockopt(fd, level, optname, optval, optlen) == 0)
5100 #ifdef __APPLE__
5101 if (level == SOL_SOCKET && optname == SO_REUSEADDR &&
5102 setsockopt(fd, level, SO_REUSEPORT, optval, optlen) != 0)
5104 SetLastError(wsaErrno());
5105 release_sock_fd( s, fd );
5106 return SOCKET_ERROR;
5108 #endif
5109 release_sock_fd( s, fd );
5110 return 0;
5112 TRACE("Setting socket error, %d\n", wsaErrno());
5113 SetLastError(wsaErrno());
5114 release_sock_fd( s, fd );
5116 return SOCKET_ERROR;
5119 /***********************************************************************
5120 * shutdown (WS2_32.22)
5122 int WINAPI WS_shutdown(SOCKET s, int how)
5124 int fd, err = WSAENOTSOCK;
5125 unsigned int options, clear_flags = 0;
5127 fd = get_sock_fd( s, 0, &options );
5128 TRACE("socket %04lx, how %i %x\n", s, how, options );
5130 if (fd == -1)
5131 return SOCKET_ERROR;
5133 switch( how )
5135 case SD_RECEIVE: /* drop receives */
5136 clear_flags |= FD_READ;
5137 break;
5138 case SD_SEND: /* drop sends */
5139 clear_flags |= FD_WRITE;
5140 break;
5141 case SD_BOTH: /* drop all */
5142 clear_flags |= FD_READ|FD_WRITE;
5143 /*fall through */
5144 default:
5145 clear_flags |= FD_WINE_LISTENING;
5148 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
5150 switch ( how )
5152 case SD_RECEIVE:
5153 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
5154 break;
5155 case SD_SEND:
5156 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
5157 break;
5158 case SD_BOTH:
5159 default:
5160 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
5161 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
5162 break;
5164 if (err) goto error;
5166 else /* non-overlapped mode */
5168 if ( shutdown( fd, how ) )
5170 err = wsaErrno();
5171 goto error;
5175 release_sock_fd( s, fd );
5176 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
5177 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
5178 return 0;
5180 error:
5181 release_sock_fd( s, fd );
5182 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
5183 SetLastError( err );
5184 return SOCKET_ERROR;
5187 /***********************************************************************
5188 * socket (WS2_32.23)
5190 SOCKET WINAPI WS_socket(int af, int type, int protocol)
5192 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
5194 return WSASocketA( af, type, protocol, NULL, 0,
5195 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
5199 /***********************************************************************
5200 * gethostbyaddr (WS2_32.51)
5202 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
5204 struct WS_hostent *retval = NULL;
5205 struct hostent* host;
5206 int unixtype = convert_af_w2u(type);
5207 const char *paddr = addr;
5208 unsigned long loopback;
5209 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5210 char *extrabuf;
5211 int ebufsize = 1024;
5212 struct hostent hostentry;
5213 int locerr = ENOBUFS;
5214 #endif
5216 /* convert back the magic loopback address if necessary */
5217 if (unixtype == AF_INET && len == 4 && !memcmp(addr, magic_loopback_addr, 4))
5219 loopback = htonl(INADDR_LOOPBACK);
5220 paddr = (char*) &loopback;
5223 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5224 host = NULL;
5225 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
5226 while(extrabuf) {
5227 int res = gethostbyaddr_r(paddr, len, unixtype,
5228 &hostentry, extrabuf, ebufsize, &host, &locerr);
5229 if (res != ERANGE) break;
5230 ebufsize *=2;
5231 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
5233 if (host) retval = WS_dup_he(host);
5234 else SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
5235 HeapFree(GetProcessHeap(),0,extrabuf);
5236 #else
5237 EnterCriticalSection( &csWSgetXXXbyYYY );
5238 host = gethostbyaddr(paddr, len, unixtype);
5239 if (host) retval = WS_dup_he(host);
5240 else SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
5241 LeaveCriticalSection( &csWSgetXXXbyYYY );
5242 #endif
5243 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
5244 return retval;
5247 /***********************************************************************
5248 * WS_compare_routes_by_metric_asc (INTERNAL)
5250 * Comparison function for qsort(), for sorting two routes (struct route)
5251 * by metric in ascending order.
5253 static int WS_compare_routes_by_metric_asc(const void *left, const void *right)
5255 return ((const struct route*)left)->metric - ((const struct route*)right)->metric;
5258 /***********************************************************************
5259 * WS_get_local_ips (INTERNAL)
5261 * Returns the list of local IP addresses by going through the network
5262 * adapters and using the local routing table to sort the addresses
5263 * from highest routing priority to lowest routing priority. This
5264 * functionality is inferred from the description for obtaining local
5265 * IP addresses given in the Knowledge Base Article Q160215.
5267 * Please note that the returned hostent is only freed when the thread
5268 * closes and is replaced if another hostent is requested.
5270 static struct WS_hostent* WS_get_local_ips( char *hostname )
5272 int numroutes = 0, i, j;
5273 DWORD n;
5274 PIP_ADAPTER_INFO adapters = NULL, k;
5275 struct WS_hostent *hostlist = NULL;
5276 PMIB_IPFORWARDTABLE routes = NULL;
5277 struct route *route_addrs = NULL;
5278 DWORD adap_size, route_size;
5280 /* Obtain the size of the adapter list and routing table, also allocate memory */
5281 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
5282 return NULL;
5283 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
5284 return NULL;
5285 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
5286 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
5287 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
5288 if (adapters == NULL || routes == NULL || route_addrs == NULL)
5289 goto cleanup;
5290 /* Obtain the adapter list and the full routing table */
5291 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
5292 goto cleanup;
5293 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
5294 goto cleanup;
5295 /* Store the interface associated with each route */
5296 for (n = 0; n < routes->dwNumEntries; n++)
5298 IF_INDEX ifindex;
5299 DWORD ifmetric;
5300 BOOL exists = FALSE;
5302 if (routes->table[n].u1.ForwardType != MIB_IPROUTE_TYPE_DIRECT)
5303 continue;
5304 ifindex = routes->table[n].dwForwardIfIndex;
5305 ifmetric = routes->table[n].dwForwardMetric1;
5306 /* Only store the lowest valued metric for an interface */
5307 for (j = 0; j < numroutes; j++)
5309 if (route_addrs[j].interface == ifindex)
5311 if (route_addrs[j].metric > ifmetric)
5312 route_addrs[j].metric = ifmetric;
5313 exists = TRUE;
5316 if (exists)
5317 continue;
5318 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
5319 if (route_addrs == NULL)
5320 goto cleanup; /* Memory allocation error, fail gracefully */
5321 route_addrs[numroutes].interface = ifindex;
5322 route_addrs[numroutes].metric = ifmetric;
5323 /* If no IP is found in the next step (for whatever reason)
5324 * then fall back to the magic loopback address.
5326 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
5327 numroutes++;
5329 if (numroutes == 0)
5330 goto cleanup; /* No routes, fall back to the Magic IP */
5331 /* Find the IP address associated with each found interface */
5332 for (i = 0; i < numroutes; i++)
5334 for (k = adapters; k != NULL; k = k->Next)
5336 char *ip = k->IpAddressList.IpAddress.String;
5338 if (route_addrs[i].interface == k->Index)
5339 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
5342 /* Allocate a hostent and enough memory for all the IPs,
5343 * including the NULL at the end of the list.
5345 hostlist = WS_create_he(hostname, 1, 0, numroutes+1, sizeof(struct in_addr));
5346 if (hostlist == NULL)
5347 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
5348 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
5349 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
5350 hostlist->h_addrtype = AF_INET;
5351 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
5352 /* Reorder the entries before placing them in the host list. Windows expects
5353 * the IP list in order from highest priority to lowest (the critical thing
5354 * is that most applications expect the first IP to be the default route).
5356 if (numroutes > 1)
5357 qsort(route_addrs, numroutes, sizeof(struct route), WS_compare_routes_by_metric_asc);
5359 for (i = 0; i < numroutes; i++)
5360 (*(struct in_addr *) hostlist->h_addr_list[i]) = route_addrs[i].addr;
5362 /* Cleanup all allocated memory except the address list,
5363 * the address list is used by the calling app.
5365 cleanup:
5366 HeapFree(GetProcessHeap(), 0, route_addrs);
5367 HeapFree(GetProcessHeap(), 0, adapters);
5368 HeapFree(GetProcessHeap(), 0, routes);
5369 return hostlist;
5372 /***********************************************************************
5373 * gethostbyname (WS2_32.52)
5375 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
5377 struct WS_hostent *retval = NULL;
5378 struct hostent* host;
5379 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5380 char *extrabuf;
5381 int ebufsize=1024;
5382 struct hostent hostentry;
5383 int locerr = ENOBUFS;
5384 #endif
5385 char hostname[100];
5386 if(!num_startup) {
5387 SetLastError(WSANOTINITIALISED);
5388 return NULL;
5390 if( gethostname( hostname, 100) == -1) {
5391 SetLastError(WSAENOBUFS); /* appropriate ? */
5392 return retval;
5394 if( !name || !name[0]) {
5395 name = hostname;
5397 /* If the hostname of the local machine is requested then return the
5398 * complete list of local IP addresses */
5399 if(strcmp(name, hostname) == 0)
5400 retval = WS_get_local_ips(hostname);
5401 /* If any other hostname was requested (or the routing table lookup failed)
5402 * then return the IP found by the host OS */
5403 if(retval == NULL)
5405 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5406 host = NULL;
5407 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
5408 while(extrabuf) {
5409 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
5410 if( res != ERANGE) break;
5411 ebufsize *=2;
5412 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
5414 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
5415 #else
5416 EnterCriticalSection( &csWSgetXXXbyYYY );
5417 host = gethostbyname(name);
5418 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
5419 #endif
5420 if (host) retval = WS_dup_he(host);
5421 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5422 HeapFree(GetProcessHeap(),0,extrabuf);
5423 #else
5424 LeaveCriticalSection( &csWSgetXXXbyYYY );
5425 #endif
5427 if (retval && retval->h_addr_list[0][0] == 127 &&
5428 strcmp(name, "localhost") != 0)
5430 /* hostname != "localhost" but has loopback address. replace by our
5431 * special address.*/
5432 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
5434 TRACE( "%s ret %p\n", debugstr_a(name), retval );
5435 return retval;
5439 /***********************************************************************
5440 * getprotobyname (WS2_32.53)
5442 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
5444 struct WS_protoent* retval = NULL;
5445 #ifdef HAVE_GETPROTOBYNAME
5446 struct protoent* proto;
5447 EnterCriticalSection( &csWSgetXXXbyYYY );
5448 if( (proto = getprotobyname(name)) != NULL )
5450 retval = WS_dup_pe(proto);
5452 else {
5453 MESSAGE("protocol %s not found; You might want to add "
5454 "this to /etc/protocols\n", debugstr_a(name) );
5455 SetLastError(WSANO_DATA);
5457 LeaveCriticalSection( &csWSgetXXXbyYYY );
5458 #endif
5459 TRACE( "%s ret %p\n", debugstr_a(name), retval );
5460 return retval;
5464 /***********************************************************************
5465 * getprotobynumber (WS2_32.54)
5467 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
5469 struct WS_protoent* retval = NULL;
5470 #ifdef HAVE_GETPROTOBYNUMBER
5471 struct protoent* proto;
5472 EnterCriticalSection( &csWSgetXXXbyYYY );
5473 if( (proto = getprotobynumber(number)) != NULL )
5475 retval = WS_dup_pe(proto);
5477 else {
5478 MESSAGE("protocol number %d not found; You might want to add "
5479 "this to /etc/protocols\n", number );
5480 SetLastError(WSANO_DATA);
5482 LeaveCriticalSection( &csWSgetXXXbyYYY );
5483 #endif
5484 TRACE("%i ret %p\n", number, retval);
5485 return retval;
5489 /***********************************************************************
5490 * getservbyname (WS2_32.55)
5492 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
5494 struct WS_servent* retval = NULL;
5495 struct servent* serv;
5496 char *name_str;
5497 char *proto_str = NULL;
5499 if (!(name_str = strdup_lower(name))) return NULL;
5501 if (proto && *proto)
5503 if (!(proto_str = strdup_lower(proto)))
5505 HeapFree( GetProcessHeap(), 0, name_str );
5506 return NULL;
5510 EnterCriticalSection( &csWSgetXXXbyYYY );
5511 serv = getservbyname(name_str, proto_str);
5512 if( serv != NULL )
5514 retval = WS_dup_se(serv);
5516 else SetLastError(WSANO_DATA);
5517 LeaveCriticalSection( &csWSgetXXXbyYYY );
5518 HeapFree( GetProcessHeap(), 0, proto_str );
5519 HeapFree( GetProcessHeap(), 0, name_str );
5520 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
5521 return retval;
5524 /***********************************************************************
5525 * freeaddrinfo (WS2_32.@)
5527 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
5529 while (res) {
5530 struct WS_addrinfo *next;
5532 HeapFree(GetProcessHeap(),0,res->ai_canonname);
5533 HeapFree(GetProcessHeap(),0,res->ai_addr);
5534 next = res->ai_next;
5535 HeapFree(GetProcessHeap(),0,res);
5536 res = next;
5540 /* helper functions for getaddrinfo()/getnameinfo() */
5541 static int convert_aiflag_w2u(int winflags) {
5542 unsigned int i;
5543 int unixflags = 0;
5545 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
5546 if (ws_aiflag_map[i][0] & winflags) {
5547 unixflags |= ws_aiflag_map[i][1];
5548 winflags &= ~ws_aiflag_map[i][0];
5550 if (winflags)
5551 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
5552 return unixflags;
5555 static int convert_niflag_w2u(int winflags) {
5556 unsigned int i;
5557 int unixflags = 0;
5559 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
5560 if (ws_niflag_map[i][0] & winflags) {
5561 unixflags |= ws_niflag_map[i][1];
5562 winflags &= ~ws_niflag_map[i][0];
5564 if (winflags)
5565 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
5566 return unixflags;
5569 static int convert_aiflag_u2w(int unixflags) {
5570 unsigned int i;
5571 int winflags = 0;
5573 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
5574 if (ws_aiflag_map[i][1] & unixflags) {
5575 winflags |= ws_aiflag_map[i][0];
5576 unixflags &= ~ws_aiflag_map[i][1];
5578 if (unixflags) /* will warn usually */
5579 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
5580 return winflags;
5583 static int convert_eai_u2w(int unixret) {
5584 int i;
5586 if (!unixret) return 0;
5588 for (i=0;ws_eai_map[i][0];i++)
5589 if (ws_eai_map[i][1] == unixret)
5590 return ws_eai_map[i][0];
5592 if (unixret == EAI_SYSTEM)
5593 /* There are broken versions of glibc which return EAI_SYSTEM
5594 * and set errno to 0 instead of returning EAI_NONAME.
5596 return errno ? sock_get_error( errno ) : WS_EAI_NONAME;
5598 FIXME("Unhandled unix EAI_xxx ret %d\n", unixret);
5599 return unixret;
5602 static char *get_hostname(void)
5604 char *ret;
5605 DWORD size = 0;
5607 GetComputerNameExA( ComputerNamePhysicalDnsHostname, NULL, &size );
5608 if (GetLastError() != ERROR_MORE_DATA) return NULL;
5609 if (!(ret = HeapAlloc( GetProcessHeap(), 0, size ))) return NULL;
5610 if (!GetComputerNameExA( ComputerNamePhysicalDnsHostname, ret, &size ))
5612 HeapFree( GetProcessHeap(), 0, ret );
5613 return NULL;
5615 return ret;
5618 /***********************************************************************
5619 * getaddrinfo (WS2_32.@)
5621 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
5623 #ifdef HAVE_GETADDRINFO
5624 struct addrinfo *unixaires = NULL;
5625 int result;
5626 struct addrinfo unixhints, *punixhints = NULL;
5627 char *hostname = NULL;
5628 const char *node;
5630 *res = NULL;
5631 if (!nodename && !servname)
5633 SetLastError(WSAHOST_NOT_FOUND);
5634 return WSAHOST_NOT_FOUND;
5637 if (!nodename)
5638 node = NULL;
5639 else if (!nodename[0])
5641 node = hostname = get_hostname();
5642 if (!node) return WSA_NOT_ENOUGH_MEMORY;
5644 else
5645 node = nodename;
5647 /* servname tweak required by OSX and BSD kernels */
5648 if (servname && !servname[0]) servname = "0";
5650 if (hints) {
5651 punixhints = &unixhints;
5653 memset(&unixhints, 0, sizeof(unixhints));
5654 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
5656 /* zero is a wildcard, no need to convert */
5657 if (hints->ai_family)
5658 punixhints->ai_family = convert_af_w2u(hints->ai_family);
5659 if (hints->ai_socktype)
5660 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
5661 if (hints->ai_protocol)
5662 punixhints->ai_protocol = max(convert_proto_w2u(hints->ai_protocol), 0);
5664 if (punixhints->ai_socktype < 0)
5666 SetLastError(WSAESOCKTNOSUPPORT);
5667 HeapFree(GetProcessHeap(), 0, hostname);
5668 return SOCKET_ERROR;
5671 /* windows allows invalid combinations of socket type and protocol, unix does not.
5672 * fix the parameters here to make getaddrinfo call always work */
5673 if (punixhints->ai_protocol == IPPROTO_TCP &&
5674 punixhints->ai_socktype != SOCK_STREAM && punixhints->ai_socktype != SOCK_SEQPACKET)
5675 punixhints->ai_socktype = 0;
5677 else if (punixhints->ai_protocol == IPPROTO_UDP && punixhints->ai_socktype != SOCK_DGRAM)
5678 punixhints->ai_socktype = 0;
5680 else if (IS_IPX_PROTO(punixhints->ai_protocol) && punixhints->ai_socktype != SOCK_DGRAM)
5681 punixhints->ai_socktype = 0;
5684 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
5685 result = getaddrinfo(node, servname, punixhints, &unixaires);
5687 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
5688 HeapFree(GetProcessHeap(), 0, hostname);
5690 if (!result) {
5691 struct addrinfo *xuai = unixaires;
5692 struct WS_addrinfo **xai = res;
5694 *xai = NULL;
5695 while (xuai) {
5696 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
5697 SIZE_T len;
5699 if (!ai)
5700 goto outofmem;
5702 *xai = ai;xai = &ai->ai_next;
5703 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
5704 ai->ai_family = convert_af_u2w(xuai->ai_family);
5705 /* copy whatever was sent in the hints */
5706 if(hints) {
5707 ai->ai_socktype = hints->ai_socktype;
5708 ai->ai_protocol = hints->ai_protocol;
5709 } else {
5710 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
5711 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
5713 if (xuai->ai_canonname) {
5714 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
5715 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
5716 if (!ai->ai_canonname)
5717 goto outofmem;
5718 strcpy(ai->ai_canonname,xuai->ai_canonname);
5720 len = xuai->ai_addrlen;
5721 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
5722 if (!ai->ai_addr)
5723 goto outofmem;
5724 ai->ai_addrlen = len;
5725 do {
5726 int winlen = ai->ai_addrlen;
5728 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
5729 ai->ai_addrlen = winlen;
5730 break;
5732 len = 2*len;
5733 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
5734 if (!ai->ai_addr)
5735 goto outofmem;
5736 ai->ai_addrlen = len;
5737 } while (1);
5738 xuai = xuai->ai_next;
5740 freeaddrinfo(unixaires);
5742 if (TRACE_ON(winsock))
5744 struct WS_addrinfo *ai = *res;
5745 while (ai)
5747 TRACE("=> %p, flags %#x, family %d, type %d, protocol %d, len %ld, name %s, addr %s\n",
5748 ai, ai->ai_flags, ai->ai_family, ai->ai_socktype, ai->ai_protocol, ai->ai_addrlen,
5749 ai->ai_canonname, debugstr_sockaddr(ai->ai_addr));
5750 ai = ai->ai_next;
5753 } else
5754 result = convert_eai_u2w(result);
5756 SetLastError(result);
5757 return result;
5759 outofmem:
5760 if (*res) WS_freeaddrinfo(*res);
5761 if (unixaires) freeaddrinfo(unixaires);
5762 return WSA_NOT_ENOUGH_MEMORY;
5763 #else
5764 FIXME("getaddrinfo() failed, not found during buildtime.\n");
5765 return EAI_FAIL;
5766 #endif
5769 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
5771 struct WS_addrinfoW *ret;
5773 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
5774 ret->ai_flags = ai->ai_flags;
5775 ret->ai_family = ai->ai_family;
5776 ret->ai_socktype = ai->ai_socktype;
5777 ret->ai_protocol = ai->ai_protocol;
5778 ret->ai_addrlen = ai->ai_addrlen;
5779 ret->ai_canonname = NULL;
5780 ret->ai_addr = NULL;
5781 ret->ai_next = NULL;
5782 if (ai->ai_canonname)
5784 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
5785 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
5787 HeapFree(GetProcessHeap(), 0, ret);
5788 return NULL;
5790 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
5792 if (ai->ai_addr)
5794 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, ai->ai_addrlen)))
5796 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
5797 HeapFree(GetProcessHeap(), 0, ret);
5798 return NULL;
5800 memcpy(ret->ai_addr, ai->ai_addr, ai->ai_addrlen);
5802 return ret;
5805 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
5807 struct WS_addrinfoW *ret, *infoW;
5809 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
5810 while (info->ai_next)
5812 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
5814 FreeAddrInfoW(ret);
5815 return NULL;
5817 infoW = infoW->ai_next;
5818 info = info->ai_next;
5820 return ret;
5823 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
5825 struct WS_addrinfo *ret;
5827 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
5828 ret->ai_flags = ai->ai_flags;
5829 ret->ai_family = ai->ai_family;
5830 ret->ai_socktype = ai->ai_socktype;
5831 ret->ai_protocol = ai->ai_protocol;
5832 ret->ai_addrlen = ai->ai_addrlen;
5833 ret->ai_canonname = NULL;
5834 ret->ai_addr = NULL;
5835 ret->ai_next = NULL;
5836 if (ai->ai_canonname)
5838 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
5839 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
5841 HeapFree(GetProcessHeap(), 0, ret);
5842 return NULL;
5844 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
5846 if (ai->ai_addr)
5848 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
5850 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
5851 HeapFree(GetProcessHeap(), 0, ret);
5852 return NULL;
5854 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
5856 return ret;
5859 /***********************************************************************
5860 * GetAddrInfoW (WS2_32.@)
5862 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
5864 int ret, len;
5865 char *nodenameA = NULL, *servnameA = NULL;
5866 struct WS_addrinfo *resA, *hintsA = NULL;
5868 *res = NULL;
5869 if (nodename)
5871 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
5872 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
5873 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
5875 if (servname)
5877 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
5878 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
5880 HeapFree(GetProcessHeap(), 0, nodenameA);
5881 return EAI_MEMORY;
5883 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
5886 if (hints) hintsA = addrinfo_WtoA(hints);
5887 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
5888 WS_freeaddrinfo(hintsA);
5890 if (!ret)
5892 *res = addrinfo_list_AtoW(resA);
5893 WS_freeaddrinfo(resA);
5896 HeapFree(GetProcessHeap(), 0, nodenameA);
5897 HeapFree(GetProcessHeap(), 0, servnameA);
5898 return ret;
5901 /***********************************************************************
5902 * FreeAddrInfoW (WS2_32.@)
5904 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
5906 while (ai)
5908 ADDRINFOW *next;
5909 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
5910 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
5911 next = ai->ai_next;
5912 HeapFree(GetProcessHeap(), 0, ai);
5913 ai = next;
5917 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
5918 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
5920 #ifdef HAVE_GETNAMEINFO
5921 int ret;
5922 union generic_unix_sockaddr sa_u;
5923 unsigned int size;
5925 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
5926 serv, servlen, flags);
5928 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
5929 if (!size)
5931 SetLastError(WSAEFAULT);
5932 return WSA_NOT_ENOUGH_MEMORY;
5934 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
5935 return convert_eai_u2w(ret);
5936 #else
5937 FIXME("getnameinfo() failed, not found during buildtime.\n");
5938 return EAI_FAIL;
5939 #endif
5942 int WINAPI GetNameInfoW(const SOCKADDR *sa, WS_socklen_t salen, PWCHAR host,
5943 DWORD hostlen, PWCHAR serv, DWORD servlen, INT flags)
5945 int ret;
5946 char *hostA = NULL, *servA = NULL;
5948 if (host && (!(hostA = HeapAlloc(GetProcessHeap(), 0, hostlen)))) return EAI_MEMORY;
5949 if (serv && (!(servA = HeapAlloc(GetProcessHeap(), 0, servlen))))
5951 HeapFree(GetProcessHeap(), 0, hostA);
5952 return EAI_MEMORY;
5955 ret = WS_getnameinfo(sa, salen, hostA, hostlen, servA, servlen, flags);
5956 if (!ret)
5958 if (host) MultiByteToWideChar(CP_ACP, 0, hostA, -1, host, hostlen);
5959 if (serv) MultiByteToWideChar(CP_ACP, 0, servA, -1, serv, servlen);
5962 HeapFree(GetProcessHeap(), 0, hostA);
5963 HeapFree(GetProcessHeap(), 0, servA);
5964 return ret;
5967 /***********************************************************************
5968 * getservbyport (WS2_32.56)
5970 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
5972 struct WS_servent* retval = NULL;
5973 #ifdef HAVE_GETSERVBYPORT
5974 struct servent* serv;
5975 char *proto_str = NULL;
5977 if (proto && *proto)
5979 if (!(proto_str = strdup_lower(proto))) return NULL;
5981 EnterCriticalSection( &csWSgetXXXbyYYY );
5982 if( (serv = getservbyport(port, proto_str)) != NULL ) {
5983 retval = WS_dup_se(serv);
5985 else SetLastError(WSANO_DATA);
5986 LeaveCriticalSection( &csWSgetXXXbyYYY );
5987 HeapFree( GetProcessHeap(), 0, proto_str );
5988 #endif
5989 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
5990 return retval;
5994 /***********************************************************************
5995 * gethostname (WS2_32.57)
5997 int WINAPI WS_gethostname(char *name, int namelen)
5999 TRACE("name %p, len %d\n", name, namelen);
6001 if (gethostname(name, namelen) == 0)
6003 TRACE("<- '%s'\n", name);
6004 return 0;
6006 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
6007 TRACE("<- ERROR !\n");
6008 return SOCKET_ERROR;
6012 /* ------------------------------------- Windows sockets extensions -- *
6014 * ------------------------------------------------------------------- */
6016 /***********************************************************************
6017 * WSAEnumNetworkEvents (WS2_32.36)
6019 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
6021 int ret;
6022 int i;
6023 int errors[FD_MAX_EVENTS];
6025 TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
6027 SERVER_START_REQ( get_socket_event )
6029 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6030 req->service = TRUE;
6031 req->c_event = wine_server_obj_handle( hEvent );
6032 wine_server_set_reply( req, errors, sizeof(errors) );
6033 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
6035 SERVER_END_REQ;
6036 if (!ret)
6038 for (i = 0; i < FD_MAX_EVENTS; i++)
6039 lpEvent->iErrorCode[i] = NtStatusToWSAError(errors[i]);
6040 return 0;
6042 SetLastError(WSAEINVAL);
6043 return SOCKET_ERROR;
6046 /***********************************************************************
6047 * WSAEventSelect (WS2_32.39)
6049 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
6051 int ret;
6053 TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
6055 SERVER_START_REQ( set_socket_event )
6057 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6058 req->mask = lEvent;
6059 req->event = wine_server_obj_handle( hEvent );
6060 req->window = 0;
6061 req->msg = 0;
6062 ret = wine_server_call( req );
6064 SERVER_END_REQ;
6065 if (!ret) return 0;
6066 SetLastError(WSAEINVAL);
6067 return SOCKET_ERROR;
6070 /**********************************************************************
6071 * WSAGetOverlappedResult (WS2_32.40)
6073 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
6074 LPDWORD lpcbTransfer, BOOL fWait,
6075 LPDWORD lpdwFlags )
6077 NTSTATUS status;
6079 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
6080 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
6082 if ( lpOverlapped == NULL )
6084 ERR( "Invalid pointer\n" );
6085 SetLastError(WSA_INVALID_PARAMETER);
6086 return FALSE;
6089 status = lpOverlapped->Internal;
6090 if (status == STATUS_PENDING)
6092 if (!fWait)
6094 SetLastError( WSA_IO_INCOMPLETE );
6095 return FALSE;
6098 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
6099 INFINITE ) == WAIT_FAILED)
6100 return FALSE;
6101 status = lpOverlapped->Internal;
6104 if ( lpcbTransfer )
6105 *lpcbTransfer = lpOverlapped->InternalHigh;
6107 if ( lpdwFlags )
6108 *lpdwFlags = lpOverlapped->u.s.Offset;
6110 if (status) SetLastError( RtlNtStatusToDosError(status) );
6111 return !status;
6115 /***********************************************************************
6116 * WSAAsyncSelect (WS2_32.101)
6118 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
6120 int ret;
6122 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
6124 SERVER_START_REQ( set_socket_event )
6126 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6127 req->mask = lEvent;
6128 req->event = 0;
6129 req->window = wine_server_user_handle( hWnd );
6130 req->msg = uMsg;
6131 ret = wine_server_call( req );
6133 SERVER_END_REQ;
6134 if (!ret) return 0;
6135 SetLastError(WSAEINVAL);
6136 return SOCKET_ERROR;
6139 /***********************************************************************
6140 * WSACreateEvent (WS2_32.31)
6143 WSAEVENT WINAPI WSACreateEvent(void)
6145 /* Create a manual-reset event, with initial state: unsignaled */
6146 TRACE("\n");
6148 return CreateEventW(NULL, TRUE, FALSE, NULL);
6151 /***********************************************************************
6152 * WSACloseEvent (WS2_32.29)
6155 BOOL WINAPI WSACloseEvent(WSAEVENT event)
6157 TRACE ("event=%p\n", event);
6159 return CloseHandle(event);
6162 /***********************************************************************
6163 * WSASocketA (WS2_32.78)
6166 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
6167 LPWSAPROTOCOL_INFOA lpProtocolInfo,
6168 GROUP g, DWORD dwFlags)
6170 INT len;
6171 WSAPROTOCOL_INFOW info;
6173 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
6174 af, type, protocol, lpProtocolInfo, g, dwFlags);
6176 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
6178 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
6179 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
6180 info.szProtocol, WSAPROTOCOL_LEN + 1);
6182 if (!len)
6184 SetLastError(WSAEINVAL);
6185 return SOCKET_ERROR;
6188 return WSASocketW(af, type, protocol, &info, g, dwFlags);
6191 /***********************************************************************
6192 * WSASocketW (WS2_32.79)
6195 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
6196 LPWSAPROTOCOL_INFOW lpProtocolInfo,
6197 GROUP g, DWORD dwFlags)
6199 SOCKET ret;
6200 DWORD err;
6201 int unixaf, unixtype, ipxptype = -1;
6204 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
6205 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
6208 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
6209 af, type, protocol, lpProtocolInfo, g, dwFlags );
6211 if (!num_startup)
6213 err = WSANOTINITIALISED;
6214 goto done;
6217 /* hack for WSADuplicateSocket */
6218 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
6219 ret = lpProtocolInfo->dwServiceFlags3;
6220 TRACE("\tgot duplicate %04lx\n", ret);
6221 return ret;
6224 if (lpProtocolInfo)
6226 if (af == FROM_PROTOCOL_INFO || !af)
6227 af = lpProtocolInfo->iAddressFamily;
6228 if (type == FROM_PROTOCOL_INFO || !type)
6229 type = lpProtocolInfo->iSocketType;
6230 if (protocol == FROM_PROTOCOL_INFO || !protocol)
6231 protocol = lpProtocolInfo->iProtocol;
6234 if (!type && (af || protocol))
6236 int autoproto = protocol;
6237 WSAPROTOCOL_INFOW infow;
6239 /* default to the first valid protocol */
6240 if (!autoproto)
6241 autoproto = valid_protocols[0];
6242 else if(IS_IPX_PROTO(autoproto))
6243 autoproto = WS_NSPROTO_IPX;
6245 if (WS_EnterSingleProtocolW(autoproto, &infow))
6247 type = infow.iSocketType;
6249 /* after win2003 it's no longer possible to pass AF_UNSPEC
6250 using the protocol info struct */
6251 if (!lpProtocolInfo && af == WS_AF_UNSPEC)
6252 af = infow.iAddressFamily;
6257 Windows has an extension to the IPX protocol that allows one to create sockets
6258 and set the IPX packet type at the same time, to do that a caller will use
6259 a protocol like NSPROTO_IPX + <PACKET TYPE>
6261 if (IS_IPX_PROTO(protocol))
6262 ipxptype = protocol - WS_NSPROTO_IPX;
6264 /* convert the socket family, type and protocol */
6265 unixaf = convert_af_w2u(af);
6266 unixtype = convert_socktype_w2u(type);
6267 protocol = convert_proto_w2u(protocol);
6268 if (unixaf == AF_UNSPEC) unixaf = -1;
6270 /* filter invalid parameters */
6271 if (protocol < 0)
6273 /* the type could not be converted */
6274 if (type && unixtype < 0)
6276 err = WSAESOCKTNOSUPPORT;
6277 goto done;
6280 err = WSAEPROTONOSUPPORT;
6281 goto done;
6283 if (unixaf < 0)
6285 /* both family and protocol can't be invalid */
6286 if (protocol <= 0)
6288 err = WSAEINVAL;
6289 goto done;
6292 /* family could not be converted and neither socket type */
6293 if (unixtype < 0 && af >= 0)
6296 err = WSAESOCKTNOSUPPORT;
6297 goto done;
6300 err = WSAEAFNOSUPPORT;
6301 goto done;
6304 SERVER_START_REQ( create_socket )
6306 req->family = unixaf;
6307 req->type = unixtype;
6308 req->protocol = protocol;
6309 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
6310 req->attributes = OBJ_INHERIT;
6311 req->flags = dwFlags;
6312 set_error( wine_server_call( req ) );
6313 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
6315 SERVER_END_REQ;
6316 if (ret)
6318 TRACE("\tcreated %04lx\n", ret );
6319 if (ipxptype > 0)
6320 set_ipx_packettype(ret, ipxptype);
6321 return ret;
6324 err = GetLastError();
6325 if (err == WSAEACCES) /* raw socket denied */
6327 if (type == SOCK_RAW)
6328 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
6329 else
6330 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
6332 else
6334 /* invalid combination of valid parameters, like SOCK_STREAM + IPPROTO_UDP */
6335 if (err == WSAEINVAL)
6336 err = WSAESOCKTNOSUPPORT;
6337 else if (err == WSAEOPNOTSUPP)
6338 err = WSAEPROTONOSUPPORT;
6341 done:
6342 WARN("\t\tfailed, error %d!\n", err);
6343 SetLastError(err);
6344 return INVALID_SOCKET;
6347 /***********************************************************************
6348 * WSAJoinLeaf (WS2_32.58)
6351 SOCKET WINAPI WSAJoinLeaf(
6352 SOCKET s,
6353 const struct WS_sockaddr *addr,
6354 int addrlen,
6355 LPWSABUF lpCallerData,
6356 LPWSABUF lpCalleeData,
6357 LPQOS lpSQOS,
6358 LPQOS lpGQOS,
6359 DWORD dwFlags)
6361 FIXME("stub.\n");
6362 return INVALID_SOCKET;
6365 /***********************************************************************
6366 * __WSAFDIsSet (WS2_32.151)
6368 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
6370 int i = set->fd_count, ret = 0;
6372 while (i--)
6373 if (set->fd_array[i] == s)
6375 ret = 1;
6376 break;
6379 TRACE("(socket %04lx, fd_set %p, count %i) <- %d\n", s, set, set->fd_count, ret);
6380 return ret;
6383 /***********************************************************************
6384 * WSAIsBlocking (WS2_32.114)
6386 BOOL WINAPI WSAIsBlocking(void)
6388 /* By default WinSock should set all its sockets to non-blocking mode
6389 * and poll in PeekMessage loop when processing "blocking" ones. This
6390 * function is supposed to tell if the program is in this loop. Our
6391 * blocking calls are truly blocking so we always return FALSE.
6393 * Note: It is allowed to call this function without prior WSAStartup().
6396 TRACE("\n");
6397 return FALSE;
6400 /***********************************************************************
6401 * WSACancelBlockingCall (WS2_32.113)
6403 INT WINAPI WSACancelBlockingCall(void)
6405 TRACE("\n");
6406 return 0;
6409 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
6411 FIXME("How was this called?\n");
6412 return x();
6416 /***********************************************************************
6417 * WSASetBlockingHook (WS2_32.109)
6419 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
6421 FARPROC prev = blocking_hook;
6422 blocking_hook = lpBlockFunc;
6423 TRACE("hook %p\n", lpBlockFunc);
6424 return prev;
6428 /***********************************************************************
6429 * WSAUnhookBlockingHook (WS2_32.110)
6431 INT WINAPI WSAUnhookBlockingHook(void)
6433 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
6434 return 0;
6438 /* ----------------------------------- end of API stuff */
6440 /* ----------------------------------- helper functions -
6442 * TODO: Merge WS_dup_..() stuff into one function that
6443 * would operate with a generic structure containing internal
6444 * pointers (via a template of some kind).
6447 static int list_size(char** l, int item_size)
6449 int i,j = 0;
6450 if(l)
6451 { for(i=0;l[i];i++)
6452 j += (item_size) ? item_size : strlen(l[i]) + 1;
6453 j += (i + 1) * sizeof(char*); }
6454 return j;
6457 static int list_dup(char** l_src, char** l_to, int item_size)
6459 char *p;
6460 int i;
6462 for (i = 0; l_src[i]; i++) ;
6463 p = (char *)(l_to + i + 1);
6464 for (i = 0; l_src[i]; i++)
6466 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
6467 memcpy(p, l_src[i], count);
6468 l_to[i] = p;
6469 p += count;
6471 l_to[i] = NULL;
6472 return p - (char *)l_to;
6475 /* ----- hostent */
6477 /* create a hostent entry
6479 * Creates the entry with enough memory for the name, aliases
6480 * addresses, and the address pointers. Also copies the name
6481 * and sets up all the pointers.
6483 * NOTE: The alias and address lists must be allocated with room
6484 * for the NULL item terminating the list. This is true even if
6485 * the list has no items ("aliases" and "addresses" must be
6486 * at least "1", a truly empty list is invalid).
6488 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length)
6490 struct WS_hostent *p_to;
6491 char *p;
6492 int size = (sizeof(struct WS_hostent) +
6493 strlen(name) + 1 +
6494 sizeof(char *) * aliases +
6495 aliases_size +
6496 sizeof(char *) * addresses +
6497 address_length * (addresses - 1)), i;
6499 if (!(p_to = check_buffer_he(size))) return NULL;
6500 memset(p_to, 0, size);
6502 /* Use the memory in the same way winsock does.
6503 * First set the pointer for aliases, second set the pointers for addresses.
6504 * Third fill the addresses indexes, fourth jump aliases names size.
6505 * Fifth fill the hostname.
6506 * NOTE: This method is valid for OS version's >= XP.
6508 p = (char *)(p_to + 1);
6509 p_to->h_aliases = (char **)p;
6510 p += sizeof(char *)*aliases;
6512 p_to->h_addr_list = (char **)p;
6513 p += sizeof(char *)*addresses;
6515 for (i = 0, addresses--; i < addresses; i++, p += address_length)
6516 p_to->h_addr_list[i] = p;
6518 /* NOTE: h_aliases must be filled in manually because we don't know each string
6519 * size, leave these pointers NULL (already set to NULL by memset earlier).
6521 p += aliases_size;
6523 p_to->h_name = p;
6524 strcpy(p, name);
6526 return p_to;
6529 /* duplicate hostent entry
6530 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
6531 * Ditto for protoent and servent.
6533 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
6535 int i, addresses = 0, alias_size = 0;
6536 struct WS_hostent *p_to;
6537 char *p;
6539 for( i = 0; p_he->h_aliases[i]; i++) alias_size += strlen(p_he->h_aliases[i]) + 1;
6540 while (p_he->h_addr_list[addresses]) addresses++;
6542 p_to = WS_create_he(p_he->h_name, i + 1, alias_size, addresses + 1, p_he->h_length);
6544 if (!p_to) return NULL;
6545 p_to->h_addrtype = convert_af_u2w(p_he->h_addrtype);
6546 p_to->h_length = p_he->h_length;
6548 for(i = 0, p = p_to->h_addr_list[0]; p_he->h_addr_list[i]; i++, p += p_to->h_length)
6549 memcpy(p, p_he->h_addr_list[i], p_to->h_length);
6551 /* Fill the aliases after the IP data */
6552 for(i = 0; p_he->h_aliases[i]; i++)
6554 p_to->h_aliases[i] = p;
6555 strcpy(p, p_he->h_aliases[i]);
6556 p += strlen(p) + 1;
6559 return p_to;
6562 /* ----- protoent */
6564 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
6566 char *p;
6567 struct WS_protoent *p_to;
6569 int size = (sizeof(*p_pe) +
6570 strlen(p_pe->p_name) + 1 +
6571 list_size(p_pe->p_aliases, 0));
6573 if (!(p_to = check_buffer_pe(size))) return NULL;
6574 p_to->p_proto = p_pe->p_proto;
6576 p = (char *)(p_to + 1);
6577 p_to->p_name = p;
6578 strcpy(p, p_pe->p_name);
6579 p += strlen(p) + 1;
6581 p_to->p_aliases = (char **)p;
6582 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
6583 return p_to;
6586 /* ----- servent */
6588 static struct WS_servent *WS_dup_se(const struct servent* p_se)
6590 char *p;
6591 struct WS_servent *p_to;
6593 int size = (sizeof(*p_se) +
6594 strlen(p_se->s_proto) + 1 +
6595 strlen(p_se->s_name) + 1 +
6596 list_size(p_se->s_aliases, 0));
6598 if (!(p_to = check_buffer_se(size))) return NULL;
6599 p_to->s_port = p_se->s_port;
6601 p = (char *)(p_to + 1);
6602 p_to->s_name = p;
6603 strcpy(p, p_se->s_name);
6604 p += strlen(p) + 1;
6606 p_to->s_proto = p;
6607 strcpy(p, p_se->s_proto);
6608 p += strlen(p) + 1;
6610 p_to->s_aliases = (char **)p;
6611 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
6612 return p_to;
6616 /***********************************************************************
6617 * WSARecv (WS2_32.67)
6619 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6620 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
6621 LPWSAOVERLAPPED lpOverlapped,
6622 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
6624 return WS2_recv_base(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
6625 NULL, NULL, lpOverlapped, lpCompletionRoutine, NULL);
6628 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6629 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
6630 struct WS_sockaddr *lpFrom,
6631 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
6632 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
6633 LPWSABUF lpControlBuffer )
6635 unsigned int i, options;
6636 int n, fd, err, overlapped;
6637 struct ws2_async *wsa, localwsa;
6638 BOOL is_blocking;
6639 DWORD timeout_start = GetTickCount();
6640 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
6642 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
6643 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
6644 (lpFromlen ? *lpFromlen : -1),
6645 lpOverlapped, lpCompletionRoutine);
6647 fd = get_sock_fd( s, FILE_READ_DATA, &options );
6648 TRACE( "fd=%d, options=%x\n", fd, options );
6650 if (fd == -1) return SOCKET_ERROR;
6652 overlapped = (lpOverlapped || lpCompletionRoutine) &&
6653 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
6654 if (overlapped || dwBufferCount > 1)
6656 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
6658 err = WSAEFAULT;
6659 goto error;
6662 else
6663 wsa = &localwsa;
6665 wsa->hSocket = SOCKET2HANDLE(s);
6666 wsa->flags = *lpFlags;
6667 wsa->lpFlags = lpFlags;
6668 wsa->addr = lpFrom;
6669 wsa->addrlen.ptr = lpFromlen;
6670 wsa->control = lpControlBuffer;
6671 wsa->n_iovecs = dwBufferCount;
6672 wsa->first_iovec = 0;
6673 for (i = 0; i < dwBufferCount; i++)
6675 /* check buffer first to trigger write watches */
6676 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
6678 err = WSAEFAULT;
6679 goto error;
6681 wsa->iovec[i].iov_base = lpBuffers[i].buf;
6682 wsa->iovec[i].iov_len = lpBuffers[i].len;
6685 for (;;)
6687 n = WS2_recv( fd, wsa );
6688 if (n == -1)
6690 if (errno != EAGAIN)
6692 int loc_errno = errno;
6693 err = wsaErrno();
6694 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
6695 goto error;
6698 else if (lpNumberOfBytesRecvd) *lpNumberOfBytesRecvd = n;
6700 if (overlapped)
6702 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
6704 wsa->user_overlapped = lpOverlapped;
6705 wsa->completion_func = lpCompletionRoutine;
6706 release_sock_fd( s, fd );
6708 if (n == -1)
6710 iosb->u.Status = STATUS_PENDING;
6711 iosb->Information = 0;
6713 SERVER_START_REQ( register_async )
6715 req->type = ASYNC_TYPE_READ;
6716 req->async.handle = wine_server_obj_handle( wsa->hSocket );
6717 req->async.callback = wine_server_client_ptr( WS2_async_recv );
6718 req->async.iosb = wine_server_client_ptr( iosb );
6719 req->async.arg = wine_server_client_ptr( wsa );
6720 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
6721 req->async.cvalue = cvalue;
6722 err = wine_server_call( req );
6724 SERVER_END_REQ;
6726 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
6727 SetLastError(NtStatusToWSAError( err ));
6728 return SOCKET_ERROR;
6731 iosb->u.Status = STATUS_SUCCESS;
6732 iosb->Information = n;
6733 if (!wsa->completion_func)
6735 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
6736 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
6737 HeapFree( GetProcessHeap(), 0, wsa );
6739 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
6740 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
6741 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6742 return 0;
6745 if (n != -1) break;
6747 if ((err = _is_blocking( s, &is_blocking )))
6749 err = NtStatusToWSAError( err );
6750 goto error;
6753 if ( is_blocking )
6755 struct pollfd pfd;
6756 int timeout = GET_RCVTIMEO(fd);
6757 if (timeout != -1)
6759 timeout -= GetTickCount() - timeout_start;
6760 if (timeout < 0) timeout = 0;
6763 pfd.fd = fd;
6764 pfd.events = POLLIN;
6765 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
6767 if (!timeout || !poll( &pfd, 1, timeout ))
6769 err = WSAETIMEDOUT;
6770 /* a timeout is not fatal */
6771 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6772 goto error;
6775 else
6777 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6778 err = WSAEWOULDBLOCK;
6779 goto error;
6783 TRACE(" -> %i bytes\n", n);
6784 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
6785 release_sock_fd( s, fd );
6786 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6787 SetLastError(ERROR_SUCCESS);
6789 return 0;
6791 error:
6792 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
6793 release_sock_fd( s, fd );
6794 WARN(" -> ERROR %d\n", err);
6795 SetLastError( err );
6796 return SOCKET_ERROR;
6799 /***********************************************************************
6800 * WSARecvFrom (WS2_32.69)
6802 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6803 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
6804 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
6805 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
6808 return WS2_recv_base( s, lpBuffers, dwBufferCount,
6809 lpNumberOfBytesRecvd, lpFlags,
6810 lpFrom, lpFromlen,
6811 lpOverlapped, lpCompletionRoutine, NULL );
6814 /***********************************************************************
6815 * WSCInstallProvider (WS2_32.88)
6817 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
6818 LPCWSTR lpszProviderDllPath,
6819 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
6820 DWORD dwNumberOfEntries,
6821 LPINT lpErrno )
6823 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
6824 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
6825 dwNumberOfEntries, lpErrno);
6826 *lpErrno = 0;
6827 return 0;
6831 /***********************************************************************
6832 * WSCDeinstallProvider (WS2_32.83)
6834 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
6836 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
6837 *lpErrno = 0;
6838 return 0;
6842 /***********************************************************************
6843 * WSAAccept (WS2_32.26)
6845 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
6846 LPCONDITIONPROC lpfnCondition, DWORD_PTR dwCallbackData)
6849 int ret = 0, size;
6850 WSABUF CallerId, CallerData, CalleeId, CalleeData;
6851 /* QOS SQOS, GQOS; */
6852 GROUP g;
6853 SOCKET cs;
6854 SOCKADDR src_addr, dst_addr;
6856 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
6857 s, addr, addrlen, lpfnCondition, dwCallbackData);
6859 cs = WS_accept(s, addr, addrlen);
6860 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
6861 if (!lpfnCondition) return cs;
6863 if (addr && addrlen)
6865 CallerId.buf = (char *)addr;
6866 CallerId.len = *addrlen;
6868 else
6870 size = sizeof(src_addr);
6871 WS_getpeername(cs, &src_addr, &size);
6872 CallerId.buf = (char *)&src_addr;
6873 CallerId.len = size;
6875 CallerData.buf = NULL;
6876 CallerData.len = 0;
6878 size = sizeof(dst_addr);
6879 WS_getsockname(cs, &dst_addr, &size);
6881 CalleeId.buf = (char *)&dst_addr;
6882 CalleeId.len = sizeof(dst_addr);
6884 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
6885 &CalleeId, &CalleeData, &g, dwCallbackData);
6887 switch (ret)
6889 case CF_ACCEPT:
6890 return cs;
6891 case CF_DEFER:
6892 SERVER_START_REQ( set_socket_deferred )
6894 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6895 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
6896 if ( !wine_server_call_err ( req ) )
6898 SetLastError( WSATRY_AGAIN );
6899 WS_closesocket( cs );
6902 SERVER_END_REQ;
6903 return SOCKET_ERROR;
6904 case CF_REJECT:
6905 WS_closesocket(cs);
6906 SetLastError(WSAECONNREFUSED);
6907 return SOCKET_ERROR;
6908 default:
6909 FIXME("Unknown return type from Condition function\n");
6910 SetLastError(WSAENOTSOCK);
6911 return SOCKET_ERROR;
6915 /***********************************************************************
6916 * WSADuplicateSocketA (WS2_32.32)
6918 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
6920 return WS_DuplicateSocket(FALSE, s, dwProcessId, (LPWSAPROTOCOL_INFOW) lpProtocolInfo);
6923 /***********************************************************************
6924 * WSADuplicateSocketW (WS2_32.33)
6926 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
6928 return WS_DuplicateSocket(TRUE, s, dwProcessId, lpProtocolInfo);
6931 /***********************************************************************
6932 * WSAInstallServiceClassA (WS2_32.48)
6934 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
6936 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
6937 SetLastError(WSAEACCES);
6938 return SOCKET_ERROR;
6941 /***********************************************************************
6942 * WSAInstallServiceClassW (WS2_32.49)
6944 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
6946 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
6947 SetLastError(WSAEACCES);
6948 return SOCKET_ERROR;
6951 /***********************************************************************
6952 * WSARemoveServiceClass (WS2_32.70)
6954 int WINAPI WSARemoveServiceClass(LPGUID info)
6956 FIXME("Request to remove service %p\n",info);
6957 SetLastError(WSATYPE_NOT_FOUND);
6958 return SOCKET_ERROR;
6961 /***********************************************************************
6962 * inet_ntop (WS2_32.@)
6964 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
6966 #ifdef HAVE_INET_NTOP
6967 struct WS_in6_addr *in6;
6968 struct WS_in_addr *in;
6969 PCSTR pdst;
6971 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
6972 if (!buffer)
6974 SetLastError( STATUS_INVALID_PARAMETER );
6975 return NULL;
6978 switch (family)
6980 case WS_AF_INET:
6982 in = addr;
6983 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
6984 break;
6986 case WS_AF_INET6:
6988 in6 = addr;
6989 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
6990 break;
6992 default:
6993 SetLastError( WSAEAFNOSUPPORT );
6994 return NULL;
6997 if (!pdst) SetLastError( STATUS_INVALID_PARAMETER );
6998 return pdst;
6999 #else
7000 FIXME( "not supported on this platform\n" );
7001 SetLastError( WSAEAFNOSUPPORT );
7002 return NULL;
7003 #endif
7006 /***********************************************************************
7007 * inet_pton (WS2_32.@)
7009 INT WINAPI WS_inet_pton( INT family, PCSTR addr, PVOID buffer)
7011 #ifdef HAVE_INET_PTON
7012 int unixaf, ret;
7014 TRACE("family %d, addr '%s', buffer (%p)\n", family, addr ? addr : "(null)", buffer);
7016 if (!addr || !buffer)
7018 SetLastError(WSAEFAULT);
7019 return SOCKET_ERROR;
7022 unixaf = convert_af_w2u(family);
7023 if (unixaf != AF_INET && unixaf != AF_INET6)
7025 SetLastError(WSAEAFNOSUPPORT);
7026 return SOCKET_ERROR;
7029 ret = inet_pton(unixaf, addr, buffer);
7030 if (ret == -1) SetLastError(wsaErrno());
7031 return ret;
7032 #else
7033 FIXME( "not supported on this platform\n" );
7034 SetLastError( WSAEAFNOSUPPORT );
7035 return SOCKET_ERROR;
7036 #endif
7040 /***********************************************************************
7041 * WSAStringToAddressA (WS2_32.80)
7043 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
7044 INT AddressFamily,
7045 LPWSAPROTOCOL_INFOA lpProtocolInfo,
7046 LPSOCKADDR lpAddress,
7047 LPINT lpAddressLength)
7049 INT res=0;
7050 LPSTR workBuffer=NULL,ptrPort;
7052 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
7053 lpProtocolInfo, lpAddress, lpAddressLength );
7055 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
7057 if (!AddressString)
7059 SetLastError(WSAEINVAL);
7060 return SOCKET_ERROR;
7063 if (lpProtocolInfo)
7064 FIXME("ProtocolInfo not implemented.\n");
7066 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
7067 strlen(AddressString) + 1);
7068 if (!workBuffer)
7070 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7071 return SOCKET_ERROR;
7074 strcpy(workBuffer, AddressString);
7076 switch(AddressFamily)
7078 case WS_AF_INET:
7080 struct in_addr inetaddr;
7082 /* If lpAddressLength is too small, tell caller the size we need */
7083 if (*lpAddressLength < sizeof(SOCKADDR_IN))
7085 *lpAddressLength = sizeof(SOCKADDR_IN);
7086 res = WSAEFAULT;
7087 break;
7089 *lpAddressLength = sizeof(SOCKADDR_IN);
7090 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
7092 ((LPSOCKADDR_IN)lpAddress)->sin_family = WS_AF_INET;
7094 ptrPort = strchr(workBuffer, ':');
7095 if(ptrPort)
7097 /* User may have entered an IPv6 and asked to parse as IPv4 */
7098 if(strchr(ptrPort + 1, ':'))
7100 res = WSAEINVAL;
7101 break;
7103 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
7104 *ptrPort = '\0';
7106 else
7108 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
7111 if(inet_aton(workBuffer, &inetaddr) > 0)
7113 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
7114 res = 0;
7116 else
7117 res = WSAEINVAL;
7119 break;
7122 case WS_AF_INET6:
7124 struct in6_addr inetaddr;
7125 /* If lpAddressLength is too small, tell caller the size we need */
7126 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
7128 *lpAddressLength = sizeof(SOCKADDR_IN6);
7129 res = WSAEFAULT;
7130 break;
7132 #ifdef HAVE_INET_PTON
7133 *lpAddressLength = sizeof(SOCKADDR_IN6);
7134 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
7136 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
7138 /* This one is a bit tricky. An IPv6 address contains colons, so the
7139 * check from IPv4 doesn't work like that. However, IPv6 addresses that
7140 * contain a port are written with braces like [fd12:3456:7890::1]:12345
7141 * so what we will do is to look for ']', check if the next char is a
7142 * colon, and if it is, parse the port as in IPv4. */
7144 ptrPort = strchr(workBuffer, ']');
7145 if(ptrPort && *(++ptrPort) == ':')
7147 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort+1));
7148 *ptrPort = '\0';
7150 else
7152 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
7155 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
7157 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
7158 sizeof(struct in6_addr));
7159 res = 0;
7161 else
7162 #endif /* HAVE_INET_PTON */
7163 res = WSAEINVAL;
7165 break;
7167 default:
7168 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
7169 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
7170 res = WSAEINVAL;
7173 HeapFree(GetProcessHeap(), 0, workBuffer);
7175 if (!res) return 0;
7176 SetLastError(res);
7177 return SOCKET_ERROR;
7180 /***********************************************************************
7181 * WSAStringToAddressW (WS2_32.81)
7183 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
7184 * If this should be the case, it would be required to map these digits
7185 * to Unicode digits (0-9) using FoldString first.
7187 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
7188 INT AddressFamily,
7189 LPWSAPROTOCOL_INFOW lpProtocolInfo,
7190 LPSOCKADDR lpAddress,
7191 LPINT lpAddressLength)
7193 INT sBuffer,res=0;
7194 LPSTR workBuffer=NULL;
7195 WSAPROTOCOL_INFOA infoA;
7196 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
7198 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
7199 lpAddress, lpAddressLength );
7201 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
7203 /* if ProtocolInfo is available - convert to ANSI variant */
7204 if (lpProtocolInfo)
7206 lpProtoInfoA = &infoA;
7207 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
7209 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
7210 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
7212 SetLastError(WSAEINVAL);
7213 return SOCKET_ERROR;
7217 if (AddressString)
7219 /* Translate AddressString to ANSI code page - assumes that only
7220 standard digits 0-9 are used with this API call */
7221 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
7222 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
7224 if (workBuffer)
7226 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
7227 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
7228 lpAddress,lpAddressLength);
7229 HeapFree( GetProcessHeap(), 0, workBuffer );
7230 return res;
7232 else
7233 res = WSA_NOT_ENOUGH_MEMORY;
7235 else
7236 res = WSAEINVAL;
7238 SetLastError(res);
7239 return SOCKET_ERROR;
7242 /***********************************************************************
7243 * WSAAddressToStringA (WS2_32.27)
7245 * See WSAAddressToStringW
7247 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
7248 LPWSAPROTOCOL_INFOA info, LPSTR string,
7249 LPDWORD lenstr )
7251 DWORD size;
7252 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
7253 CHAR *p;
7255 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
7257 if (!sockaddr) return SOCKET_ERROR;
7258 if (!string || !lenstr) return SOCKET_ERROR;
7260 switch(sockaddr->sa_family)
7262 case WS_AF_INET:
7263 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
7264 sprintf( buffer, "%u.%u.%u.%u:%u",
7265 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
7266 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
7267 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
7268 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
7269 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
7271 p = strchr( buffer, ':' );
7272 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
7273 break;
7275 case WS_AF_INET6:
7277 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
7279 buffer[0] = 0;
7280 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
7281 if ((sockaddr6->sin6_port))
7282 strcpy(buffer, "[");
7283 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, buffer+strlen(buffer), sizeof(buffer)))
7285 SetLastError(WSAEINVAL);
7286 return SOCKET_ERROR;
7288 if ((sockaddr6->sin6_scope_id))
7289 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
7290 if ((sockaddr6->sin6_port))
7291 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
7292 break;
7295 default:
7296 SetLastError(WSAEINVAL);
7297 return SOCKET_ERROR;
7300 size = strlen( buffer ) + 1;
7302 if (*lenstr < size)
7304 *lenstr = size;
7305 SetLastError(WSAEFAULT);
7306 return SOCKET_ERROR;
7309 TRACE("=> %s,%u bytes\n", debugstr_a(buffer), size);
7310 *lenstr = size;
7311 strcpy( string, buffer );
7312 return 0;
7315 /***********************************************************************
7316 * WSAAddressToStringW (WS2_32.28)
7318 * Convert a sockaddr address into a readable address string.
7320 * PARAMS
7321 * sockaddr [I] Pointer to a sockaddr structure.
7322 * len [I] Size of the sockaddr structure.
7323 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
7324 * string [I/O] Pointer to a buffer to receive the address string.
7325 * lenstr [I/O] Size of the receive buffer in WCHARs.
7327 * RETURNS
7328 * Success: 0
7329 * Failure: SOCKET_ERROR
7331 * NOTES
7332 * The 'info' parameter is ignored.
7334 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
7335 LPWSAPROTOCOL_INFOW info, LPWSTR string,
7336 LPDWORD lenstr )
7338 INT ret;
7339 DWORD size;
7340 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
7341 CHAR bufAddr[54];
7343 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
7345 size = *lenstr;
7346 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
7348 if (ret) return ret;
7350 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
7352 if (*lenstr < size)
7354 *lenstr = size;
7355 SetLastError(WSAEFAULT);
7356 return SOCKET_ERROR;
7359 TRACE("=> %s,%u bytes\n", debugstr_w(buffer), size);
7360 *lenstr = size;
7361 lstrcpyW( string, buffer );
7362 return 0;
7365 /***********************************************************************
7366 * WSAEnumNameSpaceProvidersA (WS2_32.34)
7368 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
7370 FIXME( "(%p %p) Stub!\n", len, buffer );
7371 return 0;
7374 /***********************************************************************
7375 * WSAEnumNameSpaceProvidersW (WS2_32.35)
7377 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
7379 FIXME( "(%p %p) Stub!\n", len, buffer );
7380 return 0;
7383 /***********************************************************************
7384 * WSAGetQOSByName (WS2_32.41)
7386 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
7388 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
7389 return FALSE;
7392 /***********************************************************************
7393 * WSAGetServiceClassInfoA (WS2_32.42)
7395 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
7396 LPWSASERVICECLASSINFOA info )
7398 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
7399 len, info );
7400 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7401 return SOCKET_ERROR;
7404 /***********************************************************************
7405 * WSAGetServiceClassInfoW (WS2_32.43)
7407 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
7408 LPWSASERVICECLASSINFOW info )
7410 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
7411 len, info );
7412 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7413 return SOCKET_ERROR;
7416 /***********************************************************************
7417 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
7419 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
7421 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
7422 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7423 return SOCKET_ERROR;
7426 /***********************************************************************
7427 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
7429 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
7431 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
7432 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7433 return SOCKET_ERROR;
7436 /***********************************************************************
7437 * WSALookupServiceBeginA (WS2_32.59)
7439 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
7440 DWORD dwControlFlags,
7441 LPHANDLE lphLookup)
7443 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
7444 lphLookup);
7445 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7446 return SOCKET_ERROR;
7449 /***********************************************************************
7450 * WSALookupServiceBeginW (WS2_32.60)
7452 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
7453 DWORD dwControlFlags,
7454 LPHANDLE lphLookup)
7456 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
7457 lphLookup);
7458 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7459 return SOCKET_ERROR;
7462 /***********************************************************************
7463 * WSALookupServiceEnd (WS2_32.61)
7465 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
7467 FIXME("(%p) Stub!\n", lookup );
7468 return 0;
7471 /***********************************************************************
7472 * WSALookupServiceNextA (WS2_32.62)
7474 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
7476 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
7477 SetLastError(WSA_E_NO_MORE);
7478 return SOCKET_ERROR;
7481 /***********************************************************************
7482 * WSALookupServiceNextW (WS2_32.63)
7484 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
7486 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
7487 SetLastError(WSA_E_NO_MORE);
7488 return SOCKET_ERROR;
7491 /***********************************************************************
7492 * WSANtohl (WS2_32.64)
7494 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
7496 TRACE( "(0x%04lx 0x%08x %p)\n", s, netlong, lphostlong );
7498 if (!lphostlong) return WSAEFAULT;
7500 *lphostlong = ntohl( netlong );
7501 return 0;
7504 /***********************************************************************
7505 * WSANtohs (WS2_32.65)
7507 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
7509 TRACE( "(0x%04lx 0x%08x %p)\n", s, netshort, lphostshort );
7511 if (!lphostshort) return WSAEFAULT;
7513 *lphostshort = ntohs( netshort );
7514 return 0;
7517 /***********************************************************************
7518 * WSAProviderConfigChange (WS2_32.66)
7520 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
7521 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
7523 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
7524 return SOCKET_ERROR;
7527 /***********************************************************************
7528 * WSARecvDisconnect (WS2_32.68)
7530 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
7532 TRACE( "(0x%04lx %p)\n", s, disconnectdata );
7534 return WS_shutdown( s, SD_RECEIVE );
7537 /***********************************************************************
7538 * WSASetServiceA (WS2_32.76)
7540 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
7542 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
7543 return 0;
7546 /***********************************************************************
7547 * WSASetServiceW (WS2_32.77)
7549 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
7551 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
7552 return 0;
7555 /***********************************************************************
7556 * WSCEnableNSProvider (WS2_32.84)
7558 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
7560 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
7561 return 0;
7564 /***********************************************************************
7565 * WSCGetProviderPath (WS2_32.86)
7567 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
7569 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
7571 if (!errcode || !provider || !len) return WSAEFAULT;
7573 *errcode = WSAEINVAL;
7574 return SOCKET_ERROR;
7577 /***********************************************************************
7578 * WSCInstallNameSpace (WS2_32.87)
7580 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
7581 DWORD version, LPGUID provider )
7583 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
7584 namespace, version, debugstr_guid(provider) );
7585 return 0;
7588 /***********************************************************************
7589 * WSCUnInstallNameSpace (WS2_32.89)
7591 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
7593 FIXME("(%p) Stub!\n", lpProviderId);
7594 return NO_ERROR;
7597 /***********************************************************************
7598 * WSCWriteProviderOrder (WS2_32.91)
7600 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
7602 FIXME("(%p 0x%08x) Stub!\n", entry, number);
7603 return 0;
7606 /***********************************************************************
7607 * WSANSPIoctl (WS2_32.91)
7609 INT WINAPI WSANSPIoctl( HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer,
7610 DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer,
7611 LPDWORD lpcbBytesReturned, LPWSACOMPLETION lpCompletion )
7613 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup, dwControlCode,
7614 lpvInBuffer, cbInBuffer, lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpCompletion);
7615 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7616 return SOCKET_ERROR;
7619 /*****************************************************************************
7620 * WSAEnumProtocolsA [WS2_32.@]
7622 * see function WSAEnumProtocolsW
7624 INT WINAPI WSAEnumProtocolsA( LPINT protocols, LPWSAPROTOCOL_INFOA buffer, LPDWORD len )
7626 return WS_EnumProtocols( FALSE, protocols, (LPWSAPROTOCOL_INFOW) buffer, len);
7629 /*****************************************************************************
7630 * WSAEnumProtocolsW [WS2_32.@]
7632 * Retrieves information about specified set of active network protocols.
7634 * PARAMS
7635 * protocols [I] Pointer to null-terminated array of protocol id's. NULL
7636 * retrieves information on all available protocols.
7637 * buffer [I] Pointer to a buffer to be filled with WSAPROTOCOL_INFO
7638 * structures.
7639 * len [I/O] Pointer to a variable specifying buffer size. On output
7640 * the variable holds the number of bytes needed when the
7641 * specified size is too small.
7643 * RETURNS
7644 * Success: number of WSAPROTOCOL_INFO structures in buffer.
7645 * Failure: SOCKET_ERROR
7647 * NOTES
7648 * NT4SP5 does not return SPX if protocols == NULL
7650 * BUGS
7651 * - NT4SP5 returns in addition these list of NETBIOS protocols
7652 * (address family 17), each entry two times one for socket type 2 and 5
7654 * iProtocol szProtocol
7655 * 0x80000000 \Device\NwlnkNb
7656 * 0xfffffffa \Device\NetBT_CBENT7
7657 * 0xfffffffb \Device\Nbf_CBENT7
7658 * 0xfffffffc \Device\NetBT_NdisWan5
7659 * 0xfffffffd \Device\NetBT_El9202
7660 * 0xfffffffe \Device\Nbf_El9202
7661 * 0xffffffff \Device\Nbf_NdisWan4
7663 * - there is no check that the operating system supports the returned
7664 * protocols
7666 INT WINAPI WSAEnumProtocolsW( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
7668 return WS_EnumProtocols( TRUE, protocols, buffer, len);
7671 /*****************************************************************************
7672 * WSCEnumProtocols [WS2_32.@]
7674 * PARAMS
7675 * protocols [I] Null-terminated array of iProtocol values.
7676 * buffer [O] Buffer of WSAPROTOCOL_INFOW structures.
7677 * len [I/O] Size of buffer on input/output.
7678 * errno [O] Error code.
7680 * RETURNS
7681 * Success: number of protocols to be reported on.
7682 * Failure: SOCKET_ERROR. error is in errno.
7684 * BUGS
7685 * Doesn't supply info on layered protocols.
7688 INT WINAPI WSCEnumProtocols( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len, LPINT err )
7690 INT ret = WSAEnumProtocolsW( protocols, buffer, len );
7692 if (ret == SOCKET_ERROR) *err = WSAENOBUFS;
7694 return ret;