ws2_32: Avoid a crash with tracing on.
[wine.git] / dlls / ws2_32 / socket.c
blobbd5a476e8049560dc6c49995f50701bb847248ad
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 NSPROTO_IPX,
199 NSPROTO_SPX,
200 NSPROTO_SPXII,
204 #if defined(IP_UNICAST_IF) && defined(SO_ATTACH_FILTER)
205 # define LINUX_BOUND_IF
206 struct interface_filter {
207 struct sock_filter iface_memaddr;
208 struct sock_filter iface_rule;
209 struct sock_filter ip_memaddr;
210 struct sock_filter ip_rule;
211 struct sock_filter return_keep;
212 struct sock_filter return_dump;
214 # define FILTER_JUMP_DUMP(here) (u_char)(offsetof(struct interface_filter, return_dump) \
215 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
216 /sizeof(struct sock_filter)
217 # define FILTER_JUMP_KEEP(here) (u_char)(offsetof(struct interface_filter, return_keep) \
218 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
219 /sizeof(struct sock_filter)
220 # define FILTER_JUMP_NEXT() (u_char)(0)
221 # define SKF_NET_DESTIP 16 /* offset in the network header to the destination IP */
222 static struct interface_filter generic_interface_filter = {
223 /* This filter rule allows incoming packets on the specified interface, which works for all
224 * remotely generated packets and for locally generated broadcast packets. */
225 BPF_STMT(BPF_LD+BPF_W+BPF_ABS, SKF_AD_OFF+SKF_AD_IFINDEX),
226 BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0xdeadbeef, FILTER_JUMP_KEEP(iface_rule), FILTER_JUMP_NEXT()),
227 /* This rule allows locally generated packets targeted at the specific IP address of the chosen
228 * adapter (local packets not destined for the broadcast address do not have IFINDEX set) */
229 BPF_STMT(BPF_LD+BPF_W+BPF_ABS, SKF_NET_OFF+SKF_NET_DESTIP),
230 BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0xdeadbeef, FILTER_JUMP_KEEP(ip_rule), FILTER_JUMP_DUMP(ip_rule)),
231 BPF_STMT(BPF_RET+BPF_K, (u_int)-1), /* keep packet */
232 BPF_STMT(BPF_RET+BPF_K, 0) /* dump packet */
234 #endif /* LINUX_BOUND_IF */
237 * The actual definition of WSASendTo, wrapped in a different function name
238 * so that internal calls from ws2_32 itself will not trigger programs like
239 * Garena, which hooks WSASendTo/WSARecvFrom calls.
241 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
242 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
243 const struct WS_sockaddr *to, int tolen,
244 LPWSAOVERLAPPED lpOverlapped,
245 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine );
248 * Internal fundamental receive function, essentially WSARecvFrom with an
249 * additional parameter to support message control headers.
251 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
252 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
253 struct WS_sockaddr *lpFrom,
254 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
255 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
256 LPWSABUF lpControlBuffer );
258 /* critical section to protect some non-reentrant net function */
259 static CRITICAL_SECTION csWSgetXXXbyYYY;
260 static CRITICAL_SECTION_DEBUG critsect_debug =
262 0, 0, &csWSgetXXXbyYYY,
263 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
264 0, 0, { (DWORD_PTR)(__FILE__ ": csWSgetXXXbyYYY") }
266 static CRITICAL_SECTION csWSgetXXXbyYYY = { &critsect_debug, -1, 0, 0, 0, 0 };
268 union generic_unix_sockaddr
270 struct sockaddr addr;
271 char data[128]; /* should be big enough for all families */
274 static inline const char *debugstr_sockaddr( const struct WS_sockaddr *a )
276 if (!a) return "(nil)";
277 switch (a->sa_family)
279 case WS_AF_INET:
280 return wine_dbg_sprintf("{ family AF_INET, address %s, port %d }",
281 inet_ntoa(((const struct sockaddr_in *)a)->sin_addr),
282 ntohs(((const struct sockaddr_in *)a)->sin_port));
283 case WS_AF_INET6:
285 char buf[46];
286 const char *p;
287 struct WS_sockaddr_in6 *sin = (struct WS_sockaddr_in6 *)a;
289 p = WS_inet_ntop( WS_AF_INET6, &sin->sin6_addr, buf, sizeof(buf) );
290 if (!p)
291 p = "(unknown IPv6 address)";
292 return wine_dbg_sprintf("{ family AF_INET6, address %s, port %d }",
293 p, ntohs(sin->sin6_port));
295 case WS_AF_IRDA:
297 DWORD addr;
299 memcpy( &addr, ((const SOCKADDR_IRDA *)a)->irdaDeviceID, sizeof(addr) );
300 addr = ntohl( addr );
301 return wine_dbg_sprintf("{ family AF_IRDA, addr %08x, name %s }",
302 addr,
303 ((const SOCKADDR_IRDA *)a)->irdaServiceName);
305 default:
306 return wine_dbg_sprintf("{ family %d }", a->sa_family);
310 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
311 #define SOCKET2HANDLE(s) ((HANDLE)(s))
312 #define HANDLE2SOCKET(h) ((SOCKET)(h))
314 /****************************************************************
315 * Async IO declarations
316 ****************************************************************/
318 typedef struct ws2_async
320 HANDLE hSocket;
321 int type;
322 LPWSAOVERLAPPED user_overlapped;
323 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
324 IO_STATUS_BLOCK local_iosb;
325 struct WS_sockaddr *addr;
326 union
328 int val; /* for send operations */
329 int *ptr; /* for recv operations */
330 } addrlen;
331 DWORD flags;
332 DWORD *lpFlags;
333 WSABUF *control;
334 unsigned int n_iovecs;
335 unsigned int first_iovec;
336 struct iovec iovec[1];
337 } ws2_async;
339 typedef struct ws2_accept_async
341 HANDLE listen_socket;
342 HANDLE accept_socket;
343 LPOVERLAPPED user_overlapped;
344 ULONG_PTR cvalue;
345 PVOID buf; /* buffer to write data to */
346 int data_len;
347 int local_len;
348 int remote_len;
349 struct ws2_async *read;
350 } ws2_accept_async;
352 /****************************************************************/
354 /* ----------------------------------- internal data */
356 /* ws_... struct conversion flags */
358 typedef struct /* WSAAsyncSelect() control struct */
360 HANDLE service, event, sock;
361 HWND hWnd;
362 UINT uMsg;
363 LONG lEvent;
364 } ws_select_info;
366 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
367 #define WS_MAX_UDP_DATAGRAM 1024
368 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
370 /* hostent's, servent's and protent's are stored in one buffer per thread,
371 * as documented on MSDN for the functions that return any of the buffers */
372 struct per_thread_data
374 int opentype;
375 struct WS_hostent *he_buffer;
376 struct WS_servent *se_buffer;
377 struct WS_protoent *pe_buffer;
378 int he_len;
379 int se_len;
380 int pe_len;
383 /* internal: routing description information */
384 struct route {
385 struct in_addr addr;
386 IF_INDEX interface;
387 DWORD metric;
390 static INT num_startup; /* reference counter */
391 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
393 /* function prototypes */
394 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length);
395 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
396 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
397 static struct WS_servent *WS_dup_se(const struct servent* p_se);
398 static int ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size);
400 int WSAIOCTL_GetInterfaceCount(void);
401 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
403 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus, ULONG Information );
405 #define MAP_OPTION(opt) { WS_##opt, opt }
407 static const int ws_sock_map[][2] =
409 MAP_OPTION( SO_DEBUG ),
410 MAP_OPTION( SO_ACCEPTCONN ),
411 MAP_OPTION( SO_REUSEADDR ),
412 MAP_OPTION( SO_KEEPALIVE ),
413 MAP_OPTION( SO_DONTROUTE ),
414 MAP_OPTION( SO_BROADCAST ),
415 MAP_OPTION( SO_LINGER ),
416 MAP_OPTION( SO_OOBINLINE ),
417 MAP_OPTION( SO_SNDBUF ),
418 MAP_OPTION( SO_RCVBUF ),
419 MAP_OPTION( SO_ERROR ),
420 MAP_OPTION( SO_TYPE ),
421 #ifdef SO_RCVTIMEO
422 MAP_OPTION( SO_RCVTIMEO ),
423 #endif
424 #ifdef SO_SNDTIMEO
425 MAP_OPTION( SO_SNDTIMEO ),
426 #endif
429 static const int ws_tcp_map[][2] =
431 #ifdef TCP_NODELAY
432 MAP_OPTION( TCP_NODELAY ),
433 #endif
436 static const int ws_ip_map[][2] =
438 MAP_OPTION( IP_MULTICAST_IF ),
439 MAP_OPTION( IP_MULTICAST_TTL ),
440 MAP_OPTION( IP_MULTICAST_LOOP ),
441 MAP_OPTION( IP_ADD_MEMBERSHIP ),
442 MAP_OPTION( IP_DROP_MEMBERSHIP ),
443 MAP_OPTION( IP_OPTIONS ),
444 #ifdef IP_HDRINCL
445 MAP_OPTION( IP_HDRINCL ),
446 #endif
447 MAP_OPTION( IP_TOS ),
448 MAP_OPTION( IP_TTL ),
449 #ifdef IP_PKTINFO
450 MAP_OPTION( IP_PKTINFO ),
451 #endif
452 #ifdef IP_UNICAST_IF
453 MAP_OPTION( IP_UNICAST_IF ),
454 #endif
457 static const int ws_ipv6_map[][2] =
459 #ifdef IPV6_ADD_MEMBERSHIP
460 MAP_OPTION( IPV6_ADD_MEMBERSHIP ),
461 #endif
462 #ifdef IPV6_DROP_MEMBERSHIP
463 MAP_OPTION( IPV6_DROP_MEMBERSHIP ),
464 #endif
465 MAP_OPTION( IPV6_MULTICAST_IF ),
466 MAP_OPTION( IPV6_MULTICAST_HOPS ),
467 MAP_OPTION( IPV6_MULTICAST_LOOP ),
468 MAP_OPTION( IPV6_UNICAST_HOPS ),
469 MAP_OPTION( IPV6_V6ONLY ),
470 #ifdef IPV6_UNICAST_IF
471 MAP_OPTION( IPV6_UNICAST_IF ),
472 #endif
475 static const int ws_af_map[][2] =
477 MAP_OPTION( AF_UNSPEC ),
478 MAP_OPTION( AF_INET ),
479 MAP_OPTION( AF_INET6 ),
480 #ifdef HAS_IPX
481 MAP_OPTION( AF_IPX ),
482 #endif
483 #ifdef AF_IRDA
484 MAP_OPTION( AF_IRDA ),
485 #endif
486 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
489 static const int ws_socktype_map[][2] =
491 MAP_OPTION( SOCK_DGRAM ),
492 MAP_OPTION( SOCK_STREAM ),
493 MAP_OPTION( SOCK_RAW ),
494 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
497 static const int ws_proto_map[][2] =
499 MAP_OPTION( IPPROTO_IP ),
500 MAP_OPTION( IPPROTO_TCP ),
501 MAP_OPTION( IPPROTO_UDP ),
502 MAP_OPTION( IPPROTO_ICMP ),
503 MAP_OPTION( IPPROTO_IGMP ),
504 MAP_OPTION( IPPROTO_RAW ),
505 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
508 static const int ws_aiflag_map[][2] =
510 MAP_OPTION( AI_PASSIVE ),
511 MAP_OPTION( AI_CANONNAME ),
512 MAP_OPTION( AI_NUMERICHOST ),
513 MAP_OPTION( AI_ADDRCONFIG ),
516 static const int ws_niflag_map[][2] =
518 MAP_OPTION( NI_NOFQDN ),
519 MAP_OPTION( NI_NUMERICHOST ),
520 MAP_OPTION( NI_NAMEREQD ),
521 MAP_OPTION( NI_NUMERICSERV ),
522 MAP_OPTION( NI_DGRAM ),
525 static const int ws_eai_map[][2] =
527 MAP_OPTION( EAI_AGAIN ),
528 MAP_OPTION( EAI_BADFLAGS ),
529 MAP_OPTION( EAI_FAIL ),
530 MAP_OPTION( EAI_FAMILY ),
531 MAP_OPTION( EAI_MEMORY ),
532 /* Note: EAI_NODATA is deprecated, but still
533 * used by Windows and Linux... We map the newer
534 * EAI_NONAME to EAI_NODATA for now until Windows
535 * changes too.
537 #ifdef EAI_NODATA
538 MAP_OPTION( EAI_NODATA ),
539 #endif
540 #ifdef EAI_NONAME
541 { WS_EAI_NODATA, EAI_NONAME },
542 #endif
544 MAP_OPTION( EAI_SERVICE ),
545 MAP_OPTION( EAI_SOCKTYPE ),
546 { 0, 0 }
549 static const char magic_loopback_addr[] = {127, 12, 34, 56};
551 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
552 static inline WSACMSGHDR *fill_control_message(int level, int type, WSACMSGHDR *current, ULONG *maxsize, void *data, int len)
554 ULONG msgsize = sizeof(WSACMSGHDR) + WSA_CMSG_ALIGN(len);
555 char *ptr = (char *) current + sizeof(WSACMSGHDR);
557 /* Make sure there is at least enough room for this entry */
558 if (msgsize > *maxsize)
559 return NULL;
560 *maxsize -= msgsize;
561 /* Fill in the entry */
562 current->cmsg_len = sizeof(WSACMSGHDR) + len;
563 current->cmsg_level = level;
564 current->cmsg_type = type;
565 memcpy(ptr, data, len);
566 /* Return the pointer to where next entry should go */
567 return (WSACMSGHDR *) (ptr + WSA_CMSG_ALIGN(len));
570 static inline int convert_control_headers(struct msghdr *hdr, WSABUF *control)
572 #ifdef IP_PKTINFO
573 WSACMSGHDR *cmsg_win = (WSACMSGHDR *) control->buf, *ptr;
574 ULONG ctlsize = control->len;
575 struct cmsghdr *cmsg_unix;
577 ptr = cmsg_win;
578 /* Loop over all the headers, converting as appropriate */
579 for (cmsg_unix = CMSG_FIRSTHDR(hdr); cmsg_unix != NULL; cmsg_unix = CMSG_NXTHDR(hdr, cmsg_unix))
581 switch(cmsg_unix->cmsg_level)
583 case IPPROTO_IP:
584 switch(cmsg_unix->cmsg_type)
586 case IP_PKTINFO:
588 /* Convert the Unix IP_PKTINFO structure to the Windows version */
589 struct in_pktinfo *data_unix = (struct in_pktinfo *) CMSG_DATA(cmsg_unix);
590 struct WS_in_pktinfo data_win;
592 memcpy(&data_win.ipi_addr,&data_unix->ipi_addr.s_addr,4); /* 4 bytes = 32 address bits */
593 data_win.ipi_ifindex = data_unix->ipi_ifindex;
594 ptr = fill_control_message(WS_IPPROTO_IP, WS_IP_PKTINFO, ptr, &ctlsize,
595 (void*)&data_win, sizeof(data_win));
596 if (!ptr) goto error;
597 } break;
598 default:
599 FIXME("Unhandled IPPROTO_IP message header type %d\n", cmsg_unix->cmsg_type);
600 break;
602 break;
603 default:
604 FIXME("Unhandled message header level %d\n", cmsg_unix->cmsg_level);
605 break;
609 error:
610 /* Set the length of the returned control headers */
611 control->len = (ptr == NULL ? 0 : (char*)ptr - (char*)cmsg_win);
612 return (ptr != NULL);
613 #else /* IP_PKTINFO */
614 control->len = 0;
615 return 1;
616 #endif /* IP_PKTINFO */
618 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
620 /* ----------------------------------- error handling */
622 static NTSTATUS sock_get_ntstatus( int err )
624 switch ( err )
626 case EBADF: return STATUS_INVALID_HANDLE;
627 case EBUSY: return STATUS_DEVICE_BUSY;
628 case EPERM:
629 case EACCES: return STATUS_ACCESS_DENIED;
630 case EFAULT: return STATUS_NO_MEMORY;
631 case EINVAL: return STATUS_INVALID_PARAMETER;
632 case ENFILE:
633 case EMFILE: return STATUS_TOO_MANY_OPENED_FILES;
634 case EWOULDBLOCK: return STATUS_CANT_WAIT;
635 case EINPROGRESS: return STATUS_PENDING;
636 case EALREADY: return STATUS_NETWORK_BUSY;
637 case ENOTSOCK: return STATUS_OBJECT_TYPE_MISMATCH;
638 case EDESTADDRREQ: return STATUS_INVALID_PARAMETER;
639 case EMSGSIZE: return STATUS_BUFFER_OVERFLOW;
640 case EPROTONOSUPPORT:
641 case ESOCKTNOSUPPORT:
642 case EPFNOSUPPORT:
643 case EAFNOSUPPORT:
644 case EPROTOTYPE: return STATUS_NOT_SUPPORTED;
645 case ENOPROTOOPT: return STATUS_INVALID_PARAMETER;
646 case EOPNOTSUPP: return STATUS_NOT_SUPPORTED;
647 case EADDRINUSE: return STATUS_ADDRESS_ALREADY_ASSOCIATED;
648 case EADDRNOTAVAIL: return STATUS_INVALID_PARAMETER;
649 case ECONNREFUSED: return STATUS_CONNECTION_REFUSED;
650 case ESHUTDOWN: return STATUS_PIPE_DISCONNECTED;
651 case ENOTCONN: return STATUS_CONNECTION_DISCONNECTED;
652 case ETIMEDOUT: return STATUS_IO_TIMEOUT;
653 case ENETUNREACH: return STATUS_NETWORK_UNREACHABLE;
654 case ENETDOWN: return STATUS_NETWORK_BUSY;
655 case EPIPE:
656 case ECONNRESET: return STATUS_CONNECTION_RESET;
657 case ECONNABORTED: return STATUS_CONNECTION_ABORTED;
659 case 0: return STATUS_SUCCESS;
660 default:
661 WARN("Unknown errno %d!\n", err);
662 return STATUS_UNSUCCESSFUL;
666 static UINT sock_get_error( int err )
668 switch(err)
670 case EINTR: return WSAEINTR;
671 case EBADF: return WSAEBADF;
672 case EPERM:
673 case EACCES: return WSAEACCES;
674 case EFAULT: return WSAEFAULT;
675 case EINVAL: return WSAEINVAL;
676 case EMFILE: return WSAEMFILE;
677 case EWOULDBLOCK: return WSAEWOULDBLOCK;
678 case EINPROGRESS: return WSAEINPROGRESS;
679 case EALREADY: return WSAEALREADY;
680 case ENOTSOCK: return WSAENOTSOCK;
681 case EDESTADDRREQ: return WSAEDESTADDRREQ;
682 case EMSGSIZE: return WSAEMSGSIZE;
683 case EPROTOTYPE: return WSAEPROTOTYPE;
684 case ENOPROTOOPT: return WSAENOPROTOOPT;
685 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
686 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
687 case EOPNOTSUPP: return WSAEOPNOTSUPP;
688 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
689 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
690 case EADDRINUSE: return WSAEADDRINUSE;
691 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
692 case ENETDOWN: return WSAENETDOWN;
693 case ENETUNREACH: return WSAENETUNREACH;
694 case ENETRESET: return WSAENETRESET;
695 case ECONNABORTED: return WSAECONNABORTED;
696 case EPIPE:
697 case ECONNRESET: return WSAECONNRESET;
698 case ENOBUFS: return WSAENOBUFS;
699 case EISCONN: return WSAEISCONN;
700 case ENOTCONN: return WSAENOTCONN;
701 case ESHUTDOWN: return WSAESHUTDOWN;
702 case ETOOMANYREFS: return WSAETOOMANYREFS;
703 case ETIMEDOUT: return WSAETIMEDOUT;
704 case ECONNREFUSED: return WSAECONNREFUSED;
705 case ELOOP: return WSAELOOP;
706 case ENAMETOOLONG: return WSAENAMETOOLONG;
707 case EHOSTDOWN: return WSAEHOSTDOWN;
708 case EHOSTUNREACH: return WSAEHOSTUNREACH;
709 case ENOTEMPTY: return WSAENOTEMPTY;
710 #ifdef EPROCLIM
711 case EPROCLIM: return WSAEPROCLIM;
712 #endif
713 #ifdef EUSERS
714 case EUSERS: return WSAEUSERS;
715 #endif
716 #ifdef EDQUOT
717 case EDQUOT: return WSAEDQUOT;
718 #endif
719 #ifdef ESTALE
720 case ESTALE: return WSAESTALE;
721 #endif
722 #ifdef EREMOTE
723 case EREMOTE: return WSAEREMOTE;
724 #endif
726 /* just in case we ever get here and there are no problems */
727 case 0: return 0;
728 default:
729 WARN("Unknown errno %d!\n", err);
730 return WSAEOPNOTSUPP;
734 static UINT wsaErrno(void)
736 int loc_errno = errno;
737 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
739 return sock_get_error( loc_errno );
742 /* most ws2 overlapped functions return an ntstatus-based error code */
743 static NTSTATUS wsaErrStatus(void)
745 int loc_errno = errno;
746 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
748 return sock_get_ntstatus(loc_errno);
751 static UINT wsaHerrno(int loc_errno)
753 WARN("h_errno %d.\n", loc_errno);
755 switch(loc_errno)
757 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
758 case TRY_AGAIN: return WSATRY_AGAIN;
759 case NO_RECOVERY: return WSANO_RECOVERY;
760 case NO_DATA: return WSANO_DATA;
761 case ENOBUFS: return WSAENOBUFS;
763 case 0: return 0;
764 default:
765 WARN("Unknown h_errno %d!\n", loc_errno);
766 return WSAEOPNOTSUPP;
770 static inline DWORD NtStatusToWSAError( const DWORD status )
772 /* We only need to cover the status codes set by server async request handling */
773 DWORD wserr;
774 switch ( status )
776 case STATUS_SUCCESS: wserr = 0; break;
777 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
778 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
779 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
780 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
781 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
782 case STATUS_NETWORK_BUSY: wserr = WSAEALREADY; break;
783 case STATUS_NETWORK_UNREACHABLE: wserr = WSAENETUNREACH; break;
784 case STATUS_CONNECTION_REFUSED: wserr = WSAECONNREFUSED; break;
785 case STATUS_CONNECTION_DISCONNECTED: wserr = WSAENOTCONN; break;
786 case STATUS_CONNECTION_RESET: wserr = WSAECONNRESET; break;
787 case STATUS_CONNECTION_ABORTED: wserr = WSAECONNABORTED; break;
788 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
789 case STATUS_ADDRESS_ALREADY_ASSOCIATED: wserr = WSAEADDRINUSE; break;
790 case STATUS_IO_TIMEOUT:
791 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
792 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
793 case STATUS_ACCESS_DENIED: wserr = WSAEACCES; break;
794 case STATUS_TOO_MANY_OPENED_FILES: wserr = WSAEMFILE; break;
795 case STATUS_CANT_WAIT: wserr = WSAEWOULDBLOCK; break;
796 case STATUS_BUFFER_OVERFLOW: wserr = WSAEMSGSIZE; break;
797 case STATUS_NOT_SUPPORTED: wserr = WSAEOPNOTSUPP; break;
798 case STATUS_HOST_UNREACHABLE: wserr = WSAEHOSTUNREACH; break;
800 default:
801 wserr = RtlNtStatusToDosError( status );
802 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
804 return wserr;
807 /* set last error code from NT status without mapping WSA errors */
808 static inline unsigned int set_error( unsigned int err )
810 if (err)
812 err = NtStatusToWSAError( err );
813 SetLastError( err );
815 return err;
818 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
820 int fd;
821 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
822 return -1;
823 return fd;
826 static inline void release_sock_fd( SOCKET s, int fd )
828 wine_server_release_fd( SOCKET2HANDLE(s), fd );
831 static void _enable_event( HANDLE s, unsigned int event,
832 unsigned int sstate, unsigned int cstate )
834 SERVER_START_REQ( enable_socket_event )
836 req->handle = wine_server_obj_handle( s );
837 req->mask = event;
838 req->sstate = sstate;
839 req->cstate = cstate;
840 wine_server_call( req );
842 SERVER_END_REQ;
845 static NTSTATUS _is_blocking(SOCKET s, BOOL *ret)
847 NTSTATUS status;
848 SERVER_START_REQ( get_socket_event )
850 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
851 req->service = FALSE;
852 req->c_event = 0;
853 status = wine_server_call( req );
854 *ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
856 SERVER_END_REQ;
857 return status;
860 static unsigned int _get_sock_mask(SOCKET s)
862 unsigned int ret;
863 SERVER_START_REQ( get_socket_event )
865 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
866 req->service = FALSE;
867 req->c_event = 0;
868 wine_server_call( req );
869 ret = reply->mask;
871 SERVER_END_REQ;
872 return ret;
875 static void _sync_sock_state(SOCKET s)
877 BOOL dummy;
878 /* do a dummy wineserver request in order to let
879 the wineserver run through its select loop once */
880 (void)_is_blocking(s, &dummy);
883 static int _get_sock_error(SOCKET s, unsigned int bit)
885 int events[FD_MAX_EVENTS];
887 SERVER_START_REQ( get_socket_event )
889 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
890 req->service = FALSE;
891 req->c_event = 0;
892 wine_server_set_reply( req, events, sizeof(events) );
893 wine_server_call( req );
895 SERVER_END_REQ;
896 return events[bit];
899 static struct per_thread_data *get_per_thread_data(void)
901 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
902 /* lazy initialization */
903 if (!ptb)
905 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
906 NtCurrentTeb()->WinSockData = ptb;
908 return ptb;
911 static void free_per_thread_data(void)
913 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
915 if (!ptb) return;
917 /* delete scratch buffers */
918 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
919 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
920 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
921 ptb->he_buffer = NULL;
922 ptb->se_buffer = NULL;
923 ptb->pe_buffer = NULL;
925 HeapFree( GetProcessHeap(), 0, ptb );
926 NtCurrentTeb()->WinSockData = NULL;
929 /***********************************************************************
930 * DllMain (WS2_32.init)
932 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
934 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
935 switch (fdwReason) {
936 case DLL_PROCESS_ATTACH:
937 break;
938 case DLL_PROCESS_DETACH:
939 if (fImpLoad) break;
940 free_per_thread_data();
941 DeleteCriticalSection(&csWSgetXXXbyYYY);
942 break;
943 case DLL_THREAD_DETACH:
944 free_per_thread_data();
945 break;
947 return TRUE;
950 /***********************************************************************
951 * convert_sockopt()
953 * Converts socket flags from Windows format.
954 * Return 1 if converted, 0 if not (error).
956 static int convert_sockopt(INT *level, INT *optname)
958 unsigned int i;
959 switch (*level)
961 case WS_SOL_SOCKET:
962 *level = SOL_SOCKET;
963 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
964 if( ws_sock_map[i][0] == *optname )
966 *optname = ws_sock_map[i][1];
967 return 1;
970 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
971 break;
972 case WS_IPPROTO_TCP:
973 *level = IPPROTO_TCP;
974 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
975 if ( ws_tcp_map[i][0] == *optname )
977 *optname = ws_tcp_map[i][1];
978 return 1;
981 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
982 break;
983 case WS_IPPROTO_IP:
984 *level = IPPROTO_IP;
985 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
986 if (ws_ip_map[i][0] == *optname )
988 *optname = ws_ip_map[i][1];
989 return 1;
992 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
993 break;
994 case WS_IPPROTO_IPV6:
995 *level = IPPROTO_IPV6;
996 for(i=0; i<sizeof(ws_ipv6_map)/sizeof(ws_ipv6_map[0]); i++) {
997 if (ws_ipv6_map[i][0] == *optname )
999 *optname = ws_ipv6_map[i][1];
1000 return 1;
1003 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname);
1004 break;
1005 default: FIXME("Unimplemented or unknown socket level\n");
1007 return 0;
1010 /* ----------------------------------- Per-thread info (or per-process?) */
1012 static char *strdup_lower(const char *str)
1014 int i;
1015 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
1017 if (ret)
1019 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
1020 ret[i] = 0;
1022 else SetLastError(WSAENOBUFS);
1023 return ret;
1026 static inline int sock_error_p(int s)
1028 unsigned int optval;
1029 socklen_t optlen = sizeof(optval);
1030 getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
1031 if (optval) WARN("\t[%i] error: %d\n", s, optval);
1032 return optval != 0;
1035 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
1036 * from an fd and return the value converted to milli seconds
1037 * or -1 if there is an infinite time out */
1038 static inline int get_rcvsnd_timeo( int fd, int optname)
1040 struct timeval tv;
1041 socklen_t len = sizeof(tv);
1042 int ret = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
1043 if( ret >= 0)
1044 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
1045 if( ret <= 0 ) /* tv == {0,0} means infinite time out */
1046 return -1;
1047 return ret;
1050 /* macro wrappers for portability */
1051 #ifdef SO_RCVTIMEO
1052 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
1053 #else
1054 #define GET_RCVTIMEO(fd) (-1)
1055 #endif
1057 #ifdef SO_SNDTIMEO
1058 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
1059 #else
1060 #define GET_SNDTIMEO(fd) (-1)
1061 #endif
1063 /* utility: given an fd, will block until one of the events occurs */
1064 static inline int do_block( int fd, int events, int timeout )
1066 struct pollfd pfd;
1067 int ret;
1069 pfd.fd = fd;
1070 pfd.events = events;
1072 while ((ret = poll(&pfd, 1, timeout)) < 0)
1074 if (errno != EINTR)
1075 return -1;
1077 if( ret == 0 )
1078 return 0;
1079 return pfd.revents;
1082 static int
1083 convert_af_w2u(int windowsaf) {
1084 unsigned int i;
1086 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1087 if (ws_af_map[i][0] == windowsaf)
1088 return ws_af_map[i][1];
1089 FIXME("unhandled Windows address family %d\n", windowsaf);
1090 return -1;
1093 static int
1094 convert_af_u2w(int unixaf) {
1095 unsigned int i;
1097 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1098 if (ws_af_map[i][1] == unixaf)
1099 return ws_af_map[i][0];
1100 FIXME("unhandled UNIX address family %d\n", unixaf);
1101 return -1;
1104 static int
1105 convert_proto_w2u(int windowsproto) {
1106 unsigned int i;
1108 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1109 if (ws_proto_map[i][0] == windowsproto)
1110 return ws_proto_map[i][1];
1111 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
1112 return -1;
1115 static int
1116 convert_proto_u2w(int unixproto) {
1117 unsigned int i;
1119 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1120 if (ws_proto_map[i][1] == unixproto)
1121 return ws_proto_map[i][0];
1122 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
1123 return -1;
1126 static int
1127 convert_socktype_w2u(int windowssocktype) {
1128 unsigned int i;
1130 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1131 if (ws_socktype_map[i][0] == windowssocktype)
1132 return ws_socktype_map[i][1];
1133 FIXME("unhandled Windows socket type %d\n", windowssocktype);
1134 return -1;
1137 static int
1138 convert_socktype_u2w(int unixsocktype) {
1139 unsigned int i;
1141 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1142 if (ws_socktype_map[i][1] == unixsocktype)
1143 return ws_socktype_map[i][0];
1144 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
1145 return -1;
1148 /* ----------------------------------- API -----
1150 * Init / cleanup / error checking.
1153 /***********************************************************************
1154 * WSAStartup (WS2_32.115)
1156 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
1158 TRACE("verReq=%x\n", wVersionRequested);
1160 if (LOBYTE(wVersionRequested) < 1)
1161 return WSAVERNOTSUPPORTED;
1163 if (!lpWSAData) return WSAEINVAL;
1165 num_startup++;
1167 /* that's the whole of the negotiation for now */
1168 lpWSAData->wVersion = wVersionRequested;
1169 /* return winsock information */
1170 lpWSAData->wHighVersion = 0x0202;
1171 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
1172 strcpy(lpWSAData->szSystemStatus, "Running" );
1173 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
1174 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
1175 /* don't do anything with lpWSAData->lpVendorInfo */
1176 /* (some apps don't allocate the space for this field) */
1178 TRACE("succeeded\n");
1179 return 0;
1183 /***********************************************************************
1184 * WSACleanup (WS2_32.116)
1186 INT WINAPI WSACleanup(void)
1188 if (num_startup) {
1189 num_startup--;
1190 return 0;
1192 SetLastError(WSANOTINITIALISED);
1193 return SOCKET_ERROR;
1197 /***********************************************************************
1198 * WSAGetLastError (WS2_32.111)
1200 INT WINAPI WSAGetLastError(void)
1202 return GetLastError();
1205 /***********************************************************************
1206 * WSASetLastError (WS2_32.112)
1208 void WINAPI WSASetLastError(INT iError) {
1209 SetLastError(iError);
1212 static struct WS_hostent *check_buffer_he(int size)
1214 struct per_thread_data * ptb = get_per_thread_data();
1215 if (ptb->he_buffer)
1217 if (ptb->he_len >= size ) return ptb->he_buffer;
1218 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1220 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
1221 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
1222 return ptb->he_buffer;
1225 static struct WS_servent *check_buffer_se(int size)
1227 struct per_thread_data * ptb = get_per_thread_data();
1228 if (ptb->se_buffer)
1230 if (ptb->se_len >= size ) return ptb->se_buffer;
1231 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1233 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
1234 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
1235 return ptb->se_buffer;
1238 static struct WS_protoent *check_buffer_pe(int size)
1240 struct per_thread_data * ptb = get_per_thread_data();
1241 if (ptb->pe_buffer)
1243 if (ptb->pe_len >= size ) return ptb->pe_buffer;
1244 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1246 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
1247 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
1248 return ptb->pe_buffer;
1251 /* ----------------------------------- i/o APIs */
1253 static inline BOOL supported_pf(int pf)
1255 switch (pf)
1257 case WS_AF_INET:
1258 case WS_AF_INET6:
1259 return TRUE;
1260 #ifdef HAS_IPX
1261 case WS_AF_IPX:
1262 return TRUE;
1263 #endif
1264 #ifdef HAS_IRDA
1265 case WS_AF_IRDA:
1266 return TRUE;
1267 #endif
1268 default:
1269 return FALSE;
1273 static inline BOOL supported_protocol(int protocol)
1275 int i;
1276 for (i = 0; i < sizeof(valid_protocols) / sizeof(valid_protocols[0]); i++)
1277 if (protocol == valid_protocols[i])
1278 return TRUE;
1279 return FALSE;
1282 /**********************************************************************/
1284 /* Returns the length of the converted address if successful, 0 if it was too small to
1285 * start with.
1287 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
1288 union generic_unix_sockaddr *uaddr)
1290 unsigned int uaddrlen = 0;
1292 switch (wsaddr->sa_family)
1294 #ifdef HAS_IPX
1295 case WS_AF_IPX:
1297 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
1298 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
1300 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
1301 return 0;
1303 uaddrlen = sizeof(struct sockaddr_ipx);
1304 memset( uaddr, 0, uaddrlen );
1305 uipx->sipx_family=AF_IPX;
1306 uipx->sipx_port=wsipx->sa_socket;
1307 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1308 * in one go
1310 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
1311 #ifdef IPX_FRAME_NONE
1312 uipx->sipx_type=IPX_FRAME_NONE;
1313 #endif
1314 break;
1316 #endif
1317 case WS_AF_INET6: {
1318 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
1319 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
1321 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1322 * scope_id, one without.
1324 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
1325 uaddrlen = sizeof(struct sockaddr_in6);
1326 memset( uaddr, 0, uaddrlen );
1327 uin6->sin6_family = AF_INET6;
1328 uin6->sin6_port = win6->sin6_port;
1329 uin6->sin6_flowinfo = win6->sin6_flowinfo;
1330 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1331 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
1332 #endif
1333 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
1334 break;
1336 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
1337 return 0;
1339 case WS_AF_INET: {
1340 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
1341 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
1343 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
1344 return 0;
1345 uaddrlen = sizeof(struct sockaddr_in);
1346 memset( uaddr, 0, uaddrlen );
1347 uin->sin_family = AF_INET;
1348 uin->sin_port = win->sin_port;
1349 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
1350 break;
1352 #ifdef HAS_IRDA
1353 case WS_AF_IRDA: {
1354 struct sockaddr_irda *uin = (struct sockaddr_irda *)uaddr;
1355 const SOCKADDR_IRDA *win = (const SOCKADDR_IRDA *)wsaddr;
1357 if (wsaddrlen < sizeof(SOCKADDR_IRDA))
1358 return 0;
1359 uaddrlen = sizeof(struct sockaddr_irda);
1360 memset( uaddr, 0, uaddrlen );
1361 uin->sir_family = AF_IRDA;
1362 if (!strncmp( win->irdaServiceName, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1364 unsigned int lsap_sel = 0;
1366 sscanf( win->irdaServiceName, "LSAP-SEL%u", &lsap_sel );
1367 uin->sir_lsap_sel = lsap_sel;
1369 else
1371 uin->sir_lsap_sel = LSAP_ANY;
1372 memcpy( uin->sir_name, win->irdaServiceName, 25 );
1374 memcpy( &uin->sir_addr, win->irdaDeviceID, sizeof(uin->sir_addr) );
1375 break;
1377 #endif
1378 case WS_AF_UNSPEC: {
1379 /* Try to determine the needed space by the passed windows sockaddr space */
1380 switch (wsaddrlen) {
1381 default: /* likely a ipv4 address */
1382 case sizeof(struct WS_sockaddr_in):
1383 uaddrlen = sizeof(struct sockaddr_in);
1384 break;
1385 #ifdef HAS_IPX
1386 case sizeof(struct WS_sockaddr_ipx):
1387 uaddrlen = sizeof(struct sockaddr_ipx);
1388 break;
1389 #endif
1390 #ifdef HAS_IRDA
1391 case sizeof(SOCKADDR_IRDA):
1392 uaddrlen = sizeof(struct sockaddr_irda);
1393 break;
1394 #endif
1395 case sizeof(struct WS_sockaddr_in6):
1396 case sizeof(struct WS_sockaddr_in6_old):
1397 uaddrlen = sizeof(struct sockaddr_in6);
1398 break;
1400 memset( uaddr, 0, uaddrlen );
1401 break;
1403 default:
1404 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
1405 return 0;
1407 return uaddrlen;
1410 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
1412 switch (uaddr->sa_family)
1414 #ifdef HAS_IPX
1415 case AF_IPX:
1416 FIXME("don't know how to tell if IPX socket is bound, assuming it is!\n");
1417 return TRUE;
1418 #endif
1419 case AF_INET6:
1421 static const struct sockaddr_in6 emptyAddr;
1422 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
1423 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
1425 case AF_INET:
1427 static const struct sockaddr_in emptyAddr;
1428 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
1429 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
1431 case AF_UNSPEC:
1432 return FALSE;
1433 default:
1434 FIXME("unknown address family %d\n", uaddr->sa_family);
1435 return TRUE;
1439 /* Returns 0 if successful, -1 if the buffer is too small */
1440 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
1442 int res;
1444 switch(uaddr->sa_family)
1446 #ifdef HAS_IPX
1447 case AF_IPX:
1449 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
1450 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
1452 res=-1;
1453 switch (*wsaddrlen) /* how much can we copy? */
1455 default:
1456 res=0; /* enough */
1457 *wsaddrlen = sizeof(*wsipx);
1458 wsipx->sa_socket=uipx->sipx_port;
1459 /* fall through */
1460 case 13:
1461 case 12:
1462 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
1463 /* fall through */
1464 case 11:
1465 case 10:
1466 case 9:
1467 case 8:
1468 case 7:
1469 case 6:
1470 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1471 /* fall through */
1472 case 5:
1473 case 4:
1474 case 3:
1475 case 2:
1476 wsipx->sa_family=WS_AF_IPX;
1477 /* fall through */
1478 case 1:
1479 case 0:
1480 /* way too small */
1481 break;
1484 break;
1485 #endif
1486 #ifdef HAS_IRDA
1487 case AF_IRDA: {
1488 const struct sockaddr_irda *uin = (const struct sockaddr_irda *)uaddr;
1489 SOCKADDR_IRDA *win = (SOCKADDR_IRDA *)wsaddr;
1491 if (*wsaddrlen < sizeof(SOCKADDR_IRDA))
1492 return -1;
1493 win->irdaAddressFamily = WS_AF_IRDA;
1494 memcpy( win->irdaDeviceID, &uin->sir_addr, sizeof(win->irdaDeviceID) );
1495 if (uin->sir_lsap_sel != LSAP_ANY)
1496 sprintf( win->irdaServiceName, "LSAP-SEL%u", uin->sir_lsap_sel );
1497 else
1498 memcpy( win->irdaServiceName, uin->sir_name,
1499 sizeof(win->irdaServiceName) );
1500 return 0;
1502 #endif
1503 case AF_INET6: {
1504 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1505 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1507 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1508 return -1;
1509 win6old->sin6_family = WS_AF_INET6;
1510 win6old->sin6_port = uin6->sin6_port;
1511 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1512 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1513 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1514 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1515 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1516 win6->sin6_scope_id = uin6->sin6_scope_id;
1517 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1519 else
1520 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1521 #else
1522 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1523 #endif
1524 return 0;
1526 case AF_INET: {
1527 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1528 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1530 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1531 return -1;
1532 win->sin_family = WS_AF_INET;
1533 win->sin_port = uin->sin_port;
1534 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1535 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1536 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1537 return 0;
1539 case AF_UNSPEC: {
1540 memset(wsaddr,0,*wsaddrlen);
1541 return 0;
1543 default:
1544 FIXME("Unknown address family %d\n", uaddr->sa_family);
1545 return -1;
1547 return res;
1550 static INT WS_DuplicateSocket(BOOL unicode, SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo)
1552 HANDLE hProcess;
1553 int size;
1554 WSAPROTOCOL_INFOW infow;
1556 TRACE("(unicode %d, socket %04lx, processid %x, buffer %p)\n",
1557 unicode, s, dwProcessId, lpProtocolInfo);
1559 if (!ws_protocol_info(s, unicode, &infow, &size))
1560 return SOCKET_ERROR;
1562 if (!(hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId)))
1564 SetLastError(WSAEINVAL);
1565 return SOCKET_ERROR;
1568 if (!lpProtocolInfo)
1570 CloseHandle(hProcess);
1571 SetLastError(WSAEFAULT);
1572 return SOCKET_ERROR;
1575 /* I don't know what the real Windoze does next, this is a hack */
1576 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
1577 * the target use the global duplicate, or we could copy a reference to us to the structure
1578 * and let the target duplicate it from us, but let's do it as simple as possible */
1579 memcpy(lpProtocolInfo, &infow, size);
1580 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
1581 hProcess, (LPHANDLE)&lpProtocolInfo->dwServiceFlags3,
1582 0, FALSE, DUPLICATE_SAME_ACCESS);
1583 CloseHandle(hProcess);
1584 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
1585 return 0;
1588 /*****************************************************************************
1589 * WS_EnterSingleProtocolW [internal]
1591 * enters the protocol information of one given protocol into the given
1592 * buffer.
1594 * RETURNS
1595 * TRUE if a protocol was entered into the buffer.
1597 * BUGS
1598 * - only implemented for IPX, SPX, SPXII, TCP, UDP
1599 * - there is no check that the operating system supports the returned
1600 * protocols
1602 static BOOL WS_EnterSingleProtocolW( INT protocol, WSAPROTOCOL_INFOW* info )
1604 memset( info, 0, sizeof(WSAPROTOCOL_INFOW) );
1605 info->iProtocol = protocol;
1607 switch (protocol)
1609 case WS_IPPROTO_TCP:
1610 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_EXPEDITED_DATA |
1611 XP1_GRACEFUL_CLOSE | XP1_GUARANTEED_ORDER |
1612 XP1_GUARANTEED_DELIVERY;
1613 info->ProviderId = ProviderIdIP;
1614 info->dwCatalogEntryId = 0x3e9;
1615 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1616 info->ProtocolChain.ChainLen = 1;
1617 info->iVersion = 2;
1618 info->iAddressFamily = WS_AF_INET;
1619 info->iMaxSockAddr = 0x10;
1620 info->iMinSockAddr = 0x10;
1621 info->iSocketType = WS_SOCK_STREAM;
1622 strcpyW( info->szProtocol, NameTcpW );
1623 break;
1625 case WS_IPPROTO_UDP:
1626 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_SUPPORT_BROADCAST |
1627 XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED |
1628 XP1_CONNECTIONLESS;
1629 info->ProviderId = ProviderIdIP;
1630 info->dwCatalogEntryId = 0x3ea;
1631 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1632 info->ProtocolChain.ChainLen = 1;
1633 info->iVersion = 2;
1634 info->iAddressFamily = WS_AF_INET;
1635 info->iMaxSockAddr = 0x10;
1636 info->iMinSockAddr = 0x10;
1637 info->iSocketType = WS_SOCK_DGRAM;
1638 info->dwMessageSize = 0xffbb;
1639 strcpyW( info->szProtocol, NameUdpW );
1640 break;
1642 case NSPROTO_IPX:
1643 info->dwServiceFlags1 = XP1_PARTIAL_MESSAGE | XP1_SUPPORT_BROADCAST |
1644 XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED |
1645 XP1_CONNECTIONLESS;
1646 info->ProviderId = ProviderIdIPX;
1647 info->dwCatalogEntryId = 0x406;
1648 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1649 info->ProtocolChain.ChainLen = 1;
1650 info->iVersion = 2;
1651 info->iAddressFamily = WS_AF_IPX;
1652 info->iMaxSockAddr = 0x10;
1653 info->iMinSockAddr = 0x0e;
1654 info->iSocketType = WS_SOCK_DGRAM;
1655 info->iProtocolMaxOffset = 0xff;
1656 info->dwMessageSize = 0x240;
1657 strcpyW( info->szProtocol, NameIpxW );
1658 break;
1660 case NSPROTO_SPX:
1661 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_PSEUDO_STREAM |
1662 XP1_MESSAGE_ORIENTED | XP1_GUARANTEED_ORDER |
1663 XP1_GUARANTEED_DELIVERY;
1664 info->ProviderId = ProviderIdSPX;
1665 info->dwCatalogEntryId = 0x407;
1666 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1667 info->ProtocolChain.ChainLen = 1;
1668 info->iVersion = 2;
1669 info->iAddressFamily = WS_AF_IPX;
1670 info->iMaxSockAddr = 0x10;
1671 info->iMinSockAddr = 0x0e;
1672 info->iSocketType = WS_SOCK_SEQPACKET;
1673 info->dwMessageSize = 0xffffffff;
1674 strcpyW( info->szProtocol, NameSpxW );
1675 break;
1677 case NSPROTO_SPXII:
1678 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_GRACEFUL_CLOSE |
1679 XP1_PSEUDO_STREAM | XP1_MESSAGE_ORIENTED |
1680 XP1_GUARANTEED_ORDER | XP1_GUARANTEED_DELIVERY;
1681 info->ProviderId = ProviderIdSPX;
1682 info->dwCatalogEntryId = 0x409;
1683 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1684 info->ProtocolChain.ChainLen = 1;
1685 info->iVersion = 2;
1686 info->iAddressFamily = WS_AF_IPX;
1687 info->iMaxSockAddr = 0x10;
1688 info->iMinSockAddr = 0x0e;
1689 info->iSocketType = WS_SOCK_SEQPACKET;
1690 info->dwMessageSize = 0xffffffff;
1691 strcpyW( info->szProtocol, NameSpxIIW );
1692 break;
1694 default:
1695 FIXME("unknown Protocol <0x%08x>\n", protocol);
1696 return FALSE;
1698 return TRUE;
1701 /*****************************************************************************
1702 * WS_EnterSingleProtocolA [internal]
1704 * see function WS_EnterSingleProtocolW
1707 static BOOL WS_EnterSingleProtocolA( INT protocol, WSAPROTOCOL_INFOA* info )
1709 WSAPROTOCOL_INFOW infow;
1710 INT ret;
1711 memset( info, 0, sizeof(WSAPROTOCOL_INFOA) );
1713 ret = WS_EnterSingleProtocolW( protocol, &infow );
1714 if (ret)
1716 /* convert the structure from W to A */
1717 memcpy( info, &infow, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
1718 WideCharToMultiByte( CP_ACP, 0, infow.szProtocol, -1,
1719 info->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL );
1722 return ret;
1725 static INT WS_EnumProtocols( BOOL unicode, const INT *protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
1727 INT i = 0, items = 0;
1728 DWORD size = 0;
1729 union _info
1731 LPWSAPROTOCOL_INFOA a;
1732 LPWSAPROTOCOL_INFOW w;
1733 } info;
1734 info.w = buffer;
1736 if (!protocols) protocols = valid_protocols;
1738 while (protocols[i])
1740 if(supported_protocol(protocols[i++]))
1741 items++;
1744 size = items * (unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA));
1746 TRACE("unicode %d, protocols %p, buffer %p, length %p %d, items %d, required %d\n",
1747 unicode, protocols, buffer, len, len ? *len : 0, items, size);
1749 if (*len < size || !buffer)
1751 *len = size;
1752 WSASetLastError(WSAENOBUFS);
1753 return SOCKET_ERROR;
1756 for (i = items = 0; protocols[i]; i++)
1758 if (unicode)
1760 if (WS_EnterSingleProtocolW( protocols[i], &info.w[items] ))
1761 items++;
1763 else
1765 if (WS_EnterSingleProtocolA( protocols[i], &info.a[items] ))
1766 items++;
1769 return items;
1772 static BOOL ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size)
1774 NTSTATUS status;
1776 *size = unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA);
1777 memset(buffer, 0, *size);
1779 SERVER_START_REQ( get_socket_info )
1781 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1782 status = wine_server_call( req );
1783 if (!status)
1785 buffer->iAddressFamily = convert_af_u2w(reply->family);
1786 buffer->iSocketType = convert_socktype_u2w(reply->type);
1787 buffer->iProtocol = convert_proto_u2w(reply->protocol);
1790 SERVER_END_REQ;
1792 if (status)
1794 unsigned int err = NtStatusToWSAError( status );
1795 SetLastError( err == WSAEBADF ? WSAENOTSOCK : err );
1796 return FALSE;
1799 if (unicode)
1800 WS_EnterSingleProtocolW( buffer->iProtocol, buffer);
1801 else
1802 WS_EnterSingleProtocolA( buffer->iProtocol, (WSAPROTOCOL_INFOA *)buffer);
1804 return TRUE;
1807 /**************************************************************************
1808 * Functions for handling overlapped I/O
1809 **************************************************************************/
1811 /* user APC called upon async completion */
1812 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1814 ws2_async *wsa = arg;
1816 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
1817 iosb->Information, wsa->user_overlapped,
1818 wsa->flags );
1819 HeapFree( GetProcessHeap(), 0, wsa );
1822 /***********************************************************************
1823 * WS2_recv (INTERNAL)
1825 * Workhorse for both synchronous and asynchronous recv() operations.
1827 static int WS2_recv( int fd, struct ws2_async *wsa )
1829 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1830 char pktbuf[512];
1831 #endif
1832 struct msghdr hdr;
1833 union generic_unix_sockaddr unix_sockaddr;
1834 int n;
1836 hdr.msg_name = NULL;
1838 if (wsa->addr)
1840 hdr.msg_namelen = sizeof(unix_sockaddr);
1841 hdr.msg_name = &unix_sockaddr;
1843 else
1844 hdr.msg_namelen = 0;
1846 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1847 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1848 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1849 hdr.msg_accrights = NULL;
1850 hdr.msg_accrightslen = 0;
1851 #else
1852 hdr.msg_control = pktbuf;
1853 hdr.msg_controllen = sizeof(pktbuf);
1854 hdr.msg_flags = 0;
1855 #endif
1857 if ( (n = recvmsg(fd, &hdr, wsa->flags)) == -1 )
1858 return -1;
1860 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1861 if (wsa->control)
1863 ERR("Message control headers cannot be properly supported on this system.\n");
1864 wsa->control->len = 0;
1866 #else
1867 if (wsa->control && !convert_control_headers(&hdr, wsa->control))
1869 WARN("Application passed insufficient room for control headers.\n");
1870 *wsa->lpFlags |= WS_MSG_CTRUNC;
1871 errno = EMSGSIZE;
1872 return -1;
1874 #endif
1876 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
1877 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
1879 * quoting linux 2.6 net/ipv4/tcp.c:
1880 * "According to UNIX98, msg_name/msg_namelen are ignored
1881 * on connected socket. I was just happy when found this 8) --ANK"
1883 * likewise MSDN says that lpFrom and lpFromlen are ignored for
1884 * connection-oriented sockets, so don't try to update lpFrom.
1886 if (wsa->addr && hdr.msg_namelen)
1887 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
1889 return n;
1892 /***********************************************************************
1893 * WS2_async_recv (INTERNAL)
1895 * Handler for overlapped recv() operations.
1897 static NTSTATUS WS2_async_recv( void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1899 ws2_async* wsa = user;
1900 int result = 0, fd;
1902 switch (status)
1904 case STATUS_ALERTED:
1905 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
1906 break;
1908 result = WS2_recv( fd, wsa );
1909 wine_server_release_fd( wsa->hSocket, fd );
1910 if (result >= 0)
1912 status = STATUS_SUCCESS;
1913 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1915 else
1917 if (errno == EINTR || errno == EAGAIN)
1919 status = STATUS_PENDING;
1920 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1922 else
1924 result = 0;
1925 status = wsaErrStatus();
1928 break;
1930 if (status != STATUS_PENDING)
1932 iosb->u.Status = status;
1933 iosb->Information = result;
1934 *apc = ws2_async_apc;
1936 return status;
1939 /* user APC called upon async accept completion */
1940 static void WINAPI ws2_async_accept_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1942 struct ws2_accept_async *wsa = arg;
1944 HeapFree( GetProcessHeap(), 0, wsa->read );
1945 HeapFree( GetProcessHeap(), 0, wsa );
1948 /***********************************************************************
1949 * WS2_async_accept_recv (INTERNAL)
1951 * This function is used to finish the read part of an accept request. It is
1952 * needed to place the completion on the correct socket (listener).
1954 static NTSTATUS WS2_async_accept_recv( void *arg, IO_STATUS_BLOCK *iosb, NTSTATUS status, void **apc )
1956 void *junk;
1957 struct ws2_accept_async *wsa = arg;
1959 status = WS2_async_recv( wsa->read, iosb, status, &junk );
1960 if (status == STATUS_PENDING)
1961 return status;
1963 if (wsa->user_overlapped->hEvent)
1964 SetEvent(wsa->user_overlapped->hEvent);
1965 if (wsa->cvalue)
1966 WS_AddCompletion( HANDLE2SOCKET(wsa->listen_socket), wsa->cvalue, iosb->u.Status, iosb->Information );
1968 *apc = ws2_async_accept_apc;
1969 return status;
1972 /***********************************************************************
1973 * WS2_async_accept (INTERNAL)
1975 * This is the function called to satisfy the AcceptEx callback
1977 static NTSTATUS WS2_async_accept( void *arg, IO_STATUS_BLOCK *iosb, NTSTATUS status, void **apc )
1979 struct ws2_accept_async *wsa = arg;
1980 int len;
1981 char *addr;
1983 TRACE("status: 0x%x listen: %p, accept: %p\n", status, wsa->listen_socket, wsa->accept_socket);
1985 if (status == STATUS_ALERTED)
1987 SERVER_START_REQ( accept_into_socket )
1989 req->lhandle = wine_server_obj_handle( wsa->listen_socket );
1990 req->ahandle = wine_server_obj_handle( wsa->accept_socket );
1991 status = wine_server_call( req );
1993 SERVER_END_REQ;
1995 if (status == STATUS_CANT_WAIT)
1996 return STATUS_PENDING;
1998 if (status == STATUS_INVALID_HANDLE)
2000 FIXME("AcceptEx accepting socket closed but request was not cancelled\n");
2001 status = STATUS_CANCELLED;
2004 else if (status == STATUS_HANDLES_CLOSED)
2005 status = STATUS_CANCELLED; /* strange windows behavior */
2007 if (status != STATUS_SUCCESS)
2008 goto finish;
2010 /* WS2 Spec says size param is extra 16 bytes long...what do we put in it? */
2011 addr = ((char *)wsa->buf) + wsa->data_len;
2012 len = wsa->local_len - sizeof(int);
2013 WS_getsockname(HANDLE2SOCKET(wsa->accept_socket),
2014 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
2015 *(int *)addr = len;
2017 addr += wsa->local_len;
2018 len = wsa->remote_len - sizeof(int);
2019 WS_getpeername(HANDLE2SOCKET(wsa->accept_socket),
2020 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
2021 *(int *)addr = len;
2023 if (!wsa->read)
2024 goto finish;
2026 SERVER_START_REQ( register_async )
2028 req->type = ASYNC_TYPE_READ;
2029 req->async.handle = wine_server_obj_handle( wsa->accept_socket );
2030 req->async.callback = wine_server_client_ptr( WS2_async_accept_recv );
2031 req->async.iosb = wine_server_client_ptr( iosb );
2032 req->async.arg = wine_server_client_ptr( wsa );
2033 status = wine_server_call( req );
2035 SERVER_END_REQ;
2037 if (status != STATUS_PENDING)
2038 goto finish;
2040 /* The APC has finished but no completion should be sent for the operation yet, additional processing
2041 * needs to be performed by WS2_async_accept_recv() first. */
2042 return STATUS_MORE_PROCESSING_REQUIRED;
2044 finish:
2045 iosb->u.Status = status;
2046 iosb->Information = 0;
2048 if (wsa->user_overlapped->hEvent)
2049 SetEvent(wsa->user_overlapped->hEvent);
2051 *apc = ws2_async_accept_apc;
2052 return status;
2055 /***********************************************************************
2056 * WS2_send (INTERNAL)
2058 * Workhorse for both synchronous and asynchronous send() operations.
2060 static int WS2_send( int fd, struct ws2_async *wsa )
2062 struct msghdr hdr;
2063 union generic_unix_sockaddr unix_addr;
2064 int n, ret;
2066 hdr.msg_name = NULL;
2067 hdr.msg_namelen = 0;
2069 if (wsa->addr)
2071 hdr.msg_name = &unix_addr;
2072 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
2073 if ( !hdr.msg_namelen )
2075 errno = EFAULT;
2076 return -1;
2079 #if defined(HAS_IPX) && defined(SOL_IPX)
2080 if(wsa->addr->sa_family == WS_AF_IPX)
2082 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
2083 int val=0;
2084 socklen_t len = sizeof(int);
2086 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
2087 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
2088 * the packet type and then we can retrieve it using getsockopt. After that we can set the
2089 * ipx type in the sockaddr_opx structure with the stored value.
2091 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
2092 uipx->sipx_type = val;
2094 #endif
2097 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
2098 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
2099 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2100 hdr.msg_accrights = NULL;
2101 hdr.msg_accrightslen = 0;
2102 #else
2103 hdr.msg_control = NULL;
2104 hdr.msg_controllen = 0;
2105 hdr.msg_flags = 0;
2106 #endif
2108 ret = sendmsg(fd, &hdr, wsa->flags);
2109 if (ret >= 0)
2111 n = ret;
2112 while (wsa->first_iovec < wsa->n_iovecs && wsa->iovec[wsa->first_iovec].iov_len <= n)
2113 n -= wsa->iovec[wsa->first_iovec++].iov_len;
2114 if (wsa->first_iovec < wsa->n_iovecs)
2116 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
2117 wsa->iovec[wsa->first_iovec].iov_len -= n;
2120 return ret;
2123 /***********************************************************************
2124 * WS2_async_send (INTERNAL)
2126 * Handler for overlapped send() operations.
2128 static NTSTATUS WS2_async_send(void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
2130 ws2_async* wsa = user;
2131 int result = 0, fd;
2133 switch (status)
2135 case STATUS_ALERTED:
2136 if ( wsa->n_iovecs <= wsa->first_iovec )
2138 /* Nothing to do */
2139 status = STATUS_SUCCESS;
2140 break;
2142 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
2143 break;
2145 /* check to see if the data is ready (non-blocking) */
2146 result = WS2_send( fd, wsa );
2147 wine_server_release_fd( wsa->hSocket, fd );
2149 if (result >= 0)
2151 if (wsa->first_iovec < wsa->n_iovecs)
2152 status = STATUS_PENDING;
2153 else
2154 status = STATUS_SUCCESS;
2156 iosb->Information += result;
2158 else if (errno == EINTR || errno == EAGAIN)
2160 status = STATUS_PENDING;
2162 else
2164 status = wsaErrStatus();
2166 break;
2168 if (status != STATUS_PENDING)
2170 iosb->u.Status = status;
2171 *apc = ws2_async_apc;
2173 return status;
2176 /***********************************************************************
2177 * WS2_async_shutdown (INTERNAL)
2179 * Handler for shutdown() operations on overlapped sockets.
2181 static NTSTATUS WS2_async_shutdown( void* user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc )
2183 ws2_async* wsa = user;
2184 int fd, err = 1;
2186 switch (status)
2188 case STATUS_ALERTED:
2189 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
2190 break;
2192 switch ( wsa->type )
2194 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
2195 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
2197 status = err ? wsaErrStatus() : STATUS_SUCCESS;
2198 wine_server_release_fd( wsa->hSocket, fd );
2199 break;
2201 iosb->u.Status = status;
2202 iosb->Information = 0;
2203 *apc = ws2_async_apc;
2204 return status;
2207 /***********************************************************************
2208 * WS2_register_async_shutdown (INTERNAL)
2210 * Helper function for WS_shutdown() on overlapped sockets.
2212 static int WS2_register_async_shutdown( SOCKET s, int type )
2214 struct ws2_async *wsa;
2215 NTSTATUS status;
2217 TRACE("s %ld type %d\n", s, type);
2219 wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( struct ws2_async, iovec[1] ));
2220 if ( !wsa )
2221 return WSAEFAULT;
2223 wsa->hSocket = SOCKET2HANDLE(s);
2224 wsa->type = type;
2225 wsa->completion_func = NULL;
2227 SERVER_START_REQ( register_async )
2229 req->type = type;
2230 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2231 req->async.callback = wine_server_client_ptr( WS2_async_shutdown );
2232 req->async.iosb = wine_server_client_ptr( &wsa->local_iosb );
2233 req->async.arg = wine_server_client_ptr( wsa );
2234 req->async.cvalue = 0;
2235 status = wine_server_call( req );
2237 SERVER_END_REQ;
2239 if (status != STATUS_PENDING)
2241 HeapFree( GetProcessHeap(), 0, wsa );
2242 return NtStatusToWSAError( status );
2244 return 0;
2247 /***********************************************************************
2248 * accept (WS2_32.1)
2250 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr,
2251 int *addrlen32)
2253 NTSTATUS status;
2254 SOCKET as;
2255 BOOL is_blocking;
2257 TRACE("socket %04lx\n", s );
2258 status = _is_blocking(s, &is_blocking);
2259 if (status)
2261 set_error(status);
2262 return INVALID_SOCKET;
2265 do {
2266 /* try accepting first (if there is a deferred connection) */
2267 SERVER_START_REQ( accept_socket )
2269 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
2270 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
2271 req->attributes = OBJ_INHERIT;
2272 status = wine_server_call( req );
2273 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
2275 SERVER_END_REQ;
2276 if (!status)
2278 if (addr) WS_getpeername(as, addr, addrlen32);
2279 return as;
2281 if (is_blocking && status == STATUS_CANT_WAIT)
2283 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2284 /* block here */
2285 do_block(fd, POLLIN, -1);
2286 _sync_sock_state(s); /* let wineserver notice connection */
2287 release_sock_fd( s, fd );
2289 } while (is_blocking && status == STATUS_CANT_WAIT);
2291 set_error(status);
2292 return INVALID_SOCKET;
2295 /***********************************************************************
2296 * AcceptEx
2298 static BOOL WINAPI WS2_AcceptEx(SOCKET listener, SOCKET acceptor, PVOID dest, DWORD dest_len,
2299 DWORD local_addr_len, DWORD rem_addr_len, LPDWORD received,
2300 LPOVERLAPPED overlapped)
2302 DWORD status;
2303 struct ws2_accept_async *wsa;
2304 int fd;
2305 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
2307 TRACE("(%lx, %lx, %p, %d, %d, %d, %p, %p)\n", listener, acceptor, dest, dest_len, local_addr_len,
2308 rem_addr_len, received, overlapped);
2310 if (!dest)
2312 SetLastError(WSAEINVAL);
2313 return FALSE;
2316 if (!overlapped)
2318 SetLastError(WSA_INVALID_PARAMETER);
2319 return FALSE;
2322 if ((local_addr_len < sizeof(struct sockaddr_in) + 16)
2323 || (rem_addr_len < sizeof(struct sockaddr_in) + 16))
2325 SetLastError(WSAEINVAL);
2326 return FALSE;
2329 fd = get_sock_fd( listener, FILE_READ_DATA, NULL );
2330 if (fd == -1)
2332 SetLastError(WSAENOTSOCK);
2333 return FALSE;
2335 release_sock_fd( listener, fd );
2337 fd = get_sock_fd( acceptor, FILE_READ_DATA, NULL );
2338 if (fd == -1)
2340 SetLastError(WSAEINVAL);
2341 return FALSE;
2343 release_sock_fd( acceptor, fd );
2345 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
2346 if(!wsa)
2348 SetLastError(WSAEFAULT);
2349 return FALSE;
2352 wsa->listen_socket = SOCKET2HANDLE(listener);
2353 wsa->accept_socket = SOCKET2HANDLE(acceptor);
2354 wsa->user_overlapped = overlapped;
2355 wsa->cvalue = cvalue;
2356 wsa->buf = dest;
2357 wsa->data_len = dest_len;
2358 wsa->local_len = local_addr_len;
2359 wsa->remote_len = rem_addr_len;
2360 wsa->read = NULL;
2362 if (wsa->data_len)
2364 /* set up a read request if we need it */
2365 wsa->read = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[1]) );
2366 if (!wsa->read)
2368 HeapFree( GetProcessHeap(), 0, wsa );
2369 SetLastError(WSAEFAULT);
2370 return FALSE;
2373 wsa->read->hSocket = wsa->accept_socket;
2374 wsa->read->flags = 0;
2375 wsa->read->lpFlags = &wsa->read->flags;
2376 wsa->read->addr = NULL;
2377 wsa->read->addrlen.ptr = NULL;
2378 wsa->read->control = NULL;
2379 wsa->read->n_iovecs = 1;
2380 wsa->read->first_iovec = 0;
2381 wsa->read->iovec[0].iov_base = wsa->buf;
2382 wsa->read->iovec[0].iov_len = wsa->data_len;
2385 SERVER_START_REQ( register_async )
2387 req->type = ASYNC_TYPE_READ;
2388 req->async.handle = wine_server_obj_handle( SOCKET2HANDLE(listener) );
2389 req->async.callback = wine_server_client_ptr( WS2_async_accept );
2390 req->async.iosb = wine_server_client_ptr( overlapped );
2391 req->async.arg = wine_server_client_ptr( wsa );
2392 req->async.cvalue = cvalue;
2393 /* We don't set event since we may also have to read */
2394 status = wine_server_call( req );
2396 SERVER_END_REQ;
2398 if(status != STATUS_PENDING)
2400 HeapFree( GetProcessHeap(), 0, wsa->read );
2401 HeapFree( GetProcessHeap(), 0, wsa );
2404 SetLastError( NtStatusToWSAError(status) );
2405 return FALSE;
2408 /***********************************************************************
2409 * GetAcceptExSockaddrs
2411 static void WINAPI WS2_GetAcceptExSockaddrs(PVOID buffer, DWORD data_size, DWORD local_size, DWORD remote_size,
2412 struct WS_sockaddr **local_addr, LPINT local_addr_len,
2413 struct WS_sockaddr **remote_addr, LPINT remote_addr_len)
2415 char *cbuf = buffer;
2416 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer, data_size, local_size, remote_size, local_addr,
2417 local_addr_len, remote_addr, remote_addr_len );
2418 cbuf += data_size;
2420 *local_addr_len = *(int *) cbuf;
2421 *local_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2423 cbuf += local_size;
2425 *remote_addr_len = *(int *) cbuf;
2426 *remote_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2429 /***********************************************************************
2430 * WSASendMsg
2432 int WINAPI WSASendMsg( SOCKET s, LPWSAMSG msg, DWORD dwFlags, LPDWORD lpNumberOfBytesSent,
2433 LPWSAOVERLAPPED lpOverlapped,
2434 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
2436 if (!msg)
2438 SetLastError( WSAEFAULT );
2439 return SOCKET_ERROR;
2442 return WS2_sendto( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesSent,
2443 dwFlags, msg->name, msg->namelen,
2444 lpOverlapped, lpCompletionRoutine );
2447 /***********************************************************************
2448 * WSARecvMsg
2450 * Perform a receive operation that is capable of returning message
2451 * control headers. It is important to note that the WSAMSG parameter
2452 * must remain valid throughout the operation, even when an overlapped
2453 * receive is performed.
2455 static int WINAPI WS2_WSARecvMsg( SOCKET s, LPWSAMSG msg, LPDWORD lpNumberOfBytesRecvd,
2456 LPWSAOVERLAPPED lpOverlapped,
2457 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2459 if (!msg)
2461 SetLastError( WSAEFAULT );
2462 return SOCKET_ERROR;
2465 return WS2_recv_base( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesRecvd,
2466 &msg->dwFlags, msg->name, &msg->namelen,
2467 lpOverlapped, lpCompletionRoutine, &msg->Control );
2470 /***********************************************************************
2471 * interface_bind (INTERNAL)
2473 * Take bind() calls on any name corresponding to a local network adapter and restrict the given socket to
2474 * operating only on the specified interface. This restriction consists of two components:
2475 * 1) An outgoing packet restriction suggesting the egress interface for all packets.
2476 * 2) An incoming packet restriction dropping packets not meant for the interface.
2477 * If the function succeeds in placing these restrictions (returns TRUE) then the name for the bind() may
2478 * safely be changed to INADDR_ANY, permitting the transmission and receipt of broadcast packets on the
2479 * socket. This behavior is only relevant to UDP sockets and is needed for applications that expect to be able
2480 * to receive broadcast packets on a socket that is bound to a specific network interface.
2482 static BOOL interface_bind( SOCKET s, int fd, struct sockaddr *addr )
2484 struct sockaddr_in *in_sock = (struct sockaddr_in *) addr;
2485 unsigned int sock_type = 0;
2486 socklen_t optlen = sizeof(sock_type);
2487 in_addr_t bind_addr = in_sock->sin_addr.s_addr;
2488 PIP_ADAPTER_INFO adapters = NULL, adapter;
2489 BOOL ret = FALSE;
2490 DWORD adap_size;
2491 int enable = 1;
2493 if (bind_addr == htonl(WS_INADDR_ANY) || bind_addr == htonl(WS_INADDR_LOOPBACK))
2494 return FALSE; /* Not binding to a network adapter, special interface binding unnecessary. */
2495 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &sock_type, &optlen) == -1 || sock_type != SOCK_DGRAM)
2496 return FALSE; /* Special interface binding is only necessary for UDP datagrams. */
2497 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
2498 goto cleanup;
2499 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
2500 if (adapters == NULL || GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
2501 goto cleanup;
2502 /* Search the IPv4 adapter list for the appropriate binding interface */
2503 for (adapter = adapters; adapter != NULL; adapter = adapter->Next)
2505 in_addr_t adapter_addr = (in_addr_t) inet_addr(adapter->IpAddressList.IpAddress.String);
2507 if (bind_addr == adapter_addr)
2509 #if defined(IP_BOUND_IF)
2510 /* IP_BOUND_IF sets both the incoming and outgoing restriction at once */
2511 if (setsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &adapter->Index, sizeof(adapter->Index)) != 0)
2512 goto cleanup;
2513 ret = TRUE;
2514 #elif defined(LINUX_BOUND_IF)
2515 in_addr_t ifindex = (in_addr_t) htonl(adapter->Index);
2516 struct interface_filter specific_interface_filter;
2517 struct sock_fprog filter_prog;
2519 if (setsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex, sizeof(ifindex)) != 0)
2520 goto cleanup; /* Failed to suggest egress interface */
2521 specific_interface_filter = generic_interface_filter;
2522 specific_interface_filter.iface_rule.k = adapter->Index;
2523 specific_interface_filter.ip_rule.k = htonl(adapter_addr);
2524 filter_prog.len = sizeof(generic_interface_filter)/sizeof(struct sock_filter);
2525 filter_prog.filter = (struct sock_filter *) &specific_interface_filter;
2526 if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog, sizeof(filter_prog)) != 0)
2527 goto cleanup; /* Failed to specify incoming packet filter */
2528 ret = TRUE;
2529 #else
2530 FIXME("Broadcast packets on interface-bound sockets are not currently supported on this platform, "
2531 "receiving broadcast packets will not work on socket %04lx.\n", s);
2532 #endif
2533 break;
2536 /* Will soon be switching to INADDR_ANY: permit address reuse */
2537 if (ret && setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) == 0)
2538 TRACE("Socket %04lx bound to interface index %d\n", s, adapter->Index);
2539 else
2540 ret = FALSE;
2542 cleanup:
2543 if(!ret)
2544 ERR("Failed to bind to interface, receiving broadcast packets will not work on socket %04lx.\n", s);
2545 HeapFree(GetProcessHeap(), 0, adapters);
2546 return ret;
2549 /***********************************************************************
2550 * bind (WS2_32.2)
2552 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
2554 int fd = get_sock_fd( s, 0, NULL );
2555 int res = SOCKET_ERROR;
2557 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2559 if (fd != -1)
2561 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
2563 SetLastError(WSAEAFNOSUPPORT);
2565 else
2567 union generic_unix_sockaddr uaddr;
2568 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2569 if (!uaddrlen)
2571 SetLastError(WSAEFAULT);
2573 else
2575 #ifdef IPV6_V6ONLY
2576 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
2577 if (name->sa_family == WS_AF_INET6 &&
2578 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
2580 int enable = 1;
2581 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
2583 release_sock_fd( s, fd );
2584 SetLastError(WSAEAFNOSUPPORT);
2585 return SOCKET_ERROR;
2588 #endif
2589 if (name->sa_family == WS_AF_INET)
2591 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2592 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2594 /* Trying to bind to the default host interface, using
2595 * INADDR_ANY instead*/
2596 WARN("Trying to bind to magic IP address, using "
2597 "INADDR_ANY instead.\n");
2598 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
2600 else if (interface_bind(s, fd, &uaddr.addr))
2601 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
2603 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
2605 int loc_errno = errno;
2606 WARN("\tfailure - errno = %i\n", errno);
2607 errno = loc_errno;
2608 switch (errno)
2610 case EBADF:
2611 SetLastError(WSAENOTSOCK);
2612 break;
2613 case EADDRNOTAVAIL:
2614 SetLastError(WSAEINVAL);
2615 break;
2616 default:
2617 SetLastError(wsaErrno());
2618 break;
2621 else
2623 res=0; /* success */
2627 release_sock_fd( s, fd );
2629 return res;
2632 /***********************************************************************
2633 * closesocket (WS2_32.3)
2635 int WINAPI WS_closesocket(SOCKET s)
2637 TRACE("socket %04lx\n", s);
2638 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
2639 return SOCKET_ERROR;
2642 static int do_connect(int fd, const struct WS_sockaddr* name, int namelen)
2644 union generic_unix_sockaddr uaddr;
2645 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2647 if (!uaddrlen)
2648 return WSAEFAULT;
2650 if (name->sa_family == WS_AF_INET)
2652 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2653 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2655 /* Trying to connect to magic replace-loopback address,
2656 * assuming we really want to connect to localhost */
2657 TRACE("Trying to connect to magic IP address, using "
2658 "INADDR_LOOPBACK instead.\n");
2659 in4->sin_addr.s_addr = htonl(WS_INADDR_LOOPBACK);
2663 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
2664 return 0;
2666 return wsaErrno();
2669 /***********************************************************************
2670 * connect (WS2_32.4)
2672 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
2674 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2676 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2678 if (fd != -1)
2680 NTSTATUS status;
2681 BOOL is_blocking;
2682 int ret = do_connect(fd, name, namelen);
2683 if (ret == 0)
2684 goto connect_success;
2686 if (ret == WSAEINPROGRESS)
2688 /* tell wineserver that a connection is in progress */
2689 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2690 FD_CONNECT,
2691 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2692 status = _is_blocking( s, &is_blocking );
2693 if (status)
2695 release_sock_fd( s, fd );
2696 set_error( status );
2697 return SOCKET_ERROR;
2699 if (is_blocking)
2701 int result;
2702 /* block here */
2703 do_block(fd, POLLIN | POLLOUT, -1);
2704 _sync_sock_state(s); /* let wineserver notice connection */
2705 /* retrieve any error codes from it */
2706 result = _get_sock_error(s, FD_CONNECT_BIT);
2707 if (result)
2708 SetLastError(NtStatusToWSAError(result));
2709 else
2711 goto connect_success;
2714 else
2716 SetLastError(WSAEWOULDBLOCK);
2719 else
2721 SetLastError(ret);
2723 release_sock_fd( s, fd );
2725 return SOCKET_ERROR;
2727 connect_success:
2728 release_sock_fd( s, fd );
2729 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2730 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2731 FD_CONNECT|FD_WINE_LISTENING);
2732 return 0;
2735 /***********************************************************************
2736 * WSAConnect (WS2_32.30)
2738 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
2739 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
2740 LPQOS lpSQOS, LPQOS lpGQOS )
2742 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
2743 FIXME("unsupported parameters!\n");
2744 return WS_connect( s, name, namelen );
2747 /***********************************************************************
2748 * ConnectEx
2750 static BOOL WINAPI WS2_ConnectEx(SOCKET s, const struct WS_sockaddr* name, int namelen,
2751 PVOID sendBuf, DWORD sendBufLen, LPDWORD sent, LPOVERLAPPED ov)
2753 int fd, ret, status;
2754 union generic_unix_sockaddr uaddr;
2755 socklen_t uaddrlen = sizeof(uaddr);
2757 if (!ov)
2759 SetLastError( ERROR_INVALID_PARAMETER );
2760 return FALSE;
2763 fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2764 if (fd == -1)
2766 SetLastError( WSAENOTSOCK );
2767 return FALSE;
2770 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
2771 s, name, debugstr_sockaddr(name), namelen, sendBuf, sendBufLen, ov);
2773 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
2775 SetLastError(wsaErrno());
2776 return FALSE;
2778 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
2780 SetLastError(WSAEINVAL);
2781 return FALSE;
2784 ret = do_connect(fd, name, namelen);
2785 if (ret == 0)
2787 WSABUF wsabuf;
2789 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2790 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2791 FD_CONNECT|FD_WINE_LISTENING);
2793 wsabuf.len = sendBufLen;
2794 wsabuf.buf = (char*) sendBuf;
2796 /* WSASend takes care of completion if need be */
2797 if (WSASend(s, &wsabuf, sendBuf ? 1 : 0, sent, 0, ov, NULL) != SOCKET_ERROR)
2798 goto connection_success;
2800 else if (ret == WSAEINPROGRESS)
2802 struct ws2_async *wsa;
2803 ULONG_PTR cvalue = (((ULONG_PTR)ov->hEvent & 1) == 0) ? (ULONG_PTR)ov : 0;
2805 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2806 FD_CONNECT,
2807 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2809 /* Indirectly call WSASend */
2810 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( struct ws2_async, iovec[1] ))))
2812 SetLastError(WSAEFAULT);
2814 else
2816 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)ov;
2817 iosb->u.Status = STATUS_PENDING;
2818 iosb->Information = 0;
2820 wsa->hSocket = SOCKET2HANDLE(s);
2821 wsa->addr = NULL;
2822 wsa->addrlen.val = 0;
2823 wsa->flags = 0;
2824 wsa->lpFlags = &wsa->flags;
2825 wsa->control = NULL;
2826 wsa->n_iovecs = sendBuf ? 1 : 0;
2827 wsa->first_iovec = 0;
2828 wsa->completion_func = NULL;
2829 wsa->iovec[0].iov_base = sendBuf;
2830 wsa->iovec[0].iov_len = sendBufLen;
2832 SERVER_START_REQ( register_async )
2834 req->type = ASYNC_TYPE_WRITE;
2835 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2836 req->async.callback = wine_server_client_ptr( WS2_async_send );
2837 req->async.iosb = wine_server_client_ptr( iosb );
2838 req->async.arg = wine_server_client_ptr( wsa );
2839 req->async.event = wine_server_obj_handle( ov->hEvent );
2840 req->async.cvalue = cvalue;
2841 status = wine_server_call( req );
2843 SERVER_END_REQ;
2845 if (status != STATUS_PENDING) HeapFree(GetProcessHeap(), 0, wsa);
2847 /* If the connect already failed */
2848 if (status == STATUS_PIPE_DISCONNECTED)
2849 status = _get_sock_error(s, FD_CONNECT_BIT);
2850 SetLastError( NtStatusToWSAError(status) );
2853 else
2855 SetLastError(ret);
2858 release_sock_fd( s, fd );
2859 return FALSE;
2861 connection_success:
2862 release_sock_fd( s, fd );
2863 return TRUE;
2867 /***********************************************************************
2868 * getpeername (WS2_32.5)
2870 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
2872 int fd;
2873 int res;
2875 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
2877 fd = get_sock_fd( s, 0, NULL );
2878 res = SOCKET_ERROR;
2880 if (fd != -1)
2882 union generic_unix_sockaddr uaddr;
2883 socklen_t uaddrlen = sizeof(uaddr);
2885 if (getpeername(fd, &uaddr.addr, &uaddrlen) == 0)
2887 if (!name || !namelen)
2888 SetLastError(WSAEFAULT);
2889 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
2890 /* The buffer was too small */
2891 SetLastError(WSAEFAULT);
2892 else
2893 res = 0;
2895 else
2896 SetLastError(wsaErrno());
2897 release_sock_fd( s, fd );
2899 return res;
2902 /***********************************************************************
2903 * getsockname (WS2_32.6)
2905 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
2907 int fd;
2908 int res;
2910 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
2912 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
2913 if( (name == NULL) || (namelen == NULL) )
2915 SetLastError( WSAEFAULT );
2916 return SOCKET_ERROR;
2919 fd = get_sock_fd( s, 0, NULL );
2920 res = SOCKET_ERROR;
2922 if (fd != -1)
2924 union generic_unix_sockaddr uaddr;
2925 socklen_t uaddrlen = sizeof(uaddr);
2927 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
2929 SetLastError(wsaErrno());
2931 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
2933 SetLastError(WSAEINVAL);
2935 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
2937 /* The buffer was too small */
2938 SetLastError(WSAEFAULT);
2940 else
2942 res=0;
2944 release_sock_fd( s, fd );
2946 return res;
2949 /***********************************************************************
2950 * getsockopt (WS2_32.7)
2952 INT WINAPI WS_getsockopt(SOCKET s, INT level,
2953 INT optname, char *optval, INT *optlen)
2955 int fd;
2956 INT ret = 0;
2958 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
2959 s, level, optname, optval, optlen ? *optlen : 0);
2961 switch(level)
2963 case WS_SOL_SOCKET:
2965 switch(optname)
2967 /* Handle common cases. The special cases are below, sorted
2968 * alphabetically */
2969 case WS_SO_BROADCAST:
2970 case WS_SO_DEBUG:
2971 case WS_SO_ERROR:
2972 case WS_SO_KEEPALIVE:
2973 case WS_SO_OOBINLINE:
2974 case WS_SO_RCVBUF:
2975 case WS_SO_REUSEADDR:
2976 case WS_SO_SNDBUF:
2977 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2978 return SOCKET_ERROR;
2979 convert_sockopt(&level, &optname);
2980 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
2982 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2983 ret = SOCKET_ERROR;
2985 release_sock_fd( s, fd );
2986 return ret;
2987 case WS_SO_ACCEPTCONN:
2988 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2989 return SOCKET_ERROR;
2990 if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, optval, (socklen_t *)optlen) != 0 )
2992 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2993 ret = SOCKET_ERROR;
2995 else
2997 /* BSD returns != 0 while Windows return exact == 1 */
2998 if (*(int *)optval) *(int *)optval = 1;
3000 release_sock_fd( s, fd );
3001 return ret;
3002 case WS_SO_DONTLINGER:
3004 struct linger lingval;
3005 socklen_t len = sizeof(struct linger);
3007 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
3009 SetLastError(WSAEFAULT);
3010 return SOCKET_ERROR;
3012 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3013 return SOCKET_ERROR;
3015 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
3017 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3018 ret = SOCKET_ERROR;
3020 else
3022 *(BOOL *)optval = !lingval.l_onoff;
3023 *optlen = sizeof(BOOL);
3026 release_sock_fd( s, fd );
3027 return ret;
3030 case WS_SO_CONNECT_TIME:
3032 static int pretendtime = 0;
3033 struct WS_sockaddr addr;
3034 int len = sizeof(addr);
3036 if (!optlen || *optlen < sizeof(DWORD) || !optval)
3038 SetLastError(WSAEFAULT);
3039 return SOCKET_ERROR;
3041 if (WS_getpeername(s, &addr, &len) == SOCKET_ERROR)
3042 *(DWORD *)optval = ~0u;
3043 else
3045 if (!pretendtime) FIXME("WS_SO_CONNECT_TIME - faking results\n");
3046 *(DWORD *)optval = pretendtime++;
3048 *optlen = sizeof(DWORD);
3049 return ret;
3051 /* As mentioned in setsockopt, Windows ignores this, so we
3052 * always return true here */
3053 case WS_SO_DONTROUTE:
3054 if (!optlen || *optlen < sizeof(BOOL) || !optval)
3056 SetLastError(WSAEFAULT);
3057 return SOCKET_ERROR;
3059 *(BOOL *)optval = TRUE;
3060 *optlen = sizeof(BOOL);
3061 return 0;
3063 case WS_SO_LINGER:
3065 struct linger lingval;
3066 int so_type;
3067 socklen_t len = sizeof(struct linger), slen = sizeof(int);
3069 /* struct linger and LINGER have different sizes */
3070 if (!optlen || *optlen < sizeof(LINGER) || !optval)
3072 SetLastError(WSAEFAULT);
3073 return SOCKET_ERROR;
3075 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3076 return SOCKET_ERROR;
3078 if ((getsockopt(fd, SOL_SOCKET, SO_TYPE, &so_type, &slen) == 0 && so_type == SOCK_DGRAM))
3080 SetLastError(WSAENOPROTOOPT);
3081 ret = SOCKET_ERROR;
3083 else if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0)
3085 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3086 ret = SOCKET_ERROR;
3088 else
3090 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
3091 ((LINGER *)optval)->l_linger = lingval.l_linger;
3092 *optlen = sizeof(struct linger);
3095 release_sock_fd( s, fd );
3096 return ret;
3099 case WS_SO_MAX_MSG_SIZE:
3100 if (!optlen || *optlen < sizeof(int) || !optval)
3102 SetLastError(WSAEFAULT);
3103 return SOCKET_ERROR;
3105 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
3106 *(int *)optval = 65507;
3107 *optlen = sizeof(int);
3108 return 0;
3110 /* SO_OPENTYPE does not require a valid socket handle. */
3111 case WS_SO_OPENTYPE:
3112 if (!optlen || *optlen < sizeof(int) || !optval)
3114 SetLastError(WSAEFAULT);
3115 return SOCKET_ERROR;
3117 *(int *)optval = get_per_thread_data()->opentype;
3118 *optlen = sizeof(int);
3119 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
3120 return 0;
3121 case WS_SO_PROTOCOL_INFOA:
3122 case WS_SO_PROTOCOL_INFOW:
3124 int size;
3125 WSAPROTOCOL_INFOW infow;
3127 ret = ws_protocol_info(s, optname == WS_SO_PROTOCOL_INFOW, &infow, &size);
3128 if (ret)
3130 if (!optlen || !optval || *optlen < size)
3132 if(optlen) *optlen = size;
3133 ret = 0;
3134 SetLastError(WSAEFAULT);
3136 else
3137 memcpy(optval, &infow, size);
3139 return ret ? 0 : SOCKET_ERROR;
3141 #ifdef SO_RCVTIMEO
3142 case WS_SO_RCVTIMEO:
3143 #endif
3144 #ifdef SO_SNDTIMEO
3145 case WS_SO_SNDTIMEO:
3146 #endif
3147 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
3149 struct timeval tv;
3150 socklen_t len = sizeof(struct timeval);
3152 if (!optlen || *optlen < sizeof(int)|| !optval)
3154 SetLastError(WSAEFAULT);
3155 return SOCKET_ERROR;
3157 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3158 return SOCKET_ERROR;
3160 convert_sockopt(&level, &optname);
3161 if (getsockopt(fd, level, optname, &tv, &len) != 0 )
3163 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3164 ret = SOCKET_ERROR;
3166 else
3168 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
3169 *optlen = sizeof(int);
3172 release_sock_fd( s, fd );
3173 return ret;
3175 #endif
3176 case WS_SO_TYPE:
3178 if (!optlen || *optlen < sizeof(int) || !optval)
3180 SetLastError(WSAEFAULT);
3181 return SOCKET_ERROR;
3183 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3184 return SOCKET_ERROR;
3186 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, optval, (socklen_t *)optlen) != 0 )
3188 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3189 ret = SOCKET_ERROR;
3191 else
3192 (*(int *)optval) = convert_socktype_u2w(*(int *)optval);
3194 release_sock_fd( s, fd );
3195 return ret;
3197 default:
3198 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
3199 SetLastError(WSAENOPROTOOPT);
3200 return SOCKET_ERROR;
3201 } /* end switch(optname) */
3202 }/* end case WS_SOL_SOCKET */
3203 #ifdef HAS_IPX
3204 case NSPROTO_IPX:
3206 struct WS_sockaddr_ipx addr;
3207 IPX_ADDRESS_DATA *data;
3208 int namelen;
3209 switch(optname)
3211 case IPX_PTYPE:
3212 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3213 #ifdef SOL_IPX
3214 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (socklen_t *)optlen) == -1)
3216 ret = SOCKET_ERROR;
3218 #else
3220 struct ipx val;
3221 socklen_t len=sizeof(struct ipx);
3222 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
3223 ret = SOCKET_ERROR;
3224 else
3225 *optval = (int)val.ipx_pt;
3227 #endif
3228 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
3229 release_sock_fd( s, fd );
3230 return ret;
3232 case IPX_ADDRESS:
3234 * On a Win2000 system with one network card there are usually
3235 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
3236 * Using this call you can then retrieve info about this all.
3237 * In case of Linux it is a bit different. Usually you have
3238 * only "one" device active and further it is not possible to
3239 * query things like the linkspeed.
3241 FIXME("IPX_ADDRESS\n");
3242 namelen = sizeof(struct WS_sockaddr_ipx);
3243 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
3244 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
3246 data = (IPX_ADDRESS_DATA*)optval;
3247 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
3248 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
3249 data->adapternum = 0;
3250 data->wan = FALSE; /* We are not on a wan for now .. */
3251 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
3252 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
3253 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
3254 * note 1MB = 1000kB in this case */
3255 return 0;
3257 case IPX_MAX_ADAPTER_NUM:
3258 FIXME("IPX_MAX_ADAPTER_NUM\n");
3259 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
3260 return 0;
3262 default:
3263 FIXME("IPX optname:%x\n", optname);
3264 return SOCKET_ERROR;
3265 }/* end switch(optname) */
3266 } /* end case NSPROTO_IPX */
3267 #endif
3269 #ifdef HAS_IRDA
3270 case WS_SOL_IRLMP:
3271 switch(optname)
3273 case WS_IRLMP_ENUMDEVICES:
3275 static const int MAX_IRDA_DEVICES = 10;
3276 char buf[sizeof(struct irda_device_list) +
3277 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
3278 int res;
3279 socklen_t len = sizeof(buf);
3281 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3282 return SOCKET_ERROR;
3283 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
3284 if (res < 0)
3286 SetLastError(wsaErrno());
3287 return SOCKET_ERROR;
3289 else
3291 struct irda_device_list *src = (struct irda_device_list *)buf;
3292 DEVICELIST *dst = (DEVICELIST *)optval;
3293 INT needed = sizeof(DEVICELIST);
3294 unsigned int i;
3296 if (src->len > 0)
3297 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
3298 if (*optlen < needed)
3300 SetLastError(WSAEFAULT);
3301 return SOCKET_ERROR;
3303 *optlen = needed;
3304 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
3305 dst->numDevice = src->len;
3306 for (i = 0; i < src->len; i++)
3308 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
3309 src->dev[i].saddr, src->dev[i].daddr,
3310 src->dev[i].info, src->dev[i].hints[0],
3311 src->dev[i].hints[1]);
3312 memcpy( dst->Device[i].irdaDeviceID,
3313 &src->dev[i].daddr,
3314 sizeof(dst->Device[i].irdaDeviceID) ) ;
3315 memcpy( dst->Device[i].irdaDeviceName,
3316 src->dev[i].info,
3317 sizeof(dst->Device[i].irdaDeviceName) ) ;
3318 memcpy( &dst->Device[i].irdaDeviceHints1,
3319 &src->dev[i].hints[0],
3320 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
3321 memcpy( &dst->Device[i].irdaDeviceHints2,
3322 &src->dev[i].hints[1],
3323 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
3324 dst->Device[i].irdaCharSet = src->dev[i].charset;
3326 return 0;
3329 default:
3330 FIXME("IrDA optname:0x%x\n", optname);
3331 return SOCKET_ERROR;
3333 break; /* case WS_SOL_IRLMP */
3334 #endif
3336 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3337 case WS_IPPROTO_TCP:
3338 switch(optname)
3340 case WS_TCP_NODELAY:
3341 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3342 return SOCKET_ERROR;
3343 convert_sockopt(&level, &optname);
3344 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3346 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3347 ret = SOCKET_ERROR;
3349 release_sock_fd( s, fd );
3350 return ret;
3352 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
3353 return SOCKET_ERROR;
3355 case WS_IPPROTO_IP:
3356 switch(optname)
3358 case WS_IP_ADD_MEMBERSHIP:
3359 case WS_IP_DROP_MEMBERSHIP:
3360 #ifdef IP_HDRINCL
3361 case WS_IP_HDRINCL:
3362 #endif
3363 case WS_IP_MULTICAST_IF:
3364 case WS_IP_MULTICAST_LOOP:
3365 case WS_IP_MULTICAST_TTL:
3366 case WS_IP_OPTIONS:
3367 #ifdef IP_PKTINFO
3368 case WS_IP_PKTINFO:
3369 #endif
3370 case WS_IP_TOS:
3371 case WS_IP_TTL:
3372 #ifdef IP_UNICAST_IF
3373 case WS_IP_UNICAST_IF:
3374 #endif
3375 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3376 return SOCKET_ERROR;
3377 convert_sockopt(&level, &optname);
3378 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3380 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3381 ret = SOCKET_ERROR;
3383 release_sock_fd( s, fd );
3384 return ret;
3385 case WS_IP_DONTFRAGMENT:
3386 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
3387 *(BOOL*)optval = FALSE;
3388 return 0;
3390 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
3391 return SOCKET_ERROR;
3393 case WS_IPPROTO_IPV6:
3394 switch(optname)
3396 #ifdef IPV6_ADD_MEMBERSHIP
3397 case WS_IPV6_ADD_MEMBERSHIP:
3398 #endif
3399 #ifdef IPV6_DROP_MEMBERSHIP
3400 case WS_IPV6_DROP_MEMBERSHIP:
3401 #endif
3402 case WS_IPV6_MULTICAST_IF:
3403 case WS_IPV6_MULTICAST_HOPS:
3404 case WS_IPV6_MULTICAST_LOOP:
3405 case WS_IPV6_UNICAST_HOPS:
3406 case WS_IPV6_V6ONLY:
3407 #ifdef IPV6_UNICAST_IF
3408 case WS_IPV6_UNICAST_IF:
3409 #endif
3410 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3411 return SOCKET_ERROR;
3412 convert_sockopt(&level, &optname);
3413 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3415 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3416 ret = SOCKET_ERROR;
3418 release_sock_fd( s, fd );
3419 return ret;
3420 case WS_IPV6_DONTFRAG:
3421 FIXME("WS_IPV6_DONTFRAG is always false!\n");
3422 *(BOOL*)optval = FALSE;
3423 return 0;
3425 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
3426 return SOCKET_ERROR;
3428 default:
3429 WARN("Unknown level: 0x%08x\n", level);
3430 SetLastError(WSAEINVAL);
3431 return SOCKET_ERROR;
3432 } /* end switch(level) */
3435 /***********************************************************************
3436 * htonl (WS2_32.8)
3438 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
3440 return htonl(hostlong);
3444 /***********************************************************************
3445 * htons (WS2_32.9)
3447 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
3449 return htons(hostshort);
3452 /***********************************************************************
3453 * WSAHtonl (WS2_32.46)
3454 * From MSDN description of error codes, this function should also
3455 * check if WinSock has been initialized and the socket is a valid
3456 * socket. But why? This function only translates a host byte order
3457 * u_long into a network byte order u_long...
3459 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
3461 if (lpnetlong)
3463 *lpnetlong = htonl(hostlong);
3464 return 0;
3466 WSASetLastError(WSAEFAULT);
3467 return SOCKET_ERROR;
3470 /***********************************************************************
3471 * WSAHtons (WS2_32.47)
3472 * From MSDN description of error codes, this function should also
3473 * check if WinSock has been initialized and the socket is a valid
3474 * socket. But why? This function only translates a host byte order
3475 * u_short into a network byte order u_short...
3477 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
3480 if (lpnetshort)
3482 *lpnetshort = htons(hostshort);
3483 return 0;
3485 WSASetLastError(WSAEFAULT);
3486 return SOCKET_ERROR;
3490 /***********************************************************************
3491 * inet_addr (WS2_32.11)
3493 WS_u_long WINAPI WS_inet_addr(const char *cp)
3495 if (!cp) return INADDR_NONE;
3496 return inet_addr(cp);
3500 /***********************************************************************
3501 * ntohl (WS2_32.14)
3503 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
3505 return ntohl(netlong);
3509 /***********************************************************************
3510 * ntohs (WS2_32.15)
3512 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
3514 return ntohs(netshort);
3518 /***********************************************************************
3519 * inet_ntoa (WS2_32.12)
3521 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
3523 /* use "buffer for dummies" here because some applications have a
3524 * propensity to decode addresses in ws_hostent structure without
3525 * saving them first...
3527 static char dbuffer[16]; /* Yes, 16: 4*3 digits + 3 '.' + 1 '\0' */
3529 char* s = inet_ntoa(*((struct in_addr*)&in));
3530 if( s )
3532 strcpy(dbuffer, s);
3533 return dbuffer;
3535 SetLastError(wsaErrno());
3536 return NULL;
3539 static const char *debugstr_wsaioctl(DWORD ioctl)
3541 const char *buf_type, *family;
3543 switch(ioctl & 0x18000000)
3545 case WS_IOC_WS2:
3546 family = "IOC_WS2";
3547 break;
3548 case WS_IOC_PROTOCOL:
3549 family = "IOC_PROTOCOL";
3550 break;
3551 case WS_IOC_VENDOR:
3552 family = "IOC_VENDOR";
3553 break;
3554 default: /* WS_IOC_UNIX */
3556 BYTE size = (ioctl >> 16) & WS_IOCPARM_MASK;
3557 char x = (ioctl & 0xff00) >> 8;
3558 BYTE y = ioctl & 0xff;
3559 char args[14];
3561 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3563 case WS_IOC_VOID:
3564 buf_type = "_IO";
3565 sprintf(args, "%d, %d", x, y);
3566 break;
3567 case WS_IOC_IN:
3568 buf_type = "_IOW";
3569 sprintf(args, "'%c', %d, %d", x, y, size);
3570 break;
3571 case WS_IOC_OUT:
3572 buf_type = "_IOR";
3573 sprintf(args, "'%c', %d, %d", x, y, size);
3574 break;
3575 default:
3576 buf_type = "?";
3577 sprintf(args, "'%c', %d, %d", x, y, size);
3578 break;
3580 return wine_dbg_sprintf("%s(%s)", buf_type, args);
3584 /* We are different from WS_IOC_UNIX. */
3585 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3587 case WS_IOC_VOID:
3588 buf_type = "_WSAIO";
3589 break;
3590 case WS_IOC_INOUT:
3591 buf_type = "_WSAIORW";
3592 break;
3593 case WS_IOC_IN:
3594 buf_type = "_WSAIOW";
3595 break;
3596 case WS_IOC_OUT:
3597 buf_type = "_WSAIOR";
3598 break;
3599 default:
3600 buf_type = "?";
3601 break;
3604 return wine_dbg_sprintf("%s(%s, %d)", buf_type, family,
3605 (USHORT)(ioctl & 0xffff));
3608 /**********************************************************************
3609 * WSAIoctl (WS2_32.50)
3612 INT WINAPI WSAIoctl(SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size, LPVOID out_buff,
3613 DWORD out_size, LPDWORD ret_size, LPWSAOVERLAPPED overlapped,
3614 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
3616 int fd;
3617 DWORD status = 0, total = 0;
3619 TRACE("%ld, 0x%08x, %p, %d, %p, %d, %p, %p, %p\n",
3620 s, code, in_buff, in_size, out_buff, out_size, ret_size, overlapped, completion);
3622 switch (code)
3624 case WS_FIONBIO:
3625 if (in_size != sizeof(WS_u_long) || IS_INTRESOURCE(in_buff))
3627 WSASetLastError(WSAEFAULT);
3628 return SOCKET_ERROR;
3630 if (_get_sock_mask(s))
3632 /* AsyncSelect()'ed sockets are always nonblocking */
3633 if (!*(WS_u_long *)in_buff) status = WSAEINVAL;
3634 break;
3636 if (*(WS_u_long *)in_buff)
3637 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
3638 else
3639 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
3640 break;
3642 case WS_FIONREAD:
3644 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
3646 WSASetLastError(WSAEFAULT);
3647 return SOCKET_ERROR;
3649 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3650 if (ioctl(fd, FIONREAD, out_buff ) == -1)
3651 status = (errno == EBADF) ? WSAENOTSOCK : wsaErrno();
3652 release_sock_fd( s, fd );
3653 break;
3656 case WS_SIOCATMARK:
3658 unsigned int oob = 0, atmark = 0;
3659 socklen_t oobsize = sizeof(int);
3660 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
3662 WSASetLastError(WSAEFAULT);
3663 return SOCKET_ERROR;
3665 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3666 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
3667 if ((getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &oob, &oobsize ) == -1)
3668 || (!oob && ioctl(fd, SIOCATMARK, &atmark ) == -1))
3669 status = (errno == EBADF) ? WSAENOTSOCK : wsaErrno();
3670 else
3672 /* The SIOCATMARK value read from ioctl() is reversed
3673 * because BSD returns TRUE if it's in the OOB mark
3674 * while Windows returns TRUE if there are NO OOB bytes.
3676 (*(WS_u_long *) out_buff) = oob | !atmark;
3679 release_sock_fd( s, fd );
3680 break;
3683 case WS_FIOASYNC:
3684 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
3685 SetLastError(WSAEINVAL);
3686 return SOCKET_ERROR;
3688 case WS_SIO_GET_INTERFACE_LIST:
3690 INTERFACE_INFO* intArray = out_buff;
3691 DWORD size, numInt = 0, apiReturn;
3693 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
3695 if (!out_buff || !ret_size)
3697 WSASetLastError(WSAEFAULT);
3698 return SOCKET_ERROR;
3701 fd = get_sock_fd( s, 0, NULL );
3702 if (fd == -1) return SOCKET_ERROR;
3704 apiReturn = GetAdaptersInfo(NULL, &size);
3705 if (apiReturn == ERROR_BUFFER_OVERFLOW)
3707 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
3709 if (table)
3711 if (GetAdaptersInfo(table, &size) == NO_ERROR)
3713 PIP_ADAPTER_INFO ptr;
3715 for (ptr = table, numInt = 0; ptr; ptr = ptr->Next)
3717 unsigned int addr, mask, bcast;
3718 struct ifreq ifInfo;
3720 /* Skip interfaces without an IPv4 address. */
3721 if (ptr->IpAddressList.IpAddress.String[0] == '\0')
3722 continue;
3724 if ((numInt + 1)*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > out_size)
3726 WARN("Buffer too small = %u, out_size = %u\n", numInt + 1, out_size);
3727 status = WSAEFAULT;
3728 break;
3731 /* Socket Status Flags */
3732 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
3733 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
3735 ERR("Error obtaining status flags for socket!\n");
3736 status = WSAEINVAL;
3737 break;
3739 else
3741 /* set flags; the values of IFF_* are not the same
3742 under Linux and Windows, therefore must generate
3743 new flags */
3744 intArray->iiFlags = 0;
3745 if (ifInfo.ifr_flags & IFF_BROADCAST)
3746 intArray->iiFlags |= WS_IFF_BROADCAST;
3747 #ifdef IFF_POINTOPOINT
3748 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
3749 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
3750 #endif
3751 if (ifInfo.ifr_flags & IFF_LOOPBACK)
3752 intArray->iiFlags |= WS_IFF_LOOPBACK;
3753 if (ifInfo.ifr_flags & IFF_UP)
3754 intArray->iiFlags |= WS_IFF_UP;
3755 if (ifInfo.ifr_flags & IFF_MULTICAST)
3756 intArray->iiFlags |= WS_IFF_MULTICAST;
3759 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
3760 mask = inet_addr(ptr->IpAddressList.IpMask.String);
3761 bcast = addr | ~mask;
3762 intArray->iiAddress.AddressIn.sin_family = AF_INET;
3763 intArray->iiAddress.AddressIn.sin_port = 0;
3764 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
3765 addr;
3766 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
3767 intArray->iiNetmask.AddressIn.sin_port = 0;
3768 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
3769 mask;
3770 intArray->iiBroadcastAddress.AddressIn.sin_family =
3771 AF_INET;
3772 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
3773 intArray->iiBroadcastAddress.AddressIn.sin_addr.
3774 WS_s_addr = bcast;
3775 intArray++;
3776 numInt++;
3779 else
3781 ERR("Unable to get interface table!\n");
3782 status = WSAEINVAL;
3784 HeapFree(GetProcessHeap(),0,table);
3786 else status = WSAEINVAL;
3788 else if (apiReturn != ERROR_NO_DATA)
3790 ERR("Unable to get interface table!\n");
3791 status = WSAEINVAL;
3793 /* Calculate the size of the array being returned */
3794 total = sizeof(INTERFACE_INFO) * numInt;
3795 release_sock_fd( s, fd );
3796 break;
3799 case WS_SIO_ADDRESS_LIST_CHANGE:
3800 FIXME("-> SIO_ADDRESS_LIST_CHANGE request: stub\n");
3801 /* FIXME: error and return code depend on whether socket was created
3802 * with WSA_FLAG_OVERLAPPED, but there is no easy way to get this */
3803 break;
3805 case WS_SIO_ADDRESS_LIST_QUERY:
3807 DWORD size;
3809 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
3811 if (!ret_size)
3813 WSASetLastError(WSAEFAULT);
3814 return SOCKET_ERROR;
3817 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
3819 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
3820 DWORD num;
3822 if (!table || GetAdaptersInfo(table, &size))
3824 HeapFree(GetProcessHeap(), 0, table);
3825 status = WSAEINVAL;
3826 break;
3829 for (p = table, num = 0; p; p = p->Next)
3830 if (p->IpAddressList.IpAddress.String[0]) num++;
3832 total = sizeof(SOCKET_ADDRESS_LIST) + sizeof(SOCKET_ADDRESS) * (num - 1);
3833 total += sizeof(SOCKADDR) * num;
3835 if (total > out_size)
3837 HeapFree(GetProcessHeap(), 0, table);
3838 status = WSAEFAULT;
3839 break;
3842 if (out_buff)
3844 unsigned int i;
3845 SOCKET_ADDRESS *sa;
3846 SOCKET_ADDRESS_LIST *sa_list = out_buff;
3847 SOCKADDR_IN *sockaddr;
3849 sa = sa_list->Address;
3850 sockaddr = (SOCKADDR_IN *)((char *)sa + num * sizeof(SOCKET_ADDRESS));
3851 sa_list->iAddressCount = num;
3853 for (p = table, i = 0; p; p = p->Next)
3855 if (!p->IpAddressList.IpAddress.String[0]) continue;
3857 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
3858 sa[i].iSockaddrLength = sizeof(SOCKADDR);
3860 sockaddr[i].sin_family = AF_INET;
3861 sockaddr[i].sin_port = 0;
3862 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
3863 i++;
3867 HeapFree(GetProcessHeap(), 0, table);
3869 else
3871 WARN("unable to get IP address list\n");
3872 status = WSAEINVAL;
3874 break;
3877 case WS_SIO_FLUSH:
3878 FIXME("SIO_FLUSH: stub.\n");
3879 break;
3881 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
3883 static const GUID connectex_guid = WSAID_CONNECTEX;
3884 static const GUID disconnectex_guid = WSAID_DISCONNECTEX;
3885 static const GUID acceptex_guid = WSAID_ACCEPTEX;
3886 static const GUID getaccepexsockaddrs_guid = WSAID_GETACCEPTEXSOCKADDRS;
3887 static const GUID transmitfile_guid = WSAID_TRANSMITFILE;
3888 static const GUID transmitpackets_guid = WSAID_TRANSMITPACKETS;
3889 static const GUID wsarecvmsg_guid = WSAID_WSARECVMSG;
3890 static const GUID wsasendmsg_guid = WSAID_WSASENDMSG;
3892 if ( IsEqualGUID(&connectex_guid, in_buff) )
3894 *(LPFN_CONNECTEX *)out_buff = WS2_ConnectEx;
3895 break;
3897 else if ( IsEqualGUID(&disconnectex_guid, in_buff) )
3899 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented DisconnectEx\n");
3901 else if ( IsEqualGUID(&acceptex_guid, in_buff) )
3903 *(LPFN_ACCEPTEX *)out_buff = WS2_AcceptEx;
3904 break;
3906 else if ( IsEqualGUID(&getaccepexsockaddrs_guid, in_buff) )
3908 *(LPFN_GETACCEPTEXSOCKADDRS *)out_buff = WS2_GetAcceptExSockaddrs;
3909 break;
3911 else if ( IsEqualGUID(&transmitfile_guid, in_buff) )
3913 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitFile\n");
3915 else if ( IsEqualGUID(&transmitpackets_guid, in_buff) )
3917 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitPackets\n");
3919 else if ( IsEqualGUID(&wsarecvmsg_guid, in_buff) )
3921 *(LPFN_WSARECVMSG *)out_buff = WS2_WSARecvMsg;
3922 break;
3924 else if ( IsEqualGUID(&wsasendmsg_guid, in_buff) )
3926 *(LPFN_WSASENDMSG *)out_buff = WSASendMsg;
3927 break;
3929 else
3930 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff));
3932 status = WSAEOPNOTSUPP;
3933 break;
3935 case WS_SIO_KEEPALIVE_VALS:
3937 struct tcp_keepalive *k;
3938 int keepalive, keepidle, keepintvl;
3940 if (!in_buff || in_size < sizeof(struct tcp_keepalive))
3942 WSASetLastError(WSAEFAULT);
3943 return SOCKET_ERROR;
3946 k = in_buff;
3947 keepalive = k->onoff ? 1 : 0;
3948 keepidle = max( 1, (k->keepalivetime + 500) / 1000 );
3949 keepintvl = max( 1, (k->keepaliveinterval + 500) / 1000 );
3951 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
3953 fd = get_sock_fd(s, 0, NULL);
3954 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
3955 status = WSAEINVAL;
3956 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
3957 /* these values need to be set only if SO_KEEPALIVE is enabled */
3958 else if(keepalive)
3960 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
3961 status = WSAEINVAL;
3962 else if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
3963 status = WSAEINVAL;
3965 #else
3966 else
3967 FIXME("ignoring keepalive interval and timeout\n");
3968 #endif
3969 release_sock_fd(s, fd);
3970 break;
3972 case WS_SIO_ROUTING_INTERFACE_QUERY:
3974 struct WS_sockaddr *daddr = (struct WS_sockaddr *)in_buff;
3975 struct WS_sockaddr_in *daddr_in = (struct WS_sockaddr_in *)daddr;
3976 struct WS_sockaddr_in *saddr_in = out_buff;
3977 MIB_IPFORWARDROW row;
3978 PMIB_IPADDRTABLE ipAddrTable = NULL;
3979 DWORD size, i, found_index;
3981 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
3983 if (!in_buff || in_size < sizeof(struct WS_sockaddr) ||
3984 !out_buff || out_size < sizeof(struct WS_sockaddr_in) || !ret_size)
3986 WSASetLastError(WSAEFAULT);
3987 return SOCKET_ERROR;
3989 if (daddr->sa_family != AF_INET)
3991 FIXME("unsupported address family %d\n", daddr->sa_family);
3992 status = WSAEAFNOSUPPORT;
3993 break;
3995 if (GetBestRoute(daddr_in->sin_addr.S_un.S_addr, 0, &row) != NOERROR ||
3996 GetIpAddrTable(NULL, &size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
3998 status = WSAEFAULT;
3999 break;
4001 ipAddrTable = HeapAlloc(GetProcessHeap(), 0, size);
4002 if (GetIpAddrTable(ipAddrTable, &size, FALSE))
4004 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4005 status = WSAEFAULT;
4006 break;
4008 for (i = 0, found_index = ipAddrTable->dwNumEntries;
4009 i < ipAddrTable->dwNumEntries; i++)
4011 if (ipAddrTable->table[i].dwIndex == row.dwForwardIfIndex)
4012 found_index = i;
4014 if (found_index == ipAddrTable->dwNumEntries)
4016 ERR("no matching IP address for interface %d\n",
4017 row.dwForwardIfIndex);
4018 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4019 status = WSAEFAULT;
4020 break;
4022 saddr_in->sin_family = AF_INET;
4023 saddr_in->sin_addr.S_un.S_addr = ipAddrTable->table[found_index].dwAddr;
4024 saddr_in->sin_port = 0;
4025 total = sizeof(struct WS_sockaddr_in);
4026 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4027 break;
4029 case WS_SIO_SET_COMPATIBILITY_MODE:
4030 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
4031 status = WSAEOPNOTSUPP;
4032 break;
4033 case WS_SIO_UDP_CONNRESET:
4034 FIXME("WS_SIO_UDP_CONNRESET stub\n");
4035 break;
4036 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
4037 WSASetLastError(WSAEOPNOTSUPP);
4038 return SOCKET_ERROR;
4039 default:
4040 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code));
4041 status = WSAEOPNOTSUPP;
4042 break;
4045 if (completion)
4047 FIXME( "completion routine %p not supported\n", completion );
4049 else if (overlapped)
4051 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
4052 overlapped->Internal = status;
4053 overlapped->InternalHigh = total;
4054 if (overlapped->hEvent) NtSetEvent( overlapped->hEvent, NULL );
4055 if (cvalue) WS_AddCompletion( HANDLE2SOCKET(s), cvalue, status, total );
4058 if (!status)
4060 if (ret_size) *ret_size = total;
4061 return 0;
4063 SetLastError( status );
4064 return SOCKET_ERROR;
4068 /***********************************************************************
4069 * ioctlsocket (WS2_32.10)
4071 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
4073 DWORD ret_size;
4074 return WSAIoctl( s, cmd, argp, sizeof(WS_u_long), argp, sizeof(WS_u_long), &ret_size, NULL, NULL );
4077 /***********************************************************************
4078 * listen (WS2_32.13)
4080 int WINAPI WS_listen(SOCKET s, int backlog)
4082 int fd = get_sock_fd( s, FILE_READ_DATA, NULL ), ret = SOCKET_ERROR;
4084 TRACE("socket %04lx, backlog %d\n", s, backlog);
4085 if (fd != -1)
4087 union generic_unix_sockaddr uaddr;
4088 socklen_t uaddrlen = sizeof(uaddr);
4090 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
4092 SetLastError(wsaErrno());
4094 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
4096 SetLastError(WSAEINVAL);
4098 else if (listen(fd, backlog) == 0)
4100 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
4101 FD_WINE_LISTENING,
4102 FD_CONNECT|FD_WINE_CONNECTED);
4103 ret = 0;
4105 else
4106 SetLastError(wsaErrno());
4107 release_sock_fd( s, fd );
4109 else
4110 SetLastError(WSAENOTSOCK);
4111 return ret;
4114 /***********************************************************************
4115 * recv (WS2_32.16)
4117 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
4119 DWORD n, dwFlags = flags;
4120 WSABUF wsabuf;
4122 wsabuf.len = len;
4123 wsabuf.buf = buf;
4125 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
4126 return SOCKET_ERROR;
4127 else
4128 return n;
4131 /***********************************************************************
4132 * recvfrom (WS2_32.17)
4134 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
4135 struct WS_sockaddr *from, int *fromlen)
4137 DWORD n, dwFlags = flags;
4138 WSABUF wsabuf;
4140 wsabuf.len = len;
4141 wsabuf.buf = buf;
4143 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL, NULL) == SOCKET_ERROR )
4144 return SOCKET_ERROR;
4145 else
4146 return n;
4149 /* allocate a poll array for the corresponding fd sets */
4150 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
4151 const WS_fd_set *exceptfds, int *count_ptr )
4153 unsigned int i, j = 0, count = 0;
4154 struct pollfd *fds;
4156 if (readfds) count += readfds->fd_count;
4157 if (writefds) count += writefds->fd_count;
4158 if (exceptfds) count += exceptfds->fd_count;
4159 *count_ptr = count;
4160 if (!count)
4162 SetLastError(WSAEINVAL);
4163 return NULL;
4165 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0]))))
4167 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
4168 return NULL;
4170 if (readfds)
4171 for (i = 0; i < readfds->fd_count; i++, j++)
4173 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
4174 if (fds[j].fd == -1) goto failed;
4175 fds[j].events = POLLIN;
4176 fds[j].revents = 0;
4178 if (writefds)
4179 for (i = 0; i < writefds->fd_count; i++, j++)
4181 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
4182 if (fds[j].fd == -1) goto failed;
4183 fds[j].events = POLLOUT;
4184 fds[j].revents = 0;
4186 if (exceptfds)
4187 for (i = 0; i < exceptfds->fd_count; i++, j++)
4189 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
4190 if (fds[j].fd == -1) goto failed;
4191 fds[j].events = POLLHUP;
4192 fds[j].revents = 0;
4194 return fds;
4196 failed:
4197 count = j;
4198 j = 0;
4199 if (readfds)
4200 for (i = 0; i < readfds->fd_count && j < count; i++, j++)
4201 release_sock_fd( readfds->fd_array[i], fds[j].fd );
4202 if (writefds)
4203 for (i = 0; i < writefds->fd_count && j < count; i++, j++)
4204 release_sock_fd( writefds->fd_array[i], fds[j].fd );
4205 if (exceptfds)
4206 for (i = 0; i < exceptfds->fd_count && j < count; i++, j++)
4207 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
4208 HeapFree( GetProcessHeap(), 0, fds );
4209 return NULL;
4212 /* release the file descriptor obtained in fd_sets_to_poll */
4213 /* must be called with the original fd_set arrays, before calling get_poll_results */
4214 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
4215 const WS_fd_set *exceptfds, struct pollfd *fds )
4217 unsigned int i, j = 0;
4219 if (readfds)
4221 for (i = 0; i < readfds->fd_count; i++, j++)
4222 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
4224 if (writefds)
4226 for (i = 0; i < writefds->fd_count; i++, j++)
4227 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
4229 if (exceptfds)
4231 for (i = 0; i < exceptfds->fd_count; i++, j++)
4232 if (fds[j].fd != -1)
4234 /* make sure we have a real error before releasing the fd */
4235 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
4236 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
4241 /* map the poll results back into the Windows fd sets */
4242 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
4243 const struct pollfd *fds )
4245 unsigned int i, j = 0, k, total = 0;
4247 if (readfds)
4249 for (i = k = 0; i < readfds->fd_count; i++, j++)
4250 if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
4251 readfds->fd_count = k;
4252 total += k;
4254 if (writefds)
4256 for (i = k = 0; i < writefds->fd_count; i++, j++)
4257 if ((fds[j].revents & POLLOUT) && !(fds[j].revents & POLLHUP))
4258 writefds->fd_array[k++] = writefds->fd_array[i];
4259 writefds->fd_count = k;
4260 total += k;
4262 if (exceptfds)
4264 for (i = k = 0; i < exceptfds->fd_count; i++, j++)
4265 if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
4266 exceptfds->fd_count = k;
4267 total += k;
4269 return total;
4273 /***********************************************************************
4274 * select (WS2_32.18)
4276 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
4277 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
4278 const struct WS_timeval* ws_timeout)
4280 struct pollfd *pollfds;
4281 struct timeval tv1, tv2;
4282 int torig = 0;
4283 int count, ret, timeout = -1;
4285 TRACE("read %p, write %p, excp %p timeout %p\n",
4286 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
4288 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )))
4289 return SOCKET_ERROR;
4291 if (ws_timeout)
4293 torig = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
4294 timeout = torig;
4295 gettimeofday( &tv1, 0 );
4298 while ((ret = poll( pollfds, count, timeout )) < 0)
4300 if (errno == EINTR)
4302 if (!ws_timeout) continue;
4303 gettimeofday( &tv2, 0 );
4305 tv2.tv_sec -= tv1.tv_sec;
4306 tv2.tv_usec -= tv1.tv_usec;
4307 if (tv2.tv_usec < 0)
4309 tv2.tv_usec += 1000000;
4310 tv2.tv_sec -= 1;
4313 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
4314 if (timeout <= 0) break;
4315 } else break;
4317 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
4319 if (ret == -1) SetLastError(wsaErrno());
4320 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
4321 HeapFree( GetProcessHeap(), 0, pollfds );
4322 return ret;
4325 /* helper to send completion messages for client-only i/o operation case */
4326 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
4327 ULONG Information )
4329 SERVER_START_REQ( add_fd_completion )
4331 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
4332 req->cvalue = CompletionValue;
4333 req->status = CompletionStatus;
4334 req->information = Information;
4335 wine_server_call( req );
4337 SERVER_END_REQ;
4341 /***********************************************************************
4342 * send (WS2_32.19)
4344 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
4346 DWORD n;
4347 WSABUF wsabuf;
4349 wsabuf.len = len;
4350 wsabuf.buf = (char*) buf;
4352 if ( WS2_sendto( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
4353 return SOCKET_ERROR;
4354 else
4355 return n;
4358 /***********************************************************************
4359 * WSASend (WS2_32.72)
4361 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4362 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4363 LPWSAOVERLAPPED lpOverlapped,
4364 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4366 return WS2_sendto( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
4367 NULL, 0, lpOverlapped, lpCompletionRoutine );
4370 /***********************************************************************
4371 * WSASendDisconnect (WS2_32.73)
4373 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
4375 return WS_shutdown( s, SD_SEND );
4379 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4380 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4381 const struct WS_sockaddr *to, int tolen,
4382 LPWSAOVERLAPPED lpOverlapped,
4383 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4385 unsigned int i, options;
4386 int n, fd, err;
4387 struct ws2_async *wsa = NULL;
4388 int totalLength = 0;
4389 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
4390 DWORD bytes_sent;
4391 BOOL is_blocking;
4393 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
4394 s, lpBuffers, dwBufferCount, dwFlags,
4395 to, tolen, lpOverlapped, lpCompletionRoutine);
4397 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
4398 TRACE( "fd=%d, options=%x\n", fd, options );
4400 if ( fd == -1 ) return SOCKET_ERROR;
4402 if (!lpOverlapped && !lpNumberOfBytesSent)
4404 err = WSAEFAULT;
4405 goto error;
4407 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
4409 err = WSAEFAULT;
4410 goto error;
4413 wsa->hSocket = SOCKET2HANDLE(s);
4414 wsa->addr = (struct WS_sockaddr *)to;
4415 wsa->addrlen.val = tolen;
4416 wsa->flags = dwFlags;
4417 wsa->lpFlags = &wsa->flags;
4418 wsa->control = NULL;
4419 wsa->n_iovecs = dwBufferCount;
4420 wsa->first_iovec = 0;
4421 for ( i = 0; i < dwBufferCount; i++ )
4423 wsa->iovec[i].iov_base = lpBuffers[i].buf;
4424 wsa->iovec[i].iov_len = lpBuffers[i].len;
4425 totalLength += lpBuffers[i].len;
4428 for (;;)
4430 n = WS2_send( fd, wsa );
4431 if (n != -1 || errno != EINTR) break;
4433 if (n == -1 && errno != EAGAIN)
4435 err = wsaErrno();
4436 goto error;
4439 if ((lpOverlapped || lpCompletionRoutine) &&
4440 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
4442 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
4444 wsa->user_overlapped = lpOverlapped;
4445 wsa->completion_func = lpCompletionRoutine;
4446 release_sock_fd( s, fd );
4448 if (n == -1 || n < totalLength)
4450 iosb->u.Status = STATUS_PENDING;
4451 iosb->Information = n == -1 ? 0 : n;
4453 SERVER_START_REQ( register_async )
4455 req->type = ASYNC_TYPE_WRITE;
4456 req->async.handle = wine_server_obj_handle( wsa->hSocket );
4457 req->async.callback = wine_server_client_ptr( WS2_async_send );
4458 req->async.iosb = wine_server_client_ptr( iosb );
4459 req->async.arg = wine_server_client_ptr( wsa );
4460 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
4461 req->async.cvalue = cvalue;
4462 err = wine_server_call( req );
4464 SERVER_END_REQ;
4466 /* Enable the event only after starting the async. The server will deliver it as soon as
4467 the async is done. */
4468 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
4470 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
4471 WSASetLastError( NtStatusToWSAError( err ));
4472 return SOCKET_ERROR;
4475 iosb->u.Status = STATUS_SUCCESS;
4476 iosb->Information = n;
4477 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = n;
4478 if (!wsa->completion_func)
4480 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
4481 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
4482 HeapFree( GetProcessHeap(), 0, wsa );
4484 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
4485 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
4486 WSASetLastError(0);
4487 return 0;
4490 if ((err = _is_blocking( s, &is_blocking )))
4492 err = NtStatusToWSAError( err );
4493 goto error;
4496 if ( is_blocking )
4498 /* On a blocking non-overlapped stream socket,
4499 * sending blocks until the entire buffer is sent. */
4500 DWORD timeout_start = GetTickCount();
4502 bytes_sent = n == -1 ? 0 : n;
4504 while (wsa->first_iovec < wsa->n_iovecs)
4506 struct pollfd pfd;
4507 int timeout = GET_SNDTIMEO(fd);
4509 if (timeout != -1)
4511 timeout -= GetTickCount() - timeout_start;
4512 if (timeout < 0) timeout = 0;
4515 pfd.fd = fd;
4516 pfd.events = POLLOUT;
4518 if (!timeout || !poll( &pfd, 1, timeout ))
4520 err = WSAETIMEDOUT;
4521 goto error; /* msdn says a timeout in send is fatal */
4524 n = WS2_send( fd, wsa );
4525 if (n == -1 && errno != EAGAIN && errno != EINTR)
4527 err = wsaErrno();
4528 goto error;
4531 if (n >= 0)
4532 bytes_sent += n;
4535 else /* non-blocking */
4537 if (n < totalLength)
4538 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
4539 if (n == -1)
4541 err = WSAEWOULDBLOCK;
4542 goto error;
4544 bytes_sent = n;
4547 TRACE(" -> %i bytes\n", bytes_sent);
4549 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = bytes_sent;
4550 HeapFree( GetProcessHeap(), 0, wsa );
4551 release_sock_fd( s, fd );
4552 WSASetLastError(0);
4553 return 0;
4555 error:
4556 HeapFree( GetProcessHeap(), 0, wsa );
4557 release_sock_fd( s, fd );
4558 WARN(" -> ERROR %d\n", err);
4559 WSASetLastError(err);
4560 return SOCKET_ERROR;
4563 /***********************************************************************
4564 * WSASendTo (WS2_32.74)
4566 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4567 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4568 const struct WS_sockaddr *to, int tolen,
4569 LPWSAOVERLAPPED lpOverlapped,
4570 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4572 return WS2_sendto( s, lpBuffers, dwBufferCount,
4573 lpNumberOfBytesSent, dwFlags,
4574 to, tolen,
4575 lpOverlapped, lpCompletionRoutine );
4578 /***********************************************************************
4579 * sendto (WS2_32.20)
4581 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
4582 const struct WS_sockaddr *to, int tolen)
4584 DWORD n;
4585 WSABUF wsabuf;
4587 wsabuf.len = len;
4588 wsabuf.buf = (char*) buf;
4590 if ( WS2_sendto(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
4591 return SOCKET_ERROR;
4592 else
4593 return n;
4596 /***********************************************************************
4597 * setsockopt (WS2_32.21)
4599 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
4600 const char *optval, int optlen)
4602 int fd;
4603 int woptval;
4604 struct linger linger;
4605 struct timeval tval;
4607 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
4608 s, level, optname, optval, optlen);
4610 /* some broken apps pass the value directly instead of a pointer to it */
4611 if(optlen && IS_INTRESOURCE(optval))
4613 SetLastError(WSAEFAULT);
4614 return SOCKET_ERROR;
4617 switch(level)
4619 case WS_SOL_SOCKET:
4620 switch(optname)
4622 /* Some options need some conversion before they can be sent to
4623 * setsockopt. The conversions are done here, then they will fall though
4624 * to the general case. Special options that are not passed to
4625 * setsockopt follow below that.*/
4627 case WS_SO_DONTLINGER:
4628 if (!optval)
4630 SetLastError(WSAEFAULT);
4631 return SOCKET_ERROR;
4633 linger.l_onoff = *(const int*)optval == 0;
4634 linger.l_linger = 0;
4635 level = SOL_SOCKET;
4636 optname = SO_LINGER;
4637 optval = (char*)&linger;
4638 optlen = sizeof(struct linger);
4639 break;
4641 case WS_SO_LINGER:
4642 if (!optval)
4644 SetLastError(WSAEFAULT);
4645 return SOCKET_ERROR;
4647 linger.l_onoff = ((LINGER*)optval)->l_onoff;
4648 linger.l_linger = ((LINGER*)optval)->l_linger;
4649 level = SOL_SOCKET;
4650 optname = SO_LINGER;
4651 optval = (char*)&linger;
4652 optlen = sizeof(struct linger);
4653 break;
4655 case WS_SO_RCVBUF:
4656 if (*(const int*)optval < 2048)
4658 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
4659 return 0;
4661 /* Fall through */
4663 /* The options listed here don't need any special handling. Thanks to
4664 * the conversion happening above, options from there will fall through
4665 * to this, too.*/
4666 case WS_SO_ACCEPTCONN:
4667 case WS_SO_BROADCAST:
4668 case WS_SO_ERROR:
4669 case WS_SO_KEEPALIVE:
4670 case WS_SO_OOBINLINE:
4671 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
4672 * however, using it the BSD way fixes bug 8513 and seems to be what
4673 * most programmers assume, anyway */
4674 case WS_SO_REUSEADDR:
4675 case WS_SO_SNDBUF:
4676 case WS_SO_TYPE:
4677 convert_sockopt(&level, &optname);
4678 break;
4680 /* SO_DEBUG is a privileged operation, ignore it. */
4681 case WS_SO_DEBUG:
4682 TRACE("Ignoring SO_DEBUG\n");
4683 return 0;
4685 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
4686 * socket. According to MSDN, this option is silently ignored.*/
4687 case WS_SO_DONTROUTE:
4688 TRACE("Ignoring SO_DONTROUTE\n");
4689 return 0;
4691 /* Stops two sockets from being bound to the same port. Always happens
4692 * on unix systems, so just drop it. */
4693 case WS_SO_EXCLUSIVEADDRUSE:
4694 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
4695 return 0;
4697 /* After a ConnectEx call succeeds, the socket can't be used with half of the
4698 * normal winsock functions on windows. We don't have that problem. */
4699 case WS_SO_UPDATE_CONNECT_CONTEXT:
4700 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
4701 return 0;
4703 /* After a AcceptEx call succeeds, the socket can't be used with half of the
4704 * normal winsock functions on windows. We don't have that problem. */
4705 case WS_SO_UPDATE_ACCEPT_CONTEXT:
4706 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
4707 return 0;
4709 /* SO_OPENTYPE does not require a valid socket handle. */
4710 case WS_SO_OPENTYPE:
4711 if (!optlen || optlen < sizeof(int) || !optval)
4713 SetLastError(WSAEFAULT);
4714 return SOCKET_ERROR;
4716 get_per_thread_data()->opentype = *(const int *)optval;
4717 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
4718 return 0;
4720 #ifdef SO_RCVTIMEO
4721 case WS_SO_RCVTIMEO:
4722 #endif
4723 #ifdef SO_SNDTIMEO
4724 case WS_SO_SNDTIMEO:
4725 #endif
4726 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
4727 if (optval && optlen == sizeof(UINT32)) {
4728 /* WinSock passes milliseconds instead of struct timeval */
4729 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
4730 tval.tv_sec = *(const UINT32*)optval / 1000;
4731 /* min of 500 milliseconds */
4732 if (tval.tv_sec == 0 && tval.tv_usec && tval.tv_usec < 500000)
4733 tval.tv_usec = 500000;
4734 optlen = sizeof(struct timeval);
4735 optval = (char*)&tval;
4736 } else if (optlen == sizeof(struct timeval)) {
4737 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
4738 } else {
4739 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
4740 return 0;
4742 convert_sockopt(&level, &optname);
4743 break;
4744 #endif
4746 default:
4747 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
4748 SetLastError(WSAENOPROTOOPT);
4749 return SOCKET_ERROR;
4751 break; /* case WS_SOL_SOCKET */
4753 #ifdef HAS_IPX
4754 case NSPROTO_IPX:
4755 switch(optname)
4757 case IPX_PTYPE:
4758 fd = get_sock_fd( s, 0, NULL );
4759 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", *(const int*)optval, fd);
4761 /* We try to set the ipx type on ipx socket level. */
4762 #ifdef SOL_IPX
4763 if(setsockopt(fd, SOL_IPX, IPX_TYPE, optval, optlen) == -1)
4765 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
4766 release_sock_fd( s, fd );
4767 return SOCKET_ERROR;
4769 #else
4771 struct ipx val;
4772 /* Should we retrieve val using a getsockopt call and then
4773 * set the modified one? */
4774 val.ipx_pt = *optval;
4775 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
4777 #endif
4778 release_sock_fd( s, fd );
4779 return 0;
4781 case IPX_FILTERPTYPE:
4782 /* Sets the receive filter packet type, at the moment we don't support it */
4783 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
4784 /* Returning 0 is better for now than returning a SOCKET_ERROR */
4785 return 0;
4787 default:
4788 FIXME("opt_name:%x\n", optname);
4789 return SOCKET_ERROR;
4791 break; /* case NSPROTO_IPX */
4792 #endif
4794 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
4795 case WS_IPPROTO_TCP:
4796 switch(optname)
4798 case WS_TCP_NODELAY:
4799 convert_sockopt(&level, &optname);
4800 break;
4801 default:
4802 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
4803 return SOCKET_ERROR;
4805 break;
4807 case WS_IPPROTO_IP:
4808 switch(optname)
4810 case WS_IP_ADD_MEMBERSHIP:
4811 case WS_IP_DROP_MEMBERSHIP:
4812 #ifdef IP_HDRINCL
4813 case WS_IP_HDRINCL:
4814 #endif
4815 case WS_IP_MULTICAST_IF:
4816 case WS_IP_MULTICAST_LOOP:
4817 case WS_IP_MULTICAST_TTL:
4818 case WS_IP_OPTIONS:
4819 #ifdef IP_PKTINFO
4820 case WS_IP_PKTINFO:
4821 #endif
4822 case WS_IP_TOS:
4823 case WS_IP_TTL:
4824 #ifdef IP_UNICAST_IF
4825 case WS_IP_UNICAST_IF:
4826 #endif
4827 convert_sockopt(&level, &optname);
4828 break;
4829 case WS_IP_DONTFRAGMENT:
4830 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
4831 return 0;
4832 default:
4833 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
4834 return SOCKET_ERROR;
4836 break;
4838 case WS_IPPROTO_IPV6:
4839 switch(optname)
4841 #ifdef IPV6_ADD_MEMBERSHIP
4842 case WS_IPV6_ADD_MEMBERSHIP:
4843 #endif
4844 #ifdef IPV6_DROP_MEMBERSHIP
4845 case WS_IPV6_DROP_MEMBERSHIP:
4846 #endif
4847 case WS_IPV6_MULTICAST_IF:
4848 case WS_IPV6_MULTICAST_HOPS:
4849 case WS_IPV6_MULTICAST_LOOP:
4850 case WS_IPV6_UNICAST_HOPS:
4851 case WS_IPV6_V6ONLY:
4852 #ifdef IPV6_UNICAST_IF
4853 case WS_IPV6_UNICAST_IF:
4854 #endif
4855 convert_sockopt(&level, &optname);
4856 break;
4857 case WS_IPV6_DONTFRAG:
4858 FIXME("IPV6_DONTFRAG is silently ignored!\n");
4859 return 0;
4860 case WS_IPV6_PROTECTION_LEVEL:
4861 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
4862 return 0;
4863 default:
4864 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
4865 return SOCKET_ERROR;
4867 break;
4869 default:
4870 WARN("Unknown level: 0x%08x\n", level);
4871 SetLastError(WSAEINVAL);
4872 return SOCKET_ERROR;
4873 } /* end switch(level) */
4875 /* avoid endianness issues if argument is a 16-bit int */
4876 if (optval && optlen < sizeof(int))
4878 woptval= *((const INT16 *) optval);
4879 optval= (char*) &woptval;
4880 optlen=sizeof(int);
4882 fd = get_sock_fd( s, 0, NULL );
4883 if (fd == -1) return SOCKET_ERROR;
4885 if (setsockopt(fd, level, optname, optval, optlen) == 0)
4887 #ifdef __APPLE__
4888 if (level == SOL_SOCKET && optname == SO_REUSEADDR &&
4889 setsockopt(fd, level, SO_REUSEPORT, optval, optlen) != 0)
4891 SetLastError(wsaErrno());
4892 release_sock_fd( s, fd );
4893 return SOCKET_ERROR;
4895 #endif
4896 release_sock_fd( s, fd );
4897 return 0;
4899 TRACE("Setting socket error, %d\n", wsaErrno());
4900 SetLastError(wsaErrno());
4901 release_sock_fd( s, fd );
4903 return SOCKET_ERROR;
4906 /***********************************************************************
4907 * shutdown (WS2_32.22)
4909 int WINAPI WS_shutdown(SOCKET s, int how)
4911 int fd, err = WSAENOTSOCK;
4912 unsigned int options, clear_flags = 0;
4914 fd = get_sock_fd( s, 0, &options );
4915 TRACE("socket %04lx, how %i %x\n", s, how, options );
4917 if (fd == -1)
4918 return SOCKET_ERROR;
4920 switch( how )
4922 case 0: /* drop receives */
4923 clear_flags |= FD_READ;
4924 break;
4925 case 1: /* drop sends */
4926 clear_flags |= FD_WRITE;
4927 break;
4928 case 2: /* drop all */
4929 clear_flags |= FD_READ|FD_WRITE;
4930 /*fall through */
4931 default:
4932 clear_flags |= FD_WINE_LISTENING;
4935 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
4937 switch ( how )
4939 case SD_RECEIVE:
4940 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
4941 break;
4942 case SD_SEND:
4943 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
4944 break;
4945 case SD_BOTH:
4946 default:
4947 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
4948 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
4949 break;
4951 if (err) goto error;
4953 else /* non-overlapped mode */
4955 if ( shutdown( fd, how ) )
4957 err = wsaErrno();
4958 goto error;
4962 release_sock_fd( s, fd );
4963 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
4964 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
4965 return 0;
4967 error:
4968 release_sock_fd( s, fd );
4969 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
4970 WSASetLastError( err );
4971 return SOCKET_ERROR;
4974 /***********************************************************************
4975 * socket (WS2_32.23)
4977 SOCKET WINAPI WS_socket(int af, int type, int protocol)
4979 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
4981 return WSASocketA( af, type, protocol, NULL, 0,
4982 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
4986 /***********************************************************************
4987 * gethostbyaddr (WS2_32.51)
4989 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
4991 struct WS_hostent *retval = NULL;
4992 struct hostent* host;
4994 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4995 char *extrabuf;
4996 int ebufsize=1024;
4997 struct hostent hostentry;
4998 int locerr=ENOBUFS;
4999 host = NULL;
5000 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
5001 while(extrabuf) {
5002 int res = gethostbyaddr_r(addr, len, type,
5003 &hostentry, extrabuf, ebufsize, &host, &locerr);
5004 if( res != ERANGE) break;
5005 ebufsize *=2;
5006 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
5008 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
5009 #else
5010 EnterCriticalSection( &csWSgetXXXbyYYY );
5011 host = gethostbyaddr(addr, len, type);
5012 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
5013 #endif
5014 if( host != NULL ) retval = WS_dup_he(host);
5015 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5016 HeapFree(GetProcessHeap(),0,extrabuf);
5017 #else
5018 LeaveCriticalSection( &csWSgetXXXbyYYY );
5019 #endif
5020 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
5021 return retval;
5024 /***********************************************************************
5025 * WS_get_local_ips (INTERNAL)
5027 * Returns the list of local IP addresses by going through the network
5028 * adapters and using the local routing table to sort the addresses
5029 * from highest routing priority to lowest routing priority. This
5030 * functionality is inferred from the description for obtaining local
5031 * IP addresses given in the Knowledge Base Article Q160215.
5033 * Please note that the returned hostent is only freed when the thread
5034 * closes and is replaced if another hostent is requested.
5036 static struct WS_hostent* WS_get_local_ips( char *hostname )
5038 int last_metric, numroutes = 0, i, j;
5039 DWORD n;
5040 PIP_ADAPTER_INFO adapters = NULL, k;
5041 struct WS_hostent *hostlist = NULL;
5042 PMIB_IPFORWARDTABLE routes = NULL;
5043 struct route *route_addrs = NULL;
5044 DWORD adap_size, route_size;
5046 /* Obtain the size of the adapter list and routing table, also allocate memory */
5047 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
5048 return NULL;
5049 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
5050 return NULL;
5051 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
5052 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
5053 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
5054 if (adapters == NULL || routes == NULL || route_addrs == NULL)
5055 goto cleanup;
5056 /* Obtain the adapter list and the full routing table */
5057 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
5058 goto cleanup;
5059 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
5060 goto cleanup;
5061 /* Store the interface associated with each route */
5062 for (n = 0; n < routes->dwNumEntries; n++)
5064 IF_INDEX ifindex;
5065 DWORD ifmetric, exists = FALSE;
5067 if (routes->table[n].u1.ForwardType != MIB_IPROUTE_TYPE_DIRECT)
5068 continue;
5069 ifindex = routes->table[n].dwForwardIfIndex;
5070 ifmetric = routes->table[n].dwForwardMetric1;
5071 /* Only store the lowest valued metric for an interface */
5072 for (j = 0; j < numroutes; j++)
5074 if (route_addrs[j].interface == ifindex)
5076 if (route_addrs[j].metric > ifmetric)
5077 route_addrs[j].metric = ifmetric;
5078 exists = TRUE;
5081 if (exists)
5082 continue;
5083 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
5084 if (route_addrs == NULL)
5085 goto cleanup; /* Memory allocation error, fail gracefully */
5086 route_addrs[numroutes].interface = ifindex;
5087 route_addrs[numroutes].metric = ifmetric;
5088 /* If no IP is found in the next step (for whatever reason)
5089 * then fall back to the magic loopback address.
5091 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
5092 numroutes++;
5094 if (numroutes == 0)
5095 goto cleanup; /* No routes, fall back to the Magic IP */
5096 /* Find the IP address associated with each found interface */
5097 for (i = 0; i < numroutes; i++)
5099 for (k = adapters; k != NULL; k = k->Next)
5101 char *ip = k->IpAddressList.IpAddress.String;
5103 if (route_addrs[i].interface == k->Index)
5104 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
5107 /* Allocate a hostent and enough memory for all the IPs,
5108 * including the NULL at the end of the list.
5110 hostlist = WS_create_he(hostname, 1, 0, numroutes+1, sizeof(struct in_addr));
5111 if (hostlist == NULL)
5112 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
5113 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
5114 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
5115 hostlist->h_addrtype = AF_INET;
5116 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
5117 /* Reorder the entries when placing them in the host list, Windows expects
5118 * the IP list in order from highest priority to lowest (the critical thing
5119 * is that most applications expect the first IP to be the default route).
5121 last_metric = -1;
5122 for (i = 0; i < numroutes; i++)
5124 struct in_addr addr;
5125 int metric = 0xFFFF;
5127 memcpy(&addr, magic_loopback_addr, 4);
5128 for (j = 0; j < numroutes; j++)
5130 int this_metric = route_addrs[j].metric;
5132 if (this_metric > last_metric && this_metric < metric)
5134 addr = route_addrs[j].addr;
5135 metric = this_metric;
5138 last_metric = metric;
5139 (*(struct in_addr *) hostlist->h_addr_list[i]) = addr;
5142 /* Cleanup all allocated memory except the address list,
5143 * the address list is used by the calling app.
5145 cleanup:
5146 HeapFree(GetProcessHeap(), 0, route_addrs);
5147 HeapFree(GetProcessHeap(), 0, adapters);
5148 HeapFree(GetProcessHeap(), 0, routes);
5149 return hostlist;
5152 /***********************************************************************
5153 * gethostbyname (WS2_32.52)
5155 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
5157 struct WS_hostent *retval = NULL;
5158 struct hostent* host;
5159 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5160 char *extrabuf;
5161 int ebufsize=1024;
5162 struct hostent hostentry;
5163 int locerr = ENOBUFS;
5164 #endif
5165 char hostname[100];
5166 if(!num_startup) {
5167 SetLastError(WSANOTINITIALISED);
5168 return NULL;
5170 if( gethostname( hostname, 100) == -1) {
5171 SetLastError( WSAENOBUFS); /* appropriate ? */
5172 return retval;
5174 if( !name || !name[0]) {
5175 name = hostname;
5177 /* If the hostname of the local machine is requested then return the
5178 * complete list of local IP addresses */
5179 if(strcmp(name, hostname) == 0)
5180 retval = WS_get_local_ips(hostname);
5181 /* If any other hostname was requested (or the routing table lookup failed)
5182 * then return the IP found by the host OS */
5183 if(retval == NULL)
5185 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5186 host = NULL;
5187 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
5188 while(extrabuf) {
5189 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
5190 if( res != ERANGE) break;
5191 ebufsize *=2;
5192 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
5194 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
5195 #else
5196 EnterCriticalSection( &csWSgetXXXbyYYY );
5197 host = gethostbyname(name);
5198 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
5199 #endif
5200 if (host) retval = WS_dup_he(host);
5201 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5202 HeapFree(GetProcessHeap(),0,extrabuf);
5203 #else
5204 LeaveCriticalSection( &csWSgetXXXbyYYY );
5205 #endif
5207 if (retval && retval->h_addr_list[0][0] == 127 &&
5208 strcmp(name, "localhost") != 0)
5210 /* hostname != "localhost" but has loopback address. replace by our
5211 * special address.*/
5212 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
5214 TRACE( "%s ret %p\n", debugstr_a(name), retval );
5215 return retval;
5219 /***********************************************************************
5220 * getprotobyname (WS2_32.53)
5222 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
5224 struct WS_protoent* retval = NULL;
5225 #ifdef HAVE_GETPROTOBYNAME
5226 struct protoent* proto;
5227 EnterCriticalSection( &csWSgetXXXbyYYY );
5228 if( (proto = getprotobyname(name)) != NULL )
5230 retval = WS_dup_pe(proto);
5232 else {
5233 MESSAGE("protocol %s not found; You might want to add "
5234 "this to /etc/protocols\n", debugstr_a(name) );
5235 SetLastError(WSANO_DATA);
5237 LeaveCriticalSection( &csWSgetXXXbyYYY );
5238 #endif
5239 TRACE( "%s ret %p\n", debugstr_a(name), retval );
5240 return retval;
5244 /***********************************************************************
5245 * getprotobynumber (WS2_32.54)
5247 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
5249 struct WS_protoent* retval = NULL;
5250 #ifdef HAVE_GETPROTOBYNUMBER
5251 struct protoent* proto;
5252 EnterCriticalSection( &csWSgetXXXbyYYY );
5253 if( (proto = getprotobynumber(number)) != NULL )
5255 retval = WS_dup_pe(proto);
5257 else {
5258 MESSAGE("protocol number %d not found; You might want to add "
5259 "this to /etc/protocols\n", number );
5260 SetLastError(WSANO_DATA);
5262 LeaveCriticalSection( &csWSgetXXXbyYYY );
5263 #endif
5264 TRACE("%i ret %p\n", number, retval);
5265 return retval;
5269 /***********************************************************************
5270 * getservbyname (WS2_32.55)
5272 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
5274 struct WS_servent* retval = NULL;
5275 struct servent* serv;
5276 char *name_str;
5277 char *proto_str = NULL;
5279 if (!(name_str = strdup_lower(name))) return NULL;
5281 if (proto && *proto)
5283 if (!(proto_str = strdup_lower(proto)))
5285 HeapFree( GetProcessHeap(), 0, name_str );
5286 return NULL;
5290 EnterCriticalSection( &csWSgetXXXbyYYY );
5291 serv = getservbyname(name_str, proto_str);
5292 if( serv != NULL )
5294 retval = WS_dup_se(serv);
5296 else SetLastError(WSANO_DATA);
5297 LeaveCriticalSection( &csWSgetXXXbyYYY );
5298 HeapFree( GetProcessHeap(), 0, proto_str );
5299 HeapFree( GetProcessHeap(), 0, name_str );
5300 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
5301 return retval;
5304 /***********************************************************************
5305 * freeaddrinfo (WS2_32.@)
5307 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
5309 while (res) {
5310 struct WS_addrinfo *next;
5312 HeapFree(GetProcessHeap(),0,res->ai_canonname);
5313 HeapFree(GetProcessHeap(),0,res->ai_addr);
5314 next = res->ai_next;
5315 HeapFree(GetProcessHeap(),0,res);
5316 res = next;
5320 /* helper functions for getaddrinfo()/getnameinfo() */
5321 static int convert_aiflag_w2u(int winflags) {
5322 unsigned int i;
5323 int unixflags = 0;
5325 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
5326 if (ws_aiflag_map[i][0] & winflags) {
5327 unixflags |= ws_aiflag_map[i][1];
5328 winflags &= ~ws_aiflag_map[i][0];
5330 if (winflags)
5331 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
5332 return unixflags;
5335 static int convert_niflag_w2u(int winflags) {
5336 unsigned int i;
5337 int unixflags = 0;
5339 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
5340 if (ws_niflag_map[i][0] & winflags) {
5341 unixflags |= ws_niflag_map[i][1];
5342 winflags &= ~ws_niflag_map[i][0];
5344 if (winflags)
5345 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
5346 return unixflags;
5349 static int convert_aiflag_u2w(int unixflags) {
5350 unsigned int i;
5351 int winflags = 0;
5353 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
5354 if (ws_aiflag_map[i][1] & unixflags) {
5355 winflags |= ws_aiflag_map[i][0];
5356 unixflags &= ~ws_aiflag_map[i][1];
5358 if (unixflags) /* will warn usually */
5359 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
5360 return winflags;
5363 static int convert_eai_u2w(int unixret) {
5364 int i;
5366 for (i=0;ws_eai_map[i][0];i++)
5367 if (ws_eai_map[i][1] == unixret)
5368 return ws_eai_map[i][0];
5369 return unixret;
5372 static char *get_hostname(void)
5374 char *ret;
5375 DWORD size = 0;
5377 GetComputerNameExA( ComputerNamePhysicalDnsHostname, NULL, &size );
5378 if (GetLastError() != ERROR_MORE_DATA) return NULL;
5379 if (!(ret = HeapAlloc( GetProcessHeap(), 0, size ))) return NULL;
5380 if (!GetComputerNameExA( ComputerNamePhysicalDnsHostname, ret, &size ))
5382 HeapFree( GetProcessHeap(), 0, ret );
5383 return NULL;
5385 return ret;
5388 /***********************************************************************
5389 * getaddrinfo (WS2_32.@)
5391 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
5393 #ifdef HAVE_GETADDRINFO
5394 struct addrinfo *unixaires = NULL;
5395 int result;
5396 struct addrinfo unixhints, *punixhints = NULL;
5397 char *hostname = NULL;
5398 const char *node;
5400 if (!nodename && !servname) return WSAHOST_NOT_FOUND;
5402 if (!nodename)
5403 node = NULL;
5404 else if (!nodename[0])
5406 node = hostname = get_hostname();
5407 if (!node) return WSA_NOT_ENOUGH_MEMORY;
5409 else
5410 node = nodename;
5412 if (hints) {
5413 punixhints = &unixhints;
5415 memset(&unixhints, 0, sizeof(unixhints));
5416 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
5417 if (hints->ai_family == 0) /* wildcard, specific to getaddrinfo() */
5418 punixhints->ai_family = 0;
5419 else
5420 punixhints->ai_family = convert_af_w2u(hints->ai_family);
5421 if (hints->ai_socktype == 0) /* wildcard, specific to getaddrinfo() */
5422 punixhints->ai_socktype = 0;
5423 else
5424 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
5425 if (hints->ai_protocol == 0) /* wildcard, specific to getaddrinfo() */
5426 punixhints->ai_protocol = 0;
5427 else
5428 punixhints->ai_protocol = convert_proto_w2u(hints->ai_protocol);
5431 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
5432 result = getaddrinfo(node, servname, punixhints, &unixaires);
5434 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
5435 HeapFree(GetProcessHeap(), 0, hostname);
5437 if (!result) {
5438 struct addrinfo *xuai = unixaires;
5439 struct WS_addrinfo **xai = res;
5441 *xai = NULL;
5442 while (xuai) {
5443 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
5444 int len;
5446 if (!ai)
5447 goto outofmem;
5449 *xai = ai;xai = &ai->ai_next;
5450 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
5451 ai->ai_family = convert_af_u2w(xuai->ai_family);
5452 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
5453 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
5454 if (xuai->ai_canonname) {
5455 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
5456 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
5457 if (!ai->ai_canonname)
5458 goto outofmem;
5459 strcpy(ai->ai_canonname,xuai->ai_canonname);
5461 len = xuai->ai_addrlen;
5462 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
5463 if (!ai->ai_addr)
5464 goto outofmem;
5465 ai->ai_addrlen = len;
5466 do {
5467 int winlen = ai->ai_addrlen;
5469 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
5470 ai->ai_addrlen = winlen;
5471 break;
5473 len = 2*len;
5474 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
5475 if (!ai->ai_addr)
5476 goto outofmem;
5477 ai->ai_addrlen = len;
5478 } while (1);
5479 xuai = xuai->ai_next;
5481 freeaddrinfo(unixaires);
5482 } else {
5483 result = convert_eai_u2w(result);
5484 *res = NULL;
5486 return result;
5488 outofmem:
5489 if (*res) WS_freeaddrinfo(*res);
5490 if (unixaires) freeaddrinfo(unixaires);
5491 *res = NULL;
5492 return WSA_NOT_ENOUGH_MEMORY;
5493 #else
5494 FIXME("getaddrinfo() failed, not found during buildtime.\n");
5495 return EAI_FAIL;
5496 #endif
5499 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
5501 struct WS_addrinfoW *ret;
5503 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
5504 ret->ai_flags = ai->ai_flags;
5505 ret->ai_family = ai->ai_family;
5506 ret->ai_socktype = ai->ai_socktype;
5507 ret->ai_protocol = ai->ai_protocol;
5508 ret->ai_addrlen = ai->ai_addrlen;
5509 ret->ai_canonname = NULL;
5510 ret->ai_addr = NULL;
5511 ret->ai_next = NULL;
5512 if (ai->ai_canonname)
5514 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
5515 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
5517 HeapFree(GetProcessHeap(), 0, ret);
5518 return NULL;
5520 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
5522 if (ai->ai_addr)
5524 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
5526 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
5527 HeapFree(GetProcessHeap(), 0, ret);
5528 return NULL;
5530 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
5532 return ret;
5535 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
5537 struct WS_addrinfoW *ret, *infoW;
5539 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
5540 while (info->ai_next)
5542 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
5544 FreeAddrInfoW(ret);
5545 return NULL;
5547 infoW = infoW->ai_next;
5548 info = info->ai_next;
5550 return ret;
5553 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
5555 struct WS_addrinfo *ret;
5557 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
5558 ret->ai_flags = ai->ai_flags;
5559 ret->ai_family = ai->ai_family;
5560 ret->ai_socktype = ai->ai_socktype;
5561 ret->ai_protocol = ai->ai_protocol;
5562 ret->ai_addrlen = ai->ai_addrlen;
5563 ret->ai_canonname = NULL;
5564 ret->ai_addr = NULL;
5565 ret->ai_next = NULL;
5566 if (ai->ai_canonname)
5568 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
5569 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
5571 HeapFree(GetProcessHeap(), 0, ret);
5572 return NULL;
5574 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
5576 if (ai->ai_addr)
5578 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
5580 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
5581 HeapFree(GetProcessHeap(), 0, ret);
5582 return NULL;
5584 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
5586 return ret;
5589 /***********************************************************************
5590 * GetAddrInfoW (WS2_32.@)
5592 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
5594 int ret, len;
5595 char *nodenameA = NULL, *servnameA = NULL;
5596 struct WS_addrinfo *resA, *hintsA = NULL;
5598 if (nodename)
5600 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
5601 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
5602 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
5604 if (servname)
5606 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
5607 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
5609 HeapFree(GetProcessHeap(), 0, nodenameA);
5610 return EAI_MEMORY;
5612 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
5615 if (hints) hintsA = addrinfo_WtoA(hints);
5616 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
5617 WS_freeaddrinfo(hintsA);
5619 if (!ret)
5621 *res = addrinfo_list_AtoW(resA);
5622 WS_freeaddrinfo(resA);
5625 HeapFree(GetProcessHeap(), 0, nodenameA);
5626 HeapFree(GetProcessHeap(), 0, servnameA);
5627 return ret;
5630 /***********************************************************************
5631 * FreeAddrInfoW (WS2_32.@)
5633 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
5635 while (ai)
5637 ADDRINFOW *next;
5638 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
5639 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
5640 next = ai->ai_next;
5641 HeapFree(GetProcessHeap(), 0, ai);
5642 ai = next;
5646 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
5647 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
5649 #ifdef HAVE_GETNAMEINFO
5650 int ret;
5651 union generic_unix_sockaddr sa_u;
5652 unsigned int size;
5654 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
5655 serv, servlen, flags);
5657 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
5658 if (!size)
5660 WSASetLastError(WSAEFAULT);
5661 return WSA_NOT_ENOUGH_MEMORY;
5663 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
5664 return convert_eai_u2w(ret);
5665 #else
5666 FIXME("getnameinfo() failed, not found during buildtime.\n");
5667 return EAI_FAIL;
5668 #endif
5671 int WINAPI GetNameInfoW(const SOCKADDR *sa, WS_socklen_t salen, PWCHAR host,
5672 DWORD hostlen, PWCHAR serv, DWORD servlen, INT flags)
5674 int ret;
5675 char *hostA = NULL, *servA = NULL;
5677 if (host && (!(hostA = HeapAlloc(GetProcessHeap(), 0, hostlen)))) return EAI_MEMORY;
5678 if (serv && (!(servA = HeapAlloc(GetProcessHeap(), 0, servlen))))
5680 HeapFree(GetProcessHeap(), 0, hostA);
5681 return EAI_MEMORY;
5684 ret = WS_getnameinfo(sa, salen, hostA, hostlen, servA, servlen, flags);
5685 if (!ret)
5687 if (host) MultiByteToWideChar(CP_ACP, 0, hostA, -1, host, hostlen);
5688 if (serv) MultiByteToWideChar(CP_ACP, 0, servA, -1, serv, servlen);
5691 HeapFree(GetProcessHeap(), 0, hostA);
5692 HeapFree(GetProcessHeap(), 0, servA);
5693 return ret;
5696 /***********************************************************************
5697 * getservbyport (WS2_32.56)
5699 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
5701 struct WS_servent* retval = NULL;
5702 #ifdef HAVE_GETSERVBYPORT
5703 struct servent* serv;
5704 char *proto_str = NULL;
5706 if (proto && *proto)
5708 if (!(proto_str = strdup_lower(proto))) return NULL;
5710 EnterCriticalSection( &csWSgetXXXbyYYY );
5711 if( (serv = getservbyport(port, proto_str)) != NULL ) {
5712 retval = WS_dup_se(serv);
5714 else SetLastError(WSANO_DATA);
5715 LeaveCriticalSection( &csWSgetXXXbyYYY );
5716 HeapFree( GetProcessHeap(), 0, proto_str );
5717 #endif
5718 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
5719 return retval;
5723 /***********************************************************************
5724 * gethostname (WS2_32.57)
5726 int WINAPI WS_gethostname(char *name, int namelen)
5728 TRACE("name %p, len %d\n", name, namelen);
5730 if (gethostname(name, namelen) == 0)
5732 TRACE("<- '%s'\n", name);
5733 return 0;
5735 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
5736 TRACE("<- ERROR !\n");
5737 return SOCKET_ERROR;
5741 /* ------------------------------------- Windows sockets extensions -- *
5743 * ------------------------------------------------------------------- */
5745 /***********************************************************************
5746 * WSAEnumNetworkEvents (WS2_32.36)
5748 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
5750 int ret;
5751 int i;
5752 int errors[FD_MAX_EVENTS];
5754 TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
5756 SERVER_START_REQ( get_socket_event )
5758 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5759 req->service = TRUE;
5760 req->c_event = wine_server_obj_handle( hEvent );
5761 wine_server_set_reply( req, errors, sizeof(errors) );
5762 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
5764 SERVER_END_REQ;
5765 if (!ret)
5767 for (i = 0; i < FD_MAX_EVENTS; i++)
5768 lpEvent->iErrorCode[i] = NtStatusToWSAError(errors[i]);
5769 return 0;
5771 SetLastError(WSAEINVAL);
5772 return SOCKET_ERROR;
5775 /***********************************************************************
5776 * WSAEventSelect (WS2_32.39)
5778 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
5780 int ret;
5782 TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
5784 SERVER_START_REQ( set_socket_event )
5786 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5787 req->mask = lEvent;
5788 req->event = wine_server_obj_handle( hEvent );
5789 req->window = 0;
5790 req->msg = 0;
5791 ret = wine_server_call( req );
5793 SERVER_END_REQ;
5794 if (!ret) return 0;
5795 SetLastError(WSAEINVAL);
5796 return SOCKET_ERROR;
5799 /**********************************************************************
5800 * WSAGetOverlappedResult (WS2_32.40)
5802 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
5803 LPDWORD lpcbTransfer, BOOL fWait,
5804 LPDWORD lpdwFlags )
5806 NTSTATUS status;
5808 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
5809 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
5811 if ( lpOverlapped == NULL )
5813 ERR( "Invalid pointer\n" );
5814 WSASetLastError(WSA_INVALID_PARAMETER);
5815 return FALSE;
5818 status = lpOverlapped->Internal;
5819 if (status == STATUS_PENDING)
5821 if (!fWait)
5823 SetLastError( WSA_IO_INCOMPLETE );
5824 return FALSE;
5827 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
5828 INFINITE ) == WAIT_FAILED)
5829 return FALSE;
5830 status = lpOverlapped->Internal;
5833 if ( lpcbTransfer )
5834 *lpcbTransfer = lpOverlapped->InternalHigh;
5836 if ( lpdwFlags )
5837 *lpdwFlags = lpOverlapped->u.s.Offset;
5839 if (status) SetLastError( RtlNtStatusToDosError(status) );
5840 return !status;
5844 /***********************************************************************
5845 * WSAAsyncSelect (WS2_32.101)
5847 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
5849 int ret;
5851 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
5853 SERVER_START_REQ( set_socket_event )
5855 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5856 req->mask = lEvent;
5857 req->event = 0;
5858 req->window = wine_server_user_handle( hWnd );
5859 req->msg = uMsg;
5860 ret = wine_server_call( req );
5862 SERVER_END_REQ;
5863 if (!ret) return 0;
5864 SetLastError(WSAEINVAL);
5865 return SOCKET_ERROR;
5868 /***********************************************************************
5869 * WSACreateEvent (WS2_32.31)
5872 WSAEVENT WINAPI WSACreateEvent(void)
5874 /* Create a manual-reset event, with initial state: unsignaled */
5875 TRACE("\n");
5877 return CreateEventW(NULL, TRUE, FALSE, NULL);
5880 /***********************************************************************
5881 * WSACloseEvent (WS2_32.29)
5884 BOOL WINAPI WSACloseEvent(WSAEVENT event)
5886 TRACE ("event=%p\n", event);
5888 return CloseHandle(event);
5891 /***********************************************************************
5892 * WSASocketA (WS2_32.78)
5895 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
5896 LPWSAPROTOCOL_INFOA lpProtocolInfo,
5897 GROUP g, DWORD dwFlags)
5899 INT len;
5900 WSAPROTOCOL_INFOW info;
5902 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
5903 af, type, protocol, lpProtocolInfo, g, dwFlags);
5905 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
5907 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
5908 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
5909 info.szProtocol, WSAPROTOCOL_LEN + 1);
5911 if (!len)
5913 WSASetLastError( WSAEINVAL);
5914 return SOCKET_ERROR;
5917 return WSASocketW(af, type, protocol, &info, g, dwFlags);
5920 /***********************************************************************
5921 * WSASocketW (WS2_32.79)
5924 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
5925 LPWSAPROTOCOL_INFOW lpProtocolInfo,
5926 GROUP g, DWORD dwFlags)
5928 SOCKET ret;
5929 DWORD err;
5930 int unixaf, unixtype;
5933 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
5934 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
5937 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
5938 af, type, protocol, lpProtocolInfo, g, dwFlags );
5940 if (!num_startup)
5942 err = WSANOTINITIALISED;
5943 goto done;
5946 /* hack for WSADuplicateSocket */
5947 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
5948 ret = lpProtocolInfo->dwServiceFlags3;
5949 TRACE("\tgot duplicate %04lx\n", ret);
5950 return ret;
5953 if (lpProtocolInfo)
5955 if (af == FROM_PROTOCOL_INFO || !af)
5956 af = lpProtocolInfo->iAddressFamily;
5957 if (type == FROM_PROTOCOL_INFO || !type)
5958 type = lpProtocolInfo->iSocketType;
5959 if (protocol == FROM_PROTOCOL_INFO || !protocol)
5960 protocol = lpProtocolInfo->iProtocol;
5963 if (!type && (af || protocol))
5965 WSAPROTOCOL_INFOW infow;
5967 /* default to the first valid protocol */
5968 if (!protocol)
5969 protocol = valid_protocols[0];
5971 if (WS_EnterSingleProtocolW(protocol, &infow))
5973 type = infow.iSocketType;
5975 /* after win2003 it's no longer possible to pass AF_UNSPEC
5976 using the protocol info struct */
5977 if (!lpProtocolInfo && af == WS_AF_UNSPEC)
5978 af = infow.iAddressFamily;
5982 /* convert the socket family, type and protocol */
5983 unixaf = convert_af_w2u(af);
5984 unixtype = convert_socktype_w2u(type);
5985 protocol = convert_proto_w2u(protocol);
5986 if (unixaf == AF_UNSPEC) unixaf = -1;
5988 /* filter invalid parameters */
5989 if (protocol < 0)
5991 /* the type could not be converted */
5992 if (type && unixtype < 0)
5994 err = WSAESOCKTNOSUPPORT;
5995 goto done;
5998 err = WSAEPROTONOSUPPORT;
5999 goto done;
6001 if (unixaf < 0)
6003 /* both family and protocol can't be invalid */
6004 if (protocol <= 0)
6006 err = WSAEINVAL;
6007 goto done;
6010 /* family could not be converted and neither socket type */
6011 if (unixtype < 0 && af >= 0)
6014 err = WSAESOCKTNOSUPPORT;
6015 goto done;
6018 err = WSAEAFNOSUPPORT;
6019 goto done;
6022 SERVER_START_REQ( create_socket )
6024 req->family = unixaf;
6025 req->type = unixtype;
6026 req->protocol = protocol;
6027 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
6028 req->attributes = OBJ_INHERIT;
6029 req->flags = dwFlags;
6030 set_error( wine_server_call( req ) );
6031 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
6033 SERVER_END_REQ;
6034 if (ret)
6036 TRACE("\tcreated %04lx\n", ret );
6037 return ret;
6040 err = GetLastError();
6041 if (err == WSAEACCES) /* raw socket denied */
6043 if (type == SOCK_RAW)
6044 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
6045 else
6046 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
6048 else
6050 /* invalid combination of valid parameters, like SOCK_STREAM + IPPROTO_UDP */
6051 if (err == WSAEINVAL)
6052 err = WSAESOCKTNOSUPPORT;
6053 else if (err == WSAEOPNOTSUPP)
6054 err = WSAEPROTONOSUPPORT;
6057 done:
6058 WARN("\t\tfailed, error %d!\n", err);
6059 SetLastError(err);
6060 return INVALID_SOCKET;
6063 /***********************************************************************
6064 * WSAJoinLeaf (WS2_32.58)
6067 SOCKET WINAPI WSAJoinLeaf(
6068 SOCKET s,
6069 const struct WS_sockaddr *addr,
6070 int addrlen,
6071 LPWSABUF lpCallerData,
6072 LPWSABUF lpCalleeData,
6073 LPQOS lpSQOS,
6074 LPQOS lpGQOS,
6075 DWORD dwFlags)
6077 FIXME("stub.\n");
6078 return INVALID_SOCKET;
6081 /***********************************************************************
6082 * __WSAFDIsSet (WS2_32.151)
6084 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
6086 int i = set->fd_count;
6088 TRACE("(%ld,%p(%i))\n", s, set, i);
6090 while (i--)
6091 if (set->fd_array[i] == s) return 1;
6092 return 0;
6095 /***********************************************************************
6096 * WSAIsBlocking (WS2_32.114)
6098 BOOL WINAPI WSAIsBlocking(void)
6100 /* By default WinSock should set all its sockets to non-blocking mode
6101 * and poll in PeekMessage loop when processing "blocking" ones. This
6102 * function is supposed to tell if the program is in this loop. Our
6103 * blocking calls are truly blocking so we always return FALSE.
6105 * Note: It is allowed to call this function without prior WSAStartup().
6108 TRACE("\n");
6109 return FALSE;
6112 /***********************************************************************
6113 * WSACancelBlockingCall (WS2_32.113)
6115 INT WINAPI WSACancelBlockingCall(void)
6117 TRACE("\n");
6118 return 0;
6121 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
6123 FIXME("How was this called?\n");
6124 return x();
6128 /***********************************************************************
6129 * WSASetBlockingHook (WS2_32.109)
6131 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
6133 FARPROC prev = blocking_hook;
6134 blocking_hook = lpBlockFunc;
6135 TRACE("hook %p\n", lpBlockFunc);
6136 return prev;
6140 /***********************************************************************
6141 * WSAUnhookBlockingHook (WS2_32.110)
6143 INT WINAPI WSAUnhookBlockingHook(void)
6145 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
6146 return 0;
6150 /* ----------------------------------- end of API stuff */
6152 /* ----------------------------------- helper functions -
6154 * TODO: Merge WS_dup_..() stuff into one function that
6155 * would operate with a generic structure containing internal
6156 * pointers (via a template of some kind).
6159 static int list_size(char** l, int item_size)
6161 int i,j = 0;
6162 if(l)
6163 { for(i=0;l[i];i++)
6164 j += (item_size) ? item_size : strlen(l[i]) + 1;
6165 j += (i + 1) * sizeof(char*); }
6166 return j;
6169 static int list_dup(char** l_src, char** l_to, int item_size)
6171 char *p;
6172 int i;
6174 for (i = 0; l_src[i]; i++) ;
6175 p = (char *)(l_to + i + 1);
6176 for (i = 0; l_src[i]; i++)
6178 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
6179 memcpy(p, l_src[i], count);
6180 l_to[i] = p;
6181 p += count;
6183 l_to[i] = NULL;
6184 return p - (char *)l_to;
6187 /* ----- hostent */
6189 /* create a hostent entry
6191 * Creates the entry with enough memory for the name, aliases
6192 * addresses, and the address pointers. Also copies the name
6193 * and sets up all the pointers.
6195 * NOTE: The alias and address lists must be allocated with room
6196 * for the NULL item terminating the list. This is true even if
6197 * the list has no items ("aliases" and "addresses" must be
6198 * at least "1", a truly empty list is invalid).
6200 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length)
6202 struct WS_hostent *p_to;
6203 char *p;
6204 int size = (sizeof(struct WS_hostent) +
6205 strlen(name) + 1 +
6206 sizeof(char *) * aliases +
6207 aliases_size +
6208 sizeof(char *) * addresses +
6209 address_length * (addresses - 1)), i;
6211 if (!(p_to = check_buffer_he(size))) return NULL;
6212 memset(p_to, 0, size);
6214 /* Use the memory in the same way winsock does.
6215 * First set the pointer for aliases, second set the pointers for addresses.
6216 * Third fill the addresses indexes, fourth jump aliases names size.
6217 * Fifth fill the hostname.
6218 * NOTE: This method is valid for OS version's >= XP.
6220 p = (char *)(p_to + 1);
6221 p_to->h_aliases = (char **)p;
6222 p += sizeof(char *)*aliases;
6224 p_to->h_addr_list = (char **)p;
6225 p += sizeof(char *)*addresses;
6227 for (i = 0, addresses--; i < addresses; i++, p += address_length)
6228 p_to->h_addr_list[i] = p;
6230 /* NOTE: h_aliases must be filled in manually because we don't know each string
6231 * size, leave these pointers NULL (already set to NULL by memset earlier).
6233 p += aliases_size;
6235 p_to->h_name = p;
6236 strcpy(p, name);
6238 return p_to;
6241 /* duplicate hostent entry
6242 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
6243 * Ditto for protoent and servent.
6245 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
6247 int i, addresses = 0, alias_size = 0;
6248 struct WS_hostent *p_to;
6249 char *p;
6251 for( i = 0; p_he->h_aliases[i]; i++) alias_size += strlen(p_he->h_aliases[i]) + 1;
6252 while (p_he->h_addr_list[addresses]) addresses++;
6254 p_to = WS_create_he(p_he->h_name, i + 1, alias_size, addresses + 1, p_he->h_length);
6256 if (!p_to) return NULL;
6257 p_to->h_addrtype = p_he->h_addrtype;
6258 p_to->h_length = p_he->h_length;
6260 for(i = 0, p = p_to->h_addr_list[0]; p_he->h_addr_list[i]; i++, p += p_to->h_length)
6261 memcpy(p, p_he->h_addr_list[i], p_to->h_length);
6263 /* Fill the aliases after the IP data */
6264 for(i = 0; p_he->h_aliases[i]; i++)
6266 p_to->h_aliases[i] = p;
6267 strcpy(p, p_he->h_aliases[i]);
6268 p += strlen(p) + 1;
6271 return p_to;
6274 /* ----- protoent */
6276 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
6278 char *p;
6279 struct WS_protoent *p_to;
6281 int size = (sizeof(*p_pe) +
6282 strlen(p_pe->p_name) + 1 +
6283 list_size(p_pe->p_aliases, 0));
6285 if (!(p_to = check_buffer_pe(size))) return NULL;
6286 p_to->p_proto = p_pe->p_proto;
6288 p = (char *)(p_to + 1);
6289 p_to->p_name = p;
6290 strcpy(p, p_pe->p_name);
6291 p += strlen(p) + 1;
6293 p_to->p_aliases = (char **)p;
6294 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
6295 return p_to;
6298 /* ----- servent */
6300 static struct WS_servent *WS_dup_se(const struct servent* p_se)
6302 char *p;
6303 struct WS_servent *p_to;
6305 int size = (sizeof(*p_se) +
6306 strlen(p_se->s_proto) + 1 +
6307 strlen(p_se->s_name) + 1 +
6308 list_size(p_se->s_aliases, 0));
6310 if (!(p_to = check_buffer_se(size))) return NULL;
6311 p_to->s_port = p_se->s_port;
6313 p = (char *)(p_to + 1);
6314 p_to->s_name = p;
6315 strcpy(p, p_se->s_name);
6316 p += strlen(p) + 1;
6318 p_to->s_proto = p;
6319 strcpy(p, p_se->s_proto);
6320 p += strlen(p) + 1;
6322 p_to->s_aliases = (char **)p;
6323 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
6324 return p_to;
6328 /***********************************************************************
6329 * WSARecv (WS2_32.67)
6331 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6332 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
6333 LPWSAOVERLAPPED lpOverlapped,
6334 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
6336 return WS2_recv_base(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
6337 NULL, NULL, lpOverlapped, lpCompletionRoutine, NULL);
6340 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6341 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
6342 struct WS_sockaddr *lpFrom,
6343 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
6344 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
6345 LPWSABUF lpControlBuffer )
6347 unsigned int i, options;
6348 int n, fd, err;
6349 struct ws2_async *wsa;
6350 BOOL is_blocking;
6351 DWORD timeout_start = GetTickCount();
6352 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
6354 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
6355 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
6356 (lpFromlen ? *lpFromlen : -1),
6357 lpOverlapped, lpCompletionRoutine);
6359 fd = get_sock_fd( s, FILE_READ_DATA, &options );
6360 TRACE( "fd=%d, options=%x\n", fd, options );
6362 if (fd == -1) return SOCKET_ERROR;
6364 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
6366 err = WSAEFAULT;
6367 goto error;
6370 wsa->hSocket = SOCKET2HANDLE(s);
6371 wsa->flags = *lpFlags;
6372 wsa->lpFlags = lpFlags;
6373 wsa->addr = lpFrom;
6374 wsa->addrlen.ptr = lpFromlen;
6375 wsa->control = lpControlBuffer;
6376 wsa->n_iovecs = dwBufferCount;
6377 wsa->first_iovec = 0;
6378 for (i = 0; i < dwBufferCount; i++)
6380 /* check buffer first to trigger write watches */
6381 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
6383 err = WSAEFAULT;
6384 goto error;
6386 wsa->iovec[i].iov_base = lpBuffers[i].buf;
6387 wsa->iovec[i].iov_len = lpBuffers[i].len;
6390 for (;;)
6392 n = WS2_recv( fd, wsa );
6393 if (n == -1)
6395 if (errno == EINTR) continue;
6396 if (errno != EAGAIN)
6398 int loc_errno = errno;
6399 err = wsaErrno();
6400 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
6401 goto error;
6404 else if (lpNumberOfBytesRecvd) *lpNumberOfBytesRecvd = n;
6406 if ((lpOverlapped || lpCompletionRoutine) &&
6407 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
6409 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
6411 wsa->user_overlapped = lpOverlapped;
6412 wsa->completion_func = lpCompletionRoutine;
6413 release_sock_fd( s, fd );
6415 if (n == -1)
6417 iosb->u.Status = STATUS_PENDING;
6418 iosb->Information = 0;
6420 SERVER_START_REQ( register_async )
6422 req->type = ASYNC_TYPE_READ;
6423 req->async.handle = wine_server_obj_handle( wsa->hSocket );
6424 req->async.callback = wine_server_client_ptr( WS2_async_recv );
6425 req->async.iosb = wine_server_client_ptr( iosb );
6426 req->async.arg = wine_server_client_ptr( wsa );
6427 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
6428 req->async.cvalue = cvalue;
6429 err = wine_server_call( req );
6431 SERVER_END_REQ;
6433 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
6434 WSASetLastError( NtStatusToWSAError( err ));
6435 return SOCKET_ERROR;
6438 iosb->u.Status = STATUS_SUCCESS;
6439 iosb->Information = n;
6440 if (!wsa->completion_func)
6442 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
6443 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
6444 HeapFree( GetProcessHeap(), 0, wsa );
6446 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
6447 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
6448 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6449 return 0;
6452 if (n != -1) break;
6454 if ((err = _is_blocking( s, &is_blocking )))
6456 err = NtStatusToWSAError( err );
6457 goto error;
6460 if ( is_blocking )
6462 struct pollfd pfd;
6463 int timeout = GET_RCVTIMEO(fd);
6464 if (timeout != -1)
6466 timeout -= GetTickCount() - timeout_start;
6467 if (timeout < 0) timeout = 0;
6470 pfd.fd = fd;
6471 pfd.events = POLLIN;
6472 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
6474 if (!timeout || !poll( &pfd, 1, timeout ))
6476 err = WSAETIMEDOUT;
6477 /* a timeout is not fatal */
6478 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6479 goto error;
6482 else
6484 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6485 err = WSAEWOULDBLOCK;
6486 goto error;
6490 TRACE(" -> %i bytes\n", n);
6491 HeapFree( GetProcessHeap(), 0, wsa );
6492 release_sock_fd( s, fd );
6493 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6495 return 0;
6497 error:
6498 HeapFree( GetProcessHeap(), 0, wsa );
6499 release_sock_fd( s, fd );
6500 WARN(" -> ERROR %d\n", err);
6501 WSASetLastError( err );
6502 return SOCKET_ERROR;
6505 /***********************************************************************
6506 * WSARecvFrom (WS2_32.69)
6508 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6509 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
6510 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
6511 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
6514 return WS2_recv_base( s, lpBuffers, dwBufferCount,
6515 lpNumberOfBytesRecvd, lpFlags,
6516 lpFrom, lpFromlen,
6517 lpOverlapped, lpCompletionRoutine, NULL );
6520 /***********************************************************************
6521 * WSCInstallProvider (WS2_32.88)
6523 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
6524 LPCWSTR lpszProviderDllPath,
6525 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
6526 DWORD dwNumberOfEntries,
6527 LPINT lpErrno )
6529 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
6530 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
6531 dwNumberOfEntries, lpErrno);
6532 *lpErrno = 0;
6533 return 0;
6537 /***********************************************************************
6538 * WSCDeinstallProvider (WS2_32.83)
6540 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
6542 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
6543 *lpErrno = 0;
6544 return 0;
6548 /***********************************************************************
6549 * WSAAccept (WS2_32.26)
6551 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
6552 LPCONDITIONPROC lpfnCondition, DWORD_PTR dwCallbackData)
6555 int ret = 0, size = 0;
6556 WSABUF CallerId, CallerData, CalleeId, CalleeData;
6557 /* QOS SQOS, GQOS; */
6558 GROUP g;
6559 SOCKET cs;
6560 SOCKADDR src_addr, dst_addr;
6562 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
6563 s, addr, addrlen, lpfnCondition, dwCallbackData);
6566 size = sizeof(src_addr);
6567 cs = WS_accept(s, &src_addr, &size);
6569 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
6571 if (!lpfnCondition) return cs;
6573 CallerId.buf = (char *)&src_addr;
6574 CallerId.len = sizeof(src_addr);
6576 CallerData.buf = NULL;
6577 CallerData.len = 0;
6579 WS_getsockname(cs, &dst_addr, &size);
6581 CalleeId.buf = (char *)&dst_addr;
6582 CalleeId.len = sizeof(dst_addr);
6585 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
6586 &CalleeId, &CalleeData, &g, dwCallbackData);
6588 switch (ret)
6590 case CF_ACCEPT:
6591 if (addr && addrlen)
6592 memcpy(addr, &src_addr, (*addrlen > size) ? size : *addrlen );
6593 return cs;
6594 case CF_DEFER:
6595 SERVER_START_REQ( set_socket_deferred )
6597 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6598 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
6599 if ( !wine_server_call_err ( req ) )
6601 SetLastError( WSATRY_AGAIN );
6602 WS_closesocket( cs );
6605 SERVER_END_REQ;
6606 return SOCKET_ERROR;
6607 case CF_REJECT:
6608 WS_closesocket(cs);
6609 SetLastError(WSAECONNREFUSED);
6610 return SOCKET_ERROR;
6611 default:
6612 FIXME("Unknown return type from Condition function\n");
6613 SetLastError(WSAENOTSOCK);
6614 return SOCKET_ERROR;
6618 /***********************************************************************
6619 * WSADuplicateSocketA (WS2_32.32)
6621 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
6623 return WS_DuplicateSocket(FALSE, s, dwProcessId, (LPWSAPROTOCOL_INFOW) lpProtocolInfo);
6626 /***********************************************************************
6627 * WSADuplicateSocketW (WS2_32.33)
6629 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
6631 return WS_DuplicateSocket(TRUE, s, dwProcessId, lpProtocolInfo);
6634 /***********************************************************************
6635 * WSAInstallServiceClassA (WS2_32.48)
6637 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
6639 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
6640 WSASetLastError(WSAEACCES);
6641 return SOCKET_ERROR;
6644 /***********************************************************************
6645 * WSAInstallServiceClassW (WS2_32.49)
6647 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
6649 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
6650 WSASetLastError(WSAEACCES);
6651 return SOCKET_ERROR;
6654 /***********************************************************************
6655 * WSARemoveServiceClass (WS2_32.70)
6657 int WINAPI WSARemoveServiceClass(LPGUID info)
6659 FIXME("Request to remove service %p\n",info);
6660 WSASetLastError(WSATYPE_NOT_FOUND);
6661 return SOCKET_ERROR;
6664 /***********************************************************************
6665 * inet_ntop (WS2_32.@)
6667 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
6669 #ifdef HAVE_INET_NTOP
6670 struct WS_in6_addr *in6;
6671 struct WS_in_addr *in;
6672 PCSTR pdst;
6674 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
6675 if (!buffer)
6677 WSASetLastError( STATUS_INVALID_PARAMETER );
6678 return NULL;
6681 switch (family)
6683 case WS_AF_INET:
6685 in = addr;
6686 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
6687 break;
6689 case WS_AF_INET6:
6691 in6 = addr;
6692 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
6693 break;
6695 default:
6696 WSASetLastError( WSAEAFNOSUPPORT );
6697 return NULL;
6700 if (!pdst) WSASetLastError( STATUS_INVALID_PARAMETER );
6701 return pdst;
6702 #else
6703 FIXME( "not supported on this platform\n" );
6704 WSASetLastError( WSAEAFNOSUPPORT );
6705 return NULL;
6706 #endif
6709 /***********************************************************************
6710 * WSAStringToAddressA (WS2_32.80)
6712 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
6713 INT AddressFamily,
6714 LPWSAPROTOCOL_INFOA lpProtocolInfo,
6715 LPSOCKADDR lpAddress,
6716 LPINT lpAddressLength)
6718 INT res=0;
6719 LPSTR workBuffer=NULL,ptrPort;
6721 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
6722 lpProtocolInfo, lpAddress, lpAddressLength );
6724 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
6726 if (!AddressString)
6728 WSASetLastError(WSAEINVAL);
6729 return SOCKET_ERROR;
6732 if (lpProtocolInfo)
6733 FIXME("ProtocolInfo not implemented.\n");
6735 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
6736 strlen(AddressString) + 1);
6737 if (!workBuffer)
6739 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6740 return SOCKET_ERROR;
6743 strcpy(workBuffer, AddressString);
6745 switch(AddressFamily)
6747 case WS_AF_INET:
6749 struct in_addr inetaddr;
6751 /* If lpAddressLength is too small, tell caller the size we need */
6752 if (*lpAddressLength < sizeof(SOCKADDR_IN))
6754 *lpAddressLength = sizeof(SOCKADDR_IN);
6755 res = WSAEFAULT;
6756 break;
6758 *lpAddressLength = sizeof(SOCKADDR_IN);
6759 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
6761 ((LPSOCKADDR_IN)lpAddress)->sin_family = AF_INET;
6763 ptrPort = strchr(workBuffer, ':');
6764 if(ptrPort)
6766 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
6767 *ptrPort = '\0';
6769 else
6771 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
6774 if(inet_aton(workBuffer, &inetaddr) > 0)
6776 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
6777 res = 0;
6779 else
6780 res = WSAEINVAL;
6782 break;
6785 case WS_AF_INET6:
6787 struct in6_addr inetaddr;
6788 /* If lpAddressLength is too small, tell caller the size we need */
6789 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
6791 *lpAddressLength = sizeof(SOCKADDR_IN6);
6792 res = WSAEFAULT;
6793 break;
6795 #ifdef HAVE_INET_PTON
6796 *lpAddressLength = sizeof(SOCKADDR_IN6);
6797 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
6799 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
6801 /* This one is a bit tricky. An IPv6 address contains colons, so the
6802 * check from IPv4 doesn't work like that. However, IPv6 addresses that
6803 * contain a port are written with braces like [fd12:3456:7890::1]:12345
6804 * so what we will do is to look for ']', check if the next char is a
6805 * colon, and if it is, parse the port as in IPv4. */
6807 ptrPort = strchr(workBuffer, ']');
6808 if(ptrPort && *(++ptrPort) == ':')
6810 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort+1));
6811 *ptrPort = '\0';
6813 else
6815 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
6818 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
6820 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
6821 sizeof(struct in6_addr));
6822 res = 0;
6824 else
6825 #endif /* HAVE_INET_PTON */
6826 res = WSAEINVAL;
6828 break;
6830 default:
6831 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
6832 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
6833 res = WSAEINVAL;
6836 HeapFree(GetProcessHeap(), 0, workBuffer);
6838 if (!res) return 0;
6839 WSASetLastError(res);
6840 return SOCKET_ERROR;
6843 /***********************************************************************
6844 * WSAStringToAddressW (WS2_32.81)
6846 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
6847 * If this should be the case, it would be required to map these digits
6848 * to Unicode digits (0-9) using FoldString first.
6850 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
6851 INT AddressFamily,
6852 LPWSAPROTOCOL_INFOW lpProtocolInfo,
6853 LPSOCKADDR lpAddress,
6854 LPINT lpAddressLength)
6856 INT sBuffer,res=0;
6857 LPSTR workBuffer=NULL;
6858 WSAPROTOCOL_INFOA infoA;
6859 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
6861 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
6862 lpAddress, lpAddressLength );
6864 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
6866 /* if ProtocolInfo is available - convert to ANSI variant */
6867 if (lpProtocolInfo)
6869 lpProtoInfoA = &infoA;
6870 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
6872 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
6873 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
6875 WSASetLastError( WSAEINVAL);
6876 return SOCKET_ERROR;
6880 if (AddressString)
6882 /* Translate AddressString to ANSI code page - assumes that only
6883 standard digits 0-9 are used with this API call */
6884 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
6885 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
6887 if (workBuffer)
6889 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
6890 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
6891 lpAddress,lpAddressLength);
6892 HeapFree( GetProcessHeap(), 0, workBuffer );
6893 return res;
6895 else
6896 res = WSA_NOT_ENOUGH_MEMORY;
6898 else
6899 res = WSAEINVAL;
6901 WSASetLastError(res);
6902 return SOCKET_ERROR;
6905 /***********************************************************************
6906 * WSAAddressToStringA (WS2_32.27)
6908 * See WSAAddressToStringW
6910 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
6911 LPWSAPROTOCOL_INFOA info, LPSTR string,
6912 LPDWORD lenstr )
6914 DWORD size;
6915 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
6916 CHAR *p;
6918 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
6920 if (!sockaddr) return SOCKET_ERROR;
6921 if (!string || !lenstr) return SOCKET_ERROR;
6923 switch(sockaddr->sa_family)
6925 case WS_AF_INET:
6926 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
6927 sprintf( buffer, "%u.%u.%u.%u:%u",
6928 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
6929 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
6930 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
6931 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
6932 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
6934 p = strchr( buffer, ':' );
6935 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
6936 break;
6938 case WS_AF_INET6:
6940 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
6942 buffer[0] = 0;
6943 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
6944 if ((sockaddr6->sin6_port))
6945 strcpy(buffer, "[");
6946 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, buffer+strlen(buffer), sizeof(buffer)))
6948 WSASetLastError(WSAEINVAL);
6949 return SOCKET_ERROR;
6951 if ((sockaddr6->sin6_scope_id))
6952 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
6953 if ((sockaddr6->sin6_port))
6954 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
6955 break;
6958 default:
6959 WSASetLastError(WSAEINVAL);
6960 return SOCKET_ERROR;
6963 size = strlen( buffer ) + 1;
6965 if (*lenstr < size)
6967 *lenstr = size;
6968 WSASetLastError(WSAEFAULT);
6969 return SOCKET_ERROR;
6972 *lenstr = size;
6973 strcpy( string, buffer );
6974 return 0;
6977 /***********************************************************************
6978 * WSAAddressToStringW (WS2_32.28)
6980 * Convert a sockaddr address into a readable address string.
6982 * PARAMS
6983 * sockaddr [I] Pointer to a sockaddr structure.
6984 * len [I] Size of the sockaddr structure.
6985 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
6986 * string [I/O] Pointer to a buffer to receive the address string.
6987 * lenstr [I/O] Size of the receive buffer in WCHARs.
6989 * RETURNS
6990 * Success: 0
6991 * Failure: SOCKET_ERROR
6993 * NOTES
6994 * The 'info' parameter is ignored.
6996 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
6997 LPWSAPROTOCOL_INFOW info, LPWSTR string,
6998 LPDWORD lenstr )
7000 INT ret;
7001 DWORD size;
7002 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
7003 CHAR bufAddr[54];
7005 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
7007 size = *lenstr;
7008 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
7010 if (ret) return ret;
7012 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
7014 if (*lenstr < size)
7016 *lenstr = size;
7017 WSASetLastError(WSAEFAULT);
7018 return SOCKET_ERROR;
7021 *lenstr = size;
7022 lstrcpyW( string, buffer );
7023 return 0;
7026 /***********************************************************************
7027 * WSAEnumNameSpaceProvidersA (WS2_32.34)
7029 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
7031 FIXME( "(%p %p) Stub!\n", len, buffer );
7032 return 0;
7035 /***********************************************************************
7036 * WSAEnumNameSpaceProvidersW (WS2_32.35)
7038 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
7040 FIXME( "(%p %p) Stub!\n", len, buffer );
7041 return 0;
7044 /***********************************************************************
7045 * WSAGetQOSByName (WS2_32.41)
7047 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
7049 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
7050 return FALSE;
7053 /***********************************************************************
7054 * WSAGetServiceClassInfoA (WS2_32.42)
7056 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
7057 LPWSASERVICECLASSINFOA info )
7059 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
7060 len, info );
7061 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7062 return SOCKET_ERROR;
7065 /***********************************************************************
7066 * WSAGetServiceClassInfoW (WS2_32.43)
7068 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
7069 LPWSASERVICECLASSINFOW info )
7071 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
7072 len, info );
7073 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7074 return SOCKET_ERROR;
7077 /***********************************************************************
7078 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
7080 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
7082 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
7083 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7084 return SOCKET_ERROR;
7087 /***********************************************************************
7088 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
7090 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
7092 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
7093 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7094 return SOCKET_ERROR;
7097 /***********************************************************************
7098 * WSALookupServiceBeginA (WS2_32.59)
7100 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
7101 DWORD dwControlFlags,
7102 LPHANDLE lphLookup)
7104 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
7105 lphLookup);
7106 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7107 return SOCKET_ERROR;
7110 /***********************************************************************
7111 * WSALookupServiceBeginW (WS2_32.60)
7113 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
7114 DWORD dwControlFlags,
7115 LPHANDLE lphLookup)
7117 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
7118 lphLookup);
7119 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7120 return SOCKET_ERROR;
7123 /***********************************************************************
7124 * WSALookupServiceEnd (WS2_32.61)
7126 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
7128 FIXME("(%p) Stub!\n", lookup );
7129 return 0;
7132 /***********************************************************************
7133 * WSALookupServiceNextA (WS2_32.62)
7135 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
7137 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
7138 WSASetLastError(WSA_E_NO_MORE);
7139 return SOCKET_ERROR;
7142 /***********************************************************************
7143 * WSALookupServiceNextW (WS2_32.63)
7145 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
7147 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
7148 WSASetLastError(WSA_E_NO_MORE);
7149 return SOCKET_ERROR;
7152 /***********************************************************************
7153 * WSANtohl (WS2_32.64)
7155 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
7157 TRACE( "(0x%04lx 0x%08x %p)\n", s, netlong, lphostlong );
7159 if (!lphostlong) return WSAEFAULT;
7161 *lphostlong = ntohl( netlong );
7162 return 0;
7165 /***********************************************************************
7166 * WSANtohs (WS2_32.65)
7168 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
7170 TRACE( "(0x%04lx 0x%08x %p)\n", s, netshort, lphostshort );
7172 if (!lphostshort) return WSAEFAULT;
7174 *lphostshort = ntohs( netshort );
7175 return 0;
7178 /***********************************************************************
7179 * WSAProviderConfigChange (WS2_32.66)
7181 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
7182 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
7184 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
7185 return SOCKET_ERROR;
7188 /***********************************************************************
7189 * WSARecvDisconnect (WS2_32.68)
7191 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
7193 TRACE( "(0x%04lx %p)\n", s, disconnectdata );
7195 return WS_shutdown( s, 0 );
7198 /***********************************************************************
7199 * WSASetServiceA (WS2_32.76)
7201 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
7203 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
7204 return 0;
7207 /***********************************************************************
7208 * WSASetServiceW (WS2_32.77)
7210 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
7212 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
7213 return 0;
7216 /***********************************************************************
7217 * WSCEnableNSProvider (WS2_32.84)
7219 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
7221 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
7222 return 0;
7225 /***********************************************************************
7226 * WSCGetProviderPath (WS2_32.86)
7228 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
7230 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
7232 if (!errcode || !provider || !len) return WSAEFAULT;
7234 *errcode = WSAEINVAL;
7235 return SOCKET_ERROR;
7238 /***********************************************************************
7239 * WSCInstallNameSpace (WS2_32.87)
7241 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
7242 DWORD version, LPGUID provider )
7244 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
7245 namespace, version, debugstr_guid(provider) );
7246 return 0;
7249 /***********************************************************************
7250 * WSCUnInstallNameSpace (WS2_32.89)
7252 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
7254 FIXME("(%p) Stub!\n", lpProviderId);
7255 return NO_ERROR;
7258 /***********************************************************************
7259 * WSCWriteProviderOrder (WS2_32.91)
7261 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
7263 FIXME("(%p 0x%08x) Stub!\n", entry, number);
7264 return 0;
7267 /***********************************************************************
7268 * WSANSPIoctl (WS2_32.91)
7270 INT WINAPI WSANSPIoctl( HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer,
7271 DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer,
7272 LPDWORD lpcbBytesReturned, LPWSACOMPLETION lpCompletion )
7274 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup, dwControlCode,
7275 lpvInBuffer, cbInBuffer, lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpCompletion);
7276 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7277 return SOCKET_ERROR;
7280 /*****************************************************************************
7281 * WSAEnumProtocolsA [WS2_32.@]
7283 * see function WSAEnumProtocolsW
7285 INT WINAPI WSAEnumProtocolsA( LPINT protocols, LPWSAPROTOCOL_INFOA buffer, LPDWORD len )
7287 return WS_EnumProtocols( FALSE, protocols, (LPWSAPROTOCOL_INFOW) buffer, len);
7290 /*****************************************************************************
7291 * WSAEnumProtocolsW [WS2_32.@]
7293 * Retrieves information about specified set of active network protocols.
7295 * PARAMS
7296 * protocols [I] Pointer to null-terminated array of protocol id's. NULL
7297 * retrieves information on all available protocols.
7298 * buffer [I] Pointer to a buffer to be filled with WSAPROTOCOL_INFO
7299 * structures.
7300 * len [I/O] Pointer to a variable specifying buffer size. On output
7301 * the variable holds the number of bytes needed when the
7302 * specified size is too small.
7304 * RETURNS
7305 * Success: number of WSAPROTOCOL_INFO structures in buffer.
7306 * Failure: SOCKET_ERROR
7308 * NOTES
7309 * NT4SP5 does not return SPX if protocols == NULL
7311 * BUGS
7312 * - NT4SP5 returns in addition these list of NETBIOS protocols
7313 * (address family 17), each entry two times one for socket type 2 and 5
7315 * iProtocol szProtocol
7316 * 0x80000000 \Device\NwlnkNb
7317 * 0xfffffffa \Device\NetBT_CBENT7
7318 * 0xfffffffb \Device\Nbf_CBENT7
7319 * 0xfffffffc \Device\NetBT_NdisWan5
7320 * 0xfffffffd \Device\NetBT_El9202
7321 * 0xfffffffe \Device\Nbf_El9202
7322 * 0xffffffff \Device\Nbf_NdisWan4
7324 * - there is no check that the operating system supports the returned
7325 * protocols
7327 INT WINAPI WSAEnumProtocolsW( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
7329 return WS_EnumProtocols( TRUE, protocols, buffer, len);
7332 /*****************************************************************************
7333 * WSCEnumProtocols [WS2_32.@]
7335 * PARAMS
7336 * protocols [I] Null-terminated array of iProtocol values.
7337 * buffer [O] Buffer of WSAPROTOCOL_INFOW structures.
7338 * len [I/O] Size of buffer on input/output.
7339 * errno [O] Error code.
7341 * RETURNS
7342 * Success: number of protocols to be reported on.
7343 * Failure: SOCKET_ERROR. error is in errno.
7345 * BUGS
7346 * Doesn't supply info on layered protocols.
7349 INT WINAPI WSCEnumProtocols( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len, LPINT err )
7351 INT ret = WSAEnumProtocolsW( protocols, buffer, len );
7353 if (ret == SOCKET_ERROR) *err = WSAENOBUFS;
7355 return ret;