ws2_32: Add missing else to getsockopt(SO_ACCEPTCONN).
[wine/wine-gecko.git] / dlls / ws2_32 / socket.c
blobfac090d6edbede848662e9adb7e1c41d9961abd3
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 fd = get_sock_fd( listener, FILE_READ_DATA, NULL );
2323 if (fd == -1)
2325 SetLastError(WSAENOTSOCK);
2326 return FALSE;
2328 release_sock_fd( listener, fd );
2330 fd = get_sock_fd( acceptor, FILE_READ_DATA, NULL );
2331 if (fd == -1)
2333 SetLastError(WSAEINVAL);
2334 return FALSE;
2336 release_sock_fd( acceptor, fd );
2338 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
2339 if(!wsa)
2341 SetLastError(WSAEFAULT);
2342 return FALSE;
2345 wsa->listen_socket = SOCKET2HANDLE(listener);
2346 wsa->accept_socket = SOCKET2HANDLE(acceptor);
2347 wsa->user_overlapped = overlapped;
2348 wsa->cvalue = cvalue;
2349 wsa->buf = dest;
2350 wsa->data_len = dest_len;
2351 wsa->local_len = local_addr_len;
2352 wsa->remote_len = rem_addr_len;
2353 wsa->read = NULL;
2355 if (wsa->data_len)
2357 /* set up a read request if we need it */
2358 wsa->read = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[1]) );
2359 if (!wsa->read)
2361 HeapFree( GetProcessHeap(), 0, wsa );
2362 SetLastError(WSAEFAULT);
2363 return FALSE;
2366 wsa->read->hSocket = wsa->accept_socket;
2367 wsa->read->flags = 0;
2368 wsa->read->lpFlags = &wsa->read->flags;
2369 wsa->read->addr = NULL;
2370 wsa->read->addrlen.ptr = NULL;
2371 wsa->read->control = NULL;
2372 wsa->read->n_iovecs = 1;
2373 wsa->read->first_iovec = 0;
2374 wsa->read->iovec[0].iov_base = wsa->buf;
2375 wsa->read->iovec[0].iov_len = wsa->data_len;
2378 SERVER_START_REQ( register_async )
2380 req->type = ASYNC_TYPE_READ;
2381 req->async.handle = wine_server_obj_handle( SOCKET2HANDLE(listener) );
2382 req->async.callback = wine_server_client_ptr( WS2_async_accept );
2383 req->async.iosb = wine_server_client_ptr( overlapped );
2384 req->async.arg = wine_server_client_ptr( wsa );
2385 req->async.cvalue = cvalue;
2386 /* We don't set event since we may also have to read */
2387 status = wine_server_call( req );
2389 SERVER_END_REQ;
2391 if(status != STATUS_PENDING)
2393 HeapFree( GetProcessHeap(), 0, wsa->read );
2394 HeapFree( GetProcessHeap(), 0, wsa );
2397 SetLastError( NtStatusToWSAError(status) );
2398 return FALSE;
2401 /***********************************************************************
2402 * GetAcceptExSockaddrs
2404 static void WINAPI WS2_GetAcceptExSockaddrs(PVOID buffer, DWORD data_size, DWORD local_size, DWORD remote_size,
2405 struct WS_sockaddr **local_addr, LPINT local_addr_len,
2406 struct WS_sockaddr **remote_addr, LPINT remote_addr_len)
2408 char *cbuf = buffer;
2409 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer, data_size, local_size, remote_size, local_addr,
2410 local_addr_len, remote_addr, remote_addr_len );
2411 cbuf += data_size;
2413 *local_addr_len = *(int *) cbuf;
2414 *local_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2416 cbuf += local_size;
2418 *remote_addr_len = *(int *) cbuf;
2419 *remote_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2422 /***********************************************************************
2423 * WSARecvMsg
2425 * Perform a receive operation that is capable of returning message
2426 * control headers. It is important to note that the WSAMSG parameter
2427 * must remain valid throughout the operation, even when an overlapped
2428 * receive is performed.
2430 static int WINAPI WS2_WSARecvMsg( SOCKET s, LPWSAMSG msg, LPDWORD lpNumberOfBytesRecvd,
2431 LPWSAOVERLAPPED lpOverlapped,
2432 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2434 if (!msg)
2436 SetLastError( WSAEFAULT );
2437 return SOCKET_ERROR;
2440 return WS2_recv_base( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesRecvd,
2441 &msg->dwFlags, msg->name, &msg->namelen,
2442 lpOverlapped, lpCompletionRoutine, &msg->Control );
2445 /***********************************************************************
2446 * interface_bind (INTERNAL)
2448 * Take bind() calls on any name corresponding to a local network adapter and restrict the given socket to
2449 * operating only on the specified interface. This restriction consists of two components:
2450 * 1) An outgoing packet restriction suggesting the egress interface for all packets.
2451 * 2) An incoming packet restriction dropping packets not meant for the interface.
2452 * If the function succeeds in placing these restrictions (returns TRUE) then the name for the bind() may
2453 * safely be changed to INADDR_ANY, permitting the transmission and receipt of broadcast packets on the
2454 * socket. This behavior is only relevant to UDP sockets and is needed for applications that expect to be able
2455 * to receive broadcast packets on a socket that is bound to a specific network interface.
2457 static BOOL interface_bind( SOCKET s, int fd, struct sockaddr *addr )
2459 struct sockaddr_in *in_sock = (struct sockaddr_in *) addr;
2460 unsigned int sock_type = 0;
2461 socklen_t optlen = sizeof(sock_type);
2462 in_addr_t bind_addr = in_sock->sin_addr.s_addr;
2463 PIP_ADAPTER_INFO adapters = NULL, adapter;
2464 BOOL ret = FALSE;
2465 DWORD adap_size;
2466 int enable = 1;
2468 if (bind_addr == htonl(WS_INADDR_ANY) || bind_addr == htonl(WS_INADDR_LOOPBACK))
2469 return FALSE; /* Not binding to a network adapter, special interface binding unnecessary. */
2470 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &sock_type, &optlen) == -1 || sock_type != SOCK_DGRAM)
2471 return FALSE; /* Special interface binding is only necessary for UDP datagrams. */
2472 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
2473 goto cleanup;
2474 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
2475 if (adapters == NULL || GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
2476 goto cleanup;
2477 /* Search the IPv4 adapter list for the appropriate binding interface */
2478 for (adapter = adapters; adapter != NULL; adapter = adapter->Next)
2480 in_addr_t adapter_addr = (in_addr_t) inet_addr(adapter->IpAddressList.IpAddress.String);
2482 if (bind_addr == adapter_addr)
2484 #if defined(IP_BOUND_IF)
2485 /* IP_BOUND_IF sets both the incoming and outgoing restriction at once */
2486 if (setsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &adapter->Index, sizeof(adapter->Index)) != 0)
2487 goto cleanup;
2488 ret = TRUE;
2489 #elif defined(LINUX_BOUND_IF)
2490 in_addr_t ifindex = (in_addr_t) htonl(adapter->Index);
2491 struct interface_filter specific_interface_filter;
2492 struct sock_fprog filter_prog;
2494 if (setsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex, sizeof(ifindex)) != 0)
2495 goto cleanup; /* Failed to suggest egress interface */
2496 specific_interface_filter = generic_interface_filter;
2497 specific_interface_filter.iface_rule.k = adapter->Index;
2498 specific_interface_filter.ip_rule.k = htonl(adapter_addr);
2499 filter_prog.len = sizeof(generic_interface_filter)/sizeof(struct sock_filter);
2500 filter_prog.filter = (struct sock_filter *) &specific_interface_filter;
2501 if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog, sizeof(filter_prog)) != 0)
2502 goto cleanup; /* Failed to specify incoming packet filter */
2503 ret = TRUE;
2504 #else
2505 FIXME("Broadcast packets on interface-bound sockets are not currently supported on this platform, "
2506 "receiving broadcast packets will not work on socket %04lx.\n", s);
2507 #endif
2508 break;
2511 /* Will soon be switching to INADDR_ANY: permit address reuse */
2512 if (ret && setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) == 0)
2513 TRACE("Socket %04lx bound to interface index %d\n", s, adapter->Index);
2514 else
2515 ret = FALSE;
2517 cleanup:
2518 if(!ret)
2519 ERR("Failed to bind to interface, receiving broadcast packets will not work on socket %04lx.\n", s);
2520 HeapFree(GetProcessHeap(), 0, adapters);
2521 return ret;
2524 /***********************************************************************
2525 * bind (WS2_32.2)
2527 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
2529 int fd = get_sock_fd( s, 0, NULL );
2530 int res = SOCKET_ERROR;
2532 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2534 if (fd != -1)
2536 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
2538 SetLastError(WSAEAFNOSUPPORT);
2540 else
2542 union generic_unix_sockaddr uaddr;
2543 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2544 if (!uaddrlen)
2546 SetLastError(WSAEFAULT);
2548 else
2550 #ifdef IPV6_V6ONLY
2551 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
2552 if (name->sa_family == WS_AF_INET6 &&
2553 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
2555 int enable = 1;
2556 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
2558 release_sock_fd( s, fd );
2559 SetLastError(WSAEAFNOSUPPORT);
2560 return SOCKET_ERROR;
2563 #endif
2564 if (name->sa_family == WS_AF_INET)
2566 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2567 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2569 /* Trying to bind to the default host interface, using
2570 * INADDR_ANY instead*/
2571 WARN("Trying to bind to magic IP address, using "
2572 "INADDR_ANY instead.\n");
2573 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
2575 else if (interface_bind(s, fd, &uaddr.addr))
2576 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
2578 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
2580 int loc_errno = errno;
2581 WARN("\tfailure - errno = %i\n", errno);
2582 errno = loc_errno;
2583 switch (errno)
2585 case EBADF:
2586 SetLastError(WSAENOTSOCK);
2587 break;
2588 case EADDRNOTAVAIL:
2589 SetLastError(WSAEINVAL);
2590 break;
2591 default:
2592 SetLastError(wsaErrno());
2593 break;
2596 else
2598 res=0; /* success */
2602 release_sock_fd( s, fd );
2604 return res;
2607 /***********************************************************************
2608 * closesocket (WS2_32.3)
2610 int WINAPI WS_closesocket(SOCKET s)
2612 TRACE("socket %04lx\n", s);
2613 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
2614 return SOCKET_ERROR;
2617 static int do_connect(int fd, const struct WS_sockaddr* name, int namelen)
2619 union generic_unix_sockaddr uaddr;
2620 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2622 if (!uaddrlen)
2623 return WSAEFAULT;
2625 if (name->sa_family == WS_AF_INET)
2627 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2628 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2630 /* Trying to connect to magic replace-loopback address,
2631 * assuming we really want to connect to localhost */
2632 TRACE("Trying to connect to magic IP address, using "
2633 "INADDR_LOOPBACK instead.\n");
2634 in4->sin_addr.s_addr = htonl(WS_INADDR_LOOPBACK);
2638 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
2639 return 0;
2641 return wsaErrno();
2644 /***********************************************************************
2645 * connect (WS2_32.4)
2647 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
2649 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2651 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2653 if (fd != -1)
2655 NTSTATUS status;
2656 BOOL is_blocking;
2657 int ret = do_connect(fd, name, namelen);
2658 if (ret == 0)
2659 goto connect_success;
2661 if (ret == WSAEINPROGRESS)
2663 /* tell wineserver that a connection is in progress */
2664 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2665 FD_CONNECT,
2666 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2667 status = _is_blocking( s, &is_blocking );
2668 if (status)
2670 release_sock_fd( s, fd );
2671 set_error( status );
2672 return SOCKET_ERROR;
2674 if (is_blocking)
2676 int result;
2677 /* block here */
2678 do_block(fd, POLLIN | POLLOUT, -1);
2679 _sync_sock_state(s); /* let wineserver notice connection */
2680 /* retrieve any error codes from it */
2681 result = _get_sock_error(s, FD_CONNECT_BIT);
2682 if (result)
2683 SetLastError(NtStatusToWSAError(result));
2684 else
2686 goto connect_success;
2689 else
2691 SetLastError(WSAEWOULDBLOCK);
2694 else
2696 SetLastError(ret);
2698 release_sock_fd( s, fd );
2700 return SOCKET_ERROR;
2702 connect_success:
2703 release_sock_fd( s, fd );
2704 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2705 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2706 FD_CONNECT|FD_WINE_LISTENING);
2707 return 0;
2710 /***********************************************************************
2711 * WSAConnect (WS2_32.30)
2713 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
2714 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
2715 LPQOS lpSQOS, LPQOS lpGQOS )
2717 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
2718 FIXME("unsupported parameters!\n");
2719 return WS_connect( s, name, namelen );
2722 /***********************************************************************
2723 * ConnectEx
2725 static BOOL WINAPI WS2_ConnectEx(SOCKET s, const struct WS_sockaddr* name, int namelen,
2726 PVOID sendBuf, DWORD sendBufLen, LPDWORD sent, LPOVERLAPPED ov)
2728 int fd, ret, status;
2729 union generic_unix_sockaddr uaddr;
2730 socklen_t uaddrlen = sizeof(uaddr);
2732 if (!ov)
2734 SetLastError( ERROR_INVALID_PARAMETER );
2735 return FALSE;
2738 fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2739 if (fd == -1)
2741 SetLastError( WSAENOTSOCK );
2742 return FALSE;
2745 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
2746 s, name, debugstr_sockaddr(name), namelen, sendBuf, sendBufLen, ov);
2748 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
2750 SetLastError(wsaErrno());
2751 return FALSE;
2753 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
2755 SetLastError(WSAEINVAL);
2756 return FALSE;
2759 ret = do_connect(fd, name, namelen);
2760 if (ret == 0)
2762 WSABUF wsabuf;
2764 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2765 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2766 FD_CONNECT|FD_WINE_LISTENING);
2768 wsabuf.len = sendBufLen;
2769 wsabuf.buf = (char*) sendBuf;
2771 /* WSASend takes care of completion if need be */
2772 if (WSASend(s, &wsabuf, sendBuf ? 1 : 0, sent, 0, ov, NULL) != SOCKET_ERROR)
2773 goto connection_success;
2775 else if (ret == WSAEINPROGRESS)
2777 struct ws2_async *wsa;
2778 ULONG_PTR cvalue = (((ULONG_PTR)ov->hEvent & 1) == 0) ? (ULONG_PTR)ov : 0;
2780 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2781 FD_CONNECT,
2782 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2784 /* Indirectly call WSASend */
2785 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( struct ws2_async, iovec[1] ))))
2787 SetLastError(WSAEFAULT);
2789 else
2791 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)ov;
2792 iosb->u.Status = STATUS_PENDING;
2793 iosb->Information = 0;
2795 wsa->hSocket = SOCKET2HANDLE(s);
2796 wsa->addr = NULL;
2797 wsa->addrlen.val = 0;
2798 wsa->flags = 0;
2799 wsa->lpFlags = &wsa->flags;
2800 wsa->control = NULL;
2801 wsa->n_iovecs = sendBuf ? 1 : 0;
2802 wsa->first_iovec = 0;
2803 wsa->completion_func = NULL;
2804 wsa->iovec[0].iov_base = sendBuf;
2805 wsa->iovec[0].iov_len = sendBufLen;
2807 SERVER_START_REQ( register_async )
2809 req->type = ASYNC_TYPE_WRITE;
2810 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2811 req->async.callback = wine_server_client_ptr( WS2_async_send );
2812 req->async.iosb = wine_server_client_ptr( iosb );
2813 req->async.arg = wine_server_client_ptr( wsa );
2814 req->async.event = wine_server_obj_handle( ov->hEvent );
2815 req->async.cvalue = cvalue;
2816 status = wine_server_call( req );
2818 SERVER_END_REQ;
2820 if (status != STATUS_PENDING) HeapFree(GetProcessHeap(), 0, wsa);
2822 /* If the connect already failed */
2823 if (status == STATUS_PIPE_DISCONNECTED)
2824 status = _get_sock_error(s, FD_CONNECT_BIT);
2825 SetLastError( NtStatusToWSAError(status) );
2828 else
2830 SetLastError(ret);
2833 release_sock_fd( s, fd );
2834 return FALSE;
2836 connection_success:
2837 release_sock_fd( s, fd );
2838 return TRUE;
2842 /***********************************************************************
2843 * getpeername (WS2_32.5)
2845 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
2847 int fd;
2848 int res;
2850 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
2852 fd = get_sock_fd( s, 0, NULL );
2853 res = SOCKET_ERROR;
2855 if (fd != -1)
2857 union generic_unix_sockaddr uaddr;
2858 socklen_t uaddrlen = sizeof(uaddr);
2860 if (getpeername(fd, &uaddr.addr, &uaddrlen) == 0)
2862 if (!name || !namelen)
2863 SetLastError(WSAEFAULT);
2864 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
2865 /* The buffer was too small */
2866 SetLastError(WSAEFAULT);
2867 else
2868 res = 0;
2870 else
2871 SetLastError(wsaErrno());
2872 release_sock_fd( s, fd );
2874 return res;
2877 /***********************************************************************
2878 * getsockname (WS2_32.6)
2880 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
2882 int fd;
2883 int res;
2885 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
2887 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
2888 if( (name == NULL) || (namelen == NULL) )
2890 SetLastError( WSAEFAULT );
2891 return SOCKET_ERROR;
2894 fd = get_sock_fd( s, 0, NULL );
2895 res = SOCKET_ERROR;
2897 if (fd != -1)
2899 union generic_unix_sockaddr uaddr;
2900 socklen_t uaddrlen = sizeof(uaddr);
2902 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
2904 SetLastError(wsaErrno());
2906 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
2908 SetLastError(WSAEINVAL);
2910 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
2912 /* The buffer was too small */
2913 SetLastError(WSAEFAULT);
2915 else
2917 res=0;
2919 release_sock_fd( s, fd );
2921 return res;
2924 /***********************************************************************
2925 * getsockopt (WS2_32.7)
2927 INT WINAPI WS_getsockopt(SOCKET s, INT level,
2928 INT optname, char *optval, INT *optlen)
2930 int fd;
2931 INT ret = 0;
2933 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
2934 s, level, optname, optval, *optlen);
2936 switch(level)
2938 case WS_SOL_SOCKET:
2940 switch(optname)
2942 /* Handle common cases. The special cases are below, sorted
2943 * alphabetically */
2944 case WS_SO_BROADCAST:
2945 case WS_SO_DEBUG:
2946 case WS_SO_ERROR:
2947 case WS_SO_KEEPALIVE:
2948 case WS_SO_OOBINLINE:
2949 case WS_SO_RCVBUF:
2950 case WS_SO_REUSEADDR:
2951 case WS_SO_SNDBUF:
2952 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2953 return SOCKET_ERROR;
2954 convert_sockopt(&level, &optname);
2955 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
2957 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2958 ret = SOCKET_ERROR;
2960 release_sock_fd( s, fd );
2961 return ret;
2962 case WS_SO_ACCEPTCONN:
2963 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2964 return SOCKET_ERROR;
2965 if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, optval, (socklen_t *)optlen) != 0 )
2967 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2968 ret = SOCKET_ERROR;
2970 else
2972 /* BSD returns != 0 while Windows return exact == 1 */
2973 if (*(int *)optval) *(int *)optval = 1;
2975 release_sock_fd( s, fd );
2976 return ret;
2977 case WS_SO_DONTLINGER:
2979 struct linger lingval;
2980 socklen_t len = sizeof(struct linger);
2982 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
2984 SetLastError(WSAEFAULT);
2985 return SOCKET_ERROR;
2987 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2988 return SOCKET_ERROR;
2990 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
2992 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2993 ret = SOCKET_ERROR;
2995 else
2997 *(BOOL *)optval = !lingval.l_onoff;
2998 *optlen = sizeof(BOOL);
3001 release_sock_fd( s, fd );
3002 return ret;
3005 case WS_SO_CONNECT_TIME:
3007 static int pretendtime = 0;
3008 struct WS_sockaddr addr;
3009 int len = sizeof(addr);
3011 if (!optlen || *optlen < sizeof(DWORD) || !optval)
3013 SetLastError(WSAEFAULT);
3014 return SOCKET_ERROR;
3016 if (WS_getpeername(s, &addr, &len) == SOCKET_ERROR)
3017 *(DWORD *)optval = ~0u;
3018 else
3020 if (!pretendtime) FIXME("WS_SO_CONNECT_TIME - faking results\n");
3021 *(DWORD *)optval = pretendtime++;
3023 *optlen = sizeof(DWORD);
3024 return ret;
3026 /* As mentioned in setsockopt, Windows ignores this, so we
3027 * always return true here */
3028 case WS_SO_DONTROUTE:
3029 if (!optlen || *optlen < sizeof(BOOL) || !optval)
3031 SetLastError(WSAEFAULT);
3032 return SOCKET_ERROR;
3034 *(BOOL *)optval = TRUE;
3035 *optlen = sizeof(BOOL);
3036 return 0;
3038 case WS_SO_LINGER:
3040 struct linger lingval;
3041 int so_type;
3042 socklen_t len = sizeof(struct linger), slen = sizeof(int);
3044 /* struct linger and LINGER have different sizes */
3045 if (!optlen || *optlen < sizeof(LINGER) || !optval)
3047 SetLastError(WSAEFAULT);
3048 return SOCKET_ERROR;
3050 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3051 return SOCKET_ERROR;
3053 if ((getsockopt(fd, SOL_SOCKET, SO_TYPE, &so_type, &slen) == 0 && so_type == SOCK_DGRAM))
3055 SetLastError(WSAENOPROTOOPT);
3056 ret = SOCKET_ERROR;
3058 else if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0)
3060 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3061 ret = SOCKET_ERROR;
3063 else
3065 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
3066 ((LINGER *)optval)->l_linger = lingval.l_linger;
3067 *optlen = sizeof(struct linger);
3070 release_sock_fd( s, fd );
3071 return ret;
3074 case WS_SO_MAX_MSG_SIZE:
3075 if (!optlen || *optlen < sizeof(int) || !optval)
3077 SetLastError(WSAEFAULT);
3078 return SOCKET_ERROR;
3080 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
3081 *(int *)optval = 65507;
3082 *optlen = sizeof(int);
3083 return 0;
3085 /* SO_OPENTYPE does not require a valid socket handle. */
3086 case WS_SO_OPENTYPE:
3087 if (!optlen || *optlen < sizeof(int) || !optval)
3089 SetLastError(WSAEFAULT);
3090 return SOCKET_ERROR;
3092 *(int *)optval = get_per_thread_data()->opentype;
3093 *optlen = sizeof(int);
3094 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
3095 return 0;
3096 case WS_SO_PROTOCOL_INFOA:
3097 case WS_SO_PROTOCOL_INFOW:
3099 int size;
3100 WSAPROTOCOL_INFOW infow;
3102 ret = ws_protocol_info(s, optname == WS_SO_PROTOCOL_INFOW, &infow, &size);
3103 if (ret)
3105 if (!optlen || !optval || *optlen < size)
3107 if(optlen) *optlen = size;
3108 ret = 0;
3109 SetLastError(WSAEFAULT);
3111 else
3112 memcpy(optval, &infow, size);
3114 return ret ? 0 : SOCKET_ERROR;
3116 #ifdef SO_RCVTIMEO
3117 case WS_SO_RCVTIMEO:
3118 #endif
3119 #ifdef SO_SNDTIMEO
3120 case WS_SO_SNDTIMEO:
3121 #endif
3122 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
3124 struct timeval tv;
3125 socklen_t len = sizeof(struct timeval);
3127 if (!optlen || *optlen < sizeof(int)|| !optval)
3129 SetLastError(WSAEFAULT);
3130 return SOCKET_ERROR;
3132 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3133 return SOCKET_ERROR;
3135 convert_sockopt(&level, &optname);
3136 if (getsockopt(fd, level, optname, &tv, &len) != 0 )
3138 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3139 ret = SOCKET_ERROR;
3141 else
3143 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
3144 *optlen = sizeof(int);
3147 release_sock_fd( s, fd );
3148 return ret;
3150 #endif
3151 case WS_SO_TYPE:
3153 if (!optlen || *optlen < sizeof(int) || !optval)
3155 SetLastError(WSAEFAULT);
3156 return SOCKET_ERROR;
3158 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3159 return SOCKET_ERROR;
3161 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, optval, (socklen_t *)optlen) != 0 )
3163 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3164 ret = SOCKET_ERROR;
3166 else
3167 (*(int *)optval) = convert_socktype_u2w(*(int *)optval);
3169 release_sock_fd( s, fd );
3170 return ret;
3172 default:
3173 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
3174 SetLastError(WSAENOPROTOOPT);
3175 return SOCKET_ERROR;
3176 } /* end switch(optname) */
3177 }/* end case WS_SOL_SOCKET */
3178 #ifdef HAS_IPX
3179 case NSPROTO_IPX:
3181 struct WS_sockaddr_ipx addr;
3182 IPX_ADDRESS_DATA *data;
3183 int namelen;
3184 switch(optname)
3186 case IPX_PTYPE:
3187 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3188 #ifdef SOL_IPX
3189 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (socklen_t *)optlen) == -1)
3191 ret = SOCKET_ERROR;
3193 #else
3195 struct ipx val;
3196 socklen_t len=sizeof(struct ipx);
3197 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
3198 ret = SOCKET_ERROR;
3199 else
3200 *optval = (int)val.ipx_pt;
3202 #endif
3203 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
3204 release_sock_fd( s, fd );
3205 return ret;
3207 case IPX_ADDRESS:
3209 * On a Win2000 system with one network card there are usually
3210 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
3211 * Using this call you can then retrieve info about this all.
3212 * In case of Linux it is a bit different. Usually you have
3213 * only "one" device active and further it is not possible to
3214 * query things like the linkspeed.
3216 FIXME("IPX_ADDRESS\n");
3217 namelen = sizeof(struct WS_sockaddr_ipx);
3218 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
3219 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
3221 data = (IPX_ADDRESS_DATA*)optval;
3222 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
3223 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
3224 data->adapternum = 0;
3225 data->wan = FALSE; /* We are not on a wan for now .. */
3226 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
3227 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
3228 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
3229 * note 1MB = 1000kB in this case */
3230 return 0;
3232 case IPX_MAX_ADAPTER_NUM:
3233 FIXME("IPX_MAX_ADAPTER_NUM\n");
3234 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
3235 return 0;
3237 default:
3238 FIXME("IPX optname:%x\n", optname);
3239 return SOCKET_ERROR;
3240 }/* end switch(optname) */
3241 } /* end case NSPROTO_IPX */
3242 #endif
3244 #ifdef HAS_IRDA
3245 case WS_SOL_IRLMP:
3246 switch(optname)
3248 case WS_IRLMP_ENUMDEVICES:
3250 static const int MAX_IRDA_DEVICES = 10;
3251 char buf[sizeof(struct irda_device_list) +
3252 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
3253 int res;
3254 socklen_t len = sizeof(buf);
3256 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3257 return SOCKET_ERROR;
3258 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
3259 if (res < 0)
3261 SetLastError(wsaErrno());
3262 return SOCKET_ERROR;
3264 else
3266 struct irda_device_list *src = (struct irda_device_list *)buf;
3267 DEVICELIST *dst = (DEVICELIST *)optval;
3268 INT needed = sizeof(DEVICELIST);
3269 unsigned int i;
3271 if (src->len > 0)
3272 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
3273 if (*optlen < needed)
3275 SetLastError(WSAEFAULT);
3276 return SOCKET_ERROR;
3278 *optlen = needed;
3279 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
3280 dst->numDevice = src->len;
3281 for (i = 0; i < src->len; i++)
3283 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
3284 src->dev[i].saddr, src->dev[i].daddr,
3285 src->dev[i].info, src->dev[i].hints[0],
3286 src->dev[i].hints[1]);
3287 memcpy( dst->Device[i].irdaDeviceID,
3288 &src->dev[i].daddr,
3289 sizeof(dst->Device[i].irdaDeviceID) ) ;
3290 memcpy( dst->Device[i].irdaDeviceName,
3291 src->dev[i].info,
3292 sizeof(dst->Device[i].irdaDeviceName) ) ;
3293 memcpy( &dst->Device[i].irdaDeviceHints1,
3294 &src->dev[i].hints[0],
3295 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
3296 memcpy( &dst->Device[i].irdaDeviceHints2,
3297 &src->dev[i].hints[1],
3298 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
3299 dst->Device[i].irdaCharSet = src->dev[i].charset;
3301 return 0;
3304 default:
3305 FIXME("IrDA optname:0x%x\n", optname);
3306 return SOCKET_ERROR;
3308 break; /* case WS_SOL_IRLMP */
3309 #endif
3311 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3312 case WS_IPPROTO_TCP:
3313 switch(optname)
3315 case WS_TCP_NODELAY:
3316 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3317 return SOCKET_ERROR;
3318 convert_sockopt(&level, &optname);
3319 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3321 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3322 ret = SOCKET_ERROR;
3324 release_sock_fd( s, fd );
3325 return ret;
3327 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
3328 return SOCKET_ERROR;
3330 case WS_IPPROTO_IP:
3331 switch(optname)
3333 case WS_IP_ADD_MEMBERSHIP:
3334 case WS_IP_DROP_MEMBERSHIP:
3335 #ifdef IP_HDRINCL
3336 case WS_IP_HDRINCL:
3337 #endif
3338 case WS_IP_MULTICAST_IF:
3339 case WS_IP_MULTICAST_LOOP:
3340 case WS_IP_MULTICAST_TTL:
3341 case WS_IP_OPTIONS:
3342 #ifdef IP_PKTINFO
3343 case WS_IP_PKTINFO:
3344 #endif
3345 case WS_IP_TOS:
3346 case WS_IP_TTL:
3347 #ifdef IP_UNICAST_IF
3348 case WS_IP_UNICAST_IF:
3349 #endif
3350 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3351 return SOCKET_ERROR;
3352 convert_sockopt(&level, &optname);
3353 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3355 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3356 ret = SOCKET_ERROR;
3358 release_sock_fd( s, fd );
3359 return ret;
3360 case WS_IP_DONTFRAGMENT:
3361 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
3362 *(BOOL*)optval = FALSE;
3363 return 0;
3365 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
3366 return SOCKET_ERROR;
3368 case WS_IPPROTO_IPV6:
3369 switch(optname)
3371 #ifdef IPV6_ADD_MEMBERSHIP
3372 case WS_IPV6_ADD_MEMBERSHIP:
3373 #endif
3374 #ifdef IPV6_DROP_MEMBERSHIP
3375 case WS_IPV6_DROP_MEMBERSHIP:
3376 #endif
3377 case WS_IPV6_MULTICAST_IF:
3378 case WS_IPV6_MULTICAST_HOPS:
3379 case WS_IPV6_MULTICAST_LOOP:
3380 case WS_IPV6_UNICAST_HOPS:
3381 case WS_IPV6_V6ONLY:
3382 #ifdef IPV6_UNICAST_IF
3383 case WS_IPV6_UNICAST_IF:
3384 #endif
3385 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3386 return SOCKET_ERROR;
3387 convert_sockopt(&level, &optname);
3388 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3390 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3391 ret = SOCKET_ERROR;
3393 release_sock_fd( s, fd );
3394 return ret;
3395 case WS_IPV6_DONTFRAG:
3396 FIXME("WS_IPV6_DONTFRAG is always false!\n");
3397 *(BOOL*)optval = FALSE;
3398 return 0;
3400 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
3401 return SOCKET_ERROR;
3403 default:
3404 WARN("Unknown level: 0x%08x\n", level);
3405 SetLastError(WSAEINVAL);
3406 return SOCKET_ERROR;
3407 } /* end switch(level) */
3410 /***********************************************************************
3411 * htonl (WS2_32.8)
3413 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
3415 return htonl(hostlong);
3419 /***********************************************************************
3420 * htons (WS2_32.9)
3422 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
3424 return htons(hostshort);
3427 /***********************************************************************
3428 * WSAHtonl (WS2_32.46)
3429 * From MSDN description of error codes, this function should also
3430 * check if WinSock has been initialized and the socket is a valid
3431 * socket. But why? This function only translates a host byte order
3432 * u_long into a network byte order u_long...
3434 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
3436 if (lpnetlong)
3438 *lpnetlong = htonl(hostlong);
3439 return 0;
3441 WSASetLastError(WSAEFAULT);
3442 return SOCKET_ERROR;
3445 /***********************************************************************
3446 * WSAHtons (WS2_32.47)
3447 * From MSDN description of error codes, this function should also
3448 * check if WinSock has been initialized and the socket is a valid
3449 * socket. But why? This function only translates a host byte order
3450 * u_short into a network byte order u_short...
3452 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
3455 if (lpnetshort)
3457 *lpnetshort = htons(hostshort);
3458 return 0;
3460 WSASetLastError(WSAEFAULT);
3461 return SOCKET_ERROR;
3465 /***********************************************************************
3466 * inet_addr (WS2_32.11)
3468 WS_u_long WINAPI WS_inet_addr(const char *cp)
3470 if (!cp) return INADDR_NONE;
3471 return inet_addr(cp);
3475 /***********************************************************************
3476 * ntohl (WS2_32.14)
3478 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
3480 return ntohl(netlong);
3484 /***********************************************************************
3485 * ntohs (WS2_32.15)
3487 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
3489 return ntohs(netshort);
3493 /***********************************************************************
3494 * inet_ntoa (WS2_32.12)
3496 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
3498 /* use "buffer for dummies" here because some applications have a
3499 * propensity to decode addresses in ws_hostent structure without
3500 * saving them first...
3502 static char dbuffer[16]; /* Yes, 16: 4*3 digits + 3 '.' + 1 '\0' */
3504 char* s = inet_ntoa(*((struct in_addr*)&in));
3505 if( s )
3507 strcpy(dbuffer, s);
3508 return dbuffer;
3510 SetLastError(wsaErrno());
3511 return NULL;
3514 static const char *debugstr_wsaioctl(DWORD ioctl)
3516 const char *buf_type, *family;
3518 switch(ioctl & 0x18000000)
3520 case WS_IOC_WS2:
3521 family = "IOC_WS2";
3522 break;
3523 case WS_IOC_PROTOCOL:
3524 family = "IOC_PROTOCOL";
3525 break;
3526 case WS_IOC_VENDOR:
3527 family = "IOC_VENDOR";
3528 break;
3529 default: /* WS_IOC_UNIX */
3531 BYTE size = (ioctl >> 16) & WS_IOCPARM_MASK;
3532 char x = (ioctl & 0xff00) >> 8;
3533 BYTE y = ioctl & 0xff;
3534 char args[14];
3536 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3538 case WS_IOC_VOID:
3539 buf_type = "_IO";
3540 sprintf(args, "%d, %d", x, y);
3541 break;
3542 case WS_IOC_IN:
3543 buf_type = "_IOW";
3544 sprintf(args, "'%c', %d, %d", x, y, size);
3545 break;
3546 case WS_IOC_OUT:
3547 buf_type = "_IOR";
3548 sprintf(args, "'%c', %d, %d", x, y, size);
3549 break;
3550 default:
3551 buf_type = "?";
3552 sprintf(args, "'%c', %d, %d", x, y, size);
3553 break;
3555 return wine_dbg_sprintf("%s(%s)", buf_type, args);
3559 /* We are different from WS_IOC_UNIX. */
3560 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3562 case WS_IOC_VOID:
3563 buf_type = "_WSAIO";
3564 break;
3565 case WS_IOC_INOUT:
3566 buf_type = "_WSAIORW";
3567 break;
3568 case WS_IOC_IN:
3569 buf_type = "_WSAIOW";
3570 break;
3571 case WS_IOC_OUT:
3572 buf_type = "_WSAIOR";
3573 break;
3574 default:
3575 buf_type = "?";
3576 break;
3579 return wine_dbg_sprintf("%s(%s, %d)", buf_type, family,
3580 (USHORT)(ioctl & 0xffff));
3583 /**********************************************************************
3584 * WSAIoctl (WS2_32.50)
3587 INT WINAPI WSAIoctl(SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size, LPVOID out_buff,
3588 DWORD out_size, LPDWORD ret_size, LPWSAOVERLAPPED overlapped,
3589 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
3591 int fd;
3592 DWORD status = 0, total = 0;
3594 TRACE("%ld, 0x%08x, %p, %d, %p, %d, %p, %p, %p\n",
3595 s, code, in_buff, in_size, out_buff, out_size, ret_size, overlapped, completion);
3597 switch (code)
3599 case WS_FIONBIO:
3600 if (in_size != sizeof(WS_u_long) || IS_INTRESOURCE(in_buff))
3602 WSASetLastError(WSAEFAULT);
3603 return SOCKET_ERROR;
3605 if (_get_sock_mask(s))
3607 /* AsyncSelect()'ed sockets are always nonblocking */
3608 if (!*(WS_u_long *)in_buff) status = WSAEINVAL;
3609 break;
3611 if (*(WS_u_long *)in_buff)
3612 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
3613 else
3614 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
3615 break;
3617 case WS_FIONREAD:
3619 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
3621 WSASetLastError(WSAEFAULT);
3622 return SOCKET_ERROR;
3624 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3625 if (ioctl(fd, FIONREAD, out_buff ) == -1)
3626 status = (errno == EBADF) ? WSAENOTSOCK : wsaErrno();
3627 release_sock_fd( s, fd );
3628 break;
3631 case WS_SIOCATMARK:
3633 unsigned int oob = 0, atmark = 0;
3634 socklen_t oobsize = sizeof(int);
3635 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
3637 WSASetLastError(WSAEFAULT);
3638 return SOCKET_ERROR;
3640 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3641 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
3642 if ((getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &oob, &oobsize ) == -1)
3643 || (!oob && ioctl(fd, SIOCATMARK, &atmark ) == -1))
3644 status = (errno == EBADF) ? WSAENOTSOCK : wsaErrno();
3645 else
3647 /* The SIOCATMARK value read from ioctl() is reversed
3648 * because BSD returns TRUE if it's in the OOB mark
3649 * while Windows returns TRUE if there are NO OOB bytes.
3651 (*(WS_u_long *) out_buff) = oob | !atmark;
3654 release_sock_fd( s, fd );
3655 break;
3658 case WS_FIOASYNC:
3659 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
3660 SetLastError(WSAEINVAL);
3661 return SOCKET_ERROR;
3663 case WS_SIO_GET_INTERFACE_LIST:
3665 INTERFACE_INFO* intArray = out_buff;
3666 DWORD size, numInt = 0, apiReturn;
3668 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
3670 if (!out_buff || !ret_size)
3672 WSASetLastError(WSAEFAULT);
3673 return SOCKET_ERROR;
3676 fd = get_sock_fd( s, 0, NULL );
3677 if (fd == -1) return SOCKET_ERROR;
3679 apiReturn = GetAdaptersInfo(NULL, &size);
3680 if (apiReturn == ERROR_BUFFER_OVERFLOW)
3682 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
3684 if (table)
3686 if (GetAdaptersInfo(table, &size) == NO_ERROR)
3688 PIP_ADAPTER_INFO ptr;
3690 for (ptr = table, numInt = 0; ptr; ptr = ptr->Next)
3692 unsigned int addr, mask, bcast;
3693 struct ifreq ifInfo;
3695 /* Skip interfaces without an IPv4 address. */
3696 if (ptr->IpAddressList.IpAddress.String[0] == '\0')
3697 continue;
3699 if ((numInt + 1)*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > out_size)
3701 WARN("Buffer too small = %u, out_size = %u\n", numInt + 1, out_size);
3702 status = WSAEFAULT;
3703 break;
3706 /* Socket Status Flags */
3707 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
3708 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
3710 ERR("Error obtaining status flags for socket!\n");
3711 status = WSAEINVAL;
3712 break;
3714 else
3716 /* set flags; the values of IFF_* are not the same
3717 under Linux and Windows, therefore must generate
3718 new flags */
3719 intArray->iiFlags = 0;
3720 if (ifInfo.ifr_flags & IFF_BROADCAST)
3721 intArray->iiFlags |= WS_IFF_BROADCAST;
3722 #ifdef IFF_POINTOPOINT
3723 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
3724 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
3725 #endif
3726 if (ifInfo.ifr_flags & IFF_LOOPBACK)
3727 intArray->iiFlags |= WS_IFF_LOOPBACK;
3728 if (ifInfo.ifr_flags & IFF_UP)
3729 intArray->iiFlags |= WS_IFF_UP;
3730 if (ifInfo.ifr_flags & IFF_MULTICAST)
3731 intArray->iiFlags |= WS_IFF_MULTICAST;
3734 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
3735 mask = inet_addr(ptr->IpAddressList.IpMask.String);
3736 bcast = addr | ~mask;
3737 intArray->iiAddress.AddressIn.sin_family = AF_INET;
3738 intArray->iiAddress.AddressIn.sin_port = 0;
3739 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
3740 addr;
3741 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
3742 intArray->iiNetmask.AddressIn.sin_port = 0;
3743 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
3744 mask;
3745 intArray->iiBroadcastAddress.AddressIn.sin_family =
3746 AF_INET;
3747 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
3748 intArray->iiBroadcastAddress.AddressIn.sin_addr.
3749 WS_s_addr = bcast;
3750 intArray++;
3751 numInt++;
3754 else
3756 ERR("Unable to get interface table!\n");
3757 status = WSAEINVAL;
3759 HeapFree(GetProcessHeap(),0,table);
3761 else status = WSAEINVAL;
3763 else if (apiReturn != ERROR_NO_DATA)
3765 ERR("Unable to get interface table!\n");
3766 status = WSAEINVAL;
3768 /* Calculate the size of the array being returned */
3769 total = sizeof(INTERFACE_INFO) * numInt;
3770 release_sock_fd( s, fd );
3771 break;
3774 case WS_SIO_ADDRESS_LIST_CHANGE:
3775 FIXME("-> SIO_ADDRESS_LIST_CHANGE request: stub\n");
3776 /* FIXME: error and return code depend on whether socket was created
3777 * with WSA_FLAG_OVERLAPPED, but there is no easy way to get this */
3778 break;
3780 case WS_SIO_ADDRESS_LIST_QUERY:
3782 DWORD size;
3784 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
3786 if (!ret_size)
3788 WSASetLastError(WSAEFAULT);
3789 return SOCKET_ERROR;
3792 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
3794 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
3795 DWORD num;
3797 if (!table || GetAdaptersInfo(table, &size))
3799 HeapFree(GetProcessHeap(), 0, table);
3800 status = WSAEINVAL;
3801 break;
3804 for (p = table, num = 0; p; p = p->Next)
3805 if (p->IpAddressList.IpAddress.String[0]) num++;
3807 total = sizeof(SOCKET_ADDRESS_LIST) + sizeof(SOCKET_ADDRESS) * (num - 1);
3808 total += sizeof(SOCKADDR) * num;
3810 if (total > out_size)
3812 HeapFree(GetProcessHeap(), 0, table);
3813 status = WSAEFAULT;
3814 break;
3817 if (out_buff)
3819 unsigned int i;
3820 SOCKET_ADDRESS *sa;
3821 SOCKET_ADDRESS_LIST *sa_list = out_buff;
3822 SOCKADDR_IN *sockaddr;
3824 sa = sa_list->Address;
3825 sockaddr = (SOCKADDR_IN *)((char *)sa + num * sizeof(SOCKET_ADDRESS));
3826 sa_list->iAddressCount = num;
3828 for (p = table, i = 0; p; p = p->Next)
3830 if (!p->IpAddressList.IpAddress.String[0]) continue;
3832 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
3833 sa[i].iSockaddrLength = sizeof(SOCKADDR);
3835 sockaddr[i].sin_family = AF_INET;
3836 sockaddr[i].sin_port = 0;
3837 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
3838 i++;
3842 HeapFree(GetProcessHeap(), 0, table);
3844 else
3846 WARN("unable to get IP address list\n");
3847 status = WSAEINVAL;
3849 break;
3852 case WS_SIO_FLUSH:
3853 FIXME("SIO_FLUSH: stub.\n");
3854 break;
3856 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
3858 static const GUID connectex_guid = WSAID_CONNECTEX;
3859 static const GUID disconnectex_guid = WSAID_DISCONNECTEX;
3860 static const GUID acceptex_guid = WSAID_ACCEPTEX;
3861 static const GUID getaccepexsockaddrs_guid = WSAID_GETACCEPTEXSOCKADDRS;
3862 static const GUID transmitfile_guid = WSAID_TRANSMITFILE;
3863 static const GUID transmitpackets_guid = WSAID_TRANSMITPACKETS;
3864 static const GUID wsarecvmsg_guid = WSAID_WSARECVMSG;
3865 static const GUID wsasendmsg_guid = WSAID_WSASENDMSG;
3867 if ( IsEqualGUID(&connectex_guid, in_buff) )
3869 *(LPFN_CONNECTEX *)out_buff = WS2_ConnectEx;
3870 break;
3872 else if ( IsEqualGUID(&disconnectex_guid, in_buff) )
3874 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented DisconnectEx\n");
3876 else if ( IsEqualGUID(&acceptex_guid, in_buff) )
3878 *(LPFN_ACCEPTEX *)out_buff = WS2_AcceptEx;
3879 break;
3881 else if ( IsEqualGUID(&getaccepexsockaddrs_guid, in_buff) )
3883 *(LPFN_GETACCEPTEXSOCKADDRS *)out_buff = WS2_GetAcceptExSockaddrs;
3884 break;
3886 else if ( IsEqualGUID(&transmitfile_guid, in_buff) )
3888 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitFile\n");
3890 else if ( IsEqualGUID(&transmitpackets_guid, in_buff) )
3892 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitPackets\n");
3894 else if ( IsEqualGUID(&wsarecvmsg_guid, in_buff) )
3896 *(LPFN_WSARECVMSG *)out_buff = WS2_WSARecvMsg;
3897 break;
3899 else if ( IsEqualGUID(&wsasendmsg_guid, in_buff) )
3901 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented WSASendMsg\n");
3903 else
3904 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff));
3906 status = WSAEOPNOTSUPP;
3907 break;
3909 case WS_SIO_KEEPALIVE_VALS:
3911 struct tcp_keepalive *k;
3912 int keepalive, keepidle, keepintvl;
3914 if (!in_buff || in_size < sizeof(struct tcp_keepalive))
3916 WSASetLastError(WSAEFAULT);
3917 return SOCKET_ERROR;
3920 k = in_buff;
3921 keepalive = k->onoff ? 1 : 0;
3922 keepidle = max( 1, (k->keepalivetime + 500) / 1000 );
3923 keepintvl = max( 1, (k->keepaliveinterval + 500) / 1000 );
3925 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
3927 fd = get_sock_fd(s, 0, NULL);
3928 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
3929 status = WSAEINVAL;
3930 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
3931 /* these values need to be set only if SO_KEEPALIVE is enabled */
3932 else if(keepalive)
3934 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
3935 status = WSAEINVAL;
3936 else if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
3937 status = WSAEINVAL;
3939 #else
3940 else
3941 FIXME("ignoring keepalive interval and timeout\n");
3942 #endif
3943 release_sock_fd(s, fd);
3944 break;
3946 case WS_SIO_ROUTING_INTERFACE_QUERY:
3948 struct WS_sockaddr *daddr = (struct WS_sockaddr *)in_buff;
3949 struct WS_sockaddr_in *daddr_in = (struct WS_sockaddr_in *)daddr;
3950 struct WS_sockaddr_in *saddr_in = out_buff;
3951 MIB_IPFORWARDROW row;
3952 PMIB_IPADDRTABLE ipAddrTable = NULL;
3953 DWORD size, i, found_index;
3955 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
3957 if (!in_buff || in_size < sizeof(struct WS_sockaddr) ||
3958 !out_buff || out_size < sizeof(struct WS_sockaddr_in) || !ret_size)
3960 WSASetLastError(WSAEFAULT);
3961 return SOCKET_ERROR;
3963 if (daddr->sa_family != AF_INET)
3965 FIXME("unsupported address family %d\n", daddr->sa_family);
3966 status = WSAEAFNOSUPPORT;
3967 break;
3969 if (GetBestRoute(daddr_in->sin_addr.S_un.S_addr, 0, &row) != NOERROR ||
3970 GetIpAddrTable(NULL, &size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
3972 status = WSAEFAULT;
3973 break;
3975 ipAddrTable = HeapAlloc(GetProcessHeap(), 0, size);
3976 if (GetIpAddrTable(ipAddrTable, &size, FALSE))
3978 HeapFree(GetProcessHeap(), 0, ipAddrTable);
3979 status = WSAEFAULT;
3980 break;
3982 for (i = 0, found_index = ipAddrTable->dwNumEntries;
3983 i < ipAddrTable->dwNumEntries; i++)
3985 if (ipAddrTable->table[i].dwIndex == row.dwForwardIfIndex)
3986 found_index = i;
3988 if (found_index == ipAddrTable->dwNumEntries)
3990 ERR("no matching IP address for interface %d\n",
3991 row.dwForwardIfIndex);
3992 HeapFree(GetProcessHeap(), 0, ipAddrTable);
3993 status = WSAEFAULT;
3994 break;
3996 saddr_in->sin_family = AF_INET;
3997 saddr_in->sin_addr.S_un.S_addr = ipAddrTable->table[found_index].dwAddr;
3998 saddr_in->sin_port = 0;
3999 total = sizeof(struct WS_sockaddr_in);
4000 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4001 break;
4003 case WS_SIO_SET_COMPATIBILITY_MODE:
4004 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
4005 status = WSAEOPNOTSUPP;
4006 break;
4007 case WS_SIO_UDP_CONNRESET:
4008 FIXME("WS_SIO_UDP_CONNRESET stub\n");
4009 break;
4010 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
4011 WSASetLastError(WSAEOPNOTSUPP);
4012 return SOCKET_ERROR;
4013 default:
4014 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code));
4015 status = WSAEOPNOTSUPP;
4016 break;
4019 if (completion)
4021 FIXME( "completion routine %p not supported\n", completion );
4023 else if (overlapped)
4025 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
4026 overlapped->Internal = status;
4027 overlapped->InternalHigh = total;
4028 if (overlapped->hEvent) NtSetEvent( overlapped->hEvent, NULL );
4029 if (cvalue) WS_AddCompletion( HANDLE2SOCKET(s), cvalue, status, total );
4032 if (!status)
4034 if (ret_size) *ret_size = total;
4035 return 0;
4037 SetLastError( status );
4038 return SOCKET_ERROR;
4042 /***********************************************************************
4043 * ioctlsocket (WS2_32.10)
4045 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
4047 DWORD ret_size;
4048 return WSAIoctl( s, cmd, argp, sizeof(WS_u_long), argp, sizeof(WS_u_long), &ret_size, NULL, NULL );
4051 /***********************************************************************
4052 * listen (WS2_32.13)
4054 int WINAPI WS_listen(SOCKET s, int backlog)
4056 int fd = get_sock_fd( s, FILE_READ_DATA, NULL ), ret = SOCKET_ERROR;
4058 TRACE("socket %04lx, backlog %d\n", s, backlog);
4059 if (fd != -1)
4061 union generic_unix_sockaddr uaddr;
4062 socklen_t uaddrlen = sizeof(uaddr);
4064 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
4066 SetLastError(wsaErrno());
4068 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
4070 SetLastError(WSAEINVAL);
4072 else if (listen(fd, backlog) == 0)
4074 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
4075 FD_WINE_LISTENING,
4076 FD_CONNECT|FD_WINE_CONNECTED);
4077 ret = 0;
4079 else
4080 SetLastError(wsaErrno());
4081 release_sock_fd( s, fd );
4083 else
4084 SetLastError(WSAENOTSOCK);
4085 return ret;
4088 /***********************************************************************
4089 * recv (WS2_32.16)
4091 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
4093 DWORD n, dwFlags = flags;
4094 WSABUF wsabuf;
4096 wsabuf.len = len;
4097 wsabuf.buf = buf;
4099 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
4100 return SOCKET_ERROR;
4101 else
4102 return n;
4105 /***********************************************************************
4106 * recvfrom (WS2_32.17)
4108 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
4109 struct WS_sockaddr *from, int *fromlen)
4111 DWORD n, dwFlags = flags;
4112 WSABUF wsabuf;
4114 wsabuf.len = len;
4115 wsabuf.buf = buf;
4117 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL, NULL) == SOCKET_ERROR )
4118 return SOCKET_ERROR;
4119 else
4120 return n;
4123 /* allocate a poll array for the corresponding fd sets */
4124 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
4125 const WS_fd_set *exceptfds, int *count_ptr )
4127 unsigned int i, j = 0, count = 0;
4128 struct pollfd *fds;
4130 if (readfds) count += readfds->fd_count;
4131 if (writefds) count += writefds->fd_count;
4132 if (exceptfds) count += exceptfds->fd_count;
4133 *count_ptr = count;
4134 if (!count)
4136 SetLastError(WSAEINVAL);
4137 return NULL;
4139 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0]))))
4141 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
4142 return NULL;
4144 if (readfds)
4145 for (i = 0; i < readfds->fd_count; i++, j++)
4147 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
4148 if (fds[j].fd == -1) goto failed;
4149 fds[j].events = POLLIN;
4150 fds[j].revents = 0;
4152 if (writefds)
4153 for (i = 0; i < writefds->fd_count; i++, j++)
4155 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
4156 if (fds[j].fd == -1) goto failed;
4157 fds[j].events = POLLOUT;
4158 fds[j].revents = 0;
4160 if (exceptfds)
4161 for (i = 0; i < exceptfds->fd_count; i++, j++)
4163 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
4164 if (fds[j].fd == -1) goto failed;
4165 fds[j].events = POLLHUP;
4166 fds[j].revents = 0;
4168 return fds;
4170 failed:
4171 count = j;
4172 j = 0;
4173 if (readfds)
4174 for (i = 0; i < readfds->fd_count && j < count; i++, j++)
4175 release_sock_fd( readfds->fd_array[i], fds[j].fd );
4176 if (writefds)
4177 for (i = 0; i < writefds->fd_count && j < count; i++, j++)
4178 release_sock_fd( writefds->fd_array[i], fds[j].fd );
4179 if (exceptfds)
4180 for (i = 0; i < exceptfds->fd_count && j < count; i++, j++)
4181 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
4182 HeapFree( GetProcessHeap(), 0, fds );
4183 return NULL;
4186 /* release the file descriptor obtained in fd_sets_to_poll */
4187 /* must be called with the original fd_set arrays, before calling get_poll_results */
4188 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
4189 const WS_fd_set *exceptfds, struct pollfd *fds )
4191 unsigned int i, j = 0;
4193 if (readfds)
4195 for (i = 0; i < readfds->fd_count; i++, j++)
4196 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
4198 if (writefds)
4200 for (i = 0; i < writefds->fd_count; i++, j++)
4201 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
4203 if (exceptfds)
4205 for (i = 0; i < exceptfds->fd_count; i++, j++)
4206 if (fds[j].fd != -1)
4208 /* make sure we have a real error before releasing the fd */
4209 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
4210 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
4215 /* map the poll results back into the Windows fd sets */
4216 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
4217 const struct pollfd *fds )
4219 unsigned int i, j = 0, k, total = 0;
4221 if (readfds)
4223 for (i = k = 0; i < readfds->fd_count; i++, j++)
4224 if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
4225 readfds->fd_count = k;
4226 total += k;
4228 if (writefds)
4230 for (i = k = 0; i < writefds->fd_count; i++, j++)
4231 if ((fds[j].revents & POLLOUT) && !(fds[j].revents & POLLHUP))
4232 writefds->fd_array[k++] = writefds->fd_array[i];
4233 writefds->fd_count = k;
4234 total += k;
4236 if (exceptfds)
4238 for (i = k = 0; i < exceptfds->fd_count; i++, j++)
4239 if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
4240 exceptfds->fd_count = k;
4241 total += k;
4243 return total;
4247 /***********************************************************************
4248 * select (WS2_32.18)
4250 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
4251 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
4252 const struct WS_timeval* ws_timeout)
4254 struct pollfd *pollfds;
4255 struct timeval tv1, tv2;
4256 int torig = 0;
4257 int count, ret, timeout = -1;
4259 TRACE("read %p, write %p, excp %p timeout %p\n",
4260 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
4262 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )))
4263 return SOCKET_ERROR;
4265 if (ws_timeout)
4267 torig = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
4268 timeout = torig;
4269 gettimeofday( &tv1, 0 );
4272 while ((ret = poll( pollfds, count, timeout )) < 0)
4274 if (errno == EINTR)
4276 if (!ws_timeout) continue;
4277 gettimeofday( &tv2, 0 );
4279 tv2.tv_sec -= tv1.tv_sec;
4280 tv2.tv_usec -= tv1.tv_usec;
4281 if (tv2.tv_usec < 0)
4283 tv2.tv_usec += 1000000;
4284 tv2.tv_sec -= 1;
4287 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
4288 if (timeout <= 0) break;
4289 } else break;
4291 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
4293 if (ret == -1) SetLastError(wsaErrno());
4294 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
4295 HeapFree( GetProcessHeap(), 0, pollfds );
4296 return ret;
4299 /* helper to send completion messages for client-only i/o operation case */
4300 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
4301 ULONG Information )
4303 SERVER_START_REQ( add_fd_completion )
4305 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
4306 req->cvalue = CompletionValue;
4307 req->status = CompletionStatus;
4308 req->information = Information;
4309 wine_server_call( req );
4311 SERVER_END_REQ;
4315 /***********************************************************************
4316 * send (WS2_32.19)
4318 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
4320 DWORD n;
4321 WSABUF wsabuf;
4323 wsabuf.len = len;
4324 wsabuf.buf = (char*) buf;
4326 if ( WS2_sendto( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
4327 return SOCKET_ERROR;
4328 else
4329 return n;
4332 /***********************************************************************
4333 * WSASend (WS2_32.72)
4335 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4336 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4337 LPWSAOVERLAPPED lpOverlapped,
4338 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4340 return WS2_sendto( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
4341 NULL, 0, lpOverlapped, lpCompletionRoutine );
4344 /***********************************************************************
4345 * WSASendDisconnect (WS2_32.73)
4347 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
4349 return WS_shutdown( s, SD_SEND );
4353 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4354 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4355 const struct WS_sockaddr *to, int tolen,
4356 LPWSAOVERLAPPED lpOverlapped,
4357 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4359 unsigned int i, options;
4360 int n, fd, err;
4361 struct ws2_async *wsa = NULL;
4362 int totalLength = 0;
4363 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
4364 DWORD bytes_sent;
4365 BOOL is_blocking;
4367 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
4368 s, lpBuffers, dwBufferCount, dwFlags,
4369 to, tolen, lpOverlapped, lpCompletionRoutine);
4371 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
4372 TRACE( "fd=%d, options=%x\n", fd, options );
4374 if ( fd == -1 ) return SOCKET_ERROR;
4376 if (!lpOverlapped && !lpNumberOfBytesSent)
4378 err = WSAEFAULT;
4379 goto error;
4381 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
4383 err = WSAEFAULT;
4384 goto error;
4387 wsa->hSocket = SOCKET2HANDLE(s);
4388 wsa->addr = (struct WS_sockaddr *)to;
4389 wsa->addrlen.val = tolen;
4390 wsa->flags = dwFlags;
4391 wsa->lpFlags = &wsa->flags;
4392 wsa->control = NULL;
4393 wsa->n_iovecs = dwBufferCount;
4394 wsa->first_iovec = 0;
4395 for ( i = 0; i < dwBufferCount; i++ )
4397 wsa->iovec[i].iov_base = lpBuffers[i].buf;
4398 wsa->iovec[i].iov_len = lpBuffers[i].len;
4399 totalLength += lpBuffers[i].len;
4402 for (;;)
4404 n = WS2_send( fd, wsa );
4405 if (n != -1 || errno != EINTR) break;
4407 if (n == -1 && errno != EAGAIN)
4409 err = wsaErrno();
4410 goto error;
4413 if ((lpOverlapped || lpCompletionRoutine) &&
4414 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
4416 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
4418 wsa->user_overlapped = lpOverlapped;
4419 wsa->completion_func = lpCompletionRoutine;
4420 release_sock_fd( s, fd );
4422 if (n == -1 || n < totalLength)
4424 iosb->u.Status = STATUS_PENDING;
4425 iosb->Information = n == -1 ? 0 : n;
4427 SERVER_START_REQ( register_async )
4429 req->type = ASYNC_TYPE_WRITE;
4430 req->async.handle = wine_server_obj_handle( wsa->hSocket );
4431 req->async.callback = wine_server_client_ptr( WS2_async_send );
4432 req->async.iosb = wine_server_client_ptr( iosb );
4433 req->async.arg = wine_server_client_ptr( wsa );
4434 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
4435 req->async.cvalue = cvalue;
4436 err = wine_server_call( req );
4438 SERVER_END_REQ;
4440 /* Enable the event only after starting the async. The server will deliver it as soon as
4441 the async is done. */
4442 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
4444 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
4445 WSASetLastError( NtStatusToWSAError( err ));
4446 return SOCKET_ERROR;
4449 iosb->u.Status = STATUS_SUCCESS;
4450 iosb->Information = n;
4451 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = n;
4452 if (!wsa->completion_func)
4454 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
4455 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
4456 HeapFree( GetProcessHeap(), 0, wsa );
4458 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
4459 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
4460 WSASetLastError(0);
4461 return 0;
4464 if ((err = _is_blocking( s, &is_blocking )))
4466 err = NtStatusToWSAError( err );
4467 goto error;
4470 if ( is_blocking )
4472 /* On a blocking non-overlapped stream socket,
4473 * sending blocks until the entire buffer is sent. */
4474 DWORD timeout_start = GetTickCount();
4476 bytes_sent = n == -1 ? 0 : n;
4478 while (wsa->first_iovec < wsa->n_iovecs)
4480 struct pollfd pfd;
4481 int timeout = GET_SNDTIMEO(fd);
4483 if (timeout != -1)
4485 timeout -= GetTickCount() - timeout_start;
4486 if (timeout < 0) timeout = 0;
4489 pfd.fd = fd;
4490 pfd.events = POLLOUT;
4492 if (!timeout || !poll( &pfd, 1, timeout ))
4494 err = WSAETIMEDOUT;
4495 goto error; /* msdn says a timeout in send is fatal */
4498 n = WS2_send( fd, wsa );
4499 if (n == -1 && errno != EAGAIN && errno != EINTR)
4501 err = wsaErrno();
4502 goto error;
4505 if (n >= 0)
4506 bytes_sent += n;
4509 else /* non-blocking */
4511 if (n < totalLength)
4512 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
4513 if (n == -1)
4515 err = WSAEWOULDBLOCK;
4516 goto error;
4518 bytes_sent = n;
4521 TRACE(" -> %i bytes\n", bytes_sent);
4523 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = bytes_sent;
4524 HeapFree( GetProcessHeap(), 0, wsa );
4525 release_sock_fd( s, fd );
4526 WSASetLastError(0);
4527 return 0;
4529 error:
4530 HeapFree( GetProcessHeap(), 0, wsa );
4531 release_sock_fd( s, fd );
4532 WARN(" -> ERROR %d\n", err);
4533 WSASetLastError(err);
4534 return SOCKET_ERROR;
4537 /***********************************************************************
4538 * WSASendTo (WS2_32.74)
4540 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4541 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4542 const struct WS_sockaddr *to, int tolen,
4543 LPWSAOVERLAPPED lpOverlapped,
4544 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4546 return WS2_sendto( s, lpBuffers, dwBufferCount,
4547 lpNumberOfBytesSent, dwFlags,
4548 to, tolen,
4549 lpOverlapped, lpCompletionRoutine );
4552 /***********************************************************************
4553 * sendto (WS2_32.20)
4555 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
4556 const struct WS_sockaddr *to, int tolen)
4558 DWORD n;
4559 WSABUF wsabuf;
4561 wsabuf.len = len;
4562 wsabuf.buf = (char*) buf;
4564 if ( WS2_sendto(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
4565 return SOCKET_ERROR;
4566 else
4567 return n;
4570 /***********************************************************************
4571 * setsockopt (WS2_32.21)
4573 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
4574 const char *optval, int optlen)
4576 int fd;
4577 int woptval;
4578 struct linger linger;
4579 struct timeval tval;
4581 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
4582 s, level, optname, optval, optlen);
4584 /* some broken apps pass the value directly instead of a pointer to it */
4585 if(optlen && IS_INTRESOURCE(optval))
4587 SetLastError(WSAEFAULT);
4588 return SOCKET_ERROR;
4591 switch(level)
4593 case WS_SOL_SOCKET:
4594 switch(optname)
4596 /* Some options need some conversion before they can be sent to
4597 * setsockopt. The conversions are done here, then they will fall though
4598 * to the general case. Special options that are not passed to
4599 * setsockopt follow below that.*/
4601 case WS_SO_DONTLINGER:
4602 if (!optval)
4604 SetLastError(WSAEFAULT);
4605 return SOCKET_ERROR;
4607 linger.l_onoff = *(const int*)optval == 0;
4608 linger.l_linger = 0;
4609 level = SOL_SOCKET;
4610 optname = SO_LINGER;
4611 optval = (char*)&linger;
4612 optlen = sizeof(struct linger);
4613 break;
4615 case WS_SO_LINGER:
4616 if (!optval)
4618 SetLastError(WSAEFAULT);
4619 return SOCKET_ERROR;
4621 linger.l_onoff = ((LINGER*)optval)->l_onoff;
4622 linger.l_linger = ((LINGER*)optval)->l_linger;
4623 level = SOL_SOCKET;
4624 optname = SO_LINGER;
4625 optval = (char*)&linger;
4626 optlen = sizeof(struct linger);
4627 break;
4629 case WS_SO_RCVBUF:
4630 if (*(const int*)optval < 2048)
4632 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
4633 return 0;
4635 /* Fall through */
4637 /* The options listed here don't need any special handling. Thanks to
4638 * the conversion happening above, options from there will fall through
4639 * to this, too.*/
4640 case WS_SO_ACCEPTCONN:
4641 case WS_SO_BROADCAST:
4642 case WS_SO_ERROR:
4643 case WS_SO_KEEPALIVE:
4644 case WS_SO_OOBINLINE:
4645 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
4646 * however, using it the BSD way fixes bug 8513 and seems to be what
4647 * most programmers assume, anyway */
4648 case WS_SO_REUSEADDR:
4649 case WS_SO_SNDBUF:
4650 case WS_SO_TYPE:
4651 convert_sockopt(&level, &optname);
4652 break;
4654 /* SO_DEBUG is a privileged operation, ignore it. */
4655 case WS_SO_DEBUG:
4656 TRACE("Ignoring SO_DEBUG\n");
4657 return 0;
4659 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
4660 * socket. According to MSDN, this option is silently ignored.*/
4661 case WS_SO_DONTROUTE:
4662 TRACE("Ignoring SO_DONTROUTE\n");
4663 return 0;
4665 /* Stops two sockets from being bound to the same port. Always happens
4666 * on unix systems, so just drop it. */
4667 case WS_SO_EXCLUSIVEADDRUSE:
4668 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
4669 return 0;
4671 /* After a ConnectEx call succeeds, the socket can't be used with half of the
4672 * normal winsock functions on windows. We don't have that problem. */
4673 case WS_SO_UPDATE_CONNECT_CONTEXT:
4674 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
4675 return 0;
4677 /* After a AcceptEx call succeeds, the socket can't be used with half of the
4678 * normal winsock functions on windows. We don't have that problem. */
4679 case WS_SO_UPDATE_ACCEPT_CONTEXT:
4680 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
4681 return 0;
4683 /* SO_OPENTYPE does not require a valid socket handle. */
4684 case WS_SO_OPENTYPE:
4685 if (!optlen || optlen < sizeof(int) || !optval)
4687 SetLastError(WSAEFAULT);
4688 return SOCKET_ERROR;
4690 get_per_thread_data()->opentype = *(const int *)optval;
4691 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
4692 return 0;
4694 #ifdef SO_RCVTIMEO
4695 case WS_SO_RCVTIMEO:
4696 #endif
4697 #ifdef SO_SNDTIMEO
4698 case WS_SO_SNDTIMEO:
4699 #endif
4700 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
4701 if (optval && optlen == sizeof(UINT32)) {
4702 /* WinSock passes milliseconds instead of struct timeval */
4703 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
4704 tval.tv_sec = *(const UINT32*)optval / 1000;
4705 /* min of 500 milliseconds */
4706 if (tval.tv_sec == 0 && tval.tv_usec && tval.tv_usec < 500000)
4707 tval.tv_usec = 500000;
4708 optlen = sizeof(struct timeval);
4709 optval = (char*)&tval;
4710 } else if (optlen == sizeof(struct timeval)) {
4711 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
4712 } else {
4713 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
4714 return 0;
4716 convert_sockopt(&level, &optname);
4717 break;
4718 #endif
4720 default:
4721 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
4722 SetLastError(WSAENOPROTOOPT);
4723 return SOCKET_ERROR;
4725 break; /* case WS_SOL_SOCKET */
4727 #ifdef HAS_IPX
4728 case NSPROTO_IPX:
4729 switch(optname)
4731 case IPX_PTYPE:
4732 fd = get_sock_fd( s, 0, NULL );
4733 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", *(const int*)optval, fd);
4735 /* We try to set the ipx type on ipx socket level. */
4736 #ifdef SOL_IPX
4737 if(setsockopt(fd, SOL_IPX, IPX_TYPE, optval, optlen) == -1)
4739 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
4740 release_sock_fd( s, fd );
4741 return SOCKET_ERROR;
4743 #else
4745 struct ipx val;
4746 /* Should we retrieve val using a getsockopt call and then
4747 * set the modified one? */
4748 val.ipx_pt = *optval;
4749 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
4751 #endif
4752 release_sock_fd( s, fd );
4753 return 0;
4755 case IPX_FILTERPTYPE:
4756 /* Sets the receive filter packet type, at the moment we don't support it */
4757 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
4758 /* Returning 0 is better for now than returning a SOCKET_ERROR */
4759 return 0;
4761 default:
4762 FIXME("opt_name:%x\n", optname);
4763 return SOCKET_ERROR;
4765 break; /* case NSPROTO_IPX */
4766 #endif
4768 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
4769 case WS_IPPROTO_TCP:
4770 switch(optname)
4772 case WS_TCP_NODELAY:
4773 convert_sockopt(&level, &optname);
4774 break;
4775 default:
4776 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
4777 return SOCKET_ERROR;
4779 break;
4781 case WS_IPPROTO_IP:
4782 switch(optname)
4784 case WS_IP_ADD_MEMBERSHIP:
4785 case WS_IP_DROP_MEMBERSHIP:
4786 #ifdef IP_HDRINCL
4787 case WS_IP_HDRINCL:
4788 #endif
4789 case WS_IP_MULTICAST_IF:
4790 case WS_IP_MULTICAST_LOOP:
4791 case WS_IP_MULTICAST_TTL:
4792 case WS_IP_OPTIONS:
4793 #ifdef IP_PKTINFO
4794 case WS_IP_PKTINFO:
4795 #endif
4796 case WS_IP_TOS:
4797 case WS_IP_TTL:
4798 #ifdef IP_UNICAST_IF
4799 case WS_IP_UNICAST_IF:
4800 #endif
4801 convert_sockopt(&level, &optname);
4802 break;
4803 case WS_IP_DONTFRAGMENT:
4804 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
4805 return 0;
4806 default:
4807 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
4808 return SOCKET_ERROR;
4810 break;
4812 case WS_IPPROTO_IPV6:
4813 switch(optname)
4815 #ifdef IPV6_ADD_MEMBERSHIP
4816 case WS_IPV6_ADD_MEMBERSHIP:
4817 #endif
4818 #ifdef IPV6_DROP_MEMBERSHIP
4819 case WS_IPV6_DROP_MEMBERSHIP:
4820 #endif
4821 case WS_IPV6_MULTICAST_IF:
4822 case WS_IPV6_MULTICAST_HOPS:
4823 case WS_IPV6_MULTICAST_LOOP:
4824 case WS_IPV6_UNICAST_HOPS:
4825 case WS_IPV6_V6ONLY:
4826 #ifdef IPV6_UNICAST_IF
4827 case WS_IPV6_UNICAST_IF:
4828 #endif
4829 convert_sockopt(&level, &optname);
4830 break;
4831 case WS_IPV6_DONTFRAG:
4832 FIXME("IPV6_DONTFRAG is silently ignored!\n");
4833 return 0;
4834 case WS_IPV6_PROTECTION_LEVEL:
4835 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
4836 return 0;
4837 default:
4838 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
4839 return SOCKET_ERROR;
4841 break;
4843 default:
4844 WARN("Unknown level: 0x%08x\n", level);
4845 SetLastError(WSAEINVAL);
4846 return SOCKET_ERROR;
4847 } /* end switch(level) */
4849 /* avoid endianness issues if argument is a 16-bit int */
4850 if (optval && optlen < sizeof(int))
4852 woptval= *((const INT16 *) optval);
4853 optval= (char*) &woptval;
4854 optlen=sizeof(int);
4856 fd = get_sock_fd( s, 0, NULL );
4857 if (fd == -1) return SOCKET_ERROR;
4859 if (setsockopt(fd, level, optname, optval, optlen) == 0)
4861 #ifdef __APPLE__
4862 if (level == SOL_SOCKET && optname == SO_REUSEADDR &&
4863 setsockopt(fd, level, SO_REUSEPORT, optval, optlen) != 0)
4865 SetLastError(wsaErrno());
4866 release_sock_fd( s, fd );
4867 return SOCKET_ERROR;
4869 #endif
4870 release_sock_fd( s, fd );
4871 return 0;
4873 TRACE("Setting socket error, %d\n", wsaErrno());
4874 SetLastError(wsaErrno());
4875 release_sock_fd( s, fd );
4877 return SOCKET_ERROR;
4880 /***********************************************************************
4881 * shutdown (WS2_32.22)
4883 int WINAPI WS_shutdown(SOCKET s, int how)
4885 int fd, err = WSAENOTSOCK;
4886 unsigned int options, clear_flags = 0;
4888 fd = get_sock_fd( s, 0, &options );
4889 TRACE("socket %04lx, how %i %x\n", s, how, options );
4891 if (fd == -1)
4892 return SOCKET_ERROR;
4894 switch( how )
4896 case 0: /* drop receives */
4897 clear_flags |= FD_READ;
4898 break;
4899 case 1: /* drop sends */
4900 clear_flags |= FD_WRITE;
4901 break;
4902 case 2: /* drop all */
4903 clear_flags |= FD_READ|FD_WRITE;
4904 /*fall through */
4905 default:
4906 clear_flags |= FD_WINE_LISTENING;
4909 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
4911 switch ( how )
4913 case SD_RECEIVE:
4914 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
4915 break;
4916 case SD_SEND:
4917 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
4918 break;
4919 case SD_BOTH:
4920 default:
4921 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
4922 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
4923 break;
4925 if (err) goto error;
4927 else /* non-overlapped mode */
4929 if ( shutdown( fd, how ) )
4931 err = wsaErrno();
4932 goto error;
4936 release_sock_fd( s, fd );
4937 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
4938 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
4939 return 0;
4941 error:
4942 release_sock_fd( s, fd );
4943 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
4944 WSASetLastError( err );
4945 return SOCKET_ERROR;
4948 /***********************************************************************
4949 * socket (WS2_32.23)
4951 SOCKET WINAPI WS_socket(int af, int type, int protocol)
4953 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
4955 return WSASocketA( af, type, protocol, NULL, 0,
4956 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
4960 /***********************************************************************
4961 * gethostbyaddr (WS2_32.51)
4963 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
4965 struct WS_hostent *retval = NULL;
4966 struct hostent* host;
4968 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4969 char *extrabuf;
4970 int ebufsize=1024;
4971 struct hostent hostentry;
4972 int locerr=ENOBUFS;
4973 host = NULL;
4974 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
4975 while(extrabuf) {
4976 int res = gethostbyaddr_r(addr, len, type,
4977 &hostentry, extrabuf, ebufsize, &host, &locerr);
4978 if( res != ERANGE) break;
4979 ebufsize *=2;
4980 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
4982 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
4983 #else
4984 EnterCriticalSection( &csWSgetXXXbyYYY );
4985 host = gethostbyaddr(addr, len, type);
4986 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
4987 #endif
4988 if( host != NULL ) retval = WS_dup_he(host);
4989 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4990 HeapFree(GetProcessHeap(),0,extrabuf);
4991 #else
4992 LeaveCriticalSection( &csWSgetXXXbyYYY );
4993 #endif
4994 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
4995 return retval;
4998 /***********************************************************************
4999 * WS_get_local_ips (INTERNAL)
5001 * Returns the list of local IP addresses by going through the network
5002 * adapters and using the local routing table to sort the addresses
5003 * from highest routing priority to lowest routing priority. This
5004 * functionality is inferred from the description for obtaining local
5005 * IP addresses given in the Knowledge Base Article Q160215.
5007 * Please note that the returned hostent is only freed when the thread
5008 * closes and is replaced if another hostent is requested.
5010 static struct WS_hostent* WS_get_local_ips( char *hostname )
5012 int last_metric, numroutes = 0, i, j;
5013 DWORD n;
5014 PIP_ADAPTER_INFO adapters = NULL, k;
5015 struct WS_hostent *hostlist = NULL;
5016 PMIB_IPFORWARDTABLE routes = NULL;
5017 struct route *route_addrs = NULL;
5018 DWORD adap_size, route_size;
5020 /* Obtain the size of the adapter list and routing table, also allocate memory */
5021 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
5022 return NULL;
5023 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
5024 return NULL;
5025 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
5026 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
5027 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
5028 if (adapters == NULL || routes == NULL || route_addrs == NULL)
5029 goto cleanup;
5030 /* Obtain the adapter list and the full routing table */
5031 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
5032 goto cleanup;
5033 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
5034 goto cleanup;
5035 /* Store the interface associated with each route */
5036 for (n = 0; n < routes->dwNumEntries; n++)
5038 IF_INDEX ifindex;
5039 DWORD ifmetric, exists = FALSE;
5041 if (routes->table[n].u1.ForwardType != MIB_IPROUTE_TYPE_DIRECT)
5042 continue;
5043 ifindex = routes->table[n].dwForwardIfIndex;
5044 ifmetric = routes->table[n].dwForwardMetric1;
5045 /* Only store the lowest valued metric for an interface */
5046 for (j = 0; j < numroutes; j++)
5048 if (route_addrs[j].interface == ifindex)
5050 if (route_addrs[j].metric > ifmetric)
5051 route_addrs[j].metric = ifmetric;
5052 exists = TRUE;
5055 if (exists)
5056 continue;
5057 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
5058 if (route_addrs == NULL)
5059 goto cleanup; /* Memory allocation error, fail gracefully */
5060 route_addrs[numroutes].interface = ifindex;
5061 route_addrs[numroutes].metric = ifmetric;
5062 /* If no IP is found in the next step (for whatever reason)
5063 * then fall back to the magic loopback address.
5065 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
5066 numroutes++;
5068 if (numroutes == 0)
5069 goto cleanup; /* No routes, fall back to the Magic IP */
5070 /* Find the IP address associated with each found interface */
5071 for (i = 0; i < numroutes; i++)
5073 for (k = adapters; k != NULL; k = k->Next)
5075 char *ip = k->IpAddressList.IpAddress.String;
5077 if (route_addrs[i].interface == k->Index)
5078 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
5081 /* Allocate a hostent and enough memory for all the IPs,
5082 * including the NULL at the end of the list.
5084 hostlist = WS_create_he(hostname, 1, 0, numroutes+1, sizeof(struct in_addr));
5085 if (hostlist == NULL)
5086 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
5087 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
5088 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
5089 hostlist->h_addrtype = AF_INET;
5090 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
5091 /* Reorder the entries when placing them in the host list, Windows expects
5092 * the IP list in order from highest priority to lowest (the critical thing
5093 * is that most applications expect the first IP to be the default route).
5095 last_metric = -1;
5096 for (i = 0; i < numroutes; i++)
5098 struct in_addr addr;
5099 int metric = 0xFFFF;
5101 memcpy(&addr, magic_loopback_addr, 4);
5102 for (j = 0; j < numroutes; j++)
5104 int this_metric = route_addrs[j].metric;
5106 if (this_metric > last_metric && this_metric < metric)
5108 addr = route_addrs[j].addr;
5109 metric = this_metric;
5112 last_metric = metric;
5113 (*(struct in_addr *) hostlist->h_addr_list[i]) = addr;
5116 /* Cleanup all allocated memory except the address list,
5117 * the address list is used by the calling app.
5119 cleanup:
5120 HeapFree(GetProcessHeap(), 0, route_addrs);
5121 HeapFree(GetProcessHeap(), 0, adapters);
5122 HeapFree(GetProcessHeap(), 0, routes);
5123 return hostlist;
5126 /***********************************************************************
5127 * gethostbyname (WS2_32.52)
5129 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
5131 struct WS_hostent *retval = NULL;
5132 struct hostent* host;
5133 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5134 char *extrabuf;
5135 int ebufsize=1024;
5136 struct hostent hostentry;
5137 int locerr = ENOBUFS;
5138 #endif
5139 char hostname[100];
5140 if(!num_startup) {
5141 SetLastError(WSANOTINITIALISED);
5142 return NULL;
5144 if( gethostname( hostname, 100) == -1) {
5145 SetLastError( WSAENOBUFS); /* appropriate ? */
5146 return retval;
5148 if( !name || !name[0]) {
5149 name = hostname;
5151 /* If the hostname of the local machine is requested then return the
5152 * complete list of local IP addresses */
5153 if(strcmp(name, hostname) == 0)
5154 retval = WS_get_local_ips(hostname);
5155 /* If any other hostname was requested (or the routing table lookup failed)
5156 * then return the IP found by the host OS */
5157 if(retval == NULL)
5159 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5160 host = NULL;
5161 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
5162 while(extrabuf) {
5163 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
5164 if( res != ERANGE) break;
5165 ebufsize *=2;
5166 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
5168 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
5169 #else
5170 EnterCriticalSection( &csWSgetXXXbyYYY );
5171 host = gethostbyname(name);
5172 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
5173 #endif
5174 if (host) retval = WS_dup_he(host);
5175 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5176 HeapFree(GetProcessHeap(),0,extrabuf);
5177 #else
5178 LeaveCriticalSection( &csWSgetXXXbyYYY );
5179 #endif
5181 if (retval && retval->h_addr_list[0][0] == 127 &&
5182 strcmp(name, "localhost") != 0)
5184 /* hostname != "localhost" but has loopback address. replace by our
5185 * special address.*/
5186 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
5188 TRACE( "%s ret %p\n", debugstr_a(name), retval );
5189 return retval;
5193 /***********************************************************************
5194 * getprotobyname (WS2_32.53)
5196 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
5198 struct WS_protoent* retval = NULL;
5199 #ifdef HAVE_GETPROTOBYNAME
5200 struct protoent* proto;
5201 EnterCriticalSection( &csWSgetXXXbyYYY );
5202 if( (proto = getprotobyname(name)) != NULL )
5204 retval = WS_dup_pe(proto);
5206 else {
5207 MESSAGE("protocol %s not found; You might want to add "
5208 "this to /etc/protocols\n", debugstr_a(name) );
5209 SetLastError(WSANO_DATA);
5211 LeaveCriticalSection( &csWSgetXXXbyYYY );
5212 #endif
5213 TRACE( "%s ret %p\n", debugstr_a(name), retval );
5214 return retval;
5218 /***********************************************************************
5219 * getprotobynumber (WS2_32.54)
5221 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
5223 struct WS_protoent* retval = NULL;
5224 #ifdef HAVE_GETPROTOBYNUMBER
5225 struct protoent* proto;
5226 EnterCriticalSection( &csWSgetXXXbyYYY );
5227 if( (proto = getprotobynumber(number)) != NULL )
5229 retval = WS_dup_pe(proto);
5231 else {
5232 MESSAGE("protocol number %d not found; You might want to add "
5233 "this to /etc/protocols\n", number );
5234 SetLastError(WSANO_DATA);
5236 LeaveCriticalSection( &csWSgetXXXbyYYY );
5237 #endif
5238 TRACE("%i ret %p\n", number, retval);
5239 return retval;
5243 /***********************************************************************
5244 * getservbyname (WS2_32.55)
5246 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
5248 struct WS_servent* retval = NULL;
5249 struct servent* serv;
5250 char *name_str;
5251 char *proto_str = NULL;
5253 if (!(name_str = strdup_lower(name))) return NULL;
5255 if (proto && *proto)
5257 if (!(proto_str = strdup_lower(proto)))
5259 HeapFree( GetProcessHeap(), 0, name_str );
5260 return NULL;
5264 EnterCriticalSection( &csWSgetXXXbyYYY );
5265 serv = getservbyname(name_str, proto_str);
5266 if( serv != NULL )
5268 retval = WS_dup_se(serv);
5270 else SetLastError(WSANO_DATA);
5271 LeaveCriticalSection( &csWSgetXXXbyYYY );
5272 HeapFree( GetProcessHeap(), 0, proto_str );
5273 HeapFree( GetProcessHeap(), 0, name_str );
5274 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
5275 return retval;
5278 /***********************************************************************
5279 * freeaddrinfo (WS2_32.@)
5281 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
5283 while (res) {
5284 struct WS_addrinfo *next;
5286 HeapFree(GetProcessHeap(),0,res->ai_canonname);
5287 HeapFree(GetProcessHeap(),0,res->ai_addr);
5288 next = res->ai_next;
5289 HeapFree(GetProcessHeap(),0,res);
5290 res = next;
5294 /* helper functions for getaddrinfo()/getnameinfo() */
5295 static int convert_aiflag_w2u(int winflags) {
5296 unsigned int i;
5297 int unixflags = 0;
5299 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
5300 if (ws_aiflag_map[i][0] & winflags) {
5301 unixflags |= ws_aiflag_map[i][1];
5302 winflags &= ~ws_aiflag_map[i][0];
5304 if (winflags)
5305 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
5306 return unixflags;
5309 static int convert_niflag_w2u(int winflags) {
5310 unsigned int i;
5311 int unixflags = 0;
5313 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
5314 if (ws_niflag_map[i][0] & winflags) {
5315 unixflags |= ws_niflag_map[i][1];
5316 winflags &= ~ws_niflag_map[i][0];
5318 if (winflags)
5319 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
5320 return unixflags;
5323 static int convert_aiflag_u2w(int unixflags) {
5324 unsigned int i;
5325 int winflags = 0;
5327 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
5328 if (ws_aiflag_map[i][1] & unixflags) {
5329 winflags |= ws_aiflag_map[i][0];
5330 unixflags &= ~ws_aiflag_map[i][1];
5332 if (unixflags) /* will warn usually */
5333 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
5334 return winflags;
5337 static int convert_eai_u2w(int unixret) {
5338 int i;
5340 for (i=0;ws_eai_map[i][0];i++)
5341 if (ws_eai_map[i][1] == unixret)
5342 return ws_eai_map[i][0];
5343 return unixret;
5346 static char *get_hostname(void)
5348 char *ret;
5349 DWORD size = 0;
5351 GetComputerNameExA( ComputerNamePhysicalDnsHostname, NULL, &size );
5352 if (GetLastError() != ERROR_MORE_DATA) return NULL;
5353 if (!(ret = HeapAlloc( GetProcessHeap(), 0, size ))) return NULL;
5354 if (!GetComputerNameExA( ComputerNamePhysicalDnsHostname, ret, &size ))
5356 HeapFree( GetProcessHeap(), 0, ret );
5357 return NULL;
5359 return ret;
5362 /***********************************************************************
5363 * getaddrinfo (WS2_32.@)
5365 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
5367 #ifdef HAVE_GETADDRINFO
5368 struct addrinfo *unixaires = NULL;
5369 int result;
5370 struct addrinfo unixhints, *punixhints = NULL;
5371 char *hostname = NULL;
5372 const char *node;
5374 if (!nodename && !servname) return WSAHOST_NOT_FOUND;
5376 if (!nodename)
5377 node = NULL;
5378 else if (!nodename[0])
5380 node = hostname = get_hostname();
5381 if (!node) return WSA_NOT_ENOUGH_MEMORY;
5383 else
5384 node = nodename;
5386 if (hints) {
5387 punixhints = &unixhints;
5389 memset(&unixhints, 0, sizeof(unixhints));
5390 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
5391 if (hints->ai_family == 0) /* wildcard, specific to getaddrinfo() */
5392 punixhints->ai_family = 0;
5393 else
5394 punixhints->ai_family = convert_af_w2u(hints->ai_family);
5395 if (hints->ai_socktype == 0) /* wildcard, specific to getaddrinfo() */
5396 punixhints->ai_socktype = 0;
5397 else
5398 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
5399 if (hints->ai_protocol == 0) /* wildcard, specific to getaddrinfo() */
5400 punixhints->ai_protocol = 0;
5401 else
5402 punixhints->ai_protocol = convert_proto_w2u(hints->ai_protocol);
5405 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
5406 result = getaddrinfo(node, servname, punixhints, &unixaires);
5408 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
5409 HeapFree(GetProcessHeap(), 0, hostname);
5411 if (!result) {
5412 struct addrinfo *xuai = unixaires;
5413 struct WS_addrinfo **xai = res;
5415 *xai = NULL;
5416 while (xuai) {
5417 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
5418 int len;
5420 if (!ai)
5421 goto outofmem;
5423 *xai = ai;xai = &ai->ai_next;
5424 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
5425 ai->ai_family = convert_af_u2w(xuai->ai_family);
5426 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
5427 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
5428 if (xuai->ai_canonname) {
5429 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
5430 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
5431 if (!ai->ai_canonname)
5432 goto outofmem;
5433 strcpy(ai->ai_canonname,xuai->ai_canonname);
5435 len = xuai->ai_addrlen;
5436 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
5437 if (!ai->ai_addr)
5438 goto outofmem;
5439 ai->ai_addrlen = len;
5440 do {
5441 int winlen = ai->ai_addrlen;
5443 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
5444 ai->ai_addrlen = winlen;
5445 break;
5447 len = 2*len;
5448 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
5449 if (!ai->ai_addr)
5450 goto outofmem;
5451 ai->ai_addrlen = len;
5452 } while (1);
5453 xuai = xuai->ai_next;
5455 freeaddrinfo(unixaires);
5456 } else {
5457 result = convert_eai_u2w(result);
5458 *res = NULL;
5460 return result;
5462 outofmem:
5463 if (*res) WS_freeaddrinfo(*res);
5464 if (unixaires) freeaddrinfo(unixaires);
5465 *res = NULL;
5466 return WSA_NOT_ENOUGH_MEMORY;
5467 #else
5468 FIXME("getaddrinfo() failed, not found during buildtime.\n");
5469 return EAI_FAIL;
5470 #endif
5473 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
5475 struct WS_addrinfoW *ret;
5477 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
5478 ret->ai_flags = ai->ai_flags;
5479 ret->ai_family = ai->ai_family;
5480 ret->ai_socktype = ai->ai_socktype;
5481 ret->ai_protocol = ai->ai_protocol;
5482 ret->ai_addrlen = ai->ai_addrlen;
5483 ret->ai_canonname = NULL;
5484 ret->ai_addr = NULL;
5485 ret->ai_next = NULL;
5486 if (ai->ai_canonname)
5488 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
5489 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
5491 HeapFree(GetProcessHeap(), 0, ret);
5492 return NULL;
5494 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
5496 if (ai->ai_addr)
5498 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
5500 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
5501 HeapFree(GetProcessHeap(), 0, ret);
5502 return NULL;
5504 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
5506 return ret;
5509 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
5511 struct WS_addrinfoW *ret, *infoW;
5513 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
5514 while (info->ai_next)
5516 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
5518 FreeAddrInfoW(ret);
5519 return NULL;
5521 infoW = infoW->ai_next;
5522 info = info->ai_next;
5524 return ret;
5527 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
5529 struct WS_addrinfo *ret;
5531 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
5532 ret->ai_flags = ai->ai_flags;
5533 ret->ai_family = ai->ai_family;
5534 ret->ai_socktype = ai->ai_socktype;
5535 ret->ai_protocol = ai->ai_protocol;
5536 ret->ai_addrlen = ai->ai_addrlen;
5537 ret->ai_canonname = NULL;
5538 ret->ai_addr = NULL;
5539 ret->ai_next = NULL;
5540 if (ai->ai_canonname)
5542 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
5543 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
5545 HeapFree(GetProcessHeap(), 0, ret);
5546 return NULL;
5548 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
5550 if (ai->ai_addr)
5552 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
5554 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
5555 HeapFree(GetProcessHeap(), 0, ret);
5556 return NULL;
5558 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
5560 return ret;
5563 /***********************************************************************
5564 * GetAddrInfoW (WS2_32.@)
5566 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
5568 int ret, len;
5569 char *nodenameA = NULL, *servnameA = NULL;
5570 struct WS_addrinfo *resA, *hintsA = NULL;
5572 if (nodename)
5574 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
5575 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
5576 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
5578 if (servname)
5580 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
5581 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
5583 HeapFree(GetProcessHeap(), 0, nodenameA);
5584 return EAI_MEMORY;
5586 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
5589 if (hints) hintsA = addrinfo_WtoA(hints);
5590 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
5591 WS_freeaddrinfo(hintsA);
5593 if (!ret)
5595 *res = addrinfo_list_AtoW(resA);
5596 WS_freeaddrinfo(resA);
5599 HeapFree(GetProcessHeap(), 0, nodenameA);
5600 HeapFree(GetProcessHeap(), 0, servnameA);
5601 return ret;
5604 /***********************************************************************
5605 * FreeAddrInfoW (WS2_32.@)
5607 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
5609 while (ai)
5611 ADDRINFOW *next;
5612 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
5613 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
5614 next = ai->ai_next;
5615 HeapFree(GetProcessHeap(), 0, ai);
5616 ai = next;
5620 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
5621 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
5623 #ifdef HAVE_GETNAMEINFO
5624 int ret;
5625 union generic_unix_sockaddr sa_u;
5626 unsigned int size;
5628 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
5629 serv, servlen, flags);
5631 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
5632 if (!size)
5634 WSASetLastError(WSAEFAULT);
5635 return WSA_NOT_ENOUGH_MEMORY;
5637 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
5638 return convert_eai_u2w(ret);
5639 #else
5640 FIXME("getnameinfo() failed, not found during buildtime.\n");
5641 return EAI_FAIL;
5642 #endif
5645 int WINAPI GetNameInfoW(const SOCKADDR *sa, WS_socklen_t salen, PWCHAR host,
5646 DWORD hostlen, PWCHAR serv, DWORD servlen, INT flags)
5648 int ret;
5649 char *hostA = NULL, *servA = NULL;
5651 if (host && (!(hostA = HeapAlloc(GetProcessHeap(), 0, hostlen)))) return EAI_MEMORY;
5652 if (serv && (!(servA = HeapAlloc(GetProcessHeap(), 0, servlen))))
5654 HeapFree(GetProcessHeap(), 0, hostA);
5655 return EAI_MEMORY;
5658 ret = WS_getnameinfo(sa, salen, hostA, hostlen, servA, servlen, flags);
5659 if (!ret)
5661 if (host) MultiByteToWideChar(CP_ACP, 0, hostA, -1, host, hostlen);
5662 if (serv) MultiByteToWideChar(CP_ACP, 0, servA, -1, serv, servlen);
5665 HeapFree(GetProcessHeap(), 0, hostA);
5666 HeapFree(GetProcessHeap(), 0, servA);
5667 return ret;
5670 /***********************************************************************
5671 * getservbyport (WS2_32.56)
5673 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
5675 struct WS_servent* retval = NULL;
5676 #ifdef HAVE_GETSERVBYPORT
5677 struct servent* serv;
5678 char *proto_str = NULL;
5680 if (proto && *proto)
5682 if (!(proto_str = strdup_lower(proto))) return NULL;
5684 EnterCriticalSection( &csWSgetXXXbyYYY );
5685 if( (serv = getservbyport(port, proto_str)) != NULL ) {
5686 retval = WS_dup_se(serv);
5688 else SetLastError(WSANO_DATA);
5689 LeaveCriticalSection( &csWSgetXXXbyYYY );
5690 HeapFree( GetProcessHeap(), 0, proto_str );
5691 #endif
5692 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
5693 return retval;
5697 /***********************************************************************
5698 * gethostname (WS2_32.57)
5700 int WINAPI WS_gethostname(char *name, int namelen)
5702 TRACE("name %p, len %d\n", name, namelen);
5704 if (gethostname(name, namelen) == 0)
5706 TRACE("<- '%s'\n", name);
5707 return 0;
5709 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
5710 TRACE("<- ERROR !\n");
5711 return SOCKET_ERROR;
5715 /* ------------------------------------- Windows sockets extensions -- *
5717 * ------------------------------------------------------------------- */
5719 /***********************************************************************
5720 * WSAEnumNetworkEvents (WS2_32.36)
5722 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
5724 int ret;
5725 int i;
5726 int errors[FD_MAX_EVENTS];
5728 TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
5730 SERVER_START_REQ( get_socket_event )
5732 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5733 req->service = TRUE;
5734 req->c_event = wine_server_obj_handle( hEvent );
5735 wine_server_set_reply( req, errors, sizeof(errors) );
5736 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
5738 SERVER_END_REQ;
5739 if (!ret)
5741 for (i = 0; i < FD_MAX_EVENTS; i++)
5742 lpEvent->iErrorCode[i] = NtStatusToWSAError(errors[i]);
5743 return 0;
5745 SetLastError(WSAEINVAL);
5746 return SOCKET_ERROR;
5749 /***********************************************************************
5750 * WSAEventSelect (WS2_32.39)
5752 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
5754 int ret;
5756 TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
5758 SERVER_START_REQ( set_socket_event )
5760 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5761 req->mask = lEvent;
5762 req->event = wine_server_obj_handle( hEvent );
5763 req->window = 0;
5764 req->msg = 0;
5765 ret = wine_server_call( req );
5767 SERVER_END_REQ;
5768 if (!ret) return 0;
5769 SetLastError(WSAEINVAL);
5770 return SOCKET_ERROR;
5773 /**********************************************************************
5774 * WSAGetOverlappedResult (WS2_32.40)
5776 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
5777 LPDWORD lpcbTransfer, BOOL fWait,
5778 LPDWORD lpdwFlags )
5780 NTSTATUS status;
5782 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
5783 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
5785 if ( lpOverlapped == NULL )
5787 ERR( "Invalid pointer\n" );
5788 WSASetLastError(WSA_INVALID_PARAMETER);
5789 return FALSE;
5792 status = lpOverlapped->Internal;
5793 if (status == STATUS_PENDING)
5795 if (!fWait)
5797 SetLastError( WSA_IO_INCOMPLETE );
5798 return FALSE;
5801 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
5802 INFINITE ) == WAIT_FAILED)
5803 return FALSE;
5804 status = lpOverlapped->Internal;
5807 if ( lpcbTransfer )
5808 *lpcbTransfer = lpOverlapped->InternalHigh;
5810 if ( lpdwFlags )
5811 *lpdwFlags = lpOverlapped->u.s.Offset;
5813 if (status) SetLastError( RtlNtStatusToDosError(status) );
5814 return !status;
5818 /***********************************************************************
5819 * WSAAsyncSelect (WS2_32.101)
5821 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
5823 int ret;
5825 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
5827 SERVER_START_REQ( set_socket_event )
5829 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5830 req->mask = lEvent;
5831 req->event = 0;
5832 req->window = wine_server_user_handle( hWnd );
5833 req->msg = uMsg;
5834 ret = wine_server_call( req );
5836 SERVER_END_REQ;
5837 if (!ret) return 0;
5838 SetLastError(WSAEINVAL);
5839 return SOCKET_ERROR;
5842 /***********************************************************************
5843 * WSACreateEvent (WS2_32.31)
5846 WSAEVENT WINAPI WSACreateEvent(void)
5848 /* Create a manual-reset event, with initial state: unsignaled */
5849 TRACE("\n");
5851 return CreateEventW(NULL, TRUE, FALSE, NULL);
5854 /***********************************************************************
5855 * WSACloseEvent (WS2_32.29)
5858 BOOL WINAPI WSACloseEvent(WSAEVENT event)
5860 TRACE ("event=%p\n", event);
5862 return CloseHandle(event);
5865 /***********************************************************************
5866 * WSASocketA (WS2_32.78)
5869 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
5870 LPWSAPROTOCOL_INFOA lpProtocolInfo,
5871 GROUP g, DWORD dwFlags)
5873 INT len;
5874 WSAPROTOCOL_INFOW info;
5876 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
5877 af, type, protocol, lpProtocolInfo, g, dwFlags);
5879 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
5881 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
5882 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
5883 info.szProtocol, WSAPROTOCOL_LEN + 1);
5885 if (!len)
5887 WSASetLastError( WSAEINVAL);
5888 return SOCKET_ERROR;
5891 return WSASocketW(af, type, protocol, &info, g, dwFlags);
5894 /***********************************************************************
5895 * WSASocketW (WS2_32.79)
5898 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
5899 LPWSAPROTOCOL_INFOW lpProtocolInfo,
5900 GROUP g, DWORD dwFlags)
5902 SOCKET ret;
5903 DWORD err;
5904 int unixaf, unixtype;
5907 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
5908 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
5911 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
5912 af, type, protocol, lpProtocolInfo, g, dwFlags );
5914 if (!num_startup)
5916 err = WSANOTINITIALISED;
5917 goto done;
5920 /* hack for WSADuplicateSocket */
5921 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
5922 ret = lpProtocolInfo->dwServiceFlags3;
5923 TRACE("\tgot duplicate %04lx\n", ret);
5924 return ret;
5927 if (lpProtocolInfo)
5929 if (af == FROM_PROTOCOL_INFO || !af)
5930 af = lpProtocolInfo->iAddressFamily;
5931 if (type == FROM_PROTOCOL_INFO || !type)
5932 type = lpProtocolInfo->iSocketType;
5933 if (protocol == FROM_PROTOCOL_INFO || !protocol)
5934 protocol = lpProtocolInfo->iProtocol;
5937 if (!type && (af || protocol))
5939 WSAPROTOCOL_INFOW infow;
5941 /* default to the first valid protocol */
5942 if (!protocol)
5943 protocol = valid_protocols[0];
5945 if (WS_EnterSingleProtocolW(protocol, &infow))
5947 type = infow.iSocketType;
5949 /* after win2003 it's no longer possible to pass AF_UNSPEC
5950 using the protocol info struct */
5951 if (!lpProtocolInfo && af == WS_AF_UNSPEC)
5952 af = infow.iAddressFamily;
5956 /* convert the socket family, type and protocol */
5957 unixaf = convert_af_w2u(af);
5958 unixtype = convert_socktype_w2u(type);
5959 protocol = convert_proto_w2u(protocol);
5960 if (unixaf == AF_UNSPEC) unixaf = -1;
5962 /* filter invalid parameters */
5963 if (protocol < 0)
5965 /* the type could not be converted */
5966 if (type && unixtype < 0)
5968 err = WSAESOCKTNOSUPPORT;
5969 goto done;
5972 err = WSAEPROTONOSUPPORT;
5973 goto done;
5975 if (unixaf < 0)
5977 /* both family and protocol can't be invalid */
5978 if (protocol <= 0)
5980 err = WSAEINVAL;
5981 goto done;
5984 /* family could not be converted and neither socket type */
5985 if (unixtype < 0 && af >= 0)
5988 err = WSAESOCKTNOSUPPORT;
5989 goto done;
5992 err = WSAEAFNOSUPPORT;
5993 goto done;
5996 SERVER_START_REQ( create_socket )
5998 req->family = unixaf;
5999 req->type = unixtype;
6000 req->protocol = protocol;
6001 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
6002 req->attributes = OBJ_INHERIT;
6003 req->flags = dwFlags;
6004 set_error( wine_server_call( req ) );
6005 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
6007 SERVER_END_REQ;
6008 if (ret)
6010 TRACE("\tcreated %04lx\n", ret );
6011 return ret;
6014 err = GetLastError();
6015 if (err == WSAEACCES) /* raw socket denied */
6017 if (type == SOCK_RAW)
6018 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
6019 else
6020 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
6022 else
6024 /* invalid combination of valid parameters, like SOCK_STREAM + IPPROTO_UDP */
6025 if (err == WSAEINVAL)
6026 err = WSAESOCKTNOSUPPORT;
6027 else if (err == WSAEOPNOTSUPP)
6028 err = WSAEPROTONOSUPPORT;
6031 done:
6032 WARN("\t\tfailed, error %d!\n", err);
6033 SetLastError(err);
6034 return INVALID_SOCKET;
6037 /***********************************************************************
6038 * WSAJoinLeaf (WS2_32.58)
6041 SOCKET WINAPI WSAJoinLeaf(
6042 SOCKET s,
6043 const struct WS_sockaddr *addr,
6044 int addrlen,
6045 LPWSABUF lpCallerData,
6046 LPWSABUF lpCalleeData,
6047 LPQOS lpSQOS,
6048 LPQOS lpGQOS,
6049 DWORD dwFlags)
6051 FIXME("stub.\n");
6052 return INVALID_SOCKET;
6055 /***********************************************************************
6056 * __WSAFDIsSet (WS2_32.151)
6058 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
6060 int i = set->fd_count;
6062 TRACE("(%ld,%p(%i))\n", s, set, i);
6064 while (i--)
6065 if (set->fd_array[i] == s) return 1;
6066 return 0;
6069 /***********************************************************************
6070 * WSAIsBlocking (WS2_32.114)
6072 BOOL WINAPI WSAIsBlocking(void)
6074 /* By default WinSock should set all its sockets to non-blocking mode
6075 * and poll in PeekMessage loop when processing "blocking" ones. This
6076 * function is supposed to tell if the program is in this loop. Our
6077 * blocking calls are truly blocking so we always return FALSE.
6079 * Note: It is allowed to call this function without prior WSAStartup().
6082 TRACE("\n");
6083 return FALSE;
6086 /***********************************************************************
6087 * WSACancelBlockingCall (WS2_32.113)
6089 INT WINAPI WSACancelBlockingCall(void)
6091 TRACE("\n");
6092 return 0;
6095 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
6097 FIXME("How was this called?\n");
6098 return x();
6102 /***********************************************************************
6103 * WSASetBlockingHook (WS2_32.109)
6105 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
6107 FARPROC prev = blocking_hook;
6108 blocking_hook = lpBlockFunc;
6109 TRACE("hook %p\n", lpBlockFunc);
6110 return prev;
6114 /***********************************************************************
6115 * WSAUnhookBlockingHook (WS2_32.110)
6117 INT WINAPI WSAUnhookBlockingHook(void)
6119 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
6120 return 0;
6124 /* ----------------------------------- end of API stuff */
6126 /* ----------------------------------- helper functions -
6128 * TODO: Merge WS_dup_..() stuff into one function that
6129 * would operate with a generic structure containing internal
6130 * pointers (via a template of some kind).
6133 static int list_size(char** l, int item_size)
6135 int i,j = 0;
6136 if(l)
6137 { for(i=0;l[i];i++)
6138 j += (item_size) ? item_size : strlen(l[i]) + 1;
6139 j += (i + 1) * sizeof(char*); }
6140 return j;
6143 static int list_dup(char** l_src, char** l_to, int item_size)
6145 char *p;
6146 int i;
6148 for (i = 0; l_src[i]; i++) ;
6149 p = (char *)(l_to + i + 1);
6150 for (i = 0; l_src[i]; i++)
6152 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
6153 memcpy(p, l_src[i], count);
6154 l_to[i] = p;
6155 p += count;
6157 l_to[i] = NULL;
6158 return p - (char *)l_to;
6161 /* ----- hostent */
6163 /* create a hostent entry
6165 * Creates the entry with enough memory for the name, aliases
6166 * addresses, and the address pointers. Also copies the name
6167 * and sets up all the pointers.
6169 * NOTE: The alias and address lists must be allocated with room
6170 * for the NULL item terminating the list. This is true even if
6171 * the list has no items ("aliases" and "addresses" must be
6172 * at least "1", a truly empty list is invalid).
6174 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length)
6176 struct WS_hostent *p_to;
6177 char *p;
6178 int size = (sizeof(struct WS_hostent) +
6179 strlen(name) + 1 +
6180 sizeof(char *) * aliases +
6181 aliases_size +
6182 sizeof(char *) * addresses +
6183 address_length * (addresses - 1)), i;
6185 if (!(p_to = check_buffer_he(size))) return NULL;
6186 memset(p_to, 0, size);
6188 /* Use the memory in the same way winsock does.
6189 * First set the pointer for aliases, second set the pointers for addresses.
6190 * Third fill the addresses indexes, fourth jump aliases names size.
6191 * Fifth fill the hostname.
6192 * NOTE: This method is valid for OS version's >= XP.
6194 p = (char *)(p_to + 1);
6195 p_to->h_aliases = (char **)p;
6196 p += sizeof(char *)*aliases;
6198 p_to->h_addr_list = (char **)p;
6199 p += sizeof(char *)*addresses;
6201 for (i = 0, addresses--; i < addresses; i++, p += address_length)
6202 p_to->h_addr_list[i] = p;
6204 /* NOTE: h_aliases must be filled in manually because we don't know each string
6205 * size, leave these pointers NULL (already set to NULL by memset earlier).
6207 p += aliases_size;
6209 p_to->h_name = p;
6210 strcpy(p, name);
6212 return p_to;
6215 /* duplicate hostent entry
6216 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
6217 * Ditto for protoent and servent.
6219 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
6221 int i, addresses = 0, alias_size = 0;
6222 struct WS_hostent *p_to;
6223 char *p;
6225 for( i = 0; p_he->h_aliases[i]; i++) alias_size += strlen(p_he->h_aliases[i]) + 1;
6226 while (p_he->h_addr_list[addresses]) addresses++;
6228 p_to = WS_create_he(p_he->h_name, i + 1, alias_size, addresses + 1, p_he->h_length);
6230 if (!p_to) return NULL;
6231 p_to->h_addrtype = p_he->h_addrtype;
6232 p_to->h_length = p_he->h_length;
6234 for(i = 0, p = p_to->h_addr_list[0]; p_he->h_addr_list[i]; i++, p += p_to->h_length)
6235 memcpy(p, p_he->h_addr_list[i], p_to->h_length);
6237 /* Fill the aliases after the IP data */
6238 for(i = 0; p_he->h_aliases[i]; i++)
6240 p_to->h_aliases[i] = p;
6241 strcpy(p, p_he->h_aliases[i]);
6242 p += strlen(p) + 1;
6245 return p_to;
6248 /* ----- protoent */
6250 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
6252 char *p;
6253 struct WS_protoent *p_to;
6255 int size = (sizeof(*p_pe) +
6256 strlen(p_pe->p_name) + 1 +
6257 list_size(p_pe->p_aliases, 0));
6259 if (!(p_to = check_buffer_pe(size))) return NULL;
6260 p_to->p_proto = p_pe->p_proto;
6262 p = (char *)(p_to + 1);
6263 p_to->p_name = p;
6264 strcpy(p, p_pe->p_name);
6265 p += strlen(p) + 1;
6267 p_to->p_aliases = (char **)p;
6268 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
6269 return p_to;
6272 /* ----- servent */
6274 static struct WS_servent *WS_dup_se(const struct servent* p_se)
6276 char *p;
6277 struct WS_servent *p_to;
6279 int size = (sizeof(*p_se) +
6280 strlen(p_se->s_proto) + 1 +
6281 strlen(p_se->s_name) + 1 +
6282 list_size(p_se->s_aliases, 0));
6284 if (!(p_to = check_buffer_se(size))) return NULL;
6285 p_to->s_port = p_se->s_port;
6287 p = (char *)(p_to + 1);
6288 p_to->s_name = p;
6289 strcpy(p, p_se->s_name);
6290 p += strlen(p) + 1;
6292 p_to->s_proto = p;
6293 strcpy(p, p_se->s_proto);
6294 p += strlen(p) + 1;
6296 p_to->s_aliases = (char **)p;
6297 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
6298 return p_to;
6302 /***********************************************************************
6303 * WSARecv (WS2_32.67)
6305 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6306 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
6307 LPWSAOVERLAPPED lpOverlapped,
6308 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
6310 return WS2_recv_base(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
6311 NULL, NULL, lpOverlapped, lpCompletionRoutine, NULL);
6314 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6315 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
6316 struct WS_sockaddr *lpFrom,
6317 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
6318 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
6319 LPWSABUF lpControlBuffer )
6321 unsigned int i, options;
6322 int n, fd, err;
6323 struct ws2_async *wsa;
6324 BOOL is_blocking;
6325 DWORD timeout_start = GetTickCount();
6326 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
6328 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
6329 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
6330 (lpFromlen ? *lpFromlen : -1),
6331 lpOverlapped, lpCompletionRoutine);
6333 fd = get_sock_fd( s, FILE_READ_DATA, &options );
6334 TRACE( "fd=%d, options=%x\n", fd, options );
6336 if (fd == -1) return SOCKET_ERROR;
6338 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
6340 err = WSAEFAULT;
6341 goto error;
6344 wsa->hSocket = SOCKET2HANDLE(s);
6345 wsa->flags = *lpFlags;
6346 wsa->lpFlags = lpFlags;
6347 wsa->addr = lpFrom;
6348 wsa->addrlen.ptr = lpFromlen;
6349 wsa->control = lpControlBuffer;
6350 wsa->n_iovecs = dwBufferCount;
6351 wsa->first_iovec = 0;
6352 for (i = 0; i < dwBufferCount; i++)
6354 /* check buffer first to trigger write watches */
6355 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
6357 err = WSAEFAULT;
6358 goto error;
6360 wsa->iovec[i].iov_base = lpBuffers[i].buf;
6361 wsa->iovec[i].iov_len = lpBuffers[i].len;
6364 for (;;)
6366 n = WS2_recv( fd, wsa );
6367 if (n == -1)
6369 if (errno == EINTR) continue;
6370 if (errno != EAGAIN)
6372 int loc_errno = errno;
6373 err = wsaErrno();
6374 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
6375 goto error;
6378 else if (lpNumberOfBytesRecvd) *lpNumberOfBytesRecvd = n;
6380 if ((lpOverlapped || lpCompletionRoutine) &&
6381 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
6383 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
6385 wsa->user_overlapped = lpOverlapped;
6386 wsa->completion_func = lpCompletionRoutine;
6387 release_sock_fd( s, fd );
6389 if (n == -1)
6391 iosb->u.Status = STATUS_PENDING;
6392 iosb->Information = 0;
6394 SERVER_START_REQ( register_async )
6396 req->type = ASYNC_TYPE_READ;
6397 req->async.handle = wine_server_obj_handle( wsa->hSocket );
6398 req->async.callback = wine_server_client_ptr( WS2_async_recv );
6399 req->async.iosb = wine_server_client_ptr( iosb );
6400 req->async.arg = wine_server_client_ptr( wsa );
6401 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
6402 req->async.cvalue = cvalue;
6403 err = wine_server_call( req );
6405 SERVER_END_REQ;
6407 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
6408 WSASetLastError( NtStatusToWSAError( err ));
6409 return SOCKET_ERROR;
6412 iosb->u.Status = STATUS_SUCCESS;
6413 iosb->Information = n;
6414 if (!wsa->completion_func)
6416 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
6417 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
6418 HeapFree( GetProcessHeap(), 0, wsa );
6420 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
6421 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
6422 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6423 return 0;
6426 if (n != -1) break;
6428 if ((err = _is_blocking( s, &is_blocking )))
6430 err = NtStatusToWSAError( err );
6431 goto error;
6434 if ( is_blocking )
6436 struct pollfd pfd;
6437 int timeout = GET_RCVTIMEO(fd);
6438 if (timeout != -1)
6440 timeout -= GetTickCount() - timeout_start;
6441 if (timeout < 0) timeout = 0;
6444 pfd.fd = fd;
6445 pfd.events = POLLIN;
6446 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
6448 if (!timeout || !poll( &pfd, 1, timeout ))
6450 err = WSAETIMEDOUT;
6451 /* a timeout is not fatal */
6452 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6453 goto error;
6456 else
6458 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6459 err = WSAEWOULDBLOCK;
6460 goto error;
6464 TRACE(" -> %i bytes\n", n);
6465 HeapFree( GetProcessHeap(), 0, wsa );
6466 release_sock_fd( s, fd );
6467 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6469 return 0;
6471 error:
6472 HeapFree( GetProcessHeap(), 0, wsa );
6473 release_sock_fd( s, fd );
6474 WARN(" -> ERROR %d\n", err);
6475 WSASetLastError( err );
6476 return SOCKET_ERROR;
6479 /***********************************************************************
6480 * WSARecvFrom (WS2_32.69)
6482 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6483 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
6484 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
6485 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
6488 return WS2_recv_base( s, lpBuffers, dwBufferCount,
6489 lpNumberOfBytesRecvd, lpFlags,
6490 lpFrom, lpFromlen,
6491 lpOverlapped, lpCompletionRoutine, NULL );
6494 /***********************************************************************
6495 * WSCInstallProvider (WS2_32.88)
6497 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
6498 LPCWSTR lpszProviderDllPath,
6499 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
6500 DWORD dwNumberOfEntries,
6501 LPINT lpErrno )
6503 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
6504 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
6505 dwNumberOfEntries, lpErrno);
6506 *lpErrno = 0;
6507 return 0;
6511 /***********************************************************************
6512 * WSCDeinstallProvider (WS2_32.83)
6514 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
6516 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
6517 *lpErrno = 0;
6518 return 0;
6522 /***********************************************************************
6523 * WSAAccept (WS2_32.26)
6525 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
6526 LPCONDITIONPROC lpfnCondition, DWORD_PTR dwCallbackData)
6529 int ret = 0, size = 0;
6530 WSABUF CallerId, CallerData, CalleeId, CalleeData;
6531 /* QOS SQOS, GQOS; */
6532 GROUP g;
6533 SOCKET cs;
6534 SOCKADDR src_addr, dst_addr;
6536 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
6537 s, addr, addrlen, lpfnCondition, dwCallbackData);
6540 size = sizeof(src_addr);
6541 cs = WS_accept(s, &src_addr, &size);
6543 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
6545 if (!lpfnCondition) return cs;
6547 CallerId.buf = (char *)&src_addr;
6548 CallerId.len = sizeof(src_addr);
6550 CallerData.buf = NULL;
6551 CallerData.len = 0;
6553 WS_getsockname(cs, &dst_addr, &size);
6555 CalleeId.buf = (char *)&dst_addr;
6556 CalleeId.len = sizeof(dst_addr);
6559 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
6560 &CalleeId, &CalleeData, &g, dwCallbackData);
6562 switch (ret)
6564 case CF_ACCEPT:
6565 if (addr && addrlen)
6566 memcpy(addr, &src_addr, (*addrlen > size) ? size : *addrlen );
6567 return cs;
6568 case CF_DEFER:
6569 SERVER_START_REQ( set_socket_deferred )
6571 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6572 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
6573 if ( !wine_server_call_err ( req ) )
6575 SetLastError( WSATRY_AGAIN );
6576 WS_closesocket( cs );
6579 SERVER_END_REQ;
6580 return SOCKET_ERROR;
6581 case CF_REJECT:
6582 WS_closesocket(cs);
6583 SetLastError(WSAECONNREFUSED);
6584 return SOCKET_ERROR;
6585 default:
6586 FIXME("Unknown return type from Condition function\n");
6587 SetLastError(WSAENOTSOCK);
6588 return SOCKET_ERROR;
6592 /***********************************************************************
6593 * WSADuplicateSocketA (WS2_32.32)
6595 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
6597 return WS_DuplicateSocket(FALSE, s, dwProcessId, (LPWSAPROTOCOL_INFOW) lpProtocolInfo);
6600 /***********************************************************************
6601 * WSADuplicateSocketW (WS2_32.33)
6603 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
6605 return WS_DuplicateSocket(TRUE, s, dwProcessId, lpProtocolInfo);
6608 /***********************************************************************
6609 * WSAInstallServiceClassA (WS2_32.48)
6611 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
6613 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
6614 WSASetLastError(WSAEACCES);
6615 return SOCKET_ERROR;
6618 /***********************************************************************
6619 * WSAInstallServiceClassW (WS2_32.49)
6621 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
6623 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
6624 WSASetLastError(WSAEACCES);
6625 return SOCKET_ERROR;
6628 /***********************************************************************
6629 * WSARemoveServiceClass (WS2_32.70)
6631 int WINAPI WSARemoveServiceClass(LPGUID info)
6633 FIXME("Request to remove service %p\n",info);
6634 WSASetLastError(WSATYPE_NOT_FOUND);
6635 return SOCKET_ERROR;
6638 /***********************************************************************
6639 * inet_ntop (WS2_32.@)
6641 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
6643 #ifdef HAVE_INET_NTOP
6644 struct WS_in6_addr *in6;
6645 struct WS_in_addr *in;
6646 PCSTR pdst;
6648 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
6649 if (!buffer)
6651 WSASetLastError( STATUS_INVALID_PARAMETER );
6652 return NULL;
6655 switch (family)
6657 case WS_AF_INET:
6659 in = addr;
6660 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
6661 break;
6663 case WS_AF_INET6:
6665 in6 = addr;
6666 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
6667 break;
6669 default:
6670 WSASetLastError( WSAEAFNOSUPPORT );
6671 return NULL;
6674 if (!pdst) WSASetLastError( STATUS_INVALID_PARAMETER );
6675 return pdst;
6676 #else
6677 FIXME( "not supported on this platform\n" );
6678 WSASetLastError( WSAEAFNOSUPPORT );
6679 return NULL;
6680 #endif
6683 /***********************************************************************
6684 * WSAStringToAddressA (WS2_32.80)
6686 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
6687 INT AddressFamily,
6688 LPWSAPROTOCOL_INFOA lpProtocolInfo,
6689 LPSOCKADDR lpAddress,
6690 LPINT lpAddressLength)
6692 INT res=0;
6693 LPSTR workBuffer=NULL,ptrPort;
6695 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
6696 lpProtocolInfo, lpAddress, lpAddressLength );
6698 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
6700 if (!AddressString)
6702 WSASetLastError(WSAEINVAL);
6703 return SOCKET_ERROR;
6706 if (lpProtocolInfo)
6707 FIXME("ProtocolInfo not implemented.\n");
6709 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
6710 strlen(AddressString) + 1);
6711 if (!workBuffer)
6713 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6714 return SOCKET_ERROR;
6717 strcpy(workBuffer, AddressString);
6719 switch(AddressFamily)
6721 case WS_AF_INET:
6723 struct in_addr inetaddr;
6725 /* If lpAddressLength is too small, tell caller the size we need */
6726 if (*lpAddressLength < sizeof(SOCKADDR_IN))
6728 *lpAddressLength = sizeof(SOCKADDR_IN);
6729 res = WSAEFAULT;
6730 break;
6732 *lpAddressLength = sizeof(SOCKADDR_IN);
6733 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
6735 ((LPSOCKADDR_IN)lpAddress)->sin_family = AF_INET;
6737 ptrPort = strchr(workBuffer, ':');
6738 if(ptrPort)
6740 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
6741 *ptrPort = '\0';
6743 else
6745 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
6748 if(inet_aton(workBuffer, &inetaddr) > 0)
6750 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
6751 res = 0;
6753 else
6754 res = WSAEINVAL;
6756 break;
6759 case WS_AF_INET6:
6761 struct in6_addr inetaddr;
6762 /* If lpAddressLength is too small, tell caller the size we need */
6763 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
6765 *lpAddressLength = sizeof(SOCKADDR_IN6);
6766 res = WSAEFAULT;
6767 break;
6769 #ifdef HAVE_INET_PTON
6770 *lpAddressLength = sizeof(SOCKADDR_IN6);
6771 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
6773 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
6775 /* This one is a bit tricky. An IPv6 address contains colons, so the
6776 * check from IPv4 doesn't work like that. However, IPv6 addresses that
6777 * contain a port are written with braces like [fd12:3456:7890::1]:12345
6778 * so what we will do is to look for ']', check if the next char is a
6779 * colon, and if it is, parse the port as in IPv4. */
6781 ptrPort = strchr(workBuffer, ']');
6782 if(ptrPort && *(++ptrPort) == ':')
6784 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort+1));
6785 *ptrPort = '\0';
6787 else
6789 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
6792 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
6794 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
6795 sizeof(struct in6_addr));
6796 res = 0;
6798 else
6799 #endif /* HAVE_INET_PTON */
6800 res = WSAEINVAL;
6802 break;
6804 default:
6805 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
6806 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
6807 res = WSAEINVAL;
6810 HeapFree(GetProcessHeap(), 0, workBuffer);
6812 if (!res) return 0;
6813 WSASetLastError(res);
6814 return SOCKET_ERROR;
6817 /***********************************************************************
6818 * WSAStringToAddressW (WS2_32.81)
6820 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
6821 * If this should be the case, it would be required to map these digits
6822 * to Unicode digits (0-9) using FoldString first.
6824 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
6825 INT AddressFamily,
6826 LPWSAPROTOCOL_INFOW lpProtocolInfo,
6827 LPSOCKADDR lpAddress,
6828 LPINT lpAddressLength)
6830 INT sBuffer,res=0;
6831 LPSTR workBuffer=NULL;
6832 WSAPROTOCOL_INFOA infoA;
6833 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
6835 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
6836 lpAddress, lpAddressLength );
6838 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
6840 /* if ProtocolInfo is available - convert to ANSI variant */
6841 if (lpProtocolInfo)
6843 lpProtoInfoA = &infoA;
6844 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
6846 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
6847 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
6849 WSASetLastError( WSAEINVAL);
6850 return SOCKET_ERROR;
6854 if (AddressString)
6856 /* Translate AddressString to ANSI code page - assumes that only
6857 standard digits 0-9 are used with this API call */
6858 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
6859 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
6861 if (workBuffer)
6863 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
6864 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
6865 lpAddress,lpAddressLength);
6866 HeapFree( GetProcessHeap(), 0, workBuffer );
6867 return res;
6869 else
6870 res = WSA_NOT_ENOUGH_MEMORY;
6872 else
6873 res = WSAEINVAL;
6875 WSASetLastError(res);
6876 return SOCKET_ERROR;
6879 /***********************************************************************
6880 * WSAAddressToStringA (WS2_32.27)
6882 * See WSAAddressToStringW
6884 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
6885 LPWSAPROTOCOL_INFOA info, LPSTR string,
6886 LPDWORD lenstr )
6888 DWORD size;
6889 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
6890 CHAR *p;
6892 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
6894 if (!sockaddr) return SOCKET_ERROR;
6895 if (!string || !lenstr) return SOCKET_ERROR;
6897 switch(sockaddr->sa_family)
6899 case WS_AF_INET:
6900 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
6901 sprintf( buffer, "%u.%u.%u.%u:%u",
6902 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
6903 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
6904 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
6905 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
6906 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
6908 p = strchr( buffer, ':' );
6909 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
6910 break;
6912 case WS_AF_INET6:
6914 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
6916 buffer[0] = 0;
6917 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
6918 if ((sockaddr6->sin6_port))
6919 strcpy(buffer, "[");
6920 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, buffer+strlen(buffer), sizeof(buffer)))
6922 WSASetLastError(WSAEINVAL);
6923 return SOCKET_ERROR;
6925 if ((sockaddr6->sin6_scope_id))
6926 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
6927 if ((sockaddr6->sin6_port))
6928 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
6929 break;
6932 default:
6933 WSASetLastError(WSAEINVAL);
6934 return SOCKET_ERROR;
6937 size = strlen( buffer ) + 1;
6939 if (*lenstr < size)
6941 *lenstr = size;
6942 WSASetLastError(WSAEFAULT);
6943 return SOCKET_ERROR;
6946 *lenstr = size;
6947 strcpy( string, buffer );
6948 return 0;
6951 /***********************************************************************
6952 * WSAAddressToStringW (WS2_32.28)
6954 * Convert a sockaddr address into a readable address string.
6956 * PARAMS
6957 * sockaddr [I] Pointer to a sockaddr structure.
6958 * len [I] Size of the sockaddr structure.
6959 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
6960 * string [I/O] Pointer to a buffer to receive the address string.
6961 * lenstr [I/O] Size of the receive buffer in WCHARs.
6963 * RETURNS
6964 * Success: 0
6965 * Failure: SOCKET_ERROR
6967 * NOTES
6968 * The 'info' parameter is ignored.
6970 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
6971 LPWSAPROTOCOL_INFOW info, LPWSTR string,
6972 LPDWORD lenstr )
6974 INT ret;
6975 DWORD size;
6976 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
6977 CHAR bufAddr[54];
6979 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
6981 size = *lenstr;
6982 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
6984 if (ret) return ret;
6986 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
6988 if (*lenstr < size)
6990 *lenstr = size;
6991 WSASetLastError(WSAEFAULT);
6992 return SOCKET_ERROR;
6995 *lenstr = size;
6996 lstrcpyW( string, buffer );
6997 return 0;
7000 /***********************************************************************
7001 * WSAEnumNameSpaceProvidersA (WS2_32.34)
7003 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
7005 FIXME( "(%p %p) Stub!\n", len, buffer );
7006 return 0;
7009 /***********************************************************************
7010 * WSAEnumNameSpaceProvidersW (WS2_32.35)
7012 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
7014 FIXME( "(%p %p) Stub!\n", len, buffer );
7015 return 0;
7018 /***********************************************************************
7019 * WSAGetQOSByName (WS2_32.41)
7021 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
7023 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
7024 return FALSE;
7027 /***********************************************************************
7028 * WSAGetServiceClassInfoA (WS2_32.42)
7030 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
7031 LPWSASERVICECLASSINFOA info )
7033 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
7034 len, info );
7035 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7036 return SOCKET_ERROR;
7039 /***********************************************************************
7040 * WSAGetServiceClassInfoW (WS2_32.43)
7042 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
7043 LPWSASERVICECLASSINFOW info )
7045 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
7046 len, info );
7047 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7048 return SOCKET_ERROR;
7051 /***********************************************************************
7052 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
7054 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
7056 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
7057 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7058 return SOCKET_ERROR;
7061 /***********************************************************************
7062 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
7064 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
7066 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
7067 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7068 return SOCKET_ERROR;
7071 /***********************************************************************
7072 * WSALookupServiceBeginA (WS2_32.59)
7074 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
7075 DWORD dwControlFlags,
7076 LPHANDLE lphLookup)
7078 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
7079 lphLookup);
7080 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7081 return SOCKET_ERROR;
7084 /***********************************************************************
7085 * WSALookupServiceBeginW (WS2_32.60)
7087 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
7088 DWORD dwControlFlags,
7089 LPHANDLE lphLookup)
7091 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
7092 lphLookup);
7093 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7094 return SOCKET_ERROR;
7097 /***********************************************************************
7098 * WSALookupServiceEnd (WS2_32.61)
7100 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
7102 FIXME("(%p) Stub!\n", lookup );
7103 return 0;
7106 /***********************************************************************
7107 * WSALookupServiceNextA (WS2_32.62)
7109 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
7111 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
7112 WSASetLastError(WSA_E_NO_MORE);
7113 return SOCKET_ERROR;
7116 /***********************************************************************
7117 * WSALookupServiceNextW (WS2_32.63)
7119 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
7121 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
7122 WSASetLastError(WSA_E_NO_MORE);
7123 return SOCKET_ERROR;
7126 /***********************************************************************
7127 * WSANtohl (WS2_32.64)
7129 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
7131 TRACE( "(0x%04lx 0x%08x %p)\n", s, netlong, lphostlong );
7133 if (!lphostlong) return WSAEFAULT;
7135 *lphostlong = ntohl( netlong );
7136 return 0;
7139 /***********************************************************************
7140 * WSANtohs (WS2_32.65)
7142 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
7144 TRACE( "(0x%04lx 0x%08x %p)\n", s, netshort, lphostshort );
7146 if (!lphostshort) return WSAEFAULT;
7148 *lphostshort = ntohs( netshort );
7149 return 0;
7152 /***********************************************************************
7153 * WSAProviderConfigChange (WS2_32.66)
7155 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
7156 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
7158 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
7159 return SOCKET_ERROR;
7162 /***********************************************************************
7163 * WSARecvDisconnect (WS2_32.68)
7165 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
7167 TRACE( "(0x%04lx %p)\n", s, disconnectdata );
7169 return WS_shutdown( s, 0 );
7172 /***********************************************************************
7173 * WSASetServiceA (WS2_32.76)
7175 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
7177 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
7178 return 0;
7181 /***********************************************************************
7182 * WSASetServiceW (WS2_32.77)
7184 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
7186 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
7187 return 0;
7190 /***********************************************************************
7191 * WSCEnableNSProvider (WS2_32.84)
7193 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
7195 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
7196 return 0;
7199 /***********************************************************************
7200 * WSCGetProviderPath (WS2_32.86)
7202 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
7204 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
7206 if (!errcode || !provider || !len) return WSAEFAULT;
7208 *errcode = WSAEINVAL;
7209 return SOCKET_ERROR;
7212 /***********************************************************************
7213 * WSCInstallNameSpace (WS2_32.87)
7215 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
7216 DWORD version, LPGUID provider )
7218 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
7219 namespace, version, debugstr_guid(provider) );
7220 return 0;
7223 /***********************************************************************
7224 * WSCUnInstallNameSpace (WS2_32.89)
7226 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
7228 FIXME("(%p) Stub!\n", lpProviderId);
7229 return NO_ERROR;
7232 /***********************************************************************
7233 * WSCWriteProviderOrder (WS2_32.91)
7235 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
7237 FIXME("(%p 0x%08x) Stub!\n", entry, number);
7238 return 0;
7241 /***********************************************************************
7242 * WSANSPIoctl (WS2_32.91)
7244 INT WINAPI WSANSPIoctl( HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer,
7245 DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer,
7246 LPDWORD lpcbBytesReturned, LPWSACOMPLETION lpCompletion )
7248 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup, dwControlCode,
7249 lpvInBuffer, cbInBuffer, lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpCompletion);
7250 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7251 return SOCKET_ERROR;
7254 /*****************************************************************************
7255 * WSAEnumProtocolsA [WS2_32.@]
7257 * see function WSAEnumProtocolsW
7259 INT WINAPI WSAEnumProtocolsA( LPINT protocols, LPWSAPROTOCOL_INFOA buffer, LPDWORD len )
7261 return WS_EnumProtocols( FALSE, protocols, (LPWSAPROTOCOL_INFOW) buffer, len);
7264 /*****************************************************************************
7265 * WSAEnumProtocolsW [WS2_32.@]
7267 * Retrieves information about specified set of active network protocols.
7269 * PARAMS
7270 * protocols [I] Pointer to null-terminated array of protocol id's. NULL
7271 * retrieves information on all available protocols.
7272 * buffer [I] Pointer to a buffer to be filled with WSAPROTOCOL_INFO
7273 * structures.
7274 * len [I/O] Pointer to a variable specifying buffer size. On output
7275 * the variable holds the number of bytes needed when the
7276 * specified size is too small.
7278 * RETURNS
7279 * Success: number of WSAPROTOCOL_INFO structures in buffer.
7280 * Failure: SOCKET_ERROR
7282 * NOTES
7283 * NT4SP5 does not return SPX if protocols == NULL
7285 * BUGS
7286 * - NT4SP5 returns in addition these list of NETBIOS protocols
7287 * (address family 17), each entry two times one for socket type 2 and 5
7289 * iProtocol szProtocol
7290 * 0x80000000 \Device\NwlnkNb
7291 * 0xfffffffa \Device\NetBT_CBENT7
7292 * 0xfffffffb \Device\Nbf_CBENT7
7293 * 0xfffffffc \Device\NetBT_NdisWan5
7294 * 0xfffffffd \Device\NetBT_El9202
7295 * 0xfffffffe \Device\Nbf_El9202
7296 * 0xffffffff \Device\Nbf_NdisWan4
7298 * - there is no check that the operating system supports the returned
7299 * protocols
7301 INT WINAPI WSAEnumProtocolsW( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
7303 return WS_EnumProtocols( TRUE, protocols, buffer, len);
7306 /*****************************************************************************
7307 * WSCEnumProtocols [WS2_32.@]
7309 * PARAMS
7310 * protocols [I] Null-terminated array of iProtocol values.
7311 * buffer [O] Buffer of WSAPROTOCOL_INFOW structures.
7312 * len [I/O] Size of buffer on input/output.
7313 * errno [O] Error code.
7315 * RETURNS
7316 * Success: number of protocols to be reported on.
7317 * Failure: SOCKET_ERROR. error is in errno.
7319 * BUGS
7320 * Doesn't supply info on layered protocols.
7323 INT WINAPI WSCEnumProtocols( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len, LPINT err )
7325 INT ret = WSAEnumProtocolsW( protocols, buffer, len );
7327 if (ret == SOCKET_ERROR) *err = WSAENOBUFS;
7329 return ret;