ws2_32: Add extended IPX protocol support.
[wine.git] / dlls / ws2_32 / socket.c
blob462ff86b56ea5b799dee4d05fd331624fe7c9294
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 # define HAS_IPX
104 #elif defined(HAVE_LINUX_IPX_H)
105 # ifdef HAVE_ASM_TYPES_H
106 # include <asm/types.h>
107 # endif
108 # ifdef HAVE_LINUX_TYPES_H
109 # include <linux/types.h>
110 # endif
111 # include <linux/ipx.h>
112 # define HAS_IPX
113 #endif
115 #ifdef HAVE_LINUX_IRDA_H
116 # ifdef HAVE_LINUX_TYPES_H
117 # include <linux/types.h>
118 # endif
119 # include <linux/irda.h>
120 # define HAS_IRDA
121 #endif
123 #ifdef HAVE_POLL_H
124 #include <poll.h>
125 #endif
126 #ifdef HAVE_SYS_POLL_H
127 # include <sys/poll.h>
128 #endif
129 #ifdef HAVE_SYS_TIME_H
130 # include <sys/time.h>
131 #endif
133 #define NONAMELESSUNION
134 #define NONAMELESSSTRUCT
135 #include "ntstatus.h"
136 #define WIN32_NO_STATUS
137 #include "windef.h"
138 #include "winbase.h"
139 #include "wingdi.h"
140 #include "winuser.h"
141 #include "winerror.h"
142 #include "winnls.h"
143 #include "winsock2.h"
144 #include "mswsock.h"
145 #include "ws2tcpip.h"
146 #include "ws2spi.h"
147 #include "wsipx.h"
148 #include "wshisotp.h"
149 #include "mstcpip.h"
150 #include "af_irda.h"
151 #include "winnt.h"
152 #define USE_WC_PREFIX /* For CMSG_DATA */
153 #include "iphlpapi.h"
154 #include "wine/server.h"
155 #include "wine/debug.h"
156 #include "wine/exception.h"
157 #include "wine/unicode.h"
159 #ifdef HAS_IPX
160 # include "wsnwlink.h"
161 #endif
163 #if defined(linux) && !defined(IP_UNICAST_IF)
164 #define IP_UNICAST_IF 50
165 #endif
167 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
168 # define sipx_network sipx_addr.x_net
169 # define sipx_node sipx_addr.x_host.c_host
170 #endif /* __FreeBSD__ */
172 #ifndef INADDR_NONE
173 #define INADDR_NONE ~0UL
174 #endif
176 WINE_DEFAULT_DEBUG_CHANNEL(winsock);
177 WINE_DECLARE_DEBUG_CHANNEL(winediag);
179 /* names of the protocols */
180 static const WCHAR NameIpxW[] = {'I', 'P', 'X', '\0'};
181 static const WCHAR NameSpxW[] = {'S', 'P', 'X', '\0'};
182 static const WCHAR NameSpxIIW[] = {'S', 'P', 'X', ' ', 'I', 'I', '\0'};
183 static const WCHAR NameTcpW[] = {'T', 'C', 'P', '/', 'I', 'P', '\0'};
184 static const WCHAR NameUdpW[] = {'U', 'D', 'P', '/', 'I', 'P', '\0'};
186 /* Taken from Win2k */
187 static const GUID ProviderIdIP = { 0xe70f1aa0, 0xab8b, 0x11cf,
188 { 0x8c, 0xa3, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
189 static const GUID ProviderIdIPX = { 0x11058240, 0xbe47, 0x11cf,
190 { 0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
191 static const GUID ProviderIdSPX = { 0x11058241, 0xbe47, 0x11cf,
192 { 0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
194 static const INT valid_protocols[] =
196 WS_IPPROTO_TCP,
197 WS_IPPROTO_UDP,
198 WS_NSPROTO_IPX,
199 WS_NSPROTO_SPX,
200 WS_NSPROTO_SPXII,
204 #define IS_IPX_PROTO(X) ((X) >= WS_NSPROTO_IPX && (X) <= WS_NSPROTO_IPX + 255)
206 #if defined(IP_UNICAST_IF) && defined(SO_ATTACH_FILTER)
207 # define LINUX_BOUND_IF
208 struct interface_filter {
209 struct sock_filter iface_memaddr;
210 struct sock_filter iface_rule;
211 struct sock_filter ip_memaddr;
212 struct sock_filter ip_rule;
213 struct sock_filter return_keep;
214 struct sock_filter return_dump;
216 # define FILTER_JUMP_DUMP(here) (u_char)(offsetof(struct interface_filter, return_dump) \
217 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
218 /sizeof(struct sock_filter)
219 # define FILTER_JUMP_KEEP(here) (u_char)(offsetof(struct interface_filter, return_keep) \
220 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
221 /sizeof(struct sock_filter)
222 # define FILTER_JUMP_NEXT() (u_char)(0)
223 # define SKF_NET_DESTIP 16 /* offset in the network header to the destination IP */
224 static struct interface_filter generic_interface_filter = {
225 /* This filter rule allows incoming packets on the specified interface, which works for all
226 * remotely generated packets and for locally generated broadcast packets. */
227 BPF_STMT(BPF_LD+BPF_W+BPF_ABS, SKF_AD_OFF+SKF_AD_IFINDEX),
228 BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0xdeadbeef, FILTER_JUMP_KEEP(iface_rule), FILTER_JUMP_NEXT()),
229 /* This rule allows locally generated packets targeted at the specific IP address of the chosen
230 * adapter (local packets not destined for the broadcast address do not have IFINDEX set) */
231 BPF_STMT(BPF_LD+BPF_W+BPF_ABS, SKF_NET_OFF+SKF_NET_DESTIP),
232 BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0xdeadbeef, FILTER_JUMP_KEEP(ip_rule), FILTER_JUMP_DUMP(ip_rule)),
233 BPF_STMT(BPF_RET+BPF_K, (u_int)-1), /* keep packet */
234 BPF_STMT(BPF_RET+BPF_K, 0) /* dump packet */
236 #endif /* LINUX_BOUND_IF */
239 * The actual definition of WSASendTo, wrapped in a different function name
240 * so that internal calls from ws2_32 itself will not trigger programs like
241 * Garena, which hooks WSASendTo/WSARecvFrom calls.
243 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
244 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
245 const struct WS_sockaddr *to, int tolen,
246 LPWSAOVERLAPPED lpOverlapped,
247 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine );
250 * Internal fundamental receive function, essentially WSARecvFrom with an
251 * additional parameter to support message control headers.
253 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
254 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
255 struct WS_sockaddr *lpFrom,
256 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
257 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
258 LPWSABUF lpControlBuffer );
260 /* critical section to protect some non-reentrant net function */
261 static CRITICAL_SECTION csWSgetXXXbyYYY;
262 static CRITICAL_SECTION_DEBUG critsect_debug =
264 0, 0, &csWSgetXXXbyYYY,
265 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
266 0, 0, { (DWORD_PTR)(__FILE__ ": csWSgetXXXbyYYY") }
268 static CRITICAL_SECTION csWSgetXXXbyYYY = { &critsect_debug, -1, 0, 0, 0, 0 };
270 union generic_unix_sockaddr
272 struct sockaddr addr;
273 char data[128]; /* should be big enough for all families */
276 static inline const char *debugstr_sockaddr( const struct WS_sockaddr *a )
278 if (!a) return "(nil)";
279 switch (a->sa_family)
281 case WS_AF_INET:
282 return wine_dbg_sprintf("{ family AF_INET, address %s, port %d }",
283 inet_ntoa(((const struct sockaddr_in *)a)->sin_addr),
284 ntohs(((const struct sockaddr_in *)a)->sin_port));
285 case WS_AF_INET6:
287 char buf[46];
288 const char *p;
289 struct WS_sockaddr_in6 *sin = (struct WS_sockaddr_in6 *)a;
291 p = WS_inet_ntop( WS_AF_INET6, &sin->sin6_addr, buf, sizeof(buf) );
292 if (!p)
293 p = "(unknown IPv6 address)";
294 return wine_dbg_sprintf("{ family AF_INET6, address %s, port %d }",
295 p, ntohs(sin->sin6_port));
297 case WS_AF_IPX:
299 int i;
300 char netnum[16], nodenum[16];
301 struct WS_sockaddr_ipx *sin = (struct WS_sockaddr_ipx *)a;
303 for (i = 0;i < 4; i++) sprintf(netnum + i * 2, "%02X", (unsigned char) sin->sa_netnum[i]);
304 for (i = 0;i < 6; i++) sprintf(nodenum + i * 2, "%02X", (unsigned char) sin->sa_nodenum[i]);
306 return wine_dbg_sprintf("{ family AF_IPX, address %s.%s, ipx socket %d }",
307 netnum, nodenum, sin->sa_socket);
309 case WS_AF_IRDA:
311 DWORD addr;
313 memcpy( &addr, ((const SOCKADDR_IRDA *)a)->irdaDeviceID, sizeof(addr) );
314 addr = ntohl( addr );
315 return wine_dbg_sprintf("{ family AF_IRDA, addr %08x, name %s }",
316 addr,
317 ((const SOCKADDR_IRDA *)a)->irdaServiceName);
319 default:
320 return wine_dbg_sprintf("{ family %d }", a->sa_family);
324 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
325 #define SOCKET2HANDLE(s) ((HANDLE)(s))
326 #define HANDLE2SOCKET(h) ((SOCKET)(h))
328 /****************************************************************
329 * Async IO declarations
330 ****************************************************************/
332 typedef struct ws2_async
334 HANDLE hSocket;
335 int type;
336 LPWSAOVERLAPPED user_overlapped;
337 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
338 IO_STATUS_BLOCK local_iosb;
339 struct WS_sockaddr *addr;
340 union
342 int val; /* for send operations */
343 int *ptr; /* for recv operations */
344 } addrlen;
345 DWORD flags;
346 DWORD *lpFlags;
347 WSABUF *control;
348 unsigned int n_iovecs;
349 unsigned int first_iovec;
350 struct iovec iovec[1];
351 } ws2_async;
353 typedef struct ws2_accept_async
355 HANDLE listen_socket;
356 HANDLE accept_socket;
357 LPOVERLAPPED user_overlapped;
358 ULONG_PTR cvalue;
359 PVOID buf; /* buffer to write data to */
360 int data_len;
361 int local_len;
362 int remote_len;
363 struct ws2_async *read;
364 } ws2_accept_async;
366 /****************************************************************/
368 /* ----------------------------------- internal data */
370 /* ws_... struct conversion flags */
372 typedef struct /* WSAAsyncSelect() control struct */
374 HANDLE service, event, sock;
375 HWND hWnd;
376 UINT uMsg;
377 LONG lEvent;
378 } ws_select_info;
380 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
381 #define WS_MAX_UDP_DATAGRAM 1024
382 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
384 /* hostent's, servent's and protent's are stored in one buffer per thread,
385 * as documented on MSDN for the functions that return any of the buffers */
386 struct per_thread_data
388 int opentype;
389 struct WS_hostent *he_buffer;
390 struct WS_servent *se_buffer;
391 struct WS_protoent *pe_buffer;
392 int he_len;
393 int se_len;
394 int pe_len;
395 char ntoa_buffer[16]; /* 4*3 digits + 3 '.' + 1 '\0' */
398 /* internal: routing description information */
399 struct route {
400 struct in_addr addr;
401 IF_INDEX interface;
402 DWORD metric;
405 static INT num_startup; /* reference counter */
406 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
408 /* function prototypes */
409 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length);
410 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
411 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
412 static struct WS_servent *WS_dup_se(const struct servent* p_se);
413 static int ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size);
415 int WSAIOCTL_GetInterfaceCount(void);
416 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
418 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus, ULONG Information );
420 #define MAP_OPTION(opt) { WS_##opt, opt }
422 static const int ws_sock_map[][2] =
424 MAP_OPTION( SO_DEBUG ),
425 MAP_OPTION( SO_ACCEPTCONN ),
426 MAP_OPTION( SO_REUSEADDR ),
427 MAP_OPTION( SO_KEEPALIVE ),
428 MAP_OPTION( SO_DONTROUTE ),
429 MAP_OPTION( SO_BROADCAST ),
430 MAP_OPTION( SO_LINGER ),
431 MAP_OPTION( SO_OOBINLINE ),
432 MAP_OPTION( SO_SNDBUF ),
433 MAP_OPTION( SO_RCVBUF ),
434 MAP_OPTION( SO_ERROR ),
435 MAP_OPTION( SO_TYPE ),
436 #ifdef SO_RCVTIMEO
437 MAP_OPTION( SO_RCVTIMEO ),
438 #endif
439 #ifdef SO_SNDTIMEO
440 MAP_OPTION( SO_SNDTIMEO ),
441 #endif
444 static const int ws_tcp_map[][2] =
446 #ifdef TCP_NODELAY
447 MAP_OPTION( TCP_NODELAY ),
448 #endif
451 static const int ws_ip_map[][2] =
453 MAP_OPTION( IP_MULTICAST_IF ),
454 MAP_OPTION( IP_MULTICAST_TTL ),
455 MAP_OPTION( IP_MULTICAST_LOOP ),
456 MAP_OPTION( IP_ADD_MEMBERSHIP ),
457 MAP_OPTION( IP_DROP_MEMBERSHIP ),
458 MAP_OPTION( IP_OPTIONS ),
459 #ifdef IP_HDRINCL
460 MAP_OPTION( IP_HDRINCL ),
461 #endif
462 MAP_OPTION( IP_TOS ),
463 MAP_OPTION( IP_TTL ),
464 #ifdef IP_PKTINFO
465 MAP_OPTION( IP_PKTINFO ),
466 #endif
467 #ifdef IP_UNICAST_IF
468 MAP_OPTION( IP_UNICAST_IF ),
469 #endif
472 static const int ws_ipv6_map[][2] =
474 #ifdef IPV6_ADD_MEMBERSHIP
475 MAP_OPTION( IPV6_ADD_MEMBERSHIP ),
476 #endif
477 #ifdef IPV6_DROP_MEMBERSHIP
478 MAP_OPTION( IPV6_DROP_MEMBERSHIP ),
479 #endif
480 MAP_OPTION( IPV6_MULTICAST_IF ),
481 MAP_OPTION( IPV6_MULTICAST_HOPS ),
482 MAP_OPTION( IPV6_MULTICAST_LOOP ),
483 MAP_OPTION( IPV6_UNICAST_HOPS ),
484 MAP_OPTION( IPV6_V6ONLY ),
485 #ifdef IPV6_UNICAST_IF
486 MAP_OPTION( IPV6_UNICAST_IF ),
487 #endif
490 static const int ws_af_map[][2] =
492 MAP_OPTION( AF_UNSPEC ),
493 MAP_OPTION( AF_INET ),
494 MAP_OPTION( AF_INET6 ),
495 #ifdef HAS_IPX
496 MAP_OPTION( AF_IPX ),
497 #endif
498 #ifdef AF_IRDA
499 MAP_OPTION( AF_IRDA ),
500 #endif
501 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
504 static const int ws_socktype_map[][2] =
506 MAP_OPTION( SOCK_DGRAM ),
507 MAP_OPTION( SOCK_STREAM ),
508 MAP_OPTION( SOCK_RAW ),
509 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
512 static const int ws_proto_map[][2] =
514 MAP_OPTION( IPPROTO_IP ),
515 MAP_OPTION( IPPROTO_TCP ),
516 MAP_OPTION( IPPROTO_UDP ),
517 MAP_OPTION( IPPROTO_ICMP ),
518 MAP_OPTION( IPPROTO_IGMP ),
519 MAP_OPTION( IPPROTO_RAW ),
520 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
523 static const int ws_aiflag_map[][2] =
525 MAP_OPTION( AI_PASSIVE ),
526 MAP_OPTION( AI_CANONNAME ),
527 MAP_OPTION( AI_NUMERICHOST ),
528 MAP_OPTION( AI_V4MAPPED ),
529 MAP_OPTION( AI_ADDRCONFIG ),
532 static const int ws_niflag_map[][2] =
534 MAP_OPTION( NI_NOFQDN ),
535 MAP_OPTION( NI_NUMERICHOST ),
536 MAP_OPTION( NI_NAMEREQD ),
537 MAP_OPTION( NI_NUMERICSERV ),
538 MAP_OPTION( NI_DGRAM ),
541 static const int ws_eai_map[][2] =
543 MAP_OPTION( EAI_AGAIN ),
544 MAP_OPTION( EAI_BADFLAGS ),
545 MAP_OPTION( EAI_FAIL ),
546 MAP_OPTION( EAI_FAMILY ),
547 MAP_OPTION( EAI_MEMORY ),
548 /* Note: EAI_NODATA is deprecated, but still
549 * used by Windows and Linux... We map the newer
550 * EAI_NONAME to EAI_NODATA for now until Windows
551 * changes too.
553 #ifdef EAI_NODATA
554 MAP_OPTION( EAI_NODATA ),
555 #endif
556 #ifdef EAI_NONAME
557 { WS_EAI_NODATA, EAI_NONAME },
558 #endif
560 MAP_OPTION( EAI_SERVICE ),
561 MAP_OPTION( EAI_SOCKTYPE ),
562 { 0, 0 }
565 static const char magic_loopback_addr[] = {127, 12, 34, 56};
567 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
568 static inline WSACMSGHDR *fill_control_message(int level, int type, WSACMSGHDR *current, ULONG *maxsize, void *data, int len)
570 ULONG msgsize = sizeof(WSACMSGHDR) + WSA_CMSG_ALIGN(len);
571 char *ptr = (char *) current + sizeof(WSACMSGHDR);
573 /* Make sure there is at least enough room for this entry */
574 if (msgsize > *maxsize)
575 return NULL;
576 *maxsize -= msgsize;
577 /* Fill in the entry */
578 current->cmsg_len = sizeof(WSACMSGHDR) + len;
579 current->cmsg_level = level;
580 current->cmsg_type = type;
581 memcpy(ptr, data, len);
582 /* Return the pointer to where next entry should go */
583 return (WSACMSGHDR *) (ptr + WSA_CMSG_ALIGN(len));
586 static inline int convert_control_headers(struct msghdr *hdr, WSABUF *control)
588 #ifdef IP_PKTINFO
589 WSACMSGHDR *cmsg_win = (WSACMSGHDR *) control->buf, *ptr;
590 ULONG ctlsize = control->len;
591 struct cmsghdr *cmsg_unix;
593 ptr = cmsg_win;
594 /* Loop over all the headers, converting as appropriate */
595 for (cmsg_unix = CMSG_FIRSTHDR(hdr); cmsg_unix != NULL; cmsg_unix = CMSG_NXTHDR(hdr, cmsg_unix))
597 switch(cmsg_unix->cmsg_level)
599 case IPPROTO_IP:
600 switch(cmsg_unix->cmsg_type)
602 case IP_PKTINFO:
604 /* Convert the Unix IP_PKTINFO structure to the Windows version */
605 struct in_pktinfo *data_unix = (struct in_pktinfo *) CMSG_DATA(cmsg_unix);
606 struct WS_in_pktinfo data_win;
608 memcpy(&data_win.ipi_addr,&data_unix->ipi_addr.s_addr,4); /* 4 bytes = 32 address bits */
609 data_win.ipi_ifindex = data_unix->ipi_ifindex;
610 ptr = fill_control_message(WS_IPPROTO_IP, WS_IP_PKTINFO, ptr, &ctlsize,
611 (void*)&data_win, sizeof(data_win));
612 if (!ptr) goto error;
613 } break;
614 default:
615 FIXME("Unhandled IPPROTO_IP message header type %d\n", cmsg_unix->cmsg_type);
616 break;
618 break;
619 default:
620 FIXME("Unhandled message header level %d\n", cmsg_unix->cmsg_level);
621 break;
625 error:
626 /* Set the length of the returned control headers */
627 control->len = (ptr == NULL ? 0 : (char*)ptr - (char*)cmsg_win);
628 return (ptr != NULL);
629 #else /* IP_PKTINFO */
630 control->len = 0;
631 return 1;
632 #endif /* IP_PKTINFO */
634 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
636 /* ----------------------------------- error handling */
638 static NTSTATUS sock_get_ntstatus( int err )
640 switch ( err )
642 case EBADF: return STATUS_INVALID_HANDLE;
643 case EBUSY: return STATUS_DEVICE_BUSY;
644 case EPERM:
645 case EACCES: return STATUS_ACCESS_DENIED;
646 case EFAULT: return STATUS_NO_MEMORY;
647 case EINVAL: return STATUS_INVALID_PARAMETER;
648 case ENFILE:
649 case EMFILE: return STATUS_TOO_MANY_OPENED_FILES;
650 case EWOULDBLOCK: return STATUS_CANT_WAIT;
651 case EINPROGRESS: return STATUS_PENDING;
652 case EALREADY: return STATUS_NETWORK_BUSY;
653 case ENOTSOCK: return STATUS_OBJECT_TYPE_MISMATCH;
654 case EDESTADDRREQ: return STATUS_INVALID_PARAMETER;
655 case EMSGSIZE: return STATUS_BUFFER_OVERFLOW;
656 case EPROTONOSUPPORT:
657 case ESOCKTNOSUPPORT:
658 case EPFNOSUPPORT:
659 case EAFNOSUPPORT:
660 case EPROTOTYPE: return STATUS_NOT_SUPPORTED;
661 case ENOPROTOOPT: return STATUS_INVALID_PARAMETER;
662 case EOPNOTSUPP: return STATUS_NOT_SUPPORTED;
663 case EADDRINUSE: return STATUS_ADDRESS_ALREADY_ASSOCIATED;
664 case EADDRNOTAVAIL: return STATUS_INVALID_PARAMETER;
665 case ECONNREFUSED: return STATUS_CONNECTION_REFUSED;
666 case ESHUTDOWN: return STATUS_PIPE_DISCONNECTED;
667 case ENOTCONN: return STATUS_CONNECTION_DISCONNECTED;
668 case ETIMEDOUT: return STATUS_IO_TIMEOUT;
669 case ENETUNREACH: return STATUS_NETWORK_UNREACHABLE;
670 case ENETDOWN: return STATUS_NETWORK_BUSY;
671 case EPIPE:
672 case ECONNRESET: return STATUS_CONNECTION_RESET;
673 case ECONNABORTED: return STATUS_CONNECTION_ABORTED;
675 case 0: return STATUS_SUCCESS;
676 default:
677 WARN("Unknown errno %d!\n", err);
678 return STATUS_UNSUCCESSFUL;
682 static UINT sock_get_error( int err )
684 switch(err)
686 case EINTR: return WSAEINTR;
687 case EBADF: return WSAEBADF;
688 case EPERM:
689 case EACCES: return WSAEACCES;
690 case EFAULT: return WSAEFAULT;
691 case EINVAL: return WSAEINVAL;
692 case EMFILE: return WSAEMFILE;
693 case EWOULDBLOCK: return WSAEWOULDBLOCK;
694 case EINPROGRESS: return WSAEINPROGRESS;
695 case EALREADY: return WSAEALREADY;
696 case ENOTSOCK: return WSAENOTSOCK;
697 case EDESTADDRREQ: return WSAEDESTADDRREQ;
698 case EMSGSIZE: return WSAEMSGSIZE;
699 case EPROTOTYPE: return WSAEPROTOTYPE;
700 case ENOPROTOOPT: return WSAENOPROTOOPT;
701 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
702 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
703 case EOPNOTSUPP: return WSAEOPNOTSUPP;
704 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
705 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
706 case EADDRINUSE: return WSAEADDRINUSE;
707 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
708 case ENETDOWN: return WSAENETDOWN;
709 case ENETUNREACH: return WSAENETUNREACH;
710 case ENETRESET: return WSAENETRESET;
711 case ECONNABORTED: return WSAECONNABORTED;
712 case EPIPE:
713 case ECONNRESET: return WSAECONNRESET;
714 case ENOBUFS: return WSAENOBUFS;
715 case EISCONN: return WSAEISCONN;
716 case ENOTCONN: return WSAENOTCONN;
717 case ESHUTDOWN: return WSAESHUTDOWN;
718 case ETOOMANYREFS: return WSAETOOMANYREFS;
719 case ETIMEDOUT: return WSAETIMEDOUT;
720 case ECONNREFUSED: return WSAECONNREFUSED;
721 case ELOOP: return WSAELOOP;
722 case ENAMETOOLONG: return WSAENAMETOOLONG;
723 case EHOSTDOWN: return WSAEHOSTDOWN;
724 case EHOSTUNREACH: return WSAEHOSTUNREACH;
725 case ENOTEMPTY: return WSAENOTEMPTY;
726 #ifdef EPROCLIM
727 case EPROCLIM: return WSAEPROCLIM;
728 #endif
729 #ifdef EUSERS
730 case EUSERS: return WSAEUSERS;
731 #endif
732 #ifdef EDQUOT
733 case EDQUOT: return WSAEDQUOT;
734 #endif
735 #ifdef ESTALE
736 case ESTALE: return WSAESTALE;
737 #endif
738 #ifdef EREMOTE
739 case EREMOTE: return WSAEREMOTE;
740 #endif
742 /* just in case we ever get here and there are no problems */
743 case 0: return 0;
744 default:
745 WARN("Unknown errno %d!\n", err);
746 return WSAEOPNOTSUPP;
750 static UINT wsaErrno(void)
752 int loc_errno = errno;
753 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
755 return sock_get_error( loc_errno );
758 /* most ws2 overlapped functions return an ntstatus-based error code */
759 static NTSTATUS wsaErrStatus(void)
761 int loc_errno = errno;
762 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
764 return sock_get_ntstatus(loc_errno);
767 static UINT wsaHerrno(int loc_errno)
769 WARN("h_errno %d.\n", loc_errno);
771 switch(loc_errno)
773 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
774 case TRY_AGAIN: return WSATRY_AGAIN;
775 case NO_RECOVERY: return WSANO_RECOVERY;
776 case NO_DATA: return WSANO_DATA;
777 case ENOBUFS: return WSAENOBUFS;
779 case 0: return 0;
780 default:
781 WARN("Unknown h_errno %d!\n", loc_errno);
782 return WSAEOPNOTSUPP;
786 static inline DWORD NtStatusToWSAError( const DWORD status )
788 /* We only need to cover the status codes set by server async request handling */
789 DWORD wserr;
790 switch ( status )
792 case STATUS_SUCCESS: wserr = 0; break;
793 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
794 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
795 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
796 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
797 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
798 case STATUS_NETWORK_BUSY: wserr = WSAEALREADY; break;
799 case STATUS_NETWORK_UNREACHABLE: wserr = WSAENETUNREACH; break;
800 case STATUS_CONNECTION_REFUSED: wserr = WSAECONNREFUSED; break;
801 case STATUS_CONNECTION_DISCONNECTED: wserr = WSAENOTCONN; break;
802 case STATUS_CONNECTION_RESET: wserr = WSAECONNRESET; break;
803 case STATUS_CONNECTION_ABORTED: wserr = WSAECONNABORTED; break;
804 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
805 case STATUS_ADDRESS_ALREADY_ASSOCIATED: wserr = WSAEADDRINUSE; break;
806 case STATUS_IO_TIMEOUT:
807 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
808 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
809 case STATUS_ACCESS_DENIED: wserr = WSAEACCES; break;
810 case STATUS_TOO_MANY_OPENED_FILES: wserr = WSAEMFILE; break;
811 case STATUS_CANT_WAIT: wserr = WSAEWOULDBLOCK; break;
812 case STATUS_BUFFER_OVERFLOW: wserr = WSAEMSGSIZE; break;
813 case STATUS_NOT_SUPPORTED: wserr = WSAEOPNOTSUPP; break;
814 case STATUS_HOST_UNREACHABLE: wserr = WSAEHOSTUNREACH; break;
816 default:
817 wserr = RtlNtStatusToDosError( status );
818 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
820 return wserr;
823 /* set last error code from NT status without mapping WSA errors */
824 static inline unsigned int set_error( unsigned int err )
826 if (err)
828 err = NtStatusToWSAError( err );
829 SetLastError( err );
831 return err;
834 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
836 int fd;
837 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
838 return -1;
839 return fd;
842 static inline void release_sock_fd( SOCKET s, int fd )
844 wine_server_release_fd( SOCKET2HANDLE(s), fd );
847 static void _enable_event( HANDLE s, unsigned int event,
848 unsigned int sstate, unsigned int cstate )
850 SERVER_START_REQ( enable_socket_event )
852 req->handle = wine_server_obj_handle( s );
853 req->mask = event;
854 req->sstate = sstate;
855 req->cstate = cstate;
856 wine_server_call( req );
858 SERVER_END_REQ;
861 static NTSTATUS _is_blocking(SOCKET s, BOOL *ret)
863 NTSTATUS status;
864 SERVER_START_REQ( get_socket_event )
866 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
867 req->service = FALSE;
868 req->c_event = 0;
869 status = wine_server_call( req );
870 *ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
872 SERVER_END_REQ;
873 return status;
876 static unsigned int _get_sock_mask(SOCKET s)
878 unsigned int ret;
879 SERVER_START_REQ( get_socket_event )
881 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
882 req->service = FALSE;
883 req->c_event = 0;
884 wine_server_call( req );
885 ret = reply->mask;
887 SERVER_END_REQ;
888 return ret;
891 static void _sync_sock_state(SOCKET s)
893 BOOL dummy;
894 /* do a dummy wineserver request in order to let
895 the wineserver run through its select loop once */
896 (void)_is_blocking(s, &dummy);
899 static int _get_sock_error(SOCKET s, unsigned int bit)
901 int events[FD_MAX_EVENTS];
903 SERVER_START_REQ( get_socket_event )
905 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
906 req->service = FALSE;
907 req->c_event = 0;
908 wine_server_set_reply( req, events, sizeof(events) );
909 wine_server_call( req );
911 SERVER_END_REQ;
912 return events[bit];
915 static struct per_thread_data *get_per_thread_data(void)
917 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
918 /* lazy initialization */
919 if (!ptb)
921 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
922 NtCurrentTeb()->WinSockData = ptb;
924 return ptb;
927 static void free_per_thread_data(void)
929 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
931 if (!ptb) return;
933 /* delete scratch buffers */
934 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
935 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
936 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
937 ptb->he_buffer = NULL;
938 ptb->se_buffer = NULL;
939 ptb->pe_buffer = NULL;
941 HeapFree( GetProcessHeap(), 0, ptb );
942 NtCurrentTeb()->WinSockData = NULL;
945 /***********************************************************************
946 * DllMain (WS2_32.init)
948 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
950 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
951 switch (fdwReason) {
952 case DLL_PROCESS_ATTACH:
953 break;
954 case DLL_PROCESS_DETACH:
955 if (fImpLoad) break;
956 free_per_thread_data();
957 DeleteCriticalSection(&csWSgetXXXbyYYY);
958 break;
959 case DLL_THREAD_DETACH:
960 free_per_thread_data();
961 break;
963 return TRUE;
966 /***********************************************************************
967 * convert_sockopt()
969 * Converts socket flags from Windows format.
970 * Return 1 if converted, 0 if not (error).
972 static int convert_sockopt(INT *level, INT *optname)
974 unsigned int i;
975 switch (*level)
977 case WS_SOL_SOCKET:
978 *level = SOL_SOCKET;
979 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
980 if( ws_sock_map[i][0] == *optname )
982 *optname = ws_sock_map[i][1];
983 return 1;
986 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
987 break;
988 case WS_IPPROTO_TCP:
989 *level = IPPROTO_TCP;
990 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
991 if ( ws_tcp_map[i][0] == *optname )
993 *optname = ws_tcp_map[i][1];
994 return 1;
997 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
998 break;
999 case WS_IPPROTO_IP:
1000 *level = IPPROTO_IP;
1001 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
1002 if (ws_ip_map[i][0] == *optname )
1004 *optname = ws_ip_map[i][1];
1005 return 1;
1008 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
1009 break;
1010 case WS_IPPROTO_IPV6:
1011 *level = IPPROTO_IPV6;
1012 for(i=0; i<sizeof(ws_ipv6_map)/sizeof(ws_ipv6_map[0]); i++) {
1013 if (ws_ipv6_map[i][0] == *optname )
1015 *optname = ws_ipv6_map[i][1];
1016 return 1;
1019 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname);
1020 break;
1021 default: FIXME("Unimplemented or unknown socket level\n");
1023 return 0;
1026 /* ----------------------------------- Per-thread info (or per-process?) */
1028 static char *strdup_lower(const char *str)
1030 int i;
1031 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
1033 if (ret)
1035 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
1036 ret[i] = 0;
1038 else SetLastError(WSAENOBUFS);
1039 return ret;
1042 static inline int sock_error_p(int s)
1044 unsigned int optval;
1045 socklen_t optlen = sizeof(optval);
1046 getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
1047 if (optval) WARN("\t[%i] error: %d\n", s, optval);
1048 return optval != 0;
1051 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
1052 * from an fd and return the value converted to milli seconds
1053 * or -1 if there is an infinite time out */
1054 static inline int get_rcvsnd_timeo( int fd, int optname)
1056 struct timeval tv;
1057 socklen_t len = sizeof(tv);
1058 int ret = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
1059 if( ret >= 0)
1060 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
1061 if( ret <= 0 ) /* tv == {0,0} means infinite time out */
1062 return -1;
1063 return ret;
1066 /* macro wrappers for portability */
1067 #ifdef SO_RCVTIMEO
1068 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
1069 #else
1070 #define GET_RCVTIMEO(fd) (-1)
1071 #endif
1073 #ifdef SO_SNDTIMEO
1074 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
1075 #else
1076 #define GET_SNDTIMEO(fd) (-1)
1077 #endif
1079 /* utility: given an fd, will block until one of the events occurs */
1080 static inline int do_block( int fd, int events, int timeout )
1082 struct pollfd pfd;
1083 int ret;
1085 pfd.fd = fd;
1086 pfd.events = events;
1088 while ((ret = poll(&pfd, 1, timeout)) < 0)
1090 if (errno != EINTR)
1091 return -1;
1093 if( ret == 0 )
1094 return 0;
1095 return pfd.revents;
1098 static int
1099 convert_af_w2u(int windowsaf) {
1100 unsigned int i;
1102 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1103 if (ws_af_map[i][0] == windowsaf)
1104 return ws_af_map[i][1];
1105 FIXME("unhandled Windows address family %d\n", windowsaf);
1106 return -1;
1109 static int
1110 convert_af_u2w(int unixaf) {
1111 unsigned int i;
1113 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1114 if (ws_af_map[i][1] == unixaf)
1115 return ws_af_map[i][0];
1116 FIXME("unhandled UNIX address family %d\n", unixaf);
1117 return -1;
1120 static int
1121 convert_proto_w2u(int windowsproto) {
1122 unsigned int i;
1124 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1125 if (ws_proto_map[i][0] == windowsproto)
1126 return ws_proto_map[i][1];
1128 /* check for extended IPX */
1129 if (IS_IPX_PROTO(windowsproto))
1130 return windowsproto;
1132 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
1133 return -1;
1136 static int
1137 convert_proto_u2w(int unixproto) {
1138 unsigned int i;
1140 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1141 if (ws_proto_map[i][1] == unixproto)
1142 return ws_proto_map[i][0];
1144 /* if value is inside IPX range just return it - the kernel simply
1145 * echoes the value used in the socket() function */
1146 if (IS_IPX_PROTO(unixproto))
1147 return unixproto;
1149 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
1150 return -1;
1153 static int
1154 convert_socktype_w2u(int windowssocktype) {
1155 unsigned int i;
1157 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1158 if (ws_socktype_map[i][0] == windowssocktype)
1159 return ws_socktype_map[i][1];
1160 FIXME("unhandled Windows socket type %d\n", windowssocktype);
1161 return -1;
1164 static int
1165 convert_socktype_u2w(int unixsocktype) {
1166 unsigned int i;
1168 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1169 if (ws_socktype_map[i][1] == unixsocktype)
1170 return ws_socktype_map[i][0];
1171 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
1172 return -1;
1175 static int set_ipx_packettype(int sock, int ptype)
1177 #ifdef HAS_IPX
1178 int fd = get_sock_fd( sock, 0, NULL ), ret = 0;
1179 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", ptype, fd);
1181 /* We try to set the ipx type on ipx socket level. */
1182 #ifdef SOL_IPX
1183 if(setsockopt(fd, SOL_IPX, IPX_TYPE, &ptype, sizeof(ptype)) == -1)
1185 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
1186 ret = SOCKET_ERROR;
1188 #else
1190 struct ipx val;
1191 /* Should we retrieve val using a getsockopt call and then
1192 * set the modified one? */
1193 val.ipx_pt = ptype;
1194 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
1196 #endif
1197 release_sock_fd( sock, fd );
1198 return ret;
1199 #else
1200 WARN("IPX support is not enabled, can't set packet type\n");
1201 return SOCKET_ERROR;
1202 #endif
1205 /* ----------------------------------- API -----
1207 * Init / cleanup / error checking.
1210 /***********************************************************************
1211 * WSAStartup (WS2_32.115)
1213 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
1215 TRACE("verReq=%x\n", wVersionRequested);
1217 if (LOBYTE(wVersionRequested) < 1)
1218 return WSAVERNOTSUPPORTED;
1220 if (!lpWSAData) return WSAEINVAL;
1222 num_startup++;
1224 /* that's the whole of the negotiation for now */
1225 lpWSAData->wVersion = wVersionRequested;
1226 /* return winsock information */
1227 lpWSAData->wHighVersion = 0x0202;
1228 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
1229 strcpy(lpWSAData->szSystemStatus, "Running" );
1230 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
1231 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
1232 /* don't do anything with lpWSAData->lpVendorInfo */
1233 /* (some apps don't allocate the space for this field) */
1235 TRACE("succeeded\n");
1236 return 0;
1240 /***********************************************************************
1241 * WSACleanup (WS2_32.116)
1243 INT WINAPI WSACleanup(void)
1245 if (num_startup) {
1246 num_startup--;
1247 return 0;
1249 SetLastError(WSANOTINITIALISED);
1250 return SOCKET_ERROR;
1254 /***********************************************************************
1255 * WSAGetLastError (WS2_32.111)
1257 INT WINAPI WSAGetLastError(void)
1259 return GetLastError();
1262 /***********************************************************************
1263 * WSASetLastError (WS2_32.112)
1265 void WINAPI WSASetLastError(INT iError) {
1266 SetLastError(iError);
1269 static struct WS_hostent *check_buffer_he(int size)
1271 struct per_thread_data * ptb = get_per_thread_data();
1272 if (ptb->he_buffer)
1274 if (ptb->he_len >= size ) return ptb->he_buffer;
1275 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1277 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
1278 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
1279 return ptb->he_buffer;
1282 static struct WS_servent *check_buffer_se(int size)
1284 struct per_thread_data * ptb = get_per_thread_data();
1285 if (ptb->se_buffer)
1287 if (ptb->se_len >= size ) return ptb->se_buffer;
1288 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1290 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
1291 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
1292 return ptb->se_buffer;
1295 static struct WS_protoent *check_buffer_pe(int size)
1297 struct per_thread_data * ptb = get_per_thread_data();
1298 if (ptb->pe_buffer)
1300 if (ptb->pe_len >= size ) return ptb->pe_buffer;
1301 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1303 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
1304 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
1305 return ptb->pe_buffer;
1308 /* ----------------------------------- i/o APIs */
1310 static inline BOOL supported_pf(int pf)
1312 switch (pf)
1314 case WS_AF_INET:
1315 case WS_AF_INET6:
1316 return TRUE;
1317 #ifdef HAS_IPX
1318 case WS_AF_IPX:
1319 return TRUE;
1320 #endif
1321 #ifdef HAS_IRDA
1322 case WS_AF_IRDA:
1323 return TRUE;
1324 #endif
1325 default:
1326 return FALSE;
1330 static inline BOOL supported_protocol(int protocol)
1332 int i;
1333 for (i = 0; i < sizeof(valid_protocols) / sizeof(valid_protocols[0]); i++)
1334 if (protocol == valid_protocols[i])
1335 return TRUE;
1336 return FALSE;
1339 /**********************************************************************/
1341 /* Returns the length of the converted address if successful, 0 if it was too small to
1342 * start with.
1344 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
1345 union generic_unix_sockaddr *uaddr)
1347 unsigned int uaddrlen = 0;
1349 switch (wsaddr->sa_family)
1351 #ifdef HAS_IPX
1352 case WS_AF_IPX:
1354 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
1355 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
1357 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
1358 return 0;
1360 uaddrlen = sizeof(struct sockaddr_ipx);
1361 memset( uaddr, 0, uaddrlen );
1362 uipx->sipx_family=AF_IPX;
1363 uipx->sipx_port=wsipx->sa_socket;
1364 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1365 * in one go
1367 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
1368 #ifdef IPX_FRAME_NONE
1369 uipx->sipx_type=IPX_FRAME_NONE;
1370 #endif
1371 break;
1373 #endif
1374 case WS_AF_INET6: {
1375 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
1376 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
1378 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1379 * scope_id, one without.
1381 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
1382 uaddrlen = sizeof(struct sockaddr_in6);
1383 memset( uaddr, 0, uaddrlen );
1384 uin6->sin6_family = AF_INET6;
1385 uin6->sin6_port = win6->sin6_port;
1386 uin6->sin6_flowinfo = win6->sin6_flowinfo;
1387 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1388 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
1389 #endif
1390 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
1391 break;
1393 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
1394 return 0;
1396 case WS_AF_INET: {
1397 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
1398 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
1400 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
1401 return 0;
1402 uaddrlen = sizeof(struct sockaddr_in);
1403 memset( uaddr, 0, uaddrlen );
1404 uin->sin_family = AF_INET;
1405 uin->sin_port = win->sin_port;
1406 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
1407 break;
1409 #ifdef HAS_IRDA
1410 case WS_AF_IRDA: {
1411 struct sockaddr_irda *uin = (struct sockaddr_irda *)uaddr;
1412 const SOCKADDR_IRDA *win = (const SOCKADDR_IRDA *)wsaddr;
1414 if (wsaddrlen < sizeof(SOCKADDR_IRDA))
1415 return 0;
1416 uaddrlen = sizeof(struct sockaddr_irda);
1417 memset( uaddr, 0, uaddrlen );
1418 uin->sir_family = AF_IRDA;
1419 if (!strncmp( win->irdaServiceName, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1421 unsigned int lsap_sel = 0;
1423 sscanf( win->irdaServiceName, "LSAP-SEL%u", &lsap_sel );
1424 uin->sir_lsap_sel = lsap_sel;
1426 else
1428 uin->sir_lsap_sel = LSAP_ANY;
1429 memcpy( uin->sir_name, win->irdaServiceName, 25 );
1431 memcpy( &uin->sir_addr, win->irdaDeviceID, sizeof(uin->sir_addr) );
1432 break;
1434 #endif
1435 case WS_AF_UNSPEC: {
1436 /* Try to determine the needed space by the passed windows sockaddr space */
1437 switch (wsaddrlen) {
1438 default: /* likely an ipv4 address */
1439 case sizeof(struct WS_sockaddr_in):
1440 uaddrlen = sizeof(struct sockaddr_in);
1441 break;
1442 #ifdef HAS_IPX
1443 case sizeof(struct WS_sockaddr_ipx):
1444 uaddrlen = sizeof(struct sockaddr_ipx);
1445 break;
1446 #endif
1447 #ifdef HAS_IRDA
1448 case sizeof(SOCKADDR_IRDA):
1449 uaddrlen = sizeof(struct sockaddr_irda);
1450 break;
1451 #endif
1452 case sizeof(struct WS_sockaddr_in6):
1453 case sizeof(struct WS_sockaddr_in6_old):
1454 uaddrlen = sizeof(struct sockaddr_in6);
1455 break;
1457 memset( uaddr, 0, uaddrlen );
1458 break;
1460 default:
1461 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
1462 return 0;
1464 return uaddrlen;
1467 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
1469 switch (uaddr->sa_family)
1471 #ifdef HAS_IPX
1472 case AF_IPX:
1474 static const struct sockaddr_ipx emptyAddr;
1475 struct sockaddr_ipx *ipx = (struct sockaddr_ipx*) uaddr;
1476 return ipx->sipx_port || ipx->sipx_network || memcmp(&ipx->sipx_node, &emptyAddr.sipx_node, sizeof(emptyAddr.sipx_node));
1478 #endif
1479 case AF_INET6:
1481 static const struct sockaddr_in6 emptyAddr;
1482 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
1483 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
1485 case AF_INET:
1487 static const struct sockaddr_in emptyAddr;
1488 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
1489 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
1491 case AF_UNSPEC:
1492 return FALSE;
1493 default:
1494 FIXME("unknown address family %d\n", uaddr->sa_family);
1495 return TRUE;
1499 /* Returns 0 if successful, -1 if the buffer is too small */
1500 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
1502 int res;
1504 switch(uaddr->sa_family)
1506 #ifdef HAS_IPX
1507 case AF_IPX:
1509 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
1510 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
1512 res=-1;
1513 switch (*wsaddrlen) /* how much can we copy? */
1515 default:
1516 res=0; /* enough */
1517 *wsaddrlen = sizeof(*wsipx);
1518 wsipx->sa_socket=uipx->sipx_port;
1519 /* fall through */
1520 case 13:
1521 case 12:
1522 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
1523 /* fall through */
1524 case 11:
1525 case 10:
1526 case 9:
1527 case 8:
1528 case 7:
1529 case 6:
1530 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1531 /* fall through */
1532 case 5:
1533 case 4:
1534 case 3:
1535 case 2:
1536 wsipx->sa_family=WS_AF_IPX;
1537 /* fall through */
1538 case 1:
1539 case 0:
1540 /* way too small */
1541 break;
1544 break;
1545 #endif
1546 #ifdef HAS_IRDA
1547 case AF_IRDA: {
1548 const struct sockaddr_irda *uin = (const struct sockaddr_irda *)uaddr;
1549 SOCKADDR_IRDA *win = (SOCKADDR_IRDA *)wsaddr;
1551 if (*wsaddrlen < sizeof(SOCKADDR_IRDA))
1552 return -1;
1553 win->irdaAddressFamily = WS_AF_IRDA;
1554 memcpy( win->irdaDeviceID, &uin->sir_addr, sizeof(win->irdaDeviceID) );
1555 if (uin->sir_lsap_sel != LSAP_ANY)
1556 sprintf( win->irdaServiceName, "LSAP-SEL%u", uin->sir_lsap_sel );
1557 else
1558 memcpy( win->irdaServiceName, uin->sir_name,
1559 sizeof(win->irdaServiceName) );
1560 return 0;
1562 #endif
1563 case AF_INET6: {
1564 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1565 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1567 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1568 return -1;
1569 win6old->sin6_family = WS_AF_INET6;
1570 win6old->sin6_port = uin6->sin6_port;
1571 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1572 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1573 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1574 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1575 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1576 win6->sin6_scope_id = uin6->sin6_scope_id;
1577 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1579 else
1580 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1581 #else
1582 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1583 #endif
1584 return 0;
1586 case AF_INET: {
1587 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1588 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1590 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1591 return -1;
1592 win->sin_family = WS_AF_INET;
1593 win->sin_port = uin->sin_port;
1594 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1595 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1596 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1597 return 0;
1599 case AF_UNSPEC: {
1600 memset(wsaddr,0,*wsaddrlen);
1601 return 0;
1603 default:
1604 FIXME("Unknown address family %d\n", uaddr->sa_family);
1605 return -1;
1607 return res;
1610 static INT WS_DuplicateSocket(BOOL unicode, SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo)
1612 HANDLE hProcess;
1613 int size;
1614 WSAPROTOCOL_INFOW infow;
1616 TRACE("(unicode %d, socket %04lx, processid %x, buffer %p)\n",
1617 unicode, s, dwProcessId, lpProtocolInfo);
1619 if (!ws_protocol_info(s, unicode, &infow, &size))
1620 return SOCKET_ERROR;
1622 if (!(hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId)))
1624 SetLastError(WSAEINVAL);
1625 return SOCKET_ERROR;
1628 if (!lpProtocolInfo)
1630 CloseHandle(hProcess);
1631 SetLastError(WSAEFAULT);
1632 return SOCKET_ERROR;
1635 /* I don't know what the real Windoze does next, this is a hack */
1636 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
1637 * the target use the global duplicate, or we could copy a reference to us to the structure
1638 * and let the target duplicate it from us, but let's do it as simple as possible */
1639 memcpy(lpProtocolInfo, &infow, size);
1640 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
1641 hProcess, (LPHANDLE)&lpProtocolInfo->dwServiceFlags3,
1642 0, FALSE, DUPLICATE_SAME_ACCESS);
1643 CloseHandle(hProcess);
1644 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
1645 return 0;
1648 /*****************************************************************************
1649 * WS_EnterSingleProtocolW [internal]
1651 * enters the protocol information of one given protocol into the given
1652 * buffer.
1654 * RETURNS
1655 * TRUE if a protocol was entered into the buffer.
1657 * BUGS
1658 * - only implemented for IPX, SPX, SPXII, TCP, UDP
1659 * - there is no check that the operating system supports the returned
1660 * protocols
1662 static BOOL WS_EnterSingleProtocolW( INT protocol, WSAPROTOCOL_INFOW* info )
1664 memset( info, 0, sizeof(WSAPROTOCOL_INFOW) );
1665 info->iProtocol = protocol;
1667 switch (protocol)
1669 case WS_IPPROTO_TCP:
1670 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_EXPEDITED_DATA |
1671 XP1_GRACEFUL_CLOSE | XP1_GUARANTEED_ORDER |
1672 XP1_GUARANTEED_DELIVERY;
1673 info->ProviderId = ProviderIdIP;
1674 info->dwCatalogEntryId = 0x3e9;
1675 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1676 info->ProtocolChain.ChainLen = 1;
1677 info->iVersion = 2;
1678 info->iAddressFamily = WS_AF_INET;
1679 info->iMaxSockAddr = 0x10;
1680 info->iMinSockAddr = 0x10;
1681 info->iSocketType = WS_SOCK_STREAM;
1682 strcpyW( info->szProtocol, NameTcpW );
1683 break;
1685 case WS_IPPROTO_UDP:
1686 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_SUPPORT_BROADCAST |
1687 XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED |
1688 XP1_CONNECTIONLESS;
1689 info->ProviderId = ProviderIdIP;
1690 info->dwCatalogEntryId = 0x3ea;
1691 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1692 info->ProtocolChain.ChainLen = 1;
1693 info->iVersion = 2;
1694 info->iAddressFamily = WS_AF_INET;
1695 info->iMaxSockAddr = 0x10;
1696 info->iMinSockAddr = 0x10;
1697 info->iSocketType = WS_SOCK_DGRAM;
1698 info->dwMessageSize = 0xffbb;
1699 strcpyW( info->szProtocol, NameUdpW );
1700 break;
1702 case WS_NSPROTO_IPX:
1703 info->dwServiceFlags1 = XP1_PARTIAL_MESSAGE | XP1_SUPPORT_BROADCAST |
1704 XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED |
1705 XP1_CONNECTIONLESS;
1706 info->ProviderId = ProviderIdIPX;
1707 info->dwCatalogEntryId = 0x406;
1708 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1709 info->ProtocolChain.ChainLen = 1;
1710 info->iVersion = 2;
1711 info->iAddressFamily = WS_AF_IPX;
1712 info->iMaxSockAddr = 0x10;
1713 info->iMinSockAddr = 0x0e;
1714 info->iSocketType = WS_SOCK_DGRAM;
1715 info->iProtocolMaxOffset = 0xff;
1716 info->dwMessageSize = 0x240;
1717 strcpyW( info->szProtocol, NameIpxW );
1718 break;
1720 case WS_NSPROTO_SPX:
1721 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_PSEUDO_STREAM |
1722 XP1_MESSAGE_ORIENTED | XP1_GUARANTEED_ORDER |
1723 XP1_GUARANTEED_DELIVERY;
1724 info->ProviderId = ProviderIdSPX;
1725 info->dwCatalogEntryId = 0x407;
1726 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1727 info->ProtocolChain.ChainLen = 1;
1728 info->iVersion = 2;
1729 info->iAddressFamily = WS_AF_IPX;
1730 info->iMaxSockAddr = 0x10;
1731 info->iMinSockAddr = 0x0e;
1732 info->iSocketType = WS_SOCK_SEQPACKET;
1733 info->dwMessageSize = 0xffffffff;
1734 strcpyW( info->szProtocol, NameSpxW );
1735 break;
1737 case WS_NSPROTO_SPXII:
1738 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_GRACEFUL_CLOSE |
1739 XP1_PSEUDO_STREAM | XP1_MESSAGE_ORIENTED |
1740 XP1_GUARANTEED_ORDER | XP1_GUARANTEED_DELIVERY;
1741 info->ProviderId = ProviderIdSPX;
1742 info->dwCatalogEntryId = 0x409;
1743 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1744 info->ProtocolChain.ChainLen = 1;
1745 info->iVersion = 2;
1746 info->iAddressFamily = WS_AF_IPX;
1747 info->iMaxSockAddr = 0x10;
1748 info->iMinSockAddr = 0x0e;
1749 info->iSocketType = WS_SOCK_SEQPACKET;
1750 info->dwMessageSize = 0xffffffff;
1751 strcpyW( info->szProtocol, NameSpxIIW );
1752 break;
1754 default:
1755 FIXME("unknown Protocol <0x%08x>\n", protocol);
1756 return FALSE;
1758 return TRUE;
1761 /*****************************************************************************
1762 * WS_EnterSingleProtocolA [internal]
1764 * see function WS_EnterSingleProtocolW
1767 static BOOL WS_EnterSingleProtocolA( INT protocol, WSAPROTOCOL_INFOA* info )
1769 WSAPROTOCOL_INFOW infow;
1770 INT ret;
1771 memset( info, 0, sizeof(WSAPROTOCOL_INFOA) );
1773 ret = WS_EnterSingleProtocolW( protocol, &infow );
1774 if (ret)
1776 /* convert the structure from W to A */
1777 memcpy( info, &infow, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
1778 WideCharToMultiByte( CP_ACP, 0, infow.szProtocol, -1,
1779 info->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL );
1782 return ret;
1785 static INT WS_EnumProtocols( BOOL unicode, const INT *protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
1787 INT i = 0, items = 0;
1788 DWORD size = 0;
1789 union _info
1791 LPWSAPROTOCOL_INFOA a;
1792 LPWSAPROTOCOL_INFOW w;
1793 } info;
1794 info.w = buffer;
1796 if (!protocols) protocols = valid_protocols;
1798 while (protocols[i])
1800 if(supported_protocol(protocols[i++]))
1801 items++;
1804 size = items * (unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA));
1806 TRACE("unicode %d, protocols %p, buffer %p, length %p %d, items %d, required %d\n",
1807 unicode, protocols, buffer, len, len ? *len : 0, items, size);
1809 if (*len < size || !buffer)
1811 *len = size;
1812 WSASetLastError(WSAENOBUFS);
1813 return SOCKET_ERROR;
1816 for (i = items = 0; protocols[i]; i++)
1818 if (unicode)
1820 if (WS_EnterSingleProtocolW( protocols[i], &info.w[items] ))
1821 items++;
1823 else
1825 if (WS_EnterSingleProtocolA( protocols[i], &info.a[items] ))
1826 items++;
1829 return items;
1832 static BOOL ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size)
1834 NTSTATUS status;
1836 *size = unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA);
1837 memset(buffer, 0, *size);
1839 SERVER_START_REQ( get_socket_info )
1841 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1842 status = wine_server_call( req );
1843 if (!status)
1845 buffer->iAddressFamily = convert_af_u2w(reply->family);
1846 buffer->iSocketType = convert_socktype_u2w(reply->type);
1847 buffer->iProtocol = convert_proto_u2w(reply->protocol);
1850 SERVER_END_REQ;
1852 if (status)
1854 unsigned int err = NtStatusToWSAError( status );
1855 SetLastError( err == WSAEBADF ? WSAENOTSOCK : err );
1856 return FALSE;
1859 if (unicode)
1860 WS_EnterSingleProtocolW( buffer->iProtocol, buffer);
1861 else
1862 WS_EnterSingleProtocolA( buffer->iProtocol, (WSAPROTOCOL_INFOA *)buffer);
1864 return TRUE;
1867 /**************************************************************************
1868 * Functions for handling overlapped I/O
1869 **************************************************************************/
1871 /* user APC called upon async completion */
1872 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1874 ws2_async *wsa = arg;
1876 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
1877 iosb->Information, wsa->user_overlapped,
1878 wsa->flags );
1879 HeapFree( GetProcessHeap(), 0, wsa );
1882 /***********************************************************************
1883 * WS2_recv (INTERNAL)
1885 * Workhorse for both synchronous and asynchronous recv() operations.
1887 static int WS2_recv( int fd, struct ws2_async *wsa )
1889 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1890 char pktbuf[512];
1891 #endif
1892 struct msghdr hdr;
1893 union generic_unix_sockaddr unix_sockaddr;
1894 int n;
1896 hdr.msg_name = NULL;
1898 if (wsa->addr)
1900 hdr.msg_namelen = sizeof(unix_sockaddr);
1901 hdr.msg_name = &unix_sockaddr;
1903 else
1904 hdr.msg_namelen = 0;
1906 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1907 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1908 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1909 hdr.msg_accrights = NULL;
1910 hdr.msg_accrightslen = 0;
1911 #else
1912 hdr.msg_control = pktbuf;
1913 hdr.msg_controllen = sizeof(pktbuf);
1914 hdr.msg_flags = 0;
1915 #endif
1917 if ( (n = recvmsg(fd, &hdr, wsa->flags)) == -1 )
1918 return -1;
1920 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1921 if (wsa->control)
1923 ERR("Message control headers cannot be properly supported on this system.\n");
1924 wsa->control->len = 0;
1926 #else
1927 if (wsa->control && !convert_control_headers(&hdr, wsa->control))
1929 WARN("Application passed insufficient room for control headers.\n");
1930 *wsa->lpFlags |= WS_MSG_CTRUNC;
1931 errno = EMSGSIZE;
1932 return -1;
1934 #endif
1936 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
1937 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
1939 * quoting linux 2.6 net/ipv4/tcp.c:
1940 * "According to UNIX98, msg_name/msg_namelen are ignored
1941 * on connected socket. I was just happy when found this 8) --ANK"
1943 * likewise MSDN says that lpFrom and lpFromlen are ignored for
1944 * connection-oriented sockets, so don't try to update lpFrom.
1946 if (wsa->addr && hdr.msg_namelen)
1947 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
1949 return n;
1952 /***********************************************************************
1953 * WS2_async_recv (INTERNAL)
1955 * Handler for overlapped recv() operations.
1957 static NTSTATUS WS2_async_recv( void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1959 ws2_async* wsa = user;
1960 int result = 0, fd;
1962 switch (status)
1964 case STATUS_ALERTED:
1965 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
1966 break;
1968 result = WS2_recv( fd, wsa );
1969 wine_server_release_fd( wsa->hSocket, fd );
1970 if (result >= 0)
1972 status = STATUS_SUCCESS;
1973 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1975 else
1977 if (errno == EINTR || errno == EAGAIN)
1979 status = STATUS_PENDING;
1980 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1982 else
1984 result = 0;
1985 status = wsaErrStatus();
1988 break;
1990 if (status != STATUS_PENDING)
1992 iosb->u.Status = status;
1993 iosb->Information = result;
1994 *apc = ws2_async_apc;
1996 return status;
1999 /* user APC called upon async accept completion */
2000 static void WINAPI ws2_async_accept_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
2002 struct ws2_accept_async *wsa = arg;
2004 HeapFree( GetProcessHeap(), 0, wsa->read );
2005 HeapFree( GetProcessHeap(), 0, wsa );
2008 /***********************************************************************
2009 * WS2_async_accept_recv (INTERNAL)
2011 * This function is used to finish the read part of an accept request. It is
2012 * needed to place the completion on the correct socket (listener).
2014 static NTSTATUS WS2_async_accept_recv( void *arg, IO_STATUS_BLOCK *iosb, NTSTATUS status, void **apc )
2016 void *junk;
2017 struct ws2_accept_async *wsa = arg;
2019 status = WS2_async_recv( wsa->read, iosb, status, &junk );
2020 if (status == STATUS_PENDING)
2021 return status;
2023 if (wsa->user_overlapped->hEvent)
2024 SetEvent(wsa->user_overlapped->hEvent);
2025 if (wsa->cvalue)
2026 WS_AddCompletion( HANDLE2SOCKET(wsa->listen_socket), wsa->cvalue, iosb->u.Status, iosb->Information );
2028 *apc = ws2_async_accept_apc;
2029 return status;
2032 /***********************************************************************
2033 * WS2_async_accept (INTERNAL)
2035 * This is the function called to satisfy the AcceptEx callback
2037 static NTSTATUS WS2_async_accept( void *arg, IO_STATUS_BLOCK *iosb, NTSTATUS status, void **apc )
2039 struct ws2_accept_async *wsa = arg;
2040 int len;
2041 char *addr;
2043 TRACE("status: 0x%x listen: %p, accept: %p\n", status, wsa->listen_socket, wsa->accept_socket);
2045 if (status == STATUS_ALERTED)
2047 SERVER_START_REQ( accept_into_socket )
2049 req->lhandle = wine_server_obj_handle( wsa->listen_socket );
2050 req->ahandle = wine_server_obj_handle( wsa->accept_socket );
2051 status = wine_server_call( req );
2053 SERVER_END_REQ;
2055 if (status == STATUS_CANT_WAIT)
2056 return STATUS_PENDING;
2058 if (status == STATUS_INVALID_HANDLE)
2060 FIXME("AcceptEx accepting socket closed but request was not cancelled\n");
2061 status = STATUS_CANCELLED;
2064 else if (status == STATUS_HANDLES_CLOSED)
2065 status = STATUS_CANCELLED; /* strange windows behavior */
2067 if (status != STATUS_SUCCESS)
2068 goto finish;
2070 /* WS2 Spec says size param is extra 16 bytes long...what do we put in it? */
2071 addr = ((char *)wsa->buf) + wsa->data_len;
2072 len = wsa->local_len - sizeof(int);
2073 WS_getsockname(HANDLE2SOCKET(wsa->accept_socket),
2074 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
2075 *(int *)addr = len;
2077 addr += wsa->local_len;
2078 len = wsa->remote_len - sizeof(int);
2079 WS_getpeername(HANDLE2SOCKET(wsa->accept_socket),
2080 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
2081 *(int *)addr = len;
2083 if (!wsa->read)
2084 goto finish;
2086 SERVER_START_REQ( register_async )
2088 req->type = ASYNC_TYPE_READ;
2089 req->async.handle = wine_server_obj_handle( wsa->accept_socket );
2090 req->async.callback = wine_server_client_ptr( WS2_async_accept_recv );
2091 req->async.iosb = wine_server_client_ptr( iosb );
2092 req->async.arg = wine_server_client_ptr( wsa );
2093 status = wine_server_call( req );
2095 SERVER_END_REQ;
2097 if (status != STATUS_PENDING)
2098 goto finish;
2100 /* The APC has finished but no completion should be sent for the operation yet, additional processing
2101 * needs to be performed by WS2_async_accept_recv() first. */
2102 return STATUS_MORE_PROCESSING_REQUIRED;
2104 finish:
2105 iosb->u.Status = status;
2106 iosb->Information = 0;
2108 if (wsa->user_overlapped->hEvent)
2109 SetEvent(wsa->user_overlapped->hEvent);
2111 *apc = ws2_async_accept_apc;
2112 return status;
2115 /***********************************************************************
2116 * WS2_send (INTERNAL)
2118 * Workhorse for both synchronous and asynchronous send() operations.
2120 static int WS2_send( int fd, struct ws2_async *wsa )
2122 struct msghdr hdr;
2123 union generic_unix_sockaddr unix_addr;
2124 int n, ret;
2126 hdr.msg_name = NULL;
2127 hdr.msg_namelen = 0;
2129 if (wsa->addr)
2131 hdr.msg_name = &unix_addr;
2132 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
2133 if ( !hdr.msg_namelen )
2135 errno = EFAULT;
2136 return -1;
2139 #if defined(HAS_IPX) && defined(SOL_IPX)
2140 if(wsa->addr->sa_family == WS_AF_IPX)
2142 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
2143 int val=0;
2144 socklen_t len = sizeof(int);
2146 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
2147 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
2148 * the packet type and then we can retrieve it using getsockopt. After that we can set the
2149 * ipx type in the sockaddr_opx structure with the stored value.
2151 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
2152 uipx->sipx_type = val;
2154 #endif
2157 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
2158 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
2159 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2160 hdr.msg_accrights = NULL;
2161 hdr.msg_accrightslen = 0;
2162 #else
2163 hdr.msg_control = NULL;
2164 hdr.msg_controllen = 0;
2165 hdr.msg_flags = 0;
2166 #endif
2168 ret = sendmsg(fd, &hdr, wsa->flags);
2169 if (ret >= 0)
2171 n = ret;
2172 while (wsa->first_iovec < wsa->n_iovecs && wsa->iovec[wsa->first_iovec].iov_len <= n)
2173 n -= wsa->iovec[wsa->first_iovec++].iov_len;
2174 if (wsa->first_iovec < wsa->n_iovecs)
2176 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
2177 wsa->iovec[wsa->first_iovec].iov_len -= n;
2180 return ret;
2183 /***********************************************************************
2184 * WS2_async_send (INTERNAL)
2186 * Handler for overlapped send() operations.
2188 static NTSTATUS WS2_async_send(void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
2190 ws2_async* wsa = user;
2191 int result = 0, fd;
2193 switch (status)
2195 case STATUS_ALERTED:
2196 if ( wsa->n_iovecs <= wsa->first_iovec )
2198 /* Nothing to do */
2199 status = STATUS_SUCCESS;
2200 break;
2202 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
2203 break;
2205 /* check to see if the data is ready (non-blocking) */
2206 result = WS2_send( fd, wsa );
2207 wine_server_release_fd( wsa->hSocket, fd );
2209 if (result >= 0)
2211 if (wsa->first_iovec < wsa->n_iovecs)
2212 status = STATUS_PENDING;
2213 else
2214 status = STATUS_SUCCESS;
2216 iosb->Information += result;
2218 else if (errno == EINTR || errno == EAGAIN)
2220 status = STATUS_PENDING;
2222 else
2224 status = wsaErrStatus();
2226 break;
2228 if (status != STATUS_PENDING)
2230 iosb->u.Status = status;
2231 *apc = ws2_async_apc;
2233 return status;
2236 /***********************************************************************
2237 * WS2_async_shutdown (INTERNAL)
2239 * Handler for shutdown() operations on overlapped sockets.
2241 static NTSTATUS WS2_async_shutdown( void* user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc )
2243 ws2_async* wsa = user;
2244 int fd, err = 1;
2246 switch (status)
2248 case STATUS_ALERTED:
2249 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
2250 break;
2252 switch ( wsa->type )
2254 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
2255 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
2257 status = err ? wsaErrStatus() : STATUS_SUCCESS;
2258 wine_server_release_fd( wsa->hSocket, fd );
2259 break;
2261 iosb->u.Status = status;
2262 iosb->Information = 0;
2263 *apc = ws2_async_apc;
2264 return status;
2267 /***********************************************************************
2268 * WS2_register_async_shutdown (INTERNAL)
2270 * Helper function for WS_shutdown() on overlapped sockets.
2272 static int WS2_register_async_shutdown( SOCKET s, int type )
2274 struct ws2_async *wsa;
2275 NTSTATUS status;
2277 TRACE("s %ld type %d\n", s, type);
2279 wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( struct ws2_async, iovec[1] ));
2280 if ( !wsa )
2281 return WSAEFAULT;
2283 wsa->hSocket = SOCKET2HANDLE(s);
2284 wsa->type = type;
2285 wsa->completion_func = NULL;
2287 SERVER_START_REQ( register_async )
2289 req->type = type;
2290 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2291 req->async.callback = wine_server_client_ptr( WS2_async_shutdown );
2292 req->async.iosb = wine_server_client_ptr( &wsa->local_iosb );
2293 req->async.arg = wine_server_client_ptr( wsa );
2294 req->async.cvalue = 0;
2295 status = wine_server_call( req );
2297 SERVER_END_REQ;
2299 if (status != STATUS_PENDING)
2301 HeapFree( GetProcessHeap(), 0, wsa );
2302 return NtStatusToWSAError( status );
2304 return 0;
2307 /***********************************************************************
2308 * accept (WS2_32.1)
2310 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr, int *addrlen32)
2312 NTSTATUS status;
2313 SOCKET as;
2314 BOOL is_blocking;
2316 TRACE("socket %04lx\n", s );
2317 status = _is_blocking(s, &is_blocking);
2318 if (status)
2320 set_error(status);
2321 return INVALID_SOCKET;
2324 do {
2325 /* try accepting first (if there is a deferred connection) */
2326 SERVER_START_REQ( accept_socket )
2328 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
2329 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
2330 req->attributes = OBJ_INHERIT;
2331 status = wine_server_call( req );
2332 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
2334 SERVER_END_REQ;
2335 if (!status)
2337 if (addr && WS_getpeername(as, addr, addrlen32))
2339 WS_closesocket(as);
2340 return SOCKET_ERROR;
2342 return as;
2344 if (is_blocking && status == STATUS_CANT_WAIT)
2346 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2347 /* block here */
2348 do_block(fd, POLLIN, -1);
2349 _sync_sock_state(s); /* let wineserver notice connection */
2350 release_sock_fd( s, fd );
2352 } while (is_blocking && status == STATUS_CANT_WAIT);
2354 set_error(status);
2355 return INVALID_SOCKET;
2358 /***********************************************************************
2359 * AcceptEx
2361 static BOOL WINAPI WS2_AcceptEx(SOCKET listener, SOCKET acceptor, PVOID dest, DWORD dest_len,
2362 DWORD local_addr_len, DWORD rem_addr_len, LPDWORD received,
2363 LPOVERLAPPED overlapped)
2365 DWORD status;
2366 struct ws2_accept_async *wsa;
2367 int fd;
2368 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
2370 TRACE("(%lx, %lx, %p, %d, %d, %d, %p, %p)\n", listener, acceptor, dest, dest_len, local_addr_len,
2371 rem_addr_len, received, overlapped);
2373 if (!dest)
2375 SetLastError(WSAEINVAL);
2376 return FALSE;
2379 if (!overlapped)
2381 SetLastError(WSA_INVALID_PARAMETER);
2382 return FALSE;
2385 if ((local_addr_len < sizeof(struct sockaddr_in) + 16)
2386 || (rem_addr_len < sizeof(struct sockaddr_in) + 16))
2388 SetLastError(WSAEINVAL);
2389 return FALSE;
2392 fd = get_sock_fd( listener, FILE_READ_DATA, NULL );
2393 if (fd == -1)
2395 SetLastError(WSAENOTSOCK);
2396 return FALSE;
2398 release_sock_fd( listener, fd );
2400 fd = get_sock_fd( acceptor, FILE_READ_DATA, NULL );
2401 if (fd == -1)
2403 SetLastError(WSAEINVAL);
2404 return FALSE;
2406 release_sock_fd( acceptor, fd );
2408 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
2409 if(!wsa)
2411 SetLastError(WSAEFAULT);
2412 return FALSE;
2415 wsa->listen_socket = SOCKET2HANDLE(listener);
2416 wsa->accept_socket = SOCKET2HANDLE(acceptor);
2417 wsa->user_overlapped = overlapped;
2418 wsa->cvalue = cvalue;
2419 wsa->buf = dest;
2420 wsa->data_len = dest_len;
2421 wsa->local_len = local_addr_len;
2422 wsa->remote_len = rem_addr_len;
2423 wsa->read = NULL;
2425 if (wsa->data_len)
2427 /* set up a read request if we need it */
2428 wsa->read = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[1]) );
2429 if (!wsa->read)
2431 HeapFree( GetProcessHeap(), 0, wsa );
2432 SetLastError(WSAEFAULT);
2433 return FALSE;
2436 wsa->read->hSocket = wsa->accept_socket;
2437 wsa->read->flags = 0;
2438 wsa->read->lpFlags = &wsa->read->flags;
2439 wsa->read->addr = NULL;
2440 wsa->read->addrlen.ptr = NULL;
2441 wsa->read->control = NULL;
2442 wsa->read->n_iovecs = 1;
2443 wsa->read->first_iovec = 0;
2444 wsa->read->iovec[0].iov_base = wsa->buf;
2445 wsa->read->iovec[0].iov_len = wsa->data_len;
2448 SERVER_START_REQ( register_async )
2450 req->type = ASYNC_TYPE_READ;
2451 req->async.handle = wine_server_obj_handle( SOCKET2HANDLE(listener) );
2452 req->async.callback = wine_server_client_ptr( WS2_async_accept );
2453 req->async.iosb = wine_server_client_ptr( overlapped );
2454 req->async.arg = wine_server_client_ptr( wsa );
2455 req->async.cvalue = cvalue;
2456 /* We don't set event since we may also have to read */
2457 status = wine_server_call( req );
2459 SERVER_END_REQ;
2461 if(status != STATUS_PENDING)
2463 HeapFree( GetProcessHeap(), 0, wsa->read );
2464 HeapFree( GetProcessHeap(), 0, wsa );
2467 SetLastError( NtStatusToWSAError(status) );
2468 return FALSE;
2471 /***********************************************************************
2472 * GetAcceptExSockaddrs
2474 static void WINAPI WS2_GetAcceptExSockaddrs(PVOID buffer, DWORD data_size, DWORD local_size, DWORD remote_size,
2475 struct WS_sockaddr **local_addr, LPINT local_addr_len,
2476 struct WS_sockaddr **remote_addr, LPINT remote_addr_len)
2478 char *cbuf = buffer;
2479 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer, data_size, local_size, remote_size, local_addr,
2480 local_addr_len, remote_addr, remote_addr_len );
2481 cbuf += data_size;
2483 *local_addr_len = *(int *) cbuf;
2484 *local_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2486 cbuf += local_size;
2488 *remote_addr_len = *(int *) cbuf;
2489 *remote_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2492 /***********************************************************************
2493 * WSASendMsg
2495 int WINAPI WSASendMsg( SOCKET s, LPWSAMSG msg, DWORD dwFlags, LPDWORD lpNumberOfBytesSent,
2496 LPWSAOVERLAPPED lpOverlapped,
2497 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
2499 if (!msg)
2501 SetLastError( WSAEFAULT );
2502 return SOCKET_ERROR;
2505 return WS2_sendto( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesSent,
2506 dwFlags, msg->name, msg->namelen,
2507 lpOverlapped, lpCompletionRoutine );
2510 /***********************************************************************
2511 * WSARecvMsg
2513 * Perform a receive operation that is capable of returning message
2514 * control headers. It is important to note that the WSAMSG parameter
2515 * must remain valid throughout the operation, even when an overlapped
2516 * receive is performed.
2518 static int WINAPI WS2_WSARecvMsg( SOCKET s, LPWSAMSG msg, LPDWORD lpNumberOfBytesRecvd,
2519 LPWSAOVERLAPPED lpOverlapped,
2520 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2522 if (!msg)
2524 SetLastError( WSAEFAULT );
2525 return SOCKET_ERROR;
2528 return WS2_recv_base( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesRecvd,
2529 &msg->dwFlags, msg->name, &msg->namelen,
2530 lpOverlapped, lpCompletionRoutine, &msg->Control );
2533 /***********************************************************************
2534 * interface_bind (INTERNAL)
2536 * Take bind() calls on any name corresponding to a local network adapter and restrict the given socket to
2537 * operating only on the specified interface. This restriction consists of two components:
2538 * 1) An outgoing packet restriction suggesting the egress interface for all packets.
2539 * 2) An incoming packet restriction dropping packets not meant for the interface.
2540 * If the function succeeds in placing these restrictions (returns TRUE) then the name for the bind() may
2541 * safely be changed to INADDR_ANY, permitting the transmission and receipt of broadcast packets on the
2542 * socket. This behavior is only relevant to UDP sockets and is needed for applications that expect to be able
2543 * to receive broadcast packets on a socket that is bound to a specific network interface.
2545 static BOOL interface_bind( SOCKET s, int fd, struct sockaddr *addr )
2547 struct sockaddr_in *in_sock = (struct sockaddr_in *) addr;
2548 unsigned int sock_type = 0;
2549 socklen_t optlen = sizeof(sock_type);
2550 in_addr_t bind_addr = in_sock->sin_addr.s_addr;
2551 PIP_ADAPTER_INFO adapters = NULL, adapter;
2552 BOOL ret = FALSE;
2553 DWORD adap_size;
2554 int enable = 1;
2556 if (bind_addr == htonl(WS_INADDR_ANY) || bind_addr == htonl(WS_INADDR_LOOPBACK))
2557 return FALSE; /* Not binding to a network adapter, special interface binding unnecessary. */
2558 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &sock_type, &optlen) == -1 || sock_type != SOCK_DGRAM)
2559 return FALSE; /* Special interface binding is only necessary for UDP datagrams. */
2560 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
2561 goto cleanup;
2562 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
2563 if (adapters == NULL || GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
2564 goto cleanup;
2565 /* Search the IPv4 adapter list for the appropriate binding interface */
2566 for (adapter = adapters; adapter != NULL; adapter = adapter->Next)
2568 in_addr_t adapter_addr = (in_addr_t) inet_addr(adapter->IpAddressList.IpAddress.String);
2570 if (bind_addr == adapter_addr)
2572 #if defined(IP_BOUND_IF)
2573 /* IP_BOUND_IF sets both the incoming and outgoing restriction at once */
2574 if (setsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &adapter->Index, sizeof(adapter->Index)) != 0)
2575 goto cleanup;
2576 ret = TRUE;
2577 #elif defined(LINUX_BOUND_IF)
2578 in_addr_t ifindex = (in_addr_t) htonl(adapter->Index);
2579 struct interface_filter specific_interface_filter;
2580 struct sock_fprog filter_prog;
2582 if (setsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex, sizeof(ifindex)) != 0)
2583 goto cleanup; /* Failed to suggest egress interface */
2584 specific_interface_filter = generic_interface_filter;
2585 specific_interface_filter.iface_rule.k = adapter->Index;
2586 specific_interface_filter.ip_rule.k = htonl(adapter_addr);
2587 filter_prog.len = sizeof(generic_interface_filter)/sizeof(struct sock_filter);
2588 filter_prog.filter = (struct sock_filter *) &specific_interface_filter;
2589 if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog, sizeof(filter_prog)) != 0)
2590 goto cleanup; /* Failed to specify incoming packet filter */
2591 ret = TRUE;
2592 #else
2593 FIXME("Broadcast packets on interface-bound sockets are not currently supported on this platform, "
2594 "receiving broadcast packets will not work on socket %04lx.\n", s);
2595 #endif
2596 break;
2599 /* Will soon be switching to INADDR_ANY: permit address reuse */
2600 if (ret && setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) == 0)
2601 TRACE("Socket %04lx bound to interface index %d\n", s, adapter->Index);
2602 else
2603 ret = FALSE;
2605 cleanup:
2606 if(!ret)
2607 ERR("Failed to bind to interface, receiving broadcast packets will not work on socket %04lx.\n", s);
2608 HeapFree(GetProcessHeap(), 0, adapters);
2609 return ret;
2612 /***********************************************************************
2613 * bind (WS2_32.2)
2615 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
2617 int fd = get_sock_fd( s, 0, NULL );
2618 int res = SOCKET_ERROR;
2620 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2622 if (fd != -1)
2624 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
2626 SetLastError(WSAEAFNOSUPPORT);
2628 else
2630 union generic_unix_sockaddr uaddr;
2631 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2632 if (!uaddrlen)
2634 SetLastError(WSAEFAULT);
2636 else
2638 #ifdef IPV6_V6ONLY
2639 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
2640 if (name->sa_family == WS_AF_INET6 &&
2641 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
2643 int enable = 1;
2644 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
2646 release_sock_fd( s, fd );
2647 SetLastError(WSAEAFNOSUPPORT);
2648 return SOCKET_ERROR;
2651 #endif
2652 if (name->sa_family == WS_AF_INET)
2654 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2655 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2657 /* Trying to bind to the default host interface, using
2658 * INADDR_ANY instead*/
2659 WARN("Trying to bind to magic IP address, using "
2660 "INADDR_ANY instead.\n");
2661 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
2663 else if (interface_bind(s, fd, &uaddr.addr))
2664 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
2666 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
2668 int loc_errno = errno;
2669 WARN("\tfailure - errno = %i\n", errno);
2670 errno = loc_errno;
2671 switch (errno)
2673 case EBADF:
2674 SetLastError(WSAENOTSOCK);
2675 break;
2676 case EADDRNOTAVAIL:
2677 SetLastError(WSAEINVAL);
2678 break;
2679 default:
2680 SetLastError(wsaErrno());
2681 break;
2684 else
2686 res=0; /* success */
2690 release_sock_fd( s, fd );
2692 return res;
2695 /***********************************************************************
2696 * closesocket (WS2_32.3)
2698 int WINAPI WS_closesocket(SOCKET s)
2700 TRACE("socket %04lx\n", s);
2701 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
2702 return SOCKET_ERROR;
2705 static int do_connect(int fd, const struct WS_sockaddr* name, int namelen)
2707 union generic_unix_sockaddr uaddr;
2708 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2710 if (!uaddrlen)
2711 return WSAEFAULT;
2713 if (name->sa_family == WS_AF_INET)
2715 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2716 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2718 /* Trying to connect to magic replace-loopback address,
2719 * assuming we really want to connect to localhost */
2720 TRACE("Trying to connect to magic IP address, using "
2721 "INADDR_LOOPBACK instead.\n");
2722 in4->sin_addr.s_addr = htonl(WS_INADDR_LOOPBACK);
2726 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
2727 return 0;
2729 return wsaErrno();
2732 /***********************************************************************
2733 * connect (WS2_32.4)
2735 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
2737 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2739 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2741 if (fd != -1)
2743 NTSTATUS status;
2744 BOOL is_blocking;
2745 int ret = do_connect(fd, name, namelen);
2746 if (ret == 0)
2747 goto connect_success;
2749 if (ret == WSAEINPROGRESS)
2751 /* tell wineserver that a connection is in progress */
2752 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2753 FD_CONNECT,
2754 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2755 status = _is_blocking( s, &is_blocking );
2756 if (status)
2758 release_sock_fd( s, fd );
2759 set_error( status );
2760 return SOCKET_ERROR;
2762 if (is_blocking)
2764 int result;
2765 /* block here */
2766 do_block(fd, POLLIN | POLLOUT, -1);
2767 _sync_sock_state(s); /* let wineserver notice connection */
2768 /* retrieve any error codes from it */
2769 result = _get_sock_error(s, FD_CONNECT_BIT);
2770 if (result)
2771 SetLastError(NtStatusToWSAError(result));
2772 else
2774 goto connect_success;
2777 else
2779 SetLastError(WSAEWOULDBLOCK);
2782 else
2784 SetLastError(ret);
2786 release_sock_fd( s, fd );
2788 return SOCKET_ERROR;
2790 connect_success:
2791 release_sock_fd( s, fd );
2792 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2793 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2794 FD_CONNECT|FD_WINE_LISTENING);
2795 return 0;
2798 /***********************************************************************
2799 * WSAConnect (WS2_32.30)
2801 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
2802 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
2803 LPQOS lpSQOS, LPQOS lpGQOS )
2805 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
2806 FIXME("unsupported parameters!\n");
2807 return WS_connect( s, name, namelen );
2810 /***********************************************************************
2811 * ConnectEx
2813 static BOOL WINAPI WS2_ConnectEx(SOCKET s, const struct WS_sockaddr* name, int namelen,
2814 PVOID sendBuf, DWORD sendBufLen, LPDWORD sent, LPOVERLAPPED ov)
2816 int fd, ret, status;
2817 union generic_unix_sockaddr uaddr;
2818 socklen_t uaddrlen = sizeof(uaddr);
2820 if (!ov)
2822 SetLastError( ERROR_INVALID_PARAMETER );
2823 return FALSE;
2826 fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2827 if (fd == -1)
2829 SetLastError( WSAENOTSOCK );
2830 return FALSE;
2833 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
2834 s, name, debugstr_sockaddr(name), namelen, sendBuf, sendBufLen, ov);
2836 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
2838 SetLastError(wsaErrno());
2839 return FALSE;
2841 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
2843 SetLastError(WSAEINVAL);
2844 return FALSE;
2847 ret = do_connect(fd, name, namelen);
2848 if (ret == 0)
2850 WSABUF wsabuf;
2852 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2853 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2854 FD_CONNECT|FD_WINE_LISTENING);
2856 wsabuf.len = sendBufLen;
2857 wsabuf.buf = (char*) sendBuf;
2859 /* WSASend takes care of completion if need be */
2860 if (WSASend(s, &wsabuf, sendBuf ? 1 : 0, sent, 0, ov, NULL) != SOCKET_ERROR)
2861 goto connection_success;
2863 else if (ret == WSAEINPROGRESS)
2865 struct ws2_async *wsa;
2866 ULONG_PTR cvalue = (((ULONG_PTR)ov->hEvent & 1) == 0) ? (ULONG_PTR)ov : 0;
2868 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2869 FD_CONNECT,
2870 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2872 /* Indirectly call WSASend */
2873 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( struct ws2_async, iovec[1] ))))
2875 SetLastError(WSAEFAULT);
2877 else
2879 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)ov;
2880 iosb->u.Status = STATUS_PENDING;
2881 iosb->Information = 0;
2883 wsa->hSocket = SOCKET2HANDLE(s);
2884 wsa->addr = NULL;
2885 wsa->addrlen.val = 0;
2886 wsa->flags = 0;
2887 wsa->lpFlags = &wsa->flags;
2888 wsa->control = NULL;
2889 wsa->n_iovecs = sendBuf ? 1 : 0;
2890 wsa->first_iovec = 0;
2891 wsa->completion_func = NULL;
2892 wsa->iovec[0].iov_base = sendBuf;
2893 wsa->iovec[0].iov_len = sendBufLen;
2895 SERVER_START_REQ( register_async )
2897 req->type = ASYNC_TYPE_WRITE;
2898 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2899 req->async.callback = wine_server_client_ptr( WS2_async_send );
2900 req->async.iosb = wine_server_client_ptr( iosb );
2901 req->async.arg = wine_server_client_ptr( wsa );
2902 req->async.event = wine_server_obj_handle( ov->hEvent );
2903 req->async.cvalue = cvalue;
2904 status = wine_server_call( req );
2906 SERVER_END_REQ;
2908 if (status != STATUS_PENDING) HeapFree(GetProcessHeap(), 0, wsa);
2910 /* If the connect already failed */
2911 if (status == STATUS_PIPE_DISCONNECTED)
2912 status = _get_sock_error(s, FD_CONNECT_BIT);
2913 SetLastError( NtStatusToWSAError(status) );
2916 else
2918 SetLastError(ret);
2921 release_sock_fd( s, fd );
2922 return FALSE;
2924 connection_success:
2925 release_sock_fd( s, fd );
2926 return TRUE;
2930 /***********************************************************************
2931 * getpeername (WS2_32.5)
2933 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
2935 int fd;
2936 int res;
2938 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
2940 fd = get_sock_fd( s, 0, NULL );
2941 res = SOCKET_ERROR;
2943 if (fd != -1)
2945 union generic_unix_sockaddr uaddr;
2946 socklen_t uaddrlen = sizeof(uaddr);
2948 if (getpeername(fd, &uaddr.addr, &uaddrlen) == 0)
2950 if (!name || !namelen)
2951 SetLastError(WSAEFAULT);
2952 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
2953 /* The buffer was too small */
2954 SetLastError(WSAEFAULT);
2955 else
2956 res = 0;
2958 else
2959 SetLastError(wsaErrno());
2960 release_sock_fd( s, fd );
2962 return res;
2965 /***********************************************************************
2966 * getsockname (WS2_32.6)
2968 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
2970 int fd;
2971 int res;
2973 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
2975 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
2976 if( (name == NULL) || (namelen == NULL) )
2978 SetLastError( WSAEFAULT );
2979 return SOCKET_ERROR;
2982 fd = get_sock_fd( s, 0, NULL );
2983 res = SOCKET_ERROR;
2985 if (fd != -1)
2987 union generic_unix_sockaddr uaddr;
2988 socklen_t uaddrlen = sizeof(uaddr);
2990 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
2992 SetLastError(wsaErrno());
2994 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
2996 SetLastError(WSAEINVAL);
2998 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3000 /* The buffer was too small */
3001 SetLastError(WSAEFAULT);
3003 else
3005 res=0;
3006 TRACE("=> %s\n", debugstr_sockaddr(name));
3008 release_sock_fd( s, fd );
3010 return res;
3013 /***********************************************************************
3014 * getsockopt (WS2_32.7)
3016 INT WINAPI WS_getsockopt(SOCKET s, INT level,
3017 INT optname, char *optval, INT *optlen)
3019 int fd;
3020 INT ret = 0;
3022 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
3023 s, level, optname, optval, optlen ? *optlen : 0);
3025 switch(level)
3027 case WS_SOL_SOCKET:
3029 switch(optname)
3031 /* Handle common cases. The special cases are below, sorted
3032 * alphabetically */
3033 case WS_SO_BROADCAST:
3034 case WS_SO_DEBUG:
3035 case WS_SO_ERROR:
3036 case WS_SO_KEEPALIVE:
3037 case WS_SO_OOBINLINE:
3038 case WS_SO_RCVBUF:
3039 case WS_SO_REUSEADDR:
3040 case WS_SO_SNDBUF:
3041 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3042 return SOCKET_ERROR;
3043 convert_sockopt(&level, &optname);
3044 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3046 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3047 ret = SOCKET_ERROR;
3049 release_sock_fd( s, fd );
3050 return ret;
3051 case WS_SO_ACCEPTCONN:
3052 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3053 return SOCKET_ERROR;
3054 if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, optval, (socklen_t *)optlen) != 0 )
3056 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3057 ret = SOCKET_ERROR;
3059 else
3061 /* BSD returns != 0 while Windows return exact == 1 */
3062 if (*(int *)optval) *(int *)optval = 1;
3064 release_sock_fd( s, fd );
3065 return ret;
3066 case WS_SO_DONTLINGER:
3068 struct linger lingval;
3069 socklen_t len = sizeof(struct linger);
3071 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
3073 SetLastError(WSAEFAULT);
3074 return SOCKET_ERROR;
3076 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3077 return SOCKET_ERROR;
3079 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
3081 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3082 ret = SOCKET_ERROR;
3084 else
3086 *(BOOL *)optval = !lingval.l_onoff;
3087 *optlen = sizeof(BOOL);
3090 release_sock_fd( s, fd );
3091 return ret;
3094 case WS_SO_CONNECT_TIME:
3096 static int pretendtime = 0;
3097 struct WS_sockaddr addr;
3098 int len = sizeof(addr);
3100 if (!optlen || *optlen < sizeof(DWORD) || !optval)
3102 SetLastError(WSAEFAULT);
3103 return SOCKET_ERROR;
3105 if (WS_getpeername(s, &addr, &len) == SOCKET_ERROR)
3106 *(DWORD *)optval = ~0u;
3107 else
3109 if (!pretendtime) FIXME("WS_SO_CONNECT_TIME - faking results\n");
3110 *(DWORD *)optval = pretendtime++;
3112 *optlen = sizeof(DWORD);
3113 return ret;
3115 /* As mentioned in setsockopt, Windows ignores this, so we
3116 * always return true here */
3117 case WS_SO_DONTROUTE:
3118 if (!optlen || *optlen < sizeof(BOOL) || !optval)
3120 SetLastError(WSAEFAULT);
3121 return SOCKET_ERROR;
3123 *(BOOL *)optval = TRUE;
3124 *optlen = sizeof(BOOL);
3125 return 0;
3127 case WS_SO_LINGER:
3129 struct linger lingval;
3130 int so_type;
3131 socklen_t len = sizeof(struct linger), slen = sizeof(int);
3133 /* struct linger and LINGER have different sizes */
3134 if (!optlen || *optlen < sizeof(LINGER) || !optval)
3136 SetLastError(WSAEFAULT);
3137 return SOCKET_ERROR;
3139 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3140 return SOCKET_ERROR;
3142 if ((getsockopt(fd, SOL_SOCKET, SO_TYPE, &so_type, &slen) == 0 && so_type == SOCK_DGRAM))
3144 SetLastError(WSAENOPROTOOPT);
3145 ret = SOCKET_ERROR;
3147 else if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0)
3149 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3150 ret = SOCKET_ERROR;
3152 else
3154 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
3155 ((LINGER *)optval)->l_linger = lingval.l_linger;
3156 *optlen = sizeof(struct linger);
3159 release_sock_fd( s, fd );
3160 return ret;
3163 case WS_SO_MAX_MSG_SIZE:
3164 if (!optlen || *optlen < sizeof(int) || !optval)
3166 SetLastError(WSAEFAULT);
3167 return SOCKET_ERROR;
3169 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
3170 *(int *)optval = 65507;
3171 *optlen = sizeof(int);
3172 return 0;
3174 /* SO_OPENTYPE does not require a valid socket handle. */
3175 case WS_SO_OPENTYPE:
3176 if (!optlen || *optlen < sizeof(int) || !optval)
3178 SetLastError(WSAEFAULT);
3179 return SOCKET_ERROR;
3181 *(int *)optval = get_per_thread_data()->opentype;
3182 *optlen = sizeof(int);
3183 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
3184 return 0;
3185 case WS_SO_PROTOCOL_INFOA:
3186 case WS_SO_PROTOCOL_INFOW:
3188 int size;
3189 WSAPROTOCOL_INFOW infow;
3191 ret = ws_protocol_info(s, optname == WS_SO_PROTOCOL_INFOW, &infow, &size);
3192 if (ret)
3194 if (!optlen || !optval || *optlen < size)
3196 if(optlen) *optlen = size;
3197 ret = 0;
3198 SetLastError(WSAEFAULT);
3200 else
3201 memcpy(optval, &infow, size);
3203 return ret ? 0 : SOCKET_ERROR;
3205 #ifdef SO_RCVTIMEO
3206 case WS_SO_RCVTIMEO:
3207 #endif
3208 #ifdef SO_SNDTIMEO
3209 case WS_SO_SNDTIMEO:
3210 #endif
3211 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
3213 struct timeval tv;
3214 socklen_t len = sizeof(struct timeval);
3216 if (!optlen || *optlen < sizeof(int)|| !optval)
3218 SetLastError(WSAEFAULT);
3219 return SOCKET_ERROR;
3221 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3222 return SOCKET_ERROR;
3224 convert_sockopt(&level, &optname);
3225 if (getsockopt(fd, level, optname, &tv, &len) != 0 )
3227 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3228 ret = SOCKET_ERROR;
3230 else
3232 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
3233 *optlen = sizeof(int);
3236 release_sock_fd( s, fd );
3237 return ret;
3239 #endif
3240 case WS_SO_TYPE:
3242 if (!optlen || *optlen < sizeof(int) || !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, optval, (socklen_t *)optlen) != 0 )
3252 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3253 ret = SOCKET_ERROR;
3255 else
3256 (*(int *)optval) = convert_socktype_u2w(*(int *)optval);
3258 release_sock_fd( s, fd );
3259 return ret;
3261 default:
3262 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
3263 SetLastError(WSAENOPROTOOPT);
3264 return SOCKET_ERROR;
3265 } /* end switch(optname) */
3266 }/* end case WS_SOL_SOCKET */
3267 #ifdef HAS_IPX
3268 case WS_NSPROTO_IPX:
3270 struct WS_sockaddr_ipx addr;
3271 IPX_ADDRESS_DATA *data;
3272 int namelen;
3273 switch(optname)
3275 case IPX_PTYPE:
3276 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3277 #ifdef SOL_IPX
3278 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (socklen_t *)optlen) == -1)
3280 ret = SOCKET_ERROR;
3282 #else
3284 struct ipx val;
3285 socklen_t len=sizeof(struct ipx);
3286 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
3287 ret = SOCKET_ERROR;
3288 else
3289 *optval = (int)val.ipx_pt;
3291 #endif
3292 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
3293 release_sock_fd( s, fd );
3294 return ret;
3296 case IPX_ADDRESS:
3298 * On a Win2000 system with one network card there are usually
3299 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
3300 * Using this call you can then retrieve info about this all.
3301 * In case of Linux it is a bit different. Usually you have
3302 * only "one" device active and further it is not possible to
3303 * query things like the linkspeed.
3305 FIXME("IPX_ADDRESS\n");
3306 namelen = sizeof(struct WS_sockaddr_ipx);
3307 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
3308 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
3310 data = (IPX_ADDRESS_DATA*)optval;
3311 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
3312 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
3313 data->adapternum = 0;
3314 data->wan = FALSE; /* We are not on a wan for now .. */
3315 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
3316 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
3317 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
3318 * note 1MB = 1000kB in this case */
3319 return 0;
3321 case IPX_MAX_ADAPTER_NUM:
3322 FIXME("IPX_MAX_ADAPTER_NUM\n");
3323 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
3324 return 0;
3326 default:
3327 FIXME("IPX optname:%x\n", optname);
3328 return SOCKET_ERROR;
3329 }/* end switch(optname) */
3330 } /* end case WS_NSPROTO_IPX */
3331 #endif
3333 #ifdef HAS_IRDA
3334 case WS_SOL_IRLMP:
3335 switch(optname)
3337 case WS_IRLMP_ENUMDEVICES:
3339 static const int MAX_IRDA_DEVICES = 10;
3340 char buf[sizeof(struct irda_device_list) +
3341 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
3342 int res;
3343 socklen_t len = sizeof(buf);
3345 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3346 return SOCKET_ERROR;
3347 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
3348 release_sock_fd( s, fd );
3349 if (res < 0)
3351 SetLastError(wsaErrno());
3352 return SOCKET_ERROR;
3354 else
3356 struct irda_device_list *src = (struct irda_device_list *)buf;
3357 DEVICELIST *dst = (DEVICELIST *)optval;
3358 INT needed = sizeof(DEVICELIST);
3359 unsigned int i;
3361 if (src->len > 0)
3362 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
3363 if (*optlen < needed)
3365 SetLastError(WSAEFAULT);
3366 return SOCKET_ERROR;
3368 *optlen = needed;
3369 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
3370 dst->numDevice = src->len;
3371 for (i = 0; i < src->len; i++)
3373 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
3374 src->dev[i].saddr, src->dev[i].daddr,
3375 src->dev[i].info, src->dev[i].hints[0],
3376 src->dev[i].hints[1]);
3377 memcpy( dst->Device[i].irdaDeviceID,
3378 &src->dev[i].daddr,
3379 sizeof(dst->Device[i].irdaDeviceID) ) ;
3380 memcpy( dst->Device[i].irdaDeviceName,
3381 src->dev[i].info,
3382 sizeof(dst->Device[i].irdaDeviceName) ) ;
3383 memcpy( &dst->Device[i].irdaDeviceHints1,
3384 &src->dev[i].hints[0],
3385 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
3386 memcpy( &dst->Device[i].irdaDeviceHints2,
3387 &src->dev[i].hints[1],
3388 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
3389 dst->Device[i].irdaCharSet = src->dev[i].charset;
3391 return 0;
3394 default:
3395 FIXME("IrDA optname:0x%x\n", optname);
3396 return SOCKET_ERROR;
3398 break; /* case WS_SOL_IRLMP */
3399 #endif
3401 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3402 case WS_IPPROTO_TCP:
3403 switch(optname)
3405 case WS_TCP_NODELAY:
3406 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3407 return SOCKET_ERROR;
3408 convert_sockopt(&level, &optname);
3409 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3411 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3412 ret = SOCKET_ERROR;
3414 release_sock_fd( s, fd );
3415 return ret;
3417 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
3418 return SOCKET_ERROR;
3420 case WS_IPPROTO_IP:
3421 switch(optname)
3423 case WS_IP_ADD_MEMBERSHIP:
3424 case WS_IP_DROP_MEMBERSHIP:
3425 #ifdef IP_HDRINCL
3426 case WS_IP_HDRINCL:
3427 #endif
3428 case WS_IP_MULTICAST_IF:
3429 case WS_IP_MULTICAST_LOOP:
3430 case WS_IP_MULTICAST_TTL:
3431 case WS_IP_OPTIONS:
3432 #ifdef IP_PKTINFO
3433 case WS_IP_PKTINFO:
3434 #endif
3435 case WS_IP_TOS:
3436 case WS_IP_TTL:
3437 #ifdef IP_UNICAST_IF
3438 case WS_IP_UNICAST_IF:
3439 #endif
3440 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3441 return SOCKET_ERROR;
3442 convert_sockopt(&level, &optname);
3443 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3445 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3446 ret = SOCKET_ERROR;
3448 release_sock_fd( s, fd );
3449 return ret;
3450 case WS_IP_DONTFRAGMENT:
3451 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
3452 *(BOOL*)optval = FALSE;
3453 return 0;
3455 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
3456 return SOCKET_ERROR;
3458 case WS_IPPROTO_IPV6:
3459 switch(optname)
3461 #ifdef IPV6_ADD_MEMBERSHIP
3462 case WS_IPV6_ADD_MEMBERSHIP:
3463 #endif
3464 #ifdef IPV6_DROP_MEMBERSHIP
3465 case WS_IPV6_DROP_MEMBERSHIP:
3466 #endif
3467 case WS_IPV6_MULTICAST_IF:
3468 case WS_IPV6_MULTICAST_HOPS:
3469 case WS_IPV6_MULTICAST_LOOP:
3470 case WS_IPV6_UNICAST_HOPS:
3471 case WS_IPV6_V6ONLY:
3472 #ifdef IPV6_UNICAST_IF
3473 case WS_IPV6_UNICAST_IF:
3474 #endif
3475 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3476 return SOCKET_ERROR;
3477 convert_sockopt(&level, &optname);
3478 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3480 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3481 ret = SOCKET_ERROR;
3483 release_sock_fd( s, fd );
3484 return ret;
3485 case WS_IPV6_DONTFRAG:
3486 FIXME("WS_IPV6_DONTFRAG is always false!\n");
3487 *(BOOL*)optval = FALSE;
3488 return 0;
3490 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
3491 return SOCKET_ERROR;
3493 default:
3494 WARN("Unknown level: 0x%08x\n", level);
3495 SetLastError(WSAEINVAL);
3496 return SOCKET_ERROR;
3497 } /* end switch(level) */
3500 /***********************************************************************
3501 * htonl (WS2_32.8)
3503 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
3505 return htonl(hostlong);
3509 /***********************************************************************
3510 * htons (WS2_32.9)
3512 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
3514 return htons(hostshort);
3517 /***********************************************************************
3518 * WSAHtonl (WS2_32.46)
3519 * From MSDN description of error codes, this function should also
3520 * check if WinSock has been initialized and the socket is a valid
3521 * socket. But why? This function only translates a host byte order
3522 * u_long into a network byte order u_long...
3524 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
3526 if (lpnetlong)
3528 *lpnetlong = htonl(hostlong);
3529 return 0;
3531 WSASetLastError(WSAEFAULT);
3532 return SOCKET_ERROR;
3535 /***********************************************************************
3536 * WSAHtons (WS2_32.47)
3537 * From MSDN description of error codes, this function should also
3538 * check if WinSock has been initialized and the socket is a valid
3539 * socket. But why? This function only translates a host byte order
3540 * u_short into a network byte order u_short...
3542 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
3545 if (lpnetshort)
3547 *lpnetshort = htons(hostshort);
3548 return 0;
3550 WSASetLastError(WSAEFAULT);
3551 return SOCKET_ERROR;
3555 /***********************************************************************
3556 * inet_addr (WS2_32.11)
3558 WS_u_long WINAPI WS_inet_addr(const char *cp)
3560 if (!cp) return INADDR_NONE;
3561 return inet_addr(cp);
3565 /***********************************************************************
3566 * ntohl (WS2_32.14)
3568 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
3570 return ntohl(netlong);
3574 /***********************************************************************
3575 * ntohs (WS2_32.15)
3577 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
3579 return ntohs(netshort);
3583 /***********************************************************************
3584 * inet_ntoa (WS2_32.12)
3586 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
3588 char* s = inet_ntoa(*((struct in_addr*)&in));
3589 if( s )
3591 struct per_thread_data *data = get_per_thread_data();
3592 strcpy(data->ntoa_buffer, s);
3593 return data->ntoa_buffer;
3595 SetLastError(wsaErrno());
3596 return NULL;
3599 static const char *debugstr_wsaioctl(DWORD ioctl)
3601 const char *buf_type, *family;
3603 switch(ioctl & 0x18000000)
3605 case WS_IOC_WS2:
3606 family = "IOC_WS2";
3607 break;
3608 case WS_IOC_PROTOCOL:
3609 family = "IOC_PROTOCOL";
3610 break;
3611 case WS_IOC_VENDOR:
3612 family = "IOC_VENDOR";
3613 break;
3614 default: /* WS_IOC_UNIX */
3616 BYTE size = (ioctl >> 16) & WS_IOCPARM_MASK;
3617 char x = (ioctl & 0xff00) >> 8;
3618 BYTE y = ioctl & 0xff;
3619 char args[14];
3621 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3623 case WS_IOC_VOID:
3624 buf_type = "_IO";
3625 sprintf(args, "%d, %d", x, y);
3626 break;
3627 case WS_IOC_IN:
3628 buf_type = "_IOW";
3629 sprintf(args, "'%c', %d, %d", x, y, size);
3630 break;
3631 case WS_IOC_OUT:
3632 buf_type = "_IOR";
3633 sprintf(args, "'%c', %d, %d", x, y, size);
3634 break;
3635 default:
3636 buf_type = "?";
3637 sprintf(args, "'%c', %d, %d", x, y, size);
3638 break;
3640 return wine_dbg_sprintf("%s(%s)", buf_type, args);
3644 /* We are different from WS_IOC_UNIX. */
3645 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3647 case WS_IOC_VOID:
3648 buf_type = "_WSAIO";
3649 break;
3650 case WS_IOC_INOUT:
3651 buf_type = "_WSAIORW";
3652 break;
3653 case WS_IOC_IN:
3654 buf_type = "_WSAIOW";
3655 break;
3656 case WS_IOC_OUT:
3657 buf_type = "_WSAIOR";
3658 break;
3659 default:
3660 buf_type = "?";
3661 break;
3664 return wine_dbg_sprintf("%s(%s, %d)", buf_type, family,
3665 (USHORT)(ioctl & 0xffff));
3668 /**********************************************************************
3669 * WSAIoctl (WS2_32.50)
3672 INT WINAPI WSAIoctl(SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size, LPVOID out_buff,
3673 DWORD out_size, LPDWORD ret_size, LPWSAOVERLAPPED overlapped,
3674 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
3676 int fd;
3677 DWORD status = 0, total = 0;
3679 TRACE("%ld, 0x%08x, %p, %d, %p, %d, %p, %p, %p\n",
3680 s, code, in_buff, in_size, out_buff, out_size, ret_size, overlapped, completion);
3682 switch (code)
3684 case WS_FIONBIO:
3685 if (in_size != sizeof(WS_u_long) || IS_INTRESOURCE(in_buff))
3687 WSASetLastError(WSAEFAULT);
3688 return SOCKET_ERROR;
3690 if (_get_sock_mask(s))
3692 /* AsyncSelect()'ed sockets are always nonblocking */
3693 if (!*(WS_u_long *)in_buff) status = WSAEINVAL;
3694 break;
3696 if (*(WS_u_long *)in_buff)
3697 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
3698 else
3699 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
3700 break;
3702 case WS_FIONREAD:
3704 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
3706 WSASetLastError(WSAEFAULT);
3707 return SOCKET_ERROR;
3709 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3710 if (ioctl(fd, FIONREAD, out_buff ) == -1)
3711 status = (errno == EBADF) ? WSAENOTSOCK : wsaErrno();
3712 release_sock_fd( s, fd );
3713 break;
3716 case WS_SIOCATMARK:
3718 unsigned int oob = 0, atmark = 0;
3719 socklen_t oobsize = sizeof(int);
3720 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
3722 WSASetLastError(WSAEFAULT);
3723 return SOCKET_ERROR;
3725 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3726 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
3727 if ((getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &oob, &oobsize ) == -1)
3728 || (!oob && ioctl(fd, SIOCATMARK, &atmark ) == -1))
3729 status = (errno == EBADF) ? WSAENOTSOCK : wsaErrno();
3730 else
3732 /* The SIOCATMARK value read from ioctl() is reversed
3733 * because BSD returns TRUE if it's in the OOB mark
3734 * while Windows returns TRUE if there are NO OOB bytes.
3736 (*(WS_u_long *) out_buff) = oob | !atmark;
3739 release_sock_fd( s, fd );
3740 break;
3743 case WS_FIOASYNC:
3744 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
3745 SetLastError(WSAEINVAL);
3746 return SOCKET_ERROR;
3748 case WS_SIO_GET_INTERFACE_LIST:
3750 INTERFACE_INFO* intArray = out_buff;
3751 DWORD size, numInt = 0, apiReturn;
3753 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
3755 if (!out_buff || !ret_size)
3757 WSASetLastError(WSAEFAULT);
3758 return SOCKET_ERROR;
3761 fd = get_sock_fd( s, 0, NULL );
3762 if (fd == -1) return SOCKET_ERROR;
3764 apiReturn = GetAdaptersInfo(NULL, &size);
3765 if (apiReturn == ERROR_BUFFER_OVERFLOW)
3767 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
3769 if (table)
3771 if (GetAdaptersInfo(table, &size) == NO_ERROR)
3773 PIP_ADAPTER_INFO ptr;
3775 for (ptr = table, numInt = 0; ptr; ptr = ptr->Next)
3777 unsigned int addr, mask, bcast;
3778 struct ifreq ifInfo;
3780 /* Skip interfaces without an IPv4 address. */
3781 if (ptr->IpAddressList.IpAddress.String[0] == '\0')
3782 continue;
3784 if ((numInt + 1)*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > out_size)
3786 WARN("Buffer too small = %u, out_size = %u\n", numInt + 1, out_size);
3787 status = WSAEFAULT;
3788 break;
3791 /* Socket Status Flags */
3792 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
3793 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
3795 ERR("Error obtaining status flags for socket!\n");
3796 status = WSAEINVAL;
3797 break;
3799 else
3801 /* set flags; the values of IFF_* are not the same
3802 under Linux and Windows, therefore must generate
3803 new flags */
3804 intArray->iiFlags = 0;
3805 if (ifInfo.ifr_flags & IFF_BROADCAST)
3806 intArray->iiFlags |= WS_IFF_BROADCAST;
3807 #ifdef IFF_POINTOPOINT
3808 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
3809 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
3810 #endif
3811 if (ifInfo.ifr_flags & IFF_LOOPBACK)
3812 intArray->iiFlags |= WS_IFF_LOOPBACK;
3813 if (ifInfo.ifr_flags & IFF_UP)
3814 intArray->iiFlags |= WS_IFF_UP;
3815 if (ifInfo.ifr_flags & IFF_MULTICAST)
3816 intArray->iiFlags |= WS_IFF_MULTICAST;
3819 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
3820 mask = inet_addr(ptr->IpAddressList.IpMask.String);
3821 bcast = addr | ~mask;
3822 intArray->iiAddress.AddressIn.sin_family = AF_INET;
3823 intArray->iiAddress.AddressIn.sin_port = 0;
3824 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
3825 addr;
3826 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
3827 intArray->iiNetmask.AddressIn.sin_port = 0;
3828 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
3829 mask;
3830 intArray->iiBroadcastAddress.AddressIn.sin_family =
3831 AF_INET;
3832 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
3833 intArray->iiBroadcastAddress.AddressIn.sin_addr.
3834 WS_s_addr = bcast;
3835 intArray++;
3836 numInt++;
3839 else
3841 ERR("Unable to get interface table!\n");
3842 status = WSAEINVAL;
3844 HeapFree(GetProcessHeap(),0,table);
3846 else status = WSAEINVAL;
3848 else if (apiReturn != ERROR_NO_DATA)
3850 ERR("Unable to get interface table!\n");
3851 status = WSAEINVAL;
3853 /* Calculate the size of the array being returned */
3854 total = sizeof(INTERFACE_INFO) * numInt;
3855 release_sock_fd( s, fd );
3856 break;
3859 case WS_SIO_ADDRESS_LIST_CHANGE:
3860 FIXME("-> SIO_ADDRESS_LIST_CHANGE request: stub\n");
3861 /* FIXME: error and return code depend on whether socket was created
3862 * with WSA_FLAG_OVERLAPPED, but there is no easy way to get this */
3863 break;
3865 case WS_SIO_ADDRESS_LIST_QUERY:
3867 DWORD size;
3869 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
3871 if (!ret_size)
3873 WSASetLastError(WSAEFAULT);
3874 return SOCKET_ERROR;
3877 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
3879 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
3880 DWORD num;
3882 if (!table || GetAdaptersInfo(table, &size))
3884 HeapFree(GetProcessHeap(), 0, table);
3885 status = WSAEINVAL;
3886 break;
3889 for (p = table, num = 0; p; p = p->Next)
3890 if (p->IpAddressList.IpAddress.String[0]) num++;
3892 total = sizeof(SOCKET_ADDRESS_LIST) + sizeof(SOCKET_ADDRESS) * (num - 1);
3893 total += sizeof(SOCKADDR) * num;
3895 if (total > out_size)
3897 HeapFree(GetProcessHeap(), 0, table);
3898 status = WSAEFAULT;
3899 break;
3902 if (out_buff)
3904 unsigned int i;
3905 SOCKET_ADDRESS *sa;
3906 SOCKET_ADDRESS_LIST *sa_list = out_buff;
3907 SOCKADDR_IN *sockaddr;
3909 sa = sa_list->Address;
3910 sockaddr = (SOCKADDR_IN *)((char *)sa + num * sizeof(SOCKET_ADDRESS));
3911 sa_list->iAddressCount = num;
3913 for (p = table, i = 0; p; p = p->Next)
3915 if (!p->IpAddressList.IpAddress.String[0]) continue;
3917 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
3918 sa[i].iSockaddrLength = sizeof(SOCKADDR);
3920 sockaddr[i].sin_family = AF_INET;
3921 sockaddr[i].sin_port = 0;
3922 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
3923 i++;
3927 HeapFree(GetProcessHeap(), 0, table);
3929 else
3931 WARN("unable to get IP address list\n");
3932 status = WSAEINVAL;
3934 break;
3937 case WS_SIO_FLUSH:
3938 FIXME("SIO_FLUSH: stub.\n");
3939 break;
3941 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
3943 static const GUID connectex_guid = WSAID_CONNECTEX;
3944 static const GUID disconnectex_guid = WSAID_DISCONNECTEX;
3945 static const GUID acceptex_guid = WSAID_ACCEPTEX;
3946 static const GUID getaccepexsockaddrs_guid = WSAID_GETACCEPTEXSOCKADDRS;
3947 static const GUID transmitfile_guid = WSAID_TRANSMITFILE;
3948 static const GUID transmitpackets_guid = WSAID_TRANSMITPACKETS;
3949 static const GUID wsarecvmsg_guid = WSAID_WSARECVMSG;
3950 static const GUID wsasendmsg_guid = WSAID_WSASENDMSG;
3952 if ( IsEqualGUID(&connectex_guid, in_buff) )
3954 *(LPFN_CONNECTEX *)out_buff = WS2_ConnectEx;
3955 break;
3957 else if ( IsEqualGUID(&disconnectex_guid, in_buff) )
3959 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented DisconnectEx\n");
3961 else if ( IsEqualGUID(&acceptex_guid, in_buff) )
3963 *(LPFN_ACCEPTEX *)out_buff = WS2_AcceptEx;
3964 break;
3966 else if ( IsEqualGUID(&getaccepexsockaddrs_guid, in_buff) )
3968 *(LPFN_GETACCEPTEXSOCKADDRS *)out_buff = WS2_GetAcceptExSockaddrs;
3969 break;
3971 else if ( IsEqualGUID(&transmitfile_guid, in_buff) )
3973 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitFile\n");
3975 else if ( IsEqualGUID(&transmitpackets_guid, in_buff) )
3977 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitPackets\n");
3979 else if ( IsEqualGUID(&wsarecvmsg_guid, in_buff) )
3981 *(LPFN_WSARECVMSG *)out_buff = WS2_WSARecvMsg;
3982 break;
3984 else if ( IsEqualGUID(&wsasendmsg_guid, in_buff) )
3986 *(LPFN_WSASENDMSG *)out_buff = WSASendMsg;
3987 break;
3989 else
3990 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff));
3992 status = WSAEOPNOTSUPP;
3993 break;
3995 case WS_SIO_KEEPALIVE_VALS:
3997 struct tcp_keepalive *k;
3998 int keepalive, keepidle, keepintvl;
4000 if (!in_buff || in_size < sizeof(struct tcp_keepalive))
4002 WSASetLastError(WSAEFAULT);
4003 return SOCKET_ERROR;
4006 k = in_buff;
4007 keepalive = k->onoff ? 1 : 0;
4008 keepidle = max( 1, (k->keepalivetime + 500) / 1000 );
4009 keepintvl = max( 1, (k->keepaliveinterval + 500) / 1000 );
4011 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
4013 fd = get_sock_fd(s, 0, NULL);
4014 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
4015 status = WSAEINVAL;
4016 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
4017 /* these values need to be set only if SO_KEEPALIVE is enabled */
4018 else if(keepalive)
4020 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
4021 status = WSAEINVAL;
4022 else if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
4023 status = WSAEINVAL;
4025 #else
4026 else
4027 FIXME("ignoring keepalive interval and timeout\n");
4028 #endif
4029 release_sock_fd(s, fd);
4030 break;
4032 case WS_SIO_ROUTING_INTERFACE_QUERY:
4034 struct WS_sockaddr *daddr = (struct WS_sockaddr *)in_buff;
4035 struct WS_sockaddr_in *daddr_in = (struct WS_sockaddr_in *)daddr;
4036 struct WS_sockaddr_in *saddr_in = out_buff;
4037 MIB_IPFORWARDROW row;
4038 PMIB_IPADDRTABLE ipAddrTable = NULL;
4039 DWORD size, i, found_index;
4041 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
4043 if (!in_buff || in_size < sizeof(struct WS_sockaddr) ||
4044 !out_buff || out_size < sizeof(struct WS_sockaddr_in) || !ret_size)
4046 WSASetLastError(WSAEFAULT);
4047 return SOCKET_ERROR;
4049 if (daddr->sa_family != AF_INET)
4051 FIXME("unsupported address family %d\n", daddr->sa_family);
4052 status = WSAEAFNOSUPPORT;
4053 break;
4055 if (GetBestRoute(daddr_in->sin_addr.S_un.S_addr, 0, &row) != NOERROR ||
4056 GetIpAddrTable(NULL, &size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
4058 status = WSAEFAULT;
4059 break;
4061 ipAddrTable = HeapAlloc(GetProcessHeap(), 0, size);
4062 if (GetIpAddrTable(ipAddrTable, &size, FALSE))
4064 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4065 status = WSAEFAULT;
4066 break;
4068 for (i = 0, found_index = ipAddrTable->dwNumEntries;
4069 i < ipAddrTable->dwNumEntries; i++)
4071 if (ipAddrTable->table[i].dwIndex == row.dwForwardIfIndex)
4072 found_index = i;
4074 if (found_index == ipAddrTable->dwNumEntries)
4076 ERR("no matching IP address for interface %d\n",
4077 row.dwForwardIfIndex);
4078 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4079 status = WSAEFAULT;
4080 break;
4082 saddr_in->sin_family = AF_INET;
4083 saddr_in->sin_addr.S_un.S_addr = ipAddrTable->table[found_index].dwAddr;
4084 saddr_in->sin_port = 0;
4085 total = sizeof(struct WS_sockaddr_in);
4086 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4087 break;
4089 case WS_SIO_SET_COMPATIBILITY_MODE:
4090 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
4091 status = WSAEOPNOTSUPP;
4092 break;
4093 case WS_SIO_UDP_CONNRESET:
4094 FIXME("WS_SIO_UDP_CONNRESET stub\n");
4095 break;
4096 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
4097 WSASetLastError(WSAEOPNOTSUPP);
4098 return SOCKET_ERROR;
4099 default:
4100 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code));
4101 status = WSAEOPNOTSUPP;
4102 break;
4105 if (completion)
4107 FIXME( "completion routine %p not supported\n", completion );
4109 else if (overlapped)
4111 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
4112 overlapped->Internal = status;
4113 overlapped->InternalHigh = total;
4114 if (overlapped->hEvent) NtSetEvent( overlapped->hEvent, NULL );
4115 if (cvalue) WS_AddCompletion( HANDLE2SOCKET(s), cvalue, status, total );
4118 if (!status)
4120 if (ret_size) *ret_size = total;
4121 return 0;
4123 SetLastError( status );
4124 return SOCKET_ERROR;
4128 /***********************************************************************
4129 * ioctlsocket (WS2_32.10)
4131 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
4133 DWORD ret_size;
4134 return WSAIoctl( s, cmd, argp, sizeof(WS_u_long), argp, sizeof(WS_u_long), &ret_size, NULL, NULL );
4137 /***********************************************************************
4138 * listen (WS2_32.13)
4140 int WINAPI WS_listen(SOCKET s, int backlog)
4142 int fd = get_sock_fd( s, FILE_READ_DATA, NULL ), ret = SOCKET_ERROR;
4144 TRACE("socket %04lx, backlog %d\n", s, backlog);
4145 if (fd != -1)
4147 union generic_unix_sockaddr uaddr;
4148 socklen_t uaddrlen = sizeof(uaddr);
4150 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
4152 SetLastError(wsaErrno());
4154 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
4156 SetLastError(WSAEINVAL);
4158 else if (listen(fd, backlog) == 0)
4160 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
4161 FD_WINE_LISTENING,
4162 FD_CONNECT|FD_WINE_CONNECTED);
4163 ret = 0;
4165 else
4166 SetLastError(wsaErrno());
4167 release_sock_fd( s, fd );
4169 else
4170 SetLastError(WSAENOTSOCK);
4171 return ret;
4174 /***********************************************************************
4175 * recv (WS2_32.16)
4177 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
4179 DWORD n, dwFlags = flags;
4180 WSABUF wsabuf;
4182 wsabuf.len = len;
4183 wsabuf.buf = buf;
4185 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
4186 return SOCKET_ERROR;
4187 else
4188 return n;
4191 /***********************************************************************
4192 * recvfrom (WS2_32.17)
4194 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
4195 struct WS_sockaddr *from, int *fromlen)
4197 DWORD n, dwFlags = flags;
4198 WSABUF wsabuf;
4200 wsabuf.len = len;
4201 wsabuf.buf = buf;
4203 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL, NULL) == SOCKET_ERROR )
4204 return SOCKET_ERROR;
4205 else
4206 return n;
4209 /* allocate a poll array for the corresponding fd sets */
4210 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
4211 const WS_fd_set *exceptfds, int *count_ptr )
4213 unsigned int i, j = 0, count = 0;
4214 struct pollfd *fds;
4216 if (readfds) count += readfds->fd_count;
4217 if (writefds) count += writefds->fd_count;
4218 if (exceptfds) count += exceptfds->fd_count;
4219 *count_ptr = count;
4220 if (!count)
4222 SetLastError(WSAEINVAL);
4223 return NULL;
4225 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0]))))
4227 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
4228 return NULL;
4230 if (readfds)
4231 for (i = 0; i < readfds->fd_count; i++, j++)
4233 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
4234 if (fds[j].fd == -1) goto failed;
4235 fds[j].events = POLLIN;
4236 fds[j].revents = 0;
4238 if (writefds)
4239 for (i = 0; i < writefds->fd_count; i++, j++)
4241 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
4242 if (fds[j].fd == -1) goto failed;
4243 fds[j].events = POLLOUT;
4244 fds[j].revents = 0;
4246 if (exceptfds)
4247 for (i = 0; i < exceptfds->fd_count; i++, j++)
4249 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
4250 if (fds[j].fd == -1) goto failed;
4251 fds[j].events = POLLHUP;
4252 fds[j].revents = 0;
4254 return fds;
4256 failed:
4257 count = j;
4258 j = 0;
4259 if (readfds)
4260 for (i = 0; i < readfds->fd_count && j < count; i++, j++)
4261 release_sock_fd( readfds->fd_array[i], fds[j].fd );
4262 if (writefds)
4263 for (i = 0; i < writefds->fd_count && j < count; i++, j++)
4264 release_sock_fd( writefds->fd_array[i], fds[j].fd );
4265 if (exceptfds)
4266 for (i = 0; i < exceptfds->fd_count && j < count; i++, j++)
4267 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
4268 HeapFree( GetProcessHeap(), 0, fds );
4269 return NULL;
4272 /* release the file descriptor obtained in fd_sets_to_poll */
4273 /* must be called with the original fd_set arrays, before calling get_poll_results */
4274 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
4275 const WS_fd_set *exceptfds, struct pollfd *fds )
4277 unsigned int i, j = 0;
4279 if (readfds)
4281 for (i = 0; i < readfds->fd_count; i++, j++)
4282 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
4284 if (writefds)
4286 for (i = 0; i < writefds->fd_count; i++, j++)
4287 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
4289 if (exceptfds)
4291 for (i = 0; i < exceptfds->fd_count; i++, j++)
4292 if (fds[j].fd != -1)
4294 /* make sure we have a real error before releasing the fd */
4295 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
4296 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
4301 /* map the poll results back into the Windows fd sets */
4302 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
4303 const struct pollfd *fds )
4305 unsigned int i, j = 0, k, total = 0;
4307 if (readfds)
4309 for (i = k = 0; i < readfds->fd_count; i++, j++)
4310 if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
4311 readfds->fd_count = k;
4312 total += k;
4314 if (writefds)
4316 for (i = k = 0; i < writefds->fd_count; i++, j++)
4317 if ((fds[j].revents & POLLOUT) && !(fds[j].revents & POLLHUP))
4318 writefds->fd_array[k++] = writefds->fd_array[i];
4319 writefds->fd_count = k;
4320 total += k;
4322 if (exceptfds)
4324 for (i = k = 0; i < exceptfds->fd_count; i++, j++)
4325 if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
4326 exceptfds->fd_count = k;
4327 total += k;
4329 return total;
4333 /***********************************************************************
4334 * select (WS2_32.18)
4336 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
4337 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
4338 const struct WS_timeval* ws_timeout)
4340 struct pollfd *pollfds;
4341 struct timeval tv1, tv2;
4342 int torig = 0;
4343 int count, ret, timeout = -1;
4345 TRACE("read %p, write %p, excp %p timeout %p\n",
4346 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
4348 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )))
4349 return SOCKET_ERROR;
4351 if (ws_timeout)
4353 torig = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
4354 timeout = torig;
4355 gettimeofday( &tv1, 0 );
4358 while ((ret = poll( pollfds, count, timeout )) < 0)
4360 if (errno == EINTR)
4362 if (!ws_timeout) continue;
4363 gettimeofday( &tv2, 0 );
4365 tv2.tv_sec -= tv1.tv_sec;
4366 tv2.tv_usec -= tv1.tv_usec;
4367 if (tv2.tv_usec < 0)
4369 tv2.tv_usec += 1000000;
4370 tv2.tv_sec -= 1;
4373 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
4374 if (timeout <= 0) break;
4375 } else break;
4377 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
4379 if (ret == -1) SetLastError(wsaErrno());
4380 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
4381 HeapFree( GetProcessHeap(), 0, pollfds );
4382 return ret;
4385 /* helper to send completion messages for client-only i/o operation case */
4386 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
4387 ULONG Information )
4389 SERVER_START_REQ( add_fd_completion )
4391 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
4392 req->cvalue = CompletionValue;
4393 req->status = CompletionStatus;
4394 req->information = Information;
4395 wine_server_call( req );
4397 SERVER_END_REQ;
4401 /***********************************************************************
4402 * send (WS2_32.19)
4404 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
4406 DWORD n;
4407 WSABUF wsabuf;
4409 wsabuf.len = len;
4410 wsabuf.buf = (char*) buf;
4412 if ( WS2_sendto( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
4413 return SOCKET_ERROR;
4414 else
4415 return n;
4418 /***********************************************************************
4419 * WSASend (WS2_32.72)
4421 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4422 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4423 LPWSAOVERLAPPED lpOverlapped,
4424 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4426 return WS2_sendto( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
4427 NULL, 0, lpOverlapped, lpCompletionRoutine );
4430 /***********************************************************************
4431 * WSASendDisconnect (WS2_32.73)
4433 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
4435 return WS_shutdown( s, SD_SEND );
4439 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4440 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4441 const struct WS_sockaddr *to, int tolen,
4442 LPWSAOVERLAPPED lpOverlapped,
4443 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4445 unsigned int i, options;
4446 int n, fd, err;
4447 struct ws2_async *wsa = NULL;
4448 int totalLength = 0;
4449 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
4450 DWORD bytes_sent;
4451 BOOL is_blocking;
4453 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
4454 s, lpBuffers, dwBufferCount, dwFlags,
4455 to, tolen, lpOverlapped, lpCompletionRoutine);
4457 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
4458 TRACE( "fd=%d, options=%x\n", fd, options );
4460 if ( fd == -1 ) return SOCKET_ERROR;
4462 if (!lpOverlapped && !lpNumberOfBytesSent)
4464 err = WSAEFAULT;
4465 goto error;
4467 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
4469 err = WSAEFAULT;
4470 goto error;
4473 wsa->hSocket = SOCKET2HANDLE(s);
4474 wsa->addr = (struct WS_sockaddr *)to;
4475 wsa->addrlen.val = tolen;
4476 wsa->flags = dwFlags;
4477 wsa->lpFlags = &wsa->flags;
4478 wsa->control = NULL;
4479 wsa->n_iovecs = dwBufferCount;
4480 wsa->first_iovec = 0;
4481 for ( i = 0; i < dwBufferCount; i++ )
4483 wsa->iovec[i].iov_base = lpBuffers[i].buf;
4484 wsa->iovec[i].iov_len = lpBuffers[i].len;
4485 totalLength += lpBuffers[i].len;
4488 for (;;)
4490 n = WS2_send( fd, wsa );
4491 if (n != -1 || errno != EINTR) break;
4493 if (n == -1 && errno != EAGAIN)
4495 err = wsaErrno();
4496 goto error;
4499 if ((lpOverlapped || lpCompletionRoutine) &&
4500 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
4502 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
4504 wsa->user_overlapped = lpOverlapped;
4505 wsa->completion_func = lpCompletionRoutine;
4506 release_sock_fd( s, fd );
4508 if (n == -1 || n < totalLength)
4510 iosb->u.Status = STATUS_PENDING;
4511 iosb->Information = n == -1 ? 0 : n;
4513 SERVER_START_REQ( register_async )
4515 req->type = ASYNC_TYPE_WRITE;
4516 req->async.handle = wine_server_obj_handle( wsa->hSocket );
4517 req->async.callback = wine_server_client_ptr( WS2_async_send );
4518 req->async.iosb = wine_server_client_ptr( iosb );
4519 req->async.arg = wine_server_client_ptr( wsa );
4520 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
4521 req->async.cvalue = cvalue;
4522 err = wine_server_call( req );
4524 SERVER_END_REQ;
4526 /* Enable the event only after starting the async. The server will deliver it as soon as
4527 the async is done. */
4528 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
4530 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
4531 WSASetLastError( NtStatusToWSAError( err ));
4532 return SOCKET_ERROR;
4535 iosb->u.Status = STATUS_SUCCESS;
4536 iosb->Information = n;
4537 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = n;
4538 if (!wsa->completion_func)
4540 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
4541 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
4542 HeapFree( GetProcessHeap(), 0, wsa );
4544 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
4545 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
4546 WSASetLastError(0);
4547 return 0;
4550 if ((err = _is_blocking( s, &is_blocking )))
4552 err = NtStatusToWSAError( err );
4553 goto error;
4556 if ( is_blocking )
4558 /* On a blocking non-overlapped stream socket,
4559 * sending blocks until the entire buffer is sent. */
4560 DWORD timeout_start = GetTickCount();
4562 bytes_sent = n == -1 ? 0 : n;
4564 while (wsa->first_iovec < wsa->n_iovecs)
4566 struct pollfd pfd;
4567 int timeout = GET_SNDTIMEO(fd);
4569 if (timeout != -1)
4571 timeout -= GetTickCount() - timeout_start;
4572 if (timeout < 0) timeout = 0;
4575 pfd.fd = fd;
4576 pfd.events = POLLOUT;
4578 if (!timeout || !poll( &pfd, 1, timeout ))
4580 err = WSAETIMEDOUT;
4581 goto error; /* msdn says a timeout in send is fatal */
4584 n = WS2_send( fd, wsa );
4585 if (n == -1 && errno != EAGAIN && errno != EINTR)
4587 err = wsaErrno();
4588 goto error;
4591 if (n >= 0)
4592 bytes_sent += n;
4595 else /* non-blocking */
4597 if (n < totalLength)
4598 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
4599 if (n == -1)
4601 err = WSAEWOULDBLOCK;
4602 goto error;
4604 bytes_sent = n;
4607 TRACE(" -> %i bytes\n", bytes_sent);
4609 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = bytes_sent;
4610 HeapFree( GetProcessHeap(), 0, wsa );
4611 release_sock_fd( s, fd );
4612 WSASetLastError(0);
4613 return 0;
4615 error:
4616 HeapFree( GetProcessHeap(), 0, wsa );
4617 release_sock_fd( s, fd );
4618 WARN(" -> ERROR %d\n", err);
4619 WSASetLastError(err);
4620 return SOCKET_ERROR;
4623 /***********************************************************************
4624 * WSASendTo (WS2_32.74)
4626 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4627 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4628 const struct WS_sockaddr *to, int tolen,
4629 LPWSAOVERLAPPED lpOverlapped,
4630 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4632 return WS2_sendto( s, lpBuffers, dwBufferCount,
4633 lpNumberOfBytesSent, dwFlags,
4634 to, tolen,
4635 lpOverlapped, lpCompletionRoutine );
4638 /***********************************************************************
4639 * sendto (WS2_32.20)
4641 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
4642 const struct WS_sockaddr *to, int tolen)
4644 DWORD n;
4645 WSABUF wsabuf;
4647 wsabuf.len = len;
4648 wsabuf.buf = (char*) buf;
4650 if ( WS2_sendto(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
4651 return SOCKET_ERROR;
4652 else
4653 return n;
4656 /***********************************************************************
4657 * setsockopt (WS2_32.21)
4659 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
4660 const char *optval, int optlen)
4662 int fd;
4663 int woptval;
4664 struct linger linger;
4665 struct timeval tval;
4667 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
4668 s, level, optname, optval, optlen);
4670 /* some broken apps pass the value directly instead of a pointer to it */
4671 if(optlen && IS_INTRESOURCE(optval))
4673 SetLastError(WSAEFAULT);
4674 return SOCKET_ERROR;
4677 switch(level)
4679 case WS_SOL_SOCKET:
4680 switch(optname)
4682 /* Some options need some conversion before they can be sent to
4683 * setsockopt. The conversions are done here, then they will fall though
4684 * to the general case. Special options that are not passed to
4685 * setsockopt follow below that.*/
4687 case WS_SO_DONTLINGER:
4688 if (!optval)
4690 SetLastError(WSAEFAULT);
4691 return SOCKET_ERROR;
4693 linger.l_onoff = *(const int*)optval == 0;
4694 linger.l_linger = 0;
4695 level = SOL_SOCKET;
4696 optname = SO_LINGER;
4697 optval = (char*)&linger;
4698 optlen = sizeof(struct linger);
4699 break;
4701 case WS_SO_LINGER:
4702 if (!optval)
4704 SetLastError(WSAEFAULT);
4705 return SOCKET_ERROR;
4707 linger.l_onoff = ((LINGER*)optval)->l_onoff;
4708 linger.l_linger = ((LINGER*)optval)->l_linger;
4709 level = SOL_SOCKET;
4710 optname = SO_LINGER;
4711 optval = (char*)&linger;
4712 optlen = sizeof(struct linger);
4713 break;
4715 case WS_SO_RCVBUF:
4716 if (*(const int*)optval < 2048)
4718 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
4719 return 0;
4721 /* Fall through */
4723 /* The options listed here don't need any special handling. Thanks to
4724 * the conversion happening above, options from there will fall through
4725 * to this, too.*/
4726 case WS_SO_ACCEPTCONN:
4727 case WS_SO_BROADCAST:
4728 case WS_SO_ERROR:
4729 case WS_SO_KEEPALIVE:
4730 case WS_SO_OOBINLINE:
4731 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
4732 * however, using it the BSD way fixes bug 8513 and seems to be what
4733 * most programmers assume, anyway */
4734 case WS_SO_REUSEADDR:
4735 case WS_SO_SNDBUF:
4736 case WS_SO_TYPE:
4737 convert_sockopt(&level, &optname);
4738 break;
4740 /* SO_DEBUG is a privileged operation, ignore it. */
4741 case WS_SO_DEBUG:
4742 TRACE("Ignoring SO_DEBUG\n");
4743 return 0;
4745 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
4746 * socket. According to MSDN, this option is silently ignored.*/
4747 case WS_SO_DONTROUTE:
4748 TRACE("Ignoring SO_DONTROUTE\n");
4749 return 0;
4751 /* Stops two sockets from being bound to the same port. Always happens
4752 * on unix systems, so just drop it. */
4753 case WS_SO_EXCLUSIVEADDRUSE:
4754 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
4755 return 0;
4757 /* After a ConnectEx call succeeds, the socket can't be used with half of the
4758 * normal winsock functions on windows. We don't have that problem. */
4759 case WS_SO_UPDATE_CONNECT_CONTEXT:
4760 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
4761 return 0;
4763 /* After a AcceptEx call succeeds, the socket can't be used with half of the
4764 * normal winsock functions on windows. We don't have that problem. */
4765 case WS_SO_UPDATE_ACCEPT_CONTEXT:
4766 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
4767 return 0;
4769 /* SO_OPENTYPE does not require a valid socket handle. */
4770 case WS_SO_OPENTYPE:
4771 if (!optlen || optlen < sizeof(int) || !optval)
4773 SetLastError(WSAEFAULT);
4774 return SOCKET_ERROR;
4776 get_per_thread_data()->opentype = *(const int *)optval;
4777 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
4778 return 0;
4780 #ifdef SO_RCVTIMEO
4781 case WS_SO_RCVTIMEO:
4782 #endif
4783 #ifdef SO_SNDTIMEO
4784 case WS_SO_SNDTIMEO:
4785 #endif
4786 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
4787 if (optval && optlen == sizeof(UINT32)) {
4788 /* WinSock passes milliseconds instead of struct timeval */
4789 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
4790 tval.tv_sec = *(const UINT32*)optval / 1000;
4791 /* min of 500 milliseconds */
4792 if (tval.tv_sec == 0 && tval.tv_usec && tval.tv_usec < 500000)
4793 tval.tv_usec = 500000;
4794 optlen = sizeof(struct timeval);
4795 optval = (char*)&tval;
4796 } else if (optlen == sizeof(struct timeval)) {
4797 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
4798 } else {
4799 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
4800 return 0;
4802 convert_sockopt(&level, &optname);
4803 break;
4804 #endif
4806 default:
4807 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
4808 SetLastError(WSAENOPROTOOPT);
4809 return SOCKET_ERROR;
4811 break; /* case WS_SOL_SOCKET */
4813 #ifdef HAS_IPX
4814 case WS_NSPROTO_IPX:
4815 switch(optname)
4817 case IPX_PTYPE:
4818 return set_ipx_packettype(s, *(int*)optval);
4820 case IPX_FILTERPTYPE:
4821 /* Sets the receive filter packet type, at the moment we don't support it */
4822 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
4823 /* Returning 0 is better for now than returning a SOCKET_ERROR */
4824 return 0;
4826 default:
4827 FIXME("opt_name:%x\n", optname);
4828 return SOCKET_ERROR;
4830 break; /* case WS_NSPROTO_IPX */
4831 #endif
4833 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
4834 case WS_IPPROTO_TCP:
4835 switch(optname)
4837 case WS_TCP_NODELAY:
4838 convert_sockopt(&level, &optname);
4839 break;
4840 default:
4841 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
4842 return SOCKET_ERROR;
4844 break;
4846 case WS_IPPROTO_IP:
4847 switch(optname)
4849 case WS_IP_ADD_MEMBERSHIP:
4850 case WS_IP_DROP_MEMBERSHIP:
4851 #ifdef IP_HDRINCL
4852 case WS_IP_HDRINCL:
4853 #endif
4854 case WS_IP_MULTICAST_IF:
4855 case WS_IP_MULTICAST_LOOP:
4856 case WS_IP_MULTICAST_TTL:
4857 case WS_IP_OPTIONS:
4858 #ifdef IP_PKTINFO
4859 case WS_IP_PKTINFO:
4860 #endif
4861 case WS_IP_TOS:
4862 case WS_IP_TTL:
4863 #ifdef IP_UNICAST_IF
4864 case WS_IP_UNICAST_IF:
4865 #endif
4866 convert_sockopt(&level, &optname);
4867 break;
4868 case WS_IP_DONTFRAGMENT:
4869 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
4870 return 0;
4871 default:
4872 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
4873 return SOCKET_ERROR;
4875 break;
4877 case WS_IPPROTO_IPV6:
4878 switch(optname)
4880 #ifdef IPV6_ADD_MEMBERSHIP
4881 case WS_IPV6_ADD_MEMBERSHIP:
4882 #endif
4883 #ifdef IPV6_DROP_MEMBERSHIP
4884 case WS_IPV6_DROP_MEMBERSHIP:
4885 #endif
4886 case WS_IPV6_MULTICAST_IF:
4887 case WS_IPV6_MULTICAST_HOPS:
4888 case WS_IPV6_MULTICAST_LOOP:
4889 case WS_IPV6_UNICAST_HOPS:
4890 case WS_IPV6_V6ONLY:
4891 #ifdef IPV6_UNICAST_IF
4892 case WS_IPV6_UNICAST_IF:
4893 #endif
4894 convert_sockopt(&level, &optname);
4895 break;
4896 case WS_IPV6_DONTFRAG:
4897 FIXME("IPV6_DONTFRAG is silently ignored!\n");
4898 return 0;
4899 case WS_IPV6_PROTECTION_LEVEL:
4900 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
4901 return 0;
4902 default:
4903 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
4904 return SOCKET_ERROR;
4906 break;
4908 default:
4909 WARN("Unknown level: 0x%08x\n", level);
4910 SetLastError(WSAEINVAL);
4911 return SOCKET_ERROR;
4912 } /* end switch(level) */
4914 /* avoid endianness issues if argument is a 16-bit int */
4915 if (optval && optlen < sizeof(int))
4917 woptval= *((const INT16 *) optval);
4918 optval= (char*) &woptval;
4919 optlen=sizeof(int);
4921 fd = get_sock_fd( s, 0, NULL );
4922 if (fd == -1) return SOCKET_ERROR;
4924 if (setsockopt(fd, level, optname, optval, optlen) == 0)
4926 #ifdef __APPLE__
4927 if (level == SOL_SOCKET && optname == SO_REUSEADDR &&
4928 setsockopt(fd, level, SO_REUSEPORT, optval, optlen) != 0)
4930 SetLastError(wsaErrno());
4931 release_sock_fd( s, fd );
4932 return SOCKET_ERROR;
4934 #endif
4935 release_sock_fd( s, fd );
4936 return 0;
4938 TRACE("Setting socket error, %d\n", wsaErrno());
4939 SetLastError(wsaErrno());
4940 release_sock_fd( s, fd );
4942 return SOCKET_ERROR;
4945 /***********************************************************************
4946 * shutdown (WS2_32.22)
4948 int WINAPI WS_shutdown(SOCKET s, int how)
4950 int fd, err = WSAENOTSOCK;
4951 unsigned int options, clear_flags = 0;
4953 fd = get_sock_fd( s, 0, &options );
4954 TRACE("socket %04lx, how %i %x\n", s, how, options );
4956 if (fd == -1)
4957 return SOCKET_ERROR;
4959 switch( how )
4961 case 0: /* drop receives */
4962 clear_flags |= FD_READ;
4963 break;
4964 case 1: /* drop sends */
4965 clear_flags |= FD_WRITE;
4966 break;
4967 case 2: /* drop all */
4968 clear_flags |= FD_READ|FD_WRITE;
4969 /*fall through */
4970 default:
4971 clear_flags |= FD_WINE_LISTENING;
4974 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
4976 switch ( how )
4978 case SD_RECEIVE:
4979 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
4980 break;
4981 case SD_SEND:
4982 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
4983 break;
4984 case SD_BOTH:
4985 default:
4986 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
4987 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
4988 break;
4990 if (err) goto error;
4992 else /* non-overlapped mode */
4994 if ( shutdown( fd, how ) )
4996 err = wsaErrno();
4997 goto error;
5001 release_sock_fd( s, fd );
5002 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
5003 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
5004 return 0;
5006 error:
5007 release_sock_fd( s, fd );
5008 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
5009 WSASetLastError( err );
5010 return SOCKET_ERROR;
5013 /***********************************************************************
5014 * socket (WS2_32.23)
5016 SOCKET WINAPI WS_socket(int af, int type, int protocol)
5018 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
5020 return WSASocketA( af, type, protocol, NULL, 0,
5021 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
5025 /***********************************************************************
5026 * gethostbyaddr (WS2_32.51)
5028 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
5030 struct WS_hostent *retval = NULL;
5031 struct hostent* host;
5033 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5034 char *extrabuf;
5035 int ebufsize=1024;
5036 struct hostent hostentry;
5037 int locerr=ENOBUFS;
5038 host = NULL;
5039 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
5040 while(extrabuf) {
5041 int res = gethostbyaddr_r(addr, len, type,
5042 &hostentry, extrabuf, ebufsize, &host, &locerr);
5043 if( res != ERANGE) break;
5044 ebufsize *=2;
5045 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
5047 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
5048 #else
5049 EnterCriticalSection( &csWSgetXXXbyYYY );
5050 host = gethostbyaddr(addr, len, type);
5051 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
5052 #endif
5053 if( host != NULL ) retval = WS_dup_he(host);
5054 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5055 HeapFree(GetProcessHeap(),0,extrabuf);
5056 #else
5057 LeaveCriticalSection( &csWSgetXXXbyYYY );
5058 #endif
5059 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
5060 return retval;
5063 /***********************************************************************
5064 * WS_get_local_ips (INTERNAL)
5066 * Returns the list of local IP addresses by going through the network
5067 * adapters and using the local routing table to sort the addresses
5068 * from highest routing priority to lowest routing priority. This
5069 * functionality is inferred from the description for obtaining local
5070 * IP addresses given in the Knowledge Base Article Q160215.
5072 * Please note that the returned hostent is only freed when the thread
5073 * closes and is replaced if another hostent is requested.
5075 static struct WS_hostent* WS_get_local_ips( char *hostname )
5077 int last_metric, numroutes = 0, i, j;
5078 DWORD n;
5079 PIP_ADAPTER_INFO adapters = NULL, k;
5080 struct WS_hostent *hostlist = NULL;
5081 PMIB_IPFORWARDTABLE routes = NULL;
5082 struct route *route_addrs = NULL;
5083 DWORD adap_size, route_size;
5085 /* Obtain the size of the adapter list and routing table, also allocate memory */
5086 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
5087 return NULL;
5088 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
5089 return NULL;
5090 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
5091 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
5092 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
5093 if (adapters == NULL || routes == NULL || route_addrs == NULL)
5094 goto cleanup;
5095 /* Obtain the adapter list and the full routing table */
5096 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
5097 goto cleanup;
5098 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
5099 goto cleanup;
5100 /* Store the interface associated with each route */
5101 for (n = 0; n < routes->dwNumEntries; n++)
5103 IF_INDEX ifindex;
5104 DWORD ifmetric;
5105 BOOL exists = FALSE;
5107 if (routes->table[n].u1.ForwardType != MIB_IPROUTE_TYPE_DIRECT)
5108 continue;
5109 ifindex = routes->table[n].dwForwardIfIndex;
5110 ifmetric = routes->table[n].dwForwardMetric1;
5111 /* Only store the lowest valued metric for an interface */
5112 for (j = 0; j < numroutes; j++)
5114 if (route_addrs[j].interface == ifindex)
5116 if (route_addrs[j].metric > ifmetric)
5117 route_addrs[j].metric = ifmetric;
5118 exists = TRUE;
5121 if (exists)
5122 continue;
5123 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
5124 if (route_addrs == NULL)
5125 goto cleanup; /* Memory allocation error, fail gracefully */
5126 route_addrs[numroutes].interface = ifindex;
5127 route_addrs[numroutes].metric = ifmetric;
5128 /* If no IP is found in the next step (for whatever reason)
5129 * then fall back to the magic loopback address.
5131 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
5132 numroutes++;
5134 if (numroutes == 0)
5135 goto cleanup; /* No routes, fall back to the Magic IP */
5136 /* Find the IP address associated with each found interface */
5137 for (i = 0; i < numroutes; i++)
5139 for (k = adapters; k != NULL; k = k->Next)
5141 char *ip = k->IpAddressList.IpAddress.String;
5143 if (route_addrs[i].interface == k->Index)
5144 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
5147 /* Allocate a hostent and enough memory for all the IPs,
5148 * including the NULL at the end of the list.
5150 hostlist = WS_create_he(hostname, 1, 0, numroutes+1, sizeof(struct in_addr));
5151 if (hostlist == NULL)
5152 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
5153 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
5154 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
5155 hostlist->h_addrtype = AF_INET;
5156 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
5157 /* Reorder the entries when placing them in the host list, Windows expects
5158 * the IP list in order from highest priority to lowest (the critical thing
5159 * is that most applications expect the first IP to be the default route).
5161 last_metric = -1;
5162 for (i = 0; i < numroutes; i++)
5164 struct in_addr addr;
5165 int metric = 0xFFFF;
5167 memcpy(&addr, magic_loopback_addr, 4);
5168 for (j = 0; j < numroutes; j++)
5170 int this_metric = route_addrs[j].metric;
5172 if (this_metric > last_metric && this_metric < metric)
5174 addr = route_addrs[j].addr;
5175 metric = this_metric;
5178 last_metric = metric;
5179 (*(struct in_addr *) hostlist->h_addr_list[i]) = addr;
5182 /* Cleanup all allocated memory except the address list,
5183 * the address list is used by the calling app.
5185 cleanup:
5186 HeapFree(GetProcessHeap(), 0, route_addrs);
5187 HeapFree(GetProcessHeap(), 0, adapters);
5188 HeapFree(GetProcessHeap(), 0, routes);
5189 return hostlist;
5192 /***********************************************************************
5193 * gethostbyname (WS2_32.52)
5195 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
5197 struct WS_hostent *retval = NULL;
5198 struct hostent* host;
5199 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5200 char *extrabuf;
5201 int ebufsize=1024;
5202 struct hostent hostentry;
5203 int locerr = ENOBUFS;
5204 #endif
5205 char hostname[100];
5206 if(!num_startup) {
5207 SetLastError(WSANOTINITIALISED);
5208 return NULL;
5210 if( gethostname( hostname, 100) == -1) {
5211 SetLastError( WSAENOBUFS); /* appropriate ? */
5212 return retval;
5214 if( !name || !name[0]) {
5215 name = hostname;
5217 /* If the hostname of the local machine is requested then return the
5218 * complete list of local IP addresses */
5219 if(strcmp(name, hostname) == 0)
5220 retval = WS_get_local_ips(hostname);
5221 /* If any other hostname was requested (or the routing table lookup failed)
5222 * then return the IP found by the host OS */
5223 if(retval == NULL)
5225 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5226 host = NULL;
5227 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
5228 while(extrabuf) {
5229 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
5230 if( res != ERANGE) break;
5231 ebufsize *=2;
5232 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
5234 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
5235 #else
5236 EnterCriticalSection( &csWSgetXXXbyYYY );
5237 host = gethostbyname(name);
5238 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
5239 #endif
5240 if (host) retval = WS_dup_he(host);
5241 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5242 HeapFree(GetProcessHeap(),0,extrabuf);
5243 #else
5244 LeaveCriticalSection( &csWSgetXXXbyYYY );
5245 #endif
5247 if (retval && retval->h_addr_list[0][0] == 127 &&
5248 strcmp(name, "localhost") != 0)
5250 /* hostname != "localhost" but has loopback address. replace by our
5251 * special address.*/
5252 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
5254 TRACE( "%s ret %p\n", debugstr_a(name), retval );
5255 return retval;
5259 /***********************************************************************
5260 * getprotobyname (WS2_32.53)
5262 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
5264 struct WS_protoent* retval = NULL;
5265 #ifdef HAVE_GETPROTOBYNAME
5266 struct protoent* proto;
5267 EnterCriticalSection( &csWSgetXXXbyYYY );
5268 if( (proto = getprotobyname(name)) != NULL )
5270 retval = WS_dup_pe(proto);
5272 else {
5273 MESSAGE("protocol %s not found; You might want to add "
5274 "this to /etc/protocols\n", debugstr_a(name) );
5275 SetLastError(WSANO_DATA);
5277 LeaveCriticalSection( &csWSgetXXXbyYYY );
5278 #endif
5279 TRACE( "%s ret %p\n", debugstr_a(name), retval );
5280 return retval;
5284 /***********************************************************************
5285 * getprotobynumber (WS2_32.54)
5287 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
5289 struct WS_protoent* retval = NULL;
5290 #ifdef HAVE_GETPROTOBYNUMBER
5291 struct protoent* proto;
5292 EnterCriticalSection( &csWSgetXXXbyYYY );
5293 if( (proto = getprotobynumber(number)) != NULL )
5295 retval = WS_dup_pe(proto);
5297 else {
5298 MESSAGE("protocol number %d not found; You might want to add "
5299 "this to /etc/protocols\n", number );
5300 SetLastError(WSANO_DATA);
5302 LeaveCriticalSection( &csWSgetXXXbyYYY );
5303 #endif
5304 TRACE("%i ret %p\n", number, retval);
5305 return retval;
5309 /***********************************************************************
5310 * getservbyname (WS2_32.55)
5312 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
5314 struct WS_servent* retval = NULL;
5315 struct servent* serv;
5316 char *name_str;
5317 char *proto_str = NULL;
5319 if (!(name_str = strdup_lower(name))) return NULL;
5321 if (proto && *proto)
5323 if (!(proto_str = strdup_lower(proto)))
5325 HeapFree( GetProcessHeap(), 0, name_str );
5326 return NULL;
5330 EnterCriticalSection( &csWSgetXXXbyYYY );
5331 serv = getservbyname(name_str, proto_str);
5332 if( serv != NULL )
5334 retval = WS_dup_se(serv);
5336 else SetLastError(WSANO_DATA);
5337 LeaveCriticalSection( &csWSgetXXXbyYYY );
5338 HeapFree( GetProcessHeap(), 0, proto_str );
5339 HeapFree( GetProcessHeap(), 0, name_str );
5340 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
5341 return retval;
5344 /***********************************************************************
5345 * freeaddrinfo (WS2_32.@)
5347 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
5349 while (res) {
5350 struct WS_addrinfo *next;
5352 HeapFree(GetProcessHeap(),0,res->ai_canonname);
5353 HeapFree(GetProcessHeap(),0,res->ai_addr);
5354 next = res->ai_next;
5355 HeapFree(GetProcessHeap(),0,res);
5356 res = next;
5360 /* helper functions for getaddrinfo()/getnameinfo() */
5361 static int convert_aiflag_w2u(int winflags) {
5362 unsigned int i;
5363 int unixflags = 0;
5365 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
5366 if (ws_aiflag_map[i][0] & winflags) {
5367 unixflags |= ws_aiflag_map[i][1];
5368 winflags &= ~ws_aiflag_map[i][0];
5370 if (winflags)
5371 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
5372 return unixflags;
5375 static int convert_niflag_w2u(int winflags) {
5376 unsigned int i;
5377 int unixflags = 0;
5379 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
5380 if (ws_niflag_map[i][0] & winflags) {
5381 unixflags |= ws_niflag_map[i][1];
5382 winflags &= ~ws_niflag_map[i][0];
5384 if (winflags)
5385 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
5386 return unixflags;
5389 static int convert_aiflag_u2w(int unixflags) {
5390 unsigned int i;
5391 int winflags = 0;
5393 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
5394 if (ws_aiflag_map[i][1] & unixflags) {
5395 winflags |= ws_aiflag_map[i][0];
5396 unixflags &= ~ws_aiflag_map[i][1];
5398 if (unixflags) /* will warn usually */
5399 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
5400 return winflags;
5403 static int convert_eai_u2w(int unixret) {
5404 int i;
5406 if (!unixret) return 0;
5408 for (i=0;ws_eai_map[i][0];i++)
5409 if (ws_eai_map[i][1] == unixret)
5410 return ws_eai_map[i][0];
5412 if (unixret == EAI_SYSTEM)
5413 /* There are broken versions of glibc which return EAI_SYSTEM
5414 * and set errno to 0 instead of returning EAI_NONAME.
5416 return errno ? sock_get_error( errno ) : WS_EAI_NONAME;
5418 FIXME("Unhandled unix EAI_xxx ret %d\n", unixret);
5419 return unixret;
5422 static char *get_hostname(void)
5424 char *ret;
5425 DWORD size = 0;
5427 GetComputerNameExA( ComputerNamePhysicalDnsHostname, NULL, &size );
5428 if (GetLastError() != ERROR_MORE_DATA) return NULL;
5429 if (!(ret = HeapAlloc( GetProcessHeap(), 0, size ))) return NULL;
5430 if (!GetComputerNameExA( ComputerNamePhysicalDnsHostname, ret, &size ))
5432 HeapFree( GetProcessHeap(), 0, ret );
5433 return NULL;
5435 return ret;
5438 /***********************************************************************
5439 * getaddrinfo (WS2_32.@)
5441 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
5443 #ifdef HAVE_GETADDRINFO
5444 struct addrinfo *unixaires = NULL;
5445 int result;
5446 struct addrinfo unixhints, *punixhints = NULL;
5447 char *hostname = NULL;
5448 const char *node;
5450 *res = NULL;
5451 if (!nodename && !servname) return WSAHOST_NOT_FOUND;
5453 if (!nodename)
5454 node = NULL;
5455 else if (!nodename[0])
5457 node = hostname = get_hostname();
5458 if (!node) return WSA_NOT_ENOUGH_MEMORY;
5460 else
5461 node = nodename;
5463 if (hints) {
5464 punixhints = &unixhints;
5466 memset(&unixhints, 0, sizeof(unixhints));
5467 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
5468 if (hints->ai_family == 0) /* wildcard, specific to getaddrinfo() */
5469 punixhints->ai_family = 0;
5470 else
5471 punixhints->ai_family = convert_af_w2u(hints->ai_family);
5472 if (hints->ai_socktype == 0) /* wildcard, specific to getaddrinfo() */
5473 punixhints->ai_socktype = 0;
5474 else
5475 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
5476 if (hints->ai_protocol == 0) /* wildcard, specific to getaddrinfo() */
5477 punixhints->ai_protocol = 0;
5478 else
5479 punixhints->ai_protocol = convert_proto_w2u(hints->ai_protocol);
5482 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
5483 result = getaddrinfo(node, servname, punixhints, &unixaires);
5485 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
5486 HeapFree(GetProcessHeap(), 0, hostname);
5488 if (!result) {
5489 struct addrinfo *xuai = unixaires;
5490 struct WS_addrinfo **xai = res;
5492 *xai = NULL;
5493 while (xuai) {
5494 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
5495 SIZE_T len;
5497 if (!ai)
5498 goto outofmem;
5500 *xai = ai;xai = &ai->ai_next;
5501 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
5502 ai->ai_family = convert_af_u2w(xuai->ai_family);
5503 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
5504 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
5505 if (xuai->ai_canonname) {
5506 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
5507 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
5508 if (!ai->ai_canonname)
5509 goto outofmem;
5510 strcpy(ai->ai_canonname,xuai->ai_canonname);
5512 len = xuai->ai_addrlen;
5513 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
5514 if (!ai->ai_addr)
5515 goto outofmem;
5516 ai->ai_addrlen = len;
5517 do {
5518 int winlen = ai->ai_addrlen;
5520 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
5521 ai->ai_addrlen = winlen;
5522 break;
5524 len = 2*len;
5525 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
5526 if (!ai->ai_addr)
5527 goto outofmem;
5528 ai->ai_addrlen = len;
5529 } while (1);
5530 xuai = xuai->ai_next;
5532 freeaddrinfo(unixaires);
5534 if (TRACE_ON(winsock))
5536 struct WS_addrinfo *ai = *res;
5537 while (ai)
5539 TRACE("=> %p, flags %#x, family %d, type %d, protocol %d, len %ld, name %s, addr %s\n",
5540 ai, ai->ai_flags, ai->ai_family, ai->ai_socktype, ai->ai_protocol, ai->ai_addrlen,
5541 ai->ai_canonname, debugstr_sockaddr(ai->ai_addr));
5542 ai = ai->ai_next;
5545 } else
5546 result = convert_eai_u2w(result);
5548 return result;
5550 outofmem:
5551 if (*res) WS_freeaddrinfo(*res);
5552 if (unixaires) freeaddrinfo(unixaires);
5553 return WSA_NOT_ENOUGH_MEMORY;
5554 #else
5555 FIXME("getaddrinfo() failed, not found during buildtime.\n");
5556 return EAI_FAIL;
5557 #endif
5560 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
5562 struct WS_addrinfoW *ret;
5564 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
5565 ret->ai_flags = ai->ai_flags;
5566 ret->ai_family = ai->ai_family;
5567 ret->ai_socktype = ai->ai_socktype;
5568 ret->ai_protocol = ai->ai_protocol;
5569 ret->ai_addrlen = ai->ai_addrlen;
5570 ret->ai_canonname = NULL;
5571 ret->ai_addr = NULL;
5572 ret->ai_next = NULL;
5573 if (ai->ai_canonname)
5575 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
5576 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
5578 HeapFree(GetProcessHeap(), 0, ret);
5579 return NULL;
5581 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
5583 if (ai->ai_addr)
5585 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
5587 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
5588 HeapFree(GetProcessHeap(), 0, ret);
5589 return NULL;
5591 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
5593 return ret;
5596 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
5598 struct WS_addrinfoW *ret, *infoW;
5600 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
5601 while (info->ai_next)
5603 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
5605 FreeAddrInfoW(ret);
5606 return NULL;
5608 infoW = infoW->ai_next;
5609 info = info->ai_next;
5611 return ret;
5614 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
5616 struct WS_addrinfo *ret;
5618 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
5619 ret->ai_flags = ai->ai_flags;
5620 ret->ai_family = ai->ai_family;
5621 ret->ai_socktype = ai->ai_socktype;
5622 ret->ai_protocol = ai->ai_protocol;
5623 ret->ai_addrlen = ai->ai_addrlen;
5624 ret->ai_canonname = NULL;
5625 ret->ai_addr = NULL;
5626 ret->ai_next = NULL;
5627 if (ai->ai_canonname)
5629 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
5630 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
5632 HeapFree(GetProcessHeap(), 0, ret);
5633 return NULL;
5635 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
5637 if (ai->ai_addr)
5639 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
5641 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
5642 HeapFree(GetProcessHeap(), 0, ret);
5643 return NULL;
5645 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
5647 return ret;
5650 /***********************************************************************
5651 * GetAddrInfoW (WS2_32.@)
5653 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
5655 int ret, len;
5656 char *nodenameA = NULL, *servnameA = NULL;
5657 struct WS_addrinfo *resA, *hintsA = NULL;
5659 *res = NULL;
5660 if (nodename)
5662 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
5663 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
5664 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
5666 if (servname)
5668 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
5669 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
5671 HeapFree(GetProcessHeap(), 0, nodenameA);
5672 return EAI_MEMORY;
5674 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
5677 if (hints) hintsA = addrinfo_WtoA(hints);
5678 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
5679 WS_freeaddrinfo(hintsA);
5681 if (!ret)
5683 *res = addrinfo_list_AtoW(resA);
5684 WS_freeaddrinfo(resA);
5687 HeapFree(GetProcessHeap(), 0, nodenameA);
5688 HeapFree(GetProcessHeap(), 0, servnameA);
5689 return ret;
5692 /***********************************************************************
5693 * FreeAddrInfoW (WS2_32.@)
5695 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
5697 while (ai)
5699 ADDRINFOW *next;
5700 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
5701 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
5702 next = ai->ai_next;
5703 HeapFree(GetProcessHeap(), 0, ai);
5704 ai = next;
5708 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
5709 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
5711 #ifdef HAVE_GETNAMEINFO
5712 int ret;
5713 union generic_unix_sockaddr sa_u;
5714 unsigned int size;
5716 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
5717 serv, servlen, flags);
5719 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
5720 if (!size)
5722 WSASetLastError(WSAEFAULT);
5723 return WSA_NOT_ENOUGH_MEMORY;
5725 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
5726 return convert_eai_u2w(ret);
5727 #else
5728 FIXME("getnameinfo() failed, not found during buildtime.\n");
5729 return EAI_FAIL;
5730 #endif
5733 int WINAPI GetNameInfoW(const SOCKADDR *sa, WS_socklen_t salen, PWCHAR host,
5734 DWORD hostlen, PWCHAR serv, DWORD servlen, INT flags)
5736 int ret;
5737 char *hostA = NULL, *servA = NULL;
5739 if (host && (!(hostA = HeapAlloc(GetProcessHeap(), 0, hostlen)))) return EAI_MEMORY;
5740 if (serv && (!(servA = HeapAlloc(GetProcessHeap(), 0, servlen))))
5742 HeapFree(GetProcessHeap(), 0, hostA);
5743 return EAI_MEMORY;
5746 ret = WS_getnameinfo(sa, salen, hostA, hostlen, servA, servlen, flags);
5747 if (!ret)
5749 if (host) MultiByteToWideChar(CP_ACP, 0, hostA, -1, host, hostlen);
5750 if (serv) MultiByteToWideChar(CP_ACP, 0, servA, -1, serv, servlen);
5753 HeapFree(GetProcessHeap(), 0, hostA);
5754 HeapFree(GetProcessHeap(), 0, servA);
5755 return ret;
5758 /***********************************************************************
5759 * getservbyport (WS2_32.56)
5761 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
5763 struct WS_servent* retval = NULL;
5764 #ifdef HAVE_GETSERVBYPORT
5765 struct servent* serv;
5766 char *proto_str = NULL;
5768 if (proto && *proto)
5770 if (!(proto_str = strdup_lower(proto))) return NULL;
5772 EnterCriticalSection( &csWSgetXXXbyYYY );
5773 if( (serv = getservbyport(port, proto_str)) != NULL ) {
5774 retval = WS_dup_se(serv);
5776 else SetLastError(WSANO_DATA);
5777 LeaveCriticalSection( &csWSgetXXXbyYYY );
5778 HeapFree( GetProcessHeap(), 0, proto_str );
5779 #endif
5780 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
5781 return retval;
5785 /***********************************************************************
5786 * gethostname (WS2_32.57)
5788 int WINAPI WS_gethostname(char *name, int namelen)
5790 TRACE("name %p, len %d\n", name, namelen);
5792 if (gethostname(name, namelen) == 0)
5794 TRACE("<- '%s'\n", name);
5795 return 0;
5797 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
5798 TRACE("<- ERROR !\n");
5799 return SOCKET_ERROR;
5803 /* ------------------------------------- Windows sockets extensions -- *
5805 * ------------------------------------------------------------------- */
5807 /***********************************************************************
5808 * WSAEnumNetworkEvents (WS2_32.36)
5810 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
5812 int ret;
5813 int i;
5814 int errors[FD_MAX_EVENTS];
5816 TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
5818 SERVER_START_REQ( get_socket_event )
5820 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5821 req->service = TRUE;
5822 req->c_event = wine_server_obj_handle( hEvent );
5823 wine_server_set_reply( req, errors, sizeof(errors) );
5824 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
5826 SERVER_END_REQ;
5827 if (!ret)
5829 for (i = 0; i < FD_MAX_EVENTS; i++)
5830 lpEvent->iErrorCode[i] = NtStatusToWSAError(errors[i]);
5831 return 0;
5833 SetLastError(WSAEINVAL);
5834 return SOCKET_ERROR;
5837 /***********************************************************************
5838 * WSAEventSelect (WS2_32.39)
5840 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
5842 int ret;
5844 TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
5846 SERVER_START_REQ( set_socket_event )
5848 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5849 req->mask = lEvent;
5850 req->event = wine_server_obj_handle( hEvent );
5851 req->window = 0;
5852 req->msg = 0;
5853 ret = wine_server_call( req );
5855 SERVER_END_REQ;
5856 if (!ret) return 0;
5857 SetLastError(WSAEINVAL);
5858 return SOCKET_ERROR;
5861 /**********************************************************************
5862 * WSAGetOverlappedResult (WS2_32.40)
5864 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
5865 LPDWORD lpcbTransfer, BOOL fWait,
5866 LPDWORD lpdwFlags )
5868 NTSTATUS status;
5870 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
5871 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
5873 if ( lpOverlapped == NULL )
5875 ERR( "Invalid pointer\n" );
5876 WSASetLastError(WSA_INVALID_PARAMETER);
5877 return FALSE;
5880 status = lpOverlapped->Internal;
5881 if (status == STATUS_PENDING)
5883 if (!fWait)
5885 SetLastError( WSA_IO_INCOMPLETE );
5886 return FALSE;
5889 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
5890 INFINITE ) == WAIT_FAILED)
5891 return FALSE;
5892 status = lpOverlapped->Internal;
5895 if ( lpcbTransfer )
5896 *lpcbTransfer = lpOverlapped->InternalHigh;
5898 if ( lpdwFlags )
5899 *lpdwFlags = lpOverlapped->u.s.Offset;
5901 if (status) SetLastError( RtlNtStatusToDosError(status) );
5902 return !status;
5906 /***********************************************************************
5907 * WSAAsyncSelect (WS2_32.101)
5909 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
5911 int ret;
5913 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
5915 SERVER_START_REQ( set_socket_event )
5917 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5918 req->mask = lEvent;
5919 req->event = 0;
5920 req->window = wine_server_user_handle( hWnd );
5921 req->msg = uMsg;
5922 ret = wine_server_call( req );
5924 SERVER_END_REQ;
5925 if (!ret) return 0;
5926 SetLastError(WSAEINVAL);
5927 return SOCKET_ERROR;
5930 /***********************************************************************
5931 * WSACreateEvent (WS2_32.31)
5934 WSAEVENT WINAPI WSACreateEvent(void)
5936 /* Create a manual-reset event, with initial state: unsignaled */
5937 TRACE("\n");
5939 return CreateEventW(NULL, TRUE, FALSE, NULL);
5942 /***********************************************************************
5943 * WSACloseEvent (WS2_32.29)
5946 BOOL WINAPI WSACloseEvent(WSAEVENT event)
5948 TRACE ("event=%p\n", event);
5950 return CloseHandle(event);
5953 /***********************************************************************
5954 * WSASocketA (WS2_32.78)
5957 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
5958 LPWSAPROTOCOL_INFOA lpProtocolInfo,
5959 GROUP g, DWORD dwFlags)
5961 INT len;
5962 WSAPROTOCOL_INFOW info;
5964 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
5965 af, type, protocol, lpProtocolInfo, g, dwFlags);
5967 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
5969 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
5970 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
5971 info.szProtocol, WSAPROTOCOL_LEN + 1);
5973 if (!len)
5975 WSASetLastError( WSAEINVAL);
5976 return SOCKET_ERROR;
5979 return WSASocketW(af, type, protocol, &info, g, dwFlags);
5982 /***********************************************************************
5983 * WSASocketW (WS2_32.79)
5986 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
5987 LPWSAPROTOCOL_INFOW lpProtocolInfo,
5988 GROUP g, DWORD dwFlags)
5990 SOCKET ret;
5991 DWORD err;
5992 int unixaf, unixtype, ipxptype = -1;
5995 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
5996 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
5999 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
6000 af, type, protocol, lpProtocolInfo, g, dwFlags );
6002 if (!num_startup)
6004 err = WSANOTINITIALISED;
6005 goto done;
6008 /* hack for WSADuplicateSocket */
6009 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
6010 ret = lpProtocolInfo->dwServiceFlags3;
6011 TRACE("\tgot duplicate %04lx\n", ret);
6012 return ret;
6015 if (lpProtocolInfo)
6017 if (af == FROM_PROTOCOL_INFO || !af)
6018 af = lpProtocolInfo->iAddressFamily;
6019 if (type == FROM_PROTOCOL_INFO || !type)
6020 type = lpProtocolInfo->iSocketType;
6021 if (protocol == FROM_PROTOCOL_INFO || !protocol)
6022 protocol = lpProtocolInfo->iProtocol;
6025 if (!type && (af || protocol))
6027 int autoproto = protocol;
6028 WSAPROTOCOL_INFOW infow;
6030 /* default to the first valid protocol */
6031 if (!autoproto)
6032 autoproto = valid_protocols[0];
6033 else if(IS_IPX_PROTO(autoproto))
6034 autoproto = WS_NSPROTO_IPX;
6036 if (WS_EnterSingleProtocolW(autoproto, &infow))
6038 type = infow.iSocketType;
6040 /* after win2003 it's no longer possible to pass AF_UNSPEC
6041 using the protocol info struct */
6042 if (!lpProtocolInfo && af == WS_AF_UNSPEC)
6043 af = infow.iAddressFamily;
6048 Windows has an extension to the IPX protocol that allows to create sockets
6049 and set the IPX packet type at the same time, to do that a caller will use
6050 a protocol like NSPROTO_IPX + <PACKET TYPE>
6052 if (IS_IPX_PROTO(protocol))
6053 ipxptype = protocol - WS_NSPROTO_IPX;
6055 /* convert the socket family, type and protocol */
6056 unixaf = convert_af_w2u(af);
6057 unixtype = convert_socktype_w2u(type);
6058 protocol = convert_proto_w2u(protocol);
6059 if (unixaf == AF_UNSPEC) unixaf = -1;
6061 /* filter invalid parameters */
6062 if (protocol < 0)
6064 /* the type could not be converted */
6065 if (type && unixtype < 0)
6067 err = WSAESOCKTNOSUPPORT;
6068 goto done;
6071 err = WSAEPROTONOSUPPORT;
6072 goto done;
6074 if (unixaf < 0)
6076 /* both family and protocol can't be invalid */
6077 if (protocol <= 0)
6079 err = WSAEINVAL;
6080 goto done;
6083 /* family could not be converted and neither socket type */
6084 if (unixtype < 0 && af >= 0)
6087 err = WSAESOCKTNOSUPPORT;
6088 goto done;
6091 err = WSAEAFNOSUPPORT;
6092 goto done;
6095 SERVER_START_REQ( create_socket )
6097 req->family = unixaf;
6098 req->type = unixtype;
6099 req->protocol = protocol;
6100 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
6101 req->attributes = OBJ_INHERIT;
6102 req->flags = dwFlags;
6103 set_error( wine_server_call( req ) );
6104 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
6106 SERVER_END_REQ;
6107 if (ret)
6109 TRACE("\tcreated %04lx\n", ret );
6110 if (ipxptype > 0)
6111 set_ipx_packettype(ret, ipxptype);
6112 return ret;
6115 err = GetLastError();
6116 if (err == WSAEACCES) /* raw socket denied */
6118 if (type == SOCK_RAW)
6119 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
6120 else
6121 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
6123 else
6125 /* invalid combination of valid parameters, like SOCK_STREAM + IPPROTO_UDP */
6126 if (err == WSAEINVAL)
6127 err = WSAESOCKTNOSUPPORT;
6128 else if (err == WSAEOPNOTSUPP)
6129 err = WSAEPROTONOSUPPORT;
6132 done:
6133 WARN("\t\tfailed, error %d!\n", err);
6134 SetLastError(err);
6135 return INVALID_SOCKET;
6138 /***********************************************************************
6139 * WSAJoinLeaf (WS2_32.58)
6142 SOCKET WINAPI WSAJoinLeaf(
6143 SOCKET s,
6144 const struct WS_sockaddr *addr,
6145 int addrlen,
6146 LPWSABUF lpCallerData,
6147 LPWSABUF lpCalleeData,
6148 LPQOS lpSQOS,
6149 LPQOS lpGQOS,
6150 DWORD dwFlags)
6152 FIXME("stub.\n");
6153 return INVALID_SOCKET;
6156 /***********************************************************************
6157 * __WSAFDIsSet (WS2_32.151)
6159 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
6161 int i = set->fd_count;
6163 TRACE("(%ld,%p(%i))\n", s, set, i);
6165 while (i--)
6166 if (set->fd_array[i] == s) return 1;
6167 return 0;
6170 /***********************************************************************
6171 * WSAIsBlocking (WS2_32.114)
6173 BOOL WINAPI WSAIsBlocking(void)
6175 /* By default WinSock should set all its sockets to non-blocking mode
6176 * and poll in PeekMessage loop when processing "blocking" ones. This
6177 * function is supposed to tell if the program is in this loop. Our
6178 * blocking calls are truly blocking so we always return FALSE.
6180 * Note: It is allowed to call this function without prior WSAStartup().
6183 TRACE("\n");
6184 return FALSE;
6187 /***********************************************************************
6188 * WSACancelBlockingCall (WS2_32.113)
6190 INT WINAPI WSACancelBlockingCall(void)
6192 TRACE("\n");
6193 return 0;
6196 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
6198 FIXME("How was this called?\n");
6199 return x();
6203 /***********************************************************************
6204 * WSASetBlockingHook (WS2_32.109)
6206 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
6208 FARPROC prev = blocking_hook;
6209 blocking_hook = lpBlockFunc;
6210 TRACE("hook %p\n", lpBlockFunc);
6211 return prev;
6215 /***********************************************************************
6216 * WSAUnhookBlockingHook (WS2_32.110)
6218 INT WINAPI WSAUnhookBlockingHook(void)
6220 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
6221 return 0;
6225 /* ----------------------------------- end of API stuff */
6227 /* ----------------------------------- helper functions -
6229 * TODO: Merge WS_dup_..() stuff into one function that
6230 * would operate with a generic structure containing internal
6231 * pointers (via a template of some kind).
6234 static int list_size(char** l, int item_size)
6236 int i,j = 0;
6237 if(l)
6238 { for(i=0;l[i];i++)
6239 j += (item_size) ? item_size : strlen(l[i]) + 1;
6240 j += (i + 1) * sizeof(char*); }
6241 return j;
6244 static int list_dup(char** l_src, char** l_to, int item_size)
6246 char *p;
6247 int i;
6249 for (i = 0; l_src[i]; i++) ;
6250 p = (char *)(l_to + i + 1);
6251 for (i = 0; l_src[i]; i++)
6253 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
6254 memcpy(p, l_src[i], count);
6255 l_to[i] = p;
6256 p += count;
6258 l_to[i] = NULL;
6259 return p - (char *)l_to;
6262 /* ----- hostent */
6264 /* create a hostent entry
6266 * Creates the entry with enough memory for the name, aliases
6267 * addresses, and the address pointers. Also copies the name
6268 * and sets up all the pointers.
6270 * NOTE: The alias and address lists must be allocated with room
6271 * for the NULL item terminating the list. This is true even if
6272 * the list has no items ("aliases" and "addresses" must be
6273 * at least "1", a truly empty list is invalid).
6275 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length)
6277 struct WS_hostent *p_to;
6278 char *p;
6279 int size = (sizeof(struct WS_hostent) +
6280 strlen(name) + 1 +
6281 sizeof(char *) * aliases +
6282 aliases_size +
6283 sizeof(char *) * addresses +
6284 address_length * (addresses - 1)), i;
6286 if (!(p_to = check_buffer_he(size))) return NULL;
6287 memset(p_to, 0, size);
6289 /* Use the memory in the same way winsock does.
6290 * First set the pointer for aliases, second set the pointers for addresses.
6291 * Third fill the addresses indexes, fourth jump aliases names size.
6292 * Fifth fill the hostname.
6293 * NOTE: This method is valid for OS version's >= XP.
6295 p = (char *)(p_to + 1);
6296 p_to->h_aliases = (char **)p;
6297 p += sizeof(char *)*aliases;
6299 p_to->h_addr_list = (char **)p;
6300 p += sizeof(char *)*addresses;
6302 for (i = 0, addresses--; i < addresses; i++, p += address_length)
6303 p_to->h_addr_list[i] = p;
6305 /* NOTE: h_aliases must be filled in manually because we don't know each string
6306 * size, leave these pointers NULL (already set to NULL by memset earlier).
6308 p += aliases_size;
6310 p_to->h_name = p;
6311 strcpy(p, name);
6313 return p_to;
6316 /* duplicate hostent entry
6317 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
6318 * Ditto for protoent and servent.
6320 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
6322 int i, addresses = 0, alias_size = 0;
6323 struct WS_hostent *p_to;
6324 char *p;
6326 for( i = 0; p_he->h_aliases[i]; i++) alias_size += strlen(p_he->h_aliases[i]) + 1;
6327 while (p_he->h_addr_list[addresses]) addresses++;
6329 p_to = WS_create_he(p_he->h_name, i + 1, alias_size, addresses + 1, p_he->h_length);
6331 if (!p_to) return NULL;
6332 p_to->h_addrtype = p_he->h_addrtype;
6333 p_to->h_length = p_he->h_length;
6335 for(i = 0, p = p_to->h_addr_list[0]; p_he->h_addr_list[i]; i++, p += p_to->h_length)
6336 memcpy(p, p_he->h_addr_list[i], p_to->h_length);
6338 /* Fill the aliases after the IP data */
6339 for(i = 0; p_he->h_aliases[i]; i++)
6341 p_to->h_aliases[i] = p;
6342 strcpy(p, p_he->h_aliases[i]);
6343 p += strlen(p) + 1;
6346 return p_to;
6349 /* ----- protoent */
6351 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
6353 char *p;
6354 struct WS_protoent *p_to;
6356 int size = (sizeof(*p_pe) +
6357 strlen(p_pe->p_name) + 1 +
6358 list_size(p_pe->p_aliases, 0));
6360 if (!(p_to = check_buffer_pe(size))) return NULL;
6361 p_to->p_proto = p_pe->p_proto;
6363 p = (char *)(p_to + 1);
6364 p_to->p_name = p;
6365 strcpy(p, p_pe->p_name);
6366 p += strlen(p) + 1;
6368 p_to->p_aliases = (char **)p;
6369 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
6370 return p_to;
6373 /* ----- servent */
6375 static struct WS_servent *WS_dup_se(const struct servent* p_se)
6377 char *p;
6378 struct WS_servent *p_to;
6380 int size = (sizeof(*p_se) +
6381 strlen(p_se->s_proto) + 1 +
6382 strlen(p_se->s_name) + 1 +
6383 list_size(p_se->s_aliases, 0));
6385 if (!(p_to = check_buffer_se(size))) return NULL;
6386 p_to->s_port = p_se->s_port;
6388 p = (char *)(p_to + 1);
6389 p_to->s_name = p;
6390 strcpy(p, p_se->s_name);
6391 p += strlen(p) + 1;
6393 p_to->s_proto = p;
6394 strcpy(p, p_se->s_proto);
6395 p += strlen(p) + 1;
6397 p_to->s_aliases = (char **)p;
6398 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
6399 return p_to;
6403 /***********************************************************************
6404 * WSARecv (WS2_32.67)
6406 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6407 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
6408 LPWSAOVERLAPPED lpOverlapped,
6409 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
6411 return WS2_recv_base(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
6412 NULL, NULL, lpOverlapped, lpCompletionRoutine, NULL);
6415 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6416 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
6417 struct WS_sockaddr *lpFrom,
6418 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
6419 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
6420 LPWSABUF lpControlBuffer )
6422 unsigned int i, options;
6423 int n, fd, err;
6424 struct ws2_async *wsa;
6425 BOOL is_blocking;
6426 DWORD timeout_start = GetTickCount();
6427 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
6429 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
6430 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
6431 (lpFromlen ? *lpFromlen : -1),
6432 lpOverlapped, lpCompletionRoutine);
6434 fd = get_sock_fd( s, FILE_READ_DATA, &options );
6435 TRACE( "fd=%d, options=%x\n", fd, options );
6437 if (fd == -1) return SOCKET_ERROR;
6439 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
6441 err = WSAEFAULT;
6442 goto error;
6445 wsa->hSocket = SOCKET2HANDLE(s);
6446 wsa->flags = *lpFlags;
6447 wsa->lpFlags = lpFlags;
6448 wsa->addr = lpFrom;
6449 wsa->addrlen.ptr = lpFromlen;
6450 wsa->control = lpControlBuffer;
6451 wsa->n_iovecs = dwBufferCount;
6452 wsa->first_iovec = 0;
6453 for (i = 0; i < dwBufferCount; i++)
6455 /* check buffer first to trigger write watches */
6456 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
6458 err = WSAEFAULT;
6459 goto error;
6461 wsa->iovec[i].iov_base = lpBuffers[i].buf;
6462 wsa->iovec[i].iov_len = lpBuffers[i].len;
6465 for (;;)
6467 n = WS2_recv( fd, wsa );
6468 if (n == -1)
6470 if (errno == EINTR) continue;
6471 if (errno != EAGAIN)
6473 int loc_errno = errno;
6474 err = wsaErrno();
6475 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
6476 goto error;
6479 else if (lpNumberOfBytesRecvd) *lpNumberOfBytesRecvd = n;
6481 if ((lpOverlapped || lpCompletionRoutine) &&
6482 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
6484 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
6486 wsa->user_overlapped = lpOverlapped;
6487 wsa->completion_func = lpCompletionRoutine;
6488 release_sock_fd( s, fd );
6490 if (n == -1)
6492 iosb->u.Status = STATUS_PENDING;
6493 iosb->Information = 0;
6495 SERVER_START_REQ( register_async )
6497 req->type = ASYNC_TYPE_READ;
6498 req->async.handle = wine_server_obj_handle( wsa->hSocket );
6499 req->async.callback = wine_server_client_ptr( WS2_async_recv );
6500 req->async.iosb = wine_server_client_ptr( iosb );
6501 req->async.arg = wine_server_client_ptr( wsa );
6502 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
6503 req->async.cvalue = cvalue;
6504 err = wine_server_call( req );
6506 SERVER_END_REQ;
6508 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
6509 WSASetLastError( NtStatusToWSAError( err ));
6510 return SOCKET_ERROR;
6513 iosb->u.Status = STATUS_SUCCESS;
6514 iosb->Information = n;
6515 if (!wsa->completion_func)
6517 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
6518 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
6519 HeapFree( GetProcessHeap(), 0, wsa );
6521 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
6522 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
6523 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6524 return 0;
6527 if (n != -1) break;
6529 if ((err = _is_blocking( s, &is_blocking )))
6531 err = NtStatusToWSAError( err );
6532 goto error;
6535 if ( is_blocking )
6537 struct pollfd pfd;
6538 int timeout = GET_RCVTIMEO(fd);
6539 if (timeout != -1)
6541 timeout -= GetTickCount() - timeout_start;
6542 if (timeout < 0) timeout = 0;
6545 pfd.fd = fd;
6546 pfd.events = POLLIN;
6547 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
6549 if (!timeout || !poll( &pfd, 1, timeout ))
6551 err = WSAETIMEDOUT;
6552 /* a timeout is not fatal */
6553 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6554 goto error;
6557 else
6559 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6560 err = WSAEWOULDBLOCK;
6561 goto error;
6565 TRACE(" -> %i bytes\n", n);
6566 HeapFree( GetProcessHeap(), 0, wsa );
6567 release_sock_fd( s, fd );
6568 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6570 return 0;
6572 error:
6573 HeapFree( GetProcessHeap(), 0, wsa );
6574 release_sock_fd( s, fd );
6575 WARN(" -> ERROR %d\n", err);
6576 WSASetLastError( err );
6577 return SOCKET_ERROR;
6580 /***********************************************************************
6581 * WSARecvFrom (WS2_32.69)
6583 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6584 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
6585 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
6586 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
6589 return WS2_recv_base( s, lpBuffers, dwBufferCount,
6590 lpNumberOfBytesRecvd, lpFlags,
6591 lpFrom, lpFromlen,
6592 lpOverlapped, lpCompletionRoutine, NULL );
6595 /***********************************************************************
6596 * WSCInstallProvider (WS2_32.88)
6598 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
6599 LPCWSTR lpszProviderDllPath,
6600 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
6601 DWORD dwNumberOfEntries,
6602 LPINT lpErrno )
6604 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
6605 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
6606 dwNumberOfEntries, lpErrno);
6607 *lpErrno = 0;
6608 return 0;
6612 /***********************************************************************
6613 * WSCDeinstallProvider (WS2_32.83)
6615 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
6617 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
6618 *lpErrno = 0;
6619 return 0;
6623 /***********************************************************************
6624 * WSAAccept (WS2_32.26)
6626 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
6627 LPCONDITIONPROC lpfnCondition, DWORD_PTR dwCallbackData)
6630 int ret = 0, size;
6631 WSABUF CallerId, CallerData, CalleeId, CalleeData;
6632 /* QOS SQOS, GQOS; */
6633 GROUP g;
6634 SOCKET cs;
6635 SOCKADDR src_addr, dst_addr;
6637 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
6638 s, addr, addrlen, lpfnCondition, dwCallbackData);
6640 cs = WS_accept(s, addr, addrlen);
6641 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
6642 if (!lpfnCondition) return cs;
6644 if (addr && addrlen)
6646 CallerId.buf = (char *)addr;
6647 CallerId.len = *addrlen;
6649 else
6651 size = sizeof(src_addr);
6652 WS_getpeername(cs, &src_addr, &size);
6653 CallerId.buf = (char *)&src_addr;
6654 CallerId.len = size;
6656 CallerData.buf = NULL;
6657 CallerData.len = 0;
6659 size = sizeof(dst_addr);
6660 WS_getsockname(cs, &dst_addr, &size);
6662 CalleeId.buf = (char *)&dst_addr;
6663 CalleeId.len = sizeof(dst_addr);
6665 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
6666 &CalleeId, &CalleeData, &g, dwCallbackData);
6668 switch (ret)
6670 case CF_ACCEPT:
6671 return cs;
6672 case CF_DEFER:
6673 SERVER_START_REQ( set_socket_deferred )
6675 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6676 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
6677 if ( !wine_server_call_err ( req ) )
6679 SetLastError( WSATRY_AGAIN );
6680 WS_closesocket( cs );
6683 SERVER_END_REQ;
6684 return SOCKET_ERROR;
6685 case CF_REJECT:
6686 WS_closesocket(cs);
6687 SetLastError(WSAECONNREFUSED);
6688 return SOCKET_ERROR;
6689 default:
6690 FIXME("Unknown return type from Condition function\n");
6691 SetLastError(WSAENOTSOCK);
6692 return SOCKET_ERROR;
6696 /***********************************************************************
6697 * WSADuplicateSocketA (WS2_32.32)
6699 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
6701 return WS_DuplicateSocket(FALSE, s, dwProcessId, (LPWSAPROTOCOL_INFOW) lpProtocolInfo);
6704 /***********************************************************************
6705 * WSADuplicateSocketW (WS2_32.33)
6707 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
6709 return WS_DuplicateSocket(TRUE, s, dwProcessId, lpProtocolInfo);
6712 /***********************************************************************
6713 * WSAInstallServiceClassA (WS2_32.48)
6715 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
6717 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
6718 WSASetLastError(WSAEACCES);
6719 return SOCKET_ERROR;
6722 /***********************************************************************
6723 * WSAInstallServiceClassW (WS2_32.49)
6725 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
6727 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
6728 WSASetLastError(WSAEACCES);
6729 return SOCKET_ERROR;
6732 /***********************************************************************
6733 * WSARemoveServiceClass (WS2_32.70)
6735 int WINAPI WSARemoveServiceClass(LPGUID info)
6737 FIXME("Request to remove service %p\n",info);
6738 WSASetLastError(WSATYPE_NOT_FOUND);
6739 return SOCKET_ERROR;
6742 /***********************************************************************
6743 * inet_ntop (WS2_32.@)
6745 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
6747 #ifdef HAVE_INET_NTOP
6748 struct WS_in6_addr *in6;
6749 struct WS_in_addr *in;
6750 PCSTR pdst;
6752 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
6753 if (!buffer)
6755 WSASetLastError( STATUS_INVALID_PARAMETER );
6756 return NULL;
6759 switch (family)
6761 case WS_AF_INET:
6763 in = addr;
6764 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
6765 break;
6767 case WS_AF_INET6:
6769 in6 = addr;
6770 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
6771 break;
6773 default:
6774 WSASetLastError( WSAEAFNOSUPPORT );
6775 return NULL;
6778 if (!pdst) WSASetLastError( STATUS_INVALID_PARAMETER );
6779 return pdst;
6780 #else
6781 FIXME( "not supported on this platform\n" );
6782 WSASetLastError( WSAEAFNOSUPPORT );
6783 return NULL;
6784 #endif
6787 /***********************************************************************
6788 * WSAStringToAddressA (WS2_32.80)
6790 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
6791 INT AddressFamily,
6792 LPWSAPROTOCOL_INFOA lpProtocolInfo,
6793 LPSOCKADDR lpAddress,
6794 LPINT lpAddressLength)
6796 INT res=0;
6797 LPSTR workBuffer=NULL,ptrPort;
6799 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
6800 lpProtocolInfo, lpAddress, lpAddressLength );
6802 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
6804 if (!AddressString)
6806 WSASetLastError(WSAEINVAL);
6807 return SOCKET_ERROR;
6810 if (lpProtocolInfo)
6811 FIXME("ProtocolInfo not implemented.\n");
6813 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
6814 strlen(AddressString) + 1);
6815 if (!workBuffer)
6817 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6818 return SOCKET_ERROR;
6821 strcpy(workBuffer, AddressString);
6823 switch(AddressFamily)
6825 case WS_AF_INET:
6827 struct in_addr inetaddr;
6829 /* If lpAddressLength is too small, tell caller the size we need */
6830 if (*lpAddressLength < sizeof(SOCKADDR_IN))
6832 *lpAddressLength = sizeof(SOCKADDR_IN);
6833 res = WSAEFAULT;
6834 break;
6836 *lpAddressLength = sizeof(SOCKADDR_IN);
6837 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
6839 ((LPSOCKADDR_IN)lpAddress)->sin_family = AF_INET;
6841 ptrPort = strchr(workBuffer, ':');
6842 if(ptrPort)
6844 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
6845 *ptrPort = '\0';
6847 else
6849 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
6852 if(inet_aton(workBuffer, &inetaddr) > 0)
6854 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
6855 res = 0;
6857 else
6858 res = WSAEINVAL;
6860 break;
6863 case WS_AF_INET6:
6865 struct in6_addr inetaddr;
6866 /* If lpAddressLength is too small, tell caller the size we need */
6867 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
6869 *lpAddressLength = sizeof(SOCKADDR_IN6);
6870 res = WSAEFAULT;
6871 break;
6873 #ifdef HAVE_INET_PTON
6874 *lpAddressLength = sizeof(SOCKADDR_IN6);
6875 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
6877 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
6879 /* This one is a bit tricky. An IPv6 address contains colons, so the
6880 * check from IPv4 doesn't work like that. However, IPv6 addresses that
6881 * contain a port are written with braces like [fd12:3456:7890::1]:12345
6882 * so what we will do is to look for ']', check if the next char is a
6883 * colon, and if it is, parse the port as in IPv4. */
6885 ptrPort = strchr(workBuffer, ']');
6886 if(ptrPort && *(++ptrPort) == ':')
6888 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort+1));
6889 *ptrPort = '\0';
6891 else
6893 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
6896 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
6898 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
6899 sizeof(struct in6_addr));
6900 res = 0;
6902 else
6903 #endif /* HAVE_INET_PTON */
6904 res = WSAEINVAL;
6906 break;
6908 default:
6909 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
6910 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
6911 res = WSAEINVAL;
6914 HeapFree(GetProcessHeap(), 0, workBuffer);
6916 if (!res) return 0;
6917 WSASetLastError(res);
6918 return SOCKET_ERROR;
6921 /***********************************************************************
6922 * WSAStringToAddressW (WS2_32.81)
6924 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
6925 * If this should be the case, it would be required to map these digits
6926 * to Unicode digits (0-9) using FoldString first.
6928 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
6929 INT AddressFamily,
6930 LPWSAPROTOCOL_INFOW lpProtocolInfo,
6931 LPSOCKADDR lpAddress,
6932 LPINT lpAddressLength)
6934 INT sBuffer,res=0;
6935 LPSTR workBuffer=NULL;
6936 WSAPROTOCOL_INFOA infoA;
6937 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
6939 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
6940 lpAddress, lpAddressLength );
6942 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
6944 /* if ProtocolInfo is available - convert to ANSI variant */
6945 if (lpProtocolInfo)
6947 lpProtoInfoA = &infoA;
6948 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
6950 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
6951 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
6953 WSASetLastError( WSAEINVAL);
6954 return SOCKET_ERROR;
6958 if (AddressString)
6960 /* Translate AddressString to ANSI code page - assumes that only
6961 standard digits 0-9 are used with this API call */
6962 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
6963 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
6965 if (workBuffer)
6967 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
6968 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
6969 lpAddress,lpAddressLength);
6970 HeapFree( GetProcessHeap(), 0, workBuffer );
6971 return res;
6973 else
6974 res = WSA_NOT_ENOUGH_MEMORY;
6976 else
6977 res = WSAEINVAL;
6979 WSASetLastError(res);
6980 return SOCKET_ERROR;
6983 /***********************************************************************
6984 * WSAAddressToStringA (WS2_32.27)
6986 * See WSAAddressToStringW
6988 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
6989 LPWSAPROTOCOL_INFOA info, LPSTR string,
6990 LPDWORD lenstr )
6992 DWORD size;
6993 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
6994 CHAR *p;
6996 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
6998 if (!sockaddr) return SOCKET_ERROR;
6999 if (!string || !lenstr) return SOCKET_ERROR;
7001 switch(sockaddr->sa_family)
7003 case WS_AF_INET:
7004 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
7005 sprintf( buffer, "%u.%u.%u.%u:%u",
7006 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
7007 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
7008 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
7009 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
7010 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
7012 p = strchr( buffer, ':' );
7013 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
7014 break;
7016 case WS_AF_INET6:
7018 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
7020 buffer[0] = 0;
7021 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
7022 if ((sockaddr6->sin6_port))
7023 strcpy(buffer, "[");
7024 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, buffer+strlen(buffer), sizeof(buffer)))
7026 WSASetLastError(WSAEINVAL);
7027 return SOCKET_ERROR;
7029 if ((sockaddr6->sin6_scope_id))
7030 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
7031 if ((sockaddr6->sin6_port))
7032 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
7033 break;
7036 default:
7037 WSASetLastError(WSAEINVAL);
7038 return SOCKET_ERROR;
7041 size = strlen( buffer ) + 1;
7043 if (*lenstr < size)
7045 *lenstr = size;
7046 WSASetLastError(WSAEFAULT);
7047 return SOCKET_ERROR;
7050 TRACE("=> %s,%u bytes\n", debugstr_a(buffer), size);
7051 *lenstr = size;
7052 strcpy( string, buffer );
7053 return 0;
7056 /***********************************************************************
7057 * WSAAddressToStringW (WS2_32.28)
7059 * Convert a sockaddr address into a readable address string.
7061 * PARAMS
7062 * sockaddr [I] Pointer to a sockaddr structure.
7063 * len [I] Size of the sockaddr structure.
7064 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
7065 * string [I/O] Pointer to a buffer to receive the address string.
7066 * lenstr [I/O] Size of the receive buffer in WCHARs.
7068 * RETURNS
7069 * Success: 0
7070 * Failure: SOCKET_ERROR
7072 * NOTES
7073 * The 'info' parameter is ignored.
7075 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
7076 LPWSAPROTOCOL_INFOW info, LPWSTR string,
7077 LPDWORD lenstr )
7079 INT ret;
7080 DWORD size;
7081 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
7082 CHAR bufAddr[54];
7084 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
7086 size = *lenstr;
7087 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
7089 if (ret) return ret;
7091 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
7093 if (*lenstr < size)
7095 *lenstr = size;
7096 WSASetLastError(WSAEFAULT);
7097 return SOCKET_ERROR;
7100 TRACE("=> %s,%u bytes\n", debugstr_w(buffer), size);
7101 *lenstr = size;
7102 lstrcpyW( string, buffer );
7103 return 0;
7106 /***********************************************************************
7107 * WSAEnumNameSpaceProvidersA (WS2_32.34)
7109 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
7111 FIXME( "(%p %p) Stub!\n", len, buffer );
7112 return 0;
7115 /***********************************************************************
7116 * WSAEnumNameSpaceProvidersW (WS2_32.35)
7118 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
7120 FIXME( "(%p %p) Stub!\n", len, buffer );
7121 return 0;
7124 /***********************************************************************
7125 * WSAGetQOSByName (WS2_32.41)
7127 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
7129 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
7130 return FALSE;
7133 /***********************************************************************
7134 * WSAGetServiceClassInfoA (WS2_32.42)
7136 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
7137 LPWSASERVICECLASSINFOA info )
7139 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
7140 len, info );
7141 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7142 return SOCKET_ERROR;
7145 /***********************************************************************
7146 * WSAGetServiceClassInfoW (WS2_32.43)
7148 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
7149 LPWSASERVICECLASSINFOW info )
7151 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
7152 len, info );
7153 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7154 return SOCKET_ERROR;
7157 /***********************************************************************
7158 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
7160 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
7162 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
7163 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7164 return SOCKET_ERROR;
7167 /***********************************************************************
7168 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
7170 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
7172 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
7173 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7174 return SOCKET_ERROR;
7177 /***********************************************************************
7178 * WSALookupServiceBeginA (WS2_32.59)
7180 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
7181 DWORD dwControlFlags,
7182 LPHANDLE lphLookup)
7184 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
7185 lphLookup);
7186 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7187 return SOCKET_ERROR;
7190 /***********************************************************************
7191 * WSALookupServiceBeginW (WS2_32.60)
7193 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
7194 DWORD dwControlFlags,
7195 LPHANDLE lphLookup)
7197 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
7198 lphLookup);
7199 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7200 return SOCKET_ERROR;
7203 /***********************************************************************
7204 * WSALookupServiceEnd (WS2_32.61)
7206 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
7208 FIXME("(%p) Stub!\n", lookup );
7209 return 0;
7212 /***********************************************************************
7213 * WSALookupServiceNextA (WS2_32.62)
7215 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
7217 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
7218 WSASetLastError(WSA_E_NO_MORE);
7219 return SOCKET_ERROR;
7222 /***********************************************************************
7223 * WSALookupServiceNextW (WS2_32.63)
7225 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
7227 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
7228 WSASetLastError(WSA_E_NO_MORE);
7229 return SOCKET_ERROR;
7232 /***********************************************************************
7233 * WSANtohl (WS2_32.64)
7235 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
7237 TRACE( "(0x%04lx 0x%08x %p)\n", s, netlong, lphostlong );
7239 if (!lphostlong) return WSAEFAULT;
7241 *lphostlong = ntohl( netlong );
7242 return 0;
7245 /***********************************************************************
7246 * WSANtohs (WS2_32.65)
7248 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
7250 TRACE( "(0x%04lx 0x%08x %p)\n", s, netshort, lphostshort );
7252 if (!lphostshort) return WSAEFAULT;
7254 *lphostshort = ntohs( netshort );
7255 return 0;
7258 /***********************************************************************
7259 * WSAProviderConfigChange (WS2_32.66)
7261 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
7262 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
7264 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
7265 return SOCKET_ERROR;
7268 /***********************************************************************
7269 * WSARecvDisconnect (WS2_32.68)
7271 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
7273 TRACE( "(0x%04lx %p)\n", s, disconnectdata );
7275 return WS_shutdown( s, 0 );
7278 /***********************************************************************
7279 * WSASetServiceA (WS2_32.76)
7281 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
7283 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
7284 return 0;
7287 /***********************************************************************
7288 * WSASetServiceW (WS2_32.77)
7290 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
7292 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
7293 return 0;
7296 /***********************************************************************
7297 * WSCEnableNSProvider (WS2_32.84)
7299 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
7301 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
7302 return 0;
7305 /***********************************************************************
7306 * WSCGetProviderPath (WS2_32.86)
7308 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
7310 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
7312 if (!errcode || !provider || !len) return WSAEFAULT;
7314 *errcode = WSAEINVAL;
7315 return SOCKET_ERROR;
7318 /***********************************************************************
7319 * WSCInstallNameSpace (WS2_32.87)
7321 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
7322 DWORD version, LPGUID provider )
7324 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
7325 namespace, version, debugstr_guid(provider) );
7326 return 0;
7329 /***********************************************************************
7330 * WSCUnInstallNameSpace (WS2_32.89)
7332 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
7334 FIXME("(%p) Stub!\n", lpProviderId);
7335 return NO_ERROR;
7338 /***********************************************************************
7339 * WSCWriteProviderOrder (WS2_32.91)
7341 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
7343 FIXME("(%p 0x%08x) Stub!\n", entry, number);
7344 return 0;
7347 /***********************************************************************
7348 * WSANSPIoctl (WS2_32.91)
7350 INT WINAPI WSANSPIoctl( HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer,
7351 DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer,
7352 LPDWORD lpcbBytesReturned, LPWSACOMPLETION lpCompletion )
7354 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup, dwControlCode,
7355 lpvInBuffer, cbInBuffer, lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpCompletion);
7356 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7357 return SOCKET_ERROR;
7360 /*****************************************************************************
7361 * WSAEnumProtocolsA [WS2_32.@]
7363 * see function WSAEnumProtocolsW
7365 INT WINAPI WSAEnumProtocolsA( LPINT protocols, LPWSAPROTOCOL_INFOA buffer, LPDWORD len )
7367 return WS_EnumProtocols( FALSE, protocols, (LPWSAPROTOCOL_INFOW) buffer, len);
7370 /*****************************************************************************
7371 * WSAEnumProtocolsW [WS2_32.@]
7373 * Retrieves information about specified set of active network protocols.
7375 * PARAMS
7376 * protocols [I] Pointer to null-terminated array of protocol id's. NULL
7377 * retrieves information on all available protocols.
7378 * buffer [I] Pointer to a buffer to be filled with WSAPROTOCOL_INFO
7379 * structures.
7380 * len [I/O] Pointer to a variable specifying buffer size. On output
7381 * the variable holds the number of bytes needed when the
7382 * specified size is too small.
7384 * RETURNS
7385 * Success: number of WSAPROTOCOL_INFO structures in buffer.
7386 * Failure: SOCKET_ERROR
7388 * NOTES
7389 * NT4SP5 does not return SPX if protocols == NULL
7391 * BUGS
7392 * - NT4SP5 returns in addition these list of NETBIOS protocols
7393 * (address family 17), each entry two times one for socket type 2 and 5
7395 * iProtocol szProtocol
7396 * 0x80000000 \Device\NwlnkNb
7397 * 0xfffffffa \Device\NetBT_CBENT7
7398 * 0xfffffffb \Device\Nbf_CBENT7
7399 * 0xfffffffc \Device\NetBT_NdisWan5
7400 * 0xfffffffd \Device\NetBT_El9202
7401 * 0xfffffffe \Device\Nbf_El9202
7402 * 0xffffffff \Device\Nbf_NdisWan4
7404 * - there is no check that the operating system supports the returned
7405 * protocols
7407 INT WINAPI WSAEnumProtocolsW( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
7409 return WS_EnumProtocols( TRUE, protocols, buffer, len);
7412 /*****************************************************************************
7413 * WSCEnumProtocols [WS2_32.@]
7415 * PARAMS
7416 * protocols [I] Null-terminated array of iProtocol values.
7417 * buffer [O] Buffer of WSAPROTOCOL_INFOW structures.
7418 * len [I/O] Size of buffer on input/output.
7419 * errno [O] Error code.
7421 * RETURNS
7422 * Success: number of protocols to be reported on.
7423 * Failure: SOCKET_ERROR. error is in errno.
7425 * BUGS
7426 * Doesn't supply info on layered protocols.
7429 INT WINAPI WSCEnumProtocols( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len, LPINT err )
7431 INT ret = WSAEnumProtocolsW( protocols, buffer, len );
7433 if (ret == SOCKET_ERROR) *err = WSAENOBUFS;
7435 return ret;