ws2_32: Add a more generic function to retrieve socket errors from server.
[wine/multimedia.git] / dlls / ws2_32 / socket.c
blobad75a752e6745917de766ba904b54de5fea47fdf
1 /*
2 * based on Windows Sockets 1.1 specs
4 * Copyright (C) 1993,1994,1996,1997 John Brezak, Erik Bos, Alex Korobka.
5 * Copyright (C) 2001 Stefan Leichter
6 * Copyright (C) 2004 Hans Leidekker
7 * Copyright (C) 2005 Marcus Meissner
8 * Copyright (C) 2006-2008 Kai Blin
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24 * NOTE: If you make any changes to fix a particular app, make sure
25 * they don't break something else like Netscape or telnet and ftp
26 * clients and servers (www.winsite.com got a lot of those).
29 #include "config.h"
30 #include "wine/port.h"
32 #include <stdarg.h>
33 #include <stdio.h>
34 #include <string.h>
35 #include <sys/types.h>
36 #ifdef HAVE_SYS_IPC_H
37 # include <sys/ipc.h>
38 #endif
39 #ifdef HAVE_SYS_IOCTL_H
40 # include <sys/ioctl.h>
41 #endif
42 #ifdef HAVE_SYS_FILIO_H
43 # include <sys/filio.h>
44 #endif
45 #ifdef HAVE_SYS_SOCKIO_H
46 # include <sys/sockio.h>
47 #endif
49 #if defined(__EMX__)
50 # include <sys/so_ioctl.h>
51 #endif
53 #ifdef HAVE_SYS_PARAM_H
54 # include <sys/param.h>
55 #endif
57 #ifdef HAVE_SYS_MSG_H
58 # include <sys/msg.h>
59 #endif
60 #ifdef HAVE_SYS_WAIT_H
61 # include <sys/wait.h>
62 #endif
63 #ifdef HAVE_SYS_UIO_H
64 # include <sys/uio.h>
65 #endif
66 #ifdef HAVE_SYS_SOCKET_H
67 #include <sys/socket.h>
68 #endif
69 #ifdef HAVE_NETINET_IN_H
70 # include <netinet/in.h>
71 #endif
72 #ifdef HAVE_NETINET_TCP_H
73 # include <netinet/tcp.h>
74 #endif
75 #ifdef HAVE_ARPA_INET_H
76 # include <arpa/inet.h>
77 #endif
78 #include <ctype.h>
79 #include <fcntl.h>
80 #include <errno.h>
81 #ifdef HAVE_NETDB_H
82 #include <netdb.h>
83 #endif
84 #ifdef HAVE_UNISTD_H
85 # include <unistd.h>
86 #endif
87 #include <stdlib.h>
88 #ifdef HAVE_ARPA_NAMESER_H
89 # include <arpa/nameser.h>
90 #endif
91 #ifdef HAVE_RESOLV_H
92 # include <resolv.h>
93 #endif
94 #ifdef HAVE_NET_IF_H
95 # include <net/if.h>
96 #endif
97 #ifdef HAVE_LINUX_FILTER_H
98 # include <linux/filter.h>
99 #endif
101 #ifdef HAVE_NETIPX_IPX_H
102 # include <netipx/ipx.h>
103 #elif defined(HAVE_LINUX_IPX_H)
104 # ifdef HAVE_ASM_TYPES_H
105 # include <asm/types.h>
106 # endif
107 # ifdef HAVE_LINUX_TYPES_H
108 # include <linux/types.h>
109 # endif
110 # include <linux/ipx.h>
111 #endif
112 #if defined(SOL_IPX) || defined(SO_DEFAULT_HEADERS)
113 # define HAS_IPX
114 #endif
116 #ifdef HAVE_LINUX_IRDA_H
117 # ifdef HAVE_LINUX_TYPES_H
118 # include <linux/types.h>
119 # endif
120 # include <linux/irda.h>
121 # define HAS_IRDA
122 #endif
124 #ifdef HAVE_POLL_H
125 #include <poll.h>
126 #endif
127 #ifdef HAVE_SYS_POLL_H
128 # include <sys/poll.h>
129 #endif
130 #ifdef HAVE_SYS_TIME_H
131 # include <sys/time.h>
132 #endif
134 #define NONAMELESSUNION
135 #define NONAMELESSSTRUCT
136 #include "ntstatus.h"
137 #define WIN32_NO_STATUS
138 #include "windef.h"
139 #include "winbase.h"
140 #include "wingdi.h"
141 #include "winuser.h"
142 #include "winerror.h"
143 #include "winnls.h"
144 #include "winsock2.h"
145 #include "mswsock.h"
146 #include "ws2tcpip.h"
147 #include "ws2spi.h"
148 #include "wsipx.h"
149 #include "wsnwlink.h"
150 #include "wshisotp.h"
151 #include "mstcpip.h"
152 #include "af_irda.h"
153 #include "winnt.h"
154 #define USE_WC_PREFIX /* For CMSG_DATA */
155 #include "iphlpapi.h"
156 #include "wine/server.h"
157 #include "wine/debug.h"
158 #include "wine/exception.h"
159 #include "wine/unicode.h"
161 #if defined(linux) && !defined(IP_UNICAST_IF)
162 #define IP_UNICAST_IF 50
163 #endif
165 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
166 # define sipx_network sipx_addr.x_net
167 # define sipx_node sipx_addr.x_host.c_host
168 #endif /* __FreeBSD__ */
170 #ifndef INADDR_NONE
171 #define INADDR_NONE ~0UL
172 #endif
174 WINE_DEFAULT_DEBUG_CHANNEL(winsock);
175 WINE_DECLARE_DEBUG_CHANNEL(winediag);
177 /* names of the protocols */
178 static const WCHAR NameIpxW[] = {'I', 'P', 'X', '\0'};
179 static const WCHAR NameSpxW[] = {'S', 'P', 'X', '\0'};
180 static const WCHAR NameSpxIIW[] = {'S', 'P', 'X', ' ', 'I', 'I', '\0'};
181 static const WCHAR NameTcpW[] = {'T', 'C', 'P', '/', 'I', 'P', '\0'};
182 static const WCHAR NameUdpW[] = {'U', 'D', 'P', '/', 'I', 'P', '\0'};
184 /* Taken from Win2k */
185 static const GUID ProviderIdIP = { 0xe70f1aa0, 0xab8b, 0x11cf,
186 { 0x8c, 0xa3, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
187 static const GUID ProviderIdIPX = { 0x11058240, 0xbe47, 0x11cf,
188 { 0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
189 static const GUID ProviderIdSPX = { 0x11058241, 0xbe47, 0x11cf,
190 { 0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
192 static const INT valid_protocols[] =
194 WS_IPPROTO_TCP,
195 WS_IPPROTO_UDP,
196 WS_NSPROTO_IPX,
197 WS_NSPROTO_SPX,
198 WS_NSPROTO_SPXII,
202 #define IS_IPX_PROTO(X) ((X) >= WS_NSPROTO_IPX && (X) <= WS_NSPROTO_IPX + 255)
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_IPX:
297 int i;
298 char netnum[16], nodenum[16];
299 struct WS_sockaddr_ipx *sin = (struct WS_sockaddr_ipx *)a;
301 for (i = 0;i < 4; i++) sprintf(netnum + i * 2, "%02X", (unsigned char) sin->sa_netnum[i]);
302 for (i = 0;i < 6; i++) sprintf(nodenum + i * 2, "%02X", (unsigned char) sin->sa_nodenum[i]);
304 return wine_dbg_sprintf("{ family AF_IPX, address %s.%s, ipx socket %d }",
305 netnum, nodenum, sin->sa_socket);
307 case WS_AF_IRDA:
309 DWORD addr;
311 memcpy( &addr, ((const SOCKADDR_IRDA *)a)->irdaDeviceID, sizeof(addr) );
312 addr = ntohl( addr );
313 return wine_dbg_sprintf("{ family AF_IRDA, addr %08x, name %s }",
314 addr,
315 ((const SOCKADDR_IRDA *)a)->irdaServiceName);
317 default:
318 return wine_dbg_sprintf("{ family %d }", a->sa_family);
322 static inline const char *debugstr_sockopt(int level, int optname)
324 const char *stropt = NULL, *strlevel = NULL;
326 #define DEBUG_SOCKLEVEL(x) case (x): strlevel = #x
327 #define DEBUG_SOCKOPT(x) case (x): stropt = #x; break
329 switch(level)
331 DEBUG_SOCKLEVEL(WS_SOL_SOCKET);
332 switch(optname)
334 DEBUG_SOCKOPT(WS_SO_ACCEPTCONN);
335 DEBUG_SOCKOPT(WS_SO_BROADCAST);
336 DEBUG_SOCKOPT(WS_SO_BSP_STATE);
337 DEBUG_SOCKOPT(WS_SO_CONDITIONAL_ACCEPT);
338 DEBUG_SOCKOPT(WS_SO_CONNECT_TIME);
339 DEBUG_SOCKOPT(WS_SO_DEBUG);
340 DEBUG_SOCKOPT(WS_SO_DONTLINGER);
341 DEBUG_SOCKOPT(WS_SO_DONTROUTE);
342 DEBUG_SOCKOPT(WS_SO_ERROR);
343 DEBUG_SOCKOPT(WS_SO_EXCLUSIVEADDRUSE);
344 DEBUG_SOCKOPT(WS_SO_GROUP_ID);
345 DEBUG_SOCKOPT(WS_SO_GROUP_PRIORITY);
346 DEBUG_SOCKOPT(WS_SO_KEEPALIVE);
347 DEBUG_SOCKOPT(WS_SO_LINGER);
348 DEBUG_SOCKOPT(WS_SO_MAX_MSG_SIZE);
349 DEBUG_SOCKOPT(WS_SO_OOBINLINE);
350 DEBUG_SOCKOPT(WS_SO_OPENTYPE);
351 DEBUG_SOCKOPT(WS_SO_PROTOCOL_INFOA);
352 DEBUG_SOCKOPT(WS_SO_PROTOCOL_INFOW);
353 DEBUG_SOCKOPT(WS_SO_RCVBUF);
354 DEBUG_SOCKOPT(WS_SO_RCVTIMEO);
355 DEBUG_SOCKOPT(WS_SO_REUSEADDR);
356 DEBUG_SOCKOPT(WS_SO_SNDBUF);
357 DEBUG_SOCKOPT(WS_SO_SNDTIMEO);
358 DEBUG_SOCKOPT(WS_SO_TYPE);
360 break;
362 DEBUG_SOCKLEVEL(WS_NSPROTO_IPX);
363 switch(optname)
365 DEBUG_SOCKOPT(WS_IPX_PTYPE);
366 DEBUG_SOCKOPT(WS_IPX_FILTERPTYPE);
367 DEBUG_SOCKOPT(WS_IPX_DSTYPE);
368 DEBUG_SOCKOPT(WS_IPX_RECVHDR);
369 DEBUG_SOCKOPT(WS_IPX_MAXSIZE);
370 DEBUG_SOCKOPT(WS_IPX_ADDRESS);
371 DEBUG_SOCKOPT(WS_IPX_MAX_ADAPTER_NUM);
373 break;
375 DEBUG_SOCKLEVEL(WS_SOL_IRLMP);
376 switch(optname)
378 DEBUG_SOCKOPT(WS_IRLMP_ENUMDEVICES);
380 break;
382 DEBUG_SOCKLEVEL(WS_IPPROTO_TCP);
383 switch(optname)
385 DEBUG_SOCKOPT(WS_TCP_BSDURGENT);
386 DEBUG_SOCKOPT(WS_TCP_EXPEDITED_1122);
387 DEBUG_SOCKOPT(WS_TCP_NODELAY);
389 break;
391 DEBUG_SOCKLEVEL(WS_IPPROTO_IP);
392 switch(optname)
394 DEBUG_SOCKOPT(WS_IP_ADD_MEMBERSHIP);
395 DEBUG_SOCKOPT(WS_IP_DROP_MEMBERSHIP);
396 DEBUG_SOCKOPT(WS_IP_HDRINCL);
397 DEBUG_SOCKOPT(WS_IP_MULTICAST_IF);
398 DEBUG_SOCKOPT(WS_IP_MULTICAST_LOOP);
399 DEBUG_SOCKOPT(WS_IP_MULTICAST_TTL);
400 DEBUG_SOCKOPT(WS_IP_OPTIONS);
401 DEBUG_SOCKOPT(WS_IP_PKTINFO);
402 DEBUG_SOCKOPT(WS_IP_TOS);
403 DEBUG_SOCKOPT(WS_IP_TTL);
404 DEBUG_SOCKOPT(WS_IP_UNICAST_IF);
405 DEBUG_SOCKOPT(WS_IP_DONTFRAGMENT);
407 break;
409 DEBUG_SOCKLEVEL(WS_IPPROTO_IPV6);
410 switch(optname)
412 DEBUG_SOCKOPT(WS_IPV6_ADD_MEMBERSHIP);
413 DEBUG_SOCKOPT(WS_IPV6_DROP_MEMBERSHIP);
414 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_IF);
415 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_HOPS);
416 DEBUG_SOCKOPT(WS_IPV6_MULTICAST_LOOP);
417 DEBUG_SOCKOPT(WS_IPV6_UNICAST_HOPS);
418 DEBUG_SOCKOPT(WS_IPV6_V6ONLY);
419 DEBUG_SOCKOPT(WS_IPV6_UNICAST_IF);
420 DEBUG_SOCKOPT(WS_IPV6_DONTFRAG);
422 break;
424 #undef DEBUG_SOCKLEVEL
425 #undef DEBUG_SOCKOPT
427 if (!strlevel)
428 strlevel = wine_dbg_sprintf("WS_0x%x", level);
429 if (!stropt)
430 stropt = wine_dbg_sprintf("WS_0x%x", optname);
432 return wine_dbg_sprintf("level %s, name %s", strlevel + 3, stropt + 3);
435 static inline const char *debugstr_optval(const char *optval, int optlenval)
437 if (optval && !IS_INTRESOURCE(optval) && optlenval >= 1 && optlenval <= sizeof(DWORD))
439 DWORD value = 0;
440 memcpy(&value, optval, optlenval);
441 return wine_dbg_sprintf("%p (%u)", optval, value);
443 return wine_dbg_sprintf("%p", optval);
446 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
447 #define SOCKET2HANDLE(s) ((HANDLE)(s))
448 #define HANDLE2SOCKET(h) ((SOCKET)(h))
450 /****************************************************************
451 * Async IO declarations
452 ****************************************************************/
454 struct ws2_async_io
456 struct ws2_async_io *next;
459 struct ws2_async_shutdown
461 struct ws2_async_io io;
462 HANDLE hSocket;
463 IO_STATUS_BLOCK iosb;
464 int type;
467 struct ws2_async
469 struct ws2_async_io io;
470 HANDLE hSocket;
471 LPWSAOVERLAPPED user_overlapped;
472 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
473 IO_STATUS_BLOCK local_iosb;
474 struct WS_sockaddr *addr;
475 union
477 int val; /* for send operations */
478 int *ptr; /* for recv operations */
479 } addrlen;
480 DWORD flags;
481 DWORD *lpFlags;
482 WSABUF *control;
483 unsigned int n_iovecs;
484 unsigned int first_iovec;
485 struct iovec iovec[1];
488 struct ws2_accept_async
490 struct ws2_async_io io;
491 HANDLE listen_socket;
492 HANDLE accept_socket;
493 LPOVERLAPPED user_overlapped;
494 ULONG_PTR cvalue;
495 PVOID buf; /* buffer to write data to */
496 int data_len;
497 int local_len;
498 int remote_len;
499 struct ws2_async *read;
502 static struct ws2_async_io *async_io_freelist;
504 static void release_async_io( struct ws2_async_io *io )
506 for (;;)
508 struct ws2_async_io *next = async_io_freelist;
509 io->next = next;
510 if (InterlockedCompareExchangePointer( (void **)&async_io_freelist, io, next ) == next) return;
514 static struct ws2_async_io *alloc_async_io( DWORD size )
516 /* first free remaining previous fileinfos */
518 struct ws2_async_io *io = InterlockedExchangePointer( (void **)&async_io_freelist, NULL );
520 while (io)
522 struct ws2_async_io *next = io->next;
523 HeapFree( GetProcessHeap(), 0, io );
524 io = next;
527 return HeapAlloc( GetProcessHeap(), 0, size );
530 /****************************************************************/
532 /* ----------------------------------- internal data */
534 /* ws_... struct conversion flags */
536 typedef struct /* WSAAsyncSelect() control struct */
538 HANDLE service, event, sock;
539 HWND hWnd;
540 UINT uMsg;
541 LONG lEvent;
542 } ws_select_info;
544 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
545 #define WS_MAX_UDP_DATAGRAM 1024
546 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
548 /* hostent's, servent's and protent's are stored in one buffer per thread,
549 * as documented on MSDN for the functions that return any of the buffers */
550 struct per_thread_data
552 int opentype;
553 struct WS_hostent *he_buffer;
554 struct WS_servent *se_buffer;
555 struct WS_protoent *pe_buffer;
556 int he_len;
557 int se_len;
558 int pe_len;
559 char ntoa_buffer[16]; /* 4*3 digits + 3 '.' + 1 '\0' */
562 /* internal: routing description information */
563 struct route {
564 struct in_addr addr;
565 IF_INDEX interface;
566 DWORD metric;
569 static INT num_startup; /* reference counter */
570 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
572 /* function prototypes */
573 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length);
574 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
575 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
576 static struct WS_servent *WS_dup_se(const struct servent* p_se);
577 static int ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size);
579 int WSAIOCTL_GetInterfaceCount(void);
580 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
582 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus, ULONG Information );
584 #define MAP_OPTION(opt) { WS_##opt, opt }
586 static const int ws_flags_map[][2] =
588 MAP_OPTION( MSG_OOB ),
589 MAP_OPTION( MSG_PEEK ),
590 MAP_OPTION( MSG_DONTROUTE ),
591 MAP_OPTION( MSG_WAITALL ),
594 static const int ws_sock_map[][2] =
596 MAP_OPTION( SO_DEBUG ),
597 MAP_OPTION( SO_ACCEPTCONN ),
598 MAP_OPTION( SO_REUSEADDR ),
599 MAP_OPTION( SO_KEEPALIVE ),
600 MAP_OPTION( SO_DONTROUTE ),
601 MAP_OPTION( SO_BROADCAST ),
602 MAP_OPTION( SO_LINGER ),
603 MAP_OPTION( SO_OOBINLINE ),
604 MAP_OPTION( SO_SNDBUF ),
605 MAP_OPTION( SO_RCVBUF ),
606 MAP_OPTION( SO_ERROR ),
607 MAP_OPTION( SO_TYPE ),
608 #ifdef SO_RCVTIMEO
609 MAP_OPTION( SO_RCVTIMEO ),
610 #endif
611 #ifdef SO_SNDTIMEO
612 MAP_OPTION( SO_SNDTIMEO ),
613 #endif
616 static const int ws_tcp_map[][2] =
618 #ifdef TCP_NODELAY
619 MAP_OPTION( TCP_NODELAY ),
620 #endif
623 static const int ws_ip_map[][2] =
625 MAP_OPTION( IP_MULTICAST_IF ),
626 MAP_OPTION( IP_MULTICAST_TTL ),
627 MAP_OPTION( IP_MULTICAST_LOOP ),
628 MAP_OPTION( IP_ADD_MEMBERSHIP ),
629 MAP_OPTION( IP_DROP_MEMBERSHIP ),
630 MAP_OPTION( IP_OPTIONS ),
631 #ifdef IP_HDRINCL
632 MAP_OPTION( IP_HDRINCL ),
633 #endif
634 MAP_OPTION( IP_TOS ),
635 MAP_OPTION( IP_TTL ),
636 #ifdef IP_PKTINFO
637 MAP_OPTION( IP_PKTINFO ),
638 #endif
639 #ifdef IP_UNICAST_IF
640 MAP_OPTION( IP_UNICAST_IF ),
641 #endif
644 static const int ws_ipv6_map[][2] =
646 #ifdef IPV6_ADD_MEMBERSHIP
647 MAP_OPTION( IPV6_ADD_MEMBERSHIP ),
648 #endif
649 #ifdef IPV6_DROP_MEMBERSHIP
650 MAP_OPTION( IPV6_DROP_MEMBERSHIP ),
651 #endif
652 MAP_OPTION( IPV6_MULTICAST_IF ),
653 MAP_OPTION( IPV6_MULTICAST_HOPS ),
654 MAP_OPTION( IPV6_MULTICAST_LOOP ),
655 MAP_OPTION( IPV6_UNICAST_HOPS ),
656 MAP_OPTION( IPV6_V6ONLY ),
657 #ifdef IPV6_UNICAST_IF
658 MAP_OPTION( IPV6_UNICAST_IF ),
659 #endif
662 static const int ws_af_map[][2] =
664 MAP_OPTION( AF_UNSPEC ),
665 MAP_OPTION( AF_INET ),
666 MAP_OPTION( AF_INET6 ),
667 #ifdef HAS_IPX
668 MAP_OPTION( AF_IPX ),
669 #endif
670 #ifdef AF_IRDA
671 MAP_OPTION( AF_IRDA ),
672 #endif
673 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
676 static const int ws_socktype_map[][2] =
678 MAP_OPTION( SOCK_DGRAM ),
679 MAP_OPTION( SOCK_STREAM ),
680 MAP_OPTION( SOCK_RAW ),
681 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
684 static const int ws_proto_map[][2] =
686 MAP_OPTION( IPPROTO_IP ),
687 MAP_OPTION( IPPROTO_TCP ),
688 MAP_OPTION( IPPROTO_UDP ),
689 MAP_OPTION( IPPROTO_ICMP ),
690 MAP_OPTION( IPPROTO_IGMP ),
691 MAP_OPTION( IPPROTO_RAW ),
692 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
695 static const int ws_aiflag_map[][2] =
697 MAP_OPTION( AI_PASSIVE ),
698 MAP_OPTION( AI_CANONNAME ),
699 MAP_OPTION( AI_NUMERICHOST ),
700 #ifdef AI_NUMERICSERV
701 MAP_OPTION( AI_NUMERICSERV ),
702 #endif
703 #ifdef AI_V4MAPPED
704 MAP_OPTION( AI_V4MAPPED ),
705 #endif
706 MAP_OPTION( AI_ADDRCONFIG ),
709 static const int ws_niflag_map[][2] =
711 MAP_OPTION( NI_NOFQDN ),
712 MAP_OPTION( NI_NUMERICHOST ),
713 MAP_OPTION( NI_NAMEREQD ),
714 MAP_OPTION( NI_NUMERICSERV ),
715 MAP_OPTION( NI_DGRAM ),
718 static const int ws_eai_map[][2] =
720 MAP_OPTION( EAI_AGAIN ),
721 MAP_OPTION( EAI_BADFLAGS ),
722 MAP_OPTION( EAI_FAIL ),
723 MAP_OPTION( EAI_FAMILY ),
724 MAP_OPTION( EAI_MEMORY ),
725 /* Note: EAI_NODATA is deprecated, but still
726 * used by Windows and Linux... We map the newer
727 * EAI_NONAME to EAI_NODATA for now until Windows
728 * changes too.
730 #ifdef EAI_NODATA
731 MAP_OPTION( EAI_NODATA ),
732 #endif
733 #ifdef EAI_NONAME
734 { WS_EAI_NODATA, EAI_NONAME },
735 #endif
737 MAP_OPTION( EAI_SERVICE ),
738 MAP_OPTION( EAI_SOCKTYPE ),
739 { 0, 0 }
742 static const char magic_loopback_addr[] = {127, 12, 34, 56};
744 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
745 #ifdef IP_PKTINFO
746 static inline WSACMSGHDR *fill_control_message(int level, int type, WSACMSGHDR *current, ULONG *maxsize, void *data, int len)
748 ULONG msgsize = sizeof(WSACMSGHDR) + WSA_CMSG_ALIGN(len);
749 char *ptr = (char *) current + sizeof(WSACMSGHDR);
751 /* Make sure there is at least enough room for this entry */
752 if (msgsize > *maxsize)
753 return NULL;
754 *maxsize -= msgsize;
755 /* Fill in the entry */
756 current->cmsg_len = sizeof(WSACMSGHDR) + len;
757 current->cmsg_level = level;
758 current->cmsg_type = type;
759 memcpy(ptr, data, len);
760 /* Return the pointer to where next entry should go */
761 return (WSACMSGHDR *) (ptr + WSA_CMSG_ALIGN(len));
763 #endif /* IP_PKTINFO */
765 static inline int convert_control_headers(struct msghdr *hdr, WSABUF *control)
767 #ifdef IP_PKTINFO
768 WSACMSGHDR *cmsg_win = (WSACMSGHDR *) control->buf, *ptr;
769 ULONG ctlsize = control->len;
770 struct cmsghdr *cmsg_unix;
772 ptr = cmsg_win;
773 /* Loop over all the headers, converting as appropriate */
774 for (cmsg_unix = CMSG_FIRSTHDR(hdr); cmsg_unix != NULL; cmsg_unix = CMSG_NXTHDR(hdr, cmsg_unix))
776 switch(cmsg_unix->cmsg_level)
778 case IPPROTO_IP:
779 switch(cmsg_unix->cmsg_type)
781 case IP_PKTINFO:
783 /* Convert the Unix IP_PKTINFO structure to the Windows version */
784 struct in_pktinfo *data_unix = (struct in_pktinfo *) CMSG_DATA(cmsg_unix);
785 struct WS_in_pktinfo data_win;
787 memcpy(&data_win.ipi_addr,&data_unix->ipi_addr.s_addr,4); /* 4 bytes = 32 address bits */
788 data_win.ipi_ifindex = data_unix->ipi_ifindex;
789 ptr = fill_control_message(WS_IPPROTO_IP, WS_IP_PKTINFO, ptr, &ctlsize,
790 (void*)&data_win, sizeof(data_win));
791 if (!ptr) goto error;
792 } break;
793 default:
794 FIXME("Unhandled IPPROTO_IP message header type %d\n", cmsg_unix->cmsg_type);
795 break;
797 break;
798 default:
799 FIXME("Unhandled message header level %d\n", cmsg_unix->cmsg_level);
800 break;
804 error:
805 /* Set the length of the returned control headers */
806 control->len = (ptr == NULL ? 0 : (char*)ptr - (char*)cmsg_win);
807 return (ptr != NULL);
808 #else /* IP_PKTINFO */
809 control->len = 0;
810 return 1;
811 #endif /* IP_PKTINFO */
813 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
815 /* ----------------------------------- error handling */
817 static NTSTATUS sock_get_ntstatus( int err )
819 switch ( err )
821 case EBADF: return STATUS_INVALID_HANDLE;
822 case EBUSY: return STATUS_DEVICE_BUSY;
823 case EPERM:
824 case EACCES: return STATUS_ACCESS_DENIED;
825 case EFAULT: return STATUS_NO_MEMORY;
826 case EINVAL: return STATUS_INVALID_PARAMETER;
827 case ENFILE:
828 case EMFILE: return STATUS_TOO_MANY_OPENED_FILES;
829 case EWOULDBLOCK: return STATUS_CANT_WAIT;
830 case EINPROGRESS: return STATUS_PENDING;
831 case EALREADY: return STATUS_NETWORK_BUSY;
832 case ENOTSOCK: return STATUS_OBJECT_TYPE_MISMATCH;
833 case EDESTADDRREQ: return STATUS_INVALID_PARAMETER;
834 case EMSGSIZE: return STATUS_BUFFER_OVERFLOW;
835 case EPROTONOSUPPORT:
836 case ESOCKTNOSUPPORT:
837 case EPFNOSUPPORT:
838 case EAFNOSUPPORT:
839 case EPROTOTYPE: return STATUS_NOT_SUPPORTED;
840 case ENOPROTOOPT: return STATUS_INVALID_PARAMETER;
841 case EOPNOTSUPP: return STATUS_NOT_SUPPORTED;
842 case EADDRINUSE: return STATUS_ADDRESS_ALREADY_ASSOCIATED;
843 case EADDRNOTAVAIL: return STATUS_INVALID_PARAMETER;
844 case ECONNREFUSED: return STATUS_CONNECTION_REFUSED;
845 case ESHUTDOWN: return STATUS_PIPE_DISCONNECTED;
846 case ENOTCONN: return STATUS_CONNECTION_DISCONNECTED;
847 case ETIMEDOUT: return STATUS_IO_TIMEOUT;
848 case ENETUNREACH: return STATUS_NETWORK_UNREACHABLE;
849 case ENETDOWN: return STATUS_NETWORK_BUSY;
850 case EPIPE:
851 case ECONNRESET: return STATUS_CONNECTION_RESET;
852 case ECONNABORTED: return STATUS_CONNECTION_ABORTED;
854 case 0: return STATUS_SUCCESS;
855 default:
856 WARN("Unknown errno %d!\n", err);
857 return STATUS_UNSUCCESSFUL;
861 static UINT sock_get_error( int err )
863 switch(err)
865 case EINTR: return WSAEINTR;
866 case EBADF: return WSAEBADF;
867 case EPERM:
868 case EACCES: return WSAEACCES;
869 case EFAULT: return WSAEFAULT;
870 case EINVAL: return WSAEINVAL;
871 case EMFILE: return WSAEMFILE;
872 case EWOULDBLOCK: return WSAEWOULDBLOCK;
873 case EINPROGRESS: return WSAEINPROGRESS;
874 case EALREADY: return WSAEALREADY;
875 case ENOTSOCK: return WSAENOTSOCK;
876 case EDESTADDRREQ: return WSAEDESTADDRREQ;
877 case EMSGSIZE: return WSAEMSGSIZE;
878 case EPROTOTYPE: return WSAEPROTOTYPE;
879 case ENOPROTOOPT: return WSAENOPROTOOPT;
880 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
881 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
882 case EOPNOTSUPP: return WSAEOPNOTSUPP;
883 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
884 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
885 case EADDRINUSE: return WSAEADDRINUSE;
886 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
887 case ENETDOWN: return WSAENETDOWN;
888 case ENETUNREACH: return WSAENETUNREACH;
889 case ENETRESET: return WSAENETRESET;
890 case ECONNABORTED: return WSAECONNABORTED;
891 case EPIPE:
892 case ECONNRESET: return WSAECONNRESET;
893 case ENOBUFS: return WSAENOBUFS;
894 case EISCONN: return WSAEISCONN;
895 case ENOTCONN: return WSAENOTCONN;
896 case ESHUTDOWN: return WSAESHUTDOWN;
897 case ETOOMANYREFS: return WSAETOOMANYREFS;
898 case ETIMEDOUT: return WSAETIMEDOUT;
899 case ECONNREFUSED: return WSAECONNREFUSED;
900 case ELOOP: return WSAELOOP;
901 case ENAMETOOLONG: return WSAENAMETOOLONG;
902 case EHOSTDOWN: return WSAEHOSTDOWN;
903 case EHOSTUNREACH: return WSAEHOSTUNREACH;
904 case ENOTEMPTY: return WSAENOTEMPTY;
905 #ifdef EPROCLIM
906 case EPROCLIM: return WSAEPROCLIM;
907 #endif
908 #ifdef EUSERS
909 case EUSERS: return WSAEUSERS;
910 #endif
911 #ifdef EDQUOT
912 case EDQUOT: return WSAEDQUOT;
913 #endif
914 #ifdef ESTALE
915 case ESTALE: return WSAESTALE;
916 #endif
917 #ifdef EREMOTE
918 case EREMOTE: return WSAEREMOTE;
919 #endif
921 /* just in case we ever get here and there are no problems */
922 case 0: return 0;
923 default:
924 WARN("Unknown errno %d!\n", err);
925 return WSAEOPNOTSUPP;
929 static UINT wsaErrno(void)
931 int loc_errno = errno;
932 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
934 return sock_get_error( loc_errno );
937 /* most ws2 overlapped functions return an ntstatus-based error code */
938 static NTSTATUS wsaErrStatus(void)
940 int loc_errno = errno;
941 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
943 return sock_get_ntstatus(loc_errno);
946 static UINT wsaHerrno(int loc_errno)
948 WARN("h_errno %d.\n", loc_errno);
950 switch(loc_errno)
952 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
953 case TRY_AGAIN: return WSATRY_AGAIN;
954 case NO_RECOVERY: return WSANO_RECOVERY;
955 case NO_DATA: return WSANO_DATA;
956 case ENOBUFS: return WSAENOBUFS;
958 case 0: return 0;
959 default:
960 WARN("Unknown h_errno %d!\n", loc_errno);
961 return WSAEOPNOTSUPP;
965 static inline DWORD NtStatusToWSAError( const DWORD status )
967 /* We only need to cover the status codes set by server async request handling */
968 DWORD wserr;
969 switch ( status )
971 case STATUS_SUCCESS: wserr = 0; break;
972 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
973 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
974 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
975 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
976 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
977 case STATUS_NETWORK_BUSY: wserr = WSAEALREADY; break;
978 case STATUS_NETWORK_UNREACHABLE: wserr = WSAENETUNREACH; break;
979 case STATUS_CONNECTION_REFUSED: wserr = WSAECONNREFUSED; break;
980 case STATUS_CONNECTION_DISCONNECTED: wserr = WSAENOTCONN; break;
981 case STATUS_CONNECTION_RESET: wserr = WSAECONNRESET; break;
982 case STATUS_CONNECTION_ABORTED: wserr = WSAECONNABORTED; break;
983 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
984 case STATUS_ADDRESS_ALREADY_ASSOCIATED: wserr = WSAEADDRINUSE; break;
985 case STATUS_IO_TIMEOUT:
986 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
987 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
988 case STATUS_ACCESS_DENIED: wserr = WSAEACCES; break;
989 case STATUS_TOO_MANY_OPENED_FILES: wserr = WSAEMFILE; break;
990 case STATUS_CANT_WAIT: wserr = WSAEWOULDBLOCK; break;
991 case STATUS_BUFFER_OVERFLOW: wserr = WSAEMSGSIZE; break;
992 case STATUS_NOT_SUPPORTED: wserr = WSAEOPNOTSUPP; break;
993 case STATUS_HOST_UNREACHABLE: wserr = WSAEHOSTUNREACH; break;
995 default:
996 wserr = RtlNtStatusToDosError( status );
997 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
999 return wserr;
1002 /* set last error code from NT status without mapping WSA errors */
1003 static inline unsigned int set_error( unsigned int err )
1005 if (err)
1007 err = NtStatusToWSAError( err );
1008 SetLastError( err );
1010 return err;
1013 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
1015 int fd;
1016 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
1017 return -1;
1018 return fd;
1021 static inline void release_sock_fd( SOCKET s, int fd )
1023 wine_server_release_fd( SOCKET2HANDLE(s), fd );
1026 static void _enable_event( HANDLE s, unsigned int event,
1027 unsigned int sstate, unsigned int cstate )
1029 SERVER_START_REQ( enable_socket_event )
1031 req->handle = wine_server_obj_handle( s );
1032 req->mask = event;
1033 req->sstate = sstate;
1034 req->cstate = cstate;
1035 wine_server_call( req );
1037 SERVER_END_REQ;
1040 static NTSTATUS _is_blocking(SOCKET s, BOOL *ret)
1042 NTSTATUS status;
1043 SERVER_START_REQ( get_socket_event )
1045 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1046 req->service = FALSE;
1047 req->c_event = 0;
1048 status = wine_server_call( req );
1049 *ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
1051 SERVER_END_REQ;
1052 return status;
1055 static unsigned int _get_sock_mask(SOCKET s)
1057 unsigned int ret;
1058 SERVER_START_REQ( get_socket_event )
1060 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1061 req->service = FALSE;
1062 req->c_event = 0;
1063 wine_server_call( req );
1064 ret = reply->mask;
1066 SERVER_END_REQ;
1067 return ret;
1070 static void _sync_sock_state(SOCKET s)
1072 BOOL dummy;
1073 /* do a dummy wineserver request in order to let
1074 the wineserver run through its select loop once */
1075 (void)_is_blocking(s, &dummy);
1078 static void _get_sock_errors(SOCKET s, int *events)
1080 SERVER_START_REQ( get_socket_event )
1082 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1083 req->service = FALSE;
1084 req->c_event = 0;
1085 wine_server_set_reply( req, events, sizeof(int) * FD_MAX_EVENTS );
1086 wine_server_call( req );
1088 SERVER_END_REQ;
1091 static int _get_sock_error(SOCKET s, unsigned int bit)
1093 int events[FD_MAX_EVENTS];
1094 _get_sock_errors(s, events);
1095 return events[bit];
1098 static struct per_thread_data *get_per_thread_data(void)
1100 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
1101 /* lazy initialization */
1102 if (!ptb)
1104 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
1105 NtCurrentTeb()->WinSockData = ptb;
1107 return ptb;
1110 static void free_per_thread_data(void)
1112 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
1114 if (!ptb) return;
1116 /* delete scratch buffers */
1117 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1118 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1119 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1120 ptb->he_buffer = NULL;
1121 ptb->se_buffer = NULL;
1122 ptb->pe_buffer = NULL;
1124 HeapFree( GetProcessHeap(), 0, ptb );
1125 NtCurrentTeb()->WinSockData = NULL;
1128 /***********************************************************************
1129 * DllMain (WS2_32.init)
1131 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
1133 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
1134 switch (fdwReason) {
1135 case DLL_PROCESS_ATTACH:
1136 break;
1137 case DLL_PROCESS_DETACH:
1138 if (fImpLoad) break;
1139 free_per_thread_data();
1140 DeleteCriticalSection(&csWSgetXXXbyYYY);
1141 break;
1142 case DLL_THREAD_DETACH:
1143 free_per_thread_data();
1144 break;
1146 return TRUE;
1149 /***********************************************************************
1150 * convert_flags()
1152 * Converts send/recv flags from Windows format.
1153 * Return the converted flag bits, unsupported flags remain unchanged.
1155 static int convert_flags(int flags)
1157 int i, out;
1158 if (!flags) return 0;
1160 for (out = i = 0; flags && i < sizeof(ws_flags_map) / sizeof(ws_flags_map[0]); i++)
1162 if (ws_flags_map[i][0] & flags)
1164 out |= ws_flags_map[i][1];
1165 flags &= ~ws_flags_map[i][0];
1168 if (flags)
1170 FIXME("Unknown send/recv flags 0x%x, using anyway...\n", flags);
1171 out |= flags;
1173 return out;
1176 /***********************************************************************
1177 * convert_sockopt()
1179 * Converts socket flags from Windows format.
1180 * Return 1 if converted, 0 if not (error).
1182 static int convert_sockopt(INT *level, INT *optname)
1184 unsigned int i;
1185 switch (*level)
1187 case WS_SOL_SOCKET:
1188 *level = SOL_SOCKET;
1189 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
1190 if( ws_sock_map[i][0] == *optname )
1192 *optname = ws_sock_map[i][1];
1193 return 1;
1196 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
1197 break;
1198 case WS_IPPROTO_TCP:
1199 *level = IPPROTO_TCP;
1200 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
1201 if ( ws_tcp_map[i][0] == *optname )
1203 *optname = ws_tcp_map[i][1];
1204 return 1;
1207 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
1208 break;
1209 case WS_IPPROTO_IP:
1210 *level = IPPROTO_IP;
1211 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
1212 if (ws_ip_map[i][0] == *optname )
1214 *optname = ws_ip_map[i][1];
1215 return 1;
1218 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
1219 break;
1220 case WS_IPPROTO_IPV6:
1221 *level = IPPROTO_IPV6;
1222 for(i=0; i<sizeof(ws_ipv6_map)/sizeof(ws_ipv6_map[0]); i++) {
1223 if (ws_ipv6_map[i][0] == *optname )
1225 *optname = ws_ipv6_map[i][1];
1226 return 1;
1229 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname);
1230 break;
1231 default: FIXME("Unimplemented or unknown socket level\n");
1233 return 0;
1236 /* ----------------------------------- Per-thread info (or per-process?) */
1238 static char *strdup_lower(const char *str)
1240 int i;
1241 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
1243 if (ret)
1245 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
1246 ret[i] = 0;
1248 else SetLastError(WSAENOBUFS);
1249 return ret;
1252 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
1253 * from an fd and return the value converted to milli seconds
1254 * or -1 if there is an infinite time out */
1255 static inline int get_rcvsnd_timeo( int fd, int optname)
1257 struct timeval tv;
1258 socklen_t len = sizeof(tv);
1259 int ret = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
1260 if( ret >= 0)
1261 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
1262 if( ret <= 0 ) /* tv == {0,0} means infinite time out */
1263 return -1;
1264 return ret;
1267 /* macro wrappers for portability */
1268 #ifdef SO_RCVTIMEO
1269 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
1270 #else
1271 #define GET_RCVTIMEO(fd) (-1)
1272 #endif
1274 #ifdef SO_SNDTIMEO
1275 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
1276 #else
1277 #define GET_SNDTIMEO(fd) (-1)
1278 #endif
1280 /* utility: given an fd, will block until one of the events occurs */
1281 static inline int do_block( int fd, int events, int timeout )
1283 struct pollfd pfd;
1284 int ret;
1286 pfd.fd = fd;
1287 pfd.events = events;
1289 while ((ret = poll(&pfd, 1, timeout)) < 0)
1291 if (errno != EINTR)
1292 return -1;
1294 if( ret == 0 )
1295 return 0;
1296 return pfd.revents;
1299 static int
1300 convert_af_w2u(int windowsaf) {
1301 unsigned int i;
1303 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1304 if (ws_af_map[i][0] == windowsaf)
1305 return ws_af_map[i][1];
1306 FIXME("unhandled Windows address family %d\n", windowsaf);
1307 return -1;
1310 static int
1311 convert_af_u2w(int unixaf) {
1312 unsigned int i;
1314 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1315 if (ws_af_map[i][1] == unixaf)
1316 return ws_af_map[i][0];
1317 FIXME("unhandled UNIX address family %d\n", unixaf);
1318 return -1;
1321 static int
1322 convert_proto_w2u(int windowsproto) {
1323 unsigned int i;
1325 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1326 if (ws_proto_map[i][0] == windowsproto)
1327 return ws_proto_map[i][1];
1329 /* check for extended IPX */
1330 if (IS_IPX_PROTO(windowsproto))
1331 return windowsproto;
1333 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
1334 return -1;
1337 static int
1338 convert_proto_u2w(int unixproto) {
1339 unsigned int i;
1341 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1342 if (ws_proto_map[i][1] == unixproto)
1343 return ws_proto_map[i][0];
1345 /* if value is inside IPX range just return it - the kernel simply
1346 * echoes the value used in the socket() function */
1347 if (IS_IPX_PROTO(unixproto))
1348 return unixproto;
1350 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
1351 return -1;
1354 static int
1355 convert_socktype_w2u(int windowssocktype) {
1356 unsigned int i;
1358 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1359 if (ws_socktype_map[i][0] == windowssocktype)
1360 return ws_socktype_map[i][1];
1361 FIXME("unhandled Windows socket type %d\n", windowssocktype);
1362 return -1;
1365 static int
1366 convert_socktype_u2w(int unixsocktype) {
1367 unsigned int i;
1369 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1370 if (ws_socktype_map[i][1] == unixsocktype)
1371 return ws_socktype_map[i][0];
1372 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
1373 return -1;
1376 static int set_ipx_packettype(int sock, int ptype)
1378 #ifdef HAS_IPX
1379 int fd = get_sock_fd( sock, 0, NULL ), ret = 0;
1380 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", ptype, fd);
1382 if (fd == -1) return SOCKET_ERROR;
1384 /* We try to set the ipx type on ipx socket level. */
1385 #ifdef SOL_IPX
1386 if(setsockopt(fd, SOL_IPX, IPX_TYPE, &ptype, sizeof(ptype)) == -1)
1388 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
1389 ret = SOCKET_ERROR;
1391 #else
1393 struct ipx val;
1394 /* Should we retrieve val using a getsockopt call and then
1395 * set the modified one? */
1396 val.ipx_pt = ptype;
1397 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
1399 #endif
1400 release_sock_fd( sock, fd );
1401 return ret;
1402 #else
1403 WARN("IPX support is not enabled, can't set packet type\n");
1404 return SOCKET_ERROR;
1405 #endif
1408 /* ----------------------------------- API -----
1410 * Init / cleanup / error checking.
1413 /***********************************************************************
1414 * WSAStartup (WS2_32.115)
1416 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
1418 TRACE("verReq=%x\n", wVersionRequested);
1420 if (LOBYTE(wVersionRequested) < 1)
1421 return WSAVERNOTSUPPORTED;
1423 if (!lpWSAData) return WSAEINVAL;
1425 num_startup++;
1427 /* that's the whole of the negotiation for now */
1428 lpWSAData->wVersion = wVersionRequested;
1429 /* return winsock information */
1430 lpWSAData->wHighVersion = 0x0202;
1431 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
1432 strcpy(lpWSAData->szSystemStatus, "Running" );
1433 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
1434 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
1435 /* don't do anything with lpWSAData->lpVendorInfo */
1436 /* (some apps don't allocate the space for this field) */
1438 TRACE("succeeded starts: %d\n", num_startup);
1439 return 0;
1443 /***********************************************************************
1444 * WSACleanup (WS2_32.116)
1446 INT WINAPI WSACleanup(void)
1448 if (num_startup) {
1449 num_startup--;
1450 TRACE("pending cleanups: %d\n", num_startup);
1451 return 0;
1453 SetLastError(WSANOTINITIALISED);
1454 return SOCKET_ERROR;
1458 /***********************************************************************
1459 * WSAGetLastError (WS2_32.111)
1461 INT WINAPI WSAGetLastError(void)
1463 return GetLastError();
1466 /***********************************************************************
1467 * WSASetLastError (WS2_32.112)
1469 void WINAPI WSASetLastError(INT iError) {
1470 SetLastError(iError);
1473 static struct WS_hostent *check_buffer_he(int size)
1475 struct per_thread_data * ptb = get_per_thread_data();
1476 if (ptb->he_buffer)
1478 if (ptb->he_len >= size ) return ptb->he_buffer;
1479 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1481 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
1482 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
1483 return ptb->he_buffer;
1486 static struct WS_servent *check_buffer_se(int size)
1488 struct per_thread_data * ptb = get_per_thread_data();
1489 if (ptb->se_buffer)
1491 if (ptb->se_len >= size ) return ptb->se_buffer;
1492 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1494 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
1495 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
1496 return ptb->se_buffer;
1499 static struct WS_protoent *check_buffer_pe(int size)
1501 struct per_thread_data * ptb = get_per_thread_data();
1502 if (ptb->pe_buffer)
1504 if (ptb->pe_len >= size ) return ptb->pe_buffer;
1505 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1507 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
1508 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
1509 return ptb->pe_buffer;
1512 /* ----------------------------------- i/o APIs */
1514 static inline BOOL supported_pf(int pf)
1516 switch (pf)
1518 case WS_AF_INET:
1519 case WS_AF_INET6:
1520 return TRUE;
1521 #ifdef HAS_IPX
1522 case WS_AF_IPX:
1523 return TRUE;
1524 #endif
1525 #ifdef HAS_IRDA
1526 case WS_AF_IRDA:
1527 return TRUE;
1528 #endif
1529 default:
1530 return FALSE;
1534 static inline BOOL supported_protocol(int protocol)
1536 int i;
1537 for (i = 0; i < sizeof(valid_protocols) / sizeof(valid_protocols[0]); i++)
1538 if (protocol == valid_protocols[i])
1539 return TRUE;
1540 return FALSE;
1543 /**********************************************************************/
1545 /* Returns the length of the converted address if successful, 0 if it was too small to
1546 * start with.
1548 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
1549 union generic_unix_sockaddr *uaddr)
1551 unsigned int uaddrlen = 0;
1553 switch (wsaddr->sa_family)
1555 #ifdef HAS_IPX
1556 case WS_AF_IPX:
1558 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
1559 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
1561 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
1562 return 0;
1564 uaddrlen = sizeof(struct sockaddr_ipx);
1565 memset( uaddr, 0, uaddrlen );
1566 uipx->sipx_family=AF_IPX;
1567 uipx->sipx_port=wsipx->sa_socket;
1568 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1569 * in one go
1571 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
1572 #ifdef IPX_FRAME_NONE
1573 uipx->sipx_type=IPX_FRAME_NONE;
1574 #endif
1575 break;
1577 #endif
1578 case WS_AF_INET6: {
1579 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
1580 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
1582 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1583 * scope_id, one without.
1585 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
1586 uaddrlen = sizeof(struct sockaddr_in6);
1587 memset( uaddr, 0, uaddrlen );
1588 uin6->sin6_family = AF_INET6;
1589 uin6->sin6_port = win6->sin6_port;
1590 uin6->sin6_flowinfo = win6->sin6_flowinfo;
1591 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1592 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
1593 #endif
1594 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
1595 break;
1597 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
1598 return 0;
1600 case WS_AF_INET: {
1601 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
1602 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
1604 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
1605 return 0;
1606 uaddrlen = sizeof(struct sockaddr_in);
1607 memset( uaddr, 0, uaddrlen );
1608 uin->sin_family = AF_INET;
1609 uin->sin_port = win->sin_port;
1610 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
1611 break;
1613 #ifdef HAS_IRDA
1614 case WS_AF_IRDA: {
1615 struct sockaddr_irda *uin = (struct sockaddr_irda *)uaddr;
1616 const SOCKADDR_IRDA *win = (const SOCKADDR_IRDA *)wsaddr;
1618 if (wsaddrlen < sizeof(SOCKADDR_IRDA))
1619 return 0;
1620 uaddrlen = sizeof(struct sockaddr_irda);
1621 memset( uaddr, 0, uaddrlen );
1622 uin->sir_family = AF_IRDA;
1623 if (!strncmp( win->irdaServiceName, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1625 unsigned int lsap_sel = 0;
1627 sscanf( win->irdaServiceName, "LSAP-SEL%u", &lsap_sel );
1628 uin->sir_lsap_sel = lsap_sel;
1630 else
1632 uin->sir_lsap_sel = LSAP_ANY;
1633 memcpy( uin->sir_name, win->irdaServiceName, 25 );
1635 memcpy( &uin->sir_addr, win->irdaDeviceID, sizeof(uin->sir_addr) );
1636 break;
1638 #endif
1639 case WS_AF_UNSPEC: {
1640 /* Try to determine the needed space by the passed windows sockaddr space */
1641 switch (wsaddrlen) {
1642 default: /* likely an ipv4 address */
1643 case sizeof(struct WS_sockaddr_in):
1644 uaddrlen = sizeof(struct sockaddr_in);
1645 break;
1646 #ifdef HAS_IPX
1647 case sizeof(struct WS_sockaddr_ipx):
1648 uaddrlen = sizeof(struct sockaddr_ipx);
1649 break;
1650 #endif
1651 #ifdef HAS_IRDA
1652 case sizeof(SOCKADDR_IRDA):
1653 uaddrlen = sizeof(struct sockaddr_irda);
1654 break;
1655 #endif
1656 case sizeof(struct WS_sockaddr_in6):
1657 case sizeof(struct WS_sockaddr_in6_old):
1658 uaddrlen = sizeof(struct sockaddr_in6);
1659 break;
1661 memset( uaddr, 0, uaddrlen );
1662 break;
1664 default:
1665 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
1666 return 0;
1668 return uaddrlen;
1671 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
1673 switch (uaddr->sa_family)
1675 #ifdef HAS_IPX
1676 case AF_IPX:
1678 static const struct sockaddr_ipx emptyAddr;
1679 struct sockaddr_ipx *ipx = (struct sockaddr_ipx*) uaddr;
1680 return ipx->sipx_port
1681 || memcmp(&ipx->sipx_network, &emptyAddr.sipx_network, sizeof(emptyAddr.sipx_network))
1682 || memcmp(&ipx->sipx_node, &emptyAddr.sipx_node, sizeof(emptyAddr.sipx_node));
1684 #endif
1685 case AF_INET6:
1687 static const struct sockaddr_in6 emptyAddr;
1688 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
1689 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
1691 case AF_INET:
1693 static const struct sockaddr_in emptyAddr;
1694 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
1695 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
1697 case AF_UNSPEC:
1698 return FALSE;
1699 default:
1700 FIXME("unknown address family %d\n", uaddr->sa_family);
1701 return TRUE;
1705 /* Returns -1 if getsockname fails, 0 if not bound, 1 otherwise */
1706 static int is_fd_bound(int fd, union generic_unix_sockaddr *uaddr, socklen_t *uaddrlen)
1708 union generic_unix_sockaddr inaddr;
1709 socklen_t inlen;
1710 int res;
1712 if (!uaddr) uaddr = &inaddr;
1713 if (!uaddrlen) uaddrlen = &inlen;
1715 *uaddrlen = sizeof(inaddr);
1716 res = getsockname(fd, &uaddr->addr, uaddrlen);
1717 if (!res) res = is_sockaddr_bound(&uaddr->addr, *uaddrlen);
1718 return res;
1721 /* Returns 0 if successful, -1 if the buffer is too small */
1722 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
1724 int res;
1726 switch(uaddr->sa_family)
1728 #ifdef HAS_IPX
1729 case AF_IPX:
1731 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
1732 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
1734 res=-1;
1735 switch (*wsaddrlen) /* how much can we copy? */
1737 default:
1738 res=0; /* enough */
1739 *wsaddrlen = sizeof(*wsipx);
1740 wsipx->sa_socket=uipx->sipx_port;
1741 /* fall through */
1742 case 13:
1743 case 12:
1744 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
1745 /* fall through */
1746 case 11:
1747 case 10:
1748 case 9:
1749 case 8:
1750 case 7:
1751 case 6:
1752 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1753 /* fall through */
1754 case 5:
1755 case 4:
1756 case 3:
1757 case 2:
1758 wsipx->sa_family=WS_AF_IPX;
1759 /* fall through */
1760 case 1:
1761 case 0:
1762 /* way too small */
1763 break;
1766 break;
1767 #endif
1768 #ifdef HAS_IRDA
1769 case AF_IRDA: {
1770 const struct sockaddr_irda *uin = (const struct sockaddr_irda *)uaddr;
1771 SOCKADDR_IRDA *win = (SOCKADDR_IRDA *)wsaddr;
1773 if (*wsaddrlen < sizeof(SOCKADDR_IRDA))
1774 return -1;
1775 win->irdaAddressFamily = WS_AF_IRDA;
1776 memcpy( win->irdaDeviceID, &uin->sir_addr, sizeof(win->irdaDeviceID) );
1777 if (uin->sir_lsap_sel != LSAP_ANY)
1778 sprintf( win->irdaServiceName, "LSAP-SEL%u", uin->sir_lsap_sel );
1779 else
1780 memcpy( win->irdaServiceName, uin->sir_name,
1781 sizeof(win->irdaServiceName) );
1782 return 0;
1784 #endif
1785 case AF_INET6: {
1786 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1787 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1789 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1790 return -1;
1791 win6old->sin6_family = WS_AF_INET6;
1792 win6old->sin6_port = uin6->sin6_port;
1793 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1794 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1795 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1796 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1797 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1798 win6->sin6_scope_id = uin6->sin6_scope_id;
1799 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1801 else
1802 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1803 #else
1804 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1805 #endif
1806 return 0;
1808 case AF_INET: {
1809 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1810 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1812 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1813 return -1;
1814 win->sin_family = WS_AF_INET;
1815 win->sin_port = uin->sin_port;
1816 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1817 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1818 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1819 return 0;
1821 case AF_UNSPEC: {
1822 memset(wsaddr,0,*wsaddrlen);
1823 return 0;
1825 default:
1826 FIXME("Unknown address family %d\n", uaddr->sa_family);
1827 return -1;
1829 return res;
1832 static INT WS_DuplicateSocket(BOOL unicode, SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo)
1834 HANDLE hProcess;
1835 int size;
1836 WSAPROTOCOL_INFOW infow;
1838 TRACE("(unicode %d, socket %04lx, processid %x, buffer %p)\n",
1839 unicode, s, dwProcessId, lpProtocolInfo);
1841 if (!ws_protocol_info(s, unicode, &infow, &size))
1842 return SOCKET_ERROR;
1844 if (!(hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId)))
1846 SetLastError(WSAEINVAL);
1847 return SOCKET_ERROR;
1850 if (!lpProtocolInfo)
1852 CloseHandle(hProcess);
1853 SetLastError(WSAEFAULT);
1854 return SOCKET_ERROR;
1857 /* I don't know what the real Windoze does next, this is a hack */
1858 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
1859 * the target use the global duplicate, or we could copy a reference to us to the structure
1860 * and let the target duplicate it from us, but let's do it as simple as possible */
1861 memcpy(lpProtocolInfo, &infow, size);
1862 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
1863 hProcess, (LPHANDLE)&lpProtocolInfo->dwServiceFlags3,
1864 0, FALSE, DUPLICATE_SAME_ACCESS);
1865 CloseHandle(hProcess);
1866 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
1867 return 0;
1870 /*****************************************************************************
1871 * WS_EnterSingleProtocolW [internal]
1873 * enters the protocol information of one given protocol into the given
1874 * buffer.
1876 * RETURNS
1877 * TRUE if a protocol was entered into the buffer.
1879 * BUGS
1880 * - only implemented for IPX, SPX, SPXII, TCP, UDP
1881 * - there is no check that the operating system supports the returned
1882 * protocols
1884 static BOOL WS_EnterSingleProtocolW( INT protocol, WSAPROTOCOL_INFOW* info )
1886 memset( info, 0, sizeof(WSAPROTOCOL_INFOW) );
1887 info->iProtocol = protocol;
1889 switch (protocol)
1891 case WS_IPPROTO_TCP:
1892 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_EXPEDITED_DATA |
1893 XP1_GRACEFUL_CLOSE | XP1_GUARANTEED_ORDER |
1894 XP1_GUARANTEED_DELIVERY;
1895 info->ProviderId = ProviderIdIP;
1896 info->dwCatalogEntryId = 0x3e9;
1897 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1898 info->ProtocolChain.ChainLen = 1;
1899 info->iVersion = 2;
1900 info->iAddressFamily = WS_AF_INET;
1901 info->iMaxSockAddr = 0x10;
1902 info->iMinSockAddr = 0x10;
1903 info->iSocketType = WS_SOCK_STREAM;
1904 strcpyW( info->szProtocol, NameTcpW );
1905 break;
1907 case WS_IPPROTO_UDP:
1908 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_SUPPORT_BROADCAST |
1909 XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED |
1910 XP1_CONNECTIONLESS;
1911 info->ProviderId = ProviderIdIP;
1912 info->dwCatalogEntryId = 0x3ea;
1913 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1914 info->ProtocolChain.ChainLen = 1;
1915 info->iVersion = 2;
1916 info->iAddressFamily = WS_AF_INET;
1917 info->iMaxSockAddr = 0x10;
1918 info->iMinSockAddr = 0x10;
1919 info->iSocketType = WS_SOCK_DGRAM;
1920 info->dwMessageSize = 0xffbb;
1921 strcpyW( info->szProtocol, NameUdpW );
1922 break;
1924 case WS_NSPROTO_IPX:
1925 info->dwServiceFlags1 = XP1_PARTIAL_MESSAGE | XP1_SUPPORT_BROADCAST |
1926 XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED |
1927 XP1_CONNECTIONLESS;
1928 info->ProviderId = ProviderIdIPX;
1929 info->dwCatalogEntryId = 0x406;
1930 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1931 info->ProtocolChain.ChainLen = 1;
1932 info->iVersion = 2;
1933 info->iAddressFamily = WS_AF_IPX;
1934 info->iMaxSockAddr = 0x10;
1935 info->iMinSockAddr = 0x0e;
1936 info->iSocketType = WS_SOCK_DGRAM;
1937 info->iProtocolMaxOffset = 0xff;
1938 info->dwMessageSize = 0x240;
1939 strcpyW( info->szProtocol, NameIpxW );
1940 break;
1942 case WS_NSPROTO_SPX:
1943 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_PSEUDO_STREAM |
1944 XP1_MESSAGE_ORIENTED | XP1_GUARANTEED_ORDER |
1945 XP1_GUARANTEED_DELIVERY;
1946 info->ProviderId = ProviderIdSPX;
1947 info->dwCatalogEntryId = 0x407;
1948 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1949 info->ProtocolChain.ChainLen = 1;
1950 info->iVersion = 2;
1951 info->iAddressFamily = WS_AF_IPX;
1952 info->iMaxSockAddr = 0x10;
1953 info->iMinSockAddr = 0x0e;
1954 info->iSocketType = WS_SOCK_SEQPACKET;
1955 info->dwMessageSize = 0xffffffff;
1956 strcpyW( info->szProtocol, NameSpxW );
1957 break;
1959 case WS_NSPROTO_SPXII:
1960 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_GRACEFUL_CLOSE |
1961 XP1_PSEUDO_STREAM | XP1_MESSAGE_ORIENTED |
1962 XP1_GUARANTEED_ORDER | XP1_GUARANTEED_DELIVERY;
1963 info->ProviderId = ProviderIdSPX;
1964 info->dwCatalogEntryId = 0x409;
1965 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1966 info->ProtocolChain.ChainLen = 1;
1967 info->iVersion = 2;
1968 info->iAddressFamily = WS_AF_IPX;
1969 info->iMaxSockAddr = 0x10;
1970 info->iMinSockAddr = 0x0e;
1971 info->iSocketType = WS_SOCK_SEQPACKET;
1972 info->dwMessageSize = 0xffffffff;
1973 strcpyW( info->szProtocol, NameSpxIIW );
1974 break;
1976 default:
1977 FIXME("unknown Protocol <0x%08x>\n", protocol);
1978 return FALSE;
1980 return TRUE;
1983 /*****************************************************************************
1984 * WS_EnterSingleProtocolA [internal]
1986 * see function WS_EnterSingleProtocolW
1989 static BOOL WS_EnterSingleProtocolA( INT protocol, WSAPROTOCOL_INFOA* info )
1991 WSAPROTOCOL_INFOW infow;
1992 INT ret;
1993 memset( info, 0, sizeof(WSAPROTOCOL_INFOA) );
1995 ret = WS_EnterSingleProtocolW( protocol, &infow );
1996 if (ret)
1998 /* convert the structure from W to A */
1999 memcpy( info, &infow, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
2000 WideCharToMultiByte( CP_ACP, 0, infow.szProtocol, -1,
2001 info->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL );
2004 return ret;
2007 static INT WS_EnumProtocols( BOOL unicode, const INT *protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
2009 INT i = 0, items = 0;
2010 DWORD size = 0;
2011 union _info
2013 LPWSAPROTOCOL_INFOA a;
2014 LPWSAPROTOCOL_INFOW w;
2015 } info;
2016 info.w = buffer;
2018 if (!protocols) protocols = valid_protocols;
2020 while (protocols[i])
2022 if(supported_protocol(protocols[i++]))
2023 items++;
2026 size = items * (unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA));
2028 TRACE("unicode %d, protocols %p, buffer %p, length %p %d, items %d, required %d\n",
2029 unicode, protocols, buffer, len, len ? *len : 0, items, size);
2031 if (*len < size || !buffer)
2033 *len = size;
2034 SetLastError(WSAENOBUFS);
2035 return SOCKET_ERROR;
2038 for (i = items = 0; protocols[i]; i++)
2040 if (!supported_protocol(protocols[i])) continue;
2041 if (unicode)
2043 if (WS_EnterSingleProtocolW( protocols[i], &info.w[items] ))
2044 items++;
2046 else
2048 if (WS_EnterSingleProtocolA( protocols[i], &info.a[items] ))
2049 items++;
2052 return items;
2055 static BOOL ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size)
2057 NTSTATUS status;
2059 *size = unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA);
2060 memset(buffer, 0, *size);
2062 SERVER_START_REQ( get_socket_info )
2064 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
2065 status = wine_server_call( req );
2066 if (!status)
2068 buffer->iAddressFamily = convert_af_u2w(reply->family);
2069 buffer->iSocketType = convert_socktype_u2w(reply->type);
2070 buffer->iProtocol = convert_proto_u2w(reply->protocol);
2073 SERVER_END_REQ;
2075 if (status)
2077 unsigned int err = NtStatusToWSAError( status );
2078 SetLastError( err == WSAEBADF ? WSAENOTSOCK : err );
2079 return FALSE;
2082 if (unicode)
2083 WS_EnterSingleProtocolW( buffer->iProtocol, buffer);
2084 else
2085 WS_EnterSingleProtocolA( buffer->iProtocol, (WSAPROTOCOL_INFOA *)buffer);
2087 return TRUE;
2090 /**************************************************************************
2091 * Functions for handling overlapped I/O
2092 **************************************************************************/
2094 /* user APC called upon async completion */
2095 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
2097 struct ws2_async *wsa = arg;
2099 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
2100 iosb->Information, wsa->user_overlapped,
2101 wsa->flags );
2102 release_async_io( &wsa->io );
2105 /***********************************************************************
2106 * WS2_recv (INTERNAL)
2108 * Workhorse for both synchronous and asynchronous recv() operations.
2110 static int WS2_recv( int fd, struct ws2_async *wsa, int flags )
2112 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2113 char pktbuf[512];
2114 #endif
2115 struct msghdr hdr;
2116 union generic_unix_sockaddr unix_sockaddr;
2117 int n;
2119 hdr.msg_name = NULL;
2121 if (wsa->addr)
2123 hdr.msg_namelen = sizeof(unix_sockaddr);
2124 hdr.msg_name = &unix_sockaddr;
2126 else
2127 hdr.msg_namelen = 0;
2129 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
2130 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
2131 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2132 hdr.msg_accrights = NULL;
2133 hdr.msg_accrightslen = 0;
2134 #else
2135 hdr.msg_control = pktbuf;
2136 hdr.msg_controllen = sizeof(pktbuf);
2137 hdr.msg_flags = 0;
2138 #endif
2140 while ((n = recvmsg(fd, &hdr, flags)) == -1)
2142 if (errno != EINTR)
2143 return -1;
2146 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2147 if (wsa->control)
2149 ERR("Message control headers cannot be properly supported on this system.\n");
2150 wsa->control->len = 0;
2152 #else
2153 if (wsa->control && !convert_control_headers(&hdr, wsa->control))
2155 WARN("Application passed insufficient room for control headers.\n");
2156 *wsa->lpFlags |= WS_MSG_CTRUNC;
2157 errno = EMSGSIZE;
2158 return -1;
2160 #endif
2162 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
2163 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
2165 * quoting linux 2.6 net/ipv4/tcp.c:
2166 * "According to UNIX98, msg_name/msg_namelen are ignored
2167 * on connected socket. I was just happy when found this 8) --ANK"
2169 * likewise MSDN says that lpFrom and lpFromlen are ignored for
2170 * connection-oriented sockets, so don't try to update lpFrom.
2172 if (wsa->addr && hdr.msg_namelen)
2173 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
2175 return n;
2178 /***********************************************************************
2179 * WS2_async_recv (INTERNAL)
2181 * Handler for overlapped recv() operations.
2183 static NTSTATUS WS2_async_recv( void *user, IO_STATUS_BLOCK *iosb,
2184 NTSTATUS status, void **apc, void **arg )
2186 struct ws2_async *wsa = user;
2187 int result = 0, fd;
2189 switch (status)
2191 case STATUS_ALERTED:
2192 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
2193 break;
2195 result = WS2_recv( fd, wsa, convert_flags(wsa->flags) );
2196 wine_server_release_fd( wsa->hSocket, fd );
2197 if (result >= 0)
2199 status = STATUS_SUCCESS;
2200 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
2202 else
2204 if (errno == EAGAIN)
2206 status = STATUS_PENDING;
2207 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
2209 else
2211 result = 0;
2212 status = wsaErrStatus();
2215 break;
2217 if (status != STATUS_PENDING)
2219 iosb->u.Status = status;
2220 iosb->Information = result;
2221 if (wsa->completion_func)
2223 *apc = ws2_async_apc;
2224 *arg = wsa;
2226 else
2227 release_async_io( &wsa->io );
2229 return status;
2232 /***********************************************************************
2233 * WS2_async_accept_recv (INTERNAL)
2235 * This function is used to finish the read part of an accept request. It is
2236 * needed to place the completion on the correct socket (listener).
2238 static NTSTATUS WS2_async_accept_recv( void *user, IO_STATUS_BLOCK *iosb,
2239 NTSTATUS status, void **apc, void **arg )
2241 void *junk;
2242 struct ws2_accept_async *wsa = user;
2244 status = WS2_async_recv( wsa->read, iosb, status, &junk, &junk );
2245 if (status == STATUS_PENDING)
2246 return status;
2248 if (wsa->cvalue)
2249 WS_AddCompletion( HANDLE2SOCKET(wsa->listen_socket), wsa->cvalue, iosb->u.Status, iosb->Information );
2251 release_async_io( &wsa->io );
2252 return status;
2255 /***********************************************************************
2256 * WS2_async_accept (INTERNAL)
2258 * This is the function called to satisfy the AcceptEx callback
2260 static NTSTATUS WS2_async_accept( void *user, IO_STATUS_BLOCK *iosb,
2261 NTSTATUS status, void **apc, void **arg )
2263 struct ws2_accept_async *wsa = user;
2264 int len;
2265 char *addr;
2267 TRACE("status: 0x%x listen: %p, accept: %p\n", status, wsa->listen_socket, wsa->accept_socket);
2269 if (status == STATUS_ALERTED)
2271 SERVER_START_REQ( accept_into_socket )
2273 req->lhandle = wine_server_obj_handle( wsa->listen_socket );
2274 req->ahandle = wine_server_obj_handle( wsa->accept_socket );
2275 status = wine_server_call( req );
2277 SERVER_END_REQ;
2279 if (status == STATUS_CANT_WAIT)
2280 return STATUS_PENDING;
2282 if (status == STATUS_INVALID_HANDLE)
2284 FIXME("AcceptEx accepting socket closed but request was not cancelled\n");
2285 status = STATUS_CANCELLED;
2288 else if (status == STATUS_HANDLES_CLOSED)
2289 status = STATUS_CANCELLED; /* strange windows behavior */
2291 if (status != STATUS_SUCCESS)
2292 goto finish;
2294 /* WS2 Spec says size param is extra 16 bytes long...what do we put in it? */
2295 addr = ((char *)wsa->buf) + wsa->data_len;
2296 len = wsa->local_len - sizeof(int);
2297 WS_getsockname(HANDLE2SOCKET(wsa->accept_socket),
2298 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
2299 *(int *)addr = len;
2301 addr += wsa->local_len;
2302 len = wsa->remote_len - sizeof(int);
2303 WS_getpeername(HANDLE2SOCKET(wsa->accept_socket),
2304 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
2305 *(int *)addr = len;
2307 if (!wsa->read)
2308 goto finish;
2310 SERVER_START_REQ( register_async )
2312 req->type = ASYNC_TYPE_READ;
2313 req->async.handle = wine_server_obj_handle( wsa->accept_socket );
2314 req->async.event = wine_server_obj_handle( wsa->user_overlapped->hEvent );
2315 req->async.callback = wine_server_client_ptr( WS2_async_accept_recv );
2316 req->async.iosb = wine_server_client_ptr( iosb );
2317 req->async.arg = wine_server_client_ptr( wsa );
2318 status = wine_server_call( req );
2320 SERVER_END_REQ;
2322 if (status != STATUS_PENDING)
2323 goto finish;
2325 /* The APC has finished but no completion should be sent for the operation yet, additional processing
2326 * needs to be performed by WS2_async_accept_recv() first. */
2327 return STATUS_MORE_PROCESSING_REQUIRED;
2329 finish:
2330 iosb->u.Status = status;
2331 iosb->Information = 0;
2333 if (wsa->read) release_async_io( &wsa->read->io );
2334 release_async_io( &wsa->io );
2335 return status;
2338 /***********************************************************************
2339 * WS2_send (INTERNAL)
2341 * Workhorse for both synchronous and asynchronous send() operations.
2343 static int WS2_send( int fd, struct ws2_async *wsa, int flags )
2345 struct msghdr hdr;
2346 union generic_unix_sockaddr unix_addr;
2347 int n, ret;
2349 hdr.msg_name = NULL;
2350 hdr.msg_namelen = 0;
2352 if (wsa->addr)
2354 hdr.msg_name = &unix_addr;
2355 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
2356 if ( !hdr.msg_namelen )
2358 errno = EFAULT;
2359 return -1;
2362 #if defined(HAS_IPX) && defined(SOL_IPX)
2363 if(wsa->addr->sa_family == WS_AF_IPX)
2365 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
2366 int val=0;
2367 socklen_t len = sizeof(int);
2369 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
2370 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
2371 * the packet type and then we can retrieve it using getsockopt. After that we can set the
2372 * ipx type in the sockaddr_opx structure with the stored value.
2374 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
2375 uipx->sipx_type = val;
2377 #endif
2380 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
2381 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
2382 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2383 hdr.msg_accrights = NULL;
2384 hdr.msg_accrightslen = 0;
2385 #else
2386 hdr.msg_control = NULL;
2387 hdr.msg_controllen = 0;
2388 hdr.msg_flags = 0;
2389 #endif
2391 while ((ret = sendmsg(fd, &hdr, flags)) == -1)
2393 if (errno != EINTR)
2394 return -1;
2397 n = ret;
2398 while (wsa->first_iovec < wsa->n_iovecs && wsa->iovec[wsa->first_iovec].iov_len <= n)
2399 n -= wsa->iovec[wsa->first_iovec++].iov_len;
2400 if (wsa->first_iovec < wsa->n_iovecs)
2402 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
2403 wsa->iovec[wsa->first_iovec].iov_len -= n;
2405 return ret;
2408 /***********************************************************************
2409 * WS2_async_send (INTERNAL)
2411 * Handler for overlapped send() operations.
2413 static NTSTATUS WS2_async_send( void *user, IO_STATUS_BLOCK *iosb,
2414 NTSTATUS status, void **apc, void **arg )
2416 struct ws2_async *wsa = user;
2417 int result = 0, fd;
2419 switch (status)
2421 case STATUS_ALERTED:
2422 if ( wsa->n_iovecs <= wsa->first_iovec )
2424 /* Nothing to do */
2425 status = STATUS_SUCCESS;
2426 break;
2428 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
2429 break;
2431 /* check to see if the data is ready (non-blocking) */
2432 result = WS2_send( fd, wsa, convert_flags(wsa->flags) );
2433 wine_server_release_fd( wsa->hSocket, fd );
2435 if (result >= 0)
2437 if (wsa->first_iovec < wsa->n_iovecs)
2438 status = STATUS_PENDING;
2439 else
2440 status = STATUS_SUCCESS;
2442 iosb->Information += result;
2444 else if (errno == EAGAIN)
2446 status = STATUS_PENDING;
2448 else
2450 status = wsaErrStatus();
2452 break;
2454 if (status != STATUS_PENDING)
2456 iosb->u.Status = status;
2457 if (wsa->completion_func)
2459 *apc = ws2_async_apc;
2460 *arg = wsa;
2462 else
2463 release_async_io( &wsa->io );
2465 return status;
2468 /***********************************************************************
2469 * WS2_async_shutdown (INTERNAL)
2471 * Handler for shutdown() operations on overlapped sockets.
2473 static NTSTATUS WS2_async_shutdown( void *user, IO_STATUS_BLOCK *iosb,
2474 NTSTATUS status, void **apc, void **arg )
2476 struct ws2_async_shutdown *wsa = user;
2477 int fd, err = 1;
2479 switch (status)
2481 case STATUS_ALERTED:
2482 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
2483 break;
2485 switch ( wsa->type )
2487 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
2488 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
2490 status = err ? wsaErrStatus() : STATUS_SUCCESS;
2491 wine_server_release_fd( wsa->hSocket, fd );
2492 break;
2494 iosb->u.Status = status;
2495 iosb->Information = 0;
2496 release_async_io( &wsa->io );
2497 return status;
2500 /***********************************************************************
2501 * WS2_register_async_shutdown (INTERNAL)
2503 * Helper function for WS_shutdown() on overlapped sockets.
2505 static int WS2_register_async_shutdown( SOCKET s, int type )
2507 struct ws2_async_shutdown *wsa;
2508 NTSTATUS status;
2510 TRACE("socket %04lx type %d\n", s, type);
2512 wsa = (struct ws2_async_shutdown *)alloc_async_io( sizeof(*wsa) );
2513 if ( !wsa )
2514 return WSAEFAULT;
2516 wsa->hSocket = SOCKET2HANDLE(s);
2517 wsa->type = type;
2519 SERVER_START_REQ( register_async )
2521 req->type = type;
2522 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2523 req->async.callback = wine_server_client_ptr( WS2_async_shutdown );
2524 req->async.iosb = wine_server_client_ptr( &wsa->iosb );
2525 req->async.arg = wine_server_client_ptr( wsa );
2526 req->async.cvalue = 0;
2527 status = wine_server_call( req );
2529 SERVER_END_REQ;
2531 if (status != STATUS_PENDING)
2533 HeapFree( GetProcessHeap(), 0, wsa );
2534 return NtStatusToWSAError( status );
2536 return 0;
2539 /***********************************************************************
2540 * accept (WS2_32.1)
2542 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr, int *addrlen32)
2544 NTSTATUS status;
2545 SOCKET as;
2546 BOOL is_blocking;
2548 TRACE("socket %04lx\n", s );
2549 status = _is_blocking(s, &is_blocking);
2550 if (status)
2552 set_error(status);
2553 return INVALID_SOCKET;
2556 do {
2557 /* try accepting first (if there is a deferred connection) */
2558 SERVER_START_REQ( accept_socket )
2560 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
2561 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
2562 req->attributes = OBJ_INHERIT;
2563 status = wine_server_call( req );
2564 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
2566 SERVER_END_REQ;
2567 if (!status)
2569 if (addr && WS_getpeername(as, addr, addrlen32))
2571 WS_closesocket(as);
2572 return SOCKET_ERROR;
2574 return as;
2576 if (is_blocking && status == STATUS_CANT_WAIT)
2578 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2579 /* block here */
2580 do_block(fd, POLLIN, -1);
2581 _sync_sock_state(s); /* let wineserver notice connection */
2582 release_sock_fd( s, fd );
2584 } while (is_blocking && status == STATUS_CANT_WAIT);
2586 set_error(status);
2587 return INVALID_SOCKET;
2590 /***********************************************************************
2591 * AcceptEx
2593 static BOOL WINAPI WS2_AcceptEx(SOCKET listener, SOCKET acceptor, PVOID dest, DWORD dest_len,
2594 DWORD local_addr_len, DWORD rem_addr_len, LPDWORD received,
2595 LPOVERLAPPED overlapped)
2597 DWORD status;
2598 struct ws2_accept_async *wsa;
2599 int fd;
2601 TRACE("(%04lx, %04lx, %p, %d, %d, %d, %p, %p)\n", listener, acceptor, dest, dest_len, local_addr_len,
2602 rem_addr_len, received, overlapped);
2604 if (!dest)
2606 SetLastError(WSAEINVAL);
2607 return FALSE;
2610 if (!overlapped)
2612 SetLastError(WSA_INVALID_PARAMETER);
2613 return FALSE;
2616 if (!rem_addr_len)
2618 SetLastError(WSAEFAULT);
2619 return FALSE;
2622 fd = get_sock_fd( listener, FILE_READ_DATA, NULL );
2623 if (fd == -1)
2625 SetLastError(WSAENOTSOCK);
2626 return FALSE;
2628 release_sock_fd( listener, fd );
2630 fd = get_sock_fd( acceptor, FILE_READ_DATA, NULL );
2631 if (fd == -1)
2633 SetLastError(WSAENOTSOCK);
2634 return FALSE;
2636 release_sock_fd( acceptor, fd );
2638 wsa = (struct ws2_accept_async *)alloc_async_io( sizeof(*wsa) );
2639 if(!wsa)
2641 SetLastError(WSAEFAULT);
2642 return FALSE;
2645 wsa->listen_socket = SOCKET2HANDLE(listener);
2646 wsa->accept_socket = SOCKET2HANDLE(acceptor);
2647 wsa->user_overlapped = overlapped;
2648 wsa->cvalue = !((ULONG_PTR)overlapped->hEvent & 1) ? (ULONG_PTR)overlapped : 0;
2649 wsa->buf = dest;
2650 wsa->data_len = dest_len;
2651 wsa->local_len = local_addr_len;
2652 wsa->remote_len = rem_addr_len;
2653 wsa->read = NULL;
2655 if (wsa->data_len)
2657 /* set up a read request if we need it */
2658 wsa->read = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[1]) );
2659 if (!wsa->read)
2661 HeapFree( GetProcessHeap(), 0, wsa );
2662 SetLastError(WSAEFAULT);
2663 return FALSE;
2666 wsa->read->hSocket = wsa->accept_socket;
2667 wsa->read->flags = 0;
2668 wsa->read->lpFlags = &wsa->read->flags;
2669 wsa->read->addr = NULL;
2670 wsa->read->addrlen.ptr = NULL;
2671 wsa->read->control = NULL;
2672 wsa->read->n_iovecs = 1;
2673 wsa->read->first_iovec = 0;
2674 wsa->read->completion_func = NULL;
2675 wsa->read->iovec[0].iov_base = wsa->buf;
2676 wsa->read->iovec[0].iov_len = wsa->data_len;
2679 SERVER_START_REQ( register_async )
2681 req->type = ASYNC_TYPE_READ;
2682 req->async.handle = wine_server_obj_handle( SOCKET2HANDLE(listener) );
2683 req->async.event = wine_server_obj_handle( overlapped->hEvent );
2684 req->async.callback = wine_server_client_ptr( WS2_async_accept );
2685 req->async.iosb = wine_server_client_ptr( overlapped );
2686 req->async.arg = wine_server_client_ptr( wsa );
2687 req->async.cvalue = wsa->cvalue;
2688 status = wine_server_call( req );
2690 SERVER_END_REQ;
2692 if(status != STATUS_PENDING)
2694 HeapFree( GetProcessHeap(), 0, wsa->read );
2695 HeapFree( GetProcessHeap(), 0, wsa );
2698 SetLastError( NtStatusToWSAError(status) );
2699 return FALSE;
2702 /***********************************************************************
2703 * GetAcceptExSockaddrs
2705 static void WINAPI WS2_GetAcceptExSockaddrs(PVOID buffer, DWORD data_size, DWORD local_size, DWORD remote_size,
2706 struct WS_sockaddr **local_addr, LPINT local_addr_len,
2707 struct WS_sockaddr **remote_addr, LPINT remote_addr_len)
2709 char *cbuf = buffer;
2710 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer, data_size, local_size, remote_size, local_addr,
2711 local_addr_len, remote_addr, remote_addr_len );
2712 cbuf += data_size;
2714 *local_addr_len = *(int *) cbuf;
2715 *local_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2717 cbuf += local_size;
2719 *remote_addr_len = *(int *) cbuf;
2720 *remote_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2723 /***********************************************************************
2724 * WSASendMsg
2726 int WINAPI WSASendMsg( SOCKET s, LPWSAMSG msg, DWORD dwFlags, LPDWORD lpNumberOfBytesSent,
2727 LPWSAOVERLAPPED lpOverlapped,
2728 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
2730 if (!msg)
2732 SetLastError( WSAEFAULT );
2733 return SOCKET_ERROR;
2736 return WS2_sendto( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesSent,
2737 dwFlags, msg->name, msg->namelen,
2738 lpOverlapped, lpCompletionRoutine );
2741 /***********************************************************************
2742 * WSARecvMsg
2744 * Perform a receive operation that is capable of returning message
2745 * control headers. It is important to note that the WSAMSG parameter
2746 * must remain valid throughout the operation, even when an overlapped
2747 * receive is performed.
2749 static int WINAPI WS2_WSARecvMsg( SOCKET s, LPWSAMSG msg, LPDWORD lpNumberOfBytesRecvd,
2750 LPWSAOVERLAPPED lpOverlapped,
2751 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2753 if (!msg)
2755 SetLastError( WSAEFAULT );
2756 return SOCKET_ERROR;
2759 return WS2_recv_base( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesRecvd,
2760 &msg->dwFlags, msg->name, &msg->namelen,
2761 lpOverlapped, lpCompletionRoutine, &msg->Control );
2764 /***********************************************************************
2765 * interface_bind (INTERNAL)
2767 * Take bind() calls on any name corresponding to a local network adapter and restrict the given socket to
2768 * operating only on the specified interface. This restriction consists of two components:
2769 * 1) An outgoing packet restriction suggesting the egress interface for all packets.
2770 * 2) An incoming packet restriction dropping packets not meant for the interface.
2771 * If the function succeeds in placing these restrictions (returns TRUE) then the name for the bind() may
2772 * safely be changed to INADDR_ANY, permitting the transmission and receipt of broadcast packets on the
2773 * socket. This behavior is only relevant to UDP sockets and is needed for applications that expect to be able
2774 * to receive broadcast packets on a socket that is bound to a specific network interface.
2776 static BOOL interface_bind( SOCKET s, int fd, struct sockaddr *addr )
2778 struct sockaddr_in *in_sock = (struct sockaddr_in *) addr;
2779 unsigned int sock_type = 0;
2780 socklen_t optlen = sizeof(sock_type);
2781 in_addr_t bind_addr = in_sock->sin_addr.s_addr;
2782 PIP_ADAPTER_INFO adapters = NULL, adapter;
2783 BOOL ret = FALSE;
2784 DWORD adap_size;
2785 int enable = 1;
2787 if (bind_addr == htonl(INADDR_ANY) || bind_addr == htonl(INADDR_LOOPBACK))
2788 return FALSE; /* Not binding to a network adapter, special interface binding unnecessary. */
2789 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &sock_type, &optlen) == -1 || sock_type != SOCK_DGRAM)
2790 return FALSE; /* Special interface binding is only necessary for UDP datagrams. */
2791 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
2792 goto cleanup;
2793 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
2794 if (adapters == NULL || GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
2795 goto cleanup;
2796 /* Search the IPv4 adapter list for the appropriate binding interface */
2797 for (adapter = adapters; adapter != NULL; adapter = adapter->Next)
2799 in_addr_t adapter_addr = (in_addr_t) inet_addr(adapter->IpAddressList.IpAddress.String);
2801 if (bind_addr == adapter_addr)
2803 #if defined(IP_BOUND_IF)
2804 /* IP_BOUND_IF sets both the incoming and outgoing restriction at once */
2805 if (setsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &adapter->Index, sizeof(adapter->Index)) != 0)
2806 goto cleanup;
2807 ret = TRUE;
2808 #elif defined(LINUX_BOUND_IF)
2809 in_addr_t ifindex = (in_addr_t) htonl(adapter->Index);
2810 struct interface_filter specific_interface_filter;
2811 struct sock_fprog filter_prog;
2813 if (setsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex, sizeof(ifindex)) != 0)
2814 goto cleanup; /* Failed to suggest egress interface */
2815 specific_interface_filter = generic_interface_filter;
2816 specific_interface_filter.iface_rule.k = adapter->Index;
2817 specific_interface_filter.ip_rule.k = htonl(adapter_addr);
2818 filter_prog.len = sizeof(generic_interface_filter)/sizeof(struct sock_filter);
2819 filter_prog.filter = (struct sock_filter *) &specific_interface_filter;
2820 if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog, sizeof(filter_prog)) != 0)
2821 goto cleanup; /* Failed to specify incoming packet filter */
2822 ret = TRUE;
2823 #else
2824 FIXME("Broadcast packets on interface-bound sockets are not currently supported on this platform, "
2825 "receiving broadcast packets will not work on socket %04lx.\n", s);
2826 #endif
2827 break;
2830 /* Will soon be switching to INADDR_ANY: permit address reuse */
2831 if (ret && setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) == 0)
2832 TRACE("Socket %04lx bound to interface index %d\n", s, adapter->Index);
2833 else
2834 ret = FALSE;
2836 cleanup:
2837 if(!ret)
2838 ERR("Failed to bind to interface, receiving broadcast packets will not work on socket %04lx.\n", s);
2839 HeapFree(GetProcessHeap(), 0, adapters);
2840 return ret;
2843 /***********************************************************************
2844 * bind (WS2_32.2)
2846 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
2848 int fd = get_sock_fd( s, 0, NULL );
2849 int res = SOCKET_ERROR;
2851 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2853 if (fd != -1)
2855 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
2857 SetLastError(WSAEAFNOSUPPORT);
2859 else
2861 union generic_unix_sockaddr uaddr;
2862 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2863 if (!uaddrlen)
2865 SetLastError(WSAEFAULT);
2867 else
2869 #ifdef IPV6_V6ONLY
2870 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
2871 if (name->sa_family == WS_AF_INET6 &&
2872 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
2874 int enable = 1;
2875 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
2877 release_sock_fd( s, fd );
2878 SetLastError(WSAEAFNOSUPPORT);
2879 return SOCKET_ERROR;
2882 #endif
2883 if (name->sa_family == WS_AF_INET)
2885 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2886 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2888 /* Trying to bind to the default host interface, using
2889 * INADDR_ANY instead*/
2890 WARN("Trying to bind to magic IP address, using "
2891 "INADDR_ANY instead.\n");
2892 in4->sin_addr.s_addr = htonl(INADDR_ANY);
2894 else if (interface_bind(s, fd, &uaddr.addr))
2895 in4->sin_addr.s_addr = htonl(INADDR_ANY);
2897 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
2899 int loc_errno = errno;
2900 WARN("\tfailure - errno = %i\n", errno);
2901 errno = loc_errno;
2902 switch (errno)
2904 case EBADF:
2905 SetLastError(WSAENOTSOCK);
2906 break;
2907 case EADDRNOTAVAIL:
2908 SetLastError(WSAEINVAL);
2909 break;
2910 case EADDRINUSE:
2912 int optval = 0;
2913 socklen_t optlen = sizeof(optval);
2914 /* Windows >= 2003 will return different results depending on
2915 * SO_REUSEADDR, WSAEACCES may be returned representing that
2916 * the socket hijacking protection prevented the bind */
2917 if (!getsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&optval, &optlen) && optval)
2919 SetLastError(WSAEACCES);
2920 break;
2922 /* fall through */
2924 default:
2925 SetLastError(wsaErrno());
2926 break;
2929 else
2931 res=0; /* success */
2935 release_sock_fd( s, fd );
2937 return res;
2940 /***********************************************************************
2941 * closesocket (WS2_32.3)
2943 int WINAPI WS_closesocket(SOCKET s)
2945 int res = SOCKET_ERROR, fd;
2946 if (num_startup)
2948 fd = get_sock_fd(s, FILE_READ_DATA, NULL);
2949 if (fd >= 0)
2951 release_sock_fd(s, fd);
2952 if (CloseHandle(SOCKET2HANDLE(s)))
2953 res = 0;
2955 else
2956 SetLastError(WSAENOTSOCK);
2958 else
2959 SetLastError(WSANOTINITIALISED);
2960 TRACE("(socket %04lx) -> %d\n", s, res);
2961 return res;
2964 static int do_connect(int fd, const struct WS_sockaddr* name, int namelen)
2966 union generic_unix_sockaddr uaddr;
2967 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2969 if (!uaddrlen)
2970 return WSAEFAULT;
2972 if (name->sa_family == WS_AF_INET)
2974 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2975 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2977 /* Trying to connect to magic replace-loopback address,
2978 * assuming we really want to connect to localhost */
2979 TRACE("Trying to connect to magic IP address, using "
2980 "INADDR_LOOPBACK instead.\n");
2981 in4->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
2985 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
2986 return 0;
2988 return wsaErrno();
2991 /***********************************************************************
2992 * connect (WS2_32.4)
2994 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
2996 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2998 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
3000 if (fd != -1)
3002 NTSTATUS status;
3003 BOOL is_blocking;
3004 int ret = do_connect(fd, name, namelen);
3005 if (ret == 0)
3006 goto connect_success;
3008 if (ret == WSAEINPROGRESS)
3010 /* tell wineserver that a connection is in progress */
3011 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3012 FD_CONNECT,
3013 FD_WINE_CONNECTED|FD_WINE_LISTENING);
3014 status = _is_blocking( s, &is_blocking );
3015 if (status)
3017 release_sock_fd( s, fd );
3018 set_error( status );
3019 return SOCKET_ERROR;
3021 if (is_blocking)
3023 int result;
3024 /* block here */
3025 do_block(fd, POLLIN | POLLOUT, -1);
3026 _sync_sock_state(s); /* let wineserver notice connection */
3027 /* retrieve any error codes from it */
3028 result = _get_sock_error(s, FD_CONNECT_BIT);
3029 if (result)
3030 SetLastError(NtStatusToWSAError(result));
3031 else
3033 goto connect_success;
3036 else
3038 SetLastError(WSAEWOULDBLOCK);
3041 else
3043 SetLastError(ret);
3045 release_sock_fd( s, fd );
3047 return SOCKET_ERROR;
3049 connect_success:
3050 release_sock_fd( s, fd );
3051 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3052 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
3053 FD_CONNECT|FD_WINE_LISTENING);
3054 return 0;
3057 /***********************************************************************
3058 * WSAConnect (WS2_32.30)
3060 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
3061 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
3062 LPQOS lpSQOS, LPQOS lpGQOS )
3064 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
3065 FIXME("unsupported parameters!\n");
3066 return WS_connect( s, name, namelen );
3069 /***********************************************************************
3070 * ConnectEx
3072 static BOOL WINAPI WS2_ConnectEx(SOCKET s, const struct WS_sockaddr* name, int namelen,
3073 PVOID sendBuf, DWORD sendBufLen, LPDWORD sent, LPOVERLAPPED ov)
3075 int fd, ret, status;
3077 if (!ov)
3079 SetLastError( ERROR_INVALID_PARAMETER );
3080 return FALSE;
3083 fd = get_sock_fd( s, FILE_READ_DATA, NULL );
3084 if (fd == -1)
3086 SetLastError( WSAENOTSOCK );
3087 return FALSE;
3090 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
3091 s, name, debugstr_sockaddr(name), namelen, sendBuf, sendBufLen, ov);
3093 ret = is_fd_bound(fd, NULL, NULL);
3094 if (ret <= 0)
3096 SetLastError(ret == -1 ? wsaErrno() : WSAEINVAL);
3097 return FALSE;
3100 ret = do_connect(fd, name, namelen);
3101 if (ret == 0)
3103 WSABUF wsabuf;
3105 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3106 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
3107 FD_CONNECT|FD_WINE_LISTENING);
3109 wsabuf.len = sendBufLen;
3110 wsabuf.buf = (char*) sendBuf;
3112 /* WSASend takes care of completion if need be */
3113 if (WSASend(s, &wsabuf, sendBuf ? 1 : 0, sent, 0, ov, NULL) != SOCKET_ERROR)
3114 goto connection_success;
3116 else if (ret == WSAEINPROGRESS)
3118 struct ws2_async *wsa;
3119 ULONG_PTR cvalue = (((ULONG_PTR)ov->hEvent & 1) == 0) ? (ULONG_PTR)ov : 0;
3121 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
3122 FD_CONNECT,
3123 FD_WINE_CONNECTED|FD_WINE_LISTENING);
3125 /* Indirectly call WSASend */
3126 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof( struct ws2_async, iovec[1] ))))
3128 SetLastError(WSAEFAULT);
3130 else
3132 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)ov;
3133 iosb->u.Status = STATUS_PENDING;
3134 iosb->Information = 0;
3136 wsa->hSocket = SOCKET2HANDLE(s);
3137 wsa->addr = NULL;
3138 wsa->addrlen.val = 0;
3139 wsa->flags = 0;
3140 wsa->lpFlags = &wsa->flags;
3141 wsa->control = NULL;
3142 wsa->n_iovecs = sendBuf ? 1 : 0;
3143 wsa->first_iovec = 0;
3144 wsa->completion_func = NULL;
3145 wsa->iovec[0].iov_base = sendBuf;
3146 wsa->iovec[0].iov_len = sendBufLen;
3148 SERVER_START_REQ( register_async )
3150 req->type = ASYNC_TYPE_WRITE;
3151 req->async.handle = wine_server_obj_handle( wsa->hSocket );
3152 req->async.callback = wine_server_client_ptr( WS2_async_send );
3153 req->async.iosb = wine_server_client_ptr( iosb );
3154 req->async.arg = wine_server_client_ptr( wsa );
3155 req->async.event = wine_server_obj_handle( ov->hEvent );
3156 req->async.cvalue = cvalue;
3157 status = wine_server_call( req );
3159 SERVER_END_REQ;
3161 if (status != STATUS_PENDING) HeapFree(GetProcessHeap(), 0, wsa);
3163 /* If the connect already failed */
3164 if (status == STATUS_PIPE_DISCONNECTED)
3165 status = _get_sock_error(s, FD_CONNECT_BIT);
3166 SetLastError( NtStatusToWSAError(status) );
3169 else
3171 SetLastError(ret);
3174 release_sock_fd( s, fd );
3175 return FALSE;
3177 connection_success:
3178 release_sock_fd( s, fd );
3179 return TRUE;
3183 /***********************************************************************
3184 * getpeername (WS2_32.5)
3186 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
3188 int fd;
3189 int res;
3191 TRACE("socket %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
3193 fd = get_sock_fd( s, 0, NULL );
3194 res = SOCKET_ERROR;
3196 if (fd != -1)
3198 union generic_unix_sockaddr uaddr;
3199 socklen_t uaddrlen = sizeof(uaddr);
3201 if (getpeername(fd, &uaddr.addr, &uaddrlen) == 0)
3203 if (!name || !namelen)
3204 SetLastError(WSAEFAULT);
3205 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3206 /* The buffer was too small */
3207 SetLastError(WSAEFAULT);
3208 else
3210 res = 0;
3211 TRACE("=> %s\n", debugstr_sockaddr(name));
3214 else
3215 SetLastError(wsaErrno());
3216 release_sock_fd( s, fd );
3218 return res;
3221 /***********************************************************************
3222 * getsockname (WS2_32.6)
3224 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
3226 int fd;
3227 int res;
3229 TRACE("socket %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
3231 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
3232 if( (name == NULL) || (namelen == NULL) )
3234 SetLastError( WSAEFAULT );
3235 return SOCKET_ERROR;
3238 fd = get_sock_fd( s, 0, NULL );
3239 res = SOCKET_ERROR;
3241 if (fd != -1)
3243 union generic_unix_sockaddr uaddr;
3244 socklen_t uaddrlen;
3245 int bound = is_fd_bound(fd, &uaddr, &uaddrlen);
3247 if (bound <= 0)
3249 SetLastError(bound == -1 ? wsaErrno() : WSAEINVAL);
3251 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3253 /* The buffer was too small */
3254 SetLastError(WSAEFAULT);
3256 else
3258 res = 0;
3259 TRACE("=> %s\n", debugstr_sockaddr(name));
3261 release_sock_fd( s, fd );
3263 return res;
3266 /***********************************************************************
3267 * getsockopt (WS2_32.7)
3269 INT WINAPI WS_getsockopt(SOCKET s, INT level,
3270 INT optname, char *optval, INT *optlen)
3272 int fd;
3273 INT ret = 0;
3275 TRACE("(socket %04lx, %s, optval %s, optlen %p (%d))\n", s,
3276 debugstr_sockopt(level, optname), debugstr_optval(optval, 0),
3277 optlen, optlen ? *optlen : 0);
3279 switch(level)
3281 case WS_SOL_SOCKET:
3283 switch(optname)
3285 /* Handle common cases. The special cases are below, sorted
3286 * alphabetically */
3287 case WS_SO_BROADCAST:
3288 case WS_SO_DEBUG:
3289 case WS_SO_ERROR:
3290 case WS_SO_KEEPALIVE:
3291 case WS_SO_OOBINLINE:
3292 case WS_SO_RCVBUF:
3293 case WS_SO_REUSEADDR:
3294 case WS_SO_SNDBUF:
3295 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3296 return SOCKET_ERROR;
3297 convert_sockopt(&level, &optname);
3298 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3300 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3301 ret = SOCKET_ERROR;
3303 release_sock_fd( s, fd );
3304 return ret;
3305 case WS_SO_ACCEPTCONN:
3306 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3307 return SOCKET_ERROR;
3308 if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, optval, (socklen_t *)optlen) != 0 )
3310 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3311 ret = SOCKET_ERROR;
3313 else
3315 /* BSD returns != 0 while Windows return exact == 1 */
3316 if (*(int *)optval) *(int *)optval = 1;
3318 release_sock_fd( s, fd );
3319 return ret;
3320 case WS_SO_BSP_STATE:
3322 int req_size, addr_size;
3323 WSAPROTOCOL_INFOW infow;
3324 CSADDR_INFO *csinfo;
3326 ret = ws_protocol_info(s, TRUE, &infow, &addr_size);
3327 if (ret)
3329 if (infow.iAddressFamily == WS_AF_INET)
3330 addr_size = sizeof(struct sockaddr_in);
3331 else if (infow.iAddressFamily == WS_AF_INET6)
3332 addr_size = sizeof(struct sockaddr_in6);
3333 else
3335 FIXME("Family %d is unsupported for SO_BSP_STATE\n", infow.iAddressFamily);
3336 SetLastError(WSAEAFNOSUPPORT);
3337 return SOCKET_ERROR;
3340 req_size = sizeof(CSADDR_INFO) + addr_size * 2;
3341 if (*optlen < req_size)
3343 ret = 0;
3344 SetLastError(WSAEFAULT);
3346 else
3348 union generic_unix_sockaddr uaddr;
3349 socklen_t uaddrlen;
3351 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3352 return SOCKET_ERROR;
3354 csinfo = (CSADDR_INFO*) optval;
3356 /* Check if the sock is bound */
3357 if (is_fd_bound(fd, &uaddr, &uaddrlen) == 1)
3359 csinfo->LocalAddr.lpSockaddr =
3360 (LPSOCKADDR) (optval + sizeof(CSADDR_INFO));
3361 ws_sockaddr_u2ws(&uaddr.addr, csinfo->LocalAddr.lpSockaddr, &addr_size);
3362 csinfo->LocalAddr.iSockaddrLength = addr_size;
3364 else
3366 csinfo->LocalAddr.lpSockaddr = NULL;
3367 csinfo->LocalAddr.iSockaddrLength = 0;
3370 /* Check if the sock is connected */
3371 if (!getpeername(fd, &uaddr.addr, &uaddrlen) &&
3372 is_sockaddr_bound(&uaddr.addr, uaddrlen))
3374 csinfo->RemoteAddr.lpSockaddr =
3375 (LPSOCKADDR) (optval + sizeof(CSADDR_INFO) + addr_size);
3376 ws_sockaddr_u2ws(&uaddr.addr, csinfo->RemoteAddr.lpSockaddr, &addr_size);
3377 csinfo->RemoteAddr.iSockaddrLength = addr_size;
3379 else
3381 csinfo->RemoteAddr.lpSockaddr = NULL;
3382 csinfo->RemoteAddr.iSockaddrLength = 0;
3385 csinfo->iSocketType = infow.iSocketType;
3386 csinfo->iProtocol = infow.iProtocol;
3387 release_sock_fd( s, fd );
3390 return ret ? 0 : SOCKET_ERROR;
3392 case WS_SO_DONTLINGER:
3394 struct linger lingval;
3395 socklen_t len = sizeof(struct linger);
3397 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
3399 SetLastError(WSAEFAULT);
3400 return SOCKET_ERROR;
3402 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3403 return SOCKET_ERROR;
3405 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
3407 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3408 ret = SOCKET_ERROR;
3410 else
3412 *(BOOL *)optval = !lingval.l_onoff;
3413 *optlen = sizeof(BOOL);
3416 release_sock_fd( s, fd );
3417 return ret;
3420 case WS_SO_CONNECT_TIME:
3422 static int pretendtime = 0;
3423 struct WS_sockaddr addr;
3424 int len = sizeof(addr);
3426 if (!optlen || *optlen < sizeof(DWORD) || !optval)
3428 SetLastError(WSAEFAULT);
3429 return SOCKET_ERROR;
3431 if (WS_getpeername(s, &addr, &len) == SOCKET_ERROR)
3432 *(DWORD *)optval = ~0u;
3433 else
3435 if (!pretendtime) FIXME("WS_SO_CONNECT_TIME - faking results\n");
3436 *(DWORD *)optval = pretendtime++;
3438 *optlen = sizeof(DWORD);
3439 return ret;
3441 /* As mentioned in setsockopt, Windows ignores this, so we
3442 * always return true here */
3443 case WS_SO_DONTROUTE:
3444 if (!optlen || *optlen < sizeof(BOOL) || !optval)
3446 SetLastError(WSAEFAULT);
3447 return SOCKET_ERROR;
3449 *(BOOL *)optval = TRUE;
3450 *optlen = sizeof(BOOL);
3451 return 0;
3453 case WS_SO_LINGER:
3455 struct linger lingval;
3456 int so_type;
3457 socklen_t len = sizeof(struct linger), slen = sizeof(int);
3459 /* struct linger and LINGER have different sizes */
3460 if (!optlen || *optlen < sizeof(LINGER) || !optval)
3462 SetLastError(WSAEFAULT);
3463 return SOCKET_ERROR;
3465 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3466 return SOCKET_ERROR;
3468 if ((getsockopt(fd, SOL_SOCKET, SO_TYPE, &so_type, &slen) == 0 && so_type == SOCK_DGRAM))
3470 SetLastError(WSAENOPROTOOPT);
3471 ret = SOCKET_ERROR;
3473 else if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0)
3475 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3476 ret = SOCKET_ERROR;
3478 else
3480 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
3481 ((LINGER *)optval)->l_linger = lingval.l_linger;
3482 *optlen = sizeof(struct linger);
3485 release_sock_fd( s, fd );
3486 return ret;
3489 case WS_SO_MAX_MSG_SIZE:
3490 if (!optlen || *optlen < sizeof(int) || !optval)
3492 SetLastError(WSAEFAULT);
3493 return SOCKET_ERROR;
3495 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
3496 *(int *)optval = 65507;
3497 *optlen = sizeof(int);
3498 return 0;
3500 /* SO_OPENTYPE does not require a valid socket handle. */
3501 case WS_SO_OPENTYPE:
3502 if (!optlen || *optlen < sizeof(int) || !optval)
3504 SetLastError(WSAEFAULT);
3505 return SOCKET_ERROR;
3507 *(int *)optval = get_per_thread_data()->opentype;
3508 *optlen = sizeof(int);
3509 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
3510 return 0;
3511 case WS_SO_PROTOCOL_INFOA:
3512 case WS_SO_PROTOCOL_INFOW:
3514 int size;
3515 WSAPROTOCOL_INFOW infow;
3517 ret = ws_protocol_info(s, optname == WS_SO_PROTOCOL_INFOW, &infow, &size);
3518 if (ret)
3520 if (!optlen || !optval || *optlen < size)
3522 if(optlen) *optlen = size;
3523 ret = 0;
3524 SetLastError(WSAEFAULT);
3526 else
3527 memcpy(optval, &infow, size);
3529 return ret ? 0 : SOCKET_ERROR;
3531 #ifdef SO_RCVTIMEO
3532 case WS_SO_RCVTIMEO:
3533 #endif
3534 #ifdef SO_SNDTIMEO
3535 case WS_SO_SNDTIMEO:
3536 #endif
3537 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
3539 struct timeval tv;
3540 socklen_t len = sizeof(struct timeval);
3542 if (!optlen || *optlen < sizeof(int)|| !optval)
3544 SetLastError(WSAEFAULT);
3545 return SOCKET_ERROR;
3547 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3548 return SOCKET_ERROR;
3550 convert_sockopt(&level, &optname);
3551 if (getsockopt(fd, level, optname, &tv, &len) != 0 )
3553 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3554 ret = SOCKET_ERROR;
3556 else
3558 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
3559 *optlen = sizeof(int);
3562 release_sock_fd( s, fd );
3563 return ret;
3565 #endif
3566 case WS_SO_TYPE:
3568 if (!optlen || *optlen < sizeof(int) || !optval)
3570 SetLastError(WSAEFAULT);
3571 return SOCKET_ERROR;
3573 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3574 return SOCKET_ERROR;
3576 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, optval, (socklen_t *)optlen) != 0 )
3578 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3579 ret = SOCKET_ERROR;
3581 else
3582 (*(int *)optval) = convert_socktype_u2w(*(int *)optval);
3584 release_sock_fd( s, fd );
3585 return ret;
3587 default:
3588 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
3589 SetLastError(WSAENOPROTOOPT);
3590 return SOCKET_ERROR;
3591 } /* end switch(optname) */
3592 }/* end case WS_SOL_SOCKET */
3593 #ifdef HAS_IPX
3594 case WS_NSPROTO_IPX:
3596 struct WS_sockaddr_ipx addr;
3597 IPX_ADDRESS_DATA *data;
3598 int namelen;
3599 switch(optname)
3601 case WS_IPX_PTYPE:
3602 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3603 #ifdef SOL_IPX
3604 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (socklen_t *)optlen) == -1)
3606 ret = SOCKET_ERROR;
3608 #else
3610 struct ipx val;
3611 socklen_t len=sizeof(struct ipx);
3612 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
3613 ret = SOCKET_ERROR;
3614 else
3615 *optval = (int)val.ipx_pt;
3617 #endif
3618 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
3619 release_sock_fd( s, fd );
3620 return ret;
3622 case WS_IPX_ADDRESS:
3624 * On a Win2000 system with one network card there are usually
3625 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
3626 * Using this call you can then retrieve info about this all.
3627 * In case of Linux it is a bit different. Usually you have
3628 * only "one" device active and further it is not possible to
3629 * query things like the linkspeed.
3631 FIXME("IPX_ADDRESS\n");
3632 namelen = sizeof(struct WS_sockaddr_ipx);
3633 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
3634 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
3636 data = (IPX_ADDRESS_DATA*)optval;
3637 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
3638 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
3639 data->adapternum = 0;
3640 data->wan = FALSE; /* We are not on a wan for now .. */
3641 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
3642 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
3643 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
3644 * note 1MB = 1000kB in this case */
3645 return 0;
3647 case WS_IPX_MAX_ADAPTER_NUM:
3648 FIXME("IPX_MAX_ADAPTER_NUM\n");
3649 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
3650 return 0;
3652 default:
3653 FIXME("IPX optname:%x\n", optname);
3654 return SOCKET_ERROR;
3655 }/* end switch(optname) */
3656 } /* end case WS_NSPROTO_IPX */
3657 #endif
3659 #ifdef HAS_IRDA
3660 #define MAX_IRDA_DEVICES 10
3662 case WS_SOL_IRLMP:
3663 switch(optname)
3665 case WS_IRLMP_ENUMDEVICES:
3667 char buf[sizeof(struct irda_device_list) +
3668 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
3669 int res;
3670 socklen_t len = sizeof(buf);
3672 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3673 return SOCKET_ERROR;
3674 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
3675 release_sock_fd( s, fd );
3676 if (res < 0)
3678 SetLastError(wsaErrno());
3679 return SOCKET_ERROR;
3681 else
3683 struct irda_device_list *src = (struct irda_device_list *)buf;
3684 DEVICELIST *dst = (DEVICELIST *)optval;
3685 INT needed = sizeof(DEVICELIST);
3686 unsigned int i;
3688 if (src->len > 0)
3689 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
3690 if (*optlen < needed)
3692 SetLastError(WSAEFAULT);
3693 return SOCKET_ERROR;
3695 *optlen = needed;
3696 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
3697 dst->numDevice = src->len;
3698 for (i = 0; i < src->len; i++)
3700 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
3701 src->dev[i].saddr, src->dev[i].daddr,
3702 src->dev[i].info, src->dev[i].hints[0],
3703 src->dev[i].hints[1]);
3704 memcpy( dst->Device[i].irdaDeviceID,
3705 &src->dev[i].daddr,
3706 sizeof(dst->Device[i].irdaDeviceID) ) ;
3707 memcpy( dst->Device[i].irdaDeviceName,
3708 src->dev[i].info,
3709 sizeof(dst->Device[i].irdaDeviceName) ) ;
3710 memcpy( &dst->Device[i].irdaDeviceHints1,
3711 &src->dev[i].hints[0],
3712 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
3713 memcpy( &dst->Device[i].irdaDeviceHints2,
3714 &src->dev[i].hints[1],
3715 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
3716 dst->Device[i].irdaCharSet = src->dev[i].charset;
3718 return 0;
3721 default:
3722 FIXME("IrDA optname:0x%x\n", optname);
3723 return SOCKET_ERROR;
3725 break; /* case WS_SOL_IRLMP */
3726 #undef MAX_IRDA_DEVICES
3727 #endif
3729 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3730 case WS_IPPROTO_TCP:
3731 switch(optname)
3733 case WS_TCP_NODELAY:
3734 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3735 return SOCKET_ERROR;
3736 convert_sockopt(&level, &optname);
3737 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3739 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3740 ret = SOCKET_ERROR;
3742 release_sock_fd( s, fd );
3743 return ret;
3745 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
3746 return SOCKET_ERROR;
3748 case WS_IPPROTO_IP:
3749 switch(optname)
3751 case WS_IP_ADD_MEMBERSHIP:
3752 case WS_IP_DROP_MEMBERSHIP:
3753 #ifdef IP_HDRINCL
3754 case WS_IP_HDRINCL:
3755 #endif
3756 case WS_IP_MULTICAST_IF:
3757 case WS_IP_MULTICAST_LOOP:
3758 case WS_IP_MULTICAST_TTL:
3759 case WS_IP_OPTIONS:
3760 #ifdef IP_PKTINFO
3761 case WS_IP_PKTINFO:
3762 #endif
3763 case WS_IP_TOS:
3764 case WS_IP_TTL:
3765 #ifdef IP_UNICAST_IF
3766 case WS_IP_UNICAST_IF:
3767 #endif
3768 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3769 return SOCKET_ERROR;
3770 convert_sockopt(&level, &optname);
3771 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3773 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3774 ret = SOCKET_ERROR;
3776 release_sock_fd( s, fd );
3777 return ret;
3778 case WS_IP_DONTFRAGMENT:
3779 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
3780 *(BOOL*)optval = FALSE;
3781 return 0;
3783 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
3784 return SOCKET_ERROR;
3786 case WS_IPPROTO_IPV6:
3787 switch(optname)
3789 #ifdef IPV6_ADD_MEMBERSHIP
3790 case WS_IPV6_ADD_MEMBERSHIP:
3791 #endif
3792 #ifdef IPV6_DROP_MEMBERSHIP
3793 case WS_IPV6_DROP_MEMBERSHIP:
3794 #endif
3795 case WS_IPV6_MULTICAST_IF:
3796 case WS_IPV6_MULTICAST_HOPS:
3797 case WS_IPV6_MULTICAST_LOOP:
3798 case WS_IPV6_UNICAST_HOPS:
3799 case WS_IPV6_V6ONLY:
3800 #ifdef IPV6_UNICAST_IF
3801 case WS_IPV6_UNICAST_IF:
3802 #endif
3803 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3804 return SOCKET_ERROR;
3805 convert_sockopt(&level, &optname);
3806 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3808 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3809 ret = SOCKET_ERROR;
3811 release_sock_fd( s, fd );
3812 return ret;
3813 case WS_IPV6_DONTFRAG:
3814 FIXME("WS_IPV6_DONTFRAG is always false!\n");
3815 *(BOOL*)optval = FALSE;
3816 return 0;
3818 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
3819 return SOCKET_ERROR;
3821 default:
3822 WARN("Unknown level: 0x%08x\n", level);
3823 SetLastError(WSAEINVAL);
3824 return SOCKET_ERROR;
3825 } /* end switch(level) */
3828 /***********************************************************************
3829 * htonl (WS2_32.8)
3831 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
3833 return htonl(hostlong);
3837 /***********************************************************************
3838 * htons (WS2_32.9)
3840 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
3842 return htons(hostshort);
3845 /***********************************************************************
3846 * WSAHtonl (WS2_32.46)
3847 * From MSDN description of error codes, this function should also
3848 * check if WinSock has been initialized and the socket is a valid
3849 * socket. But why? This function only translates a host byte order
3850 * u_long into a network byte order u_long...
3852 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
3854 if (lpnetlong)
3856 *lpnetlong = htonl(hostlong);
3857 return 0;
3859 SetLastError(WSAEFAULT);
3860 return SOCKET_ERROR;
3863 /***********************************************************************
3864 * WSAHtons (WS2_32.47)
3865 * From MSDN description of error codes, this function should also
3866 * check if WinSock has been initialized and the socket is a valid
3867 * socket. But why? This function only translates a host byte order
3868 * u_short into a network byte order u_short...
3870 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
3873 if (lpnetshort)
3875 *lpnetshort = htons(hostshort);
3876 return 0;
3878 SetLastError(WSAEFAULT);
3879 return SOCKET_ERROR;
3883 /***********************************************************************
3884 * inet_addr (WS2_32.11)
3886 WS_u_long WINAPI WS_inet_addr(const char *cp)
3888 if (!cp) return INADDR_NONE;
3889 return inet_addr(cp);
3893 /***********************************************************************
3894 * ntohl (WS2_32.14)
3896 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
3898 return ntohl(netlong);
3902 /***********************************************************************
3903 * ntohs (WS2_32.15)
3905 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
3907 return ntohs(netshort);
3911 /***********************************************************************
3912 * inet_ntoa (WS2_32.12)
3914 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
3916 char* s = inet_ntoa(*((struct in_addr*)&in));
3917 if( s )
3919 struct per_thread_data *data = get_per_thread_data();
3920 strcpy(data->ntoa_buffer, s);
3921 return data->ntoa_buffer;
3923 SetLastError(wsaErrno());
3924 return NULL;
3927 static const char *debugstr_wsaioctl(DWORD ioctl)
3929 const char *buf_type, *family;
3931 switch(ioctl & 0x18000000)
3933 case WS_IOC_WS2:
3934 family = "IOC_WS2";
3935 break;
3936 case WS_IOC_PROTOCOL:
3937 family = "IOC_PROTOCOL";
3938 break;
3939 case WS_IOC_VENDOR:
3940 family = "IOC_VENDOR";
3941 break;
3942 default: /* WS_IOC_UNIX */
3944 BYTE size = (ioctl >> 16) & WS_IOCPARM_MASK;
3945 char x = (ioctl & 0xff00) >> 8;
3946 BYTE y = ioctl & 0xff;
3947 char args[14];
3949 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3951 case WS_IOC_VOID:
3952 buf_type = "_IO";
3953 sprintf(args, "%d, %d", x, y);
3954 break;
3955 case WS_IOC_IN:
3956 buf_type = "_IOW";
3957 sprintf(args, "'%c', %d, %d", x, y, size);
3958 break;
3959 case WS_IOC_OUT:
3960 buf_type = "_IOR";
3961 sprintf(args, "'%c', %d, %d", x, y, size);
3962 break;
3963 default:
3964 buf_type = "?";
3965 sprintf(args, "'%c', %d, %d", x, y, size);
3966 break;
3968 return wine_dbg_sprintf("%s(%s)", buf_type, args);
3972 /* We are different from WS_IOC_UNIX. */
3973 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3975 case WS_IOC_VOID:
3976 buf_type = "_WSAIO";
3977 break;
3978 case WS_IOC_INOUT:
3979 buf_type = "_WSAIORW";
3980 break;
3981 case WS_IOC_IN:
3982 buf_type = "_WSAIOW";
3983 break;
3984 case WS_IOC_OUT:
3985 buf_type = "_WSAIOR";
3986 break;
3987 default:
3988 buf_type = "?";
3989 break;
3992 return wine_dbg_sprintf("%s(%s, %d)", buf_type, family,
3993 (USHORT)(ioctl & 0xffff));
3996 /* do an ioctl call through the server */
3997 static DWORD server_ioctl_sock( SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size,
3998 LPVOID out_buff, DWORD out_size, LPDWORD ret_size,
3999 LPWSAOVERLAPPED overlapped,
4000 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
4002 HANDLE event = overlapped ? overlapped->hEvent : 0;
4003 HANDLE handle = SOCKET2HANDLE( s );
4004 struct ws2_async *wsa;
4005 NTSTATUS status;
4006 PIO_STATUS_BLOCK io;
4008 if (!(wsa = (struct ws2_async *)alloc_async_io( sizeof(*wsa) )))
4009 return WSA_NOT_ENOUGH_MEMORY;
4010 wsa->hSocket = handle;
4011 wsa->user_overlapped = overlapped;
4012 wsa->completion_func = completion;
4013 io = (overlapped ? (PIO_STATUS_BLOCK)overlapped : &wsa->local_iosb);
4015 status = NtDeviceIoControlFile( handle, event, ws2_async_apc, wsa, io, code,
4016 in_buff, in_size, out_buff, out_size );
4017 if (status == STATUS_NOT_SUPPORTED)
4019 FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
4020 code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
4022 else if (status == STATUS_SUCCESS)
4023 *ret_size = io->Information; /* "Information" is the size written to the output buffer */
4025 if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, wsa );
4027 return NtStatusToWSAError( status );
4030 /**********************************************************************
4031 * WSAIoctl (WS2_32.50)
4034 INT WINAPI WSAIoctl(SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size, LPVOID out_buff,
4035 DWORD out_size, LPDWORD ret_size, LPWSAOVERLAPPED overlapped,
4036 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
4038 int fd;
4039 DWORD status = 0, total = 0;
4041 TRACE("%04lx, %s, %p, %d, %p, %d, %p, %p, %p\n",
4042 s, debugstr_wsaioctl(code), in_buff, in_size, out_buff, out_size, ret_size, overlapped, completion);
4044 switch (code)
4046 case WS_FIONBIO:
4047 if (in_size != sizeof(WS_u_long) || IS_INTRESOURCE(in_buff))
4049 SetLastError(WSAEFAULT);
4050 return SOCKET_ERROR;
4052 TRACE("-> FIONBIO (%x)\n", *(WS_u_long*)in_buff);
4053 if (_get_sock_mask(s))
4055 /* AsyncSelect()'ed sockets are always nonblocking */
4056 if (!*(WS_u_long *)in_buff) status = WSAEINVAL;
4057 break;
4059 if (*(WS_u_long *)in_buff)
4060 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
4061 else
4062 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
4063 break;
4065 case WS_FIONREAD:
4067 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
4069 SetLastError(WSAEFAULT);
4070 return SOCKET_ERROR;
4072 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
4073 if (ioctl(fd, FIONREAD, out_buff ) == -1)
4074 status = (errno == EBADF) ? WSAENOTSOCK : wsaErrno();
4075 release_sock_fd( s, fd );
4076 break;
4079 case WS_SIOCATMARK:
4081 unsigned int oob = 0, atmark = 0;
4082 socklen_t oobsize = sizeof(int);
4083 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
4085 SetLastError(WSAEFAULT);
4086 return SOCKET_ERROR;
4088 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
4089 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
4090 if ((getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &oob, &oobsize ) == -1)
4091 || (!oob && ioctl(fd, SIOCATMARK, &atmark ) == -1))
4092 status = (errno == EBADF) ? WSAENOTSOCK : wsaErrno();
4093 else
4095 /* The SIOCATMARK value read from ioctl() is reversed
4096 * because BSD returns TRUE if it's in the OOB mark
4097 * while Windows returns TRUE if there are NO OOB bytes.
4099 (*(WS_u_long *) out_buff) = oob || !atmark;
4102 release_sock_fd( s, fd );
4103 break;
4106 case WS_FIOASYNC:
4107 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
4108 SetLastError(WSAEINVAL);
4109 return SOCKET_ERROR;
4111 case WS_SIO_GET_INTERFACE_LIST:
4113 INTERFACE_INFO* intArray = out_buff;
4114 DWORD size, numInt = 0, apiReturn;
4116 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
4118 if (!out_buff || !ret_size)
4120 SetLastError(WSAEFAULT);
4121 return SOCKET_ERROR;
4124 fd = get_sock_fd( s, 0, NULL );
4125 if (fd == -1) return SOCKET_ERROR;
4127 apiReturn = GetAdaptersInfo(NULL, &size);
4128 if (apiReturn == ERROR_BUFFER_OVERFLOW)
4130 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
4132 if (table)
4134 if (GetAdaptersInfo(table, &size) == NO_ERROR)
4136 PIP_ADAPTER_INFO ptr;
4138 for (ptr = table, numInt = 0; ptr; ptr = ptr->Next)
4140 unsigned int addr, mask, bcast;
4141 struct ifreq ifInfo;
4143 /* Skip interfaces without an IPv4 address. */
4144 if (ptr->IpAddressList.IpAddress.String[0] == '\0')
4145 continue;
4147 if ((numInt + 1)*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > out_size)
4149 WARN("Buffer too small = %u, out_size = %u\n", numInt + 1, out_size);
4150 status = WSAEFAULT;
4151 break;
4154 /* Socket Status Flags */
4155 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
4156 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
4158 ERR("Error obtaining status flags for socket!\n");
4159 status = WSAEINVAL;
4160 break;
4162 else
4164 /* set flags; the values of IFF_* are not the same
4165 under Linux and Windows, therefore must generate
4166 new flags */
4167 intArray->iiFlags = 0;
4168 if (ifInfo.ifr_flags & IFF_BROADCAST)
4169 intArray->iiFlags |= WS_IFF_BROADCAST;
4170 #ifdef IFF_POINTOPOINT
4171 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
4172 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
4173 #endif
4174 if (ifInfo.ifr_flags & IFF_LOOPBACK)
4175 intArray->iiFlags |= WS_IFF_LOOPBACK;
4176 if (ifInfo.ifr_flags & IFF_UP)
4177 intArray->iiFlags |= WS_IFF_UP;
4178 if (ifInfo.ifr_flags & IFF_MULTICAST)
4179 intArray->iiFlags |= WS_IFF_MULTICAST;
4182 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
4183 mask = inet_addr(ptr->IpAddressList.IpMask.String);
4184 bcast = addr | ~mask;
4185 intArray->iiAddress.AddressIn.sin_family = AF_INET;
4186 intArray->iiAddress.AddressIn.sin_port = 0;
4187 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
4188 addr;
4189 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
4190 intArray->iiNetmask.AddressIn.sin_port = 0;
4191 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
4192 mask;
4193 intArray->iiBroadcastAddress.AddressIn.sin_family =
4194 AF_INET;
4195 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
4196 intArray->iiBroadcastAddress.AddressIn.sin_addr.
4197 WS_s_addr = bcast;
4198 intArray++;
4199 numInt++;
4202 else
4204 ERR("Unable to get interface table!\n");
4205 status = WSAEINVAL;
4207 HeapFree(GetProcessHeap(),0,table);
4209 else status = WSAEINVAL;
4211 else if (apiReturn != ERROR_NO_DATA)
4213 ERR("Unable to get interface table!\n");
4214 status = WSAEINVAL;
4216 /* Calculate the size of the array being returned */
4217 total = sizeof(INTERFACE_INFO) * numInt;
4218 release_sock_fd( s, fd );
4219 break;
4222 case WS_SIO_ADDRESS_LIST_QUERY:
4224 DWORD size;
4226 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
4228 if (!ret_size)
4230 SetLastError(WSAEFAULT);
4231 return SOCKET_ERROR;
4234 if (out_size && out_size < FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[0]))
4236 *ret_size = 0;
4237 SetLastError(WSAEINVAL);
4238 return SOCKET_ERROR;
4241 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
4243 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
4244 SOCKET_ADDRESS_LIST *sa_list;
4245 SOCKADDR_IN *sockaddr;
4246 SOCKET_ADDRESS *sa;
4247 unsigned int i;
4248 DWORD num;
4250 if (!table || GetAdaptersInfo(table, &size))
4252 HeapFree(GetProcessHeap(), 0, table);
4253 status = WSAEINVAL;
4254 break;
4257 for (p = table, num = 0; p; p = p->Next)
4258 if (p->IpAddressList.IpAddress.String[0]) num++;
4260 total = FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[num]) + num * sizeof(*sockaddr);
4261 if (total > out_size || !out_buff)
4263 *ret_size = total;
4264 HeapFree(GetProcessHeap(), 0, table);
4265 status = WSAEFAULT;
4266 break;
4269 sa_list = out_buff;
4270 sa = sa_list->Address;
4271 sockaddr = (SOCKADDR_IN *)&sa[num];
4272 sa_list->iAddressCount = num;
4274 for (p = table, i = 0; p; p = p->Next)
4276 if (!p->IpAddressList.IpAddress.String[0]) continue;
4278 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
4279 sa[i].iSockaddrLength = sizeof(SOCKADDR);
4281 sockaddr[i].sin_family = AF_INET;
4282 sockaddr[i].sin_port = 0;
4283 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
4284 i++;
4287 HeapFree(GetProcessHeap(), 0, table);
4289 else
4291 WARN("unable to get IP address list\n");
4292 status = WSAEINVAL;
4294 break;
4297 case WS_SIO_FLUSH:
4298 FIXME("SIO_FLUSH: stub.\n");
4299 break;
4301 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
4303 static const GUID connectex_guid = WSAID_CONNECTEX;
4304 static const GUID disconnectex_guid = WSAID_DISCONNECTEX;
4305 static const GUID acceptex_guid = WSAID_ACCEPTEX;
4306 static const GUID getaccepexsockaddrs_guid = WSAID_GETACCEPTEXSOCKADDRS;
4307 static const GUID transmitfile_guid = WSAID_TRANSMITFILE;
4308 static const GUID transmitpackets_guid = WSAID_TRANSMITPACKETS;
4309 static const GUID wsarecvmsg_guid = WSAID_WSARECVMSG;
4310 static const GUID wsasendmsg_guid = WSAID_WSASENDMSG;
4312 if ( IsEqualGUID(&connectex_guid, in_buff) )
4314 *(LPFN_CONNECTEX *)out_buff = WS2_ConnectEx;
4315 break;
4317 else if ( IsEqualGUID(&disconnectex_guid, in_buff) )
4319 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented DisconnectEx\n");
4321 else if ( IsEqualGUID(&acceptex_guid, in_buff) )
4323 *(LPFN_ACCEPTEX *)out_buff = WS2_AcceptEx;
4324 break;
4326 else if ( IsEqualGUID(&getaccepexsockaddrs_guid, in_buff) )
4328 *(LPFN_GETACCEPTEXSOCKADDRS *)out_buff = WS2_GetAcceptExSockaddrs;
4329 break;
4331 else if ( IsEqualGUID(&transmitfile_guid, in_buff) )
4333 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitFile\n");
4335 else if ( IsEqualGUID(&transmitpackets_guid, in_buff) )
4337 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitPackets\n");
4339 else if ( IsEqualGUID(&wsarecvmsg_guid, in_buff) )
4341 *(LPFN_WSARECVMSG *)out_buff = WS2_WSARecvMsg;
4342 break;
4344 else if ( IsEqualGUID(&wsasendmsg_guid, in_buff) )
4346 *(LPFN_WSASENDMSG *)out_buff = WSASendMsg;
4347 break;
4349 else
4350 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff));
4352 status = WSAEOPNOTSUPP;
4353 break;
4355 case WS_SIO_KEEPALIVE_VALS:
4357 struct tcp_keepalive *k;
4358 int keepalive, keepidle, keepintvl;
4360 if (!in_buff || in_size < sizeof(struct tcp_keepalive))
4362 SetLastError(WSAEFAULT);
4363 return SOCKET_ERROR;
4366 k = in_buff;
4367 keepalive = k->onoff ? 1 : 0;
4368 keepidle = max( 1, (k->keepalivetime + 500) / 1000 );
4369 keepintvl = max( 1, (k->keepaliveinterval + 500) / 1000 );
4371 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
4373 fd = get_sock_fd(s, 0, NULL);
4374 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
4375 status = WSAEINVAL;
4376 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
4377 /* these values need to be set only if SO_KEEPALIVE is enabled */
4378 else if(keepalive)
4380 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
4381 status = WSAEINVAL;
4382 else if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
4383 status = WSAEINVAL;
4385 #else
4386 else
4387 FIXME("ignoring keepalive interval and timeout\n");
4388 #endif
4389 release_sock_fd(s, fd);
4390 break;
4392 case WS_SIO_ROUTING_INTERFACE_QUERY:
4394 struct WS_sockaddr *daddr = (struct WS_sockaddr *)in_buff;
4395 struct WS_sockaddr_in *daddr_in = (struct WS_sockaddr_in *)daddr;
4396 struct WS_sockaddr_in *saddr_in = out_buff;
4397 MIB_IPFORWARDROW row;
4398 PMIB_IPADDRTABLE ipAddrTable = NULL;
4399 DWORD size, i, found_index;
4401 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
4403 if (!in_buff || in_size < sizeof(struct WS_sockaddr) ||
4404 !out_buff || out_size < sizeof(struct WS_sockaddr_in) || !ret_size)
4406 SetLastError(WSAEFAULT);
4407 return SOCKET_ERROR;
4409 if (daddr->sa_family != AF_INET)
4411 FIXME("unsupported address family %d\n", daddr->sa_family);
4412 status = WSAEAFNOSUPPORT;
4413 break;
4415 if (GetBestRoute(daddr_in->sin_addr.S_un.S_addr, 0, &row) != NOERROR ||
4416 GetIpAddrTable(NULL, &size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
4418 status = WSAEFAULT;
4419 break;
4421 ipAddrTable = HeapAlloc(GetProcessHeap(), 0, size);
4422 if (GetIpAddrTable(ipAddrTable, &size, FALSE))
4424 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4425 status = WSAEFAULT;
4426 break;
4428 for (i = 0, found_index = ipAddrTable->dwNumEntries;
4429 i < ipAddrTable->dwNumEntries; i++)
4431 if (ipAddrTable->table[i].dwIndex == row.dwForwardIfIndex)
4432 found_index = i;
4434 if (found_index == ipAddrTable->dwNumEntries)
4436 ERR("no matching IP address for interface %d\n",
4437 row.dwForwardIfIndex);
4438 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4439 status = WSAEFAULT;
4440 break;
4442 saddr_in->sin_family = AF_INET;
4443 saddr_in->sin_addr.S_un.S_addr = ipAddrTable->table[found_index].dwAddr;
4444 saddr_in->sin_port = 0;
4445 total = sizeof(struct WS_sockaddr_in);
4446 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4447 break;
4449 case WS_SIO_SET_COMPATIBILITY_MODE:
4450 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
4451 status = WSAEOPNOTSUPP;
4452 break;
4453 case WS_SIO_UDP_CONNRESET:
4454 FIXME("WS_SIO_UDP_CONNRESET stub\n");
4455 break;
4456 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
4457 SetLastError(WSAEOPNOTSUPP);
4458 return SOCKET_ERROR;
4459 default:
4460 status = WSAEOPNOTSUPP;
4461 break;
4464 if (status == WSAEOPNOTSUPP)
4466 status = server_ioctl_sock(s, code, in_buff, in_size, out_buff, out_size, &total,
4467 overlapped, completion);
4468 if (status != WSAEOPNOTSUPP)
4470 if (status == 0 || status == WSA_IO_PENDING)
4471 TRACE("-> %s request\n", debugstr_wsaioctl(code));
4472 else
4473 ERR("-> %s request failed with status 0x%x\n", debugstr_wsaioctl(code), status);
4475 /* overlapped and completion operations will be handled by the server */
4476 completion = NULL;
4477 overlapped = NULL;
4479 else
4480 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code));
4483 if (completion)
4485 FIXME( "completion routine %p not supported\n", completion );
4487 else if (overlapped)
4489 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
4490 overlapped->Internal = status;
4491 overlapped->InternalHigh = total;
4492 if (overlapped->hEvent) NtSetEvent( overlapped->hEvent, NULL );
4493 if (cvalue) WS_AddCompletion( HANDLE2SOCKET(s), cvalue, status, total );
4496 if (!status)
4498 if (ret_size) *ret_size = total;
4499 return 0;
4501 SetLastError( status );
4502 return SOCKET_ERROR;
4506 /***********************************************************************
4507 * ioctlsocket (WS2_32.10)
4509 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
4511 DWORD ret_size;
4512 return WSAIoctl( s, cmd, argp, sizeof(WS_u_long), argp, sizeof(WS_u_long), &ret_size, NULL, NULL );
4515 /***********************************************************************
4516 * listen (WS2_32.13)
4518 int WINAPI WS_listen(SOCKET s, int backlog)
4520 int fd = get_sock_fd( s, FILE_READ_DATA, NULL ), ret = SOCKET_ERROR;
4522 TRACE("socket %04lx, backlog %d\n", s, backlog);
4523 if (fd != -1)
4525 int bound = is_fd_bound(fd, NULL, NULL);
4527 if (bound <= 0)
4529 SetLastError(bound == -1 ? wsaErrno() : WSAEINVAL);
4531 else if (listen(fd, backlog) == 0)
4533 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
4534 FD_WINE_LISTENING,
4535 FD_CONNECT|FD_WINE_CONNECTED);
4536 ret = 0;
4538 else
4539 SetLastError(wsaErrno());
4540 release_sock_fd( s, fd );
4542 else
4543 SetLastError(WSAENOTSOCK);
4544 return ret;
4547 /***********************************************************************
4548 * recv (WS2_32.16)
4550 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
4552 DWORD n, dwFlags = flags;
4553 WSABUF wsabuf;
4555 wsabuf.len = len;
4556 wsabuf.buf = buf;
4558 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
4559 return SOCKET_ERROR;
4560 else
4561 return n;
4564 /***********************************************************************
4565 * recvfrom (WS2_32.17)
4567 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
4568 struct WS_sockaddr *from, int *fromlen)
4570 DWORD n, dwFlags = flags;
4571 WSABUF wsabuf;
4573 wsabuf.len = len;
4574 wsabuf.buf = buf;
4576 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL, NULL) == SOCKET_ERROR )
4577 return SOCKET_ERROR;
4578 else
4579 return n;
4582 /* allocate a poll array for the corresponding fd sets */
4583 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
4584 const WS_fd_set *exceptfds, int *count_ptr )
4586 unsigned int i, j = 0, count = 0;
4587 struct pollfd *fds;
4589 if (readfds) count += readfds->fd_count;
4590 if (writefds) count += writefds->fd_count;
4591 if (exceptfds) count += exceptfds->fd_count;
4592 *count_ptr = count;
4593 if (!count)
4595 SetLastError(WSAEINVAL);
4596 return NULL;
4598 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0]))))
4600 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
4601 return NULL;
4603 if (readfds)
4604 for (i = 0; i < readfds->fd_count; i++, j++)
4606 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
4607 if (fds[j].fd == -1) goto failed;
4608 fds[j].revents = 0;
4609 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1)
4611 fds[j].events = POLLIN;
4613 else
4615 release_sock_fd( readfds->fd_array[i], fds[j].fd );
4616 fds[j].fd = -1;
4617 fds[j].events = 0;
4620 if (writefds)
4621 for (i = 0; i < writefds->fd_count; i++, j++)
4623 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
4624 if (fds[j].fd == -1) goto failed;
4625 fds[j].revents = 0;
4626 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1)
4628 fds[j].events = POLLOUT;
4630 else
4632 release_sock_fd( writefds->fd_array[i], fds[j].fd );
4633 fds[j].fd = -1;
4634 fds[j].events = 0;
4637 if (exceptfds)
4638 for (i = 0; i < exceptfds->fd_count; i++, j++)
4640 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
4641 if (fds[j].fd == -1) goto failed;
4642 fds[j].revents = 0;
4643 if (is_fd_bound(fds[j].fd, NULL, NULL) == 1)
4645 int oob_inlined = 0;
4646 socklen_t olen = sizeof(oob_inlined);
4648 fds[j].events = POLLHUP;
4650 /* Check if we need to test for urgent data or not */
4651 getsockopt(fds[j].fd, SOL_SOCKET, SO_OOBINLINE, (char*) &oob_inlined, &olen);
4652 if (!oob_inlined)
4653 fds[j].events |= POLLPRI;
4655 else
4657 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
4658 fds[j].fd = -1;
4659 fds[j].events = 0;
4662 return fds;
4664 failed:
4665 count = j;
4666 j = 0;
4667 if (readfds)
4668 for (i = 0; i < readfds->fd_count && j < count; i++, j++)
4669 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
4670 if (writefds)
4671 for (i = 0; i < writefds->fd_count && j < count; i++, j++)
4672 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
4673 if (exceptfds)
4674 for (i = 0; i < exceptfds->fd_count && j < count; i++, j++)
4675 if (fds[j].fd != -1) release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
4676 HeapFree( GetProcessHeap(), 0, fds );
4677 return NULL;
4680 /* release the file descriptor obtained in fd_sets_to_poll */
4681 /* must be called with the original fd_set arrays, before calling get_poll_results */
4682 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
4683 const WS_fd_set *exceptfds, struct pollfd *fds )
4685 unsigned int i, j = 0;
4687 if (readfds)
4689 for (i = 0; i < readfds->fd_count; i++, j++)
4690 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
4692 if (writefds)
4694 for (i = 0; i < writefds->fd_count; i++, j++)
4695 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
4697 if (exceptfds)
4699 for (i = 0; i < exceptfds->fd_count; i++, j++)
4700 if (fds[j].fd != -1) release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
4704 /* map the poll results back into the Windows fd sets */
4705 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
4706 const struct pollfd *fds )
4708 const struct pollfd *poll_writefds = fds + (readfds ? readfds->fd_count : 0);
4709 const struct pollfd *poll_exceptfds = poll_writefds + (writefds ? writefds->fd_count : 0);
4710 unsigned int i, k, total = 0;
4712 if (readfds)
4714 for (i = k = 0; i < readfds->fd_count; i++)
4716 if (fds[i].revents ||
4717 (readfds == writefds && (poll_writefds[i].revents & POLLOUT) && !(poll_writefds[i].revents & POLLHUP)) ||
4718 (readfds == exceptfds && poll_exceptfds[i].revents))
4719 readfds->fd_array[k++] = readfds->fd_array[i];
4721 readfds->fd_count = k;
4722 total += k;
4724 if (writefds && writefds != readfds)
4726 for (i = k = 0; i < writefds->fd_count; i++)
4728 if (((poll_writefds[i].revents & POLLOUT) && !(poll_writefds[i].revents & POLLHUP)) ||
4729 (writefds == exceptfds && poll_exceptfds[i].revents))
4730 writefds->fd_array[k++] = writefds->fd_array[i];
4732 writefds->fd_count = k;
4733 total += k;
4735 if (exceptfds && exceptfds != readfds && exceptfds != writefds)
4737 for (i = k = 0; i < exceptfds->fd_count; i++)
4738 if (poll_exceptfds[i].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
4739 exceptfds->fd_count = k;
4740 total += k;
4742 return total;
4746 /***********************************************************************
4747 * select (WS2_32.18)
4749 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
4750 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
4751 const struct WS_timeval* ws_timeout)
4753 struct pollfd *pollfds;
4754 struct timeval tv1, tv2;
4755 int torig = 0;
4756 int count, ret, timeout = -1;
4758 TRACE("read %p, write %p, excp %p timeout %p\n",
4759 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
4761 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )))
4762 return SOCKET_ERROR;
4764 if (ws_timeout)
4766 torig = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
4767 timeout = torig;
4768 gettimeofday( &tv1, 0 );
4771 while ((ret = poll( pollfds, count, timeout )) < 0)
4773 if (errno == EINTR)
4775 if (!ws_timeout) continue;
4776 gettimeofday( &tv2, 0 );
4778 tv2.tv_sec -= tv1.tv_sec;
4779 tv2.tv_usec -= tv1.tv_usec;
4780 if (tv2.tv_usec < 0)
4782 tv2.tv_usec += 1000000;
4783 tv2.tv_sec -= 1;
4786 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
4787 if (timeout <= 0)
4789 ret = 0;
4790 break;
4792 } else break;
4794 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
4796 if (ret == -1) SetLastError(wsaErrno());
4797 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
4798 HeapFree( GetProcessHeap(), 0, pollfds );
4799 return ret;
4802 /* helper to send completion messages for client-only i/o operation case */
4803 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
4804 ULONG Information )
4806 SERVER_START_REQ( add_fd_completion )
4808 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
4809 req->cvalue = CompletionValue;
4810 req->status = CompletionStatus;
4811 req->information = Information;
4812 wine_server_call( req );
4814 SERVER_END_REQ;
4818 /***********************************************************************
4819 * send (WS2_32.19)
4821 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
4823 DWORD n;
4824 WSABUF wsabuf;
4826 wsabuf.len = len;
4827 wsabuf.buf = (char*) buf;
4829 if ( WS2_sendto( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
4830 return SOCKET_ERROR;
4831 else
4832 return n;
4835 /***********************************************************************
4836 * WSASend (WS2_32.72)
4838 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4839 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4840 LPWSAOVERLAPPED lpOverlapped,
4841 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4843 return WS2_sendto( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
4844 NULL, 0, lpOverlapped, lpCompletionRoutine );
4847 /***********************************************************************
4848 * WSASendDisconnect (WS2_32.73)
4850 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
4852 return WS_shutdown( s, SD_SEND );
4856 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4857 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4858 const struct WS_sockaddr *to, int tolen,
4859 LPWSAOVERLAPPED lpOverlapped,
4860 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4862 unsigned int i, options;
4863 int n, fd, err, overlapped, flags;
4864 struct ws2_async *wsa = NULL, localwsa;
4865 int totalLength = 0;
4866 DWORD bytes_sent;
4867 BOOL is_blocking;
4869 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
4870 s, lpBuffers, dwBufferCount, dwFlags,
4871 to, tolen, lpOverlapped, lpCompletionRoutine);
4873 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
4874 TRACE( "fd=%d, options=%x\n", fd, options );
4876 if ( fd == -1 ) return SOCKET_ERROR;
4878 if (!lpOverlapped && !lpNumberOfBytesSent)
4880 err = WSAEFAULT;
4881 goto error;
4884 overlapped = (lpOverlapped || lpCompletionRoutine) &&
4885 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
4886 if (overlapped || dwBufferCount > 1)
4888 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[dwBufferCount]))))
4890 err = WSAEFAULT;
4891 goto error;
4894 else
4895 wsa = &localwsa;
4897 wsa->hSocket = SOCKET2HANDLE(s);
4898 wsa->addr = (struct WS_sockaddr *)to;
4899 wsa->addrlen.val = tolen;
4900 wsa->flags = dwFlags;
4901 wsa->lpFlags = &wsa->flags;
4902 wsa->control = NULL;
4903 wsa->n_iovecs = dwBufferCount;
4904 wsa->first_iovec = 0;
4905 for ( i = 0; i < dwBufferCount; i++ )
4907 wsa->iovec[i].iov_base = lpBuffers[i].buf;
4908 wsa->iovec[i].iov_len = lpBuffers[i].len;
4909 totalLength += lpBuffers[i].len;
4912 flags = convert_flags(dwFlags);
4913 n = WS2_send( fd, wsa, flags );
4914 if (n == -1 && errno != EAGAIN)
4916 err = wsaErrno();
4917 goto error;
4920 if (overlapped)
4922 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
4923 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
4925 wsa->user_overlapped = lpOverlapped;
4926 wsa->completion_func = lpCompletionRoutine;
4927 release_sock_fd( s, fd );
4929 if (n == -1 || n < totalLength)
4931 iosb->u.Status = STATUS_PENDING;
4932 iosb->Information = n == -1 ? 0 : n;
4934 SERVER_START_REQ( register_async )
4936 req->type = ASYNC_TYPE_WRITE;
4937 req->async.handle = wine_server_obj_handle( wsa->hSocket );
4938 req->async.callback = wine_server_client_ptr( WS2_async_send );
4939 req->async.iosb = wine_server_client_ptr( iosb );
4940 req->async.arg = wine_server_client_ptr( wsa );
4941 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
4942 req->async.cvalue = cvalue;
4943 err = wine_server_call( req );
4945 SERVER_END_REQ;
4947 /* Enable the event only after starting the async. The server will deliver it as soon as
4948 the async is done. */
4949 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
4951 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
4952 SetLastError(NtStatusToWSAError( err ));
4953 return SOCKET_ERROR;
4956 iosb->u.Status = STATUS_SUCCESS;
4957 iosb->Information = n;
4958 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = n;
4959 if (!wsa->completion_func)
4961 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
4962 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
4963 HeapFree( GetProcessHeap(), 0, wsa );
4965 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
4966 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
4967 SetLastError(ERROR_SUCCESS);
4968 return 0;
4971 if ((err = _is_blocking( s, &is_blocking )))
4973 err = NtStatusToWSAError( err );
4974 goto error;
4977 if ( is_blocking )
4979 /* On a blocking non-overlapped stream socket,
4980 * sending blocks until the entire buffer is sent. */
4981 DWORD timeout_start = GetTickCount();
4983 bytes_sent = n == -1 ? 0 : n;
4985 while (wsa->first_iovec < wsa->n_iovecs)
4987 struct pollfd pfd;
4988 int timeout = GET_SNDTIMEO(fd);
4990 if (timeout != -1)
4992 timeout -= GetTickCount() - timeout_start;
4993 if (timeout < 0) timeout = 0;
4996 pfd.fd = fd;
4997 pfd.events = POLLOUT;
4999 if (!timeout || !poll( &pfd, 1, timeout ))
5001 err = WSAETIMEDOUT;
5002 goto error; /* msdn says a timeout in send is fatal */
5005 n = WS2_send( fd, wsa, flags );
5006 if (n == -1 && errno != EAGAIN)
5008 err = wsaErrno();
5009 goto error;
5012 if (n >= 0)
5013 bytes_sent += n;
5016 else /* non-blocking */
5018 if (n < totalLength)
5019 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
5020 if (n == -1)
5022 err = WSAEWOULDBLOCK;
5023 goto error;
5025 bytes_sent = n;
5028 TRACE(" -> %i bytes\n", bytes_sent);
5030 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = bytes_sent;
5031 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
5032 release_sock_fd( s, fd );
5033 SetLastError(ERROR_SUCCESS);
5034 return 0;
5036 error:
5037 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
5038 release_sock_fd( s, fd );
5039 WARN(" -> ERROR %d\n", err);
5040 SetLastError(err);
5041 return SOCKET_ERROR;
5044 /***********************************************************************
5045 * WSASendTo (WS2_32.74)
5047 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5048 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
5049 const struct WS_sockaddr *to, int tolen,
5050 LPWSAOVERLAPPED lpOverlapped,
5051 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5053 return WS2_sendto( s, lpBuffers, dwBufferCount,
5054 lpNumberOfBytesSent, dwFlags,
5055 to, tolen,
5056 lpOverlapped, lpCompletionRoutine );
5059 /***********************************************************************
5060 * sendto (WS2_32.20)
5062 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
5063 const struct WS_sockaddr *to, int tolen)
5065 DWORD n;
5066 WSABUF wsabuf;
5068 wsabuf.len = len;
5069 wsabuf.buf = (char*) buf;
5071 if ( WS2_sendto(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
5072 return SOCKET_ERROR;
5073 else
5074 return n;
5077 /***********************************************************************
5078 * setsockopt (WS2_32.21)
5080 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
5081 const char *optval, int optlen)
5083 int fd;
5084 int woptval;
5085 struct linger linger;
5086 struct timeval tval;
5088 TRACE("(socket %04lx, %s, optval %s, optlen %d)\n", s,
5089 debugstr_sockopt(level, optname), debugstr_optval(optval, optlen),
5090 optlen);
5092 /* some broken apps pass the value directly instead of a pointer to it */
5093 if(optlen && IS_INTRESOURCE(optval))
5095 SetLastError(WSAEFAULT);
5096 return SOCKET_ERROR;
5099 switch(level)
5101 case WS_SOL_SOCKET:
5102 switch(optname)
5104 /* Some options need some conversion before they can be sent to
5105 * setsockopt. The conversions are done here, then they will fall through
5106 * to the general case. Special options that are not passed to
5107 * setsockopt follow below that.*/
5109 case WS_SO_DONTLINGER:
5110 if (!optval)
5112 SetLastError(WSAEFAULT);
5113 return SOCKET_ERROR;
5115 linger.l_onoff = *(const int*)optval == 0;
5116 linger.l_linger = 0;
5117 level = SOL_SOCKET;
5118 optname = SO_LINGER;
5119 optval = (char*)&linger;
5120 optlen = sizeof(struct linger);
5121 break;
5123 case WS_SO_LINGER:
5124 if (!optval)
5126 SetLastError(WSAEFAULT);
5127 return SOCKET_ERROR;
5129 linger.l_onoff = ((LINGER*)optval)->l_onoff;
5130 linger.l_linger = ((LINGER*)optval)->l_linger;
5131 level = SOL_SOCKET;
5132 optname = SO_LINGER;
5133 optval = (char*)&linger;
5134 optlen = sizeof(struct linger);
5135 break;
5137 case WS_SO_RCVBUF:
5138 if (*(const int*)optval < 2048)
5140 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
5141 return 0;
5143 /* Fall through */
5145 /* The options listed here don't need any special handling. Thanks to
5146 * the conversion happening above, options from there will fall through
5147 * to this, too.*/
5148 case WS_SO_ACCEPTCONN:
5149 case WS_SO_BROADCAST:
5150 case WS_SO_ERROR:
5151 case WS_SO_KEEPALIVE:
5152 case WS_SO_OOBINLINE:
5153 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
5154 * however, using it the BSD way fixes bug 8513 and seems to be what
5155 * most programmers assume, anyway */
5156 case WS_SO_REUSEADDR:
5157 case WS_SO_SNDBUF:
5158 case WS_SO_TYPE:
5159 convert_sockopt(&level, &optname);
5160 break;
5162 /* SO_DEBUG is a privileged operation, ignore it. */
5163 case WS_SO_DEBUG:
5164 TRACE("Ignoring SO_DEBUG\n");
5165 return 0;
5167 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
5168 * socket. According to MSDN, this option is silently ignored.*/
5169 case WS_SO_DONTROUTE:
5170 TRACE("Ignoring SO_DONTROUTE\n");
5171 return 0;
5173 /* Stops two sockets from being bound to the same port. Always happens
5174 * on unix systems, so just drop it. */
5175 case WS_SO_EXCLUSIVEADDRUSE:
5176 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
5177 return 0;
5179 /* After a ConnectEx call succeeds, the socket can't be used with half of the
5180 * normal winsock functions on windows. We don't have that problem. */
5181 case WS_SO_UPDATE_CONNECT_CONTEXT:
5182 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
5183 return 0;
5185 /* After a AcceptEx call succeeds, the socket can't be used with half of the
5186 * normal winsock functions on windows. We don't have that problem. */
5187 case WS_SO_UPDATE_ACCEPT_CONTEXT:
5188 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
5189 return 0;
5191 /* SO_OPENTYPE does not require a valid socket handle. */
5192 case WS_SO_OPENTYPE:
5193 if (!optlen || optlen < sizeof(int) || !optval)
5195 SetLastError(WSAEFAULT);
5196 return SOCKET_ERROR;
5198 get_per_thread_data()->opentype = *(const int *)optval;
5199 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
5200 return 0;
5202 #ifdef SO_RCVTIMEO
5203 case WS_SO_RCVTIMEO:
5204 #endif
5205 #ifdef SO_SNDTIMEO
5206 case WS_SO_SNDTIMEO:
5207 #endif
5208 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
5209 if (optval && optlen == sizeof(UINT32)) {
5210 /* WinSock passes milliseconds instead of struct timeval */
5211 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
5212 tval.tv_sec = *(const UINT32*)optval / 1000;
5213 /* min of 500 milliseconds */
5214 if (tval.tv_sec == 0 && tval.tv_usec && tval.tv_usec < 500000)
5215 tval.tv_usec = 500000;
5216 optlen = sizeof(struct timeval);
5217 optval = (char*)&tval;
5218 } else if (optlen == sizeof(struct timeval)) {
5219 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
5220 } else {
5221 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
5222 return 0;
5224 convert_sockopt(&level, &optname);
5225 break;
5226 #endif
5228 default:
5229 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
5230 SetLastError(WSAENOPROTOOPT);
5231 return SOCKET_ERROR;
5233 break; /* case WS_SOL_SOCKET */
5235 #ifdef HAS_IPX
5236 case WS_NSPROTO_IPX:
5237 switch(optname)
5239 case WS_IPX_PTYPE:
5240 return set_ipx_packettype(s, *(int*)optval);
5242 case WS_IPX_FILTERPTYPE:
5243 /* Sets the receive filter packet type, at the moment we don't support it */
5244 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
5245 /* Returning 0 is better for now than returning a SOCKET_ERROR */
5246 return 0;
5248 default:
5249 FIXME("opt_name:%x\n", optname);
5250 return SOCKET_ERROR;
5252 break; /* case WS_NSPROTO_IPX */
5253 #endif
5255 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
5256 case WS_IPPROTO_TCP:
5257 switch(optname)
5259 case WS_TCP_NODELAY:
5260 convert_sockopt(&level, &optname);
5261 break;
5262 default:
5263 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
5264 return SOCKET_ERROR;
5266 break;
5268 case WS_IPPROTO_IP:
5269 switch(optname)
5271 case WS_IP_ADD_MEMBERSHIP:
5272 case WS_IP_DROP_MEMBERSHIP:
5273 #ifdef IP_HDRINCL
5274 case WS_IP_HDRINCL:
5275 #endif
5276 case WS_IP_MULTICAST_IF:
5277 case WS_IP_MULTICAST_LOOP:
5278 case WS_IP_MULTICAST_TTL:
5279 case WS_IP_OPTIONS:
5280 #ifdef IP_PKTINFO
5281 case WS_IP_PKTINFO:
5282 #endif
5283 case WS_IP_TOS:
5284 case WS_IP_TTL:
5285 #ifdef IP_UNICAST_IF
5286 case WS_IP_UNICAST_IF:
5287 #endif
5288 convert_sockopt(&level, &optname);
5289 break;
5290 case WS_IP_DONTFRAGMENT:
5291 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
5292 return 0;
5293 default:
5294 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
5295 return SOCKET_ERROR;
5297 break;
5299 case WS_IPPROTO_IPV6:
5300 switch(optname)
5302 #ifdef IPV6_ADD_MEMBERSHIP
5303 case WS_IPV6_ADD_MEMBERSHIP:
5304 #endif
5305 #ifdef IPV6_DROP_MEMBERSHIP
5306 case WS_IPV6_DROP_MEMBERSHIP:
5307 #endif
5308 case WS_IPV6_MULTICAST_IF:
5309 case WS_IPV6_MULTICAST_HOPS:
5310 case WS_IPV6_MULTICAST_LOOP:
5311 case WS_IPV6_UNICAST_HOPS:
5312 case WS_IPV6_V6ONLY:
5313 #ifdef IPV6_UNICAST_IF
5314 case WS_IPV6_UNICAST_IF:
5315 #endif
5316 convert_sockopt(&level, &optname);
5317 break;
5318 case WS_IPV6_DONTFRAG:
5319 FIXME("IPV6_DONTFRAG is silently ignored!\n");
5320 return 0;
5321 case WS_IPV6_PROTECTION_LEVEL:
5322 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
5323 return 0;
5324 default:
5325 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
5326 return SOCKET_ERROR;
5328 break;
5330 default:
5331 WARN("Unknown level: 0x%08x\n", level);
5332 SetLastError(WSAEINVAL);
5333 return SOCKET_ERROR;
5334 } /* end switch(level) */
5336 /* avoid endianness issues if argument is a 16-bit int */
5337 if (optval && optlen < sizeof(int))
5339 woptval= *((const INT16 *) optval);
5340 optval= (char*) &woptval;
5341 woptval&= (1 << optlen * 8) - 1;
5342 optlen=sizeof(int);
5344 fd = get_sock_fd( s, 0, NULL );
5345 if (fd == -1) return SOCKET_ERROR;
5347 if (setsockopt(fd, level, optname, optval, optlen) == 0)
5349 #ifdef __APPLE__
5350 if (level == SOL_SOCKET && optname == SO_REUSEADDR &&
5351 setsockopt(fd, level, SO_REUSEPORT, optval, optlen) != 0)
5353 SetLastError(wsaErrno());
5354 release_sock_fd( s, fd );
5355 return SOCKET_ERROR;
5357 #endif
5358 release_sock_fd( s, fd );
5359 return 0;
5361 TRACE("Setting socket error, %d\n", wsaErrno());
5362 SetLastError(wsaErrno());
5363 release_sock_fd( s, fd );
5365 return SOCKET_ERROR;
5368 /***********************************************************************
5369 * shutdown (WS2_32.22)
5371 int WINAPI WS_shutdown(SOCKET s, int how)
5373 int fd, err = WSAENOTSOCK;
5374 unsigned int options = 0, clear_flags = 0;
5376 fd = get_sock_fd( s, 0, &options );
5377 TRACE("socket %04lx, how 0x%x, options 0x%x\n", s, how, options );
5379 if (fd == -1)
5380 return SOCKET_ERROR;
5382 switch( how )
5384 case SD_RECEIVE: /* drop receives */
5385 clear_flags |= FD_READ;
5386 break;
5387 case SD_SEND: /* drop sends */
5388 clear_flags |= FD_WRITE;
5389 break;
5390 case SD_BOTH: /* drop all */
5391 clear_flags |= FD_READ|FD_WRITE;
5392 /*fall through */
5393 default:
5394 clear_flags |= FD_WINE_LISTENING;
5397 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
5399 switch ( how )
5401 case SD_RECEIVE:
5402 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
5403 break;
5404 case SD_SEND:
5405 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
5406 break;
5407 case SD_BOTH:
5408 default:
5409 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
5410 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
5411 break;
5413 if (err) goto error;
5415 else /* non-overlapped mode */
5417 if ( shutdown( fd, how ) )
5419 err = wsaErrno();
5420 goto error;
5424 release_sock_fd( s, fd );
5425 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
5426 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
5427 return 0;
5429 error:
5430 release_sock_fd( s, fd );
5431 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
5432 SetLastError( err );
5433 return SOCKET_ERROR;
5436 /***********************************************************************
5437 * socket (WS2_32.23)
5439 SOCKET WINAPI WS_socket(int af, int type, int protocol)
5441 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
5443 return WSASocketW( af, type, protocol, NULL, 0,
5444 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
5448 /***********************************************************************
5449 * gethostbyaddr (WS2_32.51)
5451 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
5453 struct WS_hostent *retval = NULL;
5454 struct hostent* host;
5455 int unixtype = convert_af_w2u(type);
5456 const char *paddr = addr;
5457 unsigned long loopback;
5458 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5459 char *extrabuf;
5460 int ebufsize = 1024;
5461 struct hostent hostentry;
5462 int locerr = ENOBUFS;
5463 #endif
5465 /* convert back the magic loopback address if necessary */
5466 if (unixtype == AF_INET && len == 4 && !memcmp(addr, magic_loopback_addr, 4))
5468 loopback = htonl(INADDR_LOOPBACK);
5469 paddr = (char*) &loopback;
5472 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5473 host = NULL;
5474 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
5475 while(extrabuf) {
5476 int res = gethostbyaddr_r(paddr, len, unixtype,
5477 &hostentry, extrabuf, ebufsize, &host, &locerr);
5478 if (res != ERANGE) break;
5479 ebufsize *=2;
5480 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
5482 if (host) retval = WS_dup_he(host);
5483 else SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
5484 HeapFree(GetProcessHeap(),0,extrabuf);
5485 #else
5486 EnterCriticalSection( &csWSgetXXXbyYYY );
5487 host = gethostbyaddr(paddr, len, unixtype);
5488 if (host) retval = WS_dup_he(host);
5489 else SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
5490 LeaveCriticalSection( &csWSgetXXXbyYYY );
5491 #endif
5492 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
5493 return retval;
5496 /***********************************************************************
5497 * WS_compare_routes_by_metric_asc (INTERNAL)
5499 * Comparison function for qsort(), for sorting two routes (struct route)
5500 * by metric in ascending order.
5502 static int WS_compare_routes_by_metric_asc(const void *left, const void *right)
5504 return ((const struct route*)left)->metric - ((const struct route*)right)->metric;
5507 /***********************************************************************
5508 * WS_get_local_ips (INTERNAL)
5510 * Returns the list of local IP addresses by going through the network
5511 * adapters and using the local routing table to sort the addresses
5512 * from highest routing priority to lowest routing priority. This
5513 * functionality is inferred from the description for obtaining local
5514 * IP addresses given in the Knowledge Base Article Q160215.
5516 * Please note that the returned hostent is only freed when the thread
5517 * closes and is replaced if another hostent is requested.
5519 static struct WS_hostent* WS_get_local_ips( char *hostname )
5521 int numroutes = 0, i, j;
5522 DWORD n;
5523 PIP_ADAPTER_INFO adapters = NULL, k;
5524 struct WS_hostent *hostlist = NULL;
5525 PMIB_IPFORWARDTABLE routes = NULL;
5526 struct route *route_addrs = NULL;
5527 DWORD adap_size, route_size;
5529 /* Obtain the size of the adapter list and routing table, also allocate memory */
5530 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
5531 return NULL;
5532 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
5533 return NULL;
5534 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
5535 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
5536 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
5537 if (adapters == NULL || routes == NULL || route_addrs == NULL)
5538 goto cleanup;
5539 /* Obtain the adapter list and the full routing table */
5540 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
5541 goto cleanup;
5542 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
5543 goto cleanup;
5544 /* Store the interface associated with each route */
5545 for (n = 0; n < routes->dwNumEntries; n++)
5547 IF_INDEX ifindex;
5548 DWORD ifmetric;
5549 BOOL exists = FALSE;
5551 if (routes->table[n].u1.ForwardType != MIB_IPROUTE_TYPE_DIRECT)
5552 continue;
5553 ifindex = routes->table[n].dwForwardIfIndex;
5554 ifmetric = routes->table[n].dwForwardMetric1;
5555 /* Only store the lowest valued metric for an interface */
5556 for (j = 0; j < numroutes; j++)
5558 if (route_addrs[j].interface == ifindex)
5560 if (route_addrs[j].metric > ifmetric)
5561 route_addrs[j].metric = ifmetric;
5562 exists = TRUE;
5565 if (exists)
5566 continue;
5567 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
5568 if (route_addrs == NULL)
5569 goto cleanup; /* Memory allocation error, fail gracefully */
5570 route_addrs[numroutes].interface = ifindex;
5571 route_addrs[numroutes].metric = ifmetric;
5572 /* If no IP is found in the next step (for whatever reason)
5573 * then fall back to the magic loopback address.
5575 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
5576 numroutes++;
5578 if (numroutes == 0)
5579 goto cleanup; /* No routes, fall back to the Magic IP */
5580 /* Find the IP address associated with each found interface */
5581 for (i = 0; i < numroutes; i++)
5583 for (k = adapters; k != NULL; k = k->Next)
5585 char *ip = k->IpAddressList.IpAddress.String;
5587 if (route_addrs[i].interface == k->Index)
5588 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
5591 /* Allocate a hostent and enough memory for all the IPs,
5592 * including the NULL at the end of the list.
5594 hostlist = WS_create_he(hostname, 1, 0, numroutes+1, sizeof(struct in_addr));
5595 if (hostlist == NULL)
5596 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
5597 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
5598 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
5599 hostlist->h_addrtype = AF_INET;
5600 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
5601 /* Reorder the entries before placing them in the host list. Windows expects
5602 * the IP list in order from highest priority to lowest (the critical thing
5603 * is that most applications expect the first IP to be the default route).
5605 if (numroutes > 1)
5606 qsort(route_addrs, numroutes, sizeof(struct route), WS_compare_routes_by_metric_asc);
5608 for (i = 0; i < numroutes; i++)
5609 (*(struct in_addr *) hostlist->h_addr_list[i]) = route_addrs[i].addr;
5611 /* Cleanup all allocated memory except the address list,
5612 * the address list is used by the calling app.
5614 cleanup:
5615 HeapFree(GetProcessHeap(), 0, route_addrs);
5616 HeapFree(GetProcessHeap(), 0, adapters);
5617 HeapFree(GetProcessHeap(), 0, routes);
5618 return hostlist;
5621 /***********************************************************************
5622 * gethostbyname (WS2_32.52)
5624 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
5626 struct WS_hostent *retval = NULL;
5627 struct hostent* host;
5628 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5629 char *extrabuf;
5630 int ebufsize=1024;
5631 struct hostent hostentry;
5632 int locerr = ENOBUFS;
5633 #endif
5634 char hostname[100];
5635 if(!num_startup) {
5636 SetLastError(WSANOTINITIALISED);
5637 return NULL;
5639 if( gethostname( hostname, 100) == -1) {
5640 SetLastError(WSAENOBUFS); /* appropriate ? */
5641 return retval;
5643 if( !name || !name[0]) {
5644 name = hostname;
5646 /* If the hostname of the local machine is requested then return the
5647 * complete list of local IP addresses */
5648 if(strcmp(name, hostname) == 0)
5649 retval = WS_get_local_ips(hostname);
5650 /* If any other hostname was requested (or the routing table lookup failed)
5651 * then return the IP found by the host OS */
5652 if(retval == NULL)
5654 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5655 host = NULL;
5656 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
5657 while(extrabuf) {
5658 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
5659 if( res != ERANGE) break;
5660 ebufsize *=2;
5661 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
5663 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
5664 #else
5665 EnterCriticalSection( &csWSgetXXXbyYYY );
5666 host = gethostbyname(name);
5667 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
5668 #endif
5669 if (host) retval = WS_dup_he(host);
5670 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5671 HeapFree(GetProcessHeap(),0,extrabuf);
5672 #else
5673 LeaveCriticalSection( &csWSgetXXXbyYYY );
5674 #endif
5676 if (retval && retval->h_addr_list[0][0] == 127 &&
5677 strcmp(name, "localhost") != 0)
5679 /* hostname != "localhost" but has loopback address. replace by our
5680 * special address.*/
5681 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
5683 TRACE( "%s ret %p\n", debugstr_a(name), retval );
5684 return retval;
5688 /***********************************************************************
5689 * getprotobyname (WS2_32.53)
5691 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
5693 struct WS_protoent* retval = NULL;
5694 #ifdef HAVE_GETPROTOBYNAME
5695 struct protoent* proto;
5696 EnterCriticalSection( &csWSgetXXXbyYYY );
5697 if( (proto = getprotobyname(name)) != NULL )
5699 retval = WS_dup_pe(proto);
5701 else {
5702 MESSAGE("protocol %s not found; You might want to add "
5703 "this to /etc/protocols\n", debugstr_a(name) );
5704 SetLastError(WSANO_DATA);
5706 LeaveCriticalSection( &csWSgetXXXbyYYY );
5707 #endif
5708 TRACE( "%s ret %p\n", debugstr_a(name), retval );
5709 return retval;
5713 /***********************************************************************
5714 * getprotobynumber (WS2_32.54)
5716 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
5718 struct WS_protoent* retval = NULL;
5719 #ifdef HAVE_GETPROTOBYNUMBER
5720 struct protoent* proto;
5721 EnterCriticalSection( &csWSgetXXXbyYYY );
5722 if( (proto = getprotobynumber(number)) != NULL )
5724 retval = WS_dup_pe(proto);
5726 else {
5727 MESSAGE("protocol number %d not found; You might want to add "
5728 "this to /etc/protocols\n", number );
5729 SetLastError(WSANO_DATA);
5731 LeaveCriticalSection( &csWSgetXXXbyYYY );
5732 #endif
5733 TRACE("%i ret %p\n", number, retval);
5734 return retval;
5738 /***********************************************************************
5739 * getservbyname (WS2_32.55)
5741 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
5743 struct WS_servent* retval = NULL;
5744 struct servent* serv;
5745 char *name_str;
5746 char *proto_str = NULL;
5748 if (!(name_str = strdup_lower(name))) return NULL;
5750 if (proto && *proto)
5752 if (!(proto_str = strdup_lower(proto)))
5754 HeapFree( GetProcessHeap(), 0, name_str );
5755 return NULL;
5759 EnterCriticalSection( &csWSgetXXXbyYYY );
5760 serv = getservbyname(name_str, proto_str);
5761 if( serv != NULL )
5763 retval = WS_dup_se(serv);
5765 else SetLastError(WSANO_DATA);
5766 LeaveCriticalSection( &csWSgetXXXbyYYY );
5767 HeapFree( GetProcessHeap(), 0, proto_str );
5768 HeapFree( GetProcessHeap(), 0, name_str );
5769 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
5770 return retval;
5773 /***********************************************************************
5774 * freeaddrinfo (WS2_32.@)
5776 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
5778 while (res) {
5779 struct WS_addrinfo *next;
5781 HeapFree(GetProcessHeap(),0,res->ai_canonname);
5782 HeapFree(GetProcessHeap(),0,res->ai_addr);
5783 next = res->ai_next;
5784 HeapFree(GetProcessHeap(),0,res);
5785 res = next;
5789 /* helper functions for getaddrinfo()/getnameinfo() */
5790 static int convert_aiflag_w2u(int winflags) {
5791 unsigned int i;
5792 int unixflags = 0;
5794 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
5795 if (ws_aiflag_map[i][0] & winflags) {
5796 unixflags |= ws_aiflag_map[i][1];
5797 winflags &= ~ws_aiflag_map[i][0];
5799 if (winflags)
5800 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
5801 return unixflags;
5804 static int convert_niflag_w2u(int winflags) {
5805 unsigned int i;
5806 int unixflags = 0;
5808 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
5809 if (ws_niflag_map[i][0] & winflags) {
5810 unixflags |= ws_niflag_map[i][1];
5811 winflags &= ~ws_niflag_map[i][0];
5813 if (winflags)
5814 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
5815 return unixflags;
5818 static int convert_aiflag_u2w(int unixflags) {
5819 unsigned int i;
5820 int winflags = 0;
5822 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
5823 if (ws_aiflag_map[i][1] & unixflags) {
5824 winflags |= ws_aiflag_map[i][0];
5825 unixflags &= ~ws_aiflag_map[i][1];
5827 if (unixflags) /* will warn usually */
5828 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
5829 return winflags;
5832 static int convert_eai_u2w(int unixret) {
5833 int i;
5835 if (!unixret) return 0;
5837 for (i=0;ws_eai_map[i][0];i++)
5838 if (ws_eai_map[i][1] == unixret)
5839 return ws_eai_map[i][0];
5841 if (unixret == EAI_SYSTEM)
5842 /* There are broken versions of glibc which return EAI_SYSTEM
5843 * and set errno to 0 instead of returning EAI_NONAME.
5845 return errno ? sock_get_error( errno ) : WS_EAI_NONAME;
5847 FIXME("Unhandled unix EAI_xxx ret %d\n", unixret);
5848 return unixret;
5851 static char *get_hostname(void)
5853 char *ret;
5854 DWORD size = 0;
5856 GetComputerNameExA( ComputerNamePhysicalDnsHostname, NULL, &size );
5857 if (GetLastError() != ERROR_MORE_DATA) return NULL;
5858 if (!(ret = HeapAlloc( GetProcessHeap(), 0, size ))) return NULL;
5859 if (!GetComputerNameExA( ComputerNamePhysicalDnsHostname, ret, &size ))
5861 HeapFree( GetProcessHeap(), 0, ret );
5862 return NULL;
5864 return ret;
5867 /***********************************************************************
5868 * getaddrinfo (WS2_32.@)
5870 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
5872 #ifdef HAVE_GETADDRINFO
5873 struct addrinfo *unixaires = NULL;
5874 int result;
5875 struct addrinfo unixhints, *punixhints = NULL;
5876 char *hostname = NULL;
5877 const char *node;
5879 *res = NULL;
5880 if (!nodename && !servname)
5882 SetLastError(WSAHOST_NOT_FOUND);
5883 return WSAHOST_NOT_FOUND;
5886 if (!nodename)
5887 node = NULL;
5888 else if (!nodename[0])
5890 node = hostname = get_hostname();
5891 if (!node) return WSA_NOT_ENOUGH_MEMORY;
5893 else
5894 node = nodename;
5896 /* servname tweak required by OSX and BSD kernels */
5897 if (servname && !servname[0]) servname = "0";
5899 if (hints) {
5900 punixhints = &unixhints;
5902 memset(&unixhints, 0, sizeof(unixhints));
5903 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
5905 /* zero is a wildcard, no need to convert */
5906 if (hints->ai_family)
5907 punixhints->ai_family = convert_af_w2u(hints->ai_family);
5908 if (hints->ai_socktype)
5909 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
5910 if (hints->ai_protocol)
5911 punixhints->ai_protocol = max(convert_proto_w2u(hints->ai_protocol), 0);
5913 if (punixhints->ai_socktype < 0)
5915 SetLastError(WSAESOCKTNOSUPPORT);
5916 HeapFree(GetProcessHeap(), 0, hostname);
5917 return SOCKET_ERROR;
5920 /* windows allows invalid combinations of socket type and protocol, unix does not.
5921 * fix the parameters here to make getaddrinfo call always work */
5922 if (punixhints->ai_protocol == IPPROTO_TCP &&
5923 punixhints->ai_socktype != SOCK_STREAM && punixhints->ai_socktype != SOCK_SEQPACKET)
5924 punixhints->ai_socktype = 0;
5926 else if (punixhints->ai_protocol == IPPROTO_UDP && punixhints->ai_socktype != SOCK_DGRAM)
5927 punixhints->ai_socktype = 0;
5929 else if (IS_IPX_PROTO(punixhints->ai_protocol) && punixhints->ai_socktype != SOCK_DGRAM)
5930 punixhints->ai_socktype = 0;
5933 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
5934 result = getaddrinfo(node, servname, punixhints, &unixaires);
5936 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
5937 HeapFree(GetProcessHeap(), 0, hostname);
5939 if (!result) {
5940 struct addrinfo *xuai = unixaires;
5941 struct WS_addrinfo **xai = res;
5943 *xai = NULL;
5944 while (xuai) {
5945 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
5946 SIZE_T len;
5948 if (!ai)
5949 goto outofmem;
5951 *xai = ai;xai = &ai->ai_next;
5952 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
5953 ai->ai_family = convert_af_u2w(xuai->ai_family);
5954 /* copy whatever was sent in the hints */
5955 if(hints) {
5956 ai->ai_socktype = hints->ai_socktype;
5957 ai->ai_protocol = hints->ai_protocol;
5958 } else {
5959 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
5960 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
5962 if (xuai->ai_canonname) {
5963 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
5964 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
5965 if (!ai->ai_canonname)
5966 goto outofmem;
5967 strcpy(ai->ai_canonname,xuai->ai_canonname);
5969 len = xuai->ai_addrlen;
5970 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
5971 if (!ai->ai_addr)
5972 goto outofmem;
5973 ai->ai_addrlen = len;
5974 do {
5975 int winlen = ai->ai_addrlen;
5977 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
5978 ai->ai_addrlen = winlen;
5979 break;
5981 len = 2*len;
5982 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
5983 if (!ai->ai_addr)
5984 goto outofmem;
5985 ai->ai_addrlen = len;
5986 } while (1);
5987 xuai = xuai->ai_next;
5989 freeaddrinfo(unixaires);
5991 if (TRACE_ON(winsock))
5993 struct WS_addrinfo *ai = *res;
5994 while (ai)
5996 TRACE("=> %p, flags %#x, family %d, type %d, protocol %d, len %ld, name %s, addr %s\n",
5997 ai, ai->ai_flags, ai->ai_family, ai->ai_socktype, ai->ai_protocol, ai->ai_addrlen,
5998 ai->ai_canonname, debugstr_sockaddr(ai->ai_addr));
5999 ai = ai->ai_next;
6002 } else
6003 result = convert_eai_u2w(result);
6005 SetLastError(result);
6006 return result;
6008 outofmem:
6009 if (*res) WS_freeaddrinfo(*res);
6010 if (unixaires) freeaddrinfo(unixaires);
6011 return WSA_NOT_ENOUGH_MEMORY;
6012 #else
6013 FIXME("getaddrinfo() failed, not found during buildtime.\n");
6014 return EAI_FAIL;
6015 #endif
6018 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
6020 struct WS_addrinfoW *ret;
6022 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
6023 ret->ai_flags = ai->ai_flags;
6024 ret->ai_family = ai->ai_family;
6025 ret->ai_socktype = ai->ai_socktype;
6026 ret->ai_protocol = ai->ai_protocol;
6027 ret->ai_addrlen = ai->ai_addrlen;
6028 ret->ai_canonname = NULL;
6029 ret->ai_addr = NULL;
6030 ret->ai_next = NULL;
6031 if (ai->ai_canonname)
6033 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
6034 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
6036 HeapFree(GetProcessHeap(), 0, ret);
6037 return NULL;
6039 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
6041 if (ai->ai_addr)
6043 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, ai->ai_addrlen)))
6045 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
6046 HeapFree(GetProcessHeap(), 0, ret);
6047 return NULL;
6049 memcpy(ret->ai_addr, ai->ai_addr, ai->ai_addrlen);
6051 return ret;
6054 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
6056 struct WS_addrinfoW *ret, *infoW;
6058 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
6059 while (info->ai_next)
6061 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
6063 FreeAddrInfoW(ret);
6064 return NULL;
6066 infoW = infoW->ai_next;
6067 info = info->ai_next;
6069 return ret;
6072 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
6074 struct WS_addrinfo *ret;
6076 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
6077 ret->ai_flags = ai->ai_flags;
6078 ret->ai_family = ai->ai_family;
6079 ret->ai_socktype = ai->ai_socktype;
6080 ret->ai_protocol = ai->ai_protocol;
6081 ret->ai_addrlen = ai->ai_addrlen;
6082 ret->ai_canonname = NULL;
6083 ret->ai_addr = NULL;
6084 ret->ai_next = NULL;
6085 if (ai->ai_canonname)
6087 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
6088 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
6090 HeapFree(GetProcessHeap(), 0, ret);
6091 return NULL;
6093 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
6095 if (ai->ai_addr)
6097 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
6099 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
6100 HeapFree(GetProcessHeap(), 0, ret);
6101 return NULL;
6103 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
6105 return ret;
6108 /***********************************************************************
6109 * GetAddrInfoW (WS2_32.@)
6111 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
6113 int ret, len;
6114 char *nodenameA = NULL, *servnameA = NULL;
6115 struct WS_addrinfo *resA, *hintsA = NULL;
6117 *res = NULL;
6118 if (nodename)
6120 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
6121 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
6122 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
6124 if (servname)
6126 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
6127 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
6129 HeapFree(GetProcessHeap(), 0, nodenameA);
6130 return EAI_MEMORY;
6132 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
6135 if (hints) hintsA = addrinfo_WtoA(hints);
6136 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
6137 WS_freeaddrinfo(hintsA);
6139 if (!ret)
6141 *res = addrinfo_list_AtoW(resA);
6142 WS_freeaddrinfo(resA);
6145 HeapFree(GetProcessHeap(), 0, nodenameA);
6146 HeapFree(GetProcessHeap(), 0, servnameA);
6147 return ret;
6150 /***********************************************************************
6151 * FreeAddrInfoW (WS2_32.@)
6153 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
6155 while (ai)
6157 ADDRINFOW *next;
6158 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
6159 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
6160 next = ai->ai_next;
6161 HeapFree(GetProcessHeap(), 0, ai);
6162 ai = next;
6166 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
6167 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
6169 #ifdef HAVE_GETNAMEINFO
6170 int ret;
6171 union generic_unix_sockaddr sa_u;
6172 unsigned int size;
6174 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
6175 serv, servlen, flags);
6177 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
6178 if (!size)
6180 SetLastError(WSAEFAULT);
6181 return WSA_NOT_ENOUGH_MEMORY;
6183 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
6184 return convert_eai_u2w(ret);
6185 #else
6186 FIXME("getnameinfo() failed, not found during buildtime.\n");
6187 return EAI_FAIL;
6188 #endif
6191 int WINAPI GetNameInfoW(const SOCKADDR *sa, WS_socklen_t salen, PWCHAR host,
6192 DWORD hostlen, PWCHAR serv, DWORD servlen, INT flags)
6194 int ret;
6195 char *hostA = NULL, *servA = NULL;
6197 if (host && (!(hostA = HeapAlloc(GetProcessHeap(), 0, hostlen)))) return EAI_MEMORY;
6198 if (serv && (!(servA = HeapAlloc(GetProcessHeap(), 0, servlen))))
6200 HeapFree(GetProcessHeap(), 0, hostA);
6201 return EAI_MEMORY;
6204 ret = WS_getnameinfo(sa, salen, hostA, hostlen, servA, servlen, flags);
6205 if (!ret)
6207 if (host) MultiByteToWideChar(CP_ACP, 0, hostA, -1, host, hostlen);
6208 if (serv) MultiByteToWideChar(CP_ACP, 0, servA, -1, serv, servlen);
6211 HeapFree(GetProcessHeap(), 0, hostA);
6212 HeapFree(GetProcessHeap(), 0, servA);
6213 return ret;
6216 /***********************************************************************
6217 * getservbyport (WS2_32.56)
6219 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
6221 struct WS_servent* retval = NULL;
6222 #ifdef HAVE_GETSERVBYPORT
6223 struct servent* serv;
6224 char *proto_str = NULL;
6226 if (proto && *proto)
6228 if (!(proto_str = strdup_lower(proto))) return NULL;
6230 EnterCriticalSection( &csWSgetXXXbyYYY );
6231 if( (serv = getservbyport(port, proto_str)) != NULL ) {
6232 retval = WS_dup_se(serv);
6234 else SetLastError(WSANO_DATA);
6235 LeaveCriticalSection( &csWSgetXXXbyYYY );
6236 HeapFree( GetProcessHeap(), 0, proto_str );
6237 #endif
6238 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
6239 return retval;
6243 /***********************************************************************
6244 * gethostname (WS2_32.57)
6246 int WINAPI WS_gethostname(char *name, int namelen)
6248 char buf[256];
6249 int len;
6251 TRACE("name %p, len %d\n", name, namelen);
6253 if (!name)
6255 SetLastError(WSAEFAULT);
6256 return SOCKET_ERROR;
6259 if (gethostname(buf, sizeof(buf)) != 0)
6261 SetLastError(wsaErrno());
6262 return SOCKET_ERROR;
6265 TRACE("<- '%s'\n", buf);
6266 len = strlen(buf);
6267 if (len > 15)
6268 WARN("Windows supports NetBIOS name length up to 15 bytes!\n");
6269 if (namelen <= len)
6271 SetLastError(WSAEFAULT);
6272 WARN("<- not enough space for hostname, required %d, got %d!\n", len + 1, namelen);
6273 return SOCKET_ERROR;
6275 strcpy(name, buf);
6276 return 0;
6280 /* ------------------------------------- Windows sockets extensions -- *
6282 * ------------------------------------------------------------------- */
6284 /***********************************************************************
6285 * WSAEnumNetworkEvents (WS2_32.36)
6287 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
6289 int ret;
6290 int i;
6291 int errors[FD_MAX_EVENTS];
6293 TRACE("%04lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
6295 SERVER_START_REQ( get_socket_event )
6297 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6298 req->service = TRUE;
6299 req->c_event = wine_server_obj_handle( hEvent );
6300 wine_server_set_reply( req, errors, sizeof(errors) );
6301 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
6303 SERVER_END_REQ;
6304 if (!ret)
6306 for (i = 0; i < FD_MAX_EVENTS; i++)
6307 lpEvent->iErrorCode[i] = NtStatusToWSAError(errors[i]);
6308 return 0;
6310 SetLastError(WSAEINVAL);
6311 return SOCKET_ERROR;
6314 /***********************************************************************
6315 * WSAEventSelect (WS2_32.39)
6317 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
6319 int ret;
6321 TRACE("%04lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
6323 SERVER_START_REQ( set_socket_event )
6325 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6326 req->mask = lEvent;
6327 req->event = wine_server_obj_handle( hEvent );
6328 req->window = 0;
6329 req->msg = 0;
6330 ret = wine_server_call( req );
6332 SERVER_END_REQ;
6333 if (!ret) return 0;
6334 SetLastError(WSAEINVAL);
6335 return SOCKET_ERROR;
6338 /**********************************************************************
6339 * WSAGetOverlappedResult (WS2_32.40)
6341 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
6342 LPDWORD lpcbTransfer, BOOL fWait,
6343 LPDWORD lpdwFlags )
6345 NTSTATUS status;
6347 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
6348 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
6350 if ( lpOverlapped == NULL )
6352 ERR( "Invalid pointer\n" );
6353 SetLastError(WSA_INVALID_PARAMETER);
6354 return FALSE;
6357 status = lpOverlapped->Internal;
6358 if (status == STATUS_PENDING)
6360 if (!fWait)
6362 SetLastError( WSA_IO_INCOMPLETE );
6363 return FALSE;
6366 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
6367 INFINITE ) == WAIT_FAILED)
6368 return FALSE;
6369 status = lpOverlapped->Internal;
6372 if ( lpcbTransfer )
6373 *lpcbTransfer = lpOverlapped->InternalHigh;
6375 if ( lpdwFlags )
6376 *lpdwFlags = lpOverlapped->u.s.Offset;
6378 if (status) SetLastError( RtlNtStatusToDosError(status) );
6379 return !status;
6383 /***********************************************************************
6384 * WSAAsyncSelect (WS2_32.101)
6386 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
6388 int ret;
6390 TRACE("%04lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
6392 SERVER_START_REQ( set_socket_event )
6394 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6395 req->mask = lEvent;
6396 req->event = 0;
6397 req->window = wine_server_user_handle( hWnd );
6398 req->msg = uMsg;
6399 ret = wine_server_call( req );
6401 SERVER_END_REQ;
6402 if (!ret) return 0;
6403 SetLastError(WSAEINVAL);
6404 return SOCKET_ERROR;
6407 /***********************************************************************
6408 * WSACreateEvent (WS2_32.31)
6411 WSAEVENT WINAPI WSACreateEvent(void)
6413 /* Create a manual-reset event, with initial state: unsignaled */
6414 TRACE("\n");
6416 return CreateEventW(NULL, TRUE, FALSE, NULL);
6419 /***********************************************************************
6420 * WSACloseEvent (WS2_32.29)
6423 BOOL WINAPI WSACloseEvent(WSAEVENT event)
6425 TRACE ("event=%p\n", event);
6427 return CloseHandle(event);
6430 /***********************************************************************
6431 * WSASocketA (WS2_32.78)
6434 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
6435 LPWSAPROTOCOL_INFOA lpProtocolInfo,
6436 GROUP g, DWORD dwFlags)
6438 INT len;
6439 WSAPROTOCOL_INFOW info;
6441 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
6442 af, type, protocol, lpProtocolInfo, g, dwFlags);
6444 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
6446 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
6447 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
6448 info.szProtocol, WSAPROTOCOL_LEN + 1);
6450 if (!len)
6452 SetLastError(WSAEINVAL);
6453 return SOCKET_ERROR;
6456 return WSASocketW(af, type, protocol, &info, g, dwFlags);
6459 /***********************************************************************
6460 * WSASocketW (WS2_32.79)
6463 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
6464 LPWSAPROTOCOL_INFOW lpProtocolInfo,
6465 GROUP g, DWORD dwFlags)
6467 SOCKET ret;
6468 DWORD err;
6469 int unixaf, unixtype, ipxptype = -1;
6472 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
6473 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
6476 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
6477 af, type, protocol, lpProtocolInfo, g, dwFlags );
6479 if (!num_startup)
6481 err = WSANOTINITIALISED;
6482 goto done;
6485 /* hack for WSADuplicateSocket */
6486 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
6487 ret = lpProtocolInfo->dwServiceFlags3;
6488 TRACE("\tgot duplicate %04lx\n", ret);
6489 return ret;
6492 if (lpProtocolInfo)
6494 if (af == FROM_PROTOCOL_INFO || !af)
6495 af = lpProtocolInfo->iAddressFamily;
6496 if (type == FROM_PROTOCOL_INFO || !type)
6497 type = lpProtocolInfo->iSocketType;
6498 if (protocol == FROM_PROTOCOL_INFO || !protocol)
6499 protocol = lpProtocolInfo->iProtocol;
6502 if (!type && (af || protocol))
6504 int autoproto = protocol;
6505 WSAPROTOCOL_INFOW infow;
6507 /* default to the first valid protocol */
6508 if (!autoproto)
6509 autoproto = valid_protocols[0];
6510 else if(IS_IPX_PROTO(autoproto))
6511 autoproto = WS_NSPROTO_IPX;
6513 if (WS_EnterSingleProtocolW(autoproto, &infow))
6515 type = infow.iSocketType;
6517 /* after win2003 it's no longer possible to pass AF_UNSPEC
6518 using the protocol info struct */
6519 if (!lpProtocolInfo && af == WS_AF_UNSPEC)
6520 af = infow.iAddressFamily;
6525 Windows has an extension to the IPX protocol that allows one to create sockets
6526 and set the IPX packet type at the same time, to do that a caller will use
6527 a protocol like NSPROTO_IPX + <PACKET TYPE>
6529 if (IS_IPX_PROTO(protocol))
6530 ipxptype = protocol - WS_NSPROTO_IPX;
6532 /* convert the socket family, type and protocol */
6533 unixaf = convert_af_w2u(af);
6534 unixtype = convert_socktype_w2u(type);
6535 protocol = convert_proto_w2u(protocol);
6536 if (unixaf == AF_UNSPEC) unixaf = -1;
6538 /* filter invalid parameters */
6539 if (protocol < 0)
6541 /* the type could not be converted */
6542 if (type && unixtype < 0)
6544 err = WSAESOCKTNOSUPPORT;
6545 goto done;
6548 err = WSAEPROTONOSUPPORT;
6549 goto done;
6551 if (unixaf < 0)
6553 /* both family and protocol can't be invalid */
6554 if (protocol <= 0)
6556 err = WSAEINVAL;
6557 goto done;
6560 /* family could not be converted and neither socket type */
6561 if (unixtype < 0 && af >= 0)
6564 err = WSAESOCKTNOSUPPORT;
6565 goto done;
6568 err = WSAEAFNOSUPPORT;
6569 goto done;
6572 SERVER_START_REQ( create_socket )
6574 req->family = unixaf;
6575 req->type = unixtype;
6576 req->protocol = protocol;
6577 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
6578 req->attributes = (dwFlags & WSA_FLAG_NO_HANDLE_INHERIT) ? 0 : OBJ_INHERIT;
6579 req->flags = dwFlags & ~WSA_FLAG_NO_HANDLE_INHERIT;
6580 set_error( wine_server_call( req ) );
6581 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
6583 SERVER_END_REQ;
6584 if (ret)
6586 TRACE("\tcreated %04lx\n", ret );
6587 if (ipxptype > 0)
6588 set_ipx_packettype(ret, ipxptype);
6589 return ret;
6592 err = GetLastError();
6593 if (err == WSAEACCES) /* raw socket denied */
6595 if (type == SOCK_RAW)
6596 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
6597 else
6598 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
6600 else
6602 /* invalid combination of valid parameters, like SOCK_STREAM + IPPROTO_UDP */
6603 if (err == WSAEINVAL)
6604 err = WSAESOCKTNOSUPPORT;
6605 else if (err == WSAEOPNOTSUPP)
6606 err = WSAEPROTONOSUPPORT;
6609 done:
6610 WARN("\t\tfailed, error %d!\n", err);
6611 SetLastError(err);
6612 return INVALID_SOCKET;
6615 /***********************************************************************
6616 * WSAJoinLeaf (WS2_32.58)
6619 SOCKET WINAPI WSAJoinLeaf(
6620 SOCKET s,
6621 const struct WS_sockaddr *addr,
6622 int addrlen,
6623 LPWSABUF lpCallerData,
6624 LPWSABUF lpCalleeData,
6625 LPQOS lpSQOS,
6626 LPQOS lpGQOS,
6627 DWORD dwFlags)
6629 FIXME("stub.\n");
6630 return INVALID_SOCKET;
6633 /***********************************************************************
6634 * __WSAFDIsSet (WS2_32.151)
6636 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
6638 int i = set->fd_count, ret = 0;
6640 while (i--)
6641 if (set->fd_array[i] == s)
6643 ret = 1;
6644 break;
6647 TRACE("(socket %04lx, fd_set %p, count %i) <- %d\n", s, set, set->fd_count, ret);
6648 return ret;
6651 /***********************************************************************
6652 * WSAIsBlocking (WS2_32.114)
6654 BOOL WINAPI WSAIsBlocking(void)
6656 /* By default WinSock should set all its sockets to non-blocking mode
6657 * and poll in PeekMessage loop when processing "blocking" ones. This
6658 * function is supposed to tell if the program is in this loop. Our
6659 * blocking calls are truly blocking so we always return FALSE.
6661 * Note: It is allowed to call this function without prior WSAStartup().
6664 TRACE("\n");
6665 return FALSE;
6668 /***********************************************************************
6669 * WSACancelBlockingCall (WS2_32.113)
6671 INT WINAPI WSACancelBlockingCall(void)
6673 TRACE("\n");
6674 return 0;
6677 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
6679 FIXME("How was this called?\n");
6680 return x();
6684 /***********************************************************************
6685 * WSASetBlockingHook (WS2_32.109)
6687 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
6689 FARPROC prev = blocking_hook;
6690 blocking_hook = lpBlockFunc;
6691 TRACE("hook %p\n", lpBlockFunc);
6692 return prev;
6696 /***********************************************************************
6697 * WSAUnhookBlockingHook (WS2_32.110)
6699 INT WINAPI WSAUnhookBlockingHook(void)
6701 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
6702 return 0;
6706 /* ----------------------------------- end of API stuff */
6708 /* ----------------------------------- helper functions -
6710 * TODO: Merge WS_dup_..() stuff into one function that
6711 * would operate with a generic structure containing internal
6712 * pointers (via a template of some kind).
6715 static int list_size(char** l, int item_size)
6717 int i,j = 0;
6718 if(l)
6719 { for(i=0;l[i];i++)
6720 j += (item_size) ? item_size : strlen(l[i]) + 1;
6721 j += (i + 1) * sizeof(char*); }
6722 return j;
6725 static int list_dup(char** l_src, char** l_to, int item_size)
6727 char *p;
6728 int i;
6730 for (i = 0; l_src[i]; i++) ;
6731 p = (char *)(l_to + i + 1);
6732 for (i = 0; l_src[i]; i++)
6734 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
6735 memcpy(p, l_src[i], count);
6736 l_to[i] = p;
6737 p += count;
6739 l_to[i] = NULL;
6740 return p - (char *)l_to;
6743 /* ----- hostent */
6745 /* create a hostent entry
6747 * Creates the entry with enough memory for the name, aliases
6748 * addresses, and the address pointers. Also copies the name
6749 * and sets up all the pointers.
6751 * NOTE: The alias and address lists must be allocated with room
6752 * for the NULL item terminating the list. This is true even if
6753 * the list has no items ("aliases" and "addresses" must be
6754 * at least "1", a truly empty list is invalid).
6756 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length)
6758 struct WS_hostent *p_to;
6759 char *p;
6760 int size = (sizeof(struct WS_hostent) +
6761 strlen(name) + 1 +
6762 sizeof(char *) * aliases +
6763 aliases_size +
6764 sizeof(char *) * addresses +
6765 address_length * (addresses - 1)), i;
6767 if (!(p_to = check_buffer_he(size))) return NULL;
6768 memset(p_to, 0, size);
6770 /* Use the memory in the same way winsock does.
6771 * First set the pointer for aliases, second set the pointers for addresses.
6772 * Third fill the addresses indexes, fourth jump aliases names size.
6773 * Fifth fill the hostname.
6774 * NOTE: This method is valid for OS version's >= XP.
6776 p = (char *)(p_to + 1);
6777 p_to->h_aliases = (char **)p;
6778 p += sizeof(char *)*aliases;
6780 p_to->h_addr_list = (char **)p;
6781 p += sizeof(char *)*addresses;
6783 for (i = 0, addresses--; i < addresses; i++, p += address_length)
6784 p_to->h_addr_list[i] = p;
6786 /* NOTE: h_aliases must be filled in manually because we don't know each string
6787 * size, leave these pointers NULL (already set to NULL by memset earlier).
6789 p += aliases_size;
6791 p_to->h_name = p;
6792 strcpy(p, name);
6794 return p_to;
6797 /* duplicate hostent entry
6798 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
6799 * Ditto for protoent and servent.
6801 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
6803 int i, addresses = 0, alias_size = 0;
6804 struct WS_hostent *p_to;
6805 char *p;
6807 for( i = 0; p_he->h_aliases[i]; i++) alias_size += strlen(p_he->h_aliases[i]) + 1;
6808 while (p_he->h_addr_list[addresses]) addresses++;
6810 p_to = WS_create_he(p_he->h_name, i + 1, alias_size, addresses + 1, p_he->h_length);
6812 if (!p_to) return NULL;
6813 p_to->h_addrtype = convert_af_u2w(p_he->h_addrtype);
6814 p_to->h_length = p_he->h_length;
6816 for(i = 0, p = p_to->h_addr_list[0]; p_he->h_addr_list[i]; i++, p += p_to->h_length)
6817 memcpy(p, p_he->h_addr_list[i], p_to->h_length);
6819 /* Fill the aliases after the IP data */
6820 for(i = 0; p_he->h_aliases[i]; i++)
6822 p_to->h_aliases[i] = p;
6823 strcpy(p, p_he->h_aliases[i]);
6824 p += strlen(p) + 1;
6827 return p_to;
6830 /* ----- protoent */
6832 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
6834 char *p;
6835 struct WS_protoent *p_to;
6837 int size = (sizeof(*p_pe) +
6838 strlen(p_pe->p_name) + 1 +
6839 list_size(p_pe->p_aliases, 0));
6841 if (!(p_to = check_buffer_pe(size))) return NULL;
6842 p_to->p_proto = p_pe->p_proto;
6844 p = (char *)(p_to + 1);
6845 p_to->p_name = p;
6846 strcpy(p, p_pe->p_name);
6847 p += strlen(p) + 1;
6849 p_to->p_aliases = (char **)p;
6850 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
6851 return p_to;
6854 /* ----- servent */
6856 static struct WS_servent *WS_dup_se(const struct servent* p_se)
6858 char *p;
6859 struct WS_servent *p_to;
6861 int size = (sizeof(*p_se) +
6862 strlen(p_se->s_proto) + 1 +
6863 strlen(p_se->s_name) + 1 +
6864 list_size(p_se->s_aliases, 0));
6866 if (!(p_to = check_buffer_se(size))) return NULL;
6867 p_to->s_port = p_se->s_port;
6869 p = (char *)(p_to + 1);
6870 p_to->s_name = p;
6871 strcpy(p, p_se->s_name);
6872 p += strlen(p) + 1;
6874 p_to->s_proto = p;
6875 strcpy(p, p_se->s_proto);
6876 p += strlen(p) + 1;
6878 p_to->s_aliases = (char **)p;
6879 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
6880 return p_to;
6884 /***********************************************************************
6885 * WSARecv (WS2_32.67)
6887 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6888 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
6889 LPWSAOVERLAPPED lpOverlapped,
6890 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
6892 return WS2_recv_base(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
6893 NULL, NULL, lpOverlapped, lpCompletionRoutine, NULL);
6896 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6897 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
6898 struct WS_sockaddr *lpFrom,
6899 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
6900 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
6901 LPWSABUF lpControlBuffer )
6903 unsigned int i, options;
6904 int n, fd, err, overlapped, flags;
6905 struct ws2_async *wsa = NULL, localwsa;
6906 BOOL is_blocking;
6907 DWORD timeout_start = GetTickCount();
6908 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
6910 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
6911 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
6912 (lpFromlen ? *lpFromlen : -1),
6913 lpOverlapped, lpCompletionRoutine);
6915 fd = get_sock_fd( s, FILE_READ_DATA, &options );
6916 TRACE( "fd=%d, options=%x\n", fd, options );
6918 if (fd == -1) return SOCKET_ERROR;
6920 if (*lpFlags & WS_MSG_OOB)
6922 /* It's invalid to receive OOB data from an OOBINLINED socket
6923 * as OOB data is turned into normal data. */
6924 i = sizeof(n);
6925 if (!getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, (char*) &n, &i) && n)
6927 err = WSAEINVAL;
6928 goto error;
6932 overlapped = (lpOverlapped || lpCompletionRoutine) &&
6933 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
6934 if (overlapped || dwBufferCount > 1)
6936 if (!(wsa = (struct ws2_async *)alloc_async_io( offsetof(struct ws2_async, iovec[dwBufferCount]))))
6938 err = WSAEFAULT;
6939 goto error;
6942 else
6943 wsa = &localwsa;
6945 wsa->hSocket = SOCKET2HANDLE(s);
6946 wsa->flags = *lpFlags;
6947 wsa->lpFlags = lpFlags;
6948 wsa->addr = lpFrom;
6949 wsa->addrlen.ptr = lpFromlen;
6950 wsa->control = lpControlBuffer;
6951 wsa->n_iovecs = dwBufferCount;
6952 wsa->first_iovec = 0;
6953 for (i = 0; i < dwBufferCount; i++)
6955 /* check buffer first to trigger write watches */
6956 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
6958 err = WSAEFAULT;
6959 goto error;
6961 wsa->iovec[i].iov_base = lpBuffers[i].buf;
6962 wsa->iovec[i].iov_len = lpBuffers[i].len;
6965 flags = convert_flags(wsa->flags);
6966 for (;;)
6968 n = WS2_recv( fd, wsa, flags );
6969 if (n == -1)
6971 /* Unix-like systems return EINVAL when attempting to read OOB data from
6972 * an empty socket buffer, convert that to a Windows expected return. */
6973 if ((flags & MSG_OOB) && errno == EINVAL)
6974 errno = EWOULDBLOCK;
6976 if (errno != EAGAIN)
6978 int loc_errno = errno;
6979 err = wsaErrno();
6980 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
6981 goto error;
6984 else if (lpNumberOfBytesRecvd) *lpNumberOfBytesRecvd = n;
6986 if (overlapped)
6988 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
6990 wsa->user_overlapped = lpOverlapped;
6991 wsa->completion_func = lpCompletionRoutine;
6992 release_sock_fd( s, fd );
6994 if (n == -1)
6996 iosb->u.Status = STATUS_PENDING;
6997 iosb->Information = 0;
6999 SERVER_START_REQ( register_async )
7001 req->type = ASYNC_TYPE_READ;
7002 req->async.handle = wine_server_obj_handle( wsa->hSocket );
7003 req->async.callback = wine_server_client_ptr( WS2_async_recv );
7004 req->async.iosb = wine_server_client_ptr( iosb );
7005 req->async.arg = wine_server_client_ptr( wsa );
7006 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
7007 req->async.cvalue = cvalue;
7008 err = wine_server_call( req );
7010 SERVER_END_REQ;
7012 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
7013 SetLastError(NtStatusToWSAError( err ));
7014 return SOCKET_ERROR;
7017 iosb->u.Status = STATUS_SUCCESS;
7018 iosb->Information = n;
7019 if (!wsa->completion_func)
7021 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
7022 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
7023 HeapFree( GetProcessHeap(), 0, wsa );
7025 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
7026 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
7027 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7028 return 0;
7031 if (n != -1) break;
7033 if ((err = _is_blocking( s, &is_blocking )))
7035 err = NtStatusToWSAError( err );
7036 goto error;
7039 if ( is_blocking )
7041 struct pollfd pfd;
7042 int timeout = GET_RCVTIMEO(fd);
7043 if (timeout != -1)
7045 timeout -= GetTickCount() - timeout_start;
7046 if (timeout < 0) timeout = 0;
7049 pfd.fd = fd;
7050 pfd.events = POLLIN;
7051 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
7053 if (!timeout || !poll( &pfd, 1, timeout ))
7055 err = WSAETIMEDOUT;
7056 /* a timeout is not fatal */
7057 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7058 goto error;
7061 else
7063 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7064 err = WSAEWOULDBLOCK;
7065 goto error;
7069 TRACE(" -> %i bytes\n", n);
7070 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
7071 release_sock_fd( s, fd );
7072 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
7073 SetLastError(ERROR_SUCCESS);
7075 return 0;
7077 error:
7078 if (wsa != &localwsa) HeapFree( GetProcessHeap(), 0, wsa );
7079 release_sock_fd( s, fd );
7080 WARN(" -> ERROR %d\n", err);
7081 SetLastError( err );
7082 return SOCKET_ERROR;
7085 /***********************************************************************
7086 * WSARecvFrom (WS2_32.69)
7088 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
7089 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
7090 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
7091 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
7094 return WS2_recv_base( s, lpBuffers, dwBufferCount,
7095 lpNumberOfBytesRecvd, lpFlags,
7096 lpFrom, lpFromlen,
7097 lpOverlapped, lpCompletionRoutine, NULL );
7100 /***********************************************************************
7101 * WSCInstallProvider (WS2_32.88)
7103 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
7104 LPCWSTR lpszProviderDllPath,
7105 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
7106 DWORD dwNumberOfEntries,
7107 LPINT lpErrno )
7109 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
7110 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
7111 dwNumberOfEntries, lpErrno);
7112 *lpErrno = 0;
7113 return 0;
7117 /***********************************************************************
7118 * WSCDeinstallProvider (WS2_32.83)
7120 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
7122 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
7123 *lpErrno = 0;
7124 return 0;
7128 /***********************************************************************
7129 * WSAAccept (WS2_32.26)
7131 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
7132 LPCONDITIONPROC lpfnCondition, DWORD_PTR dwCallbackData)
7135 int ret = 0, size;
7136 WSABUF CallerId, CallerData, CalleeId, CalleeData;
7137 /* QOS SQOS, GQOS; */
7138 GROUP g;
7139 SOCKET cs;
7140 SOCKADDR src_addr, dst_addr;
7142 TRACE("socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
7143 s, addr, addrlen, lpfnCondition, dwCallbackData);
7145 cs = WS_accept(s, addr, addrlen);
7146 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
7147 if (!lpfnCondition) return cs;
7149 if (addr && addrlen)
7151 CallerId.buf = (char *)addr;
7152 CallerId.len = *addrlen;
7154 else
7156 size = sizeof(src_addr);
7157 WS_getpeername(cs, &src_addr, &size);
7158 CallerId.buf = (char *)&src_addr;
7159 CallerId.len = size;
7161 CallerData.buf = NULL;
7162 CallerData.len = 0;
7164 size = sizeof(dst_addr);
7165 WS_getsockname(cs, &dst_addr, &size);
7167 CalleeId.buf = (char *)&dst_addr;
7168 CalleeId.len = sizeof(dst_addr);
7170 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
7171 &CalleeId, &CalleeData, &g, dwCallbackData);
7173 switch (ret)
7175 case CF_ACCEPT:
7176 return cs;
7177 case CF_DEFER:
7178 SERVER_START_REQ( set_socket_deferred )
7180 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
7181 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
7182 if ( !wine_server_call_err ( req ) )
7184 SetLastError( WSATRY_AGAIN );
7185 WS_closesocket( cs );
7188 SERVER_END_REQ;
7189 return SOCKET_ERROR;
7190 case CF_REJECT:
7191 WS_closesocket(cs);
7192 SetLastError(WSAECONNREFUSED);
7193 return SOCKET_ERROR;
7194 default:
7195 FIXME("Unknown return type from Condition function\n");
7196 SetLastError(WSAENOTSOCK);
7197 return SOCKET_ERROR;
7201 /***********************************************************************
7202 * WSADuplicateSocketA (WS2_32.32)
7204 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
7206 return WS_DuplicateSocket(FALSE, s, dwProcessId, (LPWSAPROTOCOL_INFOW) lpProtocolInfo);
7209 /***********************************************************************
7210 * WSADuplicateSocketW (WS2_32.33)
7212 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
7214 return WS_DuplicateSocket(TRUE, s, dwProcessId, lpProtocolInfo);
7217 /***********************************************************************
7218 * WSAInstallServiceClassA (WS2_32.48)
7220 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
7222 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
7223 SetLastError(WSAEACCES);
7224 return SOCKET_ERROR;
7227 /***********************************************************************
7228 * WSAInstallServiceClassW (WS2_32.49)
7230 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
7232 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
7233 SetLastError(WSAEACCES);
7234 return SOCKET_ERROR;
7237 /***********************************************************************
7238 * WSARemoveServiceClass (WS2_32.70)
7240 int WINAPI WSARemoveServiceClass(LPGUID info)
7242 FIXME("Request to remove service %p\n",info);
7243 SetLastError(WSATYPE_NOT_FOUND);
7244 return SOCKET_ERROR;
7247 /***********************************************************************
7248 * inet_ntop (WS2_32.@)
7250 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
7252 #ifdef HAVE_INET_NTOP
7253 struct WS_in6_addr *in6;
7254 struct WS_in_addr *in;
7255 PCSTR pdst;
7257 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
7258 if (!buffer)
7260 SetLastError( STATUS_INVALID_PARAMETER );
7261 return NULL;
7264 switch (family)
7266 case WS_AF_INET:
7268 in = addr;
7269 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
7270 break;
7272 case WS_AF_INET6:
7274 in6 = addr;
7275 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
7276 break;
7278 default:
7279 SetLastError( WSAEAFNOSUPPORT );
7280 return NULL;
7283 if (!pdst) SetLastError( STATUS_INVALID_PARAMETER );
7284 return pdst;
7285 #else
7286 FIXME( "not supported on this platform\n" );
7287 SetLastError( WSAEAFNOSUPPORT );
7288 return NULL;
7289 #endif
7292 /***********************************************************************
7293 * inet_pton (WS2_32.@)
7295 INT WINAPI WS_inet_pton( INT family, PCSTR addr, PVOID buffer)
7297 #ifdef HAVE_INET_PTON
7298 int unixaf, ret;
7300 TRACE("family %d, addr '%s', buffer (%p)\n", family, addr ? addr : "(null)", buffer);
7302 if (!addr || !buffer)
7304 SetLastError(WSAEFAULT);
7305 return SOCKET_ERROR;
7308 unixaf = convert_af_w2u(family);
7309 if (unixaf != AF_INET && unixaf != AF_INET6)
7311 SetLastError(WSAEAFNOSUPPORT);
7312 return SOCKET_ERROR;
7315 ret = inet_pton(unixaf, addr, buffer);
7316 if (ret == -1) SetLastError(wsaErrno());
7317 return ret;
7318 #else
7319 FIXME( "not supported on this platform\n" );
7320 SetLastError( WSAEAFNOSUPPORT );
7321 return SOCKET_ERROR;
7322 #endif
7326 /***********************************************************************
7327 * WSAStringToAddressA (WS2_32.80)
7329 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
7330 INT AddressFamily,
7331 LPWSAPROTOCOL_INFOA lpProtocolInfo,
7332 LPSOCKADDR lpAddress,
7333 LPINT lpAddressLength)
7335 INT res=0;
7336 LPSTR workBuffer=NULL,ptrPort;
7338 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
7339 lpProtocolInfo, lpAddress, lpAddressLength );
7341 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
7343 if (!AddressString)
7345 SetLastError(WSAEINVAL);
7346 return SOCKET_ERROR;
7349 if (lpProtocolInfo)
7350 FIXME("ProtocolInfo not implemented.\n");
7352 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
7353 strlen(AddressString) + 1);
7354 if (!workBuffer)
7356 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7357 return SOCKET_ERROR;
7360 strcpy(workBuffer, AddressString);
7362 switch(AddressFamily)
7364 case WS_AF_INET:
7366 struct in_addr inetaddr;
7368 /* If lpAddressLength is too small, tell caller the size we need */
7369 if (*lpAddressLength < sizeof(SOCKADDR_IN))
7371 *lpAddressLength = sizeof(SOCKADDR_IN);
7372 res = WSAEFAULT;
7373 break;
7375 *lpAddressLength = sizeof(SOCKADDR_IN);
7376 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
7378 ((LPSOCKADDR_IN)lpAddress)->sin_family = WS_AF_INET;
7380 ptrPort = strchr(workBuffer, ':');
7381 if(ptrPort)
7383 /* User may have entered an IPv6 and asked to parse as IPv4 */
7384 if(strchr(ptrPort + 1, ':'))
7386 res = WSAEINVAL;
7387 break;
7389 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
7390 *ptrPort = '\0';
7392 else
7394 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
7397 if(inet_aton(workBuffer, &inetaddr) > 0)
7399 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
7400 res = 0;
7402 else
7403 res = WSAEINVAL;
7405 break;
7408 case WS_AF_INET6:
7410 struct in6_addr inetaddr;
7411 /* If lpAddressLength is too small, tell caller the size we need */
7412 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
7414 *lpAddressLength = sizeof(SOCKADDR_IN6);
7415 res = WSAEFAULT;
7416 break;
7418 #ifdef HAVE_INET_PTON
7419 *lpAddressLength = sizeof(SOCKADDR_IN6);
7420 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
7422 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
7424 /* This one is a bit tricky. An IPv6 address contains colons, so the
7425 * check from IPv4 doesn't work like that. However, IPv6 addresses that
7426 * contain a port are written with braces like [fd12:3456:7890::1]:12345
7427 * so what we will do is to look for ']', check if the next char is a
7428 * colon, and if it is, parse the port as in IPv4. */
7430 ptrPort = strchr(workBuffer, ']');
7431 if(ptrPort && *(++ptrPort) == ':')
7433 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort+1));
7434 *ptrPort = '\0';
7436 else
7438 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
7441 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
7443 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
7444 sizeof(struct in6_addr));
7445 res = 0;
7447 else
7448 #endif /* HAVE_INET_PTON */
7449 res = WSAEINVAL;
7451 break;
7453 default:
7454 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
7455 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
7456 res = WSAEINVAL;
7459 HeapFree(GetProcessHeap(), 0, workBuffer);
7461 if (!res) return 0;
7462 SetLastError(res);
7463 return SOCKET_ERROR;
7466 /***********************************************************************
7467 * WSAStringToAddressW (WS2_32.81)
7469 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
7470 * If this should be the case, it would be required to map these digits
7471 * to Unicode digits (0-9) using FoldString first.
7473 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
7474 INT AddressFamily,
7475 LPWSAPROTOCOL_INFOW lpProtocolInfo,
7476 LPSOCKADDR lpAddress,
7477 LPINT lpAddressLength)
7479 INT sBuffer,res=0;
7480 LPSTR workBuffer=NULL;
7481 WSAPROTOCOL_INFOA infoA;
7482 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
7484 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
7485 lpAddress, lpAddressLength );
7487 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
7489 /* if ProtocolInfo is available - convert to ANSI variant */
7490 if (lpProtocolInfo)
7492 lpProtoInfoA = &infoA;
7493 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
7495 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
7496 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
7498 SetLastError(WSAEINVAL);
7499 return SOCKET_ERROR;
7503 if (AddressString)
7505 /* Translate AddressString to ANSI code page - assumes that only
7506 standard digits 0-9 are used with this API call */
7507 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
7508 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
7510 if (workBuffer)
7512 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
7513 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
7514 lpAddress,lpAddressLength);
7515 HeapFree( GetProcessHeap(), 0, workBuffer );
7516 return res;
7518 else
7519 res = WSA_NOT_ENOUGH_MEMORY;
7521 else
7522 res = WSAEINVAL;
7524 SetLastError(res);
7525 return SOCKET_ERROR;
7528 /***********************************************************************
7529 * WSAAddressToStringA (WS2_32.27)
7531 * See WSAAddressToStringW
7533 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
7534 LPWSAPROTOCOL_INFOA info, LPSTR string,
7535 LPDWORD lenstr )
7537 DWORD size;
7538 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
7539 CHAR *p;
7541 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
7543 if (!sockaddr) return SOCKET_ERROR;
7544 if (!string || !lenstr) return SOCKET_ERROR;
7546 switch(sockaddr->sa_family)
7548 case WS_AF_INET:
7549 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
7550 sprintf( buffer, "%u.%u.%u.%u:%u",
7551 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
7552 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
7553 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
7554 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
7555 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
7557 p = strchr( buffer, ':' );
7558 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
7559 break;
7561 case WS_AF_INET6:
7563 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
7565 buffer[0] = 0;
7566 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
7567 if ((sockaddr6->sin6_port))
7568 strcpy(buffer, "[");
7569 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, buffer+strlen(buffer), sizeof(buffer)))
7571 SetLastError(WSAEINVAL);
7572 return SOCKET_ERROR;
7574 if ((sockaddr6->sin6_scope_id))
7575 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
7576 if ((sockaddr6->sin6_port))
7577 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
7578 break;
7581 default:
7582 SetLastError(WSAEINVAL);
7583 return SOCKET_ERROR;
7586 size = strlen( buffer ) + 1;
7588 if (*lenstr < size)
7590 *lenstr = size;
7591 SetLastError(WSAEFAULT);
7592 return SOCKET_ERROR;
7595 TRACE("=> %s,%u bytes\n", debugstr_a(buffer), size);
7596 *lenstr = size;
7597 strcpy( string, buffer );
7598 return 0;
7601 /***********************************************************************
7602 * WSAAddressToStringW (WS2_32.28)
7604 * Convert a sockaddr address into a readable address string.
7606 * PARAMS
7607 * sockaddr [I] Pointer to a sockaddr structure.
7608 * len [I] Size of the sockaddr structure.
7609 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
7610 * string [I/O] Pointer to a buffer to receive the address string.
7611 * lenstr [I/O] Size of the receive buffer in WCHARs.
7613 * RETURNS
7614 * Success: 0
7615 * Failure: SOCKET_ERROR
7617 * NOTES
7618 * The 'info' parameter is ignored.
7620 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
7621 LPWSAPROTOCOL_INFOW info, LPWSTR string,
7622 LPDWORD lenstr )
7624 INT ret;
7625 DWORD size;
7626 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
7627 CHAR bufAddr[54];
7629 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
7631 size = *lenstr;
7632 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
7634 if (ret) return ret;
7636 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
7638 if (*lenstr < size)
7640 *lenstr = size;
7641 SetLastError(WSAEFAULT);
7642 return SOCKET_ERROR;
7645 TRACE("=> %s,%u bytes\n", debugstr_w(buffer), size);
7646 *lenstr = size;
7647 lstrcpyW( string, buffer );
7648 return 0;
7651 /***********************************************************************
7652 * WSAEnumNameSpaceProvidersA (WS2_32.34)
7654 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
7656 FIXME( "(%p %p) Stub!\n", len, buffer );
7657 return 0;
7660 /***********************************************************************
7661 * WSAEnumNameSpaceProvidersW (WS2_32.35)
7663 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
7665 FIXME( "(%p %p) Stub!\n", len, buffer );
7666 return 0;
7669 /***********************************************************************
7670 * WSAGetQOSByName (WS2_32.41)
7672 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
7674 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
7675 return FALSE;
7678 /***********************************************************************
7679 * WSAGetServiceClassInfoA (WS2_32.42)
7681 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
7682 LPWSASERVICECLASSINFOA info )
7684 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
7685 len, info );
7686 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7687 return SOCKET_ERROR;
7690 /***********************************************************************
7691 * WSAGetServiceClassInfoW (WS2_32.43)
7693 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
7694 LPWSASERVICECLASSINFOW info )
7696 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
7697 len, info );
7698 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7699 return SOCKET_ERROR;
7702 /***********************************************************************
7703 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
7705 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
7707 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
7708 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7709 return SOCKET_ERROR;
7712 /***********************************************************************
7713 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
7715 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
7717 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
7718 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7719 return SOCKET_ERROR;
7722 /***********************************************************************
7723 * WSALookupServiceBeginA (WS2_32.59)
7725 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
7726 DWORD dwControlFlags,
7727 LPHANDLE lphLookup)
7729 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
7730 lphLookup);
7731 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7732 return SOCKET_ERROR;
7735 /***********************************************************************
7736 * WSALookupServiceBeginW (WS2_32.60)
7738 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
7739 DWORD dwControlFlags,
7740 LPHANDLE lphLookup)
7742 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
7743 lphLookup);
7744 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7745 return SOCKET_ERROR;
7748 /***********************************************************************
7749 * WSALookupServiceEnd (WS2_32.61)
7751 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
7753 FIXME("(%p) Stub!\n", lookup );
7754 return 0;
7757 /***********************************************************************
7758 * WSALookupServiceNextA (WS2_32.62)
7760 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
7762 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
7763 SetLastError(WSA_E_NO_MORE);
7764 return SOCKET_ERROR;
7767 /***********************************************************************
7768 * WSALookupServiceNextW (WS2_32.63)
7770 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
7772 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
7773 SetLastError(WSA_E_NO_MORE);
7774 return SOCKET_ERROR;
7777 /***********************************************************************
7778 * WSANtohl (WS2_32.64)
7780 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
7782 TRACE( "(%04lx 0x%08x %p)\n", s, netlong, lphostlong );
7784 if (!lphostlong) return WSAEFAULT;
7786 *lphostlong = ntohl( netlong );
7787 return 0;
7790 /***********************************************************************
7791 * WSANtohs (WS2_32.65)
7793 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
7795 TRACE( "(%04lx 0x%08x %p)\n", s, netshort, lphostshort );
7797 if (!lphostshort) return WSAEFAULT;
7799 *lphostshort = ntohs( netshort );
7800 return 0;
7803 /***********************************************************************
7804 * WSAProviderConfigChange (WS2_32.66)
7806 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
7807 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
7809 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
7810 return SOCKET_ERROR;
7813 /***********************************************************************
7814 * WSARecvDisconnect (WS2_32.68)
7816 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
7818 TRACE( "(%04lx %p)\n", s, disconnectdata );
7820 return WS_shutdown( s, SD_RECEIVE );
7823 /***********************************************************************
7824 * WSASetServiceA (WS2_32.76)
7826 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
7828 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
7829 return 0;
7832 /***********************************************************************
7833 * WSASetServiceW (WS2_32.77)
7835 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
7837 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
7838 return 0;
7841 /***********************************************************************
7842 * WSCEnableNSProvider (WS2_32.84)
7844 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
7846 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
7847 return 0;
7850 /***********************************************************************
7851 * WSCGetProviderPath (WS2_32.86)
7853 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
7855 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
7857 if (!errcode || !provider || !len) return WSAEFAULT;
7859 *errcode = WSAEINVAL;
7860 return SOCKET_ERROR;
7863 /***********************************************************************
7864 * WSCInstallNameSpace (WS2_32.87)
7866 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
7867 DWORD version, LPGUID provider )
7869 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
7870 namespace, version, debugstr_guid(provider) );
7871 return 0;
7874 /***********************************************************************
7875 * WSCUnInstallNameSpace (WS2_32.89)
7877 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
7879 FIXME("(%p) Stub!\n", lpProviderId);
7880 return NO_ERROR;
7883 /***********************************************************************
7884 * WSCWriteProviderOrder (WS2_32.91)
7886 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
7888 FIXME("(%p 0x%08x) Stub!\n", entry, number);
7889 return 0;
7892 /***********************************************************************
7893 * WSANSPIoctl (WS2_32.91)
7895 INT WINAPI WSANSPIoctl( HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer,
7896 DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer,
7897 LPDWORD lpcbBytesReturned, LPWSACOMPLETION lpCompletion )
7899 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup, dwControlCode,
7900 lpvInBuffer, cbInBuffer, lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpCompletion);
7901 SetLastError(WSA_NOT_ENOUGH_MEMORY);
7902 return SOCKET_ERROR;
7905 /*****************************************************************************
7906 * WSAEnumProtocolsA [WS2_32.@]
7908 * see function WSAEnumProtocolsW
7910 INT WINAPI WSAEnumProtocolsA( LPINT protocols, LPWSAPROTOCOL_INFOA buffer, LPDWORD len )
7912 return WS_EnumProtocols( FALSE, protocols, (LPWSAPROTOCOL_INFOW) buffer, len);
7915 /*****************************************************************************
7916 * WSAEnumProtocolsW [WS2_32.@]
7918 * Retrieves information about specified set of active network protocols.
7920 * PARAMS
7921 * protocols [I] Pointer to null-terminated array of protocol id's. NULL
7922 * retrieves information on all available protocols.
7923 * buffer [I] Pointer to a buffer to be filled with WSAPROTOCOL_INFO
7924 * structures.
7925 * len [I/O] Pointer to a variable specifying buffer size. On output
7926 * the variable holds the number of bytes needed when the
7927 * specified size is too small.
7929 * RETURNS
7930 * Success: number of WSAPROTOCOL_INFO structures in buffer.
7931 * Failure: SOCKET_ERROR
7933 * NOTES
7934 * NT4SP5 does not return SPX if protocols == NULL
7936 * BUGS
7937 * - NT4SP5 returns in addition these list of NETBIOS protocols
7938 * (address family 17), each entry two times one for socket type 2 and 5
7940 * iProtocol szProtocol
7941 * 0x80000000 \Device\NwlnkNb
7942 * 0xfffffffa \Device\NetBT_CBENT7
7943 * 0xfffffffb \Device\Nbf_CBENT7
7944 * 0xfffffffc \Device\NetBT_NdisWan5
7945 * 0xfffffffd \Device\NetBT_El9202
7946 * 0xfffffffe \Device\Nbf_El9202
7947 * 0xffffffff \Device\Nbf_NdisWan4
7949 * - there is no check that the operating system supports the returned
7950 * protocols
7952 INT WINAPI WSAEnumProtocolsW( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
7954 return WS_EnumProtocols( TRUE, protocols, buffer, len);
7957 /*****************************************************************************
7958 * WSCEnumProtocols [WS2_32.@]
7960 * PARAMS
7961 * protocols [I] Null-terminated array of iProtocol values.
7962 * buffer [O] Buffer of WSAPROTOCOL_INFOW structures.
7963 * len [I/O] Size of buffer on input/output.
7964 * errno [O] Error code.
7966 * RETURNS
7967 * Success: number of protocols to be reported on.
7968 * Failure: SOCKET_ERROR. error is in errno.
7970 * BUGS
7971 * Doesn't supply info on layered protocols.
7974 INT WINAPI WSCEnumProtocols( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len, LPINT err )
7976 INT ret = WSAEnumProtocolsW( protocols, buffer, len );
7978 if (ret == SOCKET_ERROR) *err = WSAENOBUFS;
7980 return ret;