ws2_32: Normalize IPX protocol names using the WS prefix.
[wine.git] / dlls / ws2_32 / socket.c
blob8f9c491126459b1c78cb1f1ea186884ed20d4cfc
1 /*
2 * based on Windows Sockets 1.1 specs
4 * Copyright (C) 1993,1994,1996,1997 John Brezak, Erik Bos, Alex Korobka.
5 * Copyright (C) 2001 Stefan Leichter
6 * Copyright (C) 2004 Hans Leidekker
7 * Copyright (C) 2005 Marcus Meissner
8 * Copyright (C) 2006-2008 Kai Blin
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24 * NOTE: If you make any changes to fix a particular app, make sure
25 * they don't break something else like Netscape or telnet and ftp
26 * clients and servers (www.winsite.com got a lot of those).
29 #include "config.h"
30 #include "wine/port.h"
32 #include <stdarg.h>
33 #include <stdio.h>
34 #include <string.h>
35 #include <sys/types.h>
36 #ifdef HAVE_SYS_IPC_H
37 # include <sys/ipc.h>
38 #endif
39 #ifdef HAVE_SYS_IOCTL_H
40 # include <sys/ioctl.h>
41 #endif
42 #ifdef HAVE_SYS_FILIO_H
43 # include <sys/filio.h>
44 #endif
45 #ifdef HAVE_SYS_SOCKIO_H
46 # include <sys/sockio.h>
47 #endif
49 #if defined(__EMX__)
50 # include <sys/so_ioctl.h>
51 #endif
53 #ifdef HAVE_SYS_PARAM_H
54 # include <sys/param.h>
55 #endif
57 #ifdef HAVE_SYS_MSG_H
58 # include <sys/msg.h>
59 #endif
60 #ifdef HAVE_SYS_WAIT_H
61 # include <sys/wait.h>
62 #endif
63 #ifdef HAVE_SYS_UIO_H
64 # include <sys/uio.h>
65 #endif
66 #ifdef HAVE_SYS_SOCKET_H
67 #include <sys/socket.h>
68 #endif
69 #ifdef HAVE_NETINET_IN_H
70 # include <netinet/in.h>
71 #endif
72 #ifdef HAVE_NETINET_TCP_H
73 # include <netinet/tcp.h>
74 #endif
75 #ifdef HAVE_ARPA_INET_H
76 # include <arpa/inet.h>
77 #endif
78 #include <ctype.h>
79 #include <fcntl.h>
80 #include <errno.h>
81 #ifdef HAVE_NETDB_H
82 #include <netdb.h>
83 #endif
84 #ifdef HAVE_UNISTD_H
85 # include <unistd.h>
86 #endif
87 #include <stdlib.h>
88 #ifdef HAVE_ARPA_NAMESER_H
89 # include <arpa/nameser.h>
90 #endif
91 #ifdef HAVE_RESOLV_H
92 # include <resolv.h>
93 #endif
94 #ifdef HAVE_NET_IF_H
95 # include <net/if.h>
96 #endif
97 #ifdef HAVE_LINUX_FILTER_H
98 # include <linux/filter.h>
99 #endif
101 #ifdef HAVE_NETIPX_IPX_H
102 # include <netipx/ipx.h>
103 # define HAS_IPX
104 #elif defined(HAVE_LINUX_IPX_H)
105 # ifdef HAVE_ASM_TYPES_H
106 # include <asm/types.h>
107 # endif
108 # ifdef HAVE_LINUX_TYPES_H
109 # include <linux/types.h>
110 # endif
111 # include <linux/ipx.h>
112 # define HAS_IPX
113 #endif
115 #ifdef HAVE_LINUX_IRDA_H
116 # ifdef HAVE_LINUX_TYPES_H
117 # include <linux/types.h>
118 # endif
119 # include <linux/irda.h>
120 # define HAS_IRDA
121 #endif
123 #ifdef HAVE_POLL_H
124 #include <poll.h>
125 #endif
126 #ifdef HAVE_SYS_POLL_H
127 # include <sys/poll.h>
128 #endif
129 #ifdef HAVE_SYS_TIME_H
130 # include <sys/time.h>
131 #endif
133 #define NONAMELESSUNION
134 #define NONAMELESSSTRUCT
135 #include "ntstatus.h"
136 #define WIN32_NO_STATUS
137 #include "windef.h"
138 #include "winbase.h"
139 #include "wingdi.h"
140 #include "winuser.h"
141 #include "winerror.h"
142 #include "winnls.h"
143 #include "winsock2.h"
144 #include "mswsock.h"
145 #include "ws2tcpip.h"
146 #include "ws2spi.h"
147 #include "wsipx.h"
148 #include "wshisotp.h"
149 #include "mstcpip.h"
150 #include "af_irda.h"
151 #include "winnt.h"
152 #define USE_WC_PREFIX /* For CMSG_DATA */
153 #include "iphlpapi.h"
154 #include "wine/server.h"
155 #include "wine/debug.h"
156 #include "wine/exception.h"
157 #include "wine/unicode.h"
159 #ifdef HAS_IPX
160 # include "wsnwlink.h"
161 #endif
163 #if defined(linux) && !defined(IP_UNICAST_IF)
164 #define IP_UNICAST_IF 50
165 #endif
167 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
168 # define sipx_network sipx_addr.x_net
169 # define sipx_node sipx_addr.x_host.c_host
170 #endif /* __FreeBSD__ */
172 #ifndef INADDR_NONE
173 #define INADDR_NONE ~0UL
174 #endif
176 WINE_DEFAULT_DEBUG_CHANNEL(winsock);
177 WINE_DECLARE_DEBUG_CHANNEL(winediag);
179 /* names of the protocols */
180 static const WCHAR NameIpxW[] = {'I', 'P', 'X', '\0'};
181 static const WCHAR NameSpxW[] = {'S', 'P', 'X', '\0'};
182 static const WCHAR NameSpxIIW[] = {'S', 'P', 'X', ' ', 'I', 'I', '\0'};
183 static const WCHAR NameTcpW[] = {'T', 'C', 'P', '/', 'I', 'P', '\0'};
184 static const WCHAR NameUdpW[] = {'U', 'D', 'P', '/', 'I', 'P', '\0'};
186 /* Taken from Win2k */
187 static const GUID ProviderIdIP = { 0xe70f1aa0, 0xab8b, 0x11cf,
188 { 0x8c, 0xa3, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
189 static const GUID ProviderIdIPX = { 0x11058240, 0xbe47, 0x11cf,
190 { 0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
191 static const GUID ProviderIdSPX = { 0x11058241, 0xbe47, 0x11cf,
192 { 0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
194 static const INT valid_protocols[] =
196 WS_IPPROTO_TCP,
197 WS_IPPROTO_UDP,
198 WS_NSPROTO_IPX,
199 WS_NSPROTO_SPX,
200 WS_NSPROTO_SPXII,
204 #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;
381 char ntoa_buffer[16]; /* 4*3 digits + 3 '.' + 1 '\0' */
384 /* internal: routing description information */
385 struct route {
386 struct in_addr addr;
387 IF_INDEX interface;
388 DWORD metric;
391 static INT num_startup; /* reference counter */
392 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
394 /* function prototypes */
395 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length);
396 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
397 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
398 static struct WS_servent *WS_dup_se(const struct servent* p_se);
399 static int ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size);
401 int WSAIOCTL_GetInterfaceCount(void);
402 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
404 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus, ULONG Information );
406 #define MAP_OPTION(opt) { WS_##opt, opt }
408 static const int ws_sock_map[][2] =
410 MAP_OPTION( SO_DEBUG ),
411 MAP_OPTION( SO_ACCEPTCONN ),
412 MAP_OPTION( SO_REUSEADDR ),
413 MAP_OPTION( SO_KEEPALIVE ),
414 MAP_OPTION( SO_DONTROUTE ),
415 MAP_OPTION( SO_BROADCAST ),
416 MAP_OPTION( SO_LINGER ),
417 MAP_OPTION( SO_OOBINLINE ),
418 MAP_OPTION( SO_SNDBUF ),
419 MAP_OPTION( SO_RCVBUF ),
420 MAP_OPTION( SO_ERROR ),
421 MAP_OPTION( SO_TYPE ),
422 #ifdef SO_RCVTIMEO
423 MAP_OPTION( SO_RCVTIMEO ),
424 #endif
425 #ifdef SO_SNDTIMEO
426 MAP_OPTION( SO_SNDTIMEO ),
427 #endif
430 static const int ws_tcp_map[][2] =
432 #ifdef TCP_NODELAY
433 MAP_OPTION( TCP_NODELAY ),
434 #endif
437 static const int ws_ip_map[][2] =
439 MAP_OPTION( IP_MULTICAST_IF ),
440 MAP_OPTION( IP_MULTICAST_TTL ),
441 MAP_OPTION( IP_MULTICAST_LOOP ),
442 MAP_OPTION( IP_ADD_MEMBERSHIP ),
443 MAP_OPTION( IP_DROP_MEMBERSHIP ),
444 MAP_OPTION( IP_OPTIONS ),
445 #ifdef IP_HDRINCL
446 MAP_OPTION( IP_HDRINCL ),
447 #endif
448 MAP_OPTION( IP_TOS ),
449 MAP_OPTION( IP_TTL ),
450 #ifdef IP_PKTINFO
451 MAP_OPTION( IP_PKTINFO ),
452 #endif
453 #ifdef IP_UNICAST_IF
454 MAP_OPTION( IP_UNICAST_IF ),
455 #endif
458 static const int ws_ipv6_map[][2] =
460 #ifdef IPV6_ADD_MEMBERSHIP
461 MAP_OPTION( IPV6_ADD_MEMBERSHIP ),
462 #endif
463 #ifdef IPV6_DROP_MEMBERSHIP
464 MAP_OPTION( IPV6_DROP_MEMBERSHIP ),
465 #endif
466 MAP_OPTION( IPV6_MULTICAST_IF ),
467 MAP_OPTION( IPV6_MULTICAST_HOPS ),
468 MAP_OPTION( IPV6_MULTICAST_LOOP ),
469 MAP_OPTION( IPV6_UNICAST_HOPS ),
470 MAP_OPTION( IPV6_V6ONLY ),
471 #ifdef IPV6_UNICAST_IF
472 MAP_OPTION( IPV6_UNICAST_IF ),
473 #endif
476 static const int ws_af_map[][2] =
478 MAP_OPTION( AF_UNSPEC ),
479 MAP_OPTION( AF_INET ),
480 MAP_OPTION( AF_INET6 ),
481 #ifdef HAS_IPX
482 MAP_OPTION( AF_IPX ),
483 #endif
484 #ifdef AF_IRDA
485 MAP_OPTION( AF_IRDA ),
486 #endif
487 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
490 static const int ws_socktype_map[][2] =
492 MAP_OPTION( SOCK_DGRAM ),
493 MAP_OPTION( SOCK_STREAM ),
494 MAP_OPTION( SOCK_RAW ),
495 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
498 static const int ws_proto_map[][2] =
500 MAP_OPTION( IPPROTO_IP ),
501 MAP_OPTION( IPPROTO_TCP ),
502 MAP_OPTION( IPPROTO_UDP ),
503 MAP_OPTION( IPPROTO_ICMP ),
504 MAP_OPTION( IPPROTO_IGMP ),
505 MAP_OPTION( IPPROTO_RAW ),
506 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
509 static const int ws_aiflag_map[][2] =
511 MAP_OPTION( AI_PASSIVE ),
512 MAP_OPTION( AI_CANONNAME ),
513 MAP_OPTION( AI_NUMERICHOST ),
514 MAP_OPTION( AI_V4MAPPED ),
515 MAP_OPTION( AI_ADDRCONFIG ),
518 static const int ws_niflag_map[][2] =
520 MAP_OPTION( NI_NOFQDN ),
521 MAP_OPTION( NI_NUMERICHOST ),
522 MAP_OPTION( NI_NAMEREQD ),
523 MAP_OPTION( NI_NUMERICSERV ),
524 MAP_OPTION( NI_DGRAM ),
527 static const int ws_eai_map[][2] =
529 MAP_OPTION( EAI_AGAIN ),
530 MAP_OPTION( EAI_BADFLAGS ),
531 MAP_OPTION( EAI_FAIL ),
532 MAP_OPTION( EAI_FAMILY ),
533 MAP_OPTION( EAI_MEMORY ),
534 /* Note: EAI_NODATA is deprecated, but still
535 * used by Windows and Linux... We map the newer
536 * EAI_NONAME to EAI_NODATA for now until Windows
537 * changes too.
539 #ifdef EAI_NODATA
540 MAP_OPTION( EAI_NODATA ),
541 #endif
542 #ifdef EAI_NONAME
543 { WS_EAI_NODATA, EAI_NONAME },
544 #endif
546 MAP_OPTION( EAI_SERVICE ),
547 MAP_OPTION( EAI_SOCKTYPE ),
548 { 0, 0 }
551 static const char magic_loopback_addr[] = {127, 12, 34, 56};
553 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
554 static inline WSACMSGHDR *fill_control_message(int level, int type, WSACMSGHDR *current, ULONG *maxsize, void *data, int len)
556 ULONG msgsize = sizeof(WSACMSGHDR) + WSA_CMSG_ALIGN(len);
557 char *ptr = (char *) current + sizeof(WSACMSGHDR);
559 /* Make sure there is at least enough room for this entry */
560 if (msgsize > *maxsize)
561 return NULL;
562 *maxsize -= msgsize;
563 /* Fill in the entry */
564 current->cmsg_len = sizeof(WSACMSGHDR) + len;
565 current->cmsg_level = level;
566 current->cmsg_type = type;
567 memcpy(ptr, data, len);
568 /* Return the pointer to where next entry should go */
569 return (WSACMSGHDR *) (ptr + WSA_CMSG_ALIGN(len));
572 static inline int convert_control_headers(struct msghdr *hdr, WSABUF *control)
574 #ifdef IP_PKTINFO
575 WSACMSGHDR *cmsg_win = (WSACMSGHDR *) control->buf, *ptr;
576 ULONG ctlsize = control->len;
577 struct cmsghdr *cmsg_unix;
579 ptr = cmsg_win;
580 /* Loop over all the headers, converting as appropriate */
581 for (cmsg_unix = CMSG_FIRSTHDR(hdr); cmsg_unix != NULL; cmsg_unix = CMSG_NXTHDR(hdr, cmsg_unix))
583 switch(cmsg_unix->cmsg_level)
585 case IPPROTO_IP:
586 switch(cmsg_unix->cmsg_type)
588 case IP_PKTINFO:
590 /* Convert the Unix IP_PKTINFO structure to the Windows version */
591 struct in_pktinfo *data_unix = (struct in_pktinfo *) CMSG_DATA(cmsg_unix);
592 struct WS_in_pktinfo data_win;
594 memcpy(&data_win.ipi_addr,&data_unix->ipi_addr.s_addr,4); /* 4 bytes = 32 address bits */
595 data_win.ipi_ifindex = data_unix->ipi_ifindex;
596 ptr = fill_control_message(WS_IPPROTO_IP, WS_IP_PKTINFO, ptr, &ctlsize,
597 (void*)&data_win, sizeof(data_win));
598 if (!ptr) goto error;
599 } break;
600 default:
601 FIXME("Unhandled IPPROTO_IP message header type %d\n", cmsg_unix->cmsg_type);
602 break;
604 break;
605 default:
606 FIXME("Unhandled message header level %d\n", cmsg_unix->cmsg_level);
607 break;
611 error:
612 /* Set the length of the returned control headers */
613 control->len = (ptr == NULL ? 0 : (char*)ptr - (char*)cmsg_win);
614 return (ptr != NULL);
615 #else /* IP_PKTINFO */
616 control->len = 0;
617 return 1;
618 #endif /* IP_PKTINFO */
620 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
622 /* ----------------------------------- error handling */
624 static NTSTATUS sock_get_ntstatus( int err )
626 switch ( err )
628 case EBADF: return STATUS_INVALID_HANDLE;
629 case EBUSY: return STATUS_DEVICE_BUSY;
630 case EPERM:
631 case EACCES: return STATUS_ACCESS_DENIED;
632 case EFAULT: return STATUS_NO_MEMORY;
633 case EINVAL: return STATUS_INVALID_PARAMETER;
634 case ENFILE:
635 case EMFILE: return STATUS_TOO_MANY_OPENED_FILES;
636 case EWOULDBLOCK: return STATUS_CANT_WAIT;
637 case EINPROGRESS: return STATUS_PENDING;
638 case EALREADY: return STATUS_NETWORK_BUSY;
639 case ENOTSOCK: return STATUS_OBJECT_TYPE_MISMATCH;
640 case EDESTADDRREQ: return STATUS_INVALID_PARAMETER;
641 case EMSGSIZE: return STATUS_BUFFER_OVERFLOW;
642 case EPROTONOSUPPORT:
643 case ESOCKTNOSUPPORT:
644 case EPFNOSUPPORT:
645 case EAFNOSUPPORT:
646 case EPROTOTYPE: return STATUS_NOT_SUPPORTED;
647 case ENOPROTOOPT: return STATUS_INVALID_PARAMETER;
648 case EOPNOTSUPP: return STATUS_NOT_SUPPORTED;
649 case EADDRINUSE: return STATUS_ADDRESS_ALREADY_ASSOCIATED;
650 case EADDRNOTAVAIL: return STATUS_INVALID_PARAMETER;
651 case ECONNREFUSED: return STATUS_CONNECTION_REFUSED;
652 case ESHUTDOWN: return STATUS_PIPE_DISCONNECTED;
653 case ENOTCONN: return STATUS_CONNECTION_DISCONNECTED;
654 case ETIMEDOUT: return STATUS_IO_TIMEOUT;
655 case ENETUNREACH: return STATUS_NETWORK_UNREACHABLE;
656 case ENETDOWN: return STATUS_NETWORK_BUSY;
657 case EPIPE:
658 case ECONNRESET: return STATUS_CONNECTION_RESET;
659 case ECONNABORTED: return STATUS_CONNECTION_ABORTED;
661 case 0: return STATUS_SUCCESS;
662 default:
663 WARN("Unknown errno %d!\n", err);
664 return STATUS_UNSUCCESSFUL;
668 static UINT sock_get_error( int err )
670 switch(err)
672 case EINTR: return WSAEINTR;
673 case EBADF: return WSAEBADF;
674 case EPERM:
675 case EACCES: return WSAEACCES;
676 case EFAULT: return WSAEFAULT;
677 case EINVAL: return WSAEINVAL;
678 case EMFILE: return WSAEMFILE;
679 case EWOULDBLOCK: return WSAEWOULDBLOCK;
680 case EINPROGRESS: return WSAEINPROGRESS;
681 case EALREADY: return WSAEALREADY;
682 case ENOTSOCK: return WSAENOTSOCK;
683 case EDESTADDRREQ: return WSAEDESTADDRREQ;
684 case EMSGSIZE: return WSAEMSGSIZE;
685 case EPROTOTYPE: return WSAEPROTOTYPE;
686 case ENOPROTOOPT: return WSAENOPROTOOPT;
687 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
688 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
689 case EOPNOTSUPP: return WSAEOPNOTSUPP;
690 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
691 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
692 case EADDRINUSE: return WSAEADDRINUSE;
693 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
694 case ENETDOWN: return WSAENETDOWN;
695 case ENETUNREACH: return WSAENETUNREACH;
696 case ENETRESET: return WSAENETRESET;
697 case ECONNABORTED: return WSAECONNABORTED;
698 case EPIPE:
699 case ECONNRESET: return WSAECONNRESET;
700 case ENOBUFS: return WSAENOBUFS;
701 case EISCONN: return WSAEISCONN;
702 case ENOTCONN: return WSAENOTCONN;
703 case ESHUTDOWN: return WSAESHUTDOWN;
704 case ETOOMANYREFS: return WSAETOOMANYREFS;
705 case ETIMEDOUT: return WSAETIMEDOUT;
706 case ECONNREFUSED: return WSAECONNREFUSED;
707 case ELOOP: return WSAELOOP;
708 case ENAMETOOLONG: return WSAENAMETOOLONG;
709 case EHOSTDOWN: return WSAEHOSTDOWN;
710 case EHOSTUNREACH: return WSAEHOSTUNREACH;
711 case ENOTEMPTY: return WSAENOTEMPTY;
712 #ifdef EPROCLIM
713 case EPROCLIM: return WSAEPROCLIM;
714 #endif
715 #ifdef EUSERS
716 case EUSERS: return WSAEUSERS;
717 #endif
718 #ifdef EDQUOT
719 case EDQUOT: return WSAEDQUOT;
720 #endif
721 #ifdef ESTALE
722 case ESTALE: return WSAESTALE;
723 #endif
724 #ifdef EREMOTE
725 case EREMOTE: return WSAEREMOTE;
726 #endif
728 /* just in case we ever get here and there are no problems */
729 case 0: return 0;
730 default:
731 WARN("Unknown errno %d!\n", err);
732 return WSAEOPNOTSUPP;
736 static UINT wsaErrno(void)
738 int loc_errno = errno;
739 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
741 return sock_get_error( loc_errno );
744 /* most ws2 overlapped functions return an ntstatus-based error code */
745 static NTSTATUS wsaErrStatus(void)
747 int loc_errno = errno;
748 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
750 return sock_get_ntstatus(loc_errno);
753 static UINT wsaHerrno(int loc_errno)
755 WARN("h_errno %d.\n", loc_errno);
757 switch(loc_errno)
759 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
760 case TRY_AGAIN: return WSATRY_AGAIN;
761 case NO_RECOVERY: return WSANO_RECOVERY;
762 case NO_DATA: return WSANO_DATA;
763 case ENOBUFS: return WSAENOBUFS;
765 case 0: return 0;
766 default:
767 WARN("Unknown h_errno %d!\n", loc_errno);
768 return WSAEOPNOTSUPP;
772 static inline DWORD NtStatusToWSAError( const DWORD status )
774 /* We only need to cover the status codes set by server async request handling */
775 DWORD wserr;
776 switch ( status )
778 case STATUS_SUCCESS: wserr = 0; break;
779 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
780 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
781 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
782 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
783 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
784 case STATUS_NETWORK_BUSY: wserr = WSAEALREADY; break;
785 case STATUS_NETWORK_UNREACHABLE: wserr = WSAENETUNREACH; break;
786 case STATUS_CONNECTION_REFUSED: wserr = WSAECONNREFUSED; break;
787 case STATUS_CONNECTION_DISCONNECTED: wserr = WSAENOTCONN; break;
788 case STATUS_CONNECTION_RESET: wserr = WSAECONNRESET; break;
789 case STATUS_CONNECTION_ABORTED: wserr = WSAECONNABORTED; break;
790 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
791 case STATUS_ADDRESS_ALREADY_ASSOCIATED: wserr = WSAEADDRINUSE; break;
792 case STATUS_IO_TIMEOUT:
793 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
794 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
795 case STATUS_ACCESS_DENIED: wserr = WSAEACCES; break;
796 case STATUS_TOO_MANY_OPENED_FILES: wserr = WSAEMFILE; break;
797 case STATUS_CANT_WAIT: wserr = WSAEWOULDBLOCK; break;
798 case STATUS_BUFFER_OVERFLOW: wserr = WSAEMSGSIZE; break;
799 case STATUS_NOT_SUPPORTED: wserr = WSAEOPNOTSUPP; break;
800 case STATUS_HOST_UNREACHABLE: wserr = WSAEHOSTUNREACH; break;
802 default:
803 wserr = RtlNtStatusToDosError( status );
804 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
806 return wserr;
809 /* set last error code from NT status without mapping WSA errors */
810 static inline unsigned int set_error( unsigned int err )
812 if (err)
814 err = NtStatusToWSAError( err );
815 SetLastError( err );
817 return err;
820 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
822 int fd;
823 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
824 return -1;
825 return fd;
828 static inline void release_sock_fd( SOCKET s, int fd )
830 wine_server_release_fd( SOCKET2HANDLE(s), fd );
833 static void _enable_event( HANDLE s, unsigned int event,
834 unsigned int sstate, unsigned int cstate )
836 SERVER_START_REQ( enable_socket_event )
838 req->handle = wine_server_obj_handle( s );
839 req->mask = event;
840 req->sstate = sstate;
841 req->cstate = cstate;
842 wine_server_call( req );
844 SERVER_END_REQ;
847 static NTSTATUS _is_blocking(SOCKET s, BOOL *ret)
849 NTSTATUS status;
850 SERVER_START_REQ( get_socket_event )
852 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
853 req->service = FALSE;
854 req->c_event = 0;
855 status = wine_server_call( req );
856 *ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
858 SERVER_END_REQ;
859 return status;
862 static unsigned int _get_sock_mask(SOCKET s)
864 unsigned int ret;
865 SERVER_START_REQ( get_socket_event )
867 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
868 req->service = FALSE;
869 req->c_event = 0;
870 wine_server_call( req );
871 ret = reply->mask;
873 SERVER_END_REQ;
874 return ret;
877 static void _sync_sock_state(SOCKET s)
879 BOOL dummy;
880 /* do a dummy wineserver request in order to let
881 the wineserver run through its select loop once */
882 (void)_is_blocking(s, &dummy);
885 static int _get_sock_error(SOCKET s, unsigned int bit)
887 int events[FD_MAX_EVENTS];
889 SERVER_START_REQ( get_socket_event )
891 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
892 req->service = FALSE;
893 req->c_event = 0;
894 wine_server_set_reply( req, events, sizeof(events) );
895 wine_server_call( req );
897 SERVER_END_REQ;
898 return events[bit];
901 static struct per_thread_data *get_per_thread_data(void)
903 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
904 /* lazy initialization */
905 if (!ptb)
907 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
908 NtCurrentTeb()->WinSockData = ptb;
910 return ptb;
913 static void free_per_thread_data(void)
915 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
917 if (!ptb) return;
919 /* delete scratch buffers */
920 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
921 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
922 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
923 ptb->he_buffer = NULL;
924 ptb->se_buffer = NULL;
925 ptb->pe_buffer = NULL;
927 HeapFree( GetProcessHeap(), 0, ptb );
928 NtCurrentTeb()->WinSockData = NULL;
931 /***********************************************************************
932 * DllMain (WS2_32.init)
934 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
936 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
937 switch (fdwReason) {
938 case DLL_PROCESS_ATTACH:
939 break;
940 case DLL_PROCESS_DETACH:
941 if (fImpLoad) break;
942 free_per_thread_data();
943 DeleteCriticalSection(&csWSgetXXXbyYYY);
944 break;
945 case DLL_THREAD_DETACH:
946 free_per_thread_data();
947 break;
949 return TRUE;
952 /***********************************************************************
953 * convert_sockopt()
955 * Converts socket flags from Windows format.
956 * Return 1 if converted, 0 if not (error).
958 static int convert_sockopt(INT *level, INT *optname)
960 unsigned int i;
961 switch (*level)
963 case WS_SOL_SOCKET:
964 *level = SOL_SOCKET;
965 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
966 if( ws_sock_map[i][0] == *optname )
968 *optname = ws_sock_map[i][1];
969 return 1;
972 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
973 break;
974 case WS_IPPROTO_TCP:
975 *level = IPPROTO_TCP;
976 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
977 if ( ws_tcp_map[i][0] == *optname )
979 *optname = ws_tcp_map[i][1];
980 return 1;
983 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
984 break;
985 case WS_IPPROTO_IP:
986 *level = IPPROTO_IP;
987 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
988 if (ws_ip_map[i][0] == *optname )
990 *optname = ws_ip_map[i][1];
991 return 1;
994 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
995 break;
996 case WS_IPPROTO_IPV6:
997 *level = IPPROTO_IPV6;
998 for(i=0; i<sizeof(ws_ipv6_map)/sizeof(ws_ipv6_map[0]); i++) {
999 if (ws_ipv6_map[i][0] == *optname )
1001 *optname = ws_ipv6_map[i][1];
1002 return 1;
1005 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname);
1006 break;
1007 default: FIXME("Unimplemented or unknown socket level\n");
1009 return 0;
1012 /* ----------------------------------- Per-thread info (or per-process?) */
1014 static char *strdup_lower(const char *str)
1016 int i;
1017 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
1019 if (ret)
1021 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
1022 ret[i] = 0;
1024 else SetLastError(WSAENOBUFS);
1025 return ret;
1028 static inline int sock_error_p(int s)
1030 unsigned int optval;
1031 socklen_t optlen = sizeof(optval);
1032 getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
1033 if (optval) WARN("\t[%i] error: %d\n", s, optval);
1034 return optval != 0;
1037 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
1038 * from an fd and return the value converted to milli seconds
1039 * or -1 if there is an infinite time out */
1040 static inline int get_rcvsnd_timeo( int fd, int optname)
1042 struct timeval tv;
1043 socklen_t len = sizeof(tv);
1044 int ret = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
1045 if( ret >= 0)
1046 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
1047 if( ret <= 0 ) /* tv == {0,0} means infinite time out */
1048 return -1;
1049 return ret;
1052 /* macro wrappers for portability */
1053 #ifdef SO_RCVTIMEO
1054 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
1055 #else
1056 #define GET_RCVTIMEO(fd) (-1)
1057 #endif
1059 #ifdef SO_SNDTIMEO
1060 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
1061 #else
1062 #define GET_SNDTIMEO(fd) (-1)
1063 #endif
1065 /* utility: given an fd, will block until one of the events occurs */
1066 static inline int do_block( int fd, int events, int timeout )
1068 struct pollfd pfd;
1069 int ret;
1071 pfd.fd = fd;
1072 pfd.events = events;
1074 while ((ret = poll(&pfd, 1, timeout)) < 0)
1076 if (errno != EINTR)
1077 return -1;
1079 if( ret == 0 )
1080 return 0;
1081 return pfd.revents;
1084 static int
1085 convert_af_w2u(int windowsaf) {
1086 unsigned int i;
1088 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1089 if (ws_af_map[i][0] == windowsaf)
1090 return ws_af_map[i][1];
1091 FIXME("unhandled Windows address family %d\n", windowsaf);
1092 return -1;
1095 static int
1096 convert_af_u2w(int unixaf) {
1097 unsigned int i;
1099 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1100 if (ws_af_map[i][1] == unixaf)
1101 return ws_af_map[i][0];
1102 FIXME("unhandled UNIX address family %d\n", unixaf);
1103 return -1;
1106 static int
1107 convert_proto_w2u(int windowsproto) {
1108 unsigned int i;
1110 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1111 if (ws_proto_map[i][0] == windowsproto)
1112 return ws_proto_map[i][1];
1113 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
1114 return -1;
1117 static int
1118 convert_proto_u2w(int unixproto) {
1119 unsigned int i;
1121 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1122 if (ws_proto_map[i][1] == unixproto)
1123 return ws_proto_map[i][0];
1124 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
1125 return -1;
1128 static int
1129 convert_socktype_w2u(int windowssocktype) {
1130 unsigned int i;
1132 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1133 if (ws_socktype_map[i][0] == windowssocktype)
1134 return ws_socktype_map[i][1];
1135 FIXME("unhandled Windows socket type %d\n", windowssocktype);
1136 return -1;
1139 static int
1140 convert_socktype_u2w(int unixsocktype) {
1141 unsigned int i;
1143 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1144 if (ws_socktype_map[i][1] == unixsocktype)
1145 return ws_socktype_map[i][0];
1146 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
1147 return -1;
1150 /* ----------------------------------- API -----
1152 * Init / cleanup / error checking.
1155 /***********************************************************************
1156 * WSAStartup (WS2_32.115)
1158 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
1160 TRACE("verReq=%x\n", wVersionRequested);
1162 if (LOBYTE(wVersionRequested) < 1)
1163 return WSAVERNOTSUPPORTED;
1165 if (!lpWSAData) return WSAEINVAL;
1167 num_startup++;
1169 /* that's the whole of the negotiation for now */
1170 lpWSAData->wVersion = wVersionRequested;
1171 /* return winsock information */
1172 lpWSAData->wHighVersion = 0x0202;
1173 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
1174 strcpy(lpWSAData->szSystemStatus, "Running" );
1175 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
1176 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
1177 /* don't do anything with lpWSAData->lpVendorInfo */
1178 /* (some apps don't allocate the space for this field) */
1180 TRACE("succeeded\n");
1181 return 0;
1185 /***********************************************************************
1186 * WSACleanup (WS2_32.116)
1188 INT WINAPI WSACleanup(void)
1190 if (num_startup) {
1191 num_startup--;
1192 return 0;
1194 SetLastError(WSANOTINITIALISED);
1195 return SOCKET_ERROR;
1199 /***********************************************************************
1200 * WSAGetLastError (WS2_32.111)
1202 INT WINAPI WSAGetLastError(void)
1204 return GetLastError();
1207 /***********************************************************************
1208 * WSASetLastError (WS2_32.112)
1210 void WINAPI WSASetLastError(INT iError) {
1211 SetLastError(iError);
1214 static struct WS_hostent *check_buffer_he(int size)
1216 struct per_thread_data * ptb = get_per_thread_data();
1217 if (ptb->he_buffer)
1219 if (ptb->he_len >= size ) return ptb->he_buffer;
1220 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1222 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
1223 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
1224 return ptb->he_buffer;
1227 static struct WS_servent *check_buffer_se(int size)
1229 struct per_thread_data * ptb = get_per_thread_data();
1230 if (ptb->se_buffer)
1232 if (ptb->se_len >= size ) return ptb->se_buffer;
1233 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1235 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
1236 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
1237 return ptb->se_buffer;
1240 static struct WS_protoent *check_buffer_pe(int size)
1242 struct per_thread_data * ptb = get_per_thread_data();
1243 if (ptb->pe_buffer)
1245 if (ptb->pe_len >= size ) return ptb->pe_buffer;
1246 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1248 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
1249 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
1250 return ptb->pe_buffer;
1253 /* ----------------------------------- i/o APIs */
1255 static inline BOOL supported_pf(int pf)
1257 switch (pf)
1259 case WS_AF_INET:
1260 case WS_AF_INET6:
1261 return TRUE;
1262 #ifdef HAS_IPX
1263 case WS_AF_IPX:
1264 return TRUE;
1265 #endif
1266 #ifdef HAS_IRDA
1267 case WS_AF_IRDA:
1268 return TRUE;
1269 #endif
1270 default:
1271 return FALSE;
1275 static inline BOOL supported_protocol(int protocol)
1277 int i;
1278 for (i = 0; i < sizeof(valid_protocols) / sizeof(valid_protocols[0]); i++)
1279 if (protocol == valid_protocols[i])
1280 return TRUE;
1281 return FALSE;
1284 /**********************************************************************/
1286 /* Returns the length of the converted address if successful, 0 if it was too small to
1287 * start with.
1289 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
1290 union generic_unix_sockaddr *uaddr)
1292 unsigned int uaddrlen = 0;
1294 switch (wsaddr->sa_family)
1296 #ifdef HAS_IPX
1297 case WS_AF_IPX:
1299 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
1300 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
1302 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
1303 return 0;
1305 uaddrlen = sizeof(struct sockaddr_ipx);
1306 memset( uaddr, 0, uaddrlen );
1307 uipx->sipx_family=AF_IPX;
1308 uipx->sipx_port=wsipx->sa_socket;
1309 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1310 * in one go
1312 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
1313 #ifdef IPX_FRAME_NONE
1314 uipx->sipx_type=IPX_FRAME_NONE;
1315 #endif
1316 break;
1318 #endif
1319 case WS_AF_INET6: {
1320 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
1321 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
1323 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1324 * scope_id, one without.
1326 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
1327 uaddrlen = sizeof(struct sockaddr_in6);
1328 memset( uaddr, 0, uaddrlen );
1329 uin6->sin6_family = AF_INET6;
1330 uin6->sin6_port = win6->sin6_port;
1331 uin6->sin6_flowinfo = win6->sin6_flowinfo;
1332 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1333 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
1334 #endif
1335 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
1336 break;
1338 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
1339 return 0;
1341 case WS_AF_INET: {
1342 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
1343 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
1345 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
1346 return 0;
1347 uaddrlen = sizeof(struct sockaddr_in);
1348 memset( uaddr, 0, uaddrlen );
1349 uin->sin_family = AF_INET;
1350 uin->sin_port = win->sin_port;
1351 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
1352 break;
1354 #ifdef HAS_IRDA
1355 case WS_AF_IRDA: {
1356 struct sockaddr_irda *uin = (struct sockaddr_irda *)uaddr;
1357 const SOCKADDR_IRDA *win = (const SOCKADDR_IRDA *)wsaddr;
1359 if (wsaddrlen < sizeof(SOCKADDR_IRDA))
1360 return 0;
1361 uaddrlen = sizeof(struct sockaddr_irda);
1362 memset( uaddr, 0, uaddrlen );
1363 uin->sir_family = AF_IRDA;
1364 if (!strncmp( win->irdaServiceName, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1366 unsigned int lsap_sel = 0;
1368 sscanf( win->irdaServiceName, "LSAP-SEL%u", &lsap_sel );
1369 uin->sir_lsap_sel = lsap_sel;
1371 else
1373 uin->sir_lsap_sel = LSAP_ANY;
1374 memcpy( uin->sir_name, win->irdaServiceName, 25 );
1376 memcpy( &uin->sir_addr, win->irdaDeviceID, sizeof(uin->sir_addr) );
1377 break;
1379 #endif
1380 case WS_AF_UNSPEC: {
1381 /* Try to determine the needed space by the passed windows sockaddr space */
1382 switch (wsaddrlen) {
1383 default: /* likely an ipv4 address */
1384 case sizeof(struct WS_sockaddr_in):
1385 uaddrlen = sizeof(struct sockaddr_in);
1386 break;
1387 #ifdef HAS_IPX
1388 case sizeof(struct WS_sockaddr_ipx):
1389 uaddrlen = sizeof(struct sockaddr_ipx);
1390 break;
1391 #endif
1392 #ifdef HAS_IRDA
1393 case sizeof(SOCKADDR_IRDA):
1394 uaddrlen = sizeof(struct sockaddr_irda);
1395 break;
1396 #endif
1397 case sizeof(struct WS_sockaddr_in6):
1398 case sizeof(struct WS_sockaddr_in6_old):
1399 uaddrlen = sizeof(struct sockaddr_in6);
1400 break;
1402 memset( uaddr, 0, uaddrlen );
1403 break;
1405 default:
1406 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
1407 return 0;
1409 return uaddrlen;
1412 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
1414 switch (uaddr->sa_family)
1416 #ifdef HAS_IPX
1417 case AF_IPX:
1418 FIXME("don't know how to tell if IPX socket is bound, assuming it is!\n");
1419 return TRUE;
1420 #endif
1421 case AF_INET6:
1423 static const struct sockaddr_in6 emptyAddr;
1424 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
1425 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
1427 case AF_INET:
1429 static const struct sockaddr_in emptyAddr;
1430 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
1431 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
1433 case AF_UNSPEC:
1434 return FALSE;
1435 default:
1436 FIXME("unknown address family %d\n", uaddr->sa_family);
1437 return TRUE;
1441 /* Returns 0 if successful, -1 if the buffer is too small */
1442 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
1444 int res;
1446 switch(uaddr->sa_family)
1448 #ifdef HAS_IPX
1449 case AF_IPX:
1451 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
1452 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
1454 res=-1;
1455 switch (*wsaddrlen) /* how much can we copy? */
1457 default:
1458 res=0; /* enough */
1459 *wsaddrlen = sizeof(*wsipx);
1460 wsipx->sa_socket=uipx->sipx_port;
1461 /* fall through */
1462 case 13:
1463 case 12:
1464 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
1465 /* fall through */
1466 case 11:
1467 case 10:
1468 case 9:
1469 case 8:
1470 case 7:
1471 case 6:
1472 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1473 /* fall through */
1474 case 5:
1475 case 4:
1476 case 3:
1477 case 2:
1478 wsipx->sa_family=WS_AF_IPX;
1479 /* fall through */
1480 case 1:
1481 case 0:
1482 /* way too small */
1483 break;
1486 break;
1487 #endif
1488 #ifdef HAS_IRDA
1489 case AF_IRDA: {
1490 const struct sockaddr_irda *uin = (const struct sockaddr_irda *)uaddr;
1491 SOCKADDR_IRDA *win = (SOCKADDR_IRDA *)wsaddr;
1493 if (*wsaddrlen < sizeof(SOCKADDR_IRDA))
1494 return -1;
1495 win->irdaAddressFamily = WS_AF_IRDA;
1496 memcpy( win->irdaDeviceID, &uin->sir_addr, sizeof(win->irdaDeviceID) );
1497 if (uin->sir_lsap_sel != LSAP_ANY)
1498 sprintf( win->irdaServiceName, "LSAP-SEL%u", uin->sir_lsap_sel );
1499 else
1500 memcpy( win->irdaServiceName, uin->sir_name,
1501 sizeof(win->irdaServiceName) );
1502 return 0;
1504 #endif
1505 case AF_INET6: {
1506 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1507 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1509 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1510 return -1;
1511 win6old->sin6_family = WS_AF_INET6;
1512 win6old->sin6_port = uin6->sin6_port;
1513 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1514 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1515 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1516 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1517 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1518 win6->sin6_scope_id = uin6->sin6_scope_id;
1519 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1521 else
1522 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1523 #else
1524 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1525 #endif
1526 return 0;
1528 case AF_INET: {
1529 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1530 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1532 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1533 return -1;
1534 win->sin_family = WS_AF_INET;
1535 win->sin_port = uin->sin_port;
1536 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1537 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1538 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1539 return 0;
1541 case AF_UNSPEC: {
1542 memset(wsaddr,0,*wsaddrlen);
1543 return 0;
1545 default:
1546 FIXME("Unknown address family %d\n", uaddr->sa_family);
1547 return -1;
1549 return res;
1552 static INT WS_DuplicateSocket(BOOL unicode, SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo)
1554 HANDLE hProcess;
1555 int size;
1556 WSAPROTOCOL_INFOW infow;
1558 TRACE("(unicode %d, socket %04lx, processid %x, buffer %p)\n",
1559 unicode, s, dwProcessId, lpProtocolInfo);
1561 if (!ws_protocol_info(s, unicode, &infow, &size))
1562 return SOCKET_ERROR;
1564 if (!(hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId)))
1566 SetLastError(WSAEINVAL);
1567 return SOCKET_ERROR;
1570 if (!lpProtocolInfo)
1572 CloseHandle(hProcess);
1573 SetLastError(WSAEFAULT);
1574 return SOCKET_ERROR;
1577 /* I don't know what the real Windoze does next, this is a hack */
1578 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
1579 * the target use the global duplicate, or we could copy a reference to us to the structure
1580 * and let the target duplicate it from us, but let's do it as simple as possible */
1581 memcpy(lpProtocolInfo, &infow, size);
1582 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
1583 hProcess, (LPHANDLE)&lpProtocolInfo->dwServiceFlags3,
1584 0, FALSE, DUPLICATE_SAME_ACCESS);
1585 CloseHandle(hProcess);
1586 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
1587 return 0;
1590 /*****************************************************************************
1591 * WS_EnterSingleProtocolW [internal]
1593 * enters the protocol information of one given protocol into the given
1594 * buffer.
1596 * RETURNS
1597 * TRUE if a protocol was entered into the buffer.
1599 * BUGS
1600 * - only implemented for IPX, SPX, SPXII, TCP, UDP
1601 * - there is no check that the operating system supports the returned
1602 * protocols
1604 static BOOL WS_EnterSingleProtocolW( INT protocol, WSAPROTOCOL_INFOW* info )
1606 memset( info, 0, sizeof(WSAPROTOCOL_INFOW) );
1607 info->iProtocol = protocol;
1609 switch (protocol)
1611 case WS_IPPROTO_TCP:
1612 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_EXPEDITED_DATA |
1613 XP1_GRACEFUL_CLOSE | XP1_GUARANTEED_ORDER |
1614 XP1_GUARANTEED_DELIVERY;
1615 info->ProviderId = ProviderIdIP;
1616 info->dwCatalogEntryId = 0x3e9;
1617 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1618 info->ProtocolChain.ChainLen = 1;
1619 info->iVersion = 2;
1620 info->iAddressFamily = WS_AF_INET;
1621 info->iMaxSockAddr = 0x10;
1622 info->iMinSockAddr = 0x10;
1623 info->iSocketType = WS_SOCK_STREAM;
1624 strcpyW( info->szProtocol, NameTcpW );
1625 break;
1627 case WS_IPPROTO_UDP:
1628 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_SUPPORT_BROADCAST |
1629 XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED |
1630 XP1_CONNECTIONLESS;
1631 info->ProviderId = ProviderIdIP;
1632 info->dwCatalogEntryId = 0x3ea;
1633 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1634 info->ProtocolChain.ChainLen = 1;
1635 info->iVersion = 2;
1636 info->iAddressFamily = WS_AF_INET;
1637 info->iMaxSockAddr = 0x10;
1638 info->iMinSockAddr = 0x10;
1639 info->iSocketType = WS_SOCK_DGRAM;
1640 info->dwMessageSize = 0xffbb;
1641 strcpyW( info->szProtocol, NameUdpW );
1642 break;
1644 case WS_NSPROTO_IPX:
1645 info->dwServiceFlags1 = XP1_PARTIAL_MESSAGE | XP1_SUPPORT_BROADCAST |
1646 XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED |
1647 XP1_CONNECTIONLESS;
1648 info->ProviderId = ProviderIdIPX;
1649 info->dwCatalogEntryId = 0x406;
1650 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1651 info->ProtocolChain.ChainLen = 1;
1652 info->iVersion = 2;
1653 info->iAddressFamily = WS_AF_IPX;
1654 info->iMaxSockAddr = 0x10;
1655 info->iMinSockAddr = 0x0e;
1656 info->iSocketType = WS_SOCK_DGRAM;
1657 info->iProtocolMaxOffset = 0xff;
1658 info->dwMessageSize = 0x240;
1659 strcpyW( info->szProtocol, NameIpxW );
1660 break;
1662 case WS_NSPROTO_SPX:
1663 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_PSEUDO_STREAM |
1664 XP1_MESSAGE_ORIENTED | XP1_GUARANTEED_ORDER |
1665 XP1_GUARANTEED_DELIVERY;
1666 info->ProviderId = ProviderIdSPX;
1667 info->dwCatalogEntryId = 0x407;
1668 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1669 info->ProtocolChain.ChainLen = 1;
1670 info->iVersion = 2;
1671 info->iAddressFamily = WS_AF_IPX;
1672 info->iMaxSockAddr = 0x10;
1673 info->iMinSockAddr = 0x0e;
1674 info->iSocketType = WS_SOCK_SEQPACKET;
1675 info->dwMessageSize = 0xffffffff;
1676 strcpyW( info->szProtocol, NameSpxW );
1677 break;
1679 case WS_NSPROTO_SPXII:
1680 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_GRACEFUL_CLOSE |
1681 XP1_PSEUDO_STREAM | XP1_MESSAGE_ORIENTED |
1682 XP1_GUARANTEED_ORDER | XP1_GUARANTEED_DELIVERY;
1683 info->ProviderId = ProviderIdSPX;
1684 info->dwCatalogEntryId = 0x409;
1685 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1686 info->ProtocolChain.ChainLen = 1;
1687 info->iVersion = 2;
1688 info->iAddressFamily = WS_AF_IPX;
1689 info->iMaxSockAddr = 0x10;
1690 info->iMinSockAddr = 0x0e;
1691 info->iSocketType = WS_SOCK_SEQPACKET;
1692 info->dwMessageSize = 0xffffffff;
1693 strcpyW( info->szProtocol, NameSpxIIW );
1694 break;
1696 default:
1697 FIXME("unknown Protocol <0x%08x>\n", protocol);
1698 return FALSE;
1700 return TRUE;
1703 /*****************************************************************************
1704 * WS_EnterSingleProtocolA [internal]
1706 * see function WS_EnterSingleProtocolW
1709 static BOOL WS_EnterSingleProtocolA( INT protocol, WSAPROTOCOL_INFOA* info )
1711 WSAPROTOCOL_INFOW infow;
1712 INT ret;
1713 memset( info, 0, sizeof(WSAPROTOCOL_INFOA) );
1715 ret = WS_EnterSingleProtocolW( protocol, &infow );
1716 if (ret)
1718 /* convert the structure from W to A */
1719 memcpy( info, &infow, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
1720 WideCharToMultiByte( CP_ACP, 0, infow.szProtocol, -1,
1721 info->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL );
1724 return ret;
1727 static INT WS_EnumProtocols( BOOL unicode, const INT *protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
1729 INT i = 0, items = 0;
1730 DWORD size = 0;
1731 union _info
1733 LPWSAPROTOCOL_INFOA a;
1734 LPWSAPROTOCOL_INFOW w;
1735 } info;
1736 info.w = buffer;
1738 if (!protocols) protocols = valid_protocols;
1740 while (protocols[i])
1742 if(supported_protocol(protocols[i++]))
1743 items++;
1746 size = items * (unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA));
1748 TRACE("unicode %d, protocols %p, buffer %p, length %p %d, items %d, required %d\n",
1749 unicode, protocols, buffer, len, len ? *len : 0, items, size);
1751 if (*len < size || !buffer)
1753 *len = size;
1754 WSASetLastError(WSAENOBUFS);
1755 return SOCKET_ERROR;
1758 for (i = items = 0; protocols[i]; i++)
1760 if (unicode)
1762 if (WS_EnterSingleProtocolW( protocols[i], &info.w[items] ))
1763 items++;
1765 else
1767 if (WS_EnterSingleProtocolA( protocols[i], &info.a[items] ))
1768 items++;
1771 return items;
1774 static BOOL ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size)
1776 NTSTATUS status;
1778 *size = unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA);
1779 memset(buffer, 0, *size);
1781 SERVER_START_REQ( get_socket_info )
1783 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1784 status = wine_server_call( req );
1785 if (!status)
1787 buffer->iAddressFamily = convert_af_u2w(reply->family);
1788 buffer->iSocketType = convert_socktype_u2w(reply->type);
1789 buffer->iProtocol = convert_proto_u2w(reply->protocol);
1792 SERVER_END_REQ;
1794 if (status)
1796 unsigned int err = NtStatusToWSAError( status );
1797 SetLastError( err == WSAEBADF ? WSAENOTSOCK : err );
1798 return FALSE;
1801 if (unicode)
1802 WS_EnterSingleProtocolW( buffer->iProtocol, buffer);
1803 else
1804 WS_EnterSingleProtocolA( buffer->iProtocol, (WSAPROTOCOL_INFOA *)buffer);
1806 return TRUE;
1809 /**************************************************************************
1810 * Functions for handling overlapped I/O
1811 **************************************************************************/
1813 /* user APC called upon async completion */
1814 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1816 ws2_async *wsa = arg;
1818 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
1819 iosb->Information, wsa->user_overlapped,
1820 wsa->flags );
1821 HeapFree( GetProcessHeap(), 0, wsa );
1824 /***********************************************************************
1825 * WS2_recv (INTERNAL)
1827 * Workhorse for both synchronous and asynchronous recv() operations.
1829 static int WS2_recv( int fd, struct ws2_async *wsa )
1831 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1832 char pktbuf[512];
1833 #endif
1834 struct msghdr hdr;
1835 union generic_unix_sockaddr unix_sockaddr;
1836 int n;
1838 hdr.msg_name = NULL;
1840 if (wsa->addr)
1842 hdr.msg_namelen = sizeof(unix_sockaddr);
1843 hdr.msg_name = &unix_sockaddr;
1845 else
1846 hdr.msg_namelen = 0;
1848 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1849 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1850 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1851 hdr.msg_accrights = NULL;
1852 hdr.msg_accrightslen = 0;
1853 #else
1854 hdr.msg_control = pktbuf;
1855 hdr.msg_controllen = sizeof(pktbuf);
1856 hdr.msg_flags = 0;
1857 #endif
1859 if ( (n = recvmsg(fd, &hdr, wsa->flags)) == -1 )
1860 return -1;
1862 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1863 if (wsa->control)
1865 ERR("Message control headers cannot be properly supported on this system.\n");
1866 wsa->control->len = 0;
1868 #else
1869 if (wsa->control && !convert_control_headers(&hdr, wsa->control))
1871 WARN("Application passed insufficient room for control headers.\n");
1872 *wsa->lpFlags |= WS_MSG_CTRUNC;
1873 errno = EMSGSIZE;
1874 return -1;
1876 #endif
1878 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
1879 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
1881 * quoting linux 2.6 net/ipv4/tcp.c:
1882 * "According to UNIX98, msg_name/msg_namelen are ignored
1883 * on connected socket. I was just happy when found this 8) --ANK"
1885 * likewise MSDN says that lpFrom and lpFromlen are ignored for
1886 * connection-oriented sockets, so don't try to update lpFrom.
1888 if (wsa->addr && hdr.msg_namelen)
1889 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
1891 return n;
1894 /***********************************************************************
1895 * WS2_async_recv (INTERNAL)
1897 * Handler for overlapped recv() operations.
1899 static NTSTATUS WS2_async_recv( void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1901 ws2_async* wsa = user;
1902 int result = 0, fd;
1904 switch (status)
1906 case STATUS_ALERTED:
1907 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
1908 break;
1910 result = WS2_recv( fd, wsa );
1911 wine_server_release_fd( wsa->hSocket, fd );
1912 if (result >= 0)
1914 status = STATUS_SUCCESS;
1915 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1917 else
1919 if (errno == EINTR || errno == EAGAIN)
1921 status = STATUS_PENDING;
1922 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1924 else
1926 result = 0;
1927 status = wsaErrStatus();
1930 break;
1932 if (status != STATUS_PENDING)
1934 iosb->u.Status = status;
1935 iosb->Information = result;
1936 *apc = ws2_async_apc;
1938 return status;
1941 /* user APC called upon async accept completion */
1942 static void WINAPI ws2_async_accept_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1944 struct ws2_accept_async *wsa = arg;
1946 HeapFree( GetProcessHeap(), 0, wsa->read );
1947 HeapFree( GetProcessHeap(), 0, wsa );
1950 /***********************************************************************
1951 * WS2_async_accept_recv (INTERNAL)
1953 * This function is used to finish the read part of an accept request. It is
1954 * needed to place the completion on the correct socket (listener).
1956 static NTSTATUS WS2_async_accept_recv( void *arg, IO_STATUS_BLOCK *iosb, NTSTATUS status, void **apc )
1958 void *junk;
1959 struct ws2_accept_async *wsa = arg;
1961 status = WS2_async_recv( wsa->read, iosb, status, &junk );
1962 if (status == STATUS_PENDING)
1963 return status;
1965 if (wsa->user_overlapped->hEvent)
1966 SetEvent(wsa->user_overlapped->hEvent);
1967 if (wsa->cvalue)
1968 WS_AddCompletion( HANDLE2SOCKET(wsa->listen_socket), wsa->cvalue, iosb->u.Status, iosb->Information );
1970 *apc = ws2_async_accept_apc;
1971 return status;
1974 /***********************************************************************
1975 * WS2_async_accept (INTERNAL)
1977 * This is the function called to satisfy the AcceptEx callback
1979 static NTSTATUS WS2_async_accept( void *arg, IO_STATUS_BLOCK *iosb, NTSTATUS status, void **apc )
1981 struct ws2_accept_async *wsa = arg;
1982 int len;
1983 char *addr;
1985 TRACE("status: 0x%x listen: %p, accept: %p\n", status, wsa->listen_socket, wsa->accept_socket);
1987 if (status == STATUS_ALERTED)
1989 SERVER_START_REQ( accept_into_socket )
1991 req->lhandle = wine_server_obj_handle( wsa->listen_socket );
1992 req->ahandle = wine_server_obj_handle( wsa->accept_socket );
1993 status = wine_server_call( req );
1995 SERVER_END_REQ;
1997 if (status == STATUS_CANT_WAIT)
1998 return STATUS_PENDING;
2000 if (status == STATUS_INVALID_HANDLE)
2002 FIXME("AcceptEx accepting socket closed but request was not cancelled\n");
2003 status = STATUS_CANCELLED;
2006 else if (status == STATUS_HANDLES_CLOSED)
2007 status = STATUS_CANCELLED; /* strange windows behavior */
2009 if (status != STATUS_SUCCESS)
2010 goto finish;
2012 /* WS2 Spec says size param is extra 16 bytes long...what do we put in it? */
2013 addr = ((char *)wsa->buf) + wsa->data_len;
2014 len = wsa->local_len - sizeof(int);
2015 WS_getsockname(HANDLE2SOCKET(wsa->accept_socket),
2016 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
2017 *(int *)addr = len;
2019 addr += wsa->local_len;
2020 len = wsa->remote_len - sizeof(int);
2021 WS_getpeername(HANDLE2SOCKET(wsa->accept_socket),
2022 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
2023 *(int *)addr = len;
2025 if (!wsa->read)
2026 goto finish;
2028 SERVER_START_REQ( register_async )
2030 req->type = ASYNC_TYPE_READ;
2031 req->async.handle = wine_server_obj_handle( wsa->accept_socket );
2032 req->async.callback = wine_server_client_ptr( WS2_async_accept_recv );
2033 req->async.iosb = wine_server_client_ptr( iosb );
2034 req->async.arg = wine_server_client_ptr( wsa );
2035 status = wine_server_call( req );
2037 SERVER_END_REQ;
2039 if (status != STATUS_PENDING)
2040 goto finish;
2042 /* The APC has finished but no completion should be sent for the operation yet, additional processing
2043 * needs to be performed by WS2_async_accept_recv() first. */
2044 return STATUS_MORE_PROCESSING_REQUIRED;
2046 finish:
2047 iosb->u.Status = status;
2048 iosb->Information = 0;
2050 if (wsa->user_overlapped->hEvent)
2051 SetEvent(wsa->user_overlapped->hEvent);
2053 *apc = ws2_async_accept_apc;
2054 return status;
2057 /***********************************************************************
2058 * WS2_send (INTERNAL)
2060 * Workhorse for both synchronous and asynchronous send() operations.
2062 static int WS2_send( int fd, struct ws2_async *wsa )
2064 struct msghdr hdr;
2065 union generic_unix_sockaddr unix_addr;
2066 int n, ret;
2068 hdr.msg_name = NULL;
2069 hdr.msg_namelen = 0;
2071 if (wsa->addr)
2073 hdr.msg_name = &unix_addr;
2074 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
2075 if ( !hdr.msg_namelen )
2077 errno = EFAULT;
2078 return -1;
2081 #if defined(HAS_IPX) && defined(SOL_IPX)
2082 if(wsa->addr->sa_family == WS_AF_IPX)
2084 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
2085 int val=0;
2086 socklen_t len = sizeof(int);
2088 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
2089 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
2090 * the packet type and then we can retrieve it using getsockopt. After that we can set the
2091 * ipx type in the sockaddr_opx structure with the stored value.
2093 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
2094 uipx->sipx_type = val;
2096 #endif
2099 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
2100 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
2101 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2102 hdr.msg_accrights = NULL;
2103 hdr.msg_accrightslen = 0;
2104 #else
2105 hdr.msg_control = NULL;
2106 hdr.msg_controllen = 0;
2107 hdr.msg_flags = 0;
2108 #endif
2110 ret = sendmsg(fd, &hdr, wsa->flags);
2111 if (ret >= 0)
2113 n = ret;
2114 while (wsa->first_iovec < wsa->n_iovecs && wsa->iovec[wsa->first_iovec].iov_len <= n)
2115 n -= wsa->iovec[wsa->first_iovec++].iov_len;
2116 if (wsa->first_iovec < wsa->n_iovecs)
2118 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
2119 wsa->iovec[wsa->first_iovec].iov_len -= n;
2122 return ret;
2125 /***********************************************************************
2126 * WS2_async_send (INTERNAL)
2128 * Handler for overlapped send() operations.
2130 static NTSTATUS WS2_async_send(void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
2132 ws2_async* wsa = user;
2133 int result = 0, fd;
2135 switch (status)
2137 case STATUS_ALERTED:
2138 if ( wsa->n_iovecs <= wsa->first_iovec )
2140 /* Nothing to do */
2141 status = STATUS_SUCCESS;
2142 break;
2144 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
2145 break;
2147 /* check to see if the data is ready (non-blocking) */
2148 result = WS2_send( fd, wsa );
2149 wine_server_release_fd( wsa->hSocket, fd );
2151 if (result >= 0)
2153 if (wsa->first_iovec < wsa->n_iovecs)
2154 status = STATUS_PENDING;
2155 else
2156 status = STATUS_SUCCESS;
2158 iosb->Information += result;
2160 else if (errno == EINTR || errno == EAGAIN)
2162 status = STATUS_PENDING;
2164 else
2166 status = wsaErrStatus();
2168 break;
2170 if (status != STATUS_PENDING)
2172 iosb->u.Status = status;
2173 *apc = ws2_async_apc;
2175 return status;
2178 /***********************************************************************
2179 * WS2_async_shutdown (INTERNAL)
2181 * Handler for shutdown() operations on overlapped sockets.
2183 static NTSTATUS WS2_async_shutdown( void* user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc )
2185 ws2_async* wsa = user;
2186 int fd, err = 1;
2188 switch (status)
2190 case STATUS_ALERTED:
2191 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
2192 break;
2194 switch ( wsa->type )
2196 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
2197 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
2199 status = err ? wsaErrStatus() : STATUS_SUCCESS;
2200 wine_server_release_fd( wsa->hSocket, fd );
2201 break;
2203 iosb->u.Status = status;
2204 iosb->Information = 0;
2205 *apc = ws2_async_apc;
2206 return status;
2209 /***********************************************************************
2210 * WS2_register_async_shutdown (INTERNAL)
2212 * Helper function for WS_shutdown() on overlapped sockets.
2214 static int WS2_register_async_shutdown( SOCKET s, int type )
2216 struct ws2_async *wsa;
2217 NTSTATUS status;
2219 TRACE("s %ld type %d\n", s, type);
2221 wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( struct ws2_async, iovec[1] ));
2222 if ( !wsa )
2223 return WSAEFAULT;
2225 wsa->hSocket = SOCKET2HANDLE(s);
2226 wsa->type = type;
2227 wsa->completion_func = NULL;
2229 SERVER_START_REQ( register_async )
2231 req->type = type;
2232 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2233 req->async.callback = wine_server_client_ptr( WS2_async_shutdown );
2234 req->async.iosb = wine_server_client_ptr( &wsa->local_iosb );
2235 req->async.arg = wine_server_client_ptr( wsa );
2236 req->async.cvalue = 0;
2237 status = wine_server_call( req );
2239 SERVER_END_REQ;
2241 if (status != STATUS_PENDING)
2243 HeapFree( GetProcessHeap(), 0, wsa );
2244 return NtStatusToWSAError( status );
2246 return 0;
2249 /***********************************************************************
2250 * accept (WS2_32.1)
2252 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr, int *addrlen32)
2254 NTSTATUS status;
2255 SOCKET as;
2256 BOOL is_blocking;
2258 TRACE("socket %04lx\n", s );
2259 status = _is_blocking(s, &is_blocking);
2260 if (status)
2262 set_error(status);
2263 return INVALID_SOCKET;
2266 do {
2267 /* try accepting first (if there is a deferred connection) */
2268 SERVER_START_REQ( accept_socket )
2270 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
2271 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
2272 req->attributes = OBJ_INHERIT;
2273 status = wine_server_call( req );
2274 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
2276 SERVER_END_REQ;
2277 if (!status)
2279 if (addr && WS_getpeername(as, addr, addrlen32))
2281 WS_closesocket(as);
2282 return SOCKET_ERROR;
2284 return as;
2286 if (is_blocking && status == STATUS_CANT_WAIT)
2288 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2289 /* block here */
2290 do_block(fd, POLLIN, -1);
2291 _sync_sock_state(s); /* let wineserver notice connection */
2292 release_sock_fd( s, fd );
2294 } while (is_blocking && status == STATUS_CANT_WAIT);
2296 set_error(status);
2297 return INVALID_SOCKET;
2300 /***********************************************************************
2301 * AcceptEx
2303 static BOOL WINAPI WS2_AcceptEx(SOCKET listener, SOCKET acceptor, PVOID dest, DWORD dest_len,
2304 DWORD local_addr_len, DWORD rem_addr_len, LPDWORD received,
2305 LPOVERLAPPED overlapped)
2307 DWORD status;
2308 struct ws2_accept_async *wsa;
2309 int fd;
2310 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
2312 TRACE("(%lx, %lx, %p, %d, %d, %d, %p, %p)\n", listener, acceptor, dest, dest_len, local_addr_len,
2313 rem_addr_len, received, overlapped);
2315 if (!dest)
2317 SetLastError(WSAEINVAL);
2318 return FALSE;
2321 if (!overlapped)
2323 SetLastError(WSA_INVALID_PARAMETER);
2324 return FALSE;
2327 if ((local_addr_len < sizeof(struct sockaddr_in) + 16)
2328 || (rem_addr_len < sizeof(struct sockaddr_in) + 16))
2330 SetLastError(WSAEINVAL);
2331 return FALSE;
2334 fd = get_sock_fd( listener, FILE_READ_DATA, NULL );
2335 if (fd == -1)
2337 SetLastError(WSAENOTSOCK);
2338 return FALSE;
2340 release_sock_fd( listener, fd );
2342 fd = get_sock_fd( acceptor, FILE_READ_DATA, NULL );
2343 if (fd == -1)
2345 SetLastError(WSAEINVAL);
2346 return FALSE;
2348 release_sock_fd( acceptor, fd );
2350 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
2351 if(!wsa)
2353 SetLastError(WSAEFAULT);
2354 return FALSE;
2357 wsa->listen_socket = SOCKET2HANDLE(listener);
2358 wsa->accept_socket = SOCKET2HANDLE(acceptor);
2359 wsa->user_overlapped = overlapped;
2360 wsa->cvalue = cvalue;
2361 wsa->buf = dest;
2362 wsa->data_len = dest_len;
2363 wsa->local_len = local_addr_len;
2364 wsa->remote_len = rem_addr_len;
2365 wsa->read = NULL;
2367 if (wsa->data_len)
2369 /* set up a read request if we need it */
2370 wsa->read = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[1]) );
2371 if (!wsa->read)
2373 HeapFree( GetProcessHeap(), 0, wsa );
2374 SetLastError(WSAEFAULT);
2375 return FALSE;
2378 wsa->read->hSocket = wsa->accept_socket;
2379 wsa->read->flags = 0;
2380 wsa->read->lpFlags = &wsa->read->flags;
2381 wsa->read->addr = NULL;
2382 wsa->read->addrlen.ptr = NULL;
2383 wsa->read->control = NULL;
2384 wsa->read->n_iovecs = 1;
2385 wsa->read->first_iovec = 0;
2386 wsa->read->iovec[0].iov_base = wsa->buf;
2387 wsa->read->iovec[0].iov_len = wsa->data_len;
2390 SERVER_START_REQ( register_async )
2392 req->type = ASYNC_TYPE_READ;
2393 req->async.handle = wine_server_obj_handle( SOCKET2HANDLE(listener) );
2394 req->async.callback = wine_server_client_ptr( WS2_async_accept );
2395 req->async.iosb = wine_server_client_ptr( overlapped );
2396 req->async.arg = wine_server_client_ptr( wsa );
2397 req->async.cvalue = cvalue;
2398 /* We don't set event since we may also have to read */
2399 status = wine_server_call( req );
2401 SERVER_END_REQ;
2403 if(status != STATUS_PENDING)
2405 HeapFree( GetProcessHeap(), 0, wsa->read );
2406 HeapFree( GetProcessHeap(), 0, wsa );
2409 SetLastError( NtStatusToWSAError(status) );
2410 return FALSE;
2413 /***********************************************************************
2414 * GetAcceptExSockaddrs
2416 static void WINAPI WS2_GetAcceptExSockaddrs(PVOID buffer, DWORD data_size, DWORD local_size, DWORD remote_size,
2417 struct WS_sockaddr **local_addr, LPINT local_addr_len,
2418 struct WS_sockaddr **remote_addr, LPINT remote_addr_len)
2420 char *cbuf = buffer;
2421 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer, data_size, local_size, remote_size, local_addr,
2422 local_addr_len, remote_addr, remote_addr_len );
2423 cbuf += data_size;
2425 *local_addr_len = *(int *) cbuf;
2426 *local_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2428 cbuf += local_size;
2430 *remote_addr_len = *(int *) cbuf;
2431 *remote_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2434 /***********************************************************************
2435 * WSASendMsg
2437 int WINAPI WSASendMsg( SOCKET s, LPWSAMSG msg, DWORD dwFlags, LPDWORD lpNumberOfBytesSent,
2438 LPWSAOVERLAPPED lpOverlapped,
2439 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
2441 if (!msg)
2443 SetLastError( WSAEFAULT );
2444 return SOCKET_ERROR;
2447 return WS2_sendto( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesSent,
2448 dwFlags, msg->name, msg->namelen,
2449 lpOverlapped, lpCompletionRoutine );
2452 /***********************************************************************
2453 * WSARecvMsg
2455 * Perform a receive operation that is capable of returning message
2456 * control headers. It is important to note that the WSAMSG parameter
2457 * must remain valid throughout the operation, even when an overlapped
2458 * receive is performed.
2460 static int WINAPI WS2_WSARecvMsg( SOCKET s, LPWSAMSG msg, LPDWORD lpNumberOfBytesRecvd,
2461 LPWSAOVERLAPPED lpOverlapped,
2462 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2464 if (!msg)
2466 SetLastError( WSAEFAULT );
2467 return SOCKET_ERROR;
2470 return WS2_recv_base( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesRecvd,
2471 &msg->dwFlags, msg->name, &msg->namelen,
2472 lpOverlapped, lpCompletionRoutine, &msg->Control );
2475 /***********************************************************************
2476 * interface_bind (INTERNAL)
2478 * Take bind() calls on any name corresponding to a local network adapter and restrict the given socket to
2479 * operating only on the specified interface. This restriction consists of two components:
2480 * 1) An outgoing packet restriction suggesting the egress interface for all packets.
2481 * 2) An incoming packet restriction dropping packets not meant for the interface.
2482 * If the function succeeds in placing these restrictions (returns TRUE) then the name for the bind() may
2483 * safely be changed to INADDR_ANY, permitting the transmission and receipt of broadcast packets on the
2484 * socket. This behavior is only relevant to UDP sockets and is needed for applications that expect to be able
2485 * to receive broadcast packets on a socket that is bound to a specific network interface.
2487 static BOOL interface_bind( SOCKET s, int fd, struct sockaddr *addr )
2489 struct sockaddr_in *in_sock = (struct sockaddr_in *) addr;
2490 unsigned int sock_type = 0;
2491 socklen_t optlen = sizeof(sock_type);
2492 in_addr_t bind_addr = in_sock->sin_addr.s_addr;
2493 PIP_ADAPTER_INFO adapters = NULL, adapter;
2494 BOOL ret = FALSE;
2495 DWORD adap_size;
2496 int enable = 1;
2498 if (bind_addr == htonl(WS_INADDR_ANY) || bind_addr == htonl(WS_INADDR_LOOPBACK))
2499 return FALSE; /* Not binding to a network adapter, special interface binding unnecessary. */
2500 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &sock_type, &optlen) == -1 || sock_type != SOCK_DGRAM)
2501 return FALSE; /* Special interface binding is only necessary for UDP datagrams. */
2502 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
2503 goto cleanup;
2504 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
2505 if (adapters == NULL || GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
2506 goto cleanup;
2507 /* Search the IPv4 adapter list for the appropriate binding interface */
2508 for (adapter = adapters; adapter != NULL; adapter = adapter->Next)
2510 in_addr_t adapter_addr = (in_addr_t) inet_addr(adapter->IpAddressList.IpAddress.String);
2512 if (bind_addr == adapter_addr)
2514 #if defined(IP_BOUND_IF)
2515 /* IP_BOUND_IF sets both the incoming and outgoing restriction at once */
2516 if (setsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &adapter->Index, sizeof(adapter->Index)) != 0)
2517 goto cleanup;
2518 ret = TRUE;
2519 #elif defined(LINUX_BOUND_IF)
2520 in_addr_t ifindex = (in_addr_t) htonl(adapter->Index);
2521 struct interface_filter specific_interface_filter;
2522 struct sock_fprog filter_prog;
2524 if (setsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex, sizeof(ifindex)) != 0)
2525 goto cleanup; /* Failed to suggest egress interface */
2526 specific_interface_filter = generic_interface_filter;
2527 specific_interface_filter.iface_rule.k = adapter->Index;
2528 specific_interface_filter.ip_rule.k = htonl(adapter_addr);
2529 filter_prog.len = sizeof(generic_interface_filter)/sizeof(struct sock_filter);
2530 filter_prog.filter = (struct sock_filter *) &specific_interface_filter;
2531 if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog, sizeof(filter_prog)) != 0)
2532 goto cleanup; /* Failed to specify incoming packet filter */
2533 ret = TRUE;
2534 #else
2535 FIXME("Broadcast packets on interface-bound sockets are not currently supported on this platform, "
2536 "receiving broadcast packets will not work on socket %04lx.\n", s);
2537 #endif
2538 break;
2541 /* Will soon be switching to INADDR_ANY: permit address reuse */
2542 if (ret && setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) == 0)
2543 TRACE("Socket %04lx bound to interface index %d\n", s, adapter->Index);
2544 else
2545 ret = FALSE;
2547 cleanup:
2548 if(!ret)
2549 ERR("Failed to bind to interface, receiving broadcast packets will not work on socket %04lx.\n", s);
2550 HeapFree(GetProcessHeap(), 0, adapters);
2551 return ret;
2554 /***********************************************************************
2555 * bind (WS2_32.2)
2557 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
2559 int fd = get_sock_fd( s, 0, NULL );
2560 int res = SOCKET_ERROR;
2562 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2564 if (fd != -1)
2566 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
2568 SetLastError(WSAEAFNOSUPPORT);
2570 else
2572 union generic_unix_sockaddr uaddr;
2573 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2574 if (!uaddrlen)
2576 SetLastError(WSAEFAULT);
2578 else
2580 #ifdef IPV6_V6ONLY
2581 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
2582 if (name->sa_family == WS_AF_INET6 &&
2583 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
2585 int enable = 1;
2586 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
2588 release_sock_fd( s, fd );
2589 SetLastError(WSAEAFNOSUPPORT);
2590 return SOCKET_ERROR;
2593 #endif
2594 if (name->sa_family == WS_AF_INET)
2596 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2597 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2599 /* Trying to bind to the default host interface, using
2600 * INADDR_ANY instead*/
2601 WARN("Trying to bind to magic IP address, using "
2602 "INADDR_ANY instead.\n");
2603 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
2605 else if (interface_bind(s, fd, &uaddr.addr))
2606 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
2608 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
2610 int loc_errno = errno;
2611 WARN("\tfailure - errno = %i\n", errno);
2612 errno = loc_errno;
2613 switch (errno)
2615 case EBADF:
2616 SetLastError(WSAENOTSOCK);
2617 break;
2618 case EADDRNOTAVAIL:
2619 SetLastError(WSAEINVAL);
2620 break;
2621 default:
2622 SetLastError(wsaErrno());
2623 break;
2626 else
2628 res=0; /* success */
2632 release_sock_fd( s, fd );
2634 return res;
2637 /***********************************************************************
2638 * closesocket (WS2_32.3)
2640 int WINAPI WS_closesocket(SOCKET s)
2642 TRACE("socket %04lx\n", s);
2643 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
2644 return SOCKET_ERROR;
2647 static int do_connect(int fd, const struct WS_sockaddr* name, int namelen)
2649 union generic_unix_sockaddr uaddr;
2650 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2652 if (!uaddrlen)
2653 return WSAEFAULT;
2655 if (name->sa_family == WS_AF_INET)
2657 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2658 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2660 /* Trying to connect to magic replace-loopback address,
2661 * assuming we really want to connect to localhost */
2662 TRACE("Trying to connect to magic IP address, using "
2663 "INADDR_LOOPBACK instead.\n");
2664 in4->sin_addr.s_addr = htonl(WS_INADDR_LOOPBACK);
2668 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
2669 return 0;
2671 return wsaErrno();
2674 /***********************************************************************
2675 * connect (WS2_32.4)
2677 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
2679 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2681 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2683 if (fd != -1)
2685 NTSTATUS status;
2686 BOOL is_blocking;
2687 int ret = do_connect(fd, name, namelen);
2688 if (ret == 0)
2689 goto connect_success;
2691 if (ret == WSAEINPROGRESS)
2693 /* tell wineserver that a connection is in progress */
2694 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2695 FD_CONNECT,
2696 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2697 status = _is_blocking( s, &is_blocking );
2698 if (status)
2700 release_sock_fd( s, fd );
2701 set_error( status );
2702 return SOCKET_ERROR;
2704 if (is_blocking)
2706 int result;
2707 /* block here */
2708 do_block(fd, POLLIN | POLLOUT, -1);
2709 _sync_sock_state(s); /* let wineserver notice connection */
2710 /* retrieve any error codes from it */
2711 result = _get_sock_error(s, FD_CONNECT_BIT);
2712 if (result)
2713 SetLastError(NtStatusToWSAError(result));
2714 else
2716 goto connect_success;
2719 else
2721 SetLastError(WSAEWOULDBLOCK);
2724 else
2726 SetLastError(ret);
2728 release_sock_fd( s, fd );
2730 return SOCKET_ERROR;
2732 connect_success:
2733 release_sock_fd( s, fd );
2734 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2735 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2736 FD_CONNECT|FD_WINE_LISTENING);
2737 return 0;
2740 /***********************************************************************
2741 * WSAConnect (WS2_32.30)
2743 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
2744 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
2745 LPQOS lpSQOS, LPQOS lpGQOS )
2747 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
2748 FIXME("unsupported parameters!\n");
2749 return WS_connect( s, name, namelen );
2752 /***********************************************************************
2753 * ConnectEx
2755 static BOOL WINAPI WS2_ConnectEx(SOCKET s, const struct WS_sockaddr* name, int namelen,
2756 PVOID sendBuf, DWORD sendBufLen, LPDWORD sent, LPOVERLAPPED ov)
2758 int fd, ret, status;
2759 union generic_unix_sockaddr uaddr;
2760 socklen_t uaddrlen = sizeof(uaddr);
2762 if (!ov)
2764 SetLastError( ERROR_INVALID_PARAMETER );
2765 return FALSE;
2768 fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2769 if (fd == -1)
2771 SetLastError( WSAENOTSOCK );
2772 return FALSE;
2775 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
2776 s, name, debugstr_sockaddr(name), namelen, sendBuf, sendBufLen, ov);
2778 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
2780 SetLastError(wsaErrno());
2781 return FALSE;
2783 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
2785 SetLastError(WSAEINVAL);
2786 return FALSE;
2789 ret = do_connect(fd, name, namelen);
2790 if (ret == 0)
2792 WSABUF wsabuf;
2794 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2795 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2796 FD_CONNECT|FD_WINE_LISTENING);
2798 wsabuf.len = sendBufLen;
2799 wsabuf.buf = (char*) sendBuf;
2801 /* WSASend takes care of completion if need be */
2802 if (WSASend(s, &wsabuf, sendBuf ? 1 : 0, sent, 0, ov, NULL) != SOCKET_ERROR)
2803 goto connection_success;
2805 else if (ret == WSAEINPROGRESS)
2807 struct ws2_async *wsa;
2808 ULONG_PTR cvalue = (((ULONG_PTR)ov->hEvent & 1) == 0) ? (ULONG_PTR)ov : 0;
2810 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2811 FD_CONNECT,
2812 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2814 /* Indirectly call WSASend */
2815 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( struct ws2_async, iovec[1] ))))
2817 SetLastError(WSAEFAULT);
2819 else
2821 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)ov;
2822 iosb->u.Status = STATUS_PENDING;
2823 iosb->Information = 0;
2825 wsa->hSocket = SOCKET2HANDLE(s);
2826 wsa->addr = NULL;
2827 wsa->addrlen.val = 0;
2828 wsa->flags = 0;
2829 wsa->lpFlags = &wsa->flags;
2830 wsa->control = NULL;
2831 wsa->n_iovecs = sendBuf ? 1 : 0;
2832 wsa->first_iovec = 0;
2833 wsa->completion_func = NULL;
2834 wsa->iovec[0].iov_base = sendBuf;
2835 wsa->iovec[0].iov_len = sendBufLen;
2837 SERVER_START_REQ( register_async )
2839 req->type = ASYNC_TYPE_WRITE;
2840 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2841 req->async.callback = wine_server_client_ptr( WS2_async_send );
2842 req->async.iosb = wine_server_client_ptr( iosb );
2843 req->async.arg = wine_server_client_ptr( wsa );
2844 req->async.event = wine_server_obj_handle( ov->hEvent );
2845 req->async.cvalue = cvalue;
2846 status = wine_server_call( req );
2848 SERVER_END_REQ;
2850 if (status != STATUS_PENDING) HeapFree(GetProcessHeap(), 0, wsa);
2852 /* If the connect already failed */
2853 if (status == STATUS_PIPE_DISCONNECTED)
2854 status = _get_sock_error(s, FD_CONNECT_BIT);
2855 SetLastError( NtStatusToWSAError(status) );
2858 else
2860 SetLastError(ret);
2863 release_sock_fd( s, fd );
2864 return FALSE;
2866 connection_success:
2867 release_sock_fd( s, fd );
2868 return TRUE;
2872 /***********************************************************************
2873 * getpeername (WS2_32.5)
2875 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
2877 int fd;
2878 int res;
2880 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
2882 fd = get_sock_fd( s, 0, NULL );
2883 res = SOCKET_ERROR;
2885 if (fd != -1)
2887 union generic_unix_sockaddr uaddr;
2888 socklen_t uaddrlen = sizeof(uaddr);
2890 if (getpeername(fd, &uaddr.addr, &uaddrlen) == 0)
2892 if (!name || !namelen)
2893 SetLastError(WSAEFAULT);
2894 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
2895 /* The buffer was too small */
2896 SetLastError(WSAEFAULT);
2897 else
2898 res = 0;
2900 else
2901 SetLastError(wsaErrno());
2902 release_sock_fd( s, fd );
2904 return res;
2907 /***********************************************************************
2908 * getsockname (WS2_32.6)
2910 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
2912 int fd;
2913 int res;
2915 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
2917 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
2918 if( (name == NULL) || (namelen == NULL) )
2920 SetLastError( WSAEFAULT );
2921 return SOCKET_ERROR;
2924 fd = get_sock_fd( s, 0, NULL );
2925 res = SOCKET_ERROR;
2927 if (fd != -1)
2929 union generic_unix_sockaddr uaddr;
2930 socklen_t uaddrlen = sizeof(uaddr);
2932 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
2934 SetLastError(wsaErrno());
2936 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
2938 SetLastError(WSAEINVAL);
2940 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
2942 /* The buffer was too small */
2943 SetLastError(WSAEFAULT);
2945 else
2947 res=0;
2948 TRACE("=> %s\n", debugstr_sockaddr(name));
2950 release_sock_fd( s, fd );
2952 return res;
2955 /***********************************************************************
2956 * getsockopt (WS2_32.7)
2958 INT WINAPI WS_getsockopt(SOCKET s, INT level,
2959 INT optname, char *optval, INT *optlen)
2961 int fd;
2962 INT ret = 0;
2964 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
2965 s, level, optname, optval, optlen ? *optlen : 0);
2967 switch(level)
2969 case WS_SOL_SOCKET:
2971 switch(optname)
2973 /* Handle common cases. The special cases are below, sorted
2974 * alphabetically */
2975 case WS_SO_BROADCAST:
2976 case WS_SO_DEBUG:
2977 case WS_SO_ERROR:
2978 case WS_SO_KEEPALIVE:
2979 case WS_SO_OOBINLINE:
2980 case WS_SO_RCVBUF:
2981 case WS_SO_REUSEADDR:
2982 case WS_SO_SNDBUF:
2983 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2984 return SOCKET_ERROR;
2985 convert_sockopt(&level, &optname);
2986 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
2988 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2989 ret = SOCKET_ERROR;
2991 release_sock_fd( s, fd );
2992 return ret;
2993 case WS_SO_ACCEPTCONN:
2994 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2995 return SOCKET_ERROR;
2996 if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, optval, (socklen_t *)optlen) != 0 )
2998 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2999 ret = SOCKET_ERROR;
3001 else
3003 /* BSD returns != 0 while Windows return exact == 1 */
3004 if (*(int *)optval) *(int *)optval = 1;
3006 release_sock_fd( s, fd );
3007 return ret;
3008 case WS_SO_DONTLINGER:
3010 struct linger lingval;
3011 socklen_t len = sizeof(struct linger);
3013 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
3015 SetLastError(WSAEFAULT);
3016 return SOCKET_ERROR;
3018 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3019 return SOCKET_ERROR;
3021 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
3023 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3024 ret = SOCKET_ERROR;
3026 else
3028 *(BOOL *)optval = !lingval.l_onoff;
3029 *optlen = sizeof(BOOL);
3032 release_sock_fd( s, fd );
3033 return ret;
3036 case WS_SO_CONNECT_TIME:
3038 static int pretendtime = 0;
3039 struct WS_sockaddr addr;
3040 int len = sizeof(addr);
3042 if (!optlen || *optlen < sizeof(DWORD) || !optval)
3044 SetLastError(WSAEFAULT);
3045 return SOCKET_ERROR;
3047 if (WS_getpeername(s, &addr, &len) == SOCKET_ERROR)
3048 *(DWORD *)optval = ~0u;
3049 else
3051 if (!pretendtime) FIXME("WS_SO_CONNECT_TIME - faking results\n");
3052 *(DWORD *)optval = pretendtime++;
3054 *optlen = sizeof(DWORD);
3055 return ret;
3057 /* As mentioned in setsockopt, Windows ignores this, so we
3058 * always return true here */
3059 case WS_SO_DONTROUTE:
3060 if (!optlen || *optlen < sizeof(BOOL) || !optval)
3062 SetLastError(WSAEFAULT);
3063 return SOCKET_ERROR;
3065 *(BOOL *)optval = TRUE;
3066 *optlen = sizeof(BOOL);
3067 return 0;
3069 case WS_SO_LINGER:
3071 struct linger lingval;
3072 int so_type;
3073 socklen_t len = sizeof(struct linger), slen = sizeof(int);
3075 /* struct linger and LINGER have different sizes */
3076 if (!optlen || *optlen < sizeof(LINGER) || !optval)
3078 SetLastError(WSAEFAULT);
3079 return SOCKET_ERROR;
3081 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3082 return SOCKET_ERROR;
3084 if ((getsockopt(fd, SOL_SOCKET, SO_TYPE, &so_type, &slen) == 0 && so_type == SOCK_DGRAM))
3086 SetLastError(WSAENOPROTOOPT);
3087 ret = SOCKET_ERROR;
3089 else if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0)
3091 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3092 ret = SOCKET_ERROR;
3094 else
3096 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
3097 ((LINGER *)optval)->l_linger = lingval.l_linger;
3098 *optlen = sizeof(struct linger);
3101 release_sock_fd( s, fd );
3102 return ret;
3105 case WS_SO_MAX_MSG_SIZE:
3106 if (!optlen || *optlen < sizeof(int) || !optval)
3108 SetLastError(WSAEFAULT);
3109 return SOCKET_ERROR;
3111 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
3112 *(int *)optval = 65507;
3113 *optlen = sizeof(int);
3114 return 0;
3116 /* SO_OPENTYPE does not require a valid socket handle. */
3117 case WS_SO_OPENTYPE:
3118 if (!optlen || *optlen < sizeof(int) || !optval)
3120 SetLastError(WSAEFAULT);
3121 return SOCKET_ERROR;
3123 *(int *)optval = get_per_thread_data()->opentype;
3124 *optlen = sizeof(int);
3125 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
3126 return 0;
3127 case WS_SO_PROTOCOL_INFOA:
3128 case WS_SO_PROTOCOL_INFOW:
3130 int size;
3131 WSAPROTOCOL_INFOW infow;
3133 ret = ws_protocol_info(s, optname == WS_SO_PROTOCOL_INFOW, &infow, &size);
3134 if (ret)
3136 if (!optlen || !optval || *optlen < size)
3138 if(optlen) *optlen = size;
3139 ret = 0;
3140 SetLastError(WSAEFAULT);
3142 else
3143 memcpy(optval, &infow, size);
3145 return ret ? 0 : SOCKET_ERROR;
3147 #ifdef SO_RCVTIMEO
3148 case WS_SO_RCVTIMEO:
3149 #endif
3150 #ifdef SO_SNDTIMEO
3151 case WS_SO_SNDTIMEO:
3152 #endif
3153 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
3155 struct timeval tv;
3156 socklen_t len = sizeof(struct timeval);
3158 if (!optlen || *optlen < sizeof(int)|| !optval)
3160 SetLastError(WSAEFAULT);
3161 return SOCKET_ERROR;
3163 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3164 return SOCKET_ERROR;
3166 convert_sockopt(&level, &optname);
3167 if (getsockopt(fd, level, optname, &tv, &len) != 0 )
3169 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3170 ret = SOCKET_ERROR;
3172 else
3174 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
3175 *optlen = sizeof(int);
3178 release_sock_fd( s, fd );
3179 return ret;
3181 #endif
3182 case WS_SO_TYPE:
3184 if (!optlen || *optlen < sizeof(int) || !optval)
3186 SetLastError(WSAEFAULT);
3187 return SOCKET_ERROR;
3189 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3190 return SOCKET_ERROR;
3192 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, optval, (socklen_t *)optlen) != 0 )
3194 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3195 ret = SOCKET_ERROR;
3197 else
3198 (*(int *)optval) = convert_socktype_u2w(*(int *)optval);
3200 release_sock_fd( s, fd );
3201 return ret;
3203 default:
3204 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
3205 SetLastError(WSAENOPROTOOPT);
3206 return SOCKET_ERROR;
3207 } /* end switch(optname) */
3208 }/* end case WS_SOL_SOCKET */
3209 #ifdef HAS_IPX
3210 case WS_NSPROTO_IPX:
3212 struct WS_sockaddr_ipx addr;
3213 IPX_ADDRESS_DATA *data;
3214 int namelen;
3215 switch(optname)
3217 case IPX_PTYPE:
3218 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3219 #ifdef SOL_IPX
3220 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (socklen_t *)optlen) == -1)
3222 ret = SOCKET_ERROR;
3224 #else
3226 struct ipx val;
3227 socklen_t len=sizeof(struct ipx);
3228 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
3229 ret = SOCKET_ERROR;
3230 else
3231 *optval = (int)val.ipx_pt;
3233 #endif
3234 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
3235 release_sock_fd( s, fd );
3236 return ret;
3238 case IPX_ADDRESS:
3240 * On a Win2000 system with one network card there are usually
3241 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
3242 * Using this call you can then retrieve info about this all.
3243 * In case of Linux it is a bit different. Usually you have
3244 * only "one" device active and further it is not possible to
3245 * query things like the linkspeed.
3247 FIXME("IPX_ADDRESS\n");
3248 namelen = sizeof(struct WS_sockaddr_ipx);
3249 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
3250 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
3252 data = (IPX_ADDRESS_DATA*)optval;
3253 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
3254 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
3255 data->adapternum = 0;
3256 data->wan = FALSE; /* We are not on a wan for now .. */
3257 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
3258 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
3259 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
3260 * note 1MB = 1000kB in this case */
3261 return 0;
3263 case IPX_MAX_ADAPTER_NUM:
3264 FIXME("IPX_MAX_ADAPTER_NUM\n");
3265 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
3266 return 0;
3268 default:
3269 FIXME("IPX optname:%x\n", optname);
3270 return SOCKET_ERROR;
3271 }/* end switch(optname) */
3272 } /* end case WS_NSPROTO_IPX */
3273 #endif
3275 #ifdef HAS_IRDA
3276 case WS_SOL_IRLMP:
3277 switch(optname)
3279 case WS_IRLMP_ENUMDEVICES:
3281 static const int MAX_IRDA_DEVICES = 10;
3282 char buf[sizeof(struct irda_device_list) +
3283 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
3284 int res;
3285 socklen_t len = sizeof(buf);
3287 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3288 return SOCKET_ERROR;
3289 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
3290 if (res < 0)
3292 SetLastError(wsaErrno());
3293 return SOCKET_ERROR;
3295 else
3297 struct irda_device_list *src = (struct irda_device_list *)buf;
3298 DEVICELIST *dst = (DEVICELIST *)optval;
3299 INT needed = sizeof(DEVICELIST);
3300 unsigned int i;
3302 if (src->len > 0)
3303 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
3304 if (*optlen < needed)
3306 SetLastError(WSAEFAULT);
3307 return SOCKET_ERROR;
3309 *optlen = needed;
3310 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
3311 dst->numDevice = src->len;
3312 for (i = 0; i < src->len; i++)
3314 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
3315 src->dev[i].saddr, src->dev[i].daddr,
3316 src->dev[i].info, src->dev[i].hints[0],
3317 src->dev[i].hints[1]);
3318 memcpy( dst->Device[i].irdaDeviceID,
3319 &src->dev[i].daddr,
3320 sizeof(dst->Device[i].irdaDeviceID) ) ;
3321 memcpy( dst->Device[i].irdaDeviceName,
3322 src->dev[i].info,
3323 sizeof(dst->Device[i].irdaDeviceName) ) ;
3324 memcpy( &dst->Device[i].irdaDeviceHints1,
3325 &src->dev[i].hints[0],
3326 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
3327 memcpy( &dst->Device[i].irdaDeviceHints2,
3328 &src->dev[i].hints[1],
3329 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
3330 dst->Device[i].irdaCharSet = src->dev[i].charset;
3332 return 0;
3335 default:
3336 FIXME("IrDA optname:0x%x\n", optname);
3337 return SOCKET_ERROR;
3339 break; /* case WS_SOL_IRLMP */
3340 #endif
3342 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3343 case WS_IPPROTO_TCP:
3344 switch(optname)
3346 case WS_TCP_NODELAY:
3347 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3348 return SOCKET_ERROR;
3349 convert_sockopt(&level, &optname);
3350 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3352 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3353 ret = SOCKET_ERROR;
3355 release_sock_fd( s, fd );
3356 return ret;
3358 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
3359 return SOCKET_ERROR;
3361 case WS_IPPROTO_IP:
3362 switch(optname)
3364 case WS_IP_ADD_MEMBERSHIP:
3365 case WS_IP_DROP_MEMBERSHIP:
3366 #ifdef IP_HDRINCL
3367 case WS_IP_HDRINCL:
3368 #endif
3369 case WS_IP_MULTICAST_IF:
3370 case WS_IP_MULTICAST_LOOP:
3371 case WS_IP_MULTICAST_TTL:
3372 case WS_IP_OPTIONS:
3373 #ifdef IP_PKTINFO
3374 case WS_IP_PKTINFO:
3375 #endif
3376 case WS_IP_TOS:
3377 case WS_IP_TTL:
3378 #ifdef IP_UNICAST_IF
3379 case WS_IP_UNICAST_IF:
3380 #endif
3381 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3382 return SOCKET_ERROR;
3383 convert_sockopt(&level, &optname);
3384 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3386 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3387 ret = SOCKET_ERROR;
3389 release_sock_fd( s, fd );
3390 return ret;
3391 case WS_IP_DONTFRAGMENT:
3392 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
3393 *(BOOL*)optval = FALSE;
3394 return 0;
3396 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
3397 return SOCKET_ERROR;
3399 case WS_IPPROTO_IPV6:
3400 switch(optname)
3402 #ifdef IPV6_ADD_MEMBERSHIP
3403 case WS_IPV6_ADD_MEMBERSHIP:
3404 #endif
3405 #ifdef IPV6_DROP_MEMBERSHIP
3406 case WS_IPV6_DROP_MEMBERSHIP:
3407 #endif
3408 case WS_IPV6_MULTICAST_IF:
3409 case WS_IPV6_MULTICAST_HOPS:
3410 case WS_IPV6_MULTICAST_LOOP:
3411 case WS_IPV6_UNICAST_HOPS:
3412 case WS_IPV6_V6ONLY:
3413 #ifdef IPV6_UNICAST_IF
3414 case WS_IPV6_UNICAST_IF:
3415 #endif
3416 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3417 return SOCKET_ERROR;
3418 convert_sockopt(&level, &optname);
3419 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3421 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3422 ret = SOCKET_ERROR;
3424 release_sock_fd( s, fd );
3425 return ret;
3426 case WS_IPV6_DONTFRAG:
3427 FIXME("WS_IPV6_DONTFRAG is always false!\n");
3428 *(BOOL*)optval = FALSE;
3429 return 0;
3431 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
3432 return SOCKET_ERROR;
3434 default:
3435 WARN("Unknown level: 0x%08x\n", level);
3436 SetLastError(WSAEINVAL);
3437 return SOCKET_ERROR;
3438 } /* end switch(level) */
3441 /***********************************************************************
3442 * htonl (WS2_32.8)
3444 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
3446 return htonl(hostlong);
3450 /***********************************************************************
3451 * htons (WS2_32.9)
3453 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
3455 return htons(hostshort);
3458 /***********************************************************************
3459 * WSAHtonl (WS2_32.46)
3460 * From MSDN description of error codes, this function should also
3461 * check if WinSock has been initialized and the socket is a valid
3462 * socket. But why? This function only translates a host byte order
3463 * u_long into a network byte order u_long...
3465 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
3467 if (lpnetlong)
3469 *lpnetlong = htonl(hostlong);
3470 return 0;
3472 WSASetLastError(WSAEFAULT);
3473 return SOCKET_ERROR;
3476 /***********************************************************************
3477 * WSAHtons (WS2_32.47)
3478 * From MSDN description of error codes, this function should also
3479 * check if WinSock has been initialized and the socket is a valid
3480 * socket. But why? This function only translates a host byte order
3481 * u_short into a network byte order u_short...
3483 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
3486 if (lpnetshort)
3488 *lpnetshort = htons(hostshort);
3489 return 0;
3491 WSASetLastError(WSAEFAULT);
3492 return SOCKET_ERROR;
3496 /***********************************************************************
3497 * inet_addr (WS2_32.11)
3499 WS_u_long WINAPI WS_inet_addr(const char *cp)
3501 if (!cp) return INADDR_NONE;
3502 return inet_addr(cp);
3506 /***********************************************************************
3507 * ntohl (WS2_32.14)
3509 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
3511 return ntohl(netlong);
3515 /***********************************************************************
3516 * ntohs (WS2_32.15)
3518 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
3520 return ntohs(netshort);
3524 /***********************************************************************
3525 * inet_ntoa (WS2_32.12)
3527 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
3529 char* s = inet_ntoa(*((struct in_addr*)&in));
3530 if( s )
3532 struct per_thread_data *data = get_per_thread_data();
3533 strcpy(data->ntoa_buffer, s);
3534 return data->ntoa_buffer;
3536 SetLastError(wsaErrno());
3537 return NULL;
3540 static const char *debugstr_wsaioctl(DWORD ioctl)
3542 const char *buf_type, *family;
3544 switch(ioctl & 0x18000000)
3546 case WS_IOC_WS2:
3547 family = "IOC_WS2";
3548 break;
3549 case WS_IOC_PROTOCOL:
3550 family = "IOC_PROTOCOL";
3551 break;
3552 case WS_IOC_VENDOR:
3553 family = "IOC_VENDOR";
3554 break;
3555 default: /* WS_IOC_UNIX */
3557 BYTE size = (ioctl >> 16) & WS_IOCPARM_MASK;
3558 char x = (ioctl & 0xff00) >> 8;
3559 BYTE y = ioctl & 0xff;
3560 char args[14];
3562 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3564 case WS_IOC_VOID:
3565 buf_type = "_IO";
3566 sprintf(args, "%d, %d", x, y);
3567 break;
3568 case WS_IOC_IN:
3569 buf_type = "_IOW";
3570 sprintf(args, "'%c', %d, %d", x, y, size);
3571 break;
3572 case WS_IOC_OUT:
3573 buf_type = "_IOR";
3574 sprintf(args, "'%c', %d, %d", x, y, size);
3575 break;
3576 default:
3577 buf_type = "?";
3578 sprintf(args, "'%c', %d, %d", x, y, size);
3579 break;
3581 return wine_dbg_sprintf("%s(%s)", buf_type, args);
3585 /* We are different from WS_IOC_UNIX. */
3586 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3588 case WS_IOC_VOID:
3589 buf_type = "_WSAIO";
3590 break;
3591 case WS_IOC_INOUT:
3592 buf_type = "_WSAIORW";
3593 break;
3594 case WS_IOC_IN:
3595 buf_type = "_WSAIOW";
3596 break;
3597 case WS_IOC_OUT:
3598 buf_type = "_WSAIOR";
3599 break;
3600 default:
3601 buf_type = "?";
3602 break;
3605 return wine_dbg_sprintf("%s(%s, %d)", buf_type, family,
3606 (USHORT)(ioctl & 0xffff));
3609 /**********************************************************************
3610 * WSAIoctl (WS2_32.50)
3613 INT WINAPI WSAIoctl(SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size, LPVOID out_buff,
3614 DWORD out_size, LPDWORD ret_size, LPWSAOVERLAPPED overlapped,
3615 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
3617 int fd;
3618 DWORD status = 0, total = 0;
3620 TRACE("%ld, 0x%08x, %p, %d, %p, %d, %p, %p, %p\n",
3621 s, code, in_buff, in_size, out_buff, out_size, ret_size, overlapped, completion);
3623 switch (code)
3625 case WS_FIONBIO:
3626 if (in_size != sizeof(WS_u_long) || IS_INTRESOURCE(in_buff))
3628 WSASetLastError(WSAEFAULT);
3629 return SOCKET_ERROR;
3631 if (_get_sock_mask(s))
3633 /* AsyncSelect()'ed sockets are always nonblocking */
3634 if (!*(WS_u_long *)in_buff) status = WSAEINVAL;
3635 break;
3637 if (*(WS_u_long *)in_buff)
3638 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
3639 else
3640 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
3641 break;
3643 case WS_FIONREAD:
3645 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
3647 WSASetLastError(WSAEFAULT);
3648 return SOCKET_ERROR;
3650 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3651 if (ioctl(fd, FIONREAD, out_buff ) == -1)
3652 status = (errno == EBADF) ? WSAENOTSOCK : wsaErrno();
3653 release_sock_fd( s, fd );
3654 break;
3657 case WS_SIOCATMARK:
3659 unsigned int oob = 0, atmark = 0;
3660 socklen_t oobsize = sizeof(int);
3661 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
3663 WSASetLastError(WSAEFAULT);
3664 return SOCKET_ERROR;
3666 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3667 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
3668 if ((getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &oob, &oobsize ) == -1)
3669 || (!oob && ioctl(fd, SIOCATMARK, &atmark ) == -1))
3670 status = (errno == EBADF) ? WSAENOTSOCK : wsaErrno();
3671 else
3673 /* The SIOCATMARK value read from ioctl() is reversed
3674 * because BSD returns TRUE if it's in the OOB mark
3675 * while Windows returns TRUE if there are NO OOB bytes.
3677 (*(WS_u_long *) out_buff) = oob | !atmark;
3680 release_sock_fd( s, fd );
3681 break;
3684 case WS_FIOASYNC:
3685 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
3686 SetLastError(WSAEINVAL);
3687 return SOCKET_ERROR;
3689 case WS_SIO_GET_INTERFACE_LIST:
3691 INTERFACE_INFO* intArray = out_buff;
3692 DWORD size, numInt = 0, apiReturn;
3694 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
3696 if (!out_buff || !ret_size)
3698 WSASetLastError(WSAEFAULT);
3699 return SOCKET_ERROR;
3702 fd = get_sock_fd( s, 0, NULL );
3703 if (fd == -1) return SOCKET_ERROR;
3705 apiReturn = GetAdaptersInfo(NULL, &size);
3706 if (apiReturn == ERROR_BUFFER_OVERFLOW)
3708 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
3710 if (table)
3712 if (GetAdaptersInfo(table, &size) == NO_ERROR)
3714 PIP_ADAPTER_INFO ptr;
3716 for (ptr = table, numInt = 0; ptr; ptr = ptr->Next)
3718 unsigned int addr, mask, bcast;
3719 struct ifreq ifInfo;
3721 /* Skip interfaces without an IPv4 address. */
3722 if (ptr->IpAddressList.IpAddress.String[0] == '\0')
3723 continue;
3725 if ((numInt + 1)*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > out_size)
3727 WARN("Buffer too small = %u, out_size = %u\n", numInt + 1, out_size);
3728 status = WSAEFAULT;
3729 break;
3732 /* Socket Status Flags */
3733 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
3734 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
3736 ERR("Error obtaining status flags for socket!\n");
3737 status = WSAEINVAL;
3738 break;
3740 else
3742 /* set flags; the values of IFF_* are not the same
3743 under Linux and Windows, therefore must generate
3744 new flags */
3745 intArray->iiFlags = 0;
3746 if (ifInfo.ifr_flags & IFF_BROADCAST)
3747 intArray->iiFlags |= WS_IFF_BROADCAST;
3748 #ifdef IFF_POINTOPOINT
3749 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
3750 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
3751 #endif
3752 if (ifInfo.ifr_flags & IFF_LOOPBACK)
3753 intArray->iiFlags |= WS_IFF_LOOPBACK;
3754 if (ifInfo.ifr_flags & IFF_UP)
3755 intArray->iiFlags |= WS_IFF_UP;
3756 if (ifInfo.ifr_flags & IFF_MULTICAST)
3757 intArray->iiFlags |= WS_IFF_MULTICAST;
3760 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
3761 mask = inet_addr(ptr->IpAddressList.IpMask.String);
3762 bcast = addr | ~mask;
3763 intArray->iiAddress.AddressIn.sin_family = AF_INET;
3764 intArray->iiAddress.AddressIn.sin_port = 0;
3765 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
3766 addr;
3767 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
3768 intArray->iiNetmask.AddressIn.sin_port = 0;
3769 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
3770 mask;
3771 intArray->iiBroadcastAddress.AddressIn.sin_family =
3772 AF_INET;
3773 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
3774 intArray->iiBroadcastAddress.AddressIn.sin_addr.
3775 WS_s_addr = bcast;
3776 intArray++;
3777 numInt++;
3780 else
3782 ERR("Unable to get interface table!\n");
3783 status = WSAEINVAL;
3785 HeapFree(GetProcessHeap(),0,table);
3787 else status = WSAEINVAL;
3789 else if (apiReturn != ERROR_NO_DATA)
3791 ERR("Unable to get interface table!\n");
3792 status = WSAEINVAL;
3794 /* Calculate the size of the array being returned */
3795 total = sizeof(INTERFACE_INFO) * numInt;
3796 release_sock_fd( s, fd );
3797 break;
3800 case WS_SIO_ADDRESS_LIST_CHANGE:
3801 FIXME("-> SIO_ADDRESS_LIST_CHANGE request: stub\n");
3802 /* FIXME: error and return code depend on whether socket was created
3803 * with WSA_FLAG_OVERLAPPED, but there is no easy way to get this */
3804 break;
3806 case WS_SIO_ADDRESS_LIST_QUERY:
3808 DWORD size;
3810 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
3812 if (!ret_size)
3814 WSASetLastError(WSAEFAULT);
3815 return SOCKET_ERROR;
3818 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
3820 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
3821 DWORD num;
3823 if (!table || GetAdaptersInfo(table, &size))
3825 HeapFree(GetProcessHeap(), 0, table);
3826 status = WSAEINVAL;
3827 break;
3830 for (p = table, num = 0; p; p = p->Next)
3831 if (p->IpAddressList.IpAddress.String[0]) num++;
3833 total = sizeof(SOCKET_ADDRESS_LIST) + sizeof(SOCKET_ADDRESS) * (num - 1);
3834 total += sizeof(SOCKADDR) * num;
3836 if (total > out_size)
3838 HeapFree(GetProcessHeap(), 0, table);
3839 status = WSAEFAULT;
3840 break;
3843 if (out_buff)
3845 unsigned int i;
3846 SOCKET_ADDRESS *sa;
3847 SOCKET_ADDRESS_LIST *sa_list = out_buff;
3848 SOCKADDR_IN *sockaddr;
3850 sa = sa_list->Address;
3851 sockaddr = (SOCKADDR_IN *)((char *)sa + num * sizeof(SOCKET_ADDRESS));
3852 sa_list->iAddressCount = num;
3854 for (p = table, i = 0; p; p = p->Next)
3856 if (!p->IpAddressList.IpAddress.String[0]) continue;
3858 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
3859 sa[i].iSockaddrLength = sizeof(SOCKADDR);
3861 sockaddr[i].sin_family = AF_INET;
3862 sockaddr[i].sin_port = 0;
3863 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
3864 i++;
3868 HeapFree(GetProcessHeap(), 0, table);
3870 else
3872 WARN("unable to get IP address list\n");
3873 status = WSAEINVAL;
3875 break;
3878 case WS_SIO_FLUSH:
3879 FIXME("SIO_FLUSH: stub.\n");
3880 break;
3882 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
3884 static const GUID connectex_guid = WSAID_CONNECTEX;
3885 static const GUID disconnectex_guid = WSAID_DISCONNECTEX;
3886 static const GUID acceptex_guid = WSAID_ACCEPTEX;
3887 static const GUID getaccepexsockaddrs_guid = WSAID_GETACCEPTEXSOCKADDRS;
3888 static const GUID transmitfile_guid = WSAID_TRANSMITFILE;
3889 static const GUID transmitpackets_guid = WSAID_TRANSMITPACKETS;
3890 static const GUID wsarecvmsg_guid = WSAID_WSARECVMSG;
3891 static const GUID wsasendmsg_guid = WSAID_WSASENDMSG;
3893 if ( IsEqualGUID(&connectex_guid, in_buff) )
3895 *(LPFN_CONNECTEX *)out_buff = WS2_ConnectEx;
3896 break;
3898 else if ( IsEqualGUID(&disconnectex_guid, in_buff) )
3900 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented DisconnectEx\n");
3902 else if ( IsEqualGUID(&acceptex_guid, in_buff) )
3904 *(LPFN_ACCEPTEX *)out_buff = WS2_AcceptEx;
3905 break;
3907 else if ( IsEqualGUID(&getaccepexsockaddrs_guid, in_buff) )
3909 *(LPFN_GETACCEPTEXSOCKADDRS *)out_buff = WS2_GetAcceptExSockaddrs;
3910 break;
3912 else if ( IsEqualGUID(&transmitfile_guid, in_buff) )
3914 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitFile\n");
3916 else if ( IsEqualGUID(&transmitpackets_guid, in_buff) )
3918 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitPackets\n");
3920 else if ( IsEqualGUID(&wsarecvmsg_guid, in_buff) )
3922 *(LPFN_WSARECVMSG *)out_buff = WS2_WSARecvMsg;
3923 break;
3925 else if ( IsEqualGUID(&wsasendmsg_guid, in_buff) )
3927 *(LPFN_WSASENDMSG *)out_buff = WSASendMsg;
3928 break;
3930 else
3931 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff));
3933 status = WSAEOPNOTSUPP;
3934 break;
3936 case WS_SIO_KEEPALIVE_VALS:
3938 struct tcp_keepalive *k;
3939 int keepalive, keepidle, keepintvl;
3941 if (!in_buff || in_size < sizeof(struct tcp_keepalive))
3943 WSASetLastError(WSAEFAULT);
3944 return SOCKET_ERROR;
3947 k = in_buff;
3948 keepalive = k->onoff ? 1 : 0;
3949 keepidle = max( 1, (k->keepalivetime + 500) / 1000 );
3950 keepintvl = max( 1, (k->keepaliveinterval + 500) / 1000 );
3952 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
3954 fd = get_sock_fd(s, 0, NULL);
3955 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
3956 status = WSAEINVAL;
3957 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
3958 /* these values need to be set only if SO_KEEPALIVE is enabled */
3959 else if(keepalive)
3961 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
3962 status = WSAEINVAL;
3963 else if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
3964 status = WSAEINVAL;
3966 #else
3967 else
3968 FIXME("ignoring keepalive interval and timeout\n");
3969 #endif
3970 release_sock_fd(s, fd);
3971 break;
3973 case WS_SIO_ROUTING_INTERFACE_QUERY:
3975 struct WS_sockaddr *daddr = (struct WS_sockaddr *)in_buff;
3976 struct WS_sockaddr_in *daddr_in = (struct WS_sockaddr_in *)daddr;
3977 struct WS_sockaddr_in *saddr_in = out_buff;
3978 MIB_IPFORWARDROW row;
3979 PMIB_IPADDRTABLE ipAddrTable = NULL;
3980 DWORD size, i, found_index;
3982 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
3984 if (!in_buff || in_size < sizeof(struct WS_sockaddr) ||
3985 !out_buff || out_size < sizeof(struct WS_sockaddr_in) || !ret_size)
3987 WSASetLastError(WSAEFAULT);
3988 return SOCKET_ERROR;
3990 if (daddr->sa_family != AF_INET)
3992 FIXME("unsupported address family %d\n", daddr->sa_family);
3993 status = WSAEAFNOSUPPORT;
3994 break;
3996 if (GetBestRoute(daddr_in->sin_addr.S_un.S_addr, 0, &row) != NOERROR ||
3997 GetIpAddrTable(NULL, &size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
3999 status = WSAEFAULT;
4000 break;
4002 ipAddrTable = HeapAlloc(GetProcessHeap(), 0, size);
4003 if (GetIpAddrTable(ipAddrTable, &size, FALSE))
4005 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4006 status = WSAEFAULT;
4007 break;
4009 for (i = 0, found_index = ipAddrTable->dwNumEntries;
4010 i < ipAddrTable->dwNumEntries; i++)
4012 if (ipAddrTable->table[i].dwIndex == row.dwForwardIfIndex)
4013 found_index = i;
4015 if (found_index == ipAddrTable->dwNumEntries)
4017 ERR("no matching IP address for interface %d\n",
4018 row.dwForwardIfIndex);
4019 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4020 status = WSAEFAULT;
4021 break;
4023 saddr_in->sin_family = AF_INET;
4024 saddr_in->sin_addr.S_un.S_addr = ipAddrTable->table[found_index].dwAddr;
4025 saddr_in->sin_port = 0;
4026 total = sizeof(struct WS_sockaddr_in);
4027 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4028 break;
4030 case WS_SIO_SET_COMPATIBILITY_MODE:
4031 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
4032 status = WSAEOPNOTSUPP;
4033 break;
4034 case WS_SIO_UDP_CONNRESET:
4035 FIXME("WS_SIO_UDP_CONNRESET stub\n");
4036 break;
4037 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
4038 WSASetLastError(WSAEOPNOTSUPP);
4039 return SOCKET_ERROR;
4040 default:
4041 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code));
4042 status = WSAEOPNOTSUPP;
4043 break;
4046 if (completion)
4048 FIXME( "completion routine %p not supported\n", completion );
4050 else if (overlapped)
4052 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
4053 overlapped->Internal = status;
4054 overlapped->InternalHigh = total;
4055 if (overlapped->hEvent) NtSetEvent( overlapped->hEvent, NULL );
4056 if (cvalue) WS_AddCompletion( HANDLE2SOCKET(s), cvalue, status, total );
4059 if (!status)
4061 if (ret_size) *ret_size = total;
4062 return 0;
4064 SetLastError( status );
4065 return SOCKET_ERROR;
4069 /***********************************************************************
4070 * ioctlsocket (WS2_32.10)
4072 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
4074 DWORD ret_size;
4075 return WSAIoctl( s, cmd, argp, sizeof(WS_u_long), argp, sizeof(WS_u_long), &ret_size, NULL, NULL );
4078 /***********************************************************************
4079 * listen (WS2_32.13)
4081 int WINAPI WS_listen(SOCKET s, int backlog)
4083 int fd = get_sock_fd( s, FILE_READ_DATA, NULL ), ret = SOCKET_ERROR;
4085 TRACE("socket %04lx, backlog %d\n", s, backlog);
4086 if (fd != -1)
4088 union generic_unix_sockaddr uaddr;
4089 socklen_t uaddrlen = sizeof(uaddr);
4091 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
4093 SetLastError(wsaErrno());
4095 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
4097 SetLastError(WSAEINVAL);
4099 else if (listen(fd, backlog) == 0)
4101 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
4102 FD_WINE_LISTENING,
4103 FD_CONNECT|FD_WINE_CONNECTED);
4104 ret = 0;
4106 else
4107 SetLastError(wsaErrno());
4108 release_sock_fd( s, fd );
4110 else
4111 SetLastError(WSAENOTSOCK);
4112 return ret;
4115 /***********************************************************************
4116 * recv (WS2_32.16)
4118 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
4120 DWORD n, dwFlags = flags;
4121 WSABUF wsabuf;
4123 wsabuf.len = len;
4124 wsabuf.buf = buf;
4126 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
4127 return SOCKET_ERROR;
4128 else
4129 return n;
4132 /***********************************************************************
4133 * recvfrom (WS2_32.17)
4135 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
4136 struct WS_sockaddr *from, int *fromlen)
4138 DWORD n, dwFlags = flags;
4139 WSABUF wsabuf;
4141 wsabuf.len = len;
4142 wsabuf.buf = buf;
4144 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL, NULL) == SOCKET_ERROR )
4145 return SOCKET_ERROR;
4146 else
4147 return n;
4150 /* allocate a poll array for the corresponding fd sets */
4151 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
4152 const WS_fd_set *exceptfds, int *count_ptr )
4154 unsigned int i, j = 0, count = 0;
4155 struct pollfd *fds;
4157 if (readfds) count += readfds->fd_count;
4158 if (writefds) count += writefds->fd_count;
4159 if (exceptfds) count += exceptfds->fd_count;
4160 *count_ptr = count;
4161 if (!count)
4163 SetLastError(WSAEINVAL);
4164 return NULL;
4166 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0]))))
4168 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
4169 return NULL;
4171 if (readfds)
4172 for (i = 0; i < readfds->fd_count; i++, j++)
4174 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
4175 if (fds[j].fd == -1) goto failed;
4176 fds[j].events = POLLIN;
4177 fds[j].revents = 0;
4179 if (writefds)
4180 for (i = 0; i < writefds->fd_count; i++, j++)
4182 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
4183 if (fds[j].fd == -1) goto failed;
4184 fds[j].events = POLLOUT;
4185 fds[j].revents = 0;
4187 if (exceptfds)
4188 for (i = 0; i < exceptfds->fd_count; i++, j++)
4190 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
4191 if (fds[j].fd == -1) goto failed;
4192 fds[j].events = POLLHUP;
4193 fds[j].revents = 0;
4195 return fds;
4197 failed:
4198 count = j;
4199 j = 0;
4200 if (readfds)
4201 for (i = 0; i < readfds->fd_count && j < count; i++, j++)
4202 release_sock_fd( readfds->fd_array[i], fds[j].fd );
4203 if (writefds)
4204 for (i = 0; i < writefds->fd_count && j < count; i++, j++)
4205 release_sock_fd( writefds->fd_array[i], fds[j].fd );
4206 if (exceptfds)
4207 for (i = 0; i < exceptfds->fd_count && j < count; i++, j++)
4208 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
4209 HeapFree( GetProcessHeap(), 0, fds );
4210 return NULL;
4213 /* release the file descriptor obtained in fd_sets_to_poll */
4214 /* must be called with the original fd_set arrays, before calling get_poll_results */
4215 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
4216 const WS_fd_set *exceptfds, struct pollfd *fds )
4218 unsigned int i, j = 0;
4220 if (readfds)
4222 for (i = 0; i < readfds->fd_count; i++, j++)
4223 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
4225 if (writefds)
4227 for (i = 0; i < writefds->fd_count; i++, j++)
4228 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
4230 if (exceptfds)
4232 for (i = 0; i < exceptfds->fd_count; i++, j++)
4233 if (fds[j].fd != -1)
4235 /* make sure we have a real error before releasing the fd */
4236 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
4237 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
4242 /* map the poll results back into the Windows fd sets */
4243 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
4244 const struct pollfd *fds )
4246 unsigned int i, j = 0, k, total = 0;
4248 if (readfds)
4250 for (i = k = 0; i < readfds->fd_count; i++, j++)
4251 if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
4252 readfds->fd_count = k;
4253 total += k;
4255 if (writefds)
4257 for (i = k = 0; i < writefds->fd_count; i++, j++)
4258 if ((fds[j].revents & POLLOUT) && !(fds[j].revents & POLLHUP))
4259 writefds->fd_array[k++] = writefds->fd_array[i];
4260 writefds->fd_count = k;
4261 total += k;
4263 if (exceptfds)
4265 for (i = k = 0; i < exceptfds->fd_count; i++, j++)
4266 if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
4267 exceptfds->fd_count = k;
4268 total += k;
4270 return total;
4274 /***********************************************************************
4275 * select (WS2_32.18)
4277 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
4278 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
4279 const struct WS_timeval* ws_timeout)
4281 struct pollfd *pollfds;
4282 struct timeval tv1, tv2;
4283 int torig = 0;
4284 int count, ret, timeout = -1;
4286 TRACE("read %p, write %p, excp %p timeout %p\n",
4287 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
4289 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )))
4290 return SOCKET_ERROR;
4292 if (ws_timeout)
4294 torig = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
4295 timeout = torig;
4296 gettimeofday( &tv1, 0 );
4299 while ((ret = poll( pollfds, count, timeout )) < 0)
4301 if (errno == EINTR)
4303 if (!ws_timeout) continue;
4304 gettimeofday( &tv2, 0 );
4306 tv2.tv_sec -= tv1.tv_sec;
4307 tv2.tv_usec -= tv1.tv_usec;
4308 if (tv2.tv_usec < 0)
4310 tv2.tv_usec += 1000000;
4311 tv2.tv_sec -= 1;
4314 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
4315 if (timeout <= 0) break;
4316 } else break;
4318 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
4320 if (ret == -1) SetLastError(wsaErrno());
4321 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
4322 HeapFree( GetProcessHeap(), 0, pollfds );
4323 return ret;
4326 /* helper to send completion messages for client-only i/o operation case */
4327 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
4328 ULONG Information )
4330 SERVER_START_REQ( add_fd_completion )
4332 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
4333 req->cvalue = CompletionValue;
4334 req->status = CompletionStatus;
4335 req->information = Information;
4336 wine_server_call( req );
4338 SERVER_END_REQ;
4342 /***********************************************************************
4343 * send (WS2_32.19)
4345 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
4347 DWORD n;
4348 WSABUF wsabuf;
4350 wsabuf.len = len;
4351 wsabuf.buf = (char*) buf;
4353 if ( WS2_sendto( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
4354 return SOCKET_ERROR;
4355 else
4356 return n;
4359 /***********************************************************************
4360 * WSASend (WS2_32.72)
4362 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4363 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4364 LPWSAOVERLAPPED lpOverlapped,
4365 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4367 return WS2_sendto( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
4368 NULL, 0, lpOverlapped, lpCompletionRoutine );
4371 /***********************************************************************
4372 * WSASendDisconnect (WS2_32.73)
4374 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
4376 return WS_shutdown( s, SD_SEND );
4380 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4381 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4382 const struct WS_sockaddr *to, int tolen,
4383 LPWSAOVERLAPPED lpOverlapped,
4384 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4386 unsigned int i, options;
4387 int n, fd, err;
4388 struct ws2_async *wsa = NULL;
4389 int totalLength = 0;
4390 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
4391 DWORD bytes_sent;
4392 BOOL is_blocking;
4394 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
4395 s, lpBuffers, dwBufferCount, dwFlags,
4396 to, tolen, lpOverlapped, lpCompletionRoutine);
4398 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
4399 TRACE( "fd=%d, options=%x\n", fd, options );
4401 if ( fd == -1 ) return SOCKET_ERROR;
4403 if (!lpOverlapped && !lpNumberOfBytesSent)
4405 err = WSAEFAULT;
4406 goto error;
4408 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
4410 err = WSAEFAULT;
4411 goto error;
4414 wsa->hSocket = SOCKET2HANDLE(s);
4415 wsa->addr = (struct WS_sockaddr *)to;
4416 wsa->addrlen.val = tolen;
4417 wsa->flags = dwFlags;
4418 wsa->lpFlags = &wsa->flags;
4419 wsa->control = NULL;
4420 wsa->n_iovecs = dwBufferCount;
4421 wsa->first_iovec = 0;
4422 for ( i = 0; i < dwBufferCount; i++ )
4424 wsa->iovec[i].iov_base = lpBuffers[i].buf;
4425 wsa->iovec[i].iov_len = lpBuffers[i].len;
4426 totalLength += lpBuffers[i].len;
4429 for (;;)
4431 n = WS2_send( fd, wsa );
4432 if (n != -1 || errno != EINTR) break;
4434 if (n == -1 && errno != EAGAIN)
4436 err = wsaErrno();
4437 goto error;
4440 if ((lpOverlapped || lpCompletionRoutine) &&
4441 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
4443 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
4445 wsa->user_overlapped = lpOverlapped;
4446 wsa->completion_func = lpCompletionRoutine;
4447 release_sock_fd( s, fd );
4449 if (n == -1 || n < totalLength)
4451 iosb->u.Status = STATUS_PENDING;
4452 iosb->Information = n == -1 ? 0 : n;
4454 SERVER_START_REQ( register_async )
4456 req->type = ASYNC_TYPE_WRITE;
4457 req->async.handle = wine_server_obj_handle( wsa->hSocket );
4458 req->async.callback = wine_server_client_ptr( WS2_async_send );
4459 req->async.iosb = wine_server_client_ptr( iosb );
4460 req->async.arg = wine_server_client_ptr( wsa );
4461 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
4462 req->async.cvalue = cvalue;
4463 err = wine_server_call( req );
4465 SERVER_END_REQ;
4467 /* Enable the event only after starting the async. The server will deliver it as soon as
4468 the async is done. */
4469 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
4471 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
4472 WSASetLastError( NtStatusToWSAError( err ));
4473 return SOCKET_ERROR;
4476 iosb->u.Status = STATUS_SUCCESS;
4477 iosb->Information = n;
4478 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = n;
4479 if (!wsa->completion_func)
4481 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
4482 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
4483 HeapFree( GetProcessHeap(), 0, wsa );
4485 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
4486 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
4487 WSASetLastError(0);
4488 return 0;
4491 if ((err = _is_blocking( s, &is_blocking )))
4493 err = NtStatusToWSAError( err );
4494 goto error;
4497 if ( is_blocking )
4499 /* On a blocking non-overlapped stream socket,
4500 * sending blocks until the entire buffer is sent. */
4501 DWORD timeout_start = GetTickCount();
4503 bytes_sent = n == -1 ? 0 : n;
4505 while (wsa->first_iovec < wsa->n_iovecs)
4507 struct pollfd pfd;
4508 int timeout = GET_SNDTIMEO(fd);
4510 if (timeout != -1)
4512 timeout -= GetTickCount() - timeout_start;
4513 if (timeout < 0) timeout = 0;
4516 pfd.fd = fd;
4517 pfd.events = POLLOUT;
4519 if (!timeout || !poll( &pfd, 1, timeout ))
4521 err = WSAETIMEDOUT;
4522 goto error; /* msdn says a timeout in send is fatal */
4525 n = WS2_send( fd, wsa );
4526 if (n == -1 && errno != EAGAIN && errno != EINTR)
4528 err = wsaErrno();
4529 goto error;
4532 if (n >= 0)
4533 bytes_sent += n;
4536 else /* non-blocking */
4538 if (n < totalLength)
4539 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
4540 if (n == -1)
4542 err = WSAEWOULDBLOCK;
4543 goto error;
4545 bytes_sent = n;
4548 TRACE(" -> %i bytes\n", bytes_sent);
4550 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = bytes_sent;
4551 HeapFree( GetProcessHeap(), 0, wsa );
4552 release_sock_fd( s, fd );
4553 WSASetLastError(0);
4554 return 0;
4556 error:
4557 HeapFree( GetProcessHeap(), 0, wsa );
4558 release_sock_fd( s, fd );
4559 WARN(" -> ERROR %d\n", err);
4560 WSASetLastError(err);
4561 return SOCKET_ERROR;
4564 /***********************************************************************
4565 * WSASendTo (WS2_32.74)
4567 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4568 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4569 const struct WS_sockaddr *to, int tolen,
4570 LPWSAOVERLAPPED lpOverlapped,
4571 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4573 return WS2_sendto( s, lpBuffers, dwBufferCount,
4574 lpNumberOfBytesSent, dwFlags,
4575 to, tolen,
4576 lpOverlapped, lpCompletionRoutine );
4579 /***********************************************************************
4580 * sendto (WS2_32.20)
4582 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
4583 const struct WS_sockaddr *to, int tolen)
4585 DWORD n;
4586 WSABUF wsabuf;
4588 wsabuf.len = len;
4589 wsabuf.buf = (char*) buf;
4591 if ( WS2_sendto(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
4592 return SOCKET_ERROR;
4593 else
4594 return n;
4597 /***********************************************************************
4598 * setsockopt (WS2_32.21)
4600 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
4601 const char *optval, int optlen)
4603 int fd;
4604 int woptval;
4605 struct linger linger;
4606 struct timeval tval;
4608 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
4609 s, level, optname, optval, optlen);
4611 /* some broken apps pass the value directly instead of a pointer to it */
4612 if(optlen && IS_INTRESOURCE(optval))
4614 SetLastError(WSAEFAULT);
4615 return SOCKET_ERROR;
4618 switch(level)
4620 case WS_SOL_SOCKET:
4621 switch(optname)
4623 /* Some options need some conversion before they can be sent to
4624 * setsockopt. The conversions are done here, then they will fall though
4625 * to the general case. Special options that are not passed to
4626 * setsockopt follow below that.*/
4628 case WS_SO_DONTLINGER:
4629 if (!optval)
4631 SetLastError(WSAEFAULT);
4632 return SOCKET_ERROR;
4634 linger.l_onoff = *(const int*)optval == 0;
4635 linger.l_linger = 0;
4636 level = SOL_SOCKET;
4637 optname = SO_LINGER;
4638 optval = (char*)&linger;
4639 optlen = sizeof(struct linger);
4640 break;
4642 case WS_SO_LINGER:
4643 if (!optval)
4645 SetLastError(WSAEFAULT);
4646 return SOCKET_ERROR;
4648 linger.l_onoff = ((LINGER*)optval)->l_onoff;
4649 linger.l_linger = ((LINGER*)optval)->l_linger;
4650 level = SOL_SOCKET;
4651 optname = SO_LINGER;
4652 optval = (char*)&linger;
4653 optlen = sizeof(struct linger);
4654 break;
4656 case WS_SO_RCVBUF:
4657 if (*(const int*)optval < 2048)
4659 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
4660 return 0;
4662 /* Fall through */
4664 /* The options listed here don't need any special handling. Thanks to
4665 * the conversion happening above, options from there will fall through
4666 * to this, too.*/
4667 case WS_SO_ACCEPTCONN:
4668 case WS_SO_BROADCAST:
4669 case WS_SO_ERROR:
4670 case WS_SO_KEEPALIVE:
4671 case WS_SO_OOBINLINE:
4672 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
4673 * however, using it the BSD way fixes bug 8513 and seems to be what
4674 * most programmers assume, anyway */
4675 case WS_SO_REUSEADDR:
4676 case WS_SO_SNDBUF:
4677 case WS_SO_TYPE:
4678 convert_sockopt(&level, &optname);
4679 break;
4681 /* SO_DEBUG is a privileged operation, ignore it. */
4682 case WS_SO_DEBUG:
4683 TRACE("Ignoring SO_DEBUG\n");
4684 return 0;
4686 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
4687 * socket. According to MSDN, this option is silently ignored.*/
4688 case WS_SO_DONTROUTE:
4689 TRACE("Ignoring SO_DONTROUTE\n");
4690 return 0;
4692 /* Stops two sockets from being bound to the same port. Always happens
4693 * on unix systems, so just drop it. */
4694 case WS_SO_EXCLUSIVEADDRUSE:
4695 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
4696 return 0;
4698 /* After a ConnectEx call succeeds, the socket can't be used with half of the
4699 * normal winsock functions on windows. We don't have that problem. */
4700 case WS_SO_UPDATE_CONNECT_CONTEXT:
4701 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
4702 return 0;
4704 /* After a AcceptEx call succeeds, the socket can't be used with half of the
4705 * normal winsock functions on windows. We don't have that problem. */
4706 case WS_SO_UPDATE_ACCEPT_CONTEXT:
4707 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
4708 return 0;
4710 /* SO_OPENTYPE does not require a valid socket handle. */
4711 case WS_SO_OPENTYPE:
4712 if (!optlen || optlen < sizeof(int) || !optval)
4714 SetLastError(WSAEFAULT);
4715 return SOCKET_ERROR;
4717 get_per_thread_data()->opentype = *(const int *)optval;
4718 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
4719 return 0;
4721 #ifdef SO_RCVTIMEO
4722 case WS_SO_RCVTIMEO:
4723 #endif
4724 #ifdef SO_SNDTIMEO
4725 case WS_SO_SNDTIMEO:
4726 #endif
4727 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
4728 if (optval && optlen == sizeof(UINT32)) {
4729 /* WinSock passes milliseconds instead of struct timeval */
4730 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
4731 tval.tv_sec = *(const UINT32*)optval / 1000;
4732 /* min of 500 milliseconds */
4733 if (tval.tv_sec == 0 && tval.tv_usec && tval.tv_usec < 500000)
4734 tval.tv_usec = 500000;
4735 optlen = sizeof(struct timeval);
4736 optval = (char*)&tval;
4737 } else if (optlen == sizeof(struct timeval)) {
4738 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
4739 } else {
4740 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
4741 return 0;
4743 convert_sockopt(&level, &optname);
4744 break;
4745 #endif
4747 default:
4748 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
4749 SetLastError(WSAENOPROTOOPT);
4750 return SOCKET_ERROR;
4752 break; /* case WS_SOL_SOCKET */
4754 #ifdef HAS_IPX
4755 case WS_NSPROTO_IPX:
4756 switch(optname)
4758 case IPX_PTYPE:
4759 fd = get_sock_fd( s, 0, NULL );
4760 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", *(const int*)optval, fd);
4762 /* We try to set the ipx type on ipx socket level. */
4763 #ifdef SOL_IPX
4764 if(setsockopt(fd, SOL_IPX, IPX_TYPE, optval, optlen) == -1)
4766 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
4767 release_sock_fd( s, fd );
4768 return SOCKET_ERROR;
4770 #else
4772 struct ipx val;
4773 /* Should we retrieve val using a getsockopt call and then
4774 * set the modified one? */
4775 val.ipx_pt = *optval;
4776 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
4778 #endif
4779 release_sock_fd( s, fd );
4780 return 0;
4782 case IPX_FILTERPTYPE:
4783 /* Sets the receive filter packet type, at the moment we don't support it */
4784 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
4785 /* Returning 0 is better for now than returning a SOCKET_ERROR */
4786 return 0;
4788 default:
4789 FIXME("opt_name:%x\n", optname);
4790 return SOCKET_ERROR;
4792 break; /* case WS_NSPROTO_IPX */
4793 #endif
4795 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
4796 case WS_IPPROTO_TCP:
4797 switch(optname)
4799 case WS_TCP_NODELAY:
4800 convert_sockopt(&level, &optname);
4801 break;
4802 default:
4803 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
4804 return SOCKET_ERROR;
4806 break;
4808 case WS_IPPROTO_IP:
4809 switch(optname)
4811 case WS_IP_ADD_MEMBERSHIP:
4812 case WS_IP_DROP_MEMBERSHIP:
4813 #ifdef IP_HDRINCL
4814 case WS_IP_HDRINCL:
4815 #endif
4816 case WS_IP_MULTICAST_IF:
4817 case WS_IP_MULTICAST_LOOP:
4818 case WS_IP_MULTICAST_TTL:
4819 case WS_IP_OPTIONS:
4820 #ifdef IP_PKTINFO
4821 case WS_IP_PKTINFO:
4822 #endif
4823 case WS_IP_TOS:
4824 case WS_IP_TTL:
4825 #ifdef IP_UNICAST_IF
4826 case WS_IP_UNICAST_IF:
4827 #endif
4828 convert_sockopt(&level, &optname);
4829 break;
4830 case WS_IP_DONTFRAGMENT:
4831 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
4832 return 0;
4833 default:
4834 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
4835 return SOCKET_ERROR;
4837 break;
4839 case WS_IPPROTO_IPV6:
4840 switch(optname)
4842 #ifdef IPV6_ADD_MEMBERSHIP
4843 case WS_IPV6_ADD_MEMBERSHIP:
4844 #endif
4845 #ifdef IPV6_DROP_MEMBERSHIP
4846 case WS_IPV6_DROP_MEMBERSHIP:
4847 #endif
4848 case WS_IPV6_MULTICAST_IF:
4849 case WS_IPV6_MULTICAST_HOPS:
4850 case WS_IPV6_MULTICAST_LOOP:
4851 case WS_IPV6_UNICAST_HOPS:
4852 case WS_IPV6_V6ONLY:
4853 #ifdef IPV6_UNICAST_IF
4854 case WS_IPV6_UNICAST_IF:
4855 #endif
4856 convert_sockopt(&level, &optname);
4857 break;
4858 case WS_IPV6_DONTFRAG:
4859 FIXME("IPV6_DONTFRAG is silently ignored!\n");
4860 return 0;
4861 case WS_IPV6_PROTECTION_LEVEL:
4862 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
4863 return 0;
4864 default:
4865 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
4866 return SOCKET_ERROR;
4868 break;
4870 default:
4871 WARN("Unknown level: 0x%08x\n", level);
4872 SetLastError(WSAEINVAL);
4873 return SOCKET_ERROR;
4874 } /* end switch(level) */
4876 /* avoid endianness issues if argument is a 16-bit int */
4877 if (optval && optlen < sizeof(int))
4879 woptval= *((const INT16 *) optval);
4880 optval= (char*) &woptval;
4881 optlen=sizeof(int);
4883 fd = get_sock_fd( s, 0, NULL );
4884 if (fd == -1) return SOCKET_ERROR;
4886 if (setsockopt(fd, level, optname, optval, optlen) == 0)
4888 #ifdef __APPLE__
4889 if (level == SOL_SOCKET && optname == SO_REUSEADDR &&
4890 setsockopt(fd, level, SO_REUSEPORT, optval, optlen) != 0)
4892 SetLastError(wsaErrno());
4893 release_sock_fd( s, fd );
4894 return SOCKET_ERROR;
4896 #endif
4897 release_sock_fd( s, fd );
4898 return 0;
4900 TRACE("Setting socket error, %d\n", wsaErrno());
4901 SetLastError(wsaErrno());
4902 release_sock_fd( s, fd );
4904 return SOCKET_ERROR;
4907 /***********************************************************************
4908 * shutdown (WS2_32.22)
4910 int WINAPI WS_shutdown(SOCKET s, int how)
4912 int fd, err = WSAENOTSOCK;
4913 unsigned int options, clear_flags = 0;
4915 fd = get_sock_fd( s, 0, &options );
4916 TRACE("socket %04lx, how %i %x\n", s, how, options );
4918 if (fd == -1)
4919 return SOCKET_ERROR;
4921 switch( how )
4923 case 0: /* drop receives */
4924 clear_flags |= FD_READ;
4925 break;
4926 case 1: /* drop sends */
4927 clear_flags |= FD_WRITE;
4928 break;
4929 case 2: /* drop all */
4930 clear_flags |= FD_READ|FD_WRITE;
4931 /*fall through */
4932 default:
4933 clear_flags |= FD_WINE_LISTENING;
4936 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
4938 switch ( how )
4940 case SD_RECEIVE:
4941 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
4942 break;
4943 case SD_SEND:
4944 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
4945 break;
4946 case SD_BOTH:
4947 default:
4948 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
4949 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
4950 break;
4952 if (err) goto error;
4954 else /* non-overlapped mode */
4956 if ( shutdown( fd, how ) )
4958 err = wsaErrno();
4959 goto error;
4963 release_sock_fd( s, fd );
4964 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
4965 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
4966 return 0;
4968 error:
4969 release_sock_fd( s, fd );
4970 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
4971 WSASetLastError( err );
4972 return SOCKET_ERROR;
4975 /***********************************************************************
4976 * socket (WS2_32.23)
4978 SOCKET WINAPI WS_socket(int af, int type, int protocol)
4980 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
4982 return WSASocketA( af, type, protocol, NULL, 0,
4983 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
4987 /***********************************************************************
4988 * gethostbyaddr (WS2_32.51)
4990 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
4992 struct WS_hostent *retval = NULL;
4993 struct hostent* host;
4995 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4996 char *extrabuf;
4997 int ebufsize=1024;
4998 struct hostent hostentry;
4999 int locerr=ENOBUFS;
5000 host = NULL;
5001 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
5002 while(extrabuf) {
5003 int res = gethostbyaddr_r(addr, len, type,
5004 &hostentry, extrabuf, ebufsize, &host, &locerr);
5005 if( res != ERANGE) break;
5006 ebufsize *=2;
5007 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
5009 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
5010 #else
5011 EnterCriticalSection( &csWSgetXXXbyYYY );
5012 host = gethostbyaddr(addr, len, type);
5013 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
5014 #endif
5015 if( host != NULL ) retval = WS_dup_he(host);
5016 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5017 HeapFree(GetProcessHeap(),0,extrabuf);
5018 #else
5019 LeaveCriticalSection( &csWSgetXXXbyYYY );
5020 #endif
5021 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
5022 return retval;
5025 /***********************************************************************
5026 * WS_get_local_ips (INTERNAL)
5028 * Returns the list of local IP addresses by going through the network
5029 * adapters and using the local routing table to sort the addresses
5030 * from highest routing priority to lowest routing priority. This
5031 * functionality is inferred from the description for obtaining local
5032 * IP addresses given in the Knowledge Base Article Q160215.
5034 * Please note that the returned hostent is only freed when the thread
5035 * closes and is replaced if another hostent is requested.
5037 static struct WS_hostent* WS_get_local_ips( char *hostname )
5039 int last_metric, numroutes = 0, i, j;
5040 DWORD n;
5041 PIP_ADAPTER_INFO adapters = NULL, k;
5042 struct WS_hostent *hostlist = NULL;
5043 PMIB_IPFORWARDTABLE routes = NULL;
5044 struct route *route_addrs = NULL;
5045 DWORD adap_size, route_size;
5047 /* Obtain the size of the adapter list and routing table, also allocate memory */
5048 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
5049 return NULL;
5050 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
5051 return NULL;
5052 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
5053 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
5054 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
5055 if (adapters == NULL || routes == NULL || route_addrs == NULL)
5056 goto cleanup;
5057 /* Obtain the adapter list and the full routing table */
5058 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
5059 goto cleanup;
5060 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
5061 goto cleanup;
5062 /* Store the interface associated with each route */
5063 for (n = 0; n < routes->dwNumEntries; n++)
5065 IF_INDEX ifindex;
5066 DWORD ifmetric;
5067 BOOL exists = FALSE;
5069 if (routes->table[n].u1.ForwardType != MIB_IPROUTE_TYPE_DIRECT)
5070 continue;
5071 ifindex = routes->table[n].dwForwardIfIndex;
5072 ifmetric = routes->table[n].dwForwardMetric1;
5073 /* Only store the lowest valued metric for an interface */
5074 for (j = 0; j < numroutes; j++)
5076 if (route_addrs[j].interface == ifindex)
5078 if (route_addrs[j].metric > ifmetric)
5079 route_addrs[j].metric = ifmetric;
5080 exists = TRUE;
5083 if (exists)
5084 continue;
5085 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
5086 if (route_addrs == NULL)
5087 goto cleanup; /* Memory allocation error, fail gracefully */
5088 route_addrs[numroutes].interface = ifindex;
5089 route_addrs[numroutes].metric = ifmetric;
5090 /* If no IP is found in the next step (for whatever reason)
5091 * then fall back to the magic loopback address.
5093 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
5094 numroutes++;
5096 if (numroutes == 0)
5097 goto cleanup; /* No routes, fall back to the Magic IP */
5098 /* Find the IP address associated with each found interface */
5099 for (i = 0; i < numroutes; i++)
5101 for (k = adapters; k != NULL; k = k->Next)
5103 char *ip = k->IpAddressList.IpAddress.String;
5105 if (route_addrs[i].interface == k->Index)
5106 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
5109 /* Allocate a hostent and enough memory for all the IPs,
5110 * including the NULL at the end of the list.
5112 hostlist = WS_create_he(hostname, 1, 0, numroutes+1, sizeof(struct in_addr));
5113 if (hostlist == NULL)
5114 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
5115 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
5116 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
5117 hostlist->h_addrtype = AF_INET;
5118 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
5119 /* Reorder the entries when placing them in the host list, Windows expects
5120 * the IP list in order from highest priority to lowest (the critical thing
5121 * is that most applications expect the first IP to be the default route).
5123 last_metric = -1;
5124 for (i = 0; i < numroutes; i++)
5126 struct in_addr addr;
5127 int metric = 0xFFFF;
5129 memcpy(&addr, magic_loopback_addr, 4);
5130 for (j = 0; j < numroutes; j++)
5132 int this_metric = route_addrs[j].metric;
5134 if (this_metric > last_metric && this_metric < metric)
5136 addr = route_addrs[j].addr;
5137 metric = this_metric;
5140 last_metric = metric;
5141 (*(struct in_addr *) hostlist->h_addr_list[i]) = addr;
5144 /* Cleanup all allocated memory except the address list,
5145 * the address list is used by the calling app.
5147 cleanup:
5148 HeapFree(GetProcessHeap(), 0, route_addrs);
5149 HeapFree(GetProcessHeap(), 0, adapters);
5150 HeapFree(GetProcessHeap(), 0, routes);
5151 return hostlist;
5154 /***********************************************************************
5155 * gethostbyname (WS2_32.52)
5157 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
5159 struct WS_hostent *retval = NULL;
5160 struct hostent* host;
5161 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5162 char *extrabuf;
5163 int ebufsize=1024;
5164 struct hostent hostentry;
5165 int locerr = ENOBUFS;
5166 #endif
5167 char hostname[100];
5168 if(!num_startup) {
5169 SetLastError(WSANOTINITIALISED);
5170 return NULL;
5172 if( gethostname( hostname, 100) == -1) {
5173 SetLastError( WSAENOBUFS); /* appropriate ? */
5174 return retval;
5176 if( !name || !name[0]) {
5177 name = hostname;
5179 /* If the hostname of the local machine is requested then return the
5180 * complete list of local IP addresses */
5181 if(strcmp(name, hostname) == 0)
5182 retval = WS_get_local_ips(hostname);
5183 /* If any other hostname was requested (or the routing table lookup failed)
5184 * then return the IP found by the host OS */
5185 if(retval == NULL)
5187 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5188 host = NULL;
5189 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
5190 while(extrabuf) {
5191 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
5192 if( res != ERANGE) break;
5193 ebufsize *=2;
5194 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
5196 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
5197 #else
5198 EnterCriticalSection( &csWSgetXXXbyYYY );
5199 host = gethostbyname(name);
5200 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
5201 #endif
5202 if (host) retval = WS_dup_he(host);
5203 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5204 HeapFree(GetProcessHeap(),0,extrabuf);
5205 #else
5206 LeaveCriticalSection( &csWSgetXXXbyYYY );
5207 #endif
5209 if (retval && retval->h_addr_list[0][0] == 127 &&
5210 strcmp(name, "localhost") != 0)
5212 /* hostname != "localhost" but has loopback address. replace by our
5213 * special address.*/
5214 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
5216 TRACE( "%s ret %p\n", debugstr_a(name), retval );
5217 return retval;
5221 /***********************************************************************
5222 * getprotobyname (WS2_32.53)
5224 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
5226 struct WS_protoent* retval = NULL;
5227 #ifdef HAVE_GETPROTOBYNAME
5228 struct protoent* proto;
5229 EnterCriticalSection( &csWSgetXXXbyYYY );
5230 if( (proto = getprotobyname(name)) != NULL )
5232 retval = WS_dup_pe(proto);
5234 else {
5235 MESSAGE("protocol %s not found; You might want to add "
5236 "this to /etc/protocols\n", debugstr_a(name) );
5237 SetLastError(WSANO_DATA);
5239 LeaveCriticalSection( &csWSgetXXXbyYYY );
5240 #endif
5241 TRACE( "%s ret %p\n", debugstr_a(name), retval );
5242 return retval;
5246 /***********************************************************************
5247 * getprotobynumber (WS2_32.54)
5249 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
5251 struct WS_protoent* retval = NULL;
5252 #ifdef HAVE_GETPROTOBYNUMBER
5253 struct protoent* proto;
5254 EnterCriticalSection( &csWSgetXXXbyYYY );
5255 if( (proto = getprotobynumber(number)) != NULL )
5257 retval = WS_dup_pe(proto);
5259 else {
5260 MESSAGE("protocol number %d not found; You might want to add "
5261 "this to /etc/protocols\n", number );
5262 SetLastError(WSANO_DATA);
5264 LeaveCriticalSection( &csWSgetXXXbyYYY );
5265 #endif
5266 TRACE("%i ret %p\n", number, retval);
5267 return retval;
5271 /***********************************************************************
5272 * getservbyname (WS2_32.55)
5274 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
5276 struct WS_servent* retval = NULL;
5277 struct servent* serv;
5278 char *name_str;
5279 char *proto_str = NULL;
5281 if (!(name_str = strdup_lower(name))) return NULL;
5283 if (proto && *proto)
5285 if (!(proto_str = strdup_lower(proto)))
5287 HeapFree( GetProcessHeap(), 0, name_str );
5288 return NULL;
5292 EnterCriticalSection( &csWSgetXXXbyYYY );
5293 serv = getservbyname(name_str, proto_str);
5294 if( serv != NULL )
5296 retval = WS_dup_se(serv);
5298 else SetLastError(WSANO_DATA);
5299 LeaveCriticalSection( &csWSgetXXXbyYYY );
5300 HeapFree( GetProcessHeap(), 0, proto_str );
5301 HeapFree( GetProcessHeap(), 0, name_str );
5302 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
5303 return retval;
5306 /***********************************************************************
5307 * freeaddrinfo (WS2_32.@)
5309 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
5311 while (res) {
5312 struct WS_addrinfo *next;
5314 HeapFree(GetProcessHeap(),0,res->ai_canonname);
5315 HeapFree(GetProcessHeap(),0,res->ai_addr);
5316 next = res->ai_next;
5317 HeapFree(GetProcessHeap(),0,res);
5318 res = next;
5322 /* helper functions for getaddrinfo()/getnameinfo() */
5323 static int convert_aiflag_w2u(int winflags) {
5324 unsigned int i;
5325 int unixflags = 0;
5327 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
5328 if (ws_aiflag_map[i][0] & winflags) {
5329 unixflags |= ws_aiflag_map[i][1];
5330 winflags &= ~ws_aiflag_map[i][0];
5332 if (winflags)
5333 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
5334 return unixflags;
5337 static int convert_niflag_w2u(int winflags) {
5338 unsigned int i;
5339 int unixflags = 0;
5341 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
5342 if (ws_niflag_map[i][0] & winflags) {
5343 unixflags |= ws_niflag_map[i][1];
5344 winflags &= ~ws_niflag_map[i][0];
5346 if (winflags)
5347 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
5348 return unixflags;
5351 static int convert_aiflag_u2w(int unixflags) {
5352 unsigned int i;
5353 int winflags = 0;
5355 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
5356 if (ws_aiflag_map[i][1] & unixflags) {
5357 winflags |= ws_aiflag_map[i][0];
5358 unixflags &= ~ws_aiflag_map[i][1];
5360 if (unixflags) /* will warn usually */
5361 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
5362 return winflags;
5365 static int convert_eai_u2w(int unixret) {
5366 int i;
5368 if (!unixret) return 0;
5370 for (i=0;ws_eai_map[i][0];i++)
5371 if (ws_eai_map[i][1] == unixret)
5372 return ws_eai_map[i][0];
5374 if (unixret == EAI_SYSTEM)
5375 /* There are broken versions of glibc which return EAI_SYSTEM
5376 * and set errno to 0 instead of returning EAI_NONAME.
5378 return errno ? sock_get_error( errno ) : WS_EAI_NONAME;
5380 FIXME("Unhandled unix EAI_xxx ret %d\n", unixret);
5381 return unixret;
5384 static char *get_hostname(void)
5386 char *ret;
5387 DWORD size = 0;
5389 GetComputerNameExA( ComputerNamePhysicalDnsHostname, NULL, &size );
5390 if (GetLastError() != ERROR_MORE_DATA) return NULL;
5391 if (!(ret = HeapAlloc( GetProcessHeap(), 0, size ))) return NULL;
5392 if (!GetComputerNameExA( ComputerNamePhysicalDnsHostname, ret, &size ))
5394 HeapFree( GetProcessHeap(), 0, ret );
5395 return NULL;
5397 return ret;
5400 /***********************************************************************
5401 * getaddrinfo (WS2_32.@)
5403 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
5405 #ifdef HAVE_GETADDRINFO
5406 struct addrinfo *unixaires = NULL;
5407 int result;
5408 struct addrinfo unixhints, *punixhints = NULL;
5409 char *hostname = NULL;
5410 const char *node;
5412 *res = NULL;
5413 if (!nodename && !servname) return WSAHOST_NOT_FOUND;
5415 if (!nodename)
5416 node = NULL;
5417 else if (!nodename[0])
5419 node = hostname = get_hostname();
5420 if (!node) return WSA_NOT_ENOUGH_MEMORY;
5422 else
5423 node = nodename;
5425 if (hints) {
5426 punixhints = &unixhints;
5428 memset(&unixhints, 0, sizeof(unixhints));
5429 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
5430 if (hints->ai_family == 0) /* wildcard, specific to getaddrinfo() */
5431 punixhints->ai_family = 0;
5432 else
5433 punixhints->ai_family = convert_af_w2u(hints->ai_family);
5434 if (hints->ai_socktype == 0) /* wildcard, specific to getaddrinfo() */
5435 punixhints->ai_socktype = 0;
5436 else
5437 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
5438 if (hints->ai_protocol == 0) /* wildcard, specific to getaddrinfo() */
5439 punixhints->ai_protocol = 0;
5440 else
5441 punixhints->ai_protocol = convert_proto_w2u(hints->ai_protocol);
5444 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
5445 result = getaddrinfo(node, servname, punixhints, &unixaires);
5447 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
5448 HeapFree(GetProcessHeap(), 0, hostname);
5450 if (!result) {
5451 struct addrinfo *xuai = unixaires;
5452 struct WS_addrinfo **xai = res;
5454 *xai = NULL;
5455 while (xuai) {
5456 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
5457 SIZE_T len;
5459 if (!ai)
5460 goto outofmem;
5462 *xai = ai;xai = &ai->ai_next;
5463 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
5464 ai->ai_family = convert_af_u2w(xuai->ai_family);
5465 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
5466 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
5467 if (xuai->ai_canonname) {
5468 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
5469 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
5470 if (!ai->ai_canonname)
5471 goto outofmem;
5472 strcpy(ai->ai_canonname,xuai->ai_canonname);
5474 len = xuai->ai_addrlen;
5475 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
5476 if (!ai->ai_addr)
5477 goto outofmem;
5478 ai->ai_addrlen = len;
5479 do {
5480 int winlen = ai->ai_addrlen;
5482 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
5483 ai->ai_addrlen = winlen;
5484 break;
5486 len = 2*len;
5487 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
5488 if (!ai->ai_addr)
5489 goto outofmem;
5490 ai->ai_addrlen = len;
5491 } while (1);
5492 xuai = xuai->ai_next;
5494 freeaddrinfo(unixaires);
5496 if (TRACE_ON(winsock))
5498 struct WS_addrinfo *ai = *res;
5499 while (ai)
5501 TRACE("=> %p, flags %#x, family %d, type %d, protocol %d, len %ld, name %s, addr %s\n",
5502 ai, ai->ai_flags, ai->ai_family, ai->ai_socktype, ai->ai_protocol, ai->ai_addrlen,
5503 ai->ai_canonname, debugstr_sockaddr(ai->ai_addr));
5504 ai = ai->ai_next;
5507 } else
5508 result = convert_eai_u2w(result);
5510 return result;
5512 outofmem:
5513 if (*res) WS_freeaddrinfo(*res);
5514 if (unixaires) freeaddrinfo(unixaires);
5515 return WSA_NOT_ENOUGH_MEMORY;
5516 #else
5517 FIXME("getaddrinfo() failed, not found during buildtime.\n");
5518 return EAI_FAIL;
5519 #endif
5522 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
5524 struct WS_addrinfoW *ret;
5526 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
5527 ret->ai_flags = ai->ai_flags;
5528 ret->ai_family = ai->ai_family;
5529 ret->ai_socktype = ai->ai_socktype;
5530 ret->ai_protocol = ai->ai_protocol;
5531 ret->ai_addrlen = ai->ai_addrlen;
5532 ret->ai_canonname = NULL;
5533 ret->ai_addr = NULL;
5534 ret->ai_next = NULL;
5535 if (ai->ai_canonname)
5537 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
5538 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
5540 HeapFree(GetProcessHeap(), 0, ret);
5541 return NULL;
5543 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
5545 if (ai->ai_addr)
5547 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
5549 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
5550 HeapFree(GetProcessHeap(), 0, ret);
5551 return NULL;
5553 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
5555 return ret;
5558 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
5560 struct WS_addrinfoW *ret, *infoW;
5562 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
5563 while (info->ai_next)
5565 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
5567 FreeAddrInfoW(ret);
5568 return NULL;
5570 infoW = infoW->ai_next;
5571 info = info->ai_next;
5573 return ret;
5576 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
5578 struct WS_addrinfo *ret;
5580 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
5581 ret->ai_flags = ai->ai_flags;
5582 ret->ai_family = ai->ai_family;
5583 ret->ai_socktype = ai->ai_socktype;
5584 ret->ai_protocol = ai->ai_protocol;
5585 ret->ai_addrlen = ai->ai_addrlen;
5586 ret->ai_canonname = NULL;
5587 ret->ai_addr = NULL;
5588 ret->ai_next = NULL;
5589 if (ai->ai_canonname)
5591 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
5592 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
5594 HeapFree(GetProcessHeap(), 0, ret);
5595 return NULL;
5597 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
5599 if (ai->ai_addr)
5601 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
5603 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
5604 HeapFree(GetProcessHeap(), 0, ret);
5605 return NULL;
5607 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
5609 return ret;
5612 /***********************************************************************
5613 * GetAddrInfoW (WS2_32.@)
5615 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
5617 int ret, len;
5618 char *nodenameA = NULL, *servnameA = NULL;
5619 struct WS_addrinfo *resA, *hintsA = NULL;
5621 *res = NULL;
5622 if (nodename)
5624 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
5625 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
5626 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
5628 if (servname)
5630 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
5631 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
5633 HeapFree(GetProcessHeap(), 0, nodenameA);
5634 return EAI_MEMORY;
5636 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
5639 if (hints) hintsA = addrinfo_WtoA(hints);
5640 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
5641 WS_freeaddrinfo(hintsA);
5643 if (!ret)
5645 *res = addrinfo_list_AtoW(resA);
5646 WS_freeaddrinfo(resA);
5649 HeapFree(GetProcessHeap(), 0, nodenameA);
5650 HeapFree(GetProcessHeap(), 0, servnameA);
5651 return ret;
5654 /***********************************************************************
5655 * FreeAddrInfoW (WS2_32.@)
5657 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
5659 while (ai)
5661 ADDRINFOW *next;
5662 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
5663 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
5664 next = ai->ai_next;
5665 HeapFree(GetProcessHeap(), 0, ai);
5666 ai = next;
5670 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
5671 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
5673 #ifdef HAVE_GETNAMEINFO
5674 int ret;
5675 union generic_unix_sockaddr sa_u;
5676 unsigned int size;
5678 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
5679 serv, servlen, flags);
5681 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
5682 if (!size)
5684 WSASetLastError(WSAEFAULT);
5685 return WSA_NOT_ENOUGH_MEMORY;
5687 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
5688 return convert_eai_u2w(ret);
5689 #else
5690 FIXME("getnameinfo() failed, not found during buildtime.\n");
5691 return EAI_FAIL;
5692 #endif
5695 int WINAPI GetNameInfoW(const SOCKADDR *sa, WS_socklen_t salen, PWCHAR host,
5696 DWORD hostlen, PWCHAR serv, DWORD servlen, INT flags)
5698 int ret;
5699 char *hostA = NULL, *servA = NULL;
5701 if (host && (!(hostA = HeapAlloc(GetProcessHeap(), 0, hostlen)))) return EAI_MEMORY;
5702 if (serv && (!(servA = HeapAlloc(GetProcessHeap(), 0, servlen))))
5704 HeapFree(GetProcessHeap(), 0, hostA);
5705 return EAI_MEMORY;
5708 ret = WS_getnameinfo(sa, salen, hostA, hostlen, servA, servlen, flags);
5709 if (!ret)
5711 if (host) MultiByteToWideChar(CP_ACP, 0, hostA, -1, host, hostlen);
5712 if (serv) MultiByteToWideChar(CP_ACP, 0, servA, -1, serv, servlen);
5715 HeapFree(GetProcessHeap(), 0, hostA);
5716 HeapFree(GetProcessHeap(), 0, servA);
5717 return ret;
5720 /***********************************************************************
5721 * getservbyport (WS2_32.56)
5723 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
5725 struct WS_servent* retval = NULL;
5726 #ifdef HAVE_GETSERVBYPORT
5727 struct servent* serv;
5728 char *proto_str = NULL;
5730 if (proto && *proto)
5732 if (!(proto_str = strdup_lower(proto))) return NULL;
5734 EnterCriticalSection( &csWSgetXXXbyYYY );
5735 if( (serv = getservbyport(port, proto_str)) != NULL ) {
5736 retval = WS_dup_se(serv);
5738 else SetLastError(WSANO_DATA);
5739 LeaveCriticalSection( &csWSgetXXXbyYYY );
5740 HeapFree( GetProcessHeap(), 0, proto_str );
5741 #endif
5742 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
5743 return retval;
5747 /***********************************************************************
5748 * gethostname (WS2_32.57)
5750 int WINAPI WS_gethostname(char *name, int namelen)
5752 TRACE("name %p, len %d\n", name, namelen);
5754 if (gethostname(name, namelen) == 0)
5756 TRACE("<- '%s'\n", name);
5757 return 0;
5759 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
5760 TRACE("<- ERROR !\n");
5761 return SOCKET_ERROR;
5765 /* ------------------------------------- Windows sockets extensions -- *
5767 * ------------------------------------------------------------------- */
5769 /***********************************************************************
5770 * WSAEnumNetworkEvents (WS2_32.36)
5772 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
5774 int ret;
5775 int i;
5776 int errors[FD_MAX_EVENTS];
5778 TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
5780 SERVER_START_REQ( get_socket_event )
5782 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5783 req->service = TRUE;
5784 req->c_event = wine_server_obj_handle( hEvent );
5785 wine_server_set_reply( req, errors, sizeof(errors) );
5786 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
5788 SERVER_END_REQ;
5789 if (!ret)
5791 for (i = 0; i < FD_MAX_EVENTS; i++)
5792 lpEvent->iErrorCode[i] = NtStatusToWSAError(errors[i]);
5793 return 0;
5795 SetLastError(WSAEINVAL);
5796 return SOCKET_ERROR;
5799 /***********************************************************************
5800 * WSAEventSelect (WS2_32.39)
5802 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
5804 int ret;
5806 TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
5808 SERVER_START_REQ( set_socket_event )
5810 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5811 req->mask = lEvent;
5812 req->event = wine_server_obj_handle( hEvent );
5813 req->window = 0;
5814 req->msg = 0;
5815 ret = wine_server_call( req );
5817 SERVER_END_REQ;
5818 if (!ret) return 0;
5819 SetLastError(WSAEINVAL);
5820 return SOCKET_ERROR;
5823 /**********************************************************************
5824 * WSAGetOverlappedResult (WS2_32.40)
5826 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
5827 LPDWORD lpcbTransfer, BOOL fWait,
5828 LPDWORD lpdwFlags )
5830 NTSTATUS status;
5832 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
5833 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
5835 if ( lpOverlapped == NULL )
5837 ERR( "Invalid pointer\n" );
5838 WSASetLastError(WSA_INVALID_PARAMETER);
5839 return FALSE;
5842 status = lpOverlapped->Internal;
5843 if (status == STATUS_PENDING)
5845 if (!fWait)
5847 SetLastError( WSA_IO_INCOMPLETE );
5848 return FALSE;
5851 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
5852 INFINITE ) == WAIT_FAILED)
5853 return FALSE;
5854 status = lpOverlapped->Internal;
5857 if ( lpcbTransfer )
5858 *lpcbTransfer = lpOverlapped->InternalHigh;
5860 if ( lpdwFlags )
5861 *lpdwFlags = lpOverlapped->u.s.Offset;
5863 if (status) SetLastError( RtlNtStatusToDosError(status) );
5864 return !status;
5868 /***********************************************************************
5869 * WSAAsyncSelect (WS2_32.101)
5871 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
5873 int ret;
5875 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
5877 SERVER_START_REQ( set_socket_event )
5879 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5880 req->mask = lEvent;
5881 req->event = 0;
5882 req->window = wine_server_user_handle( hWnd );
5883 req->msg = uMsg;
5884 ret = wine_server_call( req );
5886 SERVER_END_REQ;
5887 if (!ret) return 0;
5888 SetLastError(WSAEINVAL);
5889 return SOCKET_ERROR;
5892 /***********************************************************************
5893 * WSACreateEvent (WS2_32.31)
5896 WSAEVENT WINAPI WSACreateEvent(void)
5898 /* Create a manual-reset event, with initial state: unsignaled */
5899 TRACE("\n");
5901 return CreateEventW(NULL, TRUE, FALSE, NULL);
5904 /***********************************************************************
5905 * WSACloseEvent (WS2_32.29)
5908 BOOL WINAPI WSACloseEvent(WSAEVENT event)
5910 TRACE ("event=%p\n", event);
5912 return CloseHandle(event);
5915 /***********************************************************************
5916 * WSASocketA (WS2_32.78)
5919 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
5920 LPWSAPROTOCOL_INFOA lpProtocolInfo,
5921 GROUP g, DWORD dwFlags)
5923 INT len;
5924 WSAPROTOCOL_INFOW info;
5926 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
5927 af, type, protocol, lpProtocolInfo, g, dwFlags);
5929 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
5931 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
5932 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
5933 info.szProtocol, WSAPROTOCOL_LEN + 1);
5935 if (!len)
5937 WSASetLastError( WSAEINVAL);
5938 return SOCKET_ERROR;
5941 return WSASocketW(af, type, protocol, &info, g, dwFlags);
5944 /***********************************************************************
5945 * WSASocketW (WS2_32.79)
5948 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
5949 LPWSAPROTOCOL_INFOW lpProtocolInfo,
5950 GROUP g, DWORD dwFlags)
5952 SOCKET ret;
5953 DWORD err;
5954 int unixaf, unixtype;
5957 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
5958 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
5961 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
5962 af, type, protocol, lpProtocolInfo, g, dwFlags );
5964 if (!num_startup)
5966 err = WSANOTINITIALISED;
5967 goto done;
5970 /* hack for WSADuplicateSocket */
5971 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
5972 ret = lpProtocolInfo->dwServiceFlags3;
5973 TRACE("\tgot duplicate %04lx\n", ret);
5974 return ret;
5977 if (lpProtocolInfo)
5979 if (af == FROM_PROTOCOL_INFO || !af)
5980 af = lpProtocolInfo->iAddressFamily;
5981 if (type == FROM_PROTOCOL_INFO || !type)
5982 type = lpProtocolInfo->iSocketType;
5983 if (protocol == FROM_PROTOCOL_INFO || !protocol)
5984 protocol = lpProtocolInfo->iProtocol;
5987 if (!type && (af || protocol))
5989 WSAPROTOCOL_INFOW infow;
5991 /* default to the first valid protocol */
5992 if (!protocol)
5993 protocol = valid_protocols[0];
5995 if (WS_EnterSingleProtocolW(protocol, &infow))
5997 type = infow.iSocketType;
5999 /* after win2003 it's no longer possible to pass AF_UNSPEC
6000 using the protocol info struct */
6001 if (!lpProtocolInfo && af == WS_AF_UNSPEC)
6002 af = infow.iAddressFamily;
6006 /* convert the socket family, type and protocol */
6007 unixaf = convert_af_w2u(af);
6008 unixtype = convert_socktype_w2u(type);
6009 protocol = convert_proto_w2u(protocol);
6010 if (unixaf == AF_UNSPEC) unixaf = -1;
6012 /* filter invalid parameters */
6013 if (protocol < 0)
6015 /* the type could not be converted */
6016 if (type && unixtype < 0)
6018 err = WSAESOCKTNOSUPPORT;
6019 goto done;
6022 err = WSAEPROTONOSUPPORT;
6023 goto done;
6025 if (unixaf < 0)
6027 /* both family and protocol can't be invalid */
6028 if (protocol <= 0)
6030 err = WSAEINVAL;
6031 goto done;
6034 /* family could not be converted and neither socket type */
6035 if (unixtype < 0 && af >= 0)
6038 err = WSAESOCKTNOSUPPORT;
6039 goto done;
6042 err = WSAEAFNOSUPPORT;
6043 goto done;
6046 SERVER_START_REQ( create_socket )
6048 req->family = unixaf;
6049 req->type = unixtype;
6050 req->protocol = protocol;
6051 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
6052 req->attributes = OBJ_INHERIT;
6053 req->flags = dwFlags;
6054 set_error( wine_server_call( req ) );
6055 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
6057 SERVER_END_REQ;
6058 if (ret)
6060 TRACE("\tcreated %04lx\n", ret );
6061 return ret;
6064 err = GetLastError();
6065 if (err == WSAEACCES) /* raw socket denied */
6067 if (type == SOCK_RAW)
6068 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
6069 else
6070 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
6072 else
6074 /* invalid combination of valid parameters, like SOCK_STREAM + IPPROTO_UDP */
6075 if (err == WSAEINVAL)
6076 err = WSAESOCKTNOSUPPORT;
6077 else if (err == WSAEOPNOTSUPP)
6078 err = WSAEPROTONOSUPPORT;
6081 done:
6082 WARN("\t\tfailed, error %d!\n", err);
6083 SetLastError(err);
6084 return INVALID_SOCKET;
6087 /***********************************************************************
6088 * WSAJoinLeaf (WS2_32.58)
6091 SOCKET WINAPI WSAJoinLeaf(
6092 SOCKET s,
6093 const struct WS_sockaddr *addr,
6094 int addrlen,
6095 LPWSABUF lpCallerData,
6096 LPWSABUF lpCalleeData,
6097 LPQOS lpSQOS,
6098 LPQOS lpGQOS,
6099 DWORD dwFlags)
6101 FIXME("stub.\n");
6102 return INVALID_SOCKET;
6105 /***********************************************************************
6106 * __WSAFDIsSet (WS2_32.151)
6108 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
6110 int i = set->fd_count;
6112 TRACE("(%ld,%p(%i))\n", s, set, i);
6114 while (i--)
6115 if (set->fd_array[i] == s) return 1;
6116 return 0;
6119 /***********************************************************************
6120 * WSAIsBlocking (WS2_32.114)
6122 BOOL WINAPI WSAIsBlocking(void)
6124 /* By default WinSock should set all its sockets to non-blocking mode
6125 * and poll in PeekMessage loop when processing "blocking" ones. This
6126 * function is supposed to tell if the program is in this loop. Our
6127 * blocking calls are truly blocking so we always return FALSE.
6129 * Note: It is allowed to call this function without prior WSAStartup().
6132 TRACE("\n");
6133 return FALSE;
6136 /***********************************************************************
6137 * WSACancelBlockingCall (WS2_32.113)
6139 INT WINAPI WSACancelBlockingCall(void)
6141 TRACE("\n");
6142 return 0;
6145 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
6147 FIXME("How was this called?\n");
6148 return x();
6152 /***********************************************************************
6153 * WSASetBlockingHook (WS2_32.109)
6155 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
6157 FARPROC prev = blocking_hook;
6158 blocking_hook = lpBlockFunc;
6159 TRACE("hook %p\n", lpBlockFunc);
6160 return prev;
6164 /***********************************************************************
6165 * WSAUnhookBlockingHook (WS2_32.110)
6167 INT WINAPI WSAUnhookBlockingHook(void)
6169 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
6170 return 0;
6174 /* ----------------------------------- end of API stuff */
6176 /* ----------------------------------- helper functions -
6178 * TODO: Merge WS_dup_..() stuff into one function that
6179 * would operate with a generic structure containing internal
6180 * pointers (via a template of some kind).
6183 static int list_size(char** l, int item_size)
6185 int i,j = 0;
6186 if(l)
6187 { for(i=0;l[i];i++)
6188 j += (item_size) ? item_size : strlen(l[i]) + 1;
6189 j += (i + 1) * sizeof(char*); }
6190 return j;
6193 static int list_dup(char** l_src, char** l_to, int item_size)
6195 char *p;
6196 int i;
6198 for (i = 0; l_src[i]; i++) ;
6199 p = (char *)(l_to + i + 1);
6200 for (i = 0; l_src[i]; i++)
6202 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
6203 memcpy(p, l_src[i], count);
6204 l_to[i] = p;
6205 p += count;
6207 l_to[i] = NULL;
6208 return p - (char *)l_to;
6211 /* ----- hostent */
6213 /* create a hostent entry
6215 * Creates the entry with enough memory for the name, aliases
6216 * addresses, and the address pointers. Also copies the name
6217 * and sets up all the pointers.
6219 * NOTE: The alias and address lists must be allocated with room
6220 * for the NULL item terminating the list. This is true even if
6221 * the list has no items ("aliases" and "addresses" must be
6222 * at least "1", a truly empty list is invalid).
6224 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length)
6226 struct WS_hostent *p_to;
6227 char *p;
6228 int size = (sizeof(struct WS_hostent) +
6229 strlen(name) + 1 +
6230 sizeof(char *) * aliases +
6231 aliases_size +
6232 sizeof(char *) * addresses +
6233 address_length * (addresses - 1)), i;
6235 if (!(p_to = check_buffer_he(size))) return NULL;
6236 memset(p_to, 0, size);
6238 /* Use the memory in the same way winsock does.
6239 * First set the pointer for aliases, second set the pointers for addresses.
6240 * Third fill the addresses indexes, fourth jump aliases names size.
6241 * Fifth fill the hostname.
6242 * NOTE: This method is valid for OS version's >= XP.
6244 p = (char *)(p_to + 1);
6245 p_to->h_aliases = (char **)p;
6246 p += sizeof(char *)*aliases;
6248 p_to->h_addr_list = (char **)p;
6249 p += sizeof(char *)*addresses;
6251 for (i = 0, addresses--; i < addresses; i++, p += address_length)
6252 p_to->h_addr_list[i] = p;
6254 /* NOTE: h_aliases must be filled in manually because we don't know each string
6255 * size, leave these pointers NULL (already set to NULL by memset earlier).
6257 p += aliases_size;
6259 p_to->h_name = p;
6260 strcpy(p, name);
6262 return p_to;
6265 /* duplicate hostent entry
6266 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
6267 * Ditto for protoent and servent.
6269 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
6271 int i, addresses = 0, alias_size = 0;
6272 struct WS_hostent *p_to;
6273 char *p;
6275 for( i = 0; p_he->h_aliases[i]; i++) alias_size += strlen(p_he->h_aliases[i]) + 1;
6276 while (p_he->h_addr_list[addresses]) addresses++;
6278 p_to = WS_create_he(p_he->h_name, i + 1, alias_size, addresses + 1, p_he->h_length);
6280 if (!p_to) return NULL;
6281 p_to->h_addrtype = p_he->h_addrtype;
6282 p_to->h_length = p_he->h_length;
6284 for(i = 0, p = p_to->h_addr_list[0]; p_he->h_addr_list[i]; i++, p += p_to->h_length)
6285 memcpy(p, p_he->h_addr_list[i], p_to->h_length);
6287 /* Fill the aliases after the IP data */
6288 for(i = 0; p_he->h_aliases[i]; i++)
6290 p_to->h_aliases[i] = p;
6291 strcpy(p, p_he->h_aliases[i]);
6292 p += strlen(p) + 1;
6295 return p_to;
6298 /* ----- protoent */
6300 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
6302 char *p;
6303 struct WS_protoent *p_to;
6305 int size = (sizeof(*p_pe) +
6306 strlen(p_pe->p_name) + 1 +
6307 list_size(p_pe->p_aliases, 0));
6309 if (!(p_to = check_buffer_pe(size))) return NULL;
6310 p_to->p_proto = p_pe->p_proto;
6312 p = (char *)(p_to + 1);
6313 p_to->p_name = p;
6314 strcpy(p, p_pe->p_name);
6315 p += strlen(p) + 1;
6317 p_to->p_aliases = (char **)p;
6318 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
6319 return p_to;
6322 /* ----- servent */
6324 static struct WS_servent *WS_dup_se(const struct servent* p_se)
6326 char *p;
6327 struct WS_servent *p_to;
6329 int size = (sizeof(*p_se) +
6330 strlen(p_se->s_proto) + 1 +
6331 strlen(p_se->s_name) + 1 +
6332 list_size(p_se->s_aliases, 0));
6334 if (!(p_to = check_buffer_se(size))) return NULL;
6335 p_to->s_port = p_se->s_port;
6337 p = (char *)(p_to + 1);
6338 p_to->s_name = p;
6339 strcpy(p, p_se->s_name);
6340 p += strlen(p) + 1;
6342 p_to->s_proto = p;
6343 strcpy(p, p_se->s_proto);
6344 p += strlen(p) + 1;
6346 p_to->s_aliases = (char **)p;
6347 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
6348 return p_to;
6352 /***********************************************************************
6353 * WSARecv (WS2_32.67)
6355 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6356 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
6357 LPWSAOVERLAPPED lpOverlapped,
6358 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
6360 return WS2_recv_base(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
6361 NULL, NULL, lpOverlapped, lpCompletionRoutine, NULL);
6364 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6365 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
6366 struct WS_sockaddr *lpFrom,
6367 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
6368 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
6369 LPWSABUF lpControlBuffer )
6371 unsigned int i, options;
6372 int n, fd, err;
6373 struct ws2_async *wsa;
6374 BOOL is_blocking;
6375 DWORD timeout_start = GetTickCount();
6376 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
6378 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
6379 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
6380 (lpFromlen ? *lpFromlen : -1),
6381 lpOverlapped, lpCompletionRoutine);
6383 fd = get_sock_fd( s, FILE_READ_DATA, &options );
6384 TRACE( "fd=%d, options=%x\n", fd, options );
6386 if (fd == -1) return SOCKET_ERROR;
6388 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
6390 err = WSAEFAULT;
6391 goto error;
6394 wsa->hSocket = SOCKET2HANDLE(s);
6395 wsa->flags = *lpFlags;
6396 wsa->lpFlags = lpFlags;
6397 wsa->addr = lpFrom;
6398 wsa->addrlen.ptr = lpFromlen;
6399 wsa->control = lpControlBuffer;
6400 wsa->n_iovecs = dwBufferCount;
6401 wsa->first_iovec = 0;
6402 for (i = 0; i < dwBufferCount; i++)
6404 /* check buffer first to trigger write watches */
6405 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
6407 err = WSAEFAULT;
6408 goto error;
6410 wsa->iovec[i].iov_base = lpBuffers[i].buf;
6411 wsa->iovec[i].iov_len = lpBuffers[i].len;
6414 for (;;)
6416 n = WS2_recv( fd, wsa );
6417 if (n == -1)
6419 if (errno == EINTR) continue;
6420 if (errno != EAGAIN)
6422 int loc_errno = errno;
6423 err = wsaErrno();
6424 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
6425 goto error;
6428 else if (lpNumberOfBytesRecvd) *lpNumberOfBytesRecvd = n;
6430 if ((lpOverlapped || lpCompletionRoutine) &&
6431 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
6433 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
6435 wsa->user_overlapped = lpOverlapped;
6436 wsa->completion_func = lpCompletionRoutine;
6437 release_sock_fd( s, fd );
6439 if (n == -1)
6441 iosb->u.Status = STATUS_PENDING;
6442 iosb->Information = 0;
6444 SERVER_START_REQ( register_async )
6446 req->type = ASYNC_TYPE_READ;
6447 req->async.handle = wine_server_obj_handle( wsa->hSocket );
6448 req->async.callback = wine_server_client_ptr( WS2_async_recv );
6449 req->async.iosb = wine_server_client_ptr( iosb );
6450 req->async.arg = wine_server_client_ptr( wsa );
6451 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
6452 req->async.cvalue = cvalue;
6453 err = wine_server_call( req );
6455 SERVER_END_REQ;
6457 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
6458 WSASetLastError( NtStatusToWSAError( err ));
6459 return SOCKET_ERROR;
6462 iosb->u.Status = STATUS_SUCCESS;
6463 iosb->Information = n;
6464 if (!wsa->completion_func)
6466 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
6467 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
6468 HeapFree( GetProcessHeap(), 0, wsa );
6470 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
6471 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
6472 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6473 return 0;
6476 if (n != -1) break;
6478 if ((err = _is_blocking( s, &is_blocking )))
6480 err = NtStatusToWSAError( err );
6481 goto error;
6484 if ( is_blocking )
6486 struct pollfd pfd;
6487 int timeout = GET_RCVTIMEO(fd);
6488 if (timeout != -1)
6490 timeout -= GetTickCount() - timeout_start;
6491 if (timeout < 0) timeout = 0;
6494 pfd.fd = fd;
6495 pfd.events = POLLIN;
6496 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
6498 if (!timeout || !poll( &pfd, 1, timeout ))
6500 err = WSAETIMEDOUT;
6501 /* a timeout is not fatal */
6502 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6503 goto error;
6506 else
6508 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6509 err = WSAEWOULDBLOCK;
6510 goto error;
6514 TRACE(" -> %i bytes\n", n);
6515 HeapFree( GetProcessHeap(), 0, wsa );
6516 release_sock_fd( s, fd );
6517 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6519 return 0;
6521 error:
6522 HeapFree( GetProcessHeap(), 0, wsa );
6523 release_sock_fd( s, fd );
6524 WARN(" -> ERROR %d\n", err);
6525 WSASetLastError( err );
6526 return SOCKET_ERROR;
6529 /***********************************************************************
6530 * WSARecvFrom (WS2_32.69)
6532 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6533 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
6534 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
6535 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
6538 return WS2_recv_base( s, lpBuffers, dwBufferCount,
6539 lpNumberOfBytesRecvd, lpFlags,
6540 lpFrom, lpFromlen,
6541 lpOverlapped, lpCompletionRoutine, NULL );
6544 /***********************************************************************
6545 * WSCInstallProvider (WS2_32.88)
6547 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
6548 LPCWSTR lpszProviderDllPath,
6549 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
6550 DWORD dwNumberOfEntries,
6551 LPINT lpErrno )
6553 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
6554 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
6555 dwNumberOfEntries, lpErrno);
6556 *lpErrno = 0;
6557 return 0;
6561 /***********************************************************************
6562 * WSCDeinstallProvider (WS2_32.83)
6564 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
6566 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
6567 *lpErrno = 0;
6568 return 0;
6572 /***********************************************************************
6573 * WSAAccept (WS2_32.26)
6575 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
6576 LPCONDITIONPROC lpfnCondition, DWORD_PTR dwCallbackData)
6579 int ret = 0, size;
6580 WSABUF CallerId, CallerData, CalleeId, CalleeData;
6581 /* QOS SQOS, GQOS; */
6582 GROUP g;
6583 SOCKET cs;
6584 SOCKADDR src_addr, dst_addr;
6586 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
6587 s, addr, addrlen, lpfnCondition, dwCallbackData);
6589 cs = WS_accept(s, addr, addrlen);
6590 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
6591 if (!lpfnCondition) return cs;
6593 if (addr && addrlen)
6595 CallerId.buf = (char *)addr;
6596 CallerId.len = *addrlen;
6598 else
6600 size = sizeof(src_addr);
6601 WS_getpeername(cs, &src_addr, &size);
6602 CallerId.buf = (char *)&src_addr;
6603 CallerId.len = size;
6605 CallerData.buf = NULL;
6606 CallerData.len = 0;
6608 size = sizeof(dst_addr);
6609 WS_getsockname(cs, &dst_addr, &size);
6611 CalleeId.buf = (char *)&dst_addr;
6612 CalleeId.len = sizeof(dst_addr);
6614 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
6615 &CalleeId, &CalleeData, &g, dwCallbackData);
6617 switch (ret)
6619 case CF_ACCEPT:
6620 return cs;
6621 case CF_DEFER:
6622 SERVER_START_REQ( set_socket_deferred )
6624 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6625 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
6626 if ( !wine_server_call_err ( req ) )
6628 SetLastError( WSATRY_AGAIN );
6629 WS_closesocket( cs );
6632 SERVER_END_REQ;
6633 return SOCKET_ERROR;
6634 case CF_REJECT:
6635 WS_closesocket(cs);
6636 SetLastError(WSAECONNREFUSED);
6637 return SOCKET_ERROR;
6638 default:
6639 FIXME("Unknown return type from Condition function\n");
6640 SetLastError(WSAENOTSOCK);
6641 return SOCKET_ERROR;
6645 /***********************************************************************
6646 * WSADuplicateSocketA (WS2_32.32)
6648 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
6650 return WS_DuplicateSocket(FALSE, s, dwProcessId, (LPWSAPROTOCOL_INFOW) lpProtocolInfo);
6653 /***********************************************************************
6654 * WSADuplicateSocketW (WS2_32.33)
6656 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
6658 return WS_DuplicateSocket(TRUE, s, dwProcessId, lpProtocolInfo);
6661 /***********************************************************************
6662 * WSAInstallServiceClassA (WS2_32.48)
6664 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
6666 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
6667 WSASetLastError(WSAEACCES);
6668 return SOCKET_ERROR;
6671 /***********************************************************************
6672 * WSAInstallServiceClassW (WS2_32.49)
6674 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
6676 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
6677 WSASetLastError(WSAEACCES);
6678 return SOCKET_ERROR;
6681 /***********************************************************************
6682 * WSARemoveServiceClass (WS2_32.70)
6684 int WINAPI WSARemoveServiceClass(LPGUID info)
6686 FIXME("Request to remove service %p\n",info);
6687 WSASetLastError(WSATYPE_NOT_FOUND);
6688 return SOCKET_ERROR;
6691 /***********************************************************************
6692 * inet_ntop (WS2_32.@)
6694 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
6696 #ifdef HAVE_INET_NTOP
6697 struct WS_in6_addr *in6;
6698 struct WS_in_addr *in;
6699 PCSTR pdst;
6701 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
6702 if (!buffer)
6704 WSASetLastError( STATUS_INVALID_PARAMETER );
6705 return NULL;
6708 switch (family)
6710 case WS_AF_INET:
6712 in = addr;
6713 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
6714 break;
6716 case WS_AF_INET6:
6718 in6 = addr;
6719 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
6720 break;
6722 default:
6723 WSASetLastError( WSAEAFNOSUPPORT );
6724 return NULL;
6727 if (!pdst) WSASetLastError( STATUS_INVALID_PARAMETER );
6728 return pdst;
6729 #else
6730 FIXME( "not supported on this platform\n" );
6731 WSASetLastError( WSAEAFNOSUPPORT );
6732 return NULL;
6733 #endif
6736 /***********************************************************************
6737 * WSAStringToAddressA (WS2_32.80)
6739 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
6740 INT AddressFamily,
6741 LPWSAPROTOCOL_INFOA lpProtocolInfo,
6742 LPSOCKADDR lpAddress,
6743 LPINT lpAddressLength)
6745 INT res=0;
6746 LPSTR workBuffer=NULL,ptrPort;
6748 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
6749 lpProtocolInfo, lpAddress, lpAddressLength );
6751 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
6753 if (!AddressString)
6755 WSASetLastError(WSAEINVAL);
6756 return SOCKET_ERROR;
6759 if (lpProtocolInfo)
6760 FIXME("ProtocolInfo not implemented.\n");
6762 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
6763 strlen(AddressString) + 1);
6764 if (!workBuffer)
6766 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6767 return SOCKET_ERROR;
6770 strcpy(workBuffer, AddressString);
6772 switch(AddressFamily)
6774 case WS_AF_INET:
6776 struct in_addr inetaddr;
6778 /* If lpAddressLength is too small, tell caller the size we need */
6779 if (*lpAddressLength < sizeof(SOCKADDR_IN))
6781 *lpAddressLength = sizeof(SOCKADDR_IN);
6782 res = WSAEFAULT;
6783 break;
6785 *lpAddressLength = sizeof(SOCKADDR_IN);
6786 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
6788 ((LPSOCKADDR_IN)lpAddress)->sin_family = AF_INET;
6790 ptrPort = strchr(workBuffer, ':');
6791 if(ptrPort)
6793 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
6794 *ptrPort = '\0';
6796 else
6798 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
6801 if(inet_aton(workBuffer, &inetaddr) > 0)
6803 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
6804 res = 0;
6806 else
6807 res = WSAEINVAL;
6809 break;
6812 case WS_AF_INET6:
6814 struct in6_addr inetaddr;
6815 /* If lpAddressLength is too small, tell caller the size we need */
6816 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
6818 *lpAddressLength = sizeof(SOCKADDR_IN6);
6819 res = WSAEFAULT;
6820 break;
6822 #ifdef HAVE_INET_PTON
6823 *lpAddressLength = sizeof(SOCKADDR_IN6);
6824 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
6826 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
6828 /* This one is a bit tricky. An IPv6 address contains colons, so the
6829 * check from IPv4 doesn't work like that. However, IPv6 addresses that
6830 * contain a port are written with braces like [fd12:3456:7890::1]:12345
6831 * so what we will do is to look for ']', check if the next char is a
6832 * colon, and if it is, parse the port as in IPv4. */
6834 ptrPort = strchr(workBuffer, ']');
6835 if(ptrPort && *(++ptrPort) == ':')
6837 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort+1));
6838 *ptrPort = '\0';
6840 else
6842 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
6845 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
6847 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
6848 sizeof(struct in6_addr));
6849 res = 0;
6851 else
6852 #endif /* HAVE_INET_PTON */
6853 res = WSAEINVAL;
6855 break;
6857 default:
6858 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
6859 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
6860 res = WSAEINVAL;
6863 HeapFree(GetProcessHeap(), 0, workBuffer);
6865 if (!res) return 0;
6866 WSASetLastError(res);
6867 return SOCKET_ERROR;
6870 /***********************************************************************
6871 * WSAStringToAddressW (WS2_32.81)
6873 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
6874 * If this should be the case, it would be required to map these digits
6875 * to Unicode digits (0-9) using FoldString first.
6877 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
6878 INT AddressFamily,
6879 LPWSAPROTOCOL_INFOW lpProtocolInfo,
6880 LPSOCKADDR lpAddress,
6881 LPINT lpAddressLength)
6883 INT sBuffer,res=0;
6884 LPSTR workBuffer=NULL;
6885 WSAPROTOCOL_INFOA infoA;
6886 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
6888 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
6889 lpAddress, lpAddressLength );
6891 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
6893 /* if ProtocolInfo is available - convert to ANSI variant */
6894 if (lpProtocolInfo)
6896 lpProtoInfoA = &infoA;
6897 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
6899 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
6900 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
6902 WSASetLastError( WSAEINVAL);
6903 return SOCKET_ERROR;
6907 if (AddressString)
6909 /* Translate AddressString to ANSI code page - assumes that only
6910 standard digits 0-9 are used with this API call */
6911 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
6912 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
6914 if (workBuffer)
6916 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
6917 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
6918 lpAddress,lpAddressLength);
6919 HeapFree( GetProcessHeap(), 0, workBuffer );
6920 return res;
6922 else
6923 res = WSA_NOT_ENOUGH_MEMORY;
6925 else
6926 res = WSAEINVAL;
6928 WSASetLastError(res);
6929 return SOCKET_ERROR;
6932 /***********************************************************************
6933 * WSAAddressToStringA (WS2_32.27)
6935 * See WSAAddressToStringW
6937 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
6938 LPWSAPROTOCOL_INFOA info, LPSTR string,
6939 LPDWORD lenstr )
6941 DWORD size;
6942 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
6943 CHAR *p;
6945 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
6947 if (!sockaddr) return SOCKET_ERROR;
6948 if (!string || !lenstr) return SOCKET_ERROR;
6950 switch(sockaddr->sa_family)
6952 case WS_AF_INET:
6953 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
6954 sprintf( buffer, "%u.%u.%u.%u:%u",
6955 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
6956 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
6957 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
6958 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
6959 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
6961 p = strchr( buffer, ':' );
6962 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
6963 break;
6965 case WS_AF_INET6:
6967 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
6969 buffer[0] = 0;
6970 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
6971 if ((sockaddr6->sin6_port))
6972 strcpy(buffer, "[");
6973 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, buffer+strlen(buffer), sizeof(buffer)))
6975 WSASetLastError(WSAEINVAL);
6976 return SOCKET_ERROR;
6978 if ((sockaddr6->sin6_scope_id))
6979 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
6980 if ((sockaddr6->sin6_port))
6981 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
6982 break;
6985 default:
6986 WSASetLastError(WSAEINVAL);
6987 return SOCKET_ERROR;
6990 size = strlen( buffer ) + 1;
6992 if (*lenstr < size)
6994 *lenstr = size;
6995 WSASetLastError(WSAEFAULT);
6996 return SOCKET_ERROR;
6999 TRACE("=> %s,%u bytes\n", debugstr_a(buffer), size);
7000 *lenstr = size;
7001 strcpy( string, buffer );
7002 return 0;
7005 /***********************************************************************
7006 * WSAAddressToStringW (WS2_32.28)
7008 * Convert a sockaddr address into a readable address string.
7010 * PARAMS
7011 * sockaddr [I] Pointer to a sockaddr structure.
7012 * len [I] Size of the sockaddr structure.
7013 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
7014 * string [I/O] Pointer to a buffer to receive the address string.
7015 * lenstr [I/O] Size of the receive buffer in WCHARs.
7017 * RETURNS
7018 * Success: 0
7019 * Failure: SOCKET_ERROR
7021 * NOTES
7022 * The 'info' parameter is ignored.
7024 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
7025 LPWSAPROTOCOL_INFOW info, LPWSTR string,
7026 LPDWORD lenstr )
7028 INT ret;
7029 DWORD size;
7030 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
7031 CHAR bufAddr[54];
7033 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
7035 size = *lenstr;
7036 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
7038 if (ret) return ret;
7040 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
7042 if (*lenstr < size)
7044 *lenstr = size;
7045 WSASetLastError(WSAEFAULT);
7046 return SOCKET_ERROR;
7049 TRACE("=> %s,%u bytes\n", debugstr_w(buffer), size);
7050 *lenstr = size;
7051 lstrcpyW( string, buffer );
7052 return 0;
7055 /***********************************************************************
7056 * WSAEnumNameSpaceProvidersA (WS2_32.34)
7058 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
7060 FIXME( "(%p %p) Stub!\n", len, buffer );
7061 return 0;
7064 /***********************************************************************
7065 * WSAEnumNameSpaceProvidersW (WS2_32.35)
7067 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
7069 FIXME( "(%p %p) Stub!\n", len, buffer );
7070 return 0;
7073 /***********************************************************************
7074 * WSAGetQOSByName (WS2_32.41)
7076 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
7078 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
7079 return FALSE;
7082 /***********************************************************************
7083 * WSAGetServiceClassInfoA (WS2_32.42)
7085 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
7086 LPWSASERVICECLASSINFOA info )
7088 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
7089 len, info );
7090 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7091 return SOCKET_ERROR;
7094 /***********************************************************************
7095 * WSAGetServiceClassInfoW (WS2_32.43)
7097 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
7098 LPWSASERVICECLASSINFOW info )
7100 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
7101 len, info );
7102 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7103 return SOCKET_ERROR;
7106 /***********************************************************************
7107 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
7109 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
7111 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
7112 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7113 return SOCKET_ERROR;
7116 /***********************************************************************
7117 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
7119 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
7121 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
7122 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7123 return SOCKET_ERROR;
7126 /***********************************************************************
7127 * WSALookupServiceBeginA (WS2_32.59)
7129 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
7130 DWORD dwControlFlags,
7131 LPHANDLE lphLookup)
7133 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
7134 lphLookup);
7135 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7136 return SOCKET_ERROR;
7139 /***********************************************************************
7140 * WSALookupServiceBeginW (WS2_32.60)
7142 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
7143 DWORD dwControlFlags,
7144 LPHANDLE lphLookup)
7146 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
7147 lphLookup);
7148 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7149 return SOCKET_ERROR;
7152 /***********************************************************************
7153 * WSALookupServiceEnd (WS2_32.61)
7155 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
7157 FIXME("(%p) Stub!\n", lookup );
7158 return 0;
7161 /***********************************************************************
7162 * WSALookupServiceNextA (WS2_32.62)
7164 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
7166 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
7167 WSASetLastError(WSA_E_NO_MORE);
7168 return SOCKET_ERROR;
7171 /***********************************************************************
7172 * WSALookupServiceNextW (WS2_32.63)
7174 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
7176 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
7177 WSASetLastError(WSA_E_NO_MORE);
7178 return SOCKET_ERROR;
7181 /***********************************************************************
7182 * WSANtohl (WS2_32.64)
7184 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
7186 TRACE( "(0x%04lx 0x%08x %p)\n", s, netlong, lphostlong );
7188 if (!lphostlong) return WSAEFAULT;
7190 *lphostlong = ntohl( netlong );
7191 return 0;
7194 /***********************************************************************
7195 * WSANtohs (WS2_32.65)
7197 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
7199 TRACE( "(0x%04lx 0x%08x %p)\n", s, netshort, lphostshort );
7201 if (!lphostshort) return WSAEFAULT;
7203 *lphostshort = ntohs( netshort );
7204 return 0;
7207 /***********************************************************************
7208 * WSAProviderConfigChange (WS2_32.66)
7210 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
7211 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
7213 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
7214 return SOCKET_ERROR;
7217 /***********************************************************************
7218 * WSARecvDisconnect (WS2_32.68)
7220 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
7222 TRACE( "(0x%04lx %p)\n", s, disconnectdata );
7224 return WS_shutdown( s, 0 );
7227 /***********************************************************************
7228 * WSASetServiceA (WS2_32.76)
7230 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
7232 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
7233 return 0;
7236 /***********************************************************************
7237 * WSASetServiceW (WS2_32.77)
7239 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
7241 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
7242 return 0;
7245 /***********************************************************************
7246 * WSCEnableNSProvider (WS2_32.84)
7248 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
7250 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
7251 return 0;
7254 /***********************************************************************
7255 * WSCGetProviderPath (WS2_32.86)
7257 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
7259 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
7261 if (!errcode || !provider || !len) return WSAEFAULT;
7263 *errcode = WSAEINVAL;
7264 return SOCKET_ERROR;
7267 /***********************************************************************
7268 * WSCInstallNameSpace (WS2_32.87)
7270 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
7271 DWORD version, LPGUID provider )
7273 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
7274 namespace, version, debugstr_guid(provider) );
7275 return 0;
7278 /***********************************************************************
7279 * WSCUnInstallNameSpace (WS2_32.89)
7281 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
7283 FIXME("(%p) Stub!\n", lpProviderId);
7284 return NO_ERROR;
7287 /***********************************************************************
7288 * WSCWriteProviderOrder (WS2_32.91)
7290 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
7292 FIXME("(%p 0x%08x) Stub!\n", entry, number);
7293 return 0;
7296 /***********************************************************************
7297 * WSANSPIoctl (WS2_32.91)
7299 INT WINAPI WSANSPIoctl( HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer,
7300 DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer,
7301 LPDWORD lpcbBytesReturned, LPWSACOMPLETION lpCompletion )
7303 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup, dwControlCode,
7304 lpvInBuffer, cbInBuffer, lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpCompletion);
7305 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7306 return SOCKET_ERROR;
7309 /*****************************************************************************
7310 * WSAEnumProtocolsA [WS2_32.@]
7312 * see function WSAEnumProtocolsW
7314 INT WINAPI WSAEnumProtocolsA( LPINT protocols, LPWSAPROTOCOL_INFOA buffer, LPDWORD len )
7316 return WS_EnumProtocols( FALSE, protocols, (LPWSAPROTOCOL_INFOW) buffer, len);
7319 /*****************************************************************************
7320 * WSAEnumProtocolsW [WS2_32.@]
7322 * Retrieves information about specified set of active network protocols.
7324 * PARAMS
7325 * protocols [I] Pointer to null-terminated array of protocol id's. NULL
7326 * retrieves information on all available protocols.
7327 * buffer [I] Pointer to a buffer to be filled with WSAPROTOCOL_INFO
7328 * structures.
7329 * len [I/O] Pointer to a variable specifying buffer size. On output
7330 * the variable holds the number of bytes needed when the
7331 * specified size is too small.
7333 * RETURNS
7334 * Success: number of WSAPROTOCOL_INFO structures in buffer.
7335 * Failure: SOCKET_ERROR
7337 * NOTES
7338 * NT4SP5 does not return SPX if protocols == NULL
7340 * BUGS
7341 * - NT4SP5 returns in addition these list of NETBIOS protocols
7342 * (address family 17), each entry two times one for socket type 2 and 5
7344 * iProtocol szProtocol
7345 * 0x80000000 \Device\NwlnkNb
7346 * 0xfffffffa \Device\NetBT_CBENT7
7347 * 0xfffffffb \Device\Nbf_CBENT7
7348 * 0xfffffffc \Device\NetBT_NdisWan5
7349 * 0xfffffffd \Device\NetBT_El9202
7350 * 0xfffffffe \Device\Nbf_El9202
7351 * 0xffffffff \Device\Nbf_NdisWan4
7353 * - there is no check that the operating system supports the returned
7354 * protocols
7356 INT WINAPI WSAEnumProtocolsW( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
7358 return WS_EnumProtocols( TRUE, protocols, buffer, len);
7361 /*****************************************************************************
7362 * WSCEnumProtocols [WS2_32.@]
7364 * PARAMS
7365 * protocols [I] Null-terminated array of iProtocol values.
7366 * buffer [O] Buffer of WSAPROTOCOL_INFOW structures.
7367 * len [I/O] Size of buffer on input/output.
7368 * errno [O] Error code.
7370 * RETURNS
7371 * Success: number of protocols to be reported on.
7372 * Failure: SOCKET_ERROR. error is in errno.
7374 * BUGS
7375 * Doesn't supply info on layered protocols.
7378 INT WINAPI WSCEnumProtocols( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len, LPINT err )
7380 INT ret = WSAEnumProtocolsW( protocols, buffer, len );
7382 if (ret == SOCKET_ERROR) *err = WSAENOBUFS;
7384 return ret;