gdiplus: Add option to save metafile tests to files.
[wine/multimedia.git] / dlls / ws2_32 / socket.c
bloba8552857e54a743b47ee47d370f6c1b76aa90776
1 /*
2 * based on Windows Sockets 1.1 specs
4 * Copyright (C) 1993,1994,1996,1997 John Brezak, Erik Bos, Alex Korobka.
5 * Copyright (C) 2001 Stefan Leichter
6 * Copyright (C) 2004 Hans Leidekker
7 * Copyright (C) 2005 Marcus Meissner
8 * Copyright (C) 2006-2008 Kai Blin
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24 * NOTE: If you make any changes to fix a particular app, make sure
25 * they don't break something else like Netscape or telnet and ftp
26 * clients and servers (www.winsite.com got a lot of those).
29 #include "config.h"
30 #include "wine/port.h"
32 #include <stdarg.h>
33 #include <stdio.h>
34 #include <string.h>
35 #include <sys/types.h>
36 #ifdef HAVE_SYS_IPC_H
37 # include <sys/ipc.h>
38 #endif
39 #ifdef HAVE_SYS_IOCTL_H
40 # include <sys/ioctl.h>
41 #endif
42 #ifdef HAVE_SYS_FILIO_H
43 # include <sys/filio.h>
44 #endif
45 #ifdef HAVE_SYS_SOCKIO_H
46 # include <sys/sockio.h>
47 #endif
49 #if defined(__EMX__)
50 # include <sys/so_ioctl.h>
51 #endif
53 #ifdef HAVE_SYS_PARAM_H
54 # include <sys/param.h>
55 #endif
57 #ifdef HAVE_SYS_MSG_H
58 # include <sys/msg.h>
59 #endif
60 #ifdef HAVE_SYS_WAIT_H
61 # include <sys/wait.h>
62 #endif
63 #ifdef HAVE_SYS_UIO_H
64 # include <sys/uio.h>
65 #endif
66 #ifdef HAVE_SYS_SOCKET_H
67 #include <sys/socket.h>
68 #endif
69 #ifdef HAVE_NETINET_IN_H
70 # include <netinet/in.h>
71 #endif
72 #ifdef HAVE_NETINET_TCP_H
73 # include <netinet/tcp.h>
74 #endif
75 #ifdef HAVE_ARPA_INET_H
76 # include <arpa/inet.h>
77 #endif
78 #include <ctype.h>
79 #include <fcntl.h>
80 #include <errno.h>
81 #ifdef HAVE_NETDB_H
82 #include <netdb.h>
83 #endif
84 #ifdef HAVE_UNISTD_H
85 # include <unistd.h>
86 #endif
87 #include <stdlib.h>
88 #ifdef HAVE_ARPA_NAMESER_H
89 # include <arpa/nameser.h>
90 #endif
91 #ifdef HAVE_RESOLV_H
92 # include <resolv.h>
93 #endif
94 #ifdef HAVE_NET_IF_H
95 # include <net/if.h>
96 #endif
97 #ifdef HAVE_LINUX_FILTER_H
98 # include <linux/filter.h>
99 #endif
101 #ifdef HAVE_NETIPX_IPX_H
102 # include <netipx/ipx.h>
103 # define HAS_IPX
104 #elif defined(HAVE_LINUX_IPX_H)
105 # ifdef HAVE_ASM_TYPES_H
106 # include <asm/types.h>
107 # endif
108 # ifdef HAVE_LINUX_TYPES_H
109 # include <linux/types.h>
110 # endif
111 # include <linux/ipx.h>
112 # define HAS_IPX
113 #endif
115 #ifdef HAVE_LINUX_IRDA_H
116 # ifdef HAVE_LINUX_TYPES_H
117 # include <linux/types.h>
118 # endif
119 # include <linux/irda.h>
120 # define HAS_IRDA
121 #endif
123 #ifdef HAVE_POLL_H
124 #include <poll.h>
125 #endif
126 #ifdef HAVE_SYS_POLL_H
127 # include <sys/poll.h>
128 #endif
129 #ifdef HAVE_SYS_TIME_H
130 # include <sys/time.h>
131 #endif
133 #define NONAMELESSUNION
134 #define NONAMELESSSTRUCT
135 #include "ntstatus.h"
136 #define WIN32_NO_STATUS
137 #include "windef.h"
138 #include "winbase.h"
139 #include "wingdi.h"
140 #include "winuser.h"
141 #include "winerror.h"
142 #include "winnls.h"
143 #include "winsock2.h"
144 #include "mswsock.h"
145 #include "ws2tcpip.h"
146 #include "ws2spi.h"
147 #include "wsipx.h"
148 #include "wshisotp.h"
149 #include "mstcpip.h"
150 #include "af_irda.h"
151 #include "winnt.h"
152 #define USE_WC_PREFIX /* For CMSG_DATA */
153 #include "iphlpapi.h"
154 #include "wine/server.h"
155 #include "wine/debug.h"
156 #include "wine/exception.h"
157 #include "wine/unicode.h"
159 #ifdef HAS_IPX
160 # include "wsnwlink.h"
161 #endif
163 #if defined(linux) && !defined(IP_UNICAST_IF)
164 #define IP_UNICAST_IF 50
165 #endif
167 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
168 # define sipx_network sipx_addr.x_net
169 # define sipx_node sipx_addr.x_host.c_host
170 #endif /* __FreeBSD__ */
172 #ifndef INADDR_NONE
173 #define INADDR_NONE ~0UL
174 #endif
176 WINE_DEFAULT_DEBUG_CHANNEL(winsock);
177 WINE_DECLARE_DEBUG_CHANNEL(winediag);
179 /* names of the protocols */
180 static const WCHAR NameIpxW[] = {'I', 'P', 'X', '\0'};
181 static const WCHAR NameSpxW[] = {'S', 'P', 'X', '\0'};
182 static const WCHAR NameSpxIIW[] = {'S', 'P', 'X', ' ', 'I', 'I', '\0'};
183 static const WCHAR NameTcpW[] = {'T', 'C', 'P', '/', 'I', 'P', '\0'};
184 static const WCHAR NameUdpW[] = {'U', 'D', 'P', '/', 'I', 'P', '\0'};
186 /* Taken from Win2k */
187 static const GUID ProviderIdIP = { 0xe70f1aa0, 0xab8b, 0x11cf,
188 { 0x8c, 0xa3, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
189 static const GUID ProviderIdIPX = { 0x11058240, 0xbe47, 0x11cf,
190 { 0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
191 static const GUID ProviderIdSPX = { 0x11058241, 0xbe47, 0x11cf,
192 { 0x95, 0xc8, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92 } };
194 static const INT valid_protocols[] =
196 WS_IPPROTO_TCP,
197 WS_IPPROTO_UDP,
198 WS_NSPROTO_IPX,
199 WS_NSPROTO_SPX,
200 WS_NSPROTO_SPXII,
204 #define IS_IPX_PROTO(X) ((X) >= WS_NSPROTO_IPX && (X) <= WS_NSPROTO_IPX + 255)
206 #if defined(IP_UNICAST_IF) && defined(SO_ATTACH_FILTER)
207 # define LINUX_BOUND_IF
208 struct interface_filter {
209 struct sock_filter iface_memaddr;
210 struct sock_filter iface_rule;
211 struct sock_filter ip_memaddr;
212 struct sock_filter ip_rule;
213 struct sock_filter return_keep;
214 struct sock_filter return_dump;
216 # define FILTER_JUMP_DUMP(here) (u_char)(offsetof(struct interface_filter, return_dump) \
217 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
218 /sizeof(struct sock_filter)
219 # define FILTER_JUMP_KEEP(here) (u_char)(offsetof(struct interface_filter, return_keep) \
220 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
221 /sizeof(struct sock_filter)
222 # define FILTER_JUMP_NEXT() (u_char)(0)
223 # define SKF_NET_DESTIP 16 /* offset in the network header to the destination IP */
224 static struct interface_filter generic_interface_filter = {
225 /* This filter rule allows incoming packets on the specified interface, which works for all
226 * remotely generated packets and for locally generated broadcast packets. */
227 BPF_STMT(BPF_LD+BPF_W+BPF_ABS, SKF_AD_OFF+SKF_AD_IFINDEX),
228 BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0xdeadbeef, FILTER_JUMP_KEEP(iface_rule), FILTER_JUMP_NEXT()),
229 /* This rule allows locally generated packets targeted at the specific IP address of the chosen
230 * adapter (local packets not destined for the broadcast address do not have IFINDEX set) */
231 BPF_STMT(BPF_LD+BPF_W+BPF_ABS, SKF_NET_OFF+SKF_NET_DESTIP),
232 BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0xdeadbeef, FILTER_JUMP_KEEP(ip_rule), FILTER_JUMP_DUMP(ip_rule)),
233 BPF_STMT(BPF_RET+BPF_K, (u_int)-1), /* keep packet */
234 BPF_STMT(BPF_RET+BPF_K, 0) /* dump packet */
236 #endif /* LINUX_BOUND_IF */
239 * The actual definition of WSASendTo, wrapped in a different function name
240 * so that internal calls from ws2_32 itself will not trigger programs like
241 * Garena, which hooks WSASendTo/WSARecvFrom calls.
243 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
244 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
245 const struct WS_sockaddr *to, int tolen,
246 LPWSAOVERLAPPED lpOverlapped,
247 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine );
250 * Internal fundamental receive function, essentially WSARecvFrom with an
251 * additional parameter to support message control headers.
253 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
254 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
255 struct WS_sockaddr *lpFrom,
256 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
257 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
258 LPWSABUF lpControlBuffer );
260 /* critical section to protect some non-reentrant net function */
261 static CRITICAL_SECTION csWSgetXXXbyYYY;
262 static CRITICAL_SECTION_DEBUG critsect_debug =
264 0, 0, &csWSgetXXXbyYYY,
265 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
266 0, 0, { (DWORD_PTR)(__FILE__ ": csWSgetXXXbyYYY") }
268 static CRITICAL_SECTION csWSgetXXXbyYYY = { &critsect_debug, -1, 0, 0, 0, 0 };
270 union generic_unix_sockaddr
272 struct sockaddr addr;
273 char data[128]; /* should be big enough for all families */
276 static inline const char *debugstr_sockaddr( const struct WS_sockaddr *a )
278 if (!a) return "(nil)";
279 switch (a->sa_family)
281 case WS_AF_INET:
282 return wine_dbg_sprintf("{ family AF_INET, address %s, port %d }",
283 inet_ntoa(((const struct sockaddr_in *)a)->sin_addr),
284 ntohs(((const struct sockaddr_in *)a)->sin_port));
285 case WS_AF_INET6:
287 char buf[46];
288 const char *p;
289 struct WS_sockaddr_in6 *sin = (struct WS_sockaddr_in6 *)a;
291 p = WS_inet_ntop( WS_AF_INET6, &sin->sin6_addr, buf, sizeof(buf) );
292 if (!p)
293 p = "(unknown IPv6 address)";
294 return wine_dbg_sprintf("{ family AF_INET6, address %s, port %d }",
295 p, ntohs(sin->sin6_port));
297 case WS_AF_IPX:
299 int i;
300 char netnum[16], nodenum[16];
301 struct WS_sockaddr_ipx *sin = (struct WS_sockaddr_ipx *)a;
303 for (i = 0;i < 4; i++) sprintf(netnum + i * 2, "%02X", (unsigned char) sin->sa_netnum[i]);
304 for (i = 0;i < 6; i++) sprintf(nodenum + i * 2, "%02X", (unsigned char) sin->sa_nodenum[i]);
306 return wine_dbg_sprintf("{ family AF_IPX, address %s.%s, ipx socket %d }",
307 netnum, nodenum, sin->sa_socket);
309 case WS_AF_IRDA:
311 DWORD addr;
313 memcpy( &addr, ((const SOCKADDR_IRDA *)a)->irdaDeviceID, sizeof(addr) );
314 addr = ntohl( addr );
315 return wine_dbg_sprintf("{ family AF_IRDA, addr %08x, name %s }",
316 addr,
317 ((const SOCKADDR_IRDA *)a)->irdaServiceName);
319 default:
320 return wine_dbg_sprintf("{ family %d }", a->sa_family);
324 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
325 #define SOCKET2HANDLE(s) ((HANDLE)(s))
326 #define HANDLE2SOCKET(h) ((SOCKET)(h))
328 /****************************************************************
329 * Async IO declarations
330 ****************************************************************/
332 typedef struct ws2_async
334 HANDLE hSocket;
335 int type;
336 LPWSAOVERLAPPED user_overlapped;
337 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
338 IO_STATUS_BLOCK local_iosb;
339 struct WS_sockaddr *addr;
340 union
342 int val; /* for send operations */
343 int *ptr; /* for recv operations */
344 } addrlen;
345 DWORD flags;
346 DWORD *lpFlags;
347 WSABUF *control;
348 unsigned int n_iovecs;
349 unsigned int first_iovec;
350 struct iovec iovec[1];
351 } ws2_async;
353 typedef struct ws2_accept_async
355 HANDLE listen_socket;
356 HANDLE accept_socket;
357 LPOVERLAPPED user_overlapped;
358 ULONG_PTR cvalue;
359 PVOID buf; /* buffer to write data to */
360 int data_len;
361 int local_len;
362 int remote_len;
363 struct ws2_async *read;
364 } ws2_accept_async;
366 /****************************************************************/
368 /* ----------------------------------- internal data */
370 /* ws_... struct conversion flags */
372 typedef struct /* WSAAsyncSelect() control struct */
374 HANDLE service, event, sock;
375 HWND hWnd;
376 UINT uMsg;
377 LONG lEvent;
378 } ws_select_info;
380 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
381 #define WS_MAX_UDP_DATAGRAM 1024
382 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
384 /* hostent's, servent's and protent's are stored in one buffer per thread,
385 * as documented on MSDN for the functions that return any of the buffers */
386 struct per_thread_data
388 int opentype;
389 struct WS_hostent *he_buffer;
390 struct WS_servent *se_buffer;
391 struct WS_protoent *pe_buffer;
392 int he_len;
393 int se_len;
394 int pe_len;
395 char ntoa_buffer[16]; /* 4*3 digits + 3 '.' + 1 '\0' */
398 /* internal: routing description information */
399 struct route {
400 struct in_addr addr;
401 IF_INDEX interface;
402 DWORD metric;
405 static INT num_startup; /* reference counter */
406 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
408 /* function prototypes */
409 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length);
410 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
411 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
412 static struct WS_servent *WS_dup_se(const struct servent* p_se);
413 static int ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size);
415 int WSAIOCTL_GetInterfaceCount(void);
416 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
418 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus, ULONG Information );
420 #define MAP_OPTION(opt) { WS_##opt, opt }
422 static const int ws_sock_map[][2] =
424 MAP_OPTION( SO_DEBUG ),
425 MAP_OPTION( SO_ACCEPTCONN ),
426 MAP_OPTION( SO_REUSEADDR ),
427 MAP_OPTION( SO_KEEPALIVE ),
428 MAP_OPTION( SO_DONTROUTE ),
429 MAP_OPTION( SO_BROADCAST ),
430 MAP_OPTION( SO_LINGER ),
431 MAP_OPTION( SO_OOBINLINE ),
432 MAP_OPTION( SO_SNDBUF ),
433 MAP_OPTION( SO_RCVBUF ),
434 MAP_OPTION( SO_ERROR ),
435 MAP_OPTION( SO_TYPE ),
436 #ifdef SO_RCVTIMEO
437 MAP_OPTION( SO_RCVTIMEO ),
438 #endif
439 #ifdef SO_SNDTIMEO
440 MAP_OPTION( SO_SNDTIMEO ),
441 #endif
444 static const int ws_tcp_map[][2] =
446 #ifdef TCP_NODELAY
447 MAP_OPTION( TCP_NODELAY ),
448 #endif
451 static const int ws_ip_map[][2] =
453 MAP_OPTION( IP_MULTICAST_IF ),
454 MAP_OPTION( IP_MULTICAST_TTL ),
455 MAP_OPTION( IP_MULTICAST_LOOP ),
456 MAP_OPTION( IP_ADD_MEMBERSHIP ),
457 MAP_OPTION( IP_DROP_MEMBERSHIP ),
458 MAP_OPTION( IP_OPTIONS ),
459 #ifdef IP_HDRINCL
460 MAP_OPTION( IP_HDRINCL ),
461 #endif
462 MAP_OPTION( IP_TOS ),
463 MAP_OPTION( IP_TTL ),
464 #ifdef IP_PKTINFO
465 MAP_OPTION( IP_PKTINFO ),
466 #endif
467 #ifdef IP_UNICAST_IF
468 MAP_OPTION( IP_UNICAST_IF ),
469 #endif
472 static const int ws_ipv6_map[][2] =
474 #ifdef IPV6_ADD_MEMBERSHIP
475 MAP_OPTION( IPV6_ADD_MEMBERSHIP ),
476 #endif
477 #ifdef IPV6_DROP_MEMBERSHIP
478 MAP_OPTION( IPV6_DROP_MEMBERSHIP ),
479 #endif
480 MAP_OPTION( IPV6_MULTICAST_IF ),
481 MAP_OPTION( IPV6_MULTICAST_HOPS ),
482 MAP_OPTION( IPV6_MULTICAST_LOOP ),
483 MAP_OPTION( IPV6_UNICAST_HOPS ),
484 MAP_OPTION( IPV6_V6ONLY ),
485 #ifdef IPV6_UNICAST_IF
486 MAP_OPTION( IPV6_UNICAST_IF ),
487 #endif
490 static const int ws_af_map[][2] =
492 MAP_OPTION( AF_UNSPEC ),
493 MAP_OPTION( AF_INET ),
494 MAP_OPTION( AF_INET6 ),
495 #ifdef HAS_IPX
496 MAP_OPTION( AF_IPX ),
497 #endif
498 #ifdef AF_IRDA
499 MAP_OPTION( AF_IRDA ),
500 #endif
501 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
504 static const int ws_socktype_map[][2] =
506 MAP_OPTION( SOCK_DGRAM ),
507 MAP_OPTION( SOCK_STREAM ),
508 MAP_OPTION( SOCK_RAW ),
509 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
512 static const int ws_proto_map[][2] =
514 MAP_OPTION( IPPROTO_IP ),
515 MAP_OPTION( IPPROTO_TCP ),
516 MAP_OPTION( IPPROTO_UDP ),
517 MAP_OPTION( IPPROTO_ICMP ),
518 MAP_OPTION( IPPROTO_IGMP ),
519 MAP_OPTION( IPPROTO_RAW ),
520 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
523 static const int ws_aiflag_map[][2] =
525 MAP_OPTION( AI_PASSIVE ),
526 MAP_OPTION( AI_CANONNAME ),
527 MAP_OPTION( AI_NUMERICHOST ),
528 MAP_OPTION( AI_V4MAPPED ),
529 MAP_OPTION( AI_ADDRCONFIG ),
532 static const int ws_niflag_map[][2] =
534 MAP_OPTION( NI_NOFQDN ),
535 MAP_OPTION( NI_NUMERICHOST ),
536 MAP_OPTION( NI_NAMEREQD ),
537 MAP_OPTION( NI_NUMERICSERV ),
538 MAP_OPTION( NI_DGRAM ),
541 static const int ws_eai_map[][2] =
543 MAP_OPTION( EAI_AGAIN ),
544 MAP_OPTION( EAI_BADFLAGS ),
545 MAP_OPTION( EAI_FAIL ),
546 MAP_OPTION( EAI_FAMILY ),
547 MAP_OPTION( EAI_MEMORY ),
548 /* Note: EAI_NODATA is deprecated, but still
549 * used by Windows and Linux... We map the newer
550 * EAI_NONAME to EAI_NODATA for now until Windows
551 * changes too.
553 #ifdef EAI_NODATA
554 MAP_OPTION( EAI_NODATA ),
555 #endif
556 #ifdef EAI_NONAME
557 { WS_EAI_NODATA, EAI_NONAME },
558 #endif
560 MAP_OPTION( EAI_SERVICE ),
561 MAP_OPTION( EAI_SOCKTYPE ),
562 { 0, 0 }
565 static const char magic_loopback_addr[] = {127, 12, 34, 56};
567 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
568 static inline WSACMSGHDR *fill_control_message(int level, int type, WSACMSGHDR *current, ULONG *maxsize, void *data, int len)
570 ULONG msgsize = sizeof(WSACMSGHDR) + WSA_CMSG_ALIGN(len);
571 char *ptr = (char *) current + sizeof(WSACMSGHDR);
573 /* Make sure there is at least enough room for this entry */
574 if (msgsize > *maxsize)
575 return NULL;
576 *maxsize -= msgsize;
577 /* Fill in the entry */
578 current->cmsg_len = sizeof(WSACMSGHDR) + len;
579 current->cmsg_level = level;
580 current->cmsg_type = type;
581 memcpy(ptr, data, len);
582 /* Return the pointer to where next entry should go */
583 return (WSACMSGHDR *) (ptr + WSA_CMSG_ALIGN(len));
586 static inline int convert_control_headers(struct msghdr *hdr, WSABUF *control)
588 #ifdef IP_PKTINFO
589 WSACMSGHDR *cmsg_win = (WSACMSGHDR *) control->buf, *ptr;
590 ULONG ctlsize = control->len;
591 struct cmsghdr *cmsg_unix;
593 ptr = cmsg_win;
594 /* Loop over all the headers, converting as appropriate */
595 for (cmsg_unix = CMSG_FIRSTHDR(hdr); cmsg_unix != NULL; cmsg_unix = CMSG_NXTHDR(hdr, cmsg_unix))
597 switch(cmsg_unix->cmsg_level)
599 case IPPROTO_IP:
600 switch(cmsg_unix->cmsg_type)
602 case IP_PKTINFO:
604 /* Convert the Unix IP_PKTINFO structure to the Windows version */
605 struct in_pktinfo *data_unix = (struct in_pktinfo *) CMSG_DATA(cmsg_unix);
606 struct WS_in_pktinfo data_win;
608 memcpy(&data_win.ipi_addr,&data_unix->ipi_addr.s_addr,4); /* 4 bytes = 32 address bits */
609 data_win.ipi_ifindex = data_unix->ipi_ifindex;
610 ptr = fill_control_message(WS_IPPROTO_IP, WS_IP_PKTINFO, ptr, &ctlsize,
611 (void*)&data_win, sizeof(data_win));
612 if (!ptr) goto error;
613 } break;
614 default:
615 FIXME("Unhandled IPPROTO_IP message header type %d\n", cmsg_unix->cmsg_type);
616 break;
618 break;
619 default:
620 FIXME("Unhandled message header level %d\n", cmsg_unix->cmsg_level);
621 break;
625 error:
626 /* Set the length of the returned control headers */
627 control->len = (ptr == NULL ? 0 : (char*)ptr - (char*)cmsg_win);
628 return (ptr != NULL);
629 #else /* IP_PKTINFO */
630 control->len = 0;
631 return 1;
632 #endif /* IP_PKTINFO */
634 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
636 /* ----------------------------------- error handling */
638 static NTSTATUS sock_get_ntstatus( int err )
640 switch ( err )
642 case EBADF: return STATUS_INVALID_HANDLE;
643 case EBUSY: return STATUS_DEVICE_BUSY;
644 case EPERM:
645 case EACCES: return STATUS_ACCESS_DENIED;
646 case EFAULT: return STATUS_NO_MEMORY;
647 case EINVAL: return STATUS_INVALID_PARAMETER;
648 case ENFILE:
649 case EMFILE: return STATUS_TOO_MANY_OPENED_FILES;
650 case EWOULDBLOCK: return STATUS_CANT_WAIT;
651 case EINPROGRESS: return STATUS_PENDING;
652 case EALREADY: return STATUS_NETWORK_BUSY;
653 case ENOTSOCK: return STATUS_OBJECT_TYPE_MISMATCH;
654 case EDESTADDRREQ: return STATUS_INVALID_PARAMETER;
655 case EMSGSIZE: return STATUS_BUFFER_OVERFLOW;
656 case EPROTONOSUPPORT:
657 case ESOCKTNOSUPPORT:
658 case EPFNOSUPPORT:
659 case EAFNOSUPPORT:
660 case EPROTOTYPE: return STATUS_NOT_SUPPORTED;
661 case ENOPROTOOPT: return STATUS_INVALID_PARAMETER;
662 case EOPNOTSUPP: return STATUS_NOT_SUPPORTED;
663 case EADDRINUSE: return STATUS_ADDRESS_ALREADY_ASSOCIATED;
664 case EADDRNOTAVAIL: return STATUS_INVALID_PARAMETER;
665 case ECONNREFUSED: return STATUS_CONNECTION_REFUSED;
666 case ESHUTDOWN: return STATUS_PIPE_DISCONNECTED;
667 case ENOTCONN: return STATUS_CONNECTION_DISCONNECTED;
668 case ETIMEDOUT: return STATUS_IO_TIMEOUT;
669 case ENETUNREACH: return STATUS_NETWORK_UNREACHABLE;
670 case ENETDOWN: return STATUS_NETWORK_BUSY;
671 case EPIPE:
672 case ECONNRESET: return STATUS_CONNECTION_RESET;
673 case ECONNABORTED: return STATUS_CONNECTION_ABORTED;
675 case 0: return STATUS_SUCCESS;
676 default:
677 WARN("Unknown errno %d!\n", err);
678 return STATUS_UNSUCCESSFUL;
682 static UINT sock_get_error( int err )
684 switch(err)
686 case EINTR: return WSAEINTR;
687 case EBADF: return WSAEBADF;
688 case EPERM:
689 case EACCES: return WSAEACCES;
690 case EFAULT: return WSAEFAULT;
691 case EINVAL: return WSAEINVAL;
692 case EMFILE: return WSAEMFILE;
693 case EWOULDBLOCK: return WSAEWOULDBLOCK;
694 case EINPROGRESS: return WSAEINPROGRESS;
695 case EALREADY: return WSAEALREADY;
696 case ENOTSOCK: return WSAENOTSOCK;
697 case EDESTADDRREQ: return WSAEDESTADDRREQ;
698 case EMSGSIZE: return WSAEMSGSIZE;
699 case EPROTOTYPE: return WSAEPROTOTYPE;
700 case ENOPROTOOPT: return WSAENOPROTOOPT;
701 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
702 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
703 case EOPNOTSUPP: return WSAEOPNOTSUPP;
704 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
705 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
706 case EADDRINUSE: return WSAEADDRINUSE;
707 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
708 case ENETDOWN: return WSAENETDOWN;
709 case ENETUNREACH: return WSAENETUNREACH;
710 case ENETRESET: return WSAENETRESET;
711 case ECONNABORTED: return WSAECONNABORTED;
712 case EPIPE:
713 case ECONNRESET: return WSAECONNRESET;
714 case ENOBUFS: return WSAENOBUFS;
715 case EISCONN: return WSAEISCONN;
716 case ENOTCONN: return WSAENOTCONN;
717 case ESHUTDOWN: return WSAESHUTDOWN;
718 case ETOOMANYREFS: return WSAETOOMANYREFS;
719 case ETIMEDOUT: return WSAETIMEDOUT;
720 case ECONNREFUSED: return WSAECONNREFUSED;
721 case ELOOP: return WSAELOOP;
722 case ENAMETOOLONG: return WSAENAMETOOLONG;
723 case EHOSTDOWN: return WSAEHOSTDOWN;
724 case EHOSTUNREACH: return WSAEHOSTUNREACH;
725 case ENOTEMPTY: return WSAENOTEMPTY;
726 #ifdef EPROCLIM
727 case EPROCLIM: return WSAEPROCLIM;
728 #endif
729 #ifdef EUSERS
730 case EUSERS: return WSAEUSERS;
731 #endif
732 #ifdef EDQUOT
733 case EDQUOT: return WSAEDQUOT;
734 #endif
735 #ifdef ESTALE
736 case ESTALE: return WSAESTALE;
737 #endif
738 #ifdef EREMOTE
739 case EREMOTE: return WSAEREMOTE;
740 #endif
742 /* just in case we ever get here and there are no problems */
743 case 0: return 0;
744 default:
745 WARN("Unknown errno %d!\n", err);
746 return WSAEOPNOTSUPP;
750 static UINT wsaErrno(void)
752 int loc_errno = errno;
753 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
755 return sock_get_error( loc_errno );
758 /* most ws2 overlapped functions return an ntstatus-based error code */
759 static NTSTATUS wsaErrStatus(void)
761 int loc_errno = errno;
762 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
764 return sock_get_ntstatus(loc_errno);
767 static UINT wsaHerrno(int loc_errno)
769 WARN("h_errno %d.\n", loc_errno);
771 switch(loc_errno)
773 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
774 case TRY_AGAIN: return WSATRY_AGAIN;
775 case NO_RECOVERY: return WSANO_RECOVERY;
776 case NO_DATA: return WSANO_DATA;
777 case ENOBUFS: return WSAENOBUFS;
779 case 0: return 0;
780 default:
781 WARN("Unknown h_errno %d!\n", loc_errno);
782 return WSAEOPNOTSUPP;
786 static inline DWORD NtStatusToWSAError( const DWORD status )
788 /* We only need to cover the status codes set by server async request handling */
789 DWORD wserr;
790 switch ( status )
792 case STATUS_SUCCESS: wserr = 0; break;
793 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
794 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
795 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
796 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
797 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
798 case STATUS_NETWORK_BUSY: wserr = WSAEALREADY; break;
799 case STATUS_NETWORK_UNREACHABLE: wserr = WSAENETUNREACH; break;
800 case STATUS_CONNECTION_REFUSED: wserr = WSAECONNREFUSED; break;
801 case STATUS_CONNECTION_DISCONNECTED: wserr = WSAENOTCONN; break;
802 case STATUS_CONNECTION_RESET: wserr = WSAECONNRESET; break;
803 case STATUS_CONNECTION_ABORTED: wserr = WSAECONNABORTED; break;
804 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
805 case STATUS_ADDRESS_ALREADY_ASSOCIATED: wserr = WSAEADDRINUSE; break;
806 case STATUS_IO_TIMEOUT:
807 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
808 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
809 case STATUS_ACCESS_DENIED: wserr = WSAEACCES; break;
810 case STATUS_TOO_MANY_OPENED_FILES: wserr = WSAEMFILE; break;
811 case STATUS_CANT_WAIT: wserr = WSAEWOULDBLOCK; break;
812 case STATUS_BUFFER_OVERFLOW: wserr = WSAEMSGSIZE; break;
813 case STATUS_NOT_SUPPORTED: wserr = WSAEOPNOTSUPP; break;
814 case STATUS_HOST_UNREACHABLE: wserr = WSAEHOSTUNREACH; break;
816 default:
817 wserr = RtlNtStatusToDosError( status );
818 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
820 return wserr;
823 /* set last error code from NT status without mapping WSA errors */
824 static inline unsigned int set_error( unsigned int err )
826 if (err)
828 err = NtStatusToWSAError( err );
829 SetLastError( err );
831 return err;
834 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
836 int fd;
837 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
838 return -1;
839 return fd;
842 static inline void release_sock_fd( SOCKET s, int fd )
844 wine_server_release_fd( SOCKET2HANDLE(s), fd );
847 static void _enable_event( HANDLE s, unsigned int event,
848 unsigned int sstate, unsigned int cstate )
850 SERVER_START_REQ( enable_socket_event )
852 req->handle = wine_server_obj_handle( s );
853 req->mask = event;
854 req->sstate = sstate;
855 req->cstate = cstate;
856 wine_server_call( req );
858 SERVER_END_REQ;
861 static NTSTATUS _is_blocking(SOCKET s, BOOL *ret)
863 NTSTATUS status;
864 SERVER_START_REQ( get_socket_event )
866 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
867 req->service = FALSE;
868 req->c_event = 0;
869 status = wine_server_call( req );
870 *ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
872 SERVER_END_REQ;
873 return status;
876 static unsigned int _get_sock_mask(SOCKET s)
878 unsigned int ret;
879 SERVER_START_REQ( get_socket_event )
881 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
882 req->service = FALSE;
883 req->c_event = 0;
884 wine_server_call( req );
885 ret = reply->mask;
887 SERVER_END_REQ;
888 return ret;
891 static void _sync_sock_state(SOCKET s)
893 BOOL dummy;
894 /* do a dummy wineserver request in order to let
895 the wineserver run through its select loop once */
896 (void)_is_blocking(s, &dummy);
899 static int _get_sock_error(SOCKET s, unsigned int bit)
901 int events[FD_MAX_EVENTS];
903 SERVER_START_REQ( get_socket_event )
905 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
906 req->service = FALSE;
907 req->c_event = 0;
908 wine_server_set_reply( req, events, sizeof(events) );
909 wine_server_call( req );
911 SERVER_END_REQ;
912 return events[bit];
915 static struct per_thread_data *get_per_thread_data(void)
917 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
918 /* lazy initialization */
919 if (!ptb)
921 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
922 NtCurrentTeb()->WinSockData = ptb;
924 return ptb;
927 static void free_per_thread_data(void)
929 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
931 if (!ptb) return;
933 /* delete scratch buffers */
934 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
935 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
936 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
937 ptb->he_buffer = NULL;
938 ptb->se_buffer = NULL;
939 ptb->pe_buffer = NULL;
941 HeapFree( GetProcessHeap(), 0, ptb );
942 NtCurrentTeb()->WinSockData = NULL;
945 /***********************************************************************
946 * DllMain (WS2_32.init)
948 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
950 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
951 switch (fdwReason) {
952 case DLL_PROCESS_ATTACH:
953 break;
954 case DLL_PROCESS_DETACH:
955 if (fImpLoad) break;
956 free_per_thread_data();
957 DeleteCriticalSection(&csWSgetXXXbyYYY);
958 break;
959 case DLL_THREAD_DETACH:
960 free_per_thread_data();
961 break;
963 return TRUE;
966 /***********************************************************************
967 * convert_sockopt()
969 * Converts socket flags from Windows format.
970 * Return 1 if converted, 0 if not (error).
972 static int convert_sockopt(INT *level, INT *optname)
974 unsigned int i;
975 switch (*level)
977 case WS_SOL_SOCKET:
978 *level = SOL_SOCKET;
979 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
980 if( ws_sock_map[i][0] == *optname )
982 *optname = ws_sock_map[i][1];
983 return 1;
986 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
987 break;
988 case WS_IPPROTO_TCP:
989 *level = IPPROTO_TCP;
990 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
991 if ( ws_tcp_map[i][0] == *optname )
993 *optname = ws_tcp_map[i][1];
994 return 1;
997 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
998 break;
999 case WS_IPPROTO_IP:
1000 *level = IPPROTO_IP;
1001 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
1002 if (ws_ip_map[i][0] == *optname )
1004 *optname = ws_ip_map[i][1];
1005 return 1;
1008 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
1009 break;
1010 case WS_IPPROTO_IPV6:
1011 *level = IPPROTO_IPV6;
1012 for(i=0; i<sizeof(ws_ipv6_map)/sizeof(ws_ipv6_map[0]); i++) {
1013 if (ws_ipv6_map[i][0] == *optname )
1015 *optname = ws_ipv6_map[i][1];
1016 return 1;
1019 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname);
1020 break;
1021 default: FIXME("Unimplemented or unknown socket level\n");
1023 return 0;
1026 /* ----------------------------------- Per-thread info (or per-process?) */
1028 static char *strdup_lower(const char *str)
1030 int i;
1031 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
1033 if (ret)
1035 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
1036 ret[i] = 0;
1038 else SetLastError(WSAENOBUFS);
1039 return ret;
1042 static inline int sock_error_p(int s)
1044 unsigned int optval;
1045 socklen_t optlen = sizeof(optval);
1046 getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
1047 if (optval) WARN("\t[%i] error: %d\n", s, optval);
1048 return optval != 0;
1051 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
1052 * from an fd and return the value converted to milli seconds
1053 * or -1 if there is an infinite time out */
1054 static inline int get_rcvsnd_timeo( int fd, int optname)
1056 struct timeval tv;
1057 socklen_t len = sizeof(tv);
1058 int ret = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
1059 if( ret >= 0)
1060 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
1061 if( ret <= 0 ) /* tv == {0,0} means infinite time out */
1062 return -1;
1063 return ret;
1066 /* macro wrappers for portability */
1067 #ifdef SO_RCVTIMEO
1068 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
1069 #else
1070 #define GET_RCVTIMEO(fd) (-1)
1071 #endif
1073 #ifdef SO_SNDTIMEO
1074 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
1075 #else
1076 #define GET_SNDTIMEO(fd) (-1)
1077 #endif
1079 /* utility: given an fd, will block until one of the events occurs */
1080 static inline int do_block( int fd, int events, int timeout )
1082 struct pollfd pfd;
1083 int ret;
1085 pfd.fd = fd;
1086 pfd.events = events;
1088 while ((ret = poll(&pfd, 1, timeout)) < 0)
1090 if (errno != EINTR)
1091 return -1;
1093 if( ret == 0 )
1094 return 0;
1095 return pfd.revents;
1098 static int
1099 convert_af_w2u(int windowsaf) {
1100 unsigned int i;
1102 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1103 if (ws_af_map[i][0] == windowsaf)
1104 return ws_af_map[i][1];
1105 FIXME("unhandled Windows address family %d\n", windowsaf);
1106 return -1;
1109 static int
1110 convert_af_u2w(int unixaf) {
1111 unsigned int i;
1113 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1114 if (ws_af_map[i][1] == unixaf)
1115 return ws_af_map[i][0];
1116 FIXME("unhandled UNIX address family %d\n", unixaf);
1117 return -1;
1120 static int
1121 convert_proto_w2u(int windowsproto) {
1122 unsigned int i;
1124 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1125 if (ws_proto_map[i][0] == windowsproto)
1126 return ws_proto_map[i][1];
1128 /* check for extended IPX */
1129 if (IS_IPX_PROTO(windowsproto))
1130 return windowsproto;
1132 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
1133 return -1;
1136 static int
1137 convert_proto_u2w(int unixproto) {
1138 unsigned int i;
1140 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1141 if (ws_proto_map[i][1] == unixproto)
1142 return ws_proto_map[i][0];
1144 /* if value is inside IPX range just return it - the kernel simply
1145 * echoes the value used in the socket() function */
1146 if (IS_IPX_PROTO(unixproto))
1147 return unixproto;
1149 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
1150 return -1;
1153 static int
1154 convert_socktype_w2u(int windowssocktype) {
1155 unsigned int i;
1157 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1158 if (ws_socktype_map[i][0] == windowssocktype)
1159 return ws_socktype_map[i][1];
1160 FIXME("unhandled Windows socket type %d\n", windowssocktype);
1161 return -1;
1164 static int
1165 convert_socktype_u2w(int unixsocktype) {
1166 unsigned int i;
1168 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1169 if (ws_socktype_map[i][1] == unixsocktype)
1170 return ws_socktype_map[i][0];
1171 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
1172 return -1;
1175 static int set_ipx_packettype(int sock, int ptype)
1177 #ifdef HAS_IPX
1178 int fd = get_sock_fd( sock, 0, NULL ), ret = 0;
1179 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", ptype, fd);
1181 if (fd == -1) return SOCKET_ERROR;
1183 /* We try to set the ipx type on ipx socket level. */
1184 #ifdef SOL_IPX
1185 if(setsockopt(fd, SOL_IPX, IPX_TYPE, &ptype, sizeof(ptype)) == -1)
1187 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
1188 ret = SOCKET_ERROR;
1190 #else
1192 struct ipx val;
1193 /* Should we retrieve val using a getsockopt call and then
1194 * set the modified one? */
1195 val.ipx_pt = ptype;
1196 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
1198 #endif
1199 release_sock_fd( sock, fd );
1200 return ret;
1201 #else
1202 WARN("IPX support is not enabled, can't set packet type\n");
1203 return SOCKET_ERROR;
1204 #endif
1207 /* ----------------------------------- API -----
1209 * Init / cleanup / error checking.
1212 /***********************************************************************
1213 * WSAStartup (WS2_32.115)
1215 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
1217 TRACE("verReq=%x\n", wVersionRequested);
1219 if (LOBYTE(wVersionRequested) < 1)
1220 return WSAVERNOTSUPPORTED;
1222 if (!lpWSAData) return WSAEINVAL;
1224 num_startup++;
1226 /* that's the whole of the negotiation for now */
1227 lpWSAData->wVersion = wVersionRequested;
1228 /* return winsock information */
1229 lpWSAData->wHighVersion = 0x0202;
1230 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
1231 strcpy(lpWSAData->szSystemStatus, "Running" );
1232 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
1233 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
1234 /* don't do anything with lpWSAData->lpVendorInfo */
1235 /* (some apps don't allocate the space for this field) */
1237 TRACE("succeeded\n");
1238 return 0;
1242 /***********************************************************************
1243 * WSACleanup (WS2_32.116)
1245 INT WINAPI WSACleanup(void)
1247 if (num_startup) {
1248 num_startup--;
1249 return 0;
1251 SetLastError(WSANOTINITIALISED);
1252 return SOCKET_ERROR;
1256 /***********************************************************************
1257 * WSAGetLastError (WS2_32.111)
1259 INT WINAPI WSAGetLastError(void)
1261 return GetLastError();
1264 /***********************************************************************
1265 * WSASetLastError (WS2_32.112)
1267 void WINAPI WSASetLastError(INT iError) {
1268 SetLastError(iError);
1271 static struct WS_hostent *check_buffer_he(int size)
1273 struct per_thread_data * ptb = get_per_thread_data();
1274 if (ptb->he_buffer)
1276 if (ptb->he_len >= size ) return ptb->he_buffer;
1277 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1279 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
1280 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
1281 return ptb->he_buffer;
1284 static struct WS_servent *check_buffer_se(int size)
1286 struct per_thread_data * ptb = get_per_thread_data();
1287 if (ptb->se_buffer)
1289 if (ptb->se_len >= size ) return ptb->se_buffer;
1290 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1292 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
1293 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
1294 return ptb->se_buffer;
1297 static struct WS_protoent *check_buffer_pe(int size)
1299 struct per_thread_data * ptb = get_per_thread_data();
1300 if (ptb->pe_buffer)
1302 if (ptb->pe_len >= size ) return ptb->pe_buffer;
1303 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1305 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
1306 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
1307 return ptb->pe_buffer;
1310 /* ----------------------------------- i/o APIs */
1312 static inline BOOL supported_pf(int pf)
1314 switch (pf)
1316 case WS_AF_INET:
1317 case WS_AF_INET6:
1318 return TRUE;
1319 #ifdef HAS_IPX
1320 case WS_AF_IPX:
1321 return TRUE;
1322 #endif
1323 #ifdef HAS_IRDA
1324 case WS_AF_IRDA:
1325 return TRUE;
1326 #endif
1327 default:
1328 return FALSE;
1332 static inline BOOL supported_protocol(int protocol)
1334 int i;
1335 for (i = 0; i < sizeof(valid_protocols) / sizeof(valid_protocols[0]); i++)
1336 if (protocol == valid_protocols[i])
1337 return TRUE;
1338 return FALSE;
1341 /**********************************************************************/
1343 /* Returns the length of the converted address if successful, 0 if it was too small to
1344 * start with.
1346 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
1347 union generic_unix_sockaddr *uaddr)
1349 unsigned int uaddrlen = 0;
1351 switch (wsaddr->sa_family)
1353 #ifdef HAS_IPX
1354 case WS_AF_IPX:
1356 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
1357 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
1359 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
1360 return 0;
1362 uaddrlen = sizeof(struct sockaddr_ipx);
1363 memset( uaddr, 0, uaddrlen );
1364 uipx->sipx_family=AF_IPX;
1365 uipx->sipx_port=wsipx->sa_socket;
1366 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1367 * in one go
1369 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
1370 #ifdef IPX_FRAME_NONE
1371 uipx->sipx_type=IPX_FRAME_NONE;
1372 #endif
1373 break;
1375 #endif
1376 case WS_AF_INET6: {
1377 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
1378 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
1380 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1381 * scope_id, one without.
1383 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
1384 uaddrlen = sizeof(struct sockaddr_in6);
1385 memset( uaddr, 0, uaddrlen );
1386 uin6->sin6_family = AF_INET6;
1387 uin6->sin6_port = win6->sin6_port;
1388 uin6->sin6_flowinfo = win6->sin6_flowinfo;
1389 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1390 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
1391 #endif
1392 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
1393 break;
1395 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
1396 return 0;
1398 case WS_AF_INET: {
1399 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
1400 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
1402 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
1403 return 0;
1404 uaddrlen = sizeof(struct sockaddr_in);
1405 memset( uaddr, 0, uaddrlen );
1406 uin->sin_family = AF_INET;
1407 uin->sin_port = win->sin_port;
1408 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
1409 break;
1411 #ifdef HAS_IRDA
1412 case WS_AF_IRDA: {
1413 struct sockaddr_irda *uin = (struct sockaddr_irda *)uaddr;
1414 const SOCKADDR_IRDA *win = (const SOCKADDR_IRDA *)wsaddr;
1416 if (wsaddrlen < sizeof(SOCKADDR_IRDA))
1417 return 0;
1418 uaddrlen = sizeof(struct sockaddr_irda);
1419 memset( uaddr, 0, uaddrlen );
1420 uin->sir_family = AF_IRDA;
1421 if (!strncmp( win->irdaServiceName, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1423 unsigned int lsap_sel = 0;
1425 sscanf( win->irdaServiceName, "LSAP-SEL%u", &lsap_sel );
1426 uin->sir_lsap_sel = lsap_sel;
1428 else
1430 uin->sir_lsap_sel = LSAP_ANY;
1431 memcpy( uin->sir_name, win->irdaServiceName, 25 );
1433 memcpy( &uin->sir_addr, win->irdaDeviceID, sizeof(uin->sir_addr) );
1434 break;
1436 #endif
1437 case WS_AF_UNSPEC: {
1438 /* Try to determine the needed space by the passed windows sockaddr space */
1439 switch (wsaddrlen) {
1440 default: /* likely an ipv4 address */
1441 case sizeof(struct WS_sockaddr_in):
1442 uaddrlen = sizeof(struct sockaddr_in);
1443 break;
1444 #ifdef HAS_IPX
1445 case sizeof(struct WS_sockaddr_ipx):
1446 uaddrlen = sizeof(struct sockaddr_ipx);
1447 break;
1448 #endif
1449 #ifdef HAS_IRDA
1450 case sizeof(SOCKADDR_IRDA):
1451 uaddrlen = sizeof(struct sockaddr_irda);
1452 break;
1453 #endif
1454 case sizeof(struct WS_sockaddr_in6):
1455 case sizeof(struct WS_sockaddr_in6_old):
1456 uaddrlen = sizeof(struct sockaddr_in6);
1457 break;
1459 memset( uaddr, 0, uaddrlen );
1460 break;
1462 default:
1463 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
1464 return 0;
1466 return uaddrlen;
1469 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
1471 switch (uaddr->sa_family)
1473 #ifdef HAS_IPX
1474 case AF_IPX:
1476 static const struct sockaddr_ipx emptyAddr;
1477 struct sockaddr_ipx *ipx = (struct sockaddr_ipx*) uaddr;
1478 return ipx->sipx_port
1479 || memcmp(&ipx->sipx_network, &emptyAddr.sipx_network, sizeof(emptyAddr.sipx_network))
1480 || memcmp(&ipx->sipx_node, &emptyAddr.sipx_node, sizeof(emptyAddr.sipx_node));
1482 #endif
1483 case AF_INET6:
1485 static const struct sockaddr_in6 emptyAddr;
1486 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
1487 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
1489 case AF_INET:
1491 static const struct sockaddr_in emptyAddr;
1492 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
1493 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
1495 case AF_UNSPEC:
1496 return FALSE;
1497 default:
1498 FIXME("unknown address family %d\n", uaddr->sa_family);
1499 return TRUE;
1503 /* Returns 0 if successful, -1 if the buffer is too small */
1504 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
1506 int res;
1508 switch(uaddr->sa_family)
1510 #ifdef HAS_IPX
1511 case AF_IPX:
1513 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
1514 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
1516 res=-1;
1517 switch (*wsaddrlen) /* how much can we copy? */
1519 default:
1520 res=0; /* enough */
1521 *wsaddrlen = sizeof(*wsipx);
1522 wsipx->sa_socket=uipx->sipx_port;
1523 /* fall through */
1524 case 13:
1525 case 12:
1526 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
1527 /* fall through */
1528 case 11:
1529 case 10:
1530 case 9:
1531 case 8:
1532 case 7:
1533 case 6:
1534 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1535 /* fall through */
1536 case 5:
1537 case 4:
1538 case 3:
1539 case 2:
1540 wsipx->sa_family=WS_AF_IPX;
1541 /* fall through */
1542 case 1:
1543 case 0:
1544 /* way too small */
1545 break;
1548 break;
1549 #endif
1550 #ifdef HAS_IRDA
1551 case AF_IRDA: {
1552 const struct sockaddr_irda *uin = (const struct sockaddr_irda *)uaddr;
1553 SOCKADDR_IRDA *win = (SOCKADDR_IRDA *)wsaddr;
1555 if (*wsaddrlen < sizeof(SOCKADDR_IRDA))
1556 return -1;
1557 win->irdaAddressFamily = WS_AF_IRDA;
1558 memcpy( win->irdaDeviceID, &uin->sir_addr, sizeof(win->irdaDeviceID) );
1559 if (uin->sir_lsap_sel != LSAP_ANY)
1560 sprintf( win->irdaServiceName, "LSAP-SEL%u", uin->sir_lsap_sel );
1561 else
1562 memcpy( win->irdaServiceName, uin->sir_name,
1563 sizeof(win->irdaServiceName) );
1564 return 0;
1566 #endif
1567 case AF_INET6: {
1568 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1569 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1571 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1572 return -1;
1573 win6old->sin6_family = WS_AF_INET6;
1574 win6old->sin6_port = uin6->sin6_port;
1575 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1576 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1577 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1578 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1579 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1580 win6->sin6_scope_id = uin6->sin6_scope_id;
1581 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1583 else
1584 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1585 #else
1586 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1587 #endif
1588 return 0;
1590 case AF_INET: {
1591 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1592 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1594 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1595 return -1;
1596 win->sin_family = WS_AF_INET;
1597 win->sin_port = uin->sin_port;
1598 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1599 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1600 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1601 return 0;
1603 case AF_UNSPEC: {
1604 memset(wsaddr,0,*wsaddrlen);
1605 return 0;
1607 default:
1608 FIXME("Unknown address family %d\n", uaddr->sa_family);
1609 return -1;
1611 return res;
1614 static INT WS_DuplicateSocket(BOOL unicode, SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo)
1616 HANDLE hProcess;
1617 int size;
1618 WSAPROTOCOL_INFOW infow;
1620 TRACE("(unicode %d, socket %04lx, processid %x, buffer %p)\n",
1621 unicode, s, dwProcessId, lpProtocolInfo);
1623 if (!ws_protocol_info(s, unicode, &infow, &size))
1624 return SOCKET_ERROR;
1626 if (!(hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId)))
1628 SetLastError(WSAEINVAL);
1629 return SOCKET_ERROR;
1632 if (!lpProtocolInfo)
1634 CloseHandle(hProcess);
1635 SetLastError(WSAEFAULT);
1636 return SOCKET_ERROR;
1639 /* I don't know what the real Windoze does next, this is a hack */
1640 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
1641 * the target use the global duplicate, or we could copy a reference to us to the structure
1642 * and let the target duplicate it from us, but let's do it as simple as possible */
1643 memcpy(lpProtocolInfo, &infow, size);
1644 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
1645 hProcess, (LPHANDLE)&lpProtocolInfo->dwServiceFlags3,
1646 0, FALSE, DUPLICATE_SAME_ACCESS);
1647 CloseHandle(hProcess);
1648 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
1649 return 0;
1652 /*****************************************************************************
1653 * WS_EnterSingleProtocolW [internal]
1655 * enters the protocol information of one given protocol into the given
1656 * buffer.
1658 * RETURNS
1659 * TRUE if a protocol was entered into the buffer.
1661 * BUGS
1662 * - only implemented for IPX, SPX, SPXII, TCP, UDP
1663 * - there is no check that the operating system supports the returned
1664 * protocols
1666 static BOOL WS_EnterSingleProtocolW( INT protocol, WSAPROTOCOL_INFOW* info )
1668 memset( info, 0, sizeof(WSAPROTOCOL_INFOW) );
1669 info->iProtocol = protocol;
1671 switch (protocol)
1673 case WS_IPPROTO_TCP:
1674 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_EXPEDITED_DATA |
1675 XP1_GRACEFUL_CLOSE | XP1_GUARANTEED_ORDER |
1676 XP1_GUARANTEED_DELIVERY;
1677 info->ProviderId = ProviderIdIP;
1678 info->dwCatalogEntryId = 0x3e9;
1679 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1680 info->ProtocolChain.ChainLen = 1;
1681 info->iVersion = 2;
1682 info->iAddressFamily = WS_AF_INET;
1683 info->iMaxSockAddr = 0x10;
1684 info->iMinSockAddr = 0x10;
1685 info->iSocketType = WS_SOCK_STREAM;
1686 strcpyW( info->szProtocol, NameTcpW );
1687 break;
1689 case WS_IPPROTO_UDP:
1690 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_SUPPORT_BROADCAST |
1691 XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED |
1692 XP1_CONNECTIONLESS;
1693 info->ProviderId = ProviderIdIP;
1694 info->dwCatalogEntryId = 0x3ea;
1695 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1696 info->ProtocolChain.ChainLen = 1;
1697 info->iVersion = 2;
1698 info->iAddressFamily = WS_AF_INET;
1699 info->iMaxSockAddr = 0x10;
1700 info->iMinSockAddr = 0x10;
1701 info->iSocketType = WS_SOCK_DGRAM;
1702 info->dwMessageSize = 0xffbb;
1703 strcpyW( info->szProtocol, NameUdpW );
1704 break;
1706 case WS_NSPROTO_IPX:
1707 info->dwServiceFlags1 = XP1_PARTIAL_MESSAGE | XP1_SUPPORT_BROADCAST |
1708 XP1_SUPPORT_MULTIPOINT | XP1_MESSAGE_ORIENTED |
1709 XP1_CONNECTIONLESS;
1710 info->ProviderId = ProviderIdIPX;
1711 info->dwCatalogEntryId = 0x406;
1712 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1713 info->ProtocolChain.ChainLen = 1;
1714 info->iVersion = 2;
1715 info->iAddressFamily = WS_AF_IPX;
1716 info->iMaxSockAddr = 0x10;
1717 info->iMinSockAddr = 0x0e;
1718 info->iSocketType = WS_SOCK_DGRAM;
1719 info->iProtocolMaxOffset = 0xff;
1720 info->dwMessageSize = 0x240;
1721 strcpyW( info->szProtocol, NameIpxW );
1722 break;
1724 case WS_NSPROTO_SPX:
1725 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_PSEUDO_STREAM |
1726 XP1_MESSAGE_ORIENTED | XP1_GUARANTEED_ORDER |
1727 XP1_GUARANTEED_DELIVERY;
1728 info->ProviderId = ProviderIdSPX;
1729 info->dwCatalogEntryId = 0x407;
1730 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1731 info->ProtocolChain.ChainLen = 1;
1732 info->iVersion = 2;
1733 info->iAddressFamily = WS_AF_IPX;
1734 info->iMaxSockAddr = 0x10;
1735 info->iMinSockAddr = 0x0e;
1736 info->iSocketType = WS_SOCK_SEQPACKET;
1737 info->dwMessageSize = 0xffffffff;
1738 strcpyW( info->szProtocol, NameSpxW );
1739 break;
1741 case WS_NSPROTO_SPXII:
1742 info->dwServiceFlags1 = XP1_IFS_HANDLES | XP1_GRACEFUL_CLOSE |
1743 XP1_PSEUDO_STREAM | XP1_MESSAGE_ORIENTED |
1744 XP1_GUARANTEED_ORDER | XP1_GUARANTEED_DELIVERY;
1745 info->ProviderId = ProviderIdSPX;
1746 info->dwCatalogEntryId = 0x409;
1747 info->dwProviderFlags = PFL_MATCHES_PROTOCOL_ZERO;
1748 info->ProtocolChain.ChainLen = 1;
1749 info->iVersion = 2;
1750 info->iAddressFamily = WS_AF_IPX;
1751 info->iMaxSockAddr = 0x10;
1752 info->iMinSockAddr = 0x0e;
1753 info->iSocketType = WS_SOCK_SEQPACKET;
1754 info->dwMessageSize = 0xffffffff;
1755 strcpyW( info->szProtocol, NameSpxIIW );
1756 break;
1758 default:
1759 FIXME("unknown Protocol <0x%08x>\n", protocol);
1760 return FALSE;
1762 return TRUE;
1765 /*****************************************************************************
1766 * WS_EnterSingleProtocolA [internal]
1768 * see function WS_EnterSingleProtocolW
1771 static BOOL WS_EnterSingleProtocolA( INT protocol, WSAPROTOCOL_INFOA* info )
1773 WSAPROTOCOL_INFOW infow;
1774 INT ret;
1775 memset( info, 0, sizeof(WSAPROTOCOL_INFOA) );
1777 ret = WS_EnterSingleProtocolW( protocol, &infow );
1778 if (ret)
1780 /* convert the structure from W to A */
1781 memcpy( info, &infow, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
1782 WideCharToMultiByte( CP_ACP, 0, infow.szProtocol, -1,
1783 info->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL );
1786 return ret;
1789 static INT WS_EnumProtocols( BOOL unicode, const INT *protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
1791 INT i = 0, items = 0;
1792 DWORD size = 0;
1793 union _info
1795 LPWSAPROTOCOL_INFOA a;
1796 LPWSAPROTOCOL_INFOW w;
1797 } info;
1798 info.w = buffer;
1800 if (!protocols) protocols = valid_protocols;
1802 while (protocols[i])
1804 if(supported_protocol(protocols[i++]))
1805 items++;
1808 size = items * (unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA));
1810 TRACE("unicode %d, protocols %p, buffer %p, length %p %d, items %d, required %d\n",
1811 unicode, protocols, buffer, len, len ? *len : 0, items, size);
1813 if (*len < size || !buffer)
1815 *len = size;
1816 WSASetLastError(WSAENOBUFS);
1817 return SOCKET_ERROR;
1820 for (i = items = 0; protocols[i]; i++)
1822 if (unicode)
1824 if (WS_EnterSingleProtocolW( protocols[i], &info.w[items] ))
1825 items++;
1827 else
1829 if (WS_EnterSingleProtocolA( protocols[i], &info.a[items] ))
1830 items++;
1833 return items;
1836 static BOOL ws_protocol_info(SOCKET s, int unicode, WSAPROTOCOL_INFOW *buffer, int *size)
1838 NTSTATUS status;
1840 *size = unicode ? sizeof(WSAPROTOCOL_INFOW) : sizeof(WSAPROTOCOL_INFOA);
1841 memset(buffer, 0, *size);
1843 SERVER_START_REQ( get_socket_info )
1845 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1846 status = wine_server_call( req );
1847 if (!status)
1849 buffer->iAddressFamily = convert_af_u2w(reply->family);
1850 buffer->iSocketType = convert_socktype_u2w(reply->type);
1851 buffer->iProtocol = convert_proto_u2w(reply->protocol);
1854 SERVER_END_REQ;
1856 if (status)
1858 unsigned int err = NtStatusToWSAError( status );
1859 SetLastError( err == WSAEBADF ? WSAENOTSOCK : err );
1860 return FALSE;
1863 if (unicode)
1864 WS_EnterSingleProtocolW( buffer->iProtocol, buffer);
1865 else
1866 WS_EnterSingleProtocolA( buffer->iProtocol, (WSAPROTOCOL_INFOA *)buffer);
1868 return TRUE;
1871 /**************************************************************************
1872 * Functions for handling overlapped I/O
1873 **************************************************************************/
1875 /* user APC called upon async completion */
1876 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1878 ws2_async *wsa = arg;
1880 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
1881 iosb->Information, wsa->user_overlapped,
1882 wsa->flags );
1883 HeapFree( GetProcessHeap(), 0, wsa );
1886 /***********************************************************************
1887 * WS2_recv (INTERNAL)
1889 * Workhorse for both synchronous and asynchronous recv() operations.
1891 static int WS2_recv( int fd, struct ws2_async *wsa )
1893 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1894 char pktbuf[512];
1895 #endif
1896 struct msghdr hdr;
1897 union generic_unix_sockaddr unix_sockaddr;
1898 int n;
1900 hdr.msg_name = NULL;
1902 if (wsa->addr)
1904 hdr.msg_namelen = sizeof(unix_sockaddr);
1905 hdr.msg_name = &unix_sockaddr;
1907 else
1908 hdr.msg_namelen = 0;
1910 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1911 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1912 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1913 hdr.msg_accrights = NULL;
1914 hdr.msg_accrightslen = 0;
1915 #else
1916 hdr.msg_control = pktbuf;
1917 hdr.msg_controllen = sizeof(pktbuf);
1918 hdr.msg_flags = 0;
1919 #endif
1921 if ( (n = recvmsg(fd, &hdr, wsa->flags)) == -1 )
1922 return -1;
1924 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1925 if (wsa->control)
1927 ERR("Message control headers cannot be properly supported on this system.\n");
1928 wsa->control->len = 0;
1930 #else
1931 if (wsa->control && !convert_control_headers(&hdr, wsa->control))
1933 WARN("Application passed insufficient room for control headers.\n");
1934 *wsa->lpFlags |= WS_MSG_CTRUNC;
1935 errno = EMSGSIZE;
1936 return -1;
1938 #endif
1940 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
1941 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
1943 * quoting linux 2.6 net/ipv4/tcp.c:
1944 * "According to UNIX98, msg_name/msg_namelen are ignored
1945 * on connected socket. I was just happy when found this 8) --ANK"
1947 * likewise MSDN says that lpFrom and lpFromlen are ignored for
1948 * connection-oriented sockets, so don't try to update lpFrom.
1950 if (wsa->addr && hdr.msg_namelen)
1951 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
1953 return n;
1956 /***********************************************************************
1957 * WS2_async_recv (INTERNAL)
1959 * Handler for overlapped recv() operations.
1961 static NTSTATUS WS2_async_recv( void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1963 ws2_async* wsa = user;
1964 int result = 0, fd;
1966 switch (status)
1968 case STATUS_ALERTED:
1969 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
1970 break;
1972 result = WS2_recv( fd, wsa );
1973 wine_server_release_fd( wsa->hSocket, fd );
1974 if (result >= 0)
1976 status = STATUS_SUCCESS;
1977 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1979 else
1981 if (errno == EINTR || errno == EAGAIN)
1983 status = STATUS_PENDING;
1984 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1986 else
1988 result = 0;
1989 status = wsaErrStatus();
1992 break;
1994 if (status != STATUS_PENDING)
1996 iosb->u.Status = status;
1997 iosb->Information = result;
1998 *apc = ws2_async_apc;
2000 return status;
2003 /* user APC called upon async accept completion */
2004 static void WINAPI ws2_async_accept_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
2006 struct ws2_accept_async *wsa = arg;
2008 HeapFree( GetProcessHeap(), 0, wsa->read );
2009 HeapFree( GetProcessHeap(), 0, wsa );
2012 /***********************************************************************
2013 * WS2_async_accept_recv (INTERNAL)
2015 * This function is used to finish the read part of an accept request. It is
2016 * needed to place the completion on the correct socket (listener).
2018 static NTSTATUS WS2_async_accept_recv( void *arg, IO_STATUS_BLOCK *iosb, NTSTATUS status, void **apc )
2020 void *junk;
2021 struct ws2_accept_async *wsa = arg;
2023 status = WS2_async_recv( wsa->read, iosb, status, &junk );
2024 if (status == STATUS_PENDING)
2025 return status;
2027 if (wsa->user_overlapped->hEvent)
2028 SetEvent(wsa->user_overlapped->hEvent);
2029 if (wsa->cvalue)
2030 WS_AddCompletion( HANDLE2SOCKET(wsa->listen_socket), wsa->cvalue, iosb->u.Status, iosb->Information );
2032 *apc = ws2_async_accept_apc;
2033 return status;
2036 /***********************************************************************
2037 * WS2_async_accept (INTERNAL)
2039 * This is the function called to satisfy the AcceptEx callback
2041 static NTSTATUS WS2_async_accept( void *arg, IO_STATUS_BLOCK *iosb, NTSTATUS status, void **apc )
2043 struct ws2_accept_async *wsa = arg;
2044 int len;
2045 char *addr;
2047 TRACE("status: 0x%x listen: %p, accept: %p\n", status, wsa->listen_socket, wsa->accept_socket);
2049 if (status == STATUS_ALERTED)
2051 SERVER_START_REQ( accept_into_socket )
2053 req->lhandle = wine_server_obj_handle( wsa->listen_socket );
2054 req->ahandle = wine_server_obj_handle( wsa->accept_socket );
2055 status = wine_server_call( req );
2057 SERVER_END_REQ;
2059 if (status == STATUS_CANT_WAIT)
2060 return STATUS_PENDING;
2062 if (status == STATUS_INVALID_HANDLE)
2064 FIXME("AcceptEx accepting socket closed but request was not cancelled\n");
2065 status = STATUS_CANCELLED;
2068 else if (status == STATUS_HANDLES_CLOSED)
2069 status = STATUS_CANCELLED; /* strange windows behavior */
2071 if (status != STATUS_SUCCESS)
2072 goto finish;
2074 /* WS2 Spec says size param is extra 16 bytes long...what do we put in it? */
2075 addr = ((char *)wsa->buf) + wsa->data_len;
2076 len = wsa->local_len - sizeof(int);
2077 WS_getsockname(HANDLE2SOCKET(wsa->accept_socket),
2078 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
2079 *(int *)addr = len;
2081 addr += wsa->local_len;
2082 len = wsa->remote_len - sizeof(int);
2083 WS_getpeername(HANDLE2SOCKET(wsa->accept_socket),
2084 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
2085 *(int *)addr = len;
2087 if (!wsa->read)
2088 goto finish;
2090 SERVER_START_REQ( register_async )
2092 req->type = ASYNC_TYPE_READ;
2093 req->async.handle = wine_server_obj_handle( wsa->accept_socket );
2094 req->async.callback = wine_server_client_ptr( WS2_async_accept_recv );
2095 req->async.iosb = wine_server_client_ptr( iosb );
2096 req->async.arg = wine_server_client_ptr( wsa );
2097 status = wine_server_call( req );
2099 SERVER_END_REQ;
2101 if (status != STATUS_PENDING)
2102 goto finish;
2104 /* The APC has finished but no completion should be sent for the operation yet, additional processing
2105 * needs to be performed by WS2_async_accept_recv() first. */
2106 return STATUS_MORE_PROCESSING_REQUIRED;
2108 finish:
2109 iosb->u.Status = status;
2110 iosb->Information = 0;
2112 if (wsa->user_overlapped->hEvent)
2113 SetEvent(wsa->user_overlapped->hEvent);
2115 *apc = ws2_async_accept_apc;
2116 return status;
2119 /***********************************************************************
2120 * WS2_send (INTERNAL)
2122 * Workhorse for both synchronous and asynchronous send() operations.
2124 static int WS2_send( int fd, struct ws2_async *wsa )
2126 struct msghdr hdr;
2127 union generic_unix_sockaddr unix_addr;
2128 int n, ret;
2130 hdr.msg_name = NULL;
2131 hdr.msg_namelen = 0;
2133 if (wsa->addr)
2135 hdr.msg_name = &unix_addr;
2136 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
2137 if ( !hdr.msg_namelen )
2139 errno = EFAULT;
2140 return -1;
2143 #if defined(HAS_IPX) && defined(SOL_IPX)
2144 if(wsa->addr->sa_family == WS_AF_IPX)
2146 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
2147 int val=0;
2148 socklen_t len = sizeof(int);
2150 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
2151 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
2152 * the packet type and then we can retrieve it using getsockopt. After that we can set the
2153 * ipx type in the sockaddr_opx structure with the stored value.
2155 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
2156 uipx->sipx_type = val;
2158 #endif
2161 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
2162 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
2163 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
2164 hdr.msg_accrights = NULL;
2165 hdr.msg_accrightslen = 0;
2166 #else
2167 hdr.msg_control = NULL;
2168 hdr.msg_controllen = 0;
2169 hdr.msg_flags = 0;
2170 #endif
2172 ret = sendmsg(fd, &hdr, wsa->flags);
2173 if (ret >= 0)
2175 n = ret;
2176 while (wsa->first_iovec < wsa->n_iovecs && wsa->iovec[wsa->first_iovec].iov_len <= n)
2177 n -= wsa->iovec[wsa->first_iovec++].iov_len;
2178 if (wsa->first_iovec < wsa->n_iovecs)
2180 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
2181 wsa->iovec[wsa->first_iovec].iov_len -= n;
2184 return ret;
2187 /***********************************************************************
2188 * WS2_async_send (INTERNAL)
2190 * Handler for overlapped send() operations.
2192 static NTSTATUS WS2_async_send(void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
2194 ws2_async* wsa = user;
2195 int result = 0, fd;
2197 switch (status)
2199 case STATUS_ALERTED:
2200 if ( wsa->n_iovecs <= wsa->first_iovec )
2202 /* Nothing to do */
2203 status = STATUS_SUCCESS;
2204 break;
2206 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
2207 break;
2209 /* check to see if the data is ready (non-blocking) */
2210 result = WS2_send( fd, wsa );
2211 wine_server_release_fd( wsa->hSocket, fd );
2213 if (result >= 0)
2215 if (wsa->first_iovec < wsa->n_iovecs)
2216 status = STATUS_PENDING;
2217 else
2218 status = STATUS_SUCCESS;
2220 iosb->Information += result;
2222 else if (errno == EINTR || errno == EAGAIN)
2224 status = STATUS_PENDING;
2226 else
2228 status = wsaErrStatus();
2230 break;
2232 if (status != STATUS_PENDING)
2234 iosb->u.Status = status;
2235 *apc = ws2_async_apc;
2237 return status;
2240 /***********************************************************************
2241 * WS2_async_shutdown (INTERNAL)
2243 * Handler for shutdown() operations on overlapped sockets.
2245 static NTSTATUS WS2_async_shutdown( void* user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc )
2247 ws2_async* wsa = user;
2248 int fd, err = 1;
2250 switch (status)
2252 case STATUS_ALERTED:
2253 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
2254 break;
2256 switch ( wsa->type )
2258 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
2259 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
2261 status = err ? wsaErrStatus() : STATUS_SUCCESS;
2262 wine_server_release_fd( wsa->hSocket, fd );
2263 break;
2265 iosb->u.Status = status;
2266 iosb->Information = 0;
2267 *apc = ws2_async_apc;
2268 return status;
2271 /***********************************************************************
2272 * WS2_register_async_shutdown (INTERNAL)
2274 * Helper function for WS_shutdown() on overlapped sockets.
2276 static int WS2_register_async_shutdown( SOCKET s, int type )
2278 struct ws2_async *wsa;
2279 NTSTATUS status;
2281 TRACE("s %ld type %d\n", s, type);
2283 wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( struct ws2_async, iovec[1] ));
2284 if ( !wsa )
2285 return WSAEFAULT;
2287 wsa->hSocket = SOCKET2HANDLE(s);
2288 wsa->type = type;
2289 wsa->completion_func = NULL;
2291 SERVER_START_REQ( register_async )
2293 req->type = type;
2294 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2295 req->async.callback = wine_server_client_ptr( WS2_async_shutdown );
2296 req->async.iosb = wine_server_client_ptr( &wsa->local_iosb );
2297 req->async.arg = wine_server_client_ptr( wsa );
2298 req->async.cvalue = 0;
2299 status = wine_server_call( req );
2301 SERVER_END_REQ;
2303 if (status != STATUS_PENDING)
2305 HeapFree( GetProcessHeap(), 0, wsa );
2306 return NtStatusToWSAError( status );
2308 return 0;
2311 /***********************************************************************
2312 * accept (WS2_32.1)
2314 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr, int *addrlen32)
2316 NTSTATUS status;
2317 SOCKET as;
2318 BOOL is_blocking;
2320 TRACE("socket %04lx\n", s );
2321 status = _is_blocking(s, &is_blocking);
2322 if (status)
2324 set_error(status);
2325 return INVALID_SOCKET;
2328 do {
2329 /* try accepting first (if there is a deferred connection) */
2330 SERVER_START_REQ( accept_socket )
2332 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
2333 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
2334 req->attributes = OBJ_INHERIT;
2335 status = wine_server_call( req );
2336 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
2338 SERVER_END_REQ;
2339 if (!status)
2341 if (addr && WS_getpeername(as, addr, addrlen32))
2343 WS_closesocket(as);
2344 return SOCKET_ERROR;
2346 return as;
2348 if (is_blocking && status == STATUS_CANT_WAIT)
2350 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2351 /* block here */
2352 do_block(fd, POLLIN, -1);
2353 _sync_sock_state(s); /* let wineserver notice connection */
2354 release_sock_fd( s, fd );
2356 } while (is_blocking && status == STATUS_CANT_WAIT);
2358 set_error(status);
2359 return INVALID_SOCKET;
2362 /***********************************************************************
2363 * AcceptEx
2365 static BOOL WINAPI WS2_AcceptEx(SOCKET listener, SOCKET acceptor, PVOID dest, DWORD dest_len,
2366 DWORD local_addr_len, DWORD rem_addr_len, LPDWORD received,
2367 LPOVERLAPPED overlapped)
2369 DWORD status;
2370 struct ws2_accept_async *wsa;
2371 int fd;
2372 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
2374 TRACE("(%lx, %lx, %p, %d, %d, %d, %p, %p)\n", listener, acceptor, dest, dest_len, local_addr_len,
2375 rem_addr_len, received, overlapped);
2377 if (!dest)
2379 SetLastError(WSAEINVAL);
2380 return FALSE;
2383 if (!overlapped)
2385 SetLastError(WSA_INVALID_PARAMETER);
2386 return FALSE;
2389 if ((local_addr_len < sizeof(struct sockaddr_in) + 16)
2390 || (rem_addr_len < sizeof(struct sockaddr_in) + 16))
2392 SetLastError(WSAEINVAL);
2393 return FALSE;
2396 fd = get_sock_fd( listener, FILE_READ_DATA, NULL );
2397 if (fd == -1)
2399 SetLastError(WSAENOTSOCK);
2400 return FALSE;
2402 release_sock_fd( listener, fd );
2404 fd = get_sock_fd( acceptor, FILE_READ_DATA, NULL );
2405 if (fd == -1)
2407 SetLastError(WSAEINVAL);
2408 return FALSE;
2410 release_sock_fd( acceptor, fd );
2412 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
2413 if(!wsa)
2415 SetLastError(WSAEFAULT);
2416 return FALSE;
2419 wsa->listen_socket = SOCKET2HANDLE(listener);
2420 wsa->accept_socket = SOCKET2HANDLE(acceptor);
2421 wsa->user_overlapped = overlapped;
2422 wsa->cvalue = cvalue;
2423 wsa->buf = dest;
2424 wsa->data_len = dest_len;
2425 wsa->local_len = local_addr_len;
2426 wsa->remote_len = rem_addr_len;
2427 wsa->read = NULL;
2429 if (wsa->data_len)
2431 /* set up a read request if we need it */
2432 wsa->read = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[1]) );
2433 if (!wsa->read)
2435 HeapFree( GetProcessHeap(), 0, wsa );
2436 SetLastError(WSAEFAULT);
2437 return FALSE;
2440 wsa->read->hSocket = wsa->accept_socket;
2441 wsa->read->flags = 0;
2442 wsa->read->lpFlags = &wsa->read->flags;
2443 wsa->read->addr = NULL;
2444 wsa->read->addrlen.ptr = NULL;
2445 wsa->read->control = NULL;
2446 wsa->read->n_iovecs = 1;
2447 wsa->read->first_iovec = 0;
2448 wsa->read->iovec[0].iov_base = wsa->buf;
2449 wsa->read->iovec[0].iov_len = wsa->data_len;
2452 SERVER_START_REQ( register_async )
2454 req->type = ASYNC_TYPE_READ;
2455 req->async.handle = wine_server_obj_handle( SOCKET2HANDLE(listener) );
2456 req->async.callback = wine_server_client_ptr( WS2_async_accept );
2457 req->async.iosb = wine_server_client_ptr( overlapped );
2458 req->async.arg = wine_server_client_ptr( wsa );
2459 req->async.cvalue = cvalue;
2460 /* We don't set event since we may also have to read */
2461 status = wine_server_call( req );
2463 SERVER_END_REQ;
2465 if(status != STATUS_PENDING)
2467 HeapFree( GetProcessHeap(), 0, wsa->read );
2468 HeapFree( GetProcessHeap(), 0, wsa );
2471 SetLastError( NtStatusToWSAError(status) );
2472 return FALSE;
2475 /***********************************************************************
2476 * GetAcceptExSockaddrs
2478 static void WINAPI WS2_GetAcceptExSockaddrs(PVOID buffer, DWORD data_size, DWORD local_size, DWORD remote_size,
2479 struct WS_sockaddr **local_addr, LPINT local_addr_len,
2480 struct WS_sockaddr **remote_addr, LPINT remote_addr_len)
2482 char *cbuf = buffer;
2483 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer, data_size, local_size, remote_size, local_addr,
2484 local_addr_len, remote_addr, remote_addr_len );
2485 cbuf += data_size;
2487 *local_addr_len = *(int *) cbuf;
2488 *local_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2490 cbuf += local_size;
2492 *remote_addr_len = *(int *) cbuf;
2493 *remote_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2496 /***********************************************************************
2497 * WSASendMsg
2499 int WINAPI WSASendMsg( SOCKET s, LPWSAMSG msg, DWORD dwFlags, LPDWORD lpNumberOfBytesSent,
2500 LPWSAOVERLAPPED lpOverlapped,
2501 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
2503 if (!msg)
2505 SetLastError( WSAEFAULT );
2506 return SOCKET_ERROR;
2509 return WS2_sendto( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesSent,
2510 dwFlags, msg->name, msg->namelen,
2511 lpOverlapped, lpCompletionRoutine );
2514 /***********************************************************************
2515 * WSARecvMsg
2517 * Perform a receive operation that is capable of returning message
2518 * control headers. It is important to note that the WSAMSG parameter
2519 * must remain valid throughout the operation, even when an overlapped
2520 * receive is performed.
2522 static int WINAPI WS2_WSARecvMsg( SOCKET s, LPWSAMSG msg, LPDWORD lpNumberOfBytesRecvd,
2523 LPWSAOVERLAPPED lpOverlapped,
2524 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2526 if (!msg)
2528 SetLastError( WSAEFAULT );
2529 return SOCKET_ERROR;
2532 return WS2_recv_base( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesRecvd,
2533 &msg->dwFlags, msg->name, &msg->namelen,
2534 lpOverlapped, lpCompletionRoutine, &msg->Control );
2537 /***********************************************************************
2538 * interface_bind (INTERNAL)
2540 * Take bind() calls on any name corresponding to a local network adapter and restrict the given socket to
2541 * operating only on the specified interface. This restriction consists of two components:
2542 * 1) An outgoing packet restriction suggesting the egress interface for all packets.
2543 * 2) An incoming packet restriction dropping packets not meant for the interface.
2544 * If the function succeeds in placing these restrictions (returns TRUE) then the name for the bind() may
2545 * safely be changed to INADDR_ANY, permitting the transmission and receipt of broadcast packets on the
2546 * socket. This behavior is only relevant to UDP sockets and is needed for applications that expect to be able
2547 * to receive broadcast packets on a socket that is bound to a specific network interface.
2549 static BOOL interface_bind( SOCKET s, int fd, struct sockaddr *addr )
2551 struct sockaddr_in *in_sock = (struct sockaddr_in *) addr;
2552 unsigned int sock_type = 0;
2553 socklen_t optlen = sizeof(sock_type);
2554 in_addr_t bind_addr = in_sock->sin_addr.s_addr;
2555 PIP_ADAPTER_INFO adapters = NULL, adapter;
2556 BOOL ret = FALSE;
2557 DWORD adap_size;
2558 int enable = 1;
2560 if (bind_addr == htonl(WS_INADDR_ANY) || bind_addr == htonl(WS_INADDR_LOOPBACK))
2561 return FALSE; /* Not binding to a network adapter, special interface binding unnecessary. */
2562 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &sock_type, &optlen) == -1 || sock_type != SOCK_DGRAM)
2563 return FALSE; /* Special interface binding is only necessary for UDP datagrams. */
2564 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
2565 goto cleanup;
2566 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
2567 if (adapters == NULL || GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
2568 goto cleanup;
2569 /* Search the IPv4 adapter list for the appropriate binding interface */
2570 for (adapter = adapters; adapter != NULL; adapter = adapter->Next)
2572 in_addr_t adapter_addr = (in_addr_t) inet_addr(adapter->IpAddressList.IpAddress.String);
2574 if (bind_addr == adapter_addr)
2576 #if defined(IP_BOUND_IF)
2577 /* IP_BOUND_IF sets both the incoming and outgoing restriction at once */
2578 if (setsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &adapter->Index, sizeof(adapter->Index)) != 0)
2579 goto cleanup;
2580 ret = TRUE;
2581 #elif defined(LINUX_BOUND_IF)
2582 in_addr_t ifindex = (in_addr_t) htonl(adapter->Index);
2583 struct interface_filter specific_interface_filter;
2584 struct sock_fprog filter_prog;
2586 if (setsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex, sizeof(ifindex)) != 0)
2587 goto cleanup; /* Failed to suggest egress interface */
2588 specific_interface_filter = generic_interface_filter;
2589 specific_interface_filter.iface_rule.k = adapter->Index;
2590 specific_interface_filter.ip_rule.k = htonl(adapter_addr);
2591 filter_prog.len = sizeof(generic_interface_filter)/sizeof(struct sock_filter);
2592 filter_prog.filter = (struct sock_filter *) &specific_interface_filter;
2593 if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog, sizeof(filter_prog)) != 0)
2594 goto cleanup; /* Failed to specify incoming packet filter */
2595 ret = TRUE;
2596 #else
2597 FIXME("Broadcast packets on interface-bound sockets are not currently supported on this platform, "
2598 "receiving broadcast packets will not work on socket %04lx.\n", s);
2599 #endif
2600 break;
2603 /* Will soon be switching to INADDR_ANY: permit address reuse */
2604 if (ret && setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) == 0)
2605 TRACE("Socket %04lx bound to interface index %d\n", s, adapter->Index);
2606 else
2607 ret = FALSE;
2609 cleanup:
2610 if(!ret)
2611 ERR("Failed to bind to interface, receiving broadcast packets will not work on socket %04lx.\n", s);
2612 HeapFree(GetProcessHeap(), 0, adapters);
2613 return ret;
2616 /***********************************************************************
2617 * bind (WS2_32.2)
2619 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
2621 int fd = get_sock_fd( s, 0, NULL );
2622 int res = SOCKET_ERROR;
2624 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2626 if (fd != -1)
2628 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
2630 SetLastError(WSAEAFNOSUPPORT);
2632 else
2634 union generic_unix_sockaddr uaddr;
2635 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2636 if (!uaddrlen)
2638 SetLastError(WSAEFAULT);
2640 else
2642 #ifdef IPV6_V6ONLY
2643 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
2644 if (name->sa_family == WS_AF_INET6 &&
2645 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
2647 int enable = 1;
2648 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
2650 release_sock_fd( s, fd );
2651 SetLastError(WSAEAFNOSUPPORT);
2652 return SOCKET_ERROR;
2655 #endif
2656 if (name->sa_family == WS_AF_INET)
2658 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2659 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2661 /* Trying to bind to the default host interface, using
2662 * INADDR_ANY instead*/
2663 WARN("Trying to bind to magic IP address, using "
2664 "INADDR_ANY instead.\n");
2665 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
2667 else if (interface_bind(s, fd, &uaddr.addr))
2668 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
2670 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
2672 int loc_errno = errno;
2673 WARN("\tfailure - errno = %i\n", errno);
2674 errno = loc_errno;
2675 switch (errno)
2677 case EBADF:
2678 SetLastError(WSAENOTSOCK);
2679 break;
2680 case EADDRNOTAVAIL:
2681 SetLastError(WSAEINVAL);
2682 break;
2683 default:
2684 SetLastError(wsaErrno());
2685 break;
2688 else
2690 res=0; /* success */
2694 release_sock_fd( s, fd );
2696 return res;
2699 /***********************************************************************
2700 * closesocket (WS2_32.3)
2702 int WINAPI WS_closesocket(SOCKET s)
2704 TRACE("socket %04lx\n", s);
2705 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
2706 return SOCKET_ERROR;
2709 static int do_connect(int fd, const struct WS_sockaddr* name, int namelen)
2711 union generic_unix_sockaddr uaddr;
2712 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2714 if (!uaddrlen)
2715 return WSAEFAULT;
2717 if (name->sa_family == WS_AF_INET)
2719 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2720 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2722 /* Trying to connect to magic replace-loopback address,
2723 * assuming we really want to connect to localhost */
2724 TRACE("Trying to connect to magic IP address, using "
2725 "INADDR_LOOPBACK instead.\n");
2726 in4->sin_addr.s_addr = htonl(WS_INADDR_LOOPBACK);
2730 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
2731 return 0;
2733 return wsaErrno();
2736 /***********************************************************************
2737 * connect (WS2_32.4)
2739 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
2741 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2743 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2745 if (fd != -1)
2747 NTSTATUS status;
2748 BOOL is_blocking;
2749 int ret = do_connect(fd, name, namelen);
2750 if (ret == 0)
2751 goto connect_success;
2753 if (ret == WSAEINPROGRESS)
2755 /* tell wineserver that a connection is in progress */
2756 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2757 FD_CONNECT,
2758 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2759 status = _is_blocking( s, &is_blocking );
2760 if (status)
2762 release_sock_fd( s, fd );
2763 set_error( status );
2764 return SOCKET_ERROR;
2766 if (is_blocking)
2768 int result;
2769 /* block here */
2770 do_block(fd, POLLIN | POLLOUT, -1);
2771 _sync_sock_state(s); /* let wineserver notice connection */
2772 /* retrieve any error codes from it */
2773 result = _get_sock_error(s, FD_CONNECT_BIT);
2774 if (result)
2775 SetLastError(NtStatusToWSAError(result));
2776 else
2778 goto connect_success;
2781 else
2783 SetLastError(WSAEWOULDBLOCK);
2786 else
2788 SetLastError(ret);
2790 release_sock_fd( s, fd );
2792 return SOCKET_ERROR;
2794 connect_success:
2795 release_sock_fd( s, fd );
2796 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2797 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2798 FD_CONNECT|FD_WINE_LISTENING);
2799 return 0;
2802 /***********************************************************************
2803 * WSAConnect (WS2_32.30)
2805 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
2806 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
2807 LPQOS lpSQOS, LPQOS lpGQOS )
2809 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
2810 FIXME("unsupported parameters!\n");
2811 return WS_connect( s, name, namelen );
2814 /***********************************************************************
2815 * ConnectEx
2817 static BOOL WINAPI WS2_ConnectEx(SOCKET s, const struct WS_sockaddr* name, int namelen,
2818 PVOID sendBuf, DWORD sendBufLen, LPDWORD sent, LPOVERLAPPED ov)
2820 int fd, ret, status;
2821 union generic_unix_sockaddr uaddr;
2822 socklen_t uaddrlen = sizeof(uaddr);
2824 if (!ov)
2826 SetLastError( ERROR_INVALID_PARAMETER );
2827 return FALSE;
2830 fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2831 if (fd == -1)
2833 SetLastError( WSAENOTSOCK );
2834 return FALSE;
2837 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
2838 s, name, debugstr_sockaddr(name), namelen, sendBuf, sendBufLen, ov);
2840 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
2842 SetLastError(wsaErrno());
2843 return FALSE;
2845 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
2847 SetLastError(WSAEINVAL);
2848 return FALSE;
2851 ret = do_connect(fd, name, namelen);
2852 if (ret == 0)
2854 WSABUF wsabuf;
2856 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2857 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2858 FD_CONNECT|FD_WINE_LISTENING);
2860 wsabuf.len = sendBufLen;
2861 wsabuf.buf = (char*) sendBuf;
2863 /* WSASend takes care of completion if need be */
2864 if (WSASend(s, &wsabuf, sendBuf ? 1 : 0, sent, 0, ov, NULL) != SOCKET_ERROR)
2865 goto connection_success;
2867 else if (ret == WSAEINPROGRESS)
2869 struct ws2_async *wsa;
2870 ULONG_PTR cvalue = (((ULONG_PTR)ov->hEvent & 1) == 0) ? (ULONG_PTR)ov : 0;
2872 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2873 FD_CONNECT,
2874 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2876 /* Indirectly call WSASend */
2877 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( struct ws2_async, iovec[1] ))))
2879 SetLastError(WSAEFAULT);
2881 else
2883 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)ov;
2884 iosb->u.Status = STATUS_PENDING;
2885 iosb->Information = 0;
2887 wsa->hSocket = SOCKET2HANDLE(s);
2888 wsa->addr = NULL;
2889 wsa->addrlen.val = 0;
2890 wsa->flags = 0;
2891 wsa->lpFlags = &wsa->flags;
2892 wsa->control = NULL;
2893 wsa->n_iovecs = sendBuf ? 1 : 0;
2894 wsa->first_iovec = 0;
2895 wsa->completion_func = NULL;
2896 wsa->iovec[0].iov_base = sendBuf;
2897 wsa->iovec[0].iov_len = sendBufLen;
2899 SERVER_START_REQ( register_async )
2901 req->type = ASYNC_TYPE_WRITE;
2902 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2903 req->async.callback = wine_server_client_ptr( WS2_async_send );
2904 req->async.iosb = wine_server_client_ptr( iosb );
2905 req->async.arg = wine_server_client_ptr( wsa );
2906 req->async.event = wine_server_obj_handle( ov->hEvent );
2907 req->async.cvalue = cvalue;
2908 status = wine_server_call( req );
2910 SERVER_END_REQ;
2912 if (status != STATUS_PENDING) HeapFree(GetProcessHeap(), 0, wsa);
2914 /* If the connect already failed */
2915 if (status == STATUS_PIPE_DISCONNECTED)
2916 status = _get_sock_error(s, FD_CONNECT_BIT);
2917 SetLastError( NtStatusToWSAError(status) );
2920 else
2922 SetLastError(ret);
2925 release_sock_fd( s, fd );
2926 return FALSE;
2928 connection_success:
2929 release_sock_fd( s, fd );
2930 return TRUE;
2934 /***********************************************************************
2935 * getpeername (WS2_32.5)
2937 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
2939 int fd;
2940 int res;
2942 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
2944 fd = get_sock_fd( s, 0, NULL );
2945 res = SOCKET_ERROR;
2947 if (fd != -1)
2949 union generic_unix_sockaddr uaddr;
2950 socklen_t uaddrlen = sizeof(uaddr);
2952 if (getpeername(fd, &uaddr.addr, &uaddrlen) == 0)
2954 if (!name || !namelen)
2955 SetLastError(WSAEFAULT);
2956 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
2957 /* The buffer was too small */
2958 SetLastError(WSAEFAULT);
2959 else
2960 res = 0;
2962 else
2963 SetLastError(wsaErrno());
2964 release_sock_fd( s, fd );
2966 return res;
2969 /***********************************************************************
2970 * getsockname (WS2_32.6)
2972 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
2974 int fd;
2975 int res;
2977 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
2979 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
2980 if( (name == NULL) || (namelen == NULL) )
2982 SetLastError( WSAEFAULT );
2983 return SOCKET_ERROR;
2986 fd = get_sock_fd( s, 0, NULL );
2987 res = SOCKET_ERROR;
2989 if (fd != -1)
2991 union generic_unix_sockaddr uaddr;
2992 socklen_t uaddrlen = sizeof(uaddr);
2994 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
2996 SetLastError(wsaErrno());
2998 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
3000 SetLastError(WSAEINVAL);
3002 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
3004 /* The buffer was too small */
3005 SetLastError(WSAEFAULT);
3007 else
3009 res=0;
3010 TRACE("=> %s\n", debugstr_sockaddr(name));
3012 release_sock_fd( s, fd );
3014 return res;
3017 /***********************************************************************
3018 * getsockopt (WS2_32.7)
3020 INT WINAPI WS_getsockopt(SOCKET s, INT level,
3021 INT optname, char *optval, INT *optlen)
3023 int fd;
3024 INT ret = 0;
3026 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
3027 s, level, optname, optval, optlen ? *optlen : 0);
3029 switch(level)
3031 case WS_SOL_SOCKET:
3033 switch(optname)
3035 /* Handle common cases. The special cases are below, sorted
3036 * alphabetically */
3037 case WS_SO_BROADCAST:
3038 case WS_SO_DEBUG:
3039 case WS_SO_ERROR:
3040 case WS_SO_KEEPALIVE:
3041 case WS_SO_OOBINLINE:
3042 case WS_SO_RCVBUF:
3043 case WS_SO_REUSEADDR:
3044 case WS_SO_SNDBUF:
3045 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3046 return SOCKET_ERROR;
3047 convert_sockopt(&level, &optname);
3048 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3050 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3051 ret = SOCKET_ERROR;
3053 release_sock_fd( s, fd );
3054 return ret;
3055 case WS_SO_ACCEPTCONN:
3056 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3057 return SOCKET_ERROR;
3058 if (getsockopt(fd, SOL_SOCKET, SO_ACCEPTCONN, optval, (socklen_t *)optlen) != 0 )
3060 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3061 ret = SOCKET_ERROR;
3063 else
3065 /* BSD returns != 0 while Windows return exact == 1 */
3066 if (*(int *)optval) *(int *)optval = 1;
3068 release_sock_fd( s, fd );
3069 return ret;
3070 case WS_SO_DONTLINGER:
3072 struct linger lingval;
3073 socklen_t len = sizeof(struct linger);
3075 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
3077 SetLastError(WSAEFAULT);
3078 return SOCKET_ERROR;
3080 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3081 return SOCKET_ERROR;
3083 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
3085 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3086 ret = SOCKET_ERROR;
3088 else
3090 *(BOOL *)optval = !lingval.l_onoff;
3091 *optlen = sizeof(BOOL);
3094 release_sock_fd( s, fd );
3095 return ret;
3098 case WS_SO_CONNECT_TIME:
3100 static int pretendtime = 0;
3101 struct WS_sockaddr addr;
3102 int len = sizeof(addr);
3104 if (!optlen || *optlen < sizeof(DWORD) || !optval)
3106 SetLastError(WSAEFAULT);
3107 return SOCKET_ERROR;
3109 if (WS_getpeername(s, &addr, &len) == SOCKET_ERROR)
3110 *(DWORD *)optval = ~0u;
3111 else
3113 if (!pretendtime) FIXME("WS_SO_CONNECT_TIME - faking results\n");
3114 *(DWORD *)optval = pretendtime++;
3116 *optlen = sizeof(DWORD);
3117 return ret;
3119 /* As mentioned in setsockopt, Windows ignores this, so we
3120 * always return true here */
3121 case WS_SO_DONTROUTE:
3122 if (!optlen || *optlen < sizeof(BOOL) || !optval)
3124 SetLastError(WSAEFAULT);
3125 return SOCKET_ERROR;
3127 *(BOOL *)optval = TRUE;
3128 *optlen = sizeof(BOOL);
3129 return 0;
3131 case WS_SO_LINGER:
3133 struct linger lingval;
3134 int so_type;
3135 socklen_t len = sizeof(struct linger), slen = sizeof(int);
3137 /* struct linger and LINGER have different sizes */
3138 if (!optlen || *optlen < sizeof(LINGER) || !optval)
3140 SetLastError(WSAEFAULT);
3141 return SOCKET_ERROR;
3143 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3144 return SOCKET_ERROR;
3146 if ((getsockopt(fd, SOL_SOCKET, SO_TYPE, &so_type, &slen) == 0 && so_type == SOCK_DGRAM))
3148 SetLastError(WSAENOPROTOOPT);
3149 ret = SOCKET_ERROR;
3151 else if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0)
3153 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3154 ret = SOCKET_ERROR;
3156 else
3158 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
3159 ((LINGER *)optval)->l_linger = lingval.l_linger;
3160 *optlen = sizeof(struct linger);
3163 release_sock_fd( s, fd );
3164 return ret;
3167 case WS_SO_MAX_MSG_SIZE:
3168 if (!optlen || *optlen < sizeof(int) || !optval)
3170 SetLastError(WSAEFAULT);
3171 return SOCKET_ERROR;
3173 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
3174 *(int *)optval = 65507;
3175 *optlen = sizeof(int);
3176 return 0;
3178 /* SO_OPENTYPE does not require a valid socket handle. */
3179 case WS_SO_OPENTYPE:
3180 if (!optlen || *optlen < sizeof(int) || !optval)
3182 SetLastError(WSAEFAULT);
3183 return SOCKET_ERROR;
3185 *(int *)optval = get_per_thread_data()->opentype;
3186 *optlen = sizeof(int);
3187 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
3188 return 0;
3189 case WS_SO_PROTOCOL_INFOA:
3190 case WS_SO_PROTOCOL_INFOW:
3192 int size;
3193 WSAPROTOCOL_INFOW infow;
3195 ret = ws_protocol_info(s, optname == WS_SO_PROTOCOL_INFOW, &infow, &size);
3196 if (ret)
3198 if (!optlen || !optval || *optlen < size)
3200 if(optlen) *optlen = size;
3201 ret = 0;
3202 SetLastError(WSAEFAULT);
3204 else
3205 memcpy(optval, &infow, size);
3207 return ret ? 0 : SOCKET_ERROR;
3209 #ifdef SO_RCVTIMEO
3210 case WS_SO_RCVTIMEO:
3211 #endif
3212 #ifdef SO_SNDTIMEO
3213 case WS_SO_SNDTIMEO:
3214 #endif
3215 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
3217 struct timeval tv;
3218 socklen_t len = sizeof(struct timeval);
3220 if (!optlen || *optlen < sizeof(int)|| !optval)
3222 SetLastError(WSAEFAULT);
3223 return SOCKET_ERROR;
3225 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3226 return SOCKET_ERROR;
3228 convert_sockopt(&level, &optname);
3229 if (getsockopt(fd, level, optname, &tv, &len) != 0 )
3231 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3232 ret = SOCKET_ERROR;
3234 else
3236 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
3237 *optlen = sizeof(int);
3240 release_sock_fd( s, fd );
3241 return ret;
3243 #endif
3244 case WS_SO_TYPE:
3246 if (!optlen || *optlen < sizeof(int) || !optval)
3248 SetLastError(WSAEFAULT);
3249 return SOCKET_ERROR;
3251 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3252 return SOCKET_ERROR;
3254 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, optval, (socklen_t *)optlen) != 0 )
3256 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3257 ret = SOCKET_ERROR;
3259 else
3260 (*(int *)optval) = convert_socktype_u2w(*(int *)optval);
3262 release_sock_fd( s, fd );
3263 return ret;
3265 default:
3266 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
3267 SetLastError(WSAENOPROTOOPT);
3268 return SOCKET_ERROR;
3269 } /* end switch(optname) */
3270 }/* end case WS_SOL_SOCKET */
3271 #ifdef HAS_IPX
3272 case WS_NSPROTO_IPX:
3274 struct WS_sockaddr_ipx addr;
3275 IPX_ADDRESS_DATA *data;
3276 int namelen;
3277 switch(optname)
3279 case IPX_PTYPE:
3280 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3281 #ifdef SOL_IPX
3282 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (socklen_t *)optlen) == -1)
3284 ret = SOCKET_ERROR;
3286 #else
3288 struct ipx val;
3289 socklen_t len=sizeof(struct ipx);
3290 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
3291 ret = SOCKET_ERROR;
3292 else
3293 *optval = (int)val.ipx_pt;
3295 #endif
3296 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
3297 release_sock_fd( s, fd );
3298 return ret;
3300 case IPX_ADDRESS:
3302 * On a Win2000 system with one network card there are usually
3303 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
3304 * Using this call you can then retrieve info about this all.
3305 * In case of Linux it is a bit different. Usually you have
3306 * only "one" device active and further it is not possible to
3307 * query things like the linkspeed.
3309 FIXME("IPX_ADDRESS\n");
3310 namelen = sizeof(struct WS_sockaddr_ipx);
3311 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
3312 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
3314 data = (IPX_ADDRESS_DATA*)optval;
3315 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
3316 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
3317 data->adapternum = 0;
3318 data->wan = FALSE; /* We are not on a wan for now .. */
3319 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
3320 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
3321 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
3322 * note 1MB = 1000kB in this case */
3323 return 0;
3325 case IPX_MAX_ADAPTER_NUM:
3326 FIXME("IPX_MAX_ADAPTER_NUM\n");
3327 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
3328 return 0;
3330 default:
3331 FIXME("IPX optname:%x\n", optname);
3332 return SOCKET_ERROR;
3333 }/* end switch(optname) */
3334 } /* end case WS_NSPROTO_IPX */
3335 #endif
3337 #ifdef HAS_IRDA
3338 case WS_SOL_IRLMP:
3339 switch(optname)
3341 case WS_IRLMP_ENUMDEVICES:
3343 static const int MAX_IRDA_DEVICES = 10;
3344 char buf[sizeof(struct irda_device_list) +
3345 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
3346 int res;
3347 socklen_t len = sizeof(buf);
3349 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3350 return SOCKET_ERROR;
3351 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
3352 release_sock_fd( s, fd );
3353 if (res < 0)
3355 SetLastError(wsaErrno());
3356 return SOCKET_ERROR;
3358 else
3360 struct irda_device_list *src = (struct irda_device_list *)buf;
3361 DEVICELIST *dst = (DEVICELIST *)optval;
3362 INT needed = sizeof(DEVICELIST);
3363 unsigned int i;
3365 if (src->len > 0)
3366 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
3367 if (*optlen < needed)
3369 SetLastError(WSAEFAULT);
3370 return SOCKET_ERROR;
3372 *optlen = needed;
3373 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
3374 dst->numDevice = src->len;
3375 for (i = 0; i < src->len; i++)
3377 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
3378 src->dev[i].saddr, src->dev[i].daddr,
3379 src->dev[i].info, src->dev[i].hints[0],
3380 src->dev[i].hints[1]);
3381 memcpy( dst->Device[i].irdaDeviceID,
3382 &src->dev[i].daddr,
3383 sizeof(dst->Device[i].irdaDeviceID) ) ;
3384 memcpy( dst->Device[i].irdaDeviceName,
3385 src->dev[i].info,
3386 sizeof(dst->Device[i].irdaDeviceName) ) ;
3387 memcpy( &dst->Device[i].irdaDeviceHints1,
3388 &src->dev[i].hints[0],
3389 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
3390 memcpy( &dst->Device[i].irdaDeviceHints2,
3391 &src->dev[i].hints[1],
3392 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
3393 dst->Device[i].irdaCharSet = src->dev[i].charset;
3395 return 0;
3398 default:
3399 FIXME("IrDA optname:0x%x\n", optname);
3400 return SOCKET_ERROR;
3402 break; /* case WS_SOL_IRLMP */
3403 #endif
3405 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3406 case WS_IPPROTO_TCP:
3407 switch(optname)
3409 case WS_TCP_NODELAY:
3410 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3411 return SOCKET_ERROR;
3412 convert_sockopt(&level, &optname);
3413 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3415 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3416 ret = SOCKET_ERROR;
3418 release_sock_fd( s, fd );
3419 return ret;
3421 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
3422 return SOCKET_ERROR;
3424 case WS_IPPROTO_IP:
3425 switch(optname)
3427 case WS_IP_ADD_MEMBERSHIP:
3428 case WS_IP_DROP_MEMBERSHIP:
3429 #ifdef IP_HDRINCL
3430 case WS_IP_HDRINCL:
3431 #endif
3432 case WS_IP_MULTICAST_IF:
3433 case WS_IP_MULTICAST_LOOP:
3434 case WS_IP_MULTICAST_TTL:
3435 case WS_IP_OPTIONS:
3436 #ifdef IP_PKTINFO
3437 case WS_IP_PKTINFO:
3438 #endif
3439 case WS_IP_TOS:
3440 case WS_IP_TTL:
3441 #ifdef IP_UNICAST_IF
3442 case WS_IP_UNICAST_IF:
3443 #endif
3444 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3445 return SOCKET_ERROR;
3446 convert_sockopt(&level, &optname);
3447 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3449 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3450 ret = SOCKET_ERROR;
3452 release_sock_fd( s, fd );
3453 return ret;
3454 case WS_IP_DONTFRAGMENT:
3455 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
3456 *(BOOL*)optval = FALSE;
3457 return 0;
3459 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
3460 return SOCKET_ERROR;
3462 case WS_IPPROTO_IPV6:
3463 switch(optname)
3465 #ifdef IPV6_ADD_MEMBERSHIP
3466 case WS_IPV6_ADD_MEMBERSHIP:
3467 #endif
3468 #ifdef IPV6_DROP_MEMBERSHIP
3469 case WS_IPV6_DROP_MEMBERSHIP:
3470 #endif
3471 case WS_IPV6_MULTICAST_IF:
3472 case WS_IPV6_MULTICAST_HOPS:
3473 case WS_IPV6_MULTICAST_LOOP:
3474 case WS_IPV6_UNICAST_HOPS:
3475 case WS_IPV6_V6ONLY:
3476 #ifdef IPV6_UNICAST_IF
3477 case WS_IPV6_UNICAST_IF:
3478 #endif
3479 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3480 return SOCKET_ERROR;
3481 convert_sockopt(&level, &optname);
3482 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3484 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3485 ret = SOCKET_ERROR;
3487 release_sock_fd( s, fd );
3488 return ret;
3489 case WS_IPV6_DONTFRAG:
3490 FIXME("WS_IPV6_DONTFRAG is always false!\n");
3491 *(BOOL*)optval = FALSE;
3492 return 0;
3494 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
3495 return SOCKET_ERROR;
3497 default:
3498 WARN("Unknown level: 0x%08x\n", level);
3499 SetLastError(WSAEINVAL);
3500 return SOCKET_ERROR;
3501 } /* end switch(level) */
3504 /***********************************************************************
3505 * htonl (WS2_32.8)
3507 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
3509 return htonl(hostlong);
3513 /***********************************************************************
3514 * htons (WS2_32.9)
3516 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
3518 return htons(hostshort);
3521 /***********************************************************************
3522 * WSAHtonl (WS2_32.46)
3523 * From MSDN description of error codes, this function should also
3524 * check if WinSock has been initialized and the socket is a valid
3525 * socket. But why? This function only translates a host byte order
3526 * u_long into a network byte order u_long...
3528 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
3530 if (lpnetlong)
3532 *lpnetlong = htonl(hostlong);
3533 return 0;
3535 WSASetLastError(WSAEFAULT);
3536 return SOCKET_ERROR;
3539 /***********************************************************************
3540 * WSAHtons (WS2_32.47)
3541 * From MSDN description of error codes, this function should also
3542 * check if WinSock has been initialized and the socket is a valid
3543 * socket. But why? This function only translates a host byte order
3544 * u_short into a network byte order u_short...
3546 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
3549 if (lpnetshort)
3551 *lpnetshort = htons(hostshort);
3552 return 0;
3554 WSASetLastError(WSAEFAULT);
3555 return SOCKET_ERROR;
3559 /***********************************************************************
3560 * inet_addr (WS2_32.11)
3562 WS_u_long WINAPI WS_inet_addr(const char *cp)
3564 if (!cp) return INADDR_NONE;
3565 return inet_addr(cp);
3569 /***********************************************************************
3570 * ntohl (WS2_32.14)
3572 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
3574 return ntohl(netlong);
3578 /***********************************************************************
3579 * ntohs (WS2_32.15)
3581 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
3583 return ntohs(netshort);
3587 /***********************************************************************
3588 * inet_ntoa (WS2_32.12)
3590 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
3592 char* s = inet_ntoa(*((struct in_addr*)&in));
3593 if( s )
3595 struct per_thread_data *data = get_per_thread_data();
3596 strcpy(data->ntoa_buffer, s);
3597 return data->ntoa_buffer;
3599 SetLastError(wsaErrno());
3600 return NULL;
3603 static const char *debugstr_wsaioctl(DWORD ioctl)
3605 const char *buf_type, *family;
3607 switch(ioctl & 0x18000000)
3609 case WS_IOC_WS2:
3610 family = "IOC_WS2";
3611 break;
3612 case WS_IOC_PROTOCOL:
3613 family = "IOC_PROTOCOL";
3614 break;
3615 case WS_IOC_VENDOR:
3616 family = "IOC_VENDOR";
3617 break;
3618 default: /* WS_IOC_UNIX */
3620 BYTE size = (ioctl >> 16) & WS_IOCPARM_MASK;
3621 char x = (ioctl & 0xff00) >> 8;
3622 BYTE y = ioctl & 0xff;
3623 char args[14];
3625 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3627 case WS_IOC_VOID:
3628 buf_type = "_IO";
3629 sprintf(args, "%d, %d", x, y);
3630 break;
3631 case WS_IOC_IN:
3632 buf_type = "_IOW";
3633 sprintf(args, "'%c', %d, %d", x, y, size);
3634 break;
3635 case WS_IOC_OUT:
3636 buf_type = "_IOR";
3637 sprintf(args, "'%c', %d, %d", x, y, size);
3638 break;
3639 default:
3640 buf_type = "?";
3641 sprintf(args, "'%c', %d, %d", x, y, size);
3642 break;
3644 return wine_dbg_sprintf("%s(%s)", buf_type, args);
3648 /* We are different from WS_IOC_UNIX. */
3649 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3651 case WS_IOC_VOID:
3652 buf_type = "_WSAIO";
3653 break;
3654 case WS_IOC_INOUT:
3655 buf_type = "_WSAIORW";
3656 break;
3657 case WS_IOC_IN:
3658 buf_type = "_WSAIOW";
3659 break;
3660 case WS_IOC_OUT:
3661 buf_type = "_WSAIOR";
3662 break;
3663 default:
3664 buf_type = "?";
3665 break;
3668 return wine_dbg_sprintf("%s(%s, %d)", buf_type, family,
3669 (USHORT)(ioctl & 0xffff));
3672 /**********************************************************************
3673 * WSAIoctl (WS2_32.50)
3676 INT WINAPI WSAIoctl(SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size, LPVOID out_buff,
3677 DWORD out_size, LPDWORD ret_size, LPWSAOVERLAPPED overlapped,
3678 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
3680 int fd;
3681 DWORD status = 0, total = 0;
3683 TRACE("%ld, 0x%08x, %p, %d, %p, %d, %p, %p, %p\n",
3684 s, code, in_buff, in_size, out_buff, out_size, ret_size, overlapped, completion);
3686 switch (code)
3688 case WS_FIONBIO:
3689 if (in_size != sizeof(WS_u_long) || IS_INTRESOURCE(in_buff))
3691 WSASetLastError(WSAEFAULT);
3692 return SOCKET_ERROR;
3694 if (_get_sock_mask(s))
3696 /* AsyncSelect()'ed sockets are always nonblocking */
3697 if (!*(WS_u_long *)in_buff) status = WSAEINVAL;
3698 break;
3700 if (*(WS_u_long *)in_buff)
3701 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
3702 else
3703 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
3704 break;
3706 case WS_FIONREAD:
3708 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
3710 WSASetLastError(WSAEFAULT);
3711 return SOCKET_ERROR;
3713 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3714 if (ioctl(fd, FIONREAD, out_buff ) == -1)
3715 status = (errno == EBADF) ? WSAENOTSOCK : wsaErrno();
3716 release_sock_fd( s, fd );
3717 break;
3720 case WS_SIOCATMARK:
3722 unsigned int oob = 0, atmark = 0;
3723 socklen_t oobsize = sizeof(int);
3724 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
3726 WSASetLastError(WSAEFAULT);
3727 return SOCKET_ERROR;
3729 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3730 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
3731 if ((getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &oob, &oobsize ) == -1)
3732 || (!oob && ioctl(fd, SIOCATMARK, &atmark ) == -1))
3733 status = (errno == EBADF) ? WSAENOTSOCK : wsaErrno();
3734 else
3736 /* The SIOCATMARK value read from ioctl() is reversed
3737 * because BSD returns TRUE if it's in the OOB mark
3738 * while Windows returns TRUE if there are NO OOB bytes.
3740 (*(WS_u_long *) out_buff) = oob | !atmark;
3743 release_sock_fd( s, fd );
3744 break;
3747 case WS_FIOASYNC:
3748 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
3749 SetLastError(WSAEINVAL);
3750 return SOCKET_ERROR;
3752 case WS_SIO_GET_INTERFACE_LIST:
3754 INTERFACE_INFO* intArray = out_buff;
3755 DWORD size, numInt = 0, apiReturn;
3757 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
3759 if (!out_buff || !ret_size)
3761 WSASetLastError(WSAEFAULT);
3762 return SOCKET_ERROR;
3765 fd = get_sock_fd( s, 0, NULL );
3766 if (fd == -1) return SOCKET_ERROR;
3768 apiReturn = GetAdaptersInfo(NULL, &size);
3769 if (apiReturn == ERROR_BUFFER_OVERFLOW)
3771 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
3773 if (table)
3775 if (GetAdaptersInfo(table, &size) == NO_ERROR)
3777 PIP_ADAPTER_INFO ptr;
3779 for (ptr = table, numInt = 0; ptr; ptr = ptr->Next)
3781 unsigned int addr, mask, bcast;
3782 struct ifreq ifInfo;
3784 /* Skip interfaces without an IPv4 address. */
3785 if (ptr->IpAddressList.IpAddress.String[0] == '\0')
3786 continue;
3788 if ((numInt + 1)*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > out_size)
3790 WARN("Buffer too small = %u, out_size = %u\n", numInt + 1, out_size);
3791 status = WSAEFAULT;
3792 break;
3795 /* Socket Status Flags */
3796 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
3797 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
3799 ERR("Error obtaining status flags for socket!\n");
3800 status = WSAEINVAL;
3801 break;
3803 else
3805 /* set flags; the values of IFF_* are not the same
3806 under Linux and Windows, therefore must generate
3807 new flags */
3808 intArray->iiFlags = 0;
3809 if (ifInfo.ifr_flags & IFF_BROADCAST)
3810 intArray->iiFlags |= WS_IFF_BROADCAST;
3811 #ifdef IFF_POINTOPOINT
3812 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
3813 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
3814 #endif
3815 if (ifInfo.ifr_flags & IFF_LOOPBACK)
3816 intArray->iiFlags |= WS_IFF_LOOPBACK;
3817 if (ifInfo.ifr_flags & IFF_UP)
3818 intArray->iiFlags |= WS_IFF_UP;
3819 if (ifInfo.ifr_flags & IFF_MULTICAST)
3820 intArray->iiFlags |= WS_IFF_MULTICAST;
3823 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
3824 mask = inet_addr(ptr->IpAddressList.IpMask.String);
3825 bcast = addr | ~mask;
3826 intArray->iiAddress.AddressIn.sin_family = AF_INET;
3827 intArray->iiAddress.AddressIn.sin_port = 0;
3828 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
3829 addr;
3830 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
3831 intArray->iiNetmask.AddressIn.sin_port = 0;
3832 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
3833 mask;
3834 intArray->iiBroadcastAddress.AddressIn.sin_family =
3835 AF_INET;
3836 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
3837 intArray->iiBroadcastAddress.AddressIn.sin_addr.
3838 WS_s_addr = bcast;
3839 intArray++;
3840 numInt++;
3843 else
3845 ERR("Unable to get interface table!\n");
3846 status = WSAEINVAL;
3848 HeapFree(GetProcessHeap(),0,table);
3850 else status = WSAEINVAL;
3852 else if (apiReturn != ERROR_NO_DATA)
3854 ERR("Unable to get interface table!\n");
3855 status = WSAEINVAL;
3857 /* Calculate the size of the array being returned */
3858 total = sizeof(INTERFACE_INFO) * numInt;
3859 release_sock_fd( s, fd );
3860 break;
3863 case WS_SIO_ADDRESS_LIST_CHANGE:
3864 FIXME("-> SIO_ADDRESS_LIST_CHANGE request: stub\n");
3865 /* FIXME: error and return code depend on whether socket was created
3866 * with WSA_FLAG_OVERLAPPED, but there is no easy way to get this */
3867 break;
3869 case WS_SIO_ADDRESS_LIST_QUERY:
3871 DWORD size;
3873 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
3875 if (!ret_size)
3877 WSASetLastError(WSAEFAULT);
3878 return SOCKET_ERROR;
3881 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
3883 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
3884 DWORD num;
3886 if (!table || GetAdaptersInfo(table, &size))
3888 HeapFree(GetProcessHeap(), 0, table);
3889 status = WSAEINVAL;
3890 break;
3893 for (p = table, num = 0; p; p = p->Next)
3894 if (p->IpAddressList.IpAddress.String[0]) num++;
3896 total = sizeof(SOCKET_ADDRESS_LIST) + sizeof(SOCKET_ADDRESS) * (num - 1);
3897 total += sizeof(SOCKADDR) * num;
3899 if (total > out_size)
3901 HeapFree(GetProcessHeap(), 0, table);
3902 status = WSAEFAULT;
3903 break;
3906 if (out_buff)
3908 unsigned int i;
3909 SOCKET_ADDRESS *sa;
3910 SOCKET_ADDRESS_LIST *sa_list = out_buff;
3911 SOCKADDR_IN *sockaddr;
3913 sa = sa_list->Address;
3914 sockaddr = (SOCKADDR_IN *)((char *)sa + num * sizeof(SOCKET_ADDRESS));
3915 sa_list->iAddressCount = num;
3917 for (p = table, i = 0; p; p = p->Next)
3919 if (!p->IpAddressList.IpAddress.String[0]) continue;
3921 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
3922 sa[i].iSockaddrLength = sizeof(SOCKADDR);
3924 sockaddr[i].sin_family = AF_INET;
3925 sockaddr[i].sin_port = 0;
3926 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
3927 i++;
3931 HeapFree(GetProcessHeap(), 0, table);
3933 else
3935 WARN("unable to get IP address list\n");
3936 status = WSAEINVAL;
3938 break;
3941 case WS_SIO_FLUSH:
3942 FIXME("SIO_FLUSH: stub.\n");
3943 break;
3945 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
3947 static const GUID connectex_guid = WSAID_CONNECTEX;
3948 static const GUID disconnectex_guid = WSAID_DISCONNECTEX;
3949 static const GUID acceptex_guid = WSAID_ACCEPTEX;
3950 static const GUID getaccepexsockaddrs_guid = WSAID_GETACCEPTEXSOCKADDRS;
3951 static const GUID transmitfile_guid = WSAID_TRANSMITFILE;
3952 static const GUID transmitpackets_guid = WSAID_TRANSMITPACKETS;
3953 static const GUID wsarecvmsg_guid = WSAID_WSARECVMSG;
3954 static const GUID wsasendmsg_guid = WSAID_WSASENDMSG;
3956 if ( IsEqualGUID(&connectex_guid, in_buff) )
3958 *(LPFN_CONNECTEX *)out_buff = WS2_ConnectEx;
3959 break;
3961 else if ( IsEqualGUID(&disconnectex_guid, in_buff) )
3963 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented DisconnectEx\n");
3965 else if ( IsEqualGUID(&acceptex_guid, in_buff) )
3967 *(LPFN_ACCEPTEX *)out_buff = WS2_AcceptEx;
3968 break;
3970 else if ( IsEqualGUID(&getaccepexsockaddrs_guid, in_buff) )
3972 *(LPFN_GETACCEPTEXSOCKADDRS *)out_buff = WS2_GetAcceptExSockaddrs;
3973 break;
3975 else if ( IsEqualGUID(&transmitfile_guid, in_buff) )
3977 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitFile\n");
3979 else if ( IsEqualGUID(&transmitpackets_guid, in_buff) )
3981 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitPackets\n");
3983 else if ( IsEqualGUID(&wsarecvmsg_guid, in_buff) )
3985 *(LPFN_WSARECVMSG *)out_buff = WS2_WSARecvMsg;
3986 break;
3988 else if ( IsEqualGUID(&wsasendmsg_guid, in_buff) )
3990 *(LPFN_WSASENDMSG *)out_buff = WSASendMsg;
3991 break;
3993 else
3994 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff));
3996 status = WSAEOPNOTSUPP;
3997 break;
3999 case WS_SIO_KEEPALIVE_VALS:
4001 struct tcp_keepalive *k;
4002 int keepalive, keepidle, keepintvl;
4004 if (!in_buff || in_size < sizeof(struct tcp_keepalive))
4006 WSASetLastError(WSAEFAULT);
4007 return SOCKET_ERROR;
4010 k = in_buff;
4011 keepalive = k->onoff ? 1 : 0;
4012 keepidle = max( 1, (k->keepalivetime + 500) / 1000 );
4013 keepintvl = max( 1, (k->keepaliveinterval + 500) / 1000 );
4015 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
4017 fd = get_sock_fd(s, 0, NULL);
4018 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
4019 status = WSAEINVAL;
4020 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
4021 /* these values need to be set only if SO_KEEPALIVE is enabled */
4022 else if(keepalive)
4024 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
4025 status = WSAEINVAL;
4026 else if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
4027 status = WSAEINVAL;
4029 #else
4030 else
4031 FIXME("ignoring keepalive interval and timeout\n");
4032 #endif
4033 release_sock_fd(s, fd);
4034 break;
4036 case WS_SIO_ROUTING_INTERFACE_QUERY:
4038 struct WS_sockaddr *daddr = (struct WS_sockaddr *)in_buff;
4039 struct WS_sockaddr_in *daddr_in = (struct WS_sockaddr_in *)daddr;
4040 struct WS_sockaddr_in *saddr_in = out_buff;
4041 MIB_IPFORWARDROW row;
4042 PMIB_IPADDRTABLE ipAddrTable = NULL;
4043 DWORD size, i, found_index;
4045 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
4047 if (!in_buff || in_size < sizeof(struct WS_sockaddr) ||
4048 !out_buff || out_size < sizeof(struct WS_sockaddr_in) || !ret_size)
4050 WSASetLastError(WSAEFAULT);
4051 return SOCKET_ERROR;
4053 if (daddr->sa_family != AF_INET)
4055 FIXME("unsupported address family %d\n", daddr->sa_family);
4056 status = WSAEAFNOSUPPORT;
4057 break;
4059 if (GetBestRoute(daddr_in->sin_addr.S_un.S_addr, 0, &row) != NOERROR ||
4060 GetIpAddrTable(NULL, &size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
4062 status = WSAEFAULT;
4063 break;
4065 ipAddrTable = HeapAlloc(GetProcessHeap(), 0, size);
4066 if (GetIpAddrTable(ipAddrTable, &size, FALSE))
4068 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4069 status = WSAEFAULT;
4070 break;
4072 for (i = 0, found_index = ipAddrTable->dwNumEntries;
4073 i < ipAddrTable->dwNumEntries; i++)
4075 if (ipAddrTable->table[i].dwIndex == row.dwForwardIfIndex)
4076 found_index = i;
4078 if (found_index == ipAddrTable->dwNumEntries)
4080 ERR("no matching IP address for interface %d\n",
4081 row.dwForwardIfIndex);
4082 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4083 status = WSAEFAULT;
4084 break;
4086 saddr_in->sin_family = AF_INET;
4087 saddr_in->sin_addr.S_un.S_addr = ipAddrTable->table[found_index].dwAddr;
4088 saddr_in->sin_port = 0;
4089 total = sizeof(struct WS_sockaddr_in);
4090 HeapFree(GetProcessHeap(), 0, ipAddrTable);
4091 break;
4093 case WS_SIO_SET_COMPATIBILITY_MODE:
4094 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
4095 status = WSAEOPNOTSUPP;
4096 break;
4097 case WS_SIO_UDP_CONNRESET:
4098 FIXME("WS_SIO_UDP_CONNRESET stub\n");
4099 break;
4100 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
4101 WSASetLastError(WSAEOPNOTSUPP);
4102 return SOCKET_ERROR;
4103 default:
4104 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code));
4105 status = WSAEOPNOTSUPP;
4106 break;
4109 if (completion)
4111 FIXME( "completion routine %p not supported\n", completion );
4113 else if (overlapped)
4115 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
4116 overlapped->Internal = status;
4117 overlapped->InternalHigh = total;
4118 if (overlapped->hEvent) NtSetEvent( overlapped->hEvent, NULL );
4119 if (cvalue) WS_AddCompletion( HANDLE2SOCKET(s), cvalue, status, total );
4122 if (!status)
4124 if (ret_size) *ret_size = total;
4125 return 0;
4127 SetLastError( status );
4128 return SOCKET_ERROR;
4132 /***********************************************************************
4133 * ioctlsocket (WS2_32.10)
4135 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
4137 DWORD ret_size;
4138 return WSAIoctl( s, cmd, argp, sizeof(WS_u_long), argp, sizeof(WS_u_long), &ret_size, NULL, NULL );
4141 /***********************************************************************
4142 * listen (WS2_32.13)
4144 int WINAPI WS_listen(SOCKET s, int backlog)
4146 int fd = get_sock_fd( s, FILE_READ_DATA, NULL ), ret = SOCKET_ERROR;
4148 TRACE("socket %04lx, backlog %d\n", s, backlog);
4149 if (fd != -1)
4151 union generic_unix_sockaddr uaddr;
4152 socklen_t uaddrlen = sizeof(uaddr);
4154 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
4156 SetLastError(wsaErrno());
4158 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
4160 SetLastError(WSAEINVAL);
4162 else if (listen(fd, backlog) == 0)
4164 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
4165 FD_WINE_LISTENING,
4166 FD_CONNECT|FD_WINE_CONNECTED);
4167 ret = 0;
4169 else
4170 SetLastError(wsaErrno());
4171 release_sock_fd( s, fd );
4173 else
4174 SetLastError(WSAENOTSOCK);
4175 return ret;
4178 /***********************************************************************
4179 * recv (WS2_32.16)
4181 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
4183 DWORD n, dwFlags = flags;
4184 WSABUF wsabuf;
4186 wsabuf.len = len;
4187 wsabuf.buf = buf;
4189 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
4190 return SOCKET_ERROR;
4191 else
4192 return n;
4195 /***********************************************************************
4196 * recvfrom (WS2_32.17)
4198 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
4199 struct WS_sockaddr *from, int *fromlen)
4201 DWORD n, dwFlags = flags;
4202 WSABUF wsabuf;
4204 wsabuf.len = len;
4205 wsabuf.buf = buf;
4207 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL, NULL) == SOCKET_ERROR )
4208 return SOCKET_ERROR;
4209 else
4210 return n;
4213 /* allocate a poll array for the corresponding fd sets */
4214 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
4215 const WS_fd_set *exceptfds, int *count_ptr )
4217 unsigned int i, j = 0, count = 0;
4218 struct pollfd *fds;
4220 if (readfds) count += readfds->fd_count;
4221 if (writefds) count += writefds->fd_count;
4222 if (exceptfds) count += exceptfds->fd_count;
4223 *count_ptr = count;
4224 if (!count)
4226 SetLastError(WSAEINVAL);
4227 return NULL;
4229 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0]))))
4231 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
4232 return NULL;
4234 if (readfds)
4235 for (i = 0; i < readfds->fd_count; i++, j++)
4237 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
4238 if (fds[j].fd == -1) goto failed;
4239 fds[j].events = POLLIN;
4240 fds[j].revents = 0;
4242 if (writefds)
4243 for (i = 0; i < writefds->fd_count; i++, j++)
4245 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
4246 if (fds[j].fd == -1) goto failed;
4247 fds[j].events = POLLOUT;
4248 fds[j].revents = 0;
4250 if (exceptfds)
4251 for (i = 0; i < exceptfds->fd_count; i++, j++)
4253 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
4254 if (fds[j].fd == -1) goto failed;
4255 fds[j].events = POLLHUP;
4256 fds[j].revents = 0;
4258 return fds;
4260 failed:
4261 count = j;
4262 j = 0;
4263 if (readfds)
4264 for (i = 0; i < readfds->fd_count && j < count; i++, j++)
4265 release_sock_fd( readfds->fd_array[i], fds[j].fd );
4266 if (writefds)
4267 for (i = 0; i < writefds->fd_count && j < count; i++, j++)
4268 release_sock_fd( writefds->fd_array[i], fds[j].fd );
4269 if (exceptfds)
4270 for (i = 0; i < exceptfds->fd_count && j < count; i++, j++)
4271 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
4272 HeapFree( GetProcessHeap(), 0, fds );
4273 return NULL;
4276 /* release the file descriptor obtained in fd_sets_to_poll */
4277 /* must be called with the original fd_set arrays, before calling get_poll_results */
4278 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
4279 const WS_fd_set *exceptfds, struct pollfd *fds )
4281 unsigned int i, j = 0;
4283 if (readfds)
4285 for (i = 0; i < readfds->fd_count; i++, j++)
4286 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
4288 if (writefds)
4290 for (i = 0; i < writefds->fd_count; i++, j++)
4291 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
4293 if (exceptfds)
4295 for (i = 0; i < exceptfds->fd_count; i++, j++)
4296 if (fds[j].fd != -1)
4298 /* make sure we have a real error before releasing the fd */
4299 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
4300 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
4305 /* map the poll results back into the Windows fd sets */
4306 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
4307 const struct pollfd *fds )
4309 unsigned int i, j = 0, k, total = 0;
4311 if (readfds)
4313 for (i = k = 0; i < readfds->fd_count; i++, j++)
4314 if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
4315 readfds->fd_count = k;
4316 total += k;
4318 if (writefds)
4320 for (i = k = 0; i < writefds->fd_count; i++, j++)
4321 if ((fds[j].revents & POLLOUT) && !(fds[j].revents & POLLHUP))
4322 writefds->fd_array[k++] = writefds->fd_array[i];
4323 writefds->fd_count = k;
4324 total += k;
4326 if (exceptfds)
4328 for (i = k = 0; i < exceptfds->fd_count; i++, j++)
4329 if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
4330 exceptfds->fd_count = k;
4331 total += k;
4333 return total;
4337 /***********************************************************************
4338 * select (WS2_32.18)
4340 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
4341 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
4342 const struct WS_timeval* ws_timeout)
4344 struct pollfd *pollfds;
4345 struct timeval tv1, tv2;
4346 int torig = 0;
4347 int count, ret, timeout = -1;
4349 TRACE("read %p, write %p, excp %p timeout %p\n",
4350 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
4352 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )))
4353 return SOCKET_ERROR;
4355 if (ws_timeout)
4357 torig = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
4358 timeout = torig;
4359 gettimeofday( &tv1, 0 );
4362 while ((ret = poll( pollfds, count, timeout )) < 0)
4364 if (errno == EINTR)
4366 if (!ws_timeout) continue;
4367 gettimeofday( &tv2, 0 );
4369 tv2.tv_sec -= tv1.tv_sec;
4370 tv2.tv_usec -= tv1.tv_usec;
4371 if (tv2.tv_usec < 0)
4373 tv2.tv_usec += 1000000;
4374 tv2.tv_sec -= 1;
4377 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
4378 if (timeout <= 0) break;
4379 } else break;
4381 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
4383 if (ret == -1) SetLastError(wsaErrno());
4384 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
4385 HeapFree( GetProcessHeap(), 0, pollfds );
4386 return ret;
4389 /* helper to send completion messages for client-only i/o operation case */
4390 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
4391 ULONG Information )
4393 SERVER_START_REQ( add_fd_completion )
4395 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
4396 req->cvalue = CompletionValue;
4397 req->status = CompletionStatus;
4398 req->information = Information;
4399 wine_server_call( req );
4401 SERVER_END_REQ;
4405 /***********************************************************************
4406 * send (WS2_32.19)
4408 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
4410 DWORD n;
4411 WSABUF wsabuf;
4413 wsabuf.len = len;
4414 wsabuf.buf = (char*) buf;
4416 if ( WS2_sendto( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
4417 return SOCKET_ERROR;
4418 else
4419 return n;
4422 /***********************************************************************
4423 * WSASend (WS2_32.72)
4425 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4426 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4427 LPWSAOVERLAPPED lpOverlapped,
4428 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4430 return WS2_sendto( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
4431 NULL, 0, lpOverlapped, lpCompletionRoutine );
4434 /***********************************************************************
4435 * WSASendDisconnect (WS2_32.73)
4437 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
4439 return WS_shutdown( s, SD_SEND );
4443 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4444 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4445 const struct WS_sockaddr *to, int tolen,
4446 LPWSAOVERLAPPED lpOverlapped,
4447 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4449 unsigned int i, options;
4450 int n, fd, err;
4451 struct ws2_async *wsa = NULL;
4452 int totalLength = 0;
4453 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
4454 DWORD bytes_sent;
4455 BOOL is_blocking;
4457 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
4458 s, lpBuffers, dwBufferCount, dwFlags,
4459 to, tolen, lpOverlapped, lpCompletionRoutine);
4461 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
4462 TRACE( "fd=%d, options=%x\n", fd, options );
4464 if ( fd == -1 ) return SOCKET_ERROR;
4466 if (!lpOverlapped && !lpNumberOfBytesSent)
4468 err = WSAEFAULT;
4469 goto error;
4471 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
4473 err = WSAEFAULT;
4474 goto error;
4477 wsa->hSocket = SOCKET2HANDLE(s);
4478 wsa->addr = (struct WS_sockaddr *)to;
4479 wsa->addrlen.val = tolen;
4480 wsa->flags = dwFlags;
4481 wsa->lpFlags = &wsa->flags;
4482 wsa->control = NULL;
4483 wsa->n_iovecs = dwBufferCount;
4484 wsa->first_iovec = 0;
4485 for ( i = 0; i < dwBufferCount; i++ )
4487 wsa->iovec[i].iov_base = lpBuffers[i].buf;
4488 wsa->iovec[i].iov_len = lpBuffers[i].len;
4489 totalLength += lpBuffers[i].len;
4492 for (;;)
4494 n = WS2_send( fd, wsa );
4495 if (n != -1 || errno != EINTR) break;
4497 if (n == -1 && errno != EAGAIN)
4499 err = wsaErrno();
4500 goto error;
4503 if ((lpOverlapped || lpCompletionRoutine) &&
4504 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
4506 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
4508 wsa->user_overlapped = lpOverlapped;
4509 wsa->completion_func = lpCompletionRoutine;
4510 release_sock_fd( s, fd );
4512 if (n == -1 || n < totalLength)
4514 iosb->u.Status = STATUS_PENDING;
4515 iosb->Information = n == -1 ? 0 : n;
4517 SERVER_START_REQ( register_async )
4519 req->type = ASYNC_TYPE_WRITE;
4520 req->async.handle = wine_server_obj_handle( wsa->hSocket );
4521 req->async.callback = wine_server_client_ptr( WS2_async_send );
4522 req->async.iosb = wine_server_client_ptr( iosb );
4523 req->async.arg = wine_server_client_ptr( wsa );
4524 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
4525 req->async.cvalue = cvalue;
4526 err = wine_server_call( req );
4528 SERVER_END_REQ;
4530 /* Enable the event only after starting the async. The server will deliver it as soon as
4531 the async is done. */
4532 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
4534 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
4535 WSASetLastError( NtStatusToWSAError( err ));
4536 return SOCKET_ERROR;
4539 iosb->u.Status = STATUS_SUCCESS;
4540 iosb->Information = n;
4541 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = n;
4542 if (!wsa->completion_func)
4544 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
4545 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
4546 HeapFree( GetProcessHeap(), 0, wsa );
4548 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
4549 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
4550 WSASetLastError(0);
4551 return 0;
4554 if ((err = _is_blocking( s, &is_blocking )))
4556 err = NtStatusToWSAError( err );
4557 goto error;
4560 if ( is_blocking )
4562 /* On a blocking non-overlapped stream socket,
4563 * sending blocks until the entire buffer is sent. */
4564 DWORD timeout_start = GetTickCount();
4566 bytes_sent = n == -1 ? 0 : n;
4568 while (wsa->first_iovec < wsa->n_iovecs)
4570 struct pollfd pfd;
4571 int timeout = GET_SNDTIMEO(fd);
4573 if (timeout != -1)
4575 timeout -= GetTickCount() - timeout_start;
4576 if (timeout < 0) timeout = 0;
4579 pfd.fd = fd;
4580 pfd.events = POLLOUT;
4582 if (!timeout || !poll( &pfd, 1, timeout ))
4584 err = WSAETIMEDOUT;
4585 goto error; /* msdn says a timeout in send is fatal */
4588 n = WS2_send( fd, wsa );
4589 if (n == -1 && errno != EAGAIN && errno != EINTR)
4591 err = wsaErrno();
4592 goto error;
4595 if (n >= 0)
4596 bytes_sent += n;
4599 else /* non-blocking */
4601 if (n < totalLength)
4602 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
4603 if (n == -1)
4605 err = WSAEWOULDBLOCK;
4606 goto error;
4608 bytes_sent = n;
4611 TRACE(" -> %i bytes\n", bytes_sent);
4613 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = bytes_sent;
4614 HeapFree( GetProcessHeap(), 0, wsa );
4615 release_sock_fd( s, fd );
4616 WSASetLastError(0);
4617 return 0;
4619 error:
4620 HeapFree( GetProcessHeap(), 0, wsa );
4621 release_sock_fd( s, fd );
4622 WARN(" -> ERROR %d\n", err);
4623 WSASetLastError(err);
4624 return SOCKET_ERROR;
4627 /***********************************************************************
4628 * WSASendTo (WS2_32.74)
4630 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4631 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4632 const struct WS_sockaddr *to, int tolen,
4633 LPWSAOVERLAPPED lpOverlapped,
4634 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4636 return WS2_sendto( s, lpBuffers, dwBufferCount,
4637 lpNumberOfBytesSent, dwFlags,
4638 to, tolen,
4639 lpOverlapped, lpCompletionRoutine );
4642 /***********************************************************************
4643 * sendto (WS2_32.20)
4645 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
4646 const struct WS_sockaddr *to, int tolen)
4648 DWORD n;
4649 WSABUF wsabuf;
4651 wsabuf.len = len;
4652 wsabuf.buf = (char*) buf;
4654 if ( WS2_sendto(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
4655 return SOCKET_ERROR;
4656 else
4657 return n;
4660 /***********************************************************************
4661 * setsockopt (WS2_32.21)
4663 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
4664 const char *optval, int optlen)
4666 int fd;
4667 int woptval;
4668 struct linger linger;
4669 struct timeval tval;
4671 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
4672 s, level, optname, optval, optlen);
4674 /* some broken apps pass the value directly instead of a pointer to it */
4675 if(optlen && IS_INTRESOURCE(optval))
4677 SetLastError(WSAEFAULT);
4678 return SOCKET_ERROR;
4681 switch(level)
4683 case WS_SOL_SOCKET:
4684 switch(optname)
4686 /* Some options need some conversion before they can be sent to
4687 * setsockopt. The conversions are done here, then they will fall though
4688 * to the general case. Special options that are not passed to
4689 * setsockopt follow below that.*/
4691 case WS_SO_DONTLINGER:
4692 if (!optval)
4694 SetLastError(WSAEFAULT);
4695 return SOCKET_ERROR;
4697 linger.l_onoff = *(const int*)optval == 0;
4698 linger.l_linger = 0;
4699 level = SOL_SOCKET;
4700 optname = SO_LINGER;
4701 optval = (char*)&linger;
4702 optlen = sizeof(struct linger);
4703 break;
4705 case WS_SO_LINGER:
4706 if (!optval)
4708 SetLastError(WSAEFAULT);
4709 return SOCKET_ERROR;
4711 linger.l_onoff = ((LINGER*)optval)->l_onoff;
4712 linger.l_linger = ((LINGER*)optval)->l_linger;
4713 level = SOL_SOCKET;
4714 optname = SO_LINGER;
4715 optval = (char*)&linger;
4716 optlen = sizeof(struct linger);
4717 break;
4719 case WS_SO_RCVBUF:
4720 if (*(const int*)optval < 2048)
4722 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
4723 return 0;
4725 /* Fall through */
4727 /* The options listed here don't need any special handling. Thanks to
4728 * the conversion happening above, options from there will fall through
4729 * to this, too.*/
4730 case WS_SO_ACCEPTCONN:
4731 case WS_SO_BROADCAST:
4732 case WS_SO_ERROR:
4733 case WS_SO_KEEPALIVE:
4734 case WS_SO_OOBINLINE:
4735 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
4736 * however, using it the BSD way fixes bug 8513 and seems to be what
4737 * most programmers assume, anyway */
4738 case WS_SO_REUSEADDR:
4739 case WS_SO_SNDBUF:
4740 case WS_SO_TYPE:
4741 convert_sockopt(&level, &optname);
4742 break;
4744 /* SO_DEBUG is a privileged operation, ignore it. */
4745 case WS_SO_DEBUG:
4746 TRACE("Ignoring SO_DEBUG\n");
4747 return 0;
4749 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
4750 * socket. According to MSDN, this option is silently ignored.*/
4751 case WS_SO_DONTROUTE:
4752 TRACE("Ignoring SO_DONTROUTE\n");
4753 return 0;
4755 /* Stops two sockets from being bound to the same port. Always happens
4756 * on unix systems, so just drop it. */
4757 case WS_SO_EXCLUSIVEADDRUSE:
4758 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
4759 return 0;
4761 /* After a ConnectEx call succeeds, the socket can't be used with half of the
4762 * normal winsock functions on windows. We don't have that problem. */
4763 case WS_SO_UPDATE_CONNECT_CONTEXT:
4764 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
4765 return 0;
4767 /* After a AcceptEx call succeeds, the socket can't be used with half of the
4768 * normal winsock functions on windows. We don't have that problem. */
4769 case WS_SO_UPDATE_ACCEPT_CONTEXT:
4770 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
4771 return 0;
4773 /* SO_OPENTYPE does not require a valid socket handle. */
4774 case WS_SO_OPENTYPE:
4775 if (!optlen || optlen < sizeof(int) || !optval)
4777 SetLastError(WSAEFAULT);
4778 return SOCKET_ERROR;
4780 get_per_thread_data()->opentype = *(const int *)optval;
4781 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
4782 return 0;
4784 #ifdef SO_RCVTIMEO
4785 case WS_SO_RCVTIMEO:
4786 #endif
4787 #ifdef SO_SNDTIMEO
4788 case WS_SO_SNDTIMEO:
4789 #endif
4790 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
4791 if (optval && optlen == sizeof(UINT32)) {
4792 /* WinSock passes milliseconds instead of struct timeval */
4793 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
4794 tval.tv_sec = *(const UINT32*)optval / 1000;
4795 /* min of 500 milliseconds */
4796 if (tval.tv_sec == 0 && tval.tv_usec && tval.tv_usec < 500000)
4797 tval.tv_usec = 500000;
4798 optlen = sizeof(struct timeval);
4799 optval = (char*)&tval;
4800 } else if (optlen == sizeof(struct timeval)) {
4801 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
4802 } else {
4803 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
4804 return 0;
4806 convert_sockopt(&level, &optname);
4807 break;
4808 #endif
4810 default:
4811 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
4812 SetLastError(WSAENOPROTOOPT);
4813 return SOCKET_ERROR;
4815 break; /* case WS_SOL_SOCKET */
4817 #ifdef HAS_IPX
4818 case WS_NSPROTO_IPX:
4819 switch(optname)
4821 case IPX_PTYPE:
4822 return set_ipx_packettype(s, *(int*)optval);
4824 case IPX_FILTERPTYPE:
4825 /* Sets the receive filter packet type, at the moment we don't support it */
4826 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
4827 /* Returning 0 is better for now than returning a SOCKET_ERROR */
4828 return 0;
4830 default:
4831 FIXME("opt_name:%x\n", optname);
4832 return SOCKET_ERROR;
4834 break; /* case WS_NSPROTO_IPX */
4835 #endif
4837 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
4838 case WS_IPPROTO_TCP:
4839 switch(optname)
4841 case WS_TCP_NODELAY:
4842 convert_sockopt(&level, &optname);
4843 break;
4844 default:
4845 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
4846 return SOCKET_ERROR;
4848 break;
4850 case WS_IPPROTO_IP:
4851 switch(optname)
4853 case WS_IP_ADD_MEMBERSHIP:
4854 case WS_IP_DROP_MEMBERSHIP:
4855 #ifdef IP_HDRINCL
4856 case WS_IP_HDRINCL:
4857 #endif
4858 case WS_IP_MULTICAST_IF:
4859 case WS_IP_MULTICAST_LOOP:
4860 case WS_IP_MULTICAST_TTL:
4861 case WS_IP_OPTIONS:
4862 #ifdef IP_PKTINFO
4863 case WS_IP_PKTINFO:
4864 #endif
4865 case WS_IP_TOS:
4866 case WS_IP_TTL:
4867 #ifdef IP_UNICAST_IF
4868 case WS_IP_UNICAST_IF:
4869 #endif
4870 convert_sockopt(&level, &optname);
4871 break;
4872 case WS_IP_DONTFRAGMENT:
4873 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
4874 return 0;
4875 default:
4876 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
4877 return SOCKET_ERROR;
4879 break;
4881 case WS_IPPROTO_IPV6:
4882 switch(optname)
4884 #ifdef IPV6_ADD_MEMBERSHIP
4885 case WS_IPV6_ADD_MEMBERSHIP:
4886 #endif
4887 #ifdef IPV6_DROP_MEMBERSHIP
4888 case WS_IPV6_DROP_MEMBERSHIP:
4889 #endif
4890 case WS_IPV6_MULTICAST_IF:
4891 case WS_IPV6_MULTICAST_HOPS:
4892 case WS_IPV6_MULTICAST_LOOP:
4893 case WS_IPV6_UNICAST_HOPS:
4894 case WS_IPV6_V6ONLY:
4895 #ifdef IPV6_UNICAST_IF
4896 case WS_IPV6_UNICAST_IF:
4897 #endif
4898 convert_sockopt(&level, &optname);
4899 break;
4900 case WS_IPV6_DONTFRAG:
4901 FIXME("IPV6_DONTFRAG is silently ignored!\n");
4902 return 0;
4903 case WS_IPV6_PROTECTION_LEVEL:
4904 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
4905 return 0;
4906 default:
4907 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
4908 return SOCKET_ERROR;
4910 break;
4912 default:
4913 WARN("Unknown level: 0x%08x\n", level);
4914 SetLastError(WSAEINVAL);
4915 return SOCKET_ERROR;
4916 } /* end switch(level) */
4918 /* avoid endianness issues if argument is a 16-bit int */
4919 if (optval && optlen < sizeof(int))
4921 woptval= *((const INT16 *) optval);
4922 optval= (char*) &woptval;
4923 optlen=sizeof(int);
4925 fd = get_sock_fd( s, 0, NULL );
4926 if (fd == -1) return SOCKET_ERROR;
4928 if (setsockopt(fd, level, optname, optval, optlen) == 0)
4930 #ifdef __APPLE__
4931 if (level == SOL_SOCKET && optname == SO_REUSEADDR &&
4932 setsockopt(fd, level, SO_REUSEPORT, optval, optlen) != 0)
4934 SetLastError(wsaErrno());
4935 release_sock_fd( s, fd );
4936 return SOCKET_ERROR;
4938 #endif
4939 release_sock_fd( s, fd );
4940 return 0;
4942 TRACE("Setting socket error, %d\n", wsaErrno());
4943 SetLastError(wsaErrno());
4944 release_sock_fd( s, fd );
4946 return SOCKET_ERROR;
4949 /***********************************************************************
4950 * shutdown (WS2_32.22)
4952 int WINAPI WS_shutdown(SOCKET s, int how)
4954 int fd, err = WSAENOTSOCK;
4955 unsigned int options, clear_flags = 0;
4957 fd = get_sock_fd( s, 0, &options );
4958 TRACE("socket %04lx, how %i %x\n", s, how, options );
4960 if (fd == -1)
4961 return SOCKET_ERROR;
4963 switch( how )
4965 case 0: /* drop receives */
4966 clear_flags |= FD_READ;
4967 break;
4968 case 1: /* drop sends */
4969 clear_flags |= FD_WRITE;
4970 break;
4971 case 2: /* drop all */
4972 clear_flags |= FD_READ|FD_WRITE;
4973 /*fall through */
4974 default:
4975 clear_flags |= FD_WINE_LISTENING;
4978 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
4980 switch ( how )
4982 case SD_RECEIVE:
4983 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
4984 break;
4985 case SD_SEND:
4986 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
4987 break;
4988 case SD_BOTH:
4989 default:
4990 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
4991 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
4992 break;
4994 if (err) goto error;
4996 else /* non-overlapped mode */
4998 if ( shutdown( fd, how ) )
5000 err = wsaErrno();
5001 goto error;
5005 release_sock_fd( s, fd );
5006 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
5007 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
5008 return 0;
5010 error:
5011 release_sock_fd( s, fd );
5012 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
5013 WSASetLastError( err );
5014 return SOCKET_ERROR;
5017 /***********************************************************************
5018 * socket (WS2_32.23)
5020 SOCKET WINAPI WS_socket(int af, int type, int protocol)
5022 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
5024 return WSASocketA( af, type, protocol, NULL, 0,
5025 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
5029 /***********************************************************************
5030 * gethostbyaddr (WS2_32.51)
5032 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
5034 struct WS_hostent *retval = NULL;
5035 struct hostent* host;
5037 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5038 char *extrabuf;
5039 int ebufsize=1024;
5040 struct hostent hostentry;
5041 int locerr=ENOBUFS;
5042 host = NULL;
5043 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
5044 while(extrabuf) {
5045 int res = gethostbyaddr_r(addr, len, type,
5046 &hostentry, extrabuf, ebufsize, &host, &locerr);
5047 if( res != ERANGE) break;
5048 ebufsize *=2;
5049 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
5051 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
5052 #else
5053 EnterCriticalSection( &csWSgetXXXbyYYY );
5054 host = gethostbyaddr(addr, len, type);
5055 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
5056 #endif
5057 if( host != NULL ) retval = WS_dup_he(host);
5058 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5059 HeapFree(GetProcessHeap(),0,extrabuf);
5060 #else
5061 LeaveCriticalSection( &csWSgetXXXbyYYY );
5062 #endif
5063 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
5064 return retval;
5067 /***********************************************************************
5068 * WS_get_local_ips (INTERNAL)
5070 * Returns the list of local IP addresses by going through the network
5071 * adapters and using the local routing table to sort the addresses
5072 * from highest routing priority to lowest routing priority. This
5073 * functionality is inferred from the description for obtaining local
5074 * IP addresses given in the Knowledge Base Article Q160215.
5076 * Please note that the returned hostent is only freed when the thread
5077 * closes and is replaced if another hostent is requested.
5079 static struct WS_hostent* WS_get_local_ips( char *hostname )
5081 int last_metric, numroutes = 0, i, j;
5082 DWORD n;
5083 PIP_ADAPTER_INFO adapters = NULL, k;
5084 struct WS_hostent *hostlist = NULL;
5085 PMIB_IPFORWARDTABLE routes = NULL;
5086 struct route *route_addrs = NULL;
5087 DWORD adap_size, route_size;
5089 /* Obtain the size of the adapter list and routing table, also allocate memory */
5090 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
5091 return NULL;
5092 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
5093 return NULL;
5094 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
5095 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
5096 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
5097 if (adapters == NULL || routes == NULL || route_addrs == NULL)
5098 goto cleanup;
5099 /* Obtain the adapter list and the full routing table */
5100 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
5101 goto cleanup;
5102 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
5103 goto cleanup;
5104 /* Store the interface associated with each route */
5105 for (n = 0; n < routes->dwNumEntries; n++)
5107 IF_INDEX ifindex;
5108 DWORD ifmetric;
5109 BOOL exists = FALSE;
5111 if (routes->table[n].u1.ForwardType != MIB_IPROUTE_TYPE_DIRECT)
5112 continue;
5113 ifindex = routes->table[n].dwForwardIfIndex;
5114 ifmetric = routes->table[n].dwForwardMetric1;
5115 /* Only store the lowest valued metric for an interface */
5116 for (j = 0; j < numroutes; j++)
5118 if (route_addrs[j].interface == ifindex)
5120 if (route_addrs[j].metric > ifmetric)
5121 route_addrs[j].metric = ifmetric;
5122 exists = TRUE;
5125 if (exists)
5126 continue;
5127 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
5128 if (route_addrs == NULL)
5129 goto cleanup; /* Memory allocation error, fail gracefully */
5130 route_addrs[numroutes].interface = ifindex;
5131 route_addrs[numroutes].metric = ifmetric;
5132 /* If no IP is found in the next step (for whatever reason)
5133 * then fall back to the magic loopback address.
5135 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
5136 numroutes++;
5138 if (numroutes == 0)
5139 goto cleanup; /* No routes, fall back to the Magic IP */
5140 /* Find the IP address associated with each found interface */
5141 for (i = 0; i < numroutes; i++)
5143 for (k = adapters; k != NULL; k = k->Next)
5145 char *ip = k->IpAddressList.IpAddress.String;
5147 if (route_addrs[i].interface == k->Index)
5148 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
5151 /* Allocate a hostent and enough memory for all the IPs,
5152 * including the NULL at the end of the list.
5154 hostlist = WS_create_he(hostname, 1, 0, numroutes+1, sizeof(struct in_addr));
5155 if (hostlist == NULL)
5156 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
5157 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
5158 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
5159 hostlist->h_addrtype = AF_INET;
5160 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
5161 /* Reorder the entries when placing them in the host list, Windows expects
5162 * the IP list in order from highest priority to lowest (the critical thing
5163 * is that most applications expect the first IP to be the default route).
5165 last_metric = -1;
5166 for (i = 0; i < numroutes; i++)
5168 struct in_addr addr;
5169 int metric = 0xFFFF;
5171 memcpy(&addr, magic_loopback_addr, 4);
5172 for (j = 0; j < numroutes; j++)
5174 int this_metric = route_addrs[j].metric;
5176 if (this_metric > last_metric && this_metric < metric)
5178 addr = route_addrs[j].addr;
5179 metric = this_metric;
5182 last_metric = metric;
5183 (*(struct in_addr *) hostlist->h_addr_list[i]) = addr;
5186 /* Cleanup all allocated memory except the address list,
5187 * the address list is used by the calling app.
5189 cleanup:
5190 HeapFree(GetProcessHeap(), 0, route_addrs);
5191 HeapFree(GetProcessHeap(), 0, adapters);
5192 HeapFree(GetProcessHeap(), 0, routes);
5193 return hostlist;
5196 /***********************************************************************
5197 * gethostbyname (WS2_32.52)
5199 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
5201 struct WS_hostent *retval = NULL;
5202 struct hostent* host;
5203 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5204 char *extrabuf;
5205 int ebufsize=1024;
5206 struct hostent hostentry;
5207 int locerr = ENOBUFS;
5208 #endif
5209 char hostname[100];
5210 if(!num_startup) {
5211 SetLastError(WSANOTINITIALISED);
5212 return NULL;
5214 if( gethostname( hostname, 100) == -1) {
5215 SetLastError( WSAENOBUFS); /* appropriate ? */
5216 return retval;
5218 if( !name || !name[0]) {
5219 name = hostname;
5221 /* If the hostname of the local machine is requested then return the
5222 * complete list of local IP addresses */
5223 if(strcmp(name, hostname) == 0)
5224 retval = WS_get_local_ips(hostname);
5225 /* If any other hostname was requested (or the routing table lookup failed)
5226 * then return the IP found by the host OS */
5227 if(retval == NULL)
5229 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5230 host = NULL;
5231 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
5232 while(extrabuf) {
5233 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
5234 if( res != ERANGE) break;
5235 ebufsize *=2;
5236 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
5238 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
5239 #else
5240 EnterCriticalSection( &csWSgetXXXbyYYY );
5241 host = gethostbyname(name);
5242 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
5243 #endif
5244 if (host) retval = WS_dup_he(host);
5245 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
5246 HeapFree(GetProcessHeap(),0,extrabuf);
5247 #else
5248 LeaveCriticalSection( &csWSgetXXXbyYYY );
5249 #endif
5251 if (retval && retval->h_addr_list[0][0] == 127 &&
5252 strcmp(name, "localhost") != 0)
5254 /* hostname != "localhost" but has loopback address. replace by our
5255 * special address.*/
5256 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
5258 TRACE( "%s ret %p\n", debugstr_a(name), retval );
5259 return retval;
5263 /***********************************************************************
5264 * getprotobyname (WS2_32.53)
5266 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
5268 struct WS_protoent* retval = NULL;
5269 #ifdef HAVE_GETPROTOBYNAME
5270 struct protoent* proto;
5271 EnterCriticalSection( &csWSgetXXXbyYYY );
5272 if( (proto = getprotobyname(name)) != NULL )
5274 retval = WS_dup_pe(proto);
5276 else {
5277 MESSAGE("protocol %s not found; You might want to add "
5278 "this to /etc/protocols\n", debugstr_a(name) );
5279 SetLastError(WSANO_DATA);
5281 LeaveCriticalSection( &csWSgetXXXbyYYY );
5282 #endif
5283 TRACE( "%s ret %p\n", debugstr_a(name), retval );
5284 return retval;
5288 /***********************************************************************
5289 * getprotobynumber (WS2_32.54)
5291 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
5293 struct WS_protoent* retval = NULL;
5294 #ifdef HAVE_GETPROTOBYNUMBER
5295 struct protoent* proto;
5296 EnterCriticalSection( &csWSgetXXXbyYYY );
5297 if( (proto = getprotobynumber(number)) != NULL )
5299 retval = WS_dup_pe(proto);
5301 else {
5302 MESSAGE("protocol number %d not found; You might want to add "
5303 "this to /etc/protocols\n", number );
5304 SetLastError(WSANO_DATA);
5306 LeaveCriticalSection( &csWSgetXXXbyYYY );
5307 #endif
5308 TRACE("%i ret %p\n", number, retval);
5309 return retval;
5313 /***********************************************************************
5314 * getservbyname (WS2_32.55)
5316 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
5318 struct WS_servent* retval = NULL;
5319 struct servent* serv;
5320 char *name_str;
5321 char *proto_str = NULL;
5323 if (!(name_str = strdup_lower(name))) return NULL;
5325 if (proto && *proto)
5327 if (!(proto_str = strdup_lower(proto)))
5329 HeapFree( GetProcessHeap(), 0, name_str );
5330 return NULL;
5334 EnterCriticalSection( &csWSgetXXXbyYYY );
5335 serv = getservbyname(name_str, proto_str);
5336 if( serv != NULL )
5338 retval = WS_dup_se(serv);
5340 else SetLastError(WSANO_DATA);
5341 LeaveCriticalSection( &csWSgetXXXbyYYY );
5342 HeapFree( GetProcessHeap(), 0, proto_str );
5343 HeapFree( GetProcessHeap(), 0, name_str );
5344 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
5345 return retval;
5348 /***********************************************************************
5349 * freeaddrinfo (WS2_32.@)
5351 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
5353 while (res) {
5354 struct WS_addrinfo *next;
5356 HeapFree(GetProcessHeap(),0,res->ai_canonname);
5357 HeapFree(GetProcessHeap(),0,res->ai_addr);
5358 next = res->ai_next;
5359 HeapFree(GetProcessHeap(),0,res);
5360 res = next;
5364 /* helper functions for getaddrinfo()/getnameinfo() */
5365 static int convert_aiflag_w2u(int winflags) {
5366 unsigned int i;
5367 int unixflags = 0;
5369 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
5370 if (ws_aiflag_map[i][0] & winflags) {
5371 unixflags |= ws_aiflag_map[i][1];
5372 winflags &= ~ws_aiflag_map[i][0];
5374 if (winflags)
5375 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
5376 return unixflags;
5379 static int convert_niflag_w2u(int winflags) {
5380 unsigned int i;
5381 int unixflags = 0;
5383 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
5384 if (ws_niflag_map[i][0] & winflags) {
5385 unixflags |= ws_niflag_map[i][1];
5386 winflags &= ~ws_niflag_map[i][0];
5388 if (winflags)
5389 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
5390 return unixflags;
5393 static int convert_aiflag_u2w(int unixflags) {
5394 unsigned int i;
5395 int winflags = 0;
5397 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
5398 if (ws_aiflag_map[i][1] & unixflags) {
5399 winflags |= ws_aiflag_map[i][0];
5400 unixflags &= ~ws_aiflag_map[i][1];
5402 if (unixflags) /* will warn usually */
5403 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
5404 return winflags;
5407 static int convert_eai_u2w(int unixret) {
5408 int i;
5410 if (!unixret) return 0;
5412 for (i=0;ws_eai_map[i][0];i++)
5413 if (ws_eai_map[i][1] == unixret)
5414 return ws_eai_map[i][0];
5416 if (unixret == EAI_SYSTEM)
5417 /* There are broken versions of glibc which return EAI_SYSTEM
5418 * and set errno to 0 instead of returning EAI_NONAME.
5420 return errno ? sock_get_error( errno ) : WS_EAI_NONAME;
5422 FIXME("Unhandled unix EAI_xxx ret %d\n", unixret);
5423 return unixret;
5426 static char *get_hostname(void)
5428 char *ret;
5429 DWORD size = 0;
5431 GetComputerNameExA( ComputerNamePhysicalDnsHostname, NULL, &size );
5432 if (GetLastError() != ERROR_MORE_DATA) return NULL;
5433 if (!(ret = HeapAlloc( GetProcessHeap(), 0, size ))) return NULL;
5434 if (!GetComputerNameExA( ComputerNamePhysicalDnsHostname, ret, &size ))
5436 HeapFree( GetProcessHeap(), 0, ret );
5437 return NULL;
5439 return ret;
5442 /***********************************************************************
5443 * getaddrinfo (WS2_32.@)
5445 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
5447 #ifdef HAVE_GETADDRINFO
5448 struct addrinfo *unixaires = NULL;
5449 int result;
5450 struct addrinfo unixhints, *punixhints = NULL;
5451 char *hostname = NULL;
5452 const char *node;
5454 *res = NULL;
5455 if (!nodename && !servname) return WSAHOST_NOT_FOUND;
5457 if (!nodename)
5458 node = NULL;
5459 else if (!nodename[0])
5461 node = hostname = get_hostname();
5462 if (!node) return WSA_NOT_ENOUGH_MEMORY;
5464 else
5465 node = nodename;
5467 if (hints) {
5468 punixhints = &unixhints;
5470 memset(&unixhints, 0, sizeof(unixhints));
5471 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
5473 /* zero is a wildcard, no need to convert */
5474 if (hints->ai_family)
5475 punixhints->ai_family = convert_af_w2u(hints->ai_family);
5476 if (hints->ai_socktype)
5477 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
5478 if (hints->ai_protocol)
5479 punixhints->ai_protocol = max(convert_proto_w2u(hints->ai_protocol), 0);
5481 if (punixhints->ai_socktype < 0)
5483 WSASetLastError(WSAESOCKTNOSUPPORT);
5484 HeapFree(GetProcessHeap(), 0, hostname);
5485 return SOCKET_ERROR;
5488 /* windows allows invalid combinations of socket type and protocol, unix does not.
5489 * fix the parameters here to make getaddrinfo call always work */
5490 if (punixhints->ai_protocol == IPPROTO_TCP &&
5491 punixhints->ai_socktype != SOCK_STREAM && punixhints->ai_socktype != SOCK_SEQPACKET)
5492 punixhints->ai_socktype = 0;
5494 else if (punixhints->ai_protocol == IPPROTO_UDP && punixhints->ai_socktype != SOCK_DGRAM)
5495 punixhints->ai_socktype = 0;
5497 else if (IS_IPX_PROTO(punixhints->ai_protocol) && punixhints->ai_socktype != SOCK_DGRAM)
5498 punixhints->ai_socktype = 0;
5501 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
5502 result = getaddrinfo(node, servname, punixhints, &unixaires);
5504 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
5505 HeapFree(GetProcessHeap(), 0, hostname);
5507 if (!result) {
5508 struct addrinfo *xuai = unixaires;
5509 struct WS_addrinfo **xai = res;
5511 *xai = NULL;
5512 while (xuai) {
5513 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
5514 SIZE_T len;
5516 if (!ai)
5517 goto outofmem;
5519 *xai = ai;xai = &ai->ai_next;
5520 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
5521 ai->ai_family = convert_af_u2w(xuai->ai_family);
5522 /* copy whatever was sent in the hints */
5523 if(hints) {
5524 ai->ai_socktype = hints->ai_socktype;
5525 ai->ai_protocol = hints->ai_protocol;
5526 } else {
5527 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
5528 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
5530 if (xuai->ai_canonname) {
5531 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
5532 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
5533 if (!ai->ai_canonname)
5534 goto outofmem;
5535 strcpy(ai->ai_canonname,xuai->ai_canonname);
5537 len = xuai->ai_addrlen;
5538 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
5539 if (!ai->ai_addr)
5540 goto outofmem;
5541 ai->ai_addrlen = len;
5542 do {
5543 int winlen = ai->ai_addrlen;
5545 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
5546 ai->ai_addrlen = winlen;
5547 break;
5549 len = 2*len;
5550 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
5551 if (!ai->ai_addr)
5552 goto outofmem;
5553 ai->ai_addrlen = len;
5554 } while (1);
5555 xuai = xuai->ai_next;
5557 freeaddrinfo(unixaires);
5559 if (TRACE_ON(winsock))
5561 struct WS_addrinfo *ai = *res;
5562 while (ai)
5564 TRACE("=> %p, flags %#x, family %d, type %d, protocol %d, len %ld, name %s, addr %s\n",
5565 ai, ai->ai_flags, ai->ai_family, ai->ai_socktype, ai->ai_protocol, ai->ai_addrlen,
5566 ai->ai_canonname, debugstr_sockaddr(ai->ai_addr));
5567 ai = ai->ai_next;
5570 } else
5571 result = convert_eai_u2w(result);
5573 return result;
5575 outofmem:
5576 if (*res) WS_freeaddrinfo(*res);
5577 if (unixaires) freeaddrinfo(unixaires);
5578 return WSA_NOT_ENOUGH_MEMORY;
5579 #else
5580 FIXME("getaddrinfo() failed, not found during buildtime.\n");
5581 return EAI_FAIL;
5582 #endif
5585 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
5587 struct WS_addrinfoW *ret;
5589 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
5590 ret->ai_flags = ai->ai_flags;
5591 ret->ai_family = ai->ai_family;
5592 ret->ai_socktype = ai->ai_socktype;
5593 ret->ai_protocol = ai->ai_protocol;
5594 ret->ai_addrlen = ai->ai_addrlen;
5595 ret->ai_canonname = NULL;
5596 ret->ai_addr = NULL;
5597 ret->ai_next = NULL;
5598 if (ai->ai_canonname)
5600 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
5601 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
5603 HeapFree(GetProcessHeap(), 0, ret);
5604 return NULL;
5606 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
5608 if (ai->ai_addr)
5610 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
5612 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
5613 HeapFree(GetProcessHeap(), 0, ret);
5614 return NULL;
5616 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
5618 return ret;
5621 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
5623 struct WS_addrinfoW *ret, *infoW;
5625 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
5626 while (info->ai_next)
5628 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
5630 FreeAddrInfoW(ret);
5631 return NULL;
5633 infoW = infoW->ai_next;
5634 info = info->ai_next;
5636 return ret;
5639 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
5641 struct WS_addrinfo *ret;
5643 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
5644 ret->ai_flags = ai->ai_flags;
5645 ret->ai_family = ai->ai_family;
5646 ret->ai_socktype = ai->ai_socktype;
5647 ret->ai_protocol = ai->ai_protocol;
5648 ret->ai_addrlen = ai->ai_addrlen;
5649 ret->ai_canonname = NULL;
5650 ret->ai_addr = NULL;
5651 ret->ai_next = NULL;
5652 if (ai->ai_canonname)
5654 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
5655 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
5657 HeapFree(GetProcessHeap(), 0, ret);
5658 return NULL;
5660 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
5662 if (ai->ai_addr)
5664 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
5666 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
5667 HeapFree(GetProcessHeap(), 0, ret);
5668 return NULL;
5670 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
5672 return ret;
5675 /***********************************************************************
5676 * GetAddrInfoW (WS2_32.@)
5678 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
5680 int ret, len;
5681 char *nodenameA = NULL, *servnameA = NULL;
5682 struct WS_addrinfo *resA, *hintsA = NULL;
5684 *res = NULL;
5685 if (nodename)
5687 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
5688 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
5689 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
5691 if (servname)
5693 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
5694 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
5696 HeapFree(GetProcessHeap(), 0, nodenameA);
5697 return EAI_MEMORY;
5699 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
5702 if (hints) hintsA = addrinfo_WtoA(hints);
5703 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
5704 WS_freeaddrinfo(hintsA);
5706 if (!ret)
5708 *res = addrinfo_list_AtoW(resA);
5709 WS_freeaddrinfo(resA);
5712 HeapFree(GetProcessHeap(), 0, nodenameA);
5713 HeapFree(GetProcessHeap(), 0, servnameA);
5714 return ret;
5717 /***********************************************************************
5718 * FreeAddrInfoW (WS2_32.@)
5720 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
5722 while (ai)
5724 ADDRINFOW *next;
5725 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
5726 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
5727 next = ai->ai_next;
5728 HeapFree(GetProcessHeap(), 0, ai);
5729 ai = next;
5733 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
5734 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
5736 #ifdef HAVE_GETNAMEINFO
5737 int ret;
5738 union generic_unix_sockaddr sa_u;
5739 unsigned int size;
5741 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
5742 serv, servlen, flags);
5744 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
5745 if (!size)
5747 WSASetLastError(WSAEFAULT);
5748 return WSA_NOT_ENOUGH_MEMORY;
5750 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
5751 return convert_eai_u2w(ret);
5752 #else
5753 FIXME("getnameinfo() failed, not found during buildtime.\n");
5754 return EAI_FAIL;
5755 #endif
5758 int WINAPI GetNameInfoW(const SOCKADDR *sa, WS_socklen_t salen, PWCHAR host,
5759 DWORD hostlen, PWCHAR serv, DWORD servlen, INT flags)
5761 int ret;
5762 char *hostA = NULL, *servA = NULL;
5764 if (host && (!(hostA = HeapAlloc(GetProcessHeap(), 0, hostlen)))) return EAI_MEMORY;
5765 if (serv && (!(servA = HeapAlloc(GetProcessHeap(), 0, servlen))))
5767 HeapFree(GetProcessHeap(), 0, hostA);
5768 return EAI_MEMORY;
5771 ret = WS_getnameinfo(sa, salen, hostA, hostlen, servA, servlen, flags);
5772 if (!ret)
5774 if (host) MultiByteToWideChar(CP_ACP, 0, hostA, -1, host, hostlen);
5775 if (serv) MultiByteToWideChar(CP_ACP, 0, servA, -1, serv, servlen);
5778 HeapFree(GetProcessHeap(), 0, hostA);
5779 HeapFree(GetProcessHeap(), 0, servA);
5780 return ret;
5783 /***********************************************************************
5784 * getservbyport (WS2_32.56)
5786 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
5788 struct WS_servent* retval = NULL;
5789 #ifdef HAVE_GETSERVBYPORT
5790 struct servent* serv;
5791 char *proto_str = NULL;
5793 if (proto && *proto)
5795 if (!(proto_str = strdup_lower(proto))) return NULL;
5797 EnterCriticalSection( &csWSgetXXXbyYYY );
5798 if( (serv = getservbyport(port, proto_str)) != NULL ) {
5799 retval = WS_dup_se(serv);
5801 else SetLastError(WSANO_DATA);
5802 LeaveCriticalSection( &csWSgetXXXbyYYY );
5803 HeapFree( GetProcessHeap(), 0, proto_str );
5804 #endif
5805 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
5806 return retval;
5810 /***********************************************************************
5811 * gethostname (WS2_32.57)
5813 int WINAPI WS_gethostname(char *name, int namelen)
5815 TRACE("name %p, len %d\n", name, namelen);
5817 if (gethostname(name, namelen) == 0)
5819 TRACE("<- '%s'\n", name);
5820 return 0;
5822 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
5823 TRACE("<- ERROR !\n");
5824 return SOCKET_ERROR;
5828 /* ------------------------------------- Windows sockets extensions -- *
5830 * ------------------------------------------------------------------- */
5832 /***********************************************************************
5833 * WSAEnumNetworkEvents (WS2_32.36)
5835 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
5837 int ret;
5838 int i;
5839 int errors[FD_MAX_EVENTS];
5841 TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
5843 SERVER_START_REQ( get_socket_event )
5845 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5846 req->service = TRUE;
5847 req->c_event = wine_server_obj_handle( hEvent );
5848 wine_server_set_reply( req, errors, sizeof(errors) );
5849 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
5851 SERVER_END_REQ;
5852 if (!ret)
5854 for (i = 0; i < FD_MAX_EVENTS; i++)
5855 lpEvent->iErrorCode[i] = NtStatusToWSAError(errors[i]);
5856 return 0;
5858 SetLastError(WSAEINVAL);
5859 return SOCKET_ERROR;
5862 /***********************************************************************
5863 * WSAEventSelect (WS2_32.39)
5865 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
5867 int ret;
5869 TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
5871 SERVER_START_REQ( set_socket_event )
5873 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5874 req->mask = lEvent;
5875 req->event = wine_server_obj_handle( hEvent );
5876 req->window = 0;
5877 req->msg = 0;
5878 ret = wine_server_call( req );
5880 SERVER_END_REQ;
5881 if (!ret) return 0;
5882 SetLastError(WSAEINVAL);
5883 return SOCKET_ERROR;
5886 /**********************************************************************
5887 * WSAGetOverlappedResult (WS2_32.40)
5889 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
5890 LPDWORD lpcbTransfer, BOOL fWait,
5891 LPDWORD lpdwFlags )
5893 NTSTATUS status;
5895 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
5896 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
5898 if ( lpOverlapped == NULL )
5900 ERR( "Invalid pointer\n" );
5901 WSASetLastError(WSA_INVALID_PARAMETER);
5902 return FALSE;
5905 status = lpOverlapped->Internal;
5906 if (status == STATUS_PENDING)
5908 if (!fWait)
5910 SetLastError( WSA_IO_INCOMPLETE );
5911 return FALSE;
5914 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
5915 INFINITE ) == WAIT_FAILED)
5916 return FALSE;
5917 status = lpOverlapped->Internal;
5920 if ( lpcbTransfer )
5921 *lpcbTransfer = lpOverlapped->InternalHigh;
5923 if ( lpdwFlags )
5924 *lpdwFlags = lpOverlapped->u.s.Offset;
5926 if (status) SetLastError( RtlNtStatusToDosError(status) );
5927 return !status;
5931 /***********************************************************************
5932 * WSAAsyncSelect (WS2_32.101)
5934 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
5936 int ret;
5938 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
5940 SERVER_START_REQ( set_socket_event )
5942 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5943 req->mask = lEvent;
5944 req->event = 0;
5945 req->window = wine_server_user_handle( hWnd );
5946 req->msg = uMsg;
5947 ret = wine_server_call( req );
5949 SERVER_END_REQ;
5950 if (!ret) return 0;
5951 SetLastError(WSAEINVAL);
5952 return SOCKET_ERROR;
5955 /***********************************************************************
5956 * WSACreateEvent (WS2_32.31)
5959 WSAEVENT WINAPI WSACreateEvent(void)
5961 /* Create a manual-reset event, with initial state: unsignaled */
5962 TRACE("\n");
5964 return CreateEventW(NULL, TRUE, FALSE, NULL);
5967 /***********************************************************************
5968 * WSACloseEvent (WS2_32.29)
5971 BOOL WINAPI WSACloseEvent(WSAEVENT event)
5973 TRACE ("event=%p\n", event);
5975 return CloseHandle(event);
5978 /***********************************************************************
5979 * WSASocketA (WS2_32.78)
5982 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
5983 LPWSAPROTOCOL_INFOA lpProtocolInfo,
5984 GROUP g, DWORD dwFlags)
5986 INT len;
5987 WSAPROTOCOL_INFOW info;
5989 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
5990 af, type, protocol, lpProtocolInfo, g, dwFlags);
5992 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
5994 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
5995 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
5996 info.szProtocol, WSAPROTOCOL_LEN + 1);
5998 if (!len)
6000 WSASetLastError( WSAEINVAL);
6001 return SOCKET_ERROR;
6004 return WSASocketW(af, type, protocol, &info, g, dwFlags);
6007 /***********************************************************************
6008 * WSASocketW (WS2_32.79)
6011 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
6012 LPWSAPROTOCOL_INFOW lpProtocolInfo,
6013 GROUP g, DWORD dwFlags)
6015 SOCKET ret;
6016 DWORD err;
6017 int unixaf, unixtype, ipxptype = -1;
6020 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
6021 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
6024 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
6025 af, type, protocol, lpProtocolInfo, g, dwFlags );
6027 if (!num_startup)
6029 err = WSANOTINITIALISED;
6030 goto done;
6033 /* hack for WSADuplicateSocket */
6034 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
6035 ret = lpProtocolInfo->dwServiceFlags3;
6036 TRACE("\tgot duplicate %04lx\n", ret);
6037 return ret;
6040 if (lpProtocolInfo)
6042 if (af == FROM_PROTOCOL_INFO || !af)
6043 af = lpProtocolInfo->iAddressFamily;
6044 if (type == FROM_PROTOCOL_INFO || !type)
6045 type = lpProtocolInfo->iSocketType;
6046 if (protocol == FROM_PROTOCOL_INFO || !protocol)
6047 protocol = lpProtocolInfo->iProtocol;
6050 if (!type && (af || protocol))
6052 int autoproto = protocol;
6053 WSAPROTOCOL_INFOW infow;
6055 /* default to the first valid protocol */
6056 if (!autoproto)
6057 autoproto = valid_protocols[0];
6058 else if(IS_IPX_PROTO(autoproto))
6059 autoproto = WS_NSPROTO_IPX;
6061 if (WS_EnterSingleProtocolW(autoproto, &infow))
6063 type = infow.iSocketType;
6065 /* after win2003 it's no longer possible to pass AF_UNSPEC
6066 using the protocol info struct */
6067 if (!lpProtocolInfo && af == WS_AF_UNSPEC)
6068 af = infow.iAddressFamily;
6073 Windows has an extension to the IPX protocol that allows to create sockets
6074 and set the IPX packet type at the same time, to do that a caller will use
6075 a protocol like NSPROTO_IPX + <PACKET TYPE>
6077 if (IS_IPX_PROTO(protocol))
6078 ipxptype = protocol - WS_NSPROTO_IPX;
6080 /* convert the socket family, type and protocol */
6081 unixaf = convert_af_w2u(af);
6082 unixtype = convert_socktype_w2u(type);
6083 protocol = convert_proto_w2u(protocol);
6084 if (unixaf == AF_UNSPEC) unixaf = -1;
6086 /* filter invalid parameters */
6087 if (protocol < 0)
6089 /* the type could not be converted */
6090 if (type && unixtype < 0)
6092 err = WSAESOCKTNOSUPPORT;
6093 goto done;
6096 err = WSAEPROTONOSUPPORT;
6097 goto done;
6099 if (unixaf < 0)
6101 /* both family and protocol can't be invalid */
6102 if (protocol <= 0)
6104 err = WSAEINVAL;
6105 goto done;
6108 /* family could not be converted and neither socket type */
6109 if (unixtype < 0 && af >= 0)
6112 err = WSAESOCKTNOSUPPORT;
6113 goto done;
6116 err = WSAEAFNOSUPPORT;
6117 goto done;
6120 SERVER_START_REQ( create_socket )
6122 req->family = unixaf;
6123 req->type = unixtype;
6124 req->protocol = protocol;
6125 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
6126 req->attributes = OBJ_INHERIT;
6127 req->flags = dwFlags;
6128 set_error( wine_server_call( req ) );
6129 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
6131 SERVER_END_REQ;
6132 if (ret)
6134 TRACE("\tcreated %04lx\n", ret );
6135 if (ipxptype > 0)
6136 set_ipx_packettype(ret, ipxptype);
6137 return ret;
6140 err = GetLastError();
6141 if (err == WSAEACCES) /* raw socket denied */
6143 if (type == SOCK_RAW)
6144 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
6145 else
6146 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
6148 else
6150 /* invalid combination of valid parameters, like SOCK_STREAM + IPPROTO_UDP */
6151 if (err == WSAEINVAL)
6152 err = WSAESOCKTNOSUPPORT;
6153 else if (err == WSAEOPNOTSUPP)
6154 err = WSAEPROTONOSUPPORT;
6157 done:
6158 WARN("\t\tfailed, error %d!\n", err);
6159 SetLastError(err);
6160 return INVALID_SOCKET;
6163 /***********************************************************************
6164 * WSAJoinLeaf (WS2_32.58)
6167 SOCKET WINAPI WSAJoinLeaf(
6168 SOCKET s,
6169 const struct WS_sockaddr *addr,
6170 int addrlen,
6171 LPWSABUF lpCallerData,
6172 LPWSABUF lpCalleeData,
6173 LPQOS lpSQOS,
6174 LPQOS lpGQOS,
6175 DWORD dwFlags)
6177 FIXME("stub.\n");
6178 return INVALID_SOCKET;
6181 /***********************************************************************
6182 * __WSAFDIsSet (WS2_32.151)
6184 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
6186 int i = set->fd_count;
6188 TRACE("(%ld,%p(%i))\n", s, set, i);
6190 while (i--)
6191 if (set->fd_array[i] == s) return 1;
6192 return 0;
6195 /***********************************************************************
6196 * WSAIsBlocking (WS2_32.114)
6198 BOOL WINAPI WSAIsBlocking(void)
6200 /* By default WinSock should set all its sockets to non-blocking mode
6201 * and poll in PeekMessage loop when processing "blocking" ones. This
6202 * function is supposed to tell if the program is in this loop. Our
6203 * blocking calls are truly blocking so we always return FALSE.
6205 * Note: It is allowed to call this function without prior WSAStartup().
6208 TRACE("\n");
6209 return FALSE;
6212 /***********************************************************************
6213 * WSACancelBlockingCall (WS2_32.113)
6215 INT WINAPI WSACancelBlockingCall(void)
6217 TRACE("\n");
6218 return 0;
6221 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
6223 FIXME("How was this called?\n");
6224 return x();
6228 /***********************************************************************
6229 * WSASetBlockingHook (WS2_32.109)
6231 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
6233 FARPROC prev = blocking_hook;
6234 blocking_hook = lpBlockFunc;
6235 TRACE("hook %p\n", lpBlockFunc);
6236 return prev;
6240 /***********************************************************************
6241 * WSAUnhookBlockingHook (WS2_32.110)
6243 INT WINAPI WSAUnhookBlockingHook(void)
6245 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
6246 return 0;
6250 /* ----------------------------------- end of API stuff */
6252 /* ----------------------------------- helper functions -
6254 * TODO: Merge WS_dup_..() stuff into one function that
6255 * would operate with a generic structure containing internal
6256 * pointers (via a template of some kind).
6259 static int list_size(char** l, int item_size)
6261 int i,j = 0;
6262 if(l)
6263 { for(i=0;l[i];i++)
6264 j += (item_size) ? item_size : strlen(l[i]) + 1;
6265 j += (i + 1) * sizeof(char*); }
6266 return j;
6269 static int list_dup(char** l_src, char** l_to, int item_size)
6271 char *p;
6272 int i;
6274 for (i = 0; l_src[i]; i++) ;
6275 p = (char *)(l_to + i + 1);
6276 for (i = 0; l_src[i]; i++)
6278 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
6279 memcpy(p, l_src[i], count);
6280 l_to[i] = p;
6281 p += count;
6283 l_to[i] = NULL;
6284 return p - (char *)l_to;
6287 /* ----- hostent */
6289 /* create a hostent entry
6291 * Creates the entry with enough memory for the name, aliases
6292 * addresses, and the address pointers. Also copies the name
6293 * and sets up all the pointers.
6295 * NOTE: The alias and address lists must be allocated with room
6296 * for the NULL item terminating the list. This is true even if
6297 * the list has no items ("aliases" and "addresses" must be
6298 * at least "1", a truly empty list is invalid).
6300 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length)
6302 struct WS_hostent *p_to;
6303 char *p;
6304 int size = (sizeof(struct WS_hostent) +
6305 strlen(name) + 1 +
6306 sizeof(char *) * aliases +
6307 aliases_size +
6308 sizeof(char *) * addresses +
6309 address_length * (addresses - 1)), i;
6311 if (!(p_to = check_buffer_he(size))) return NULL;
6312 memset(p_to, 0, size);
6314 /* Use the memory in the same way winsock does.
6315 * First set the pointer for aliases, second set the pointers for addresses.
6316 * Third fill the addresses indexes, fourth jump aliases names size.
6317 * Fifth fill the hostname.
6318 * NOTE: This method is valid for OS version's >= XP.
6320 p = (char *)(p_to + 1);
6321 p_to->h_aliases = (char **)p;
6322 p += sizeof(char *)*aliases;
6324 p_to->h_addr_list = (char **)p;
6325 p += sizeof(char *)*addresses;
6327 for (i = 0, addresses--; i < addresses; i++, p += address_length)
6328 p_to->h_addr_list[i] = p;
6330 /* NOTE: h_aliases must be filled in manually because we don't know each string
6331 * size, leave these pointers NULL (already set to NULL by memset earlier).
6333 p += aliases_size;
6335 p_to->h_name = p;
6336 strcpy(p, name);
6338 return p_to;
6341 /* duplicate hostent entry
6342 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
6343 * Ditto for protoent and servent.
6345 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
6347 int i, addresses = 0, alias_size = 0;
6348 struct WS_hostent *p_to;
6349 char *p;
6351 for( i = 0; p_he->h_aliases[i]; i++) alias_size += strlen(p_he->h_aliases[i]) + 1;
6352 while (p_he->h_addr_list[addresses]) addresses++;
6354 p_to = WS_create_he(p_he->h_name, i + 1, alias_size, addresses + 1, p_he->h_length);
6356 if (!p_to) return NULL;
6357 p_to->h_addrtype = p_he->h_addrtype;
6358 p_to->h_length = p_he->h_length;
6360 for(i = 0, p = p_to->h_addr_list[0]; p_he->h_addr_list[i]; i++, p += p_to->h_length)
6361 memcpy(p, p_he->h_addr_list[i], p_to->h_length);
6363 /* Fill the aliases after the IP data */
6364 for(i = 0; p_he->h_aliases[i]; i++)
6366 p_to->h_aliases[i] = p;
6367 strcpy(p, p_he->h_aliases[i]);
6368 p += strlen(p) + 1;
6371 return p_to;
6374 /* ----- protoent */
6376 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
6378 char *p;
6379 struct WS_protoent *p_to;
6381 int size = (sizeof(*p_pe) +
6382 strlen(p_pe->p_name) + 1 +
6383 list_size(p_pe->p_aliases, 0));
6385 if (!(p_to = check_buffer_pe(size))) return NULL;
6386 p_to->p_proto = p_pe->p_proto;
6388 p = (char *)(p_to + 1);
6389 p_to->p_name = p;
6390 strcpy(p, p_pe->p_name);
6391 p += strlen(p) + 1;
6393 p_to->p_aliases = (char **)p;
6394 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
6395 return p_to;
6398 /* ----- servent */
6400 static struct WS_servent *WS_dup_se(const struct servent* p_se)
6402 char *p;
6403 struct WS_servent *p_to;
6405 int size = (sizeof(*p_se) +
6406 strlen(p_se->s_proto) + 1 +
6407 strlen(p_se->s_name) + 1 +
6408 list_size(p_se->s_aliases, 0));
6410 if (!(p_to = check_buffer_se(size))) return NULL;
6411 p_to->s_port = p_se->s_port;
6413 p = (char *)(p_to + 1);
6414 p_to->s_name = p;
6415 strcpy(p, p_se->s_name);
6416 p += strlen(p) + 1;
6418 p_to->s_proto = p;
6419 strcpy(p, p_se->s_proto);
6420 p += strlen(p) + 1;
6422 p_to->s_aliases = (char **)p;
6423 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
6424 return p_to;
6428 /***********************************************************************
6429 * WSARecv (WS2_32.67)
6431 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6432 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
6433 LPWSAOVERLAPPED lpOverlapped,
6434 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
6436 return WS2_recv_base(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
6437 NULL, NULL, lpOverlapped, lpCompletionRoutine, NULL);
6440 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6441 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
6442 struct WS_sockaddr *lpFrom,
6443 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
6444 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
6445 LPWSABUF lpControlBuffer )
6447 unsigned int i, options;
6448 int n, fd, err;
6449 struct ws2_async *wsa;
6450 BOOL is_blocking;
6451 DWORD timeout_start = GetTickCount();
6452 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
6454 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
6455 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
6456 (lpFromlen ? *lpFromlen : -1),
6457 lpOverlapped, lpCompletionRoutine);
6459 fd = get_sock_fd( s, FILE_READ_DATA, &options );
6460 TRACE( "fd=%d, options=%x\n", fd, options );
6462 if (fd == -1) return SOCKET_ERROR;
6464 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
6466 err = WSAEFAULT;
6467 goto error;
6470 wsa->hSocket = SOCKET2HANDLE(s);
6471 wsa->flags = *lpFlags;
6472 wsa->lpFlags = lpFlags;
6473 wsa->addr = lpFrom;
6474 wsa->addrlen.ptr = lpFromlen;
6475 wsa->control = lpControlBuffer;
6476 wsa->n_iovecs = dwBufferCount;
6477 wsa->first_iovec = 0;
6478 for (i = 0; i < dwBufferCount; i++)
6480 /* check buffer first to trigger write watches */
6481 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
6483 err = WSAEFAULT;
6484 goto error;
6486 wsa->iovec[i].iov_base = lpBuffers[i].buf;
6487 wsa->iovec[i].iov_len = lpBuffers[i].len;
6490 for (;;)
6492 n = WS2_recv( fd, wsa );
6493 if (n == -1)
6495 if (errno == EINTR) continue;
6496 if (errno != EAGAIN)
6498 int loc_errno = errno;
6499 err = wsaErrno();
6500 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
6501 goto error;
6504 else if (lpNumberOfBytesRecvd) *lpNumberOfBytesRecvd = n;
6506 if ((lpOverlapped || lpCompletionRoutine) &&
6507 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
6509 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
6511 wsa->user_overlapped = lpOverlapped;
6512 wsa->completion_func = lpCompletionRoutine;
6513 release_sock_fd( s, fd );
6515 if (n == -1)
6517 iosb->u.Status = STATUS_PENDING;
6518 iosb->Information = 0;
6520 SERVER_START_REQ( register_async )
6522 req->type = ASYNC_TYPE_READ;
6523 req->async.handle = wine_server_obj_handle( wsa->hSocket );
6524 req->async.callback = wine_server_client_ptr( WS2_async_recv );
6525 req->async.iosb = wine_server_client_ptr( iosb );
6526 req->async.arg = wine_server_client_ptr( wsa );
6527 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
6528 req->async.cvalue = cvalue;
6529 err = wine_server_call( req );
6531 SERVER_END_REQ;
6533 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
6534 WSASetLastError( NtStatusToWSAError( err ));
6535 return SOCKET_ERROR;
6538 iosb->u.Status = STATUS_SUCCESS;
6539 iosb->Information = n;
6540 if (!wsa->completion_func)
6542 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
6543 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
6544 HeapFree( GetProcessHeap(), 0, wsa );
6546 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
6547 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
6548 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6549 return 0;
6552 if (n != -1) break;
6554 if ((err = _is_blocking( s, &is_blocking )))
6556 err = NtStatusToWSAError( err );
6557 goto error;
6560 if ( is_blocking )
6562 struct pollfd pfd;
6563 int timeout = GET_RCVTIMEO(fd);
6564 if (timeout != -1)
6566 timeout -= GetTickCount() - timeout_start;
6567 if (timeout < 0) timeout = 0;
6570 pfd.fd = fd;
6571 pfd.events = POLLIN;
6572 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
6574 if (!timeout || !poll( &pfd, 1, timeout ))
6576 err = WSAETIMEDOUT;
6577 /* a timeout is not fatal */
6578 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6579 goto error;
6582 else
6584 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6585 err = WSAEWOULDBLOCK;
6586 goto error;
6590 TRACE(" -> %i bytes\n", n);
6591 HeapFree( GetProcessHeap(), 0, wsa );
6592 release_sock_fd( s, fd );
6593 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6595 return 0;
6597 error:
6598 HeapFree( GetProcessHeap(), 0, wsa );
6599 release_sock_fd( s, fd );
6600 WARN(" -> ERROR %d\n", err);
6601 WSASetLastError( err );
6602 return SOCKET_ERROR;
6605 /***********************************************************************
6606 * WSARecvFrom (WS2_32.69)
6608 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6609 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
6610 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
6611 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
6614 return WS2_recv_base( s, lpBuffers, dwBufferCount,
6615 lpNumberOfBytesRecvd, lpFlags,
6616 lpFrom, lpFromlen,
6617 lpOverlapped, lpCompletionRoutine, NULL );
6620 /***********************************************************************
6621 * WSCInstallProvider (WS2_32.88)
6623 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
6624 LPCWSTR lpszProviderDllPath,
6625 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
6626 DWORD dwNumberOfEntries,
6627 LPINT lpErrno )
6629 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
6630 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
6631 dwNumberOfEntries, lpErrno);
6632 *lpErrno = 0;
6633 return 0;
6637 /***********************************************************************
6638 * WSCDeinstallProvider (WS2_32.83)
6640 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
6642 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
6643 *lpErrno = 0;
6644 return 0;
6648 /***********************************************************************
6649 * WSAAccept (WS2_32.26)
6651 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
6652 LPCONDITIONPROC lpfnCondition, DWORD_PTR dwCallbackData)
6655 int ret = 0, size;
6656 WSABUF CallerId, CallerData, CalleeId, CalleeData;
6657 /* QOS SQOS, GQOS; */
6658 GROUP g;
6659 SOCKET cs;
6660 SOCKADDR src_addr, dst_addr;
6662 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
6663 s, addr, addrlen, lpfnCondition, dwCallbackData);
6665 cs = WS_accept(s, addr, addrlen);
6666 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
6667 if (!lpfnCondition) return cs;
6669 if (addr && addrlen)
6671 CallerId.buf = (char *)addr;
6672 CallerId.len = *addrlen;
6674 else
6676 size = sizeof(src_addr);
6677 WS_getpeername(cs, &src_addr, &size);
6678 CallerId.buf = (char *)&src_addr;
6679 CallerId.len = size;
6681 CallerData.buf = NULL;
6682 CallerData.len = 0;
6684 size = sizeof(dst_addr);
6685 WS_getsockname(cs, &dst_addr, &size);
6687 CalleeId.buf = (char *)&dst_addr;
6688 CalleeId.len = sizeof(dst_addr);
6690 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
6691 &CalleeId, &CalleeData, &g, dwCallbackData);
6693 switch (ret)
6695 case CF_ACCEPT:
6696 return cs;
6697 case CF_DEFER:
6698 SERVER_START_REQ( set_socket_deferred )
6700 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6701 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
6702 if ( !wine_server_call_err ( req ) )
6704 SetLastError( WSATRY_AGAIN );
6705 WS_closesocket( cs );
6708 SERVER_END_REQ;
6709 return SOCKET_ERROR;
6710 case CF_REJECT:
6711 WS_closesocket(cs);
6712 SetLastError(WSAECONNREFUSED);
6713 return SOCKET_ERROR;
6714 default:
6715 FIXME("Unknown return type from Condition function\n");
6716 SetLastError(WSAENOTSOCK);
6717 return SOCKET_ERROR;
6721 /***********************************************************************
6722 * WSADuplicateSocketA (WS2_32.32)
6724 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
6726 return WS_DuplicateSocket(FALSE, s, dwProcessId, (LPWSAPROTOCOL_INFOW) lpProtocolInfo);
6729 /***********************************************************************
6730 * WSADuplicateSocketW (WS2_32.33)
6732 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
6734 return WS_DuplicateSocket(TRUE, s, dwProcessId, lpProtocolInfo);
6737 /***********************************************************************
6738 * WSAInstallServiceClassA (WS2_32.48)
6740 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
6742 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
6743 WSASetLastError(WSAEACCES);
6744 return SOCKET_ERROR;
6747 /***********************************************************************
6748 * WSAInstallServiceClassW (WS2_32.49)
6750 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
6752 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
6753 WSASetLastError(WSAEACCES);
6754 return SOCKET_ERROR;
6757 /***********************************************************************
6758 * WSARemoveServiceClass (WS2_32.70)
6760 int WINAPI WSARemoveServiceClass(LPGUID info)
6762 FIXME("Request to remove service %p\n",info);
6763 WSASetLastError(WSATYPE_NOT_FOUND);
6764 return SOCKET_ERROR;
6767 /***********************************************************************
6768 * inet_ntop (WS2_32.@)
6770 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
6772 #ifdef HAVE_INET_NTOP
6773 struct WS_in6_addr *in6;
6774 struct WS_in_addr *in;
6775 PCSTR pdst;
6777 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
6778 if (!buffer)
6780 WSASetLastError( STATUS_INVALID_PARAMETER );
6781 return NULL;
6784 switch (family)
6786 case WS_AF_INET:
6788 in = addr;
6789 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
6790 break;
6792 case WS_AF_INET6:
6794 in6 = addr;
6795 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
6796 break;
6798 default:
6799 WSASetLastError( WSAEAFNOSUPPORT );
6800 return NULL;
6803 if (!pdst) WSASetLastError( STATUS_INVALID_PARAMETER );
6804 return pdst;
6805 #else
6806 FIXME( "not supported on this platform\n" );
6807 WSASetLastError( WSAEAFNOSUPPORT );
6808 return NULL;
6809 #endif
6812 /***********************************************************************
6813 * WSAStringToAddressA (WS2_32.80)
6815 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
6816 INT AddressFamily,
6817 LPWSAPROTOCOL_INFOA lpProtocolInfo,
6818 LPSOCKADDR lpAddress,
6819 LPINT lpAddressLength)
6821 INT res=0;
6822 LPSTR workBuffer=NULL,ptrPort;
6824 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
6825 lpProtocolInfo, lpAddress, lpAddressLength );
6827 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
6829 if (!AddressString)
6831 WSASetLastError(WSAEINVAL);
6832 return SOCKET_ERROR;
6835 if (lpProtocolInfo)
6836 FIXME("ProtocolInfo not implemented.\n");
6838 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
6839 strlen(AddressString) + 1);
6840 if (!workBuffer)
6842 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6843 return SOCKET_ERROR;
6846 strcpy(workBuffer, AddressString);
6848 switch(AddressFamily)
6850 case WS_AF_INET:
6852 struct in_addr inetaddr;
6854 /* If lpAddressLength is too small, tell caller the size we need */
6855 if (*lpAddressLength < sizeof(SOCKADDR_IN))
6857 *lpAddressLength = sizeof(SOCKADDR_IN);
6858 res = WSAEFAULT;
6859 break;
6861 *lpAddressLength = sizeof(SOCKADDR_IN);
6862 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
6864 ((LPSOCKADDR_IN)lpAddress)->sin_family = AF_INET;
6866 ptrPort = strchr(workBuffer, ':');
6867 if(ptrPort)
6869 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
6870 *ptrPort = '\0';
6872 else
6874 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
6877 if(inet_aton(workBuffer, &inetaddr) > 0)
6879 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
6880 res = 0;
6882 else
6883 res = WSAEINVAL;
6885 break;
6888 case WS_AF_INET6:
6890 struct in6_addr inetaddr;
6891 /* If lpAddressLength is too small, tell caller the size we need */
6892 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
6894 *lpAddressLength = sizeof(SOCKADDR_IN6);
6895 res = WSAEFAULT;
6896 break;
6898 #ifdef HAVE_INET_PTON
6899 *lpAddressLength = sizeof(SOCKADDR_IN6);
6900 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
6902 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
6904 /* This one is a bit tricky. An IPv6 address contains colons, so the
6905 * check from IPv4 doesn't work like that. However, IPv6 addresses that
6906 * contain a port are written with braces like [fd12:3456:7890::1]:12345
6907 * so what we will do is to look for ']', check if the next char is a
6908 * colon, and if it is, parse the port as in IPv4. */
6910 ptrPort = strchr(workBuffer, ']');
6911 if(ptrPort && *(++ptrPort) == ':')
6913 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort+1));
6914 *ptrPort = '\0';
6916 else
6918 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
6921 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
6923 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
6924 sizeof(struct in6_addr));
6925 res = 0;
6927 else
6928 #endif /* HAVE_INET_PTON */
6929 res = WSAEINVAL;
6931 break;
6933 default:
6934 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
6935 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
6936 res = WSAEINVAL;
6939 HeapFree(GetProcessHeap(), 0, workBuffer);
6941 if (!res) return 0;
6942 WSASetLastError(res);
6943 return SOCKET_ERROR;
6946 /***********************************************************************
6947 * WSAStringToAddressW (WS2_32.81)
6949 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
6950 * If this should be the case, it would be required to map these digits
6951 * to Unicode digits (0-9) using FoldString first.
6953 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
6954 INT AddressFamily,
6955 LPWSAPROTOCOL_INFOW lpProtocolInfo,
6956 LPSOCKADDR lpAddress,
6957 LPINT lpAddressLength)
6959 INT sBuffer,res=0;
6960 LPSTR workBuffer=NULL;
6961 WSAPROTOCOL_INFOA infoA;
6962 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
6964 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
6965 lpAddress, lpAddressLength );
6967 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
6969 /* if ProtocolInfo is available - convert to ANSI variant */
6970 if (lpProtocolInfo)
6972 lpProtoInfoA = &infoA;
6973 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
6975 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
6976 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
6978 WSASetLastError( WSAEINVAL);
6979 return SOCKET_ERROR;
6983 if (AddressString)
6985 /* Translate AddressString to ANSI code page - assumes that only
6986 standard digits 0-9 are used with this API call */
6987 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
6988 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
6990 if (workBuffer)
6992 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
6993 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
6994 lpAddress,lpAddressLength);
6995 HeapFree( GetProcessHeap(), 0, workBuffer );
6996 return res;
6998 else
6999 res = WSA_NOT_ENOUGH_MEMORY;
7001 else
7002 res = WSAEINVAL;
7004 WSASetLastError(res);
7005 return SOCKET_ERROR;
7008 /***********************************************************************
7009 * WSAAddressToStringA (WS2_32.27)
7011 * See WSAAddressToStringW
7013 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
7014 LPWSAPROTOCOL_INFOA info, LPSTR string,
7015 LPDWORD lenstr )
7017 DWORD size;
7018 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
7019 CHAR *p;
7021 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
7023 if (!sockaddr) return SOCKET_ERROR;
7024 if (!string || !lenstr) return SOCKET_ERROR;
7026 switch(sockaddr->sa_family)
7028 case WS_AF_INET:
7029 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
7030 sprintf( buffer, "%u.%u.%u.%u:%u",
7031 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
7032 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
7033 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
7034 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
7035 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
7037 p = strchr( buffer, ':' );
7038 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
7039 break;
7041 case WS_AF_INET6:
7043 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
7045 buffer[0] = 0;
7046 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
7047 if ((sockaddr6->sin6_port))
7048 strcpy(buffer, "[");
7049 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, buffer+strlen(buffer), sizeof(buffer)))
7051 WSASetLastError(WSAEINVAL);
7052 return SOCKET_ERROR;
7054 if ((sockaddr6->sin6_scope_id))
7055 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
7056 if ((sockaddr6->sin6_port))
7057 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
7058 break;
7061 default:
7062 WSASetLastError(WSAEINVAL);
7063 return SOCKET_ERROR;
7066 size = strlen( buffer ) + 1;
7068 if (*lenstr < size)
7070 *lenstr = size;
7071 WSASetLastError(WSAEFAULT);
7072 return SOCKET_ERROR;
7075 TRACE("=> %s,%u bytes\n", debugstr_a(buffer), size);
7076 *lenstr = size;
7077 strcpy( string, buffer );
7078 return 0;
7081 /***********************************************************************
7082 * WSAAddressToStringW (WS2_32.28)
7084 * Convert a sockaddr address into a readable address string.
7086 * PARAMS
7087 * sockaddr [I] Pointer to a sockaddr structure.
7088 * len [I] Size of the sockaddr structure.
7089 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
7090 * string [I/O] Pointer to a buffer to receive the address string.
7091 * lenstr [I/O] Size of the receive buffer in WCHARs.
7093 * RETURNS
7094 * Success: 0
7095 * Failure: SOCKET_ERROR
7097 * NOTES
7098 * The 'info' parameter is ignored.
7100 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
7101 LPWSAPROTOCOL_INFOW info, LPWSTR string,
7102 LPDWORD lenstr )
7104 INT ret;
7105 DWORD size;
7106 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
7107 CHAR bufAddr[54];
7109 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
7111 size = *lenstr;
7112 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
7114 if (ret) return ret;
7116 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
7118 if (*lenstr < size)
7120 *lenstr = size;
7121 WSASetLastError(WSAEFAULT);
7122 return SOCKET_ERROR;
7125 TRACE("=> %s,%u bytes\n", debugstr_w(buffer), size);
7126 *lenstr = size;
7127 lstrcpyW( string, buffer );
7128 return 0;
7131 /***********************************************************************
7132 * WSAEnumNameSpaceProvidersA (WS2_32.34)
7134 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
7136 FIXME( "(%p %p) Stub!\n", len, buffer );
7137 return 0;
7140 /***********************************************************************
7141 * WSAEnumNameSpaceProvidersW (WS2_32.35)
7143 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
7145 FIXME( "(%p %p) Stub!\n", len, buffer );
7146 return 0;
7149 /***********************************************************************
7150 * WSAGetQOSByName (WS2_32.41)
7152 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
7154 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
7155 return FALSE;
7158 /***********************************************************************
7159 * WSAGetServiceClassInfoA (WS2_32.42)
7161 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
7162 LPWSASERVICECLASSINFOA info )
7164 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
7165 len, info );
7166 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7167 return SOCKET_ERROR;
7170 /***********************************************************************
7171 * WSAGetServiceClassInfoW (WS2_32.43)
7173 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
7174 LPWSASERVICECLASSINFOW info )
7176 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
7177 len, info );
7178 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7179 return SOCKET_ERROR;
7182 /***********************************************************************
7183 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
7185 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
7187 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
7188 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7189 return SOCKET_ERROR;
7192 /***********************************************************************
7193 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
7195 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
7197 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
7198 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7199 return SOCKET_ERROR;
7202 /***********************************************************************
7203 * WSALookupServiceBeginA (WS2_32.59)
7205 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
7206 DWORD dwControlFlags,
7207 LPHANDLE lphLookup)
7209 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
7210 lphLookup);
7211 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7212 return SOCKET_ERROR;
7215 /***********************************************************************
7216 * WSALookupServiceBeginW (WS2_32.60)
7218 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
7219 DWORD dwControlFlags,
7220 LPHANDLE lphLookup)
7222 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
7223 lphLookup);
7224 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7225 return SOCKET_ERROR;
7228 /***********************************************************************
7229 * WSALookupServiceEnd (WS2_32.61)
7231 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
7233 FIXME("(%p) Stub!\n", lookup );
7234 return 0;
7237 /***********************************************************************
7238 * WSALookupServiceNextA (WS2_32.62)
7240 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
7242 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
7243 WSASetLastError(WSA_E_NO_MORE);
7244 return SOCKET_ERROR;
7247 /***********************************************************************
7248 * WSALookupServiceNextW (WS2_32.63)
7250 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
7252 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
7253 WSASetLastError(WSA_E_NO_MORE);
7254 return SOCKET_ERROR;
7257 /***********************************************************************
7258 * WSANtohl (WS2_32.64)
7260 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
7262 TRACE( "(0x%04lx 0x%08x %p)\n", s, netlong, lphostlong );
7264 if (!lphostlong) return WSAEFAULT;
7266 *lphostlong = ntohl( netlong );
7267 return 0;
7270 /***********************************************************************
7271 * WSANtohs (WS2_32.65)
7273 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
7275 TRACE( "(0x%04lx 0x%08x %p)\n", s, netshort, lphostshort );
7277 if (!lphostshort) return WSAEFAULT;
7279 *lphostshort = ntohs( netshort );
7280 return 0;
7283 /***********************************************************************
7284 * WSAProviderConfigChange (WS2_32.66)
7286 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
7287 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
7289 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
7290 return SOCKET_ERROR;
7293 /***********************************************************************
7294 * WSARecvDisconnect (WS2_32.68)
7296 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
7298 TRACE( "(0x%04lx %p)\n", s, disconnectdata );
7300 return WS_shutdown( s, 0 );
7303 /***********************************************************************
7304 * WSASetServiceA (WS2_32.76)
7306 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
7308 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
7309 return 0;
7312 /***********************************************************************
7313 * WSASetServiceW (WS2_32.77)
7315 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
7317 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
7318 return 0;
7321 /***********************************************************************
7322 * WSCEnableNSProvider (WS2_32.84)
7324 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
7326 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
7327 return 0;
7330 /***********************************************************************
7331 * WSCGetProviderPath (WS2_32.86)
7333 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
7335 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
7337 if (!errcode || !provider || !len) return WSAEFAULT;
7339 *errcode = WSAEINVAL;
7340 return SOCKET_ERROR;
7343 /***********************************************************************
7344 * WSCInstallNameSpace (WS2_32.87)
7346 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
7347 DWORD version, LPGUID provider )
7349 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
7350 namespace, version, debugstr_guid(provider) );
7351 return 0;
7354 /***********************************************************************
7355 * WSCUnInstallNameSpace (WS2_32.89)
7357 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
7359 FIXME("(%p) Stub!\n", lpProviderId);
7360 return NO_ERROR;
7363 /***********************************************************************
7364 * WSCWriteProviderOrder (WS2_32.91)
7366 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
7368 FIXME("(%p 0x%08x) Stub!\n", entry, number);
7369 return 0;
7372 /***********************************************************************
7373 * WSANSPIoctl (WS2_32.91)
7375 INT WINAPI WSANSPIoctl( HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer,
7376 DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer,
7377 LPDWORD lpcbBytesReturned, LPWSACOMPLETION lpCompletion )
7379 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup, dwControlCode,
7380 lpvInBuffer, cbInBuffer, lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpCompletion);
7381 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
7382 return SOCKET_ERROR;
7385 /*****************************************************************************
7386 * WSAEnumProtocolsA [WS2_32.@]
7388 * see function WSAEnumProtocolsW
7390 INT WINAPI WSAEnumProtocolsA( LPINT protocols, LPWSAPROTOCOL_INFOA buffer, LPDWORD len )
7392 return WS_EnumProtocols( FALSE, protocols, (LPWSAPROTOCOL_INFOW) buffer, len);
7395 /*****************************************************************************
7396 * WSAEnumProtocolsW [WS2_32.@]
7398 * Retrieves information about specified set of active network protocols.
7400 * PARAMS
7401 * protocols [I] Pointer to null-terminated array of protocol id's. NULL
7402 * retrieves information on all available protocols.
7403 * buffer [I] Pointer to a buffer to be filled with WSAPROTOCOL_INFO
7404 * structures.
7405 * len [I/O] Pointer to a variable specifying buffer size. On output
7406 * the variable holds the number of bytes needed when the
7407 * specified size is too small.
7409 * RETURNS
7410 * Success: number of WSAPROTOCOL_INFO structures in buffer.
7411 * Failure: SOCKET_ERROR
7413 * NOTES
7414 * NT4SP5 does not return SPX if protocols == NULL
7416 * BUGS
7417 * - NT4SP5 returns in addition these list of NETBIOS protocols
7418 * (address family 17), each entry two times one for socket type 2 and 5
7420 * iProtocol szProtocol
7421 * 0x80000000 \Device\NwlnkNb
7422 * 0xfffffffa \Device\NetBT_CBENT7
7423 * 0xfffffffb \Device\Nbf_CBENT7
7424 * 0xfffffffc \Device\NetBT_NdisWan5
7425 * 0xfffffffd \Device\NetBT_El9202
7426 * 0xfffffffe \Device\Nbf_El9202
7427 * 0xffffffff \Device\Nbf_NdisWan4
7429 * - there is no check that the operating system supports the returned
7430 * protocols
7432 INT WINAPI WSAEnumProtocolsW( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len )
7434 return WS_EnumProtocols( TRUE, protocols, buffer, len);
7437 /*****************************************************************************
7438 * WSCEnumProtocols [WS2_32.@]
7440 * PARAMS
7441 * protocols [I] Null-terminated array of iProtocol values.
7442 * buffer [O] Buffer of WSAPROTOCOL_INFOW structures.
7443 * len [I/O] Size of buffer on input/output.
7444 * errno [O] Error code.
7446 * RETURNS
7447 * Success: number of protocols to be reported on.
7448 * Failure: SOCKET_ERROR. error is in errno.
7450 * BUGS
7451 * Doesn't supply info on layered protocols.
7454 INT WINAPI WSCEnumProtocols( LPINT protocols, LPWSAPROTOCOL_INFOW buffer, LPDWORD len, LPINT err )
7456 INT ret = WSAEnumProtocolsW( protocols, buffer, len );
7458 if (ret == SOCKET_ERROR) *err = WSAENOBUFS;
7460 return ret;