ws2_32: Implement IP_UNICAST_IF socket option.
[wine/multimedia.git] / dlls / ws2_32 / socket.c
blob5d20459ddf56871c967bb481f583553a63b03695
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) 2005 Marcus Meissner
6 * Copyright (C) 2006-2008 Kai Blin
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 * NOTE: If you make any changes to fix a particular app, make sure
23 * they don't break something else like Netscape or telnet and ftp
24 * clients and servers (www.winsite.com got a lot of those).
27 #include "config.h"
28 #include "wine/port.h"
30 #include <stdarg.h>
31 #include <stdio.h>
32 #include <string.h>
33 #include <sys/types.h>
34 #ifdef HAVE_SYS_IPC_H
35 # include <sys/ipc.h>
36 #endif
37 #ifdef HAVE_SYS_IOCTL_H
38 # include <sys/ioctl.h>
39 #endif
40 #ifdef HAVE_SYS_FILIO_H
41 # include <sys/filio.h>
42 #endif
43 #ifdef HAVE_SYS_SOCKIO_H
44 # include <sys/sockio.h>
45 #endif
47 #if defined(__EMX__)
48 # include <sys/so_ioctl.h>
49 #endif
51 #ifdef HAVE_SYS_PARAM_H
52 # include <sys/param.h>
53 #endif
55 #ifdef HAVE_SYS_MSG_H
56 # include <sys/msg.h>
57 #endif
58 #ifdef HAVE_SYS_WAIT_H
59 # include <sys/wait.h>
60 #endif
61 #ifdef HAVE_SYS_UIO_H
62 # include <sys/uio.h>
63 #endif
64 #ifdef HAVE_SYS_SOCKET_H
65 #include <sys/socket.h>
66 #endif
67 #ifdef HAVE_NETINET_IN_H
68 # include <netinet/in.h>
69 #endif
70 #ifdef HAVE_NETINET_TCP_H
71 # include <netinet/tcp.h>
72 #endif
73 #ifdef HAVE_ARPA_INET_H
74 # include <arpa/inet.h>
75 #endif
76 #include <ctype.h>
77 #include <fcntl.h>
78 #include <errno.h>
79 #ifdef HAVE_NETDB_H
80 #include <netdb.h>
81 #endif
82 #ifdef HAVE_UNISTD_H
83 # include <unistd.h>
84 #endif
85 #include <stdlib.h>
86 #ifdef HAVE_ARPA_NAMESER_H
87 # include <arpa/nameser.h>
88 #endif
89 #ifdef HAVE_RESOLV_H
90 # include <resolv.h>
91 #endif
92 #ifdef HAVE_NET_IF_H
93 # include <net/if.h>
94 #endif
96 #ifdef HAVE_NETIPX_IPX_H
97 # include <netipx/ipx.h>
98 # define HAVE_IPX
99 #elif defined(HAVE_LINUX_IPX_H)
100 # ifdef HAVE_ASM_TYPES_H
101 # include <asm/types.h>
102 # endif
103 # ifdef HAVE_LINUX_TYPES_H
104 # include <linux/types.h>
105 # endif
106 # include <linux/ipx.h>
107 # define HAVE_IPX
108 #endif
110 #ifdef HAVE_LINUX_IRDA_H
111 # ifdef HAVE_LINUX_TYPES_H
112 # include <linux/types.h>
113 # endif
114 # include <linux/irda.h>
115 # define HAVE_IRDA
116 #endif
118 #ifdef HAVE_POLL_H
119 #include <poll.h>
120 #endif
121 #ifdef HAVE_SYS_POLL_H
122 # include <sys/poll.h>
123 #endif
124 #ifdef HAVE_SYS_TIME_H
125 # include <sys/time.h>
126 #endif
128 #define NONAMELESSUNION
129 #define NONAMELESSSTRUCT
130 #include "ntstatus.h"
131 #define WIN32_NO_STATUS
132 #include "windef.h"
133 #include "winbase.h"
134 #include "wingdi.h"
135 #include "winuser.h"
136 #include "winerror.h"
137 #include "winnls.h"
138 #include "winsock2.h"
139 #include "mswsock.h"
140 #include "ws2tcpip.h"
141 #include "ws2spi.h"
142 #include "wsipx.h"
143 #include "mstcpip.h"
144 #include "af_irda.h"
145 #include "winnt.h"
146 #define USE_WC_PREFIX /* For CMSG_DATA */
147 #include "iphlpapi.h"
148 #include "wine/server.h"
149 #include "wine/debug.h"
150 #include "wine/exception.h"
151 #include "wine/unicode.h"
153 #ifdef HAVE_IPX
154 # include "wsnwlink.h"
155 #endif
158 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
159 # define sipx_network sipx_addr.x_net
160 # define sipx_node sipx_addr.x_host.c_host
161 #endif /* __FreeBSD__ */
163 #ifndef INADDR_NONE
164 #define INADDR_NONE ~0UL
165 #endif
167 WINE_DEFAULT_DEBUG_CHANNEL(winsock);
168 WINE_DECLARE_DEBUG_CHANNEL(winediag);
172 * The actual definition of WSASendTo, wrapped in a different function name
173 * so that internal calls from ws2_32 itself will not trigger programs like
174 * Garena, which hooks WSASendTo/WSARecvFrom calls.
176 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
177 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
178 const struct WS_sockaddr *to, int tolen,
179 LPWSAOVERLAPPED lpOverlapped,
180 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine );
183 * Internal fundamental receive function, essentially WSARecvFrom with an
184 * additional parameter to support message control headers.
186 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
187 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
188 struct WS_sockaddr *lpFrom,
189 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
190 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
191 LPWSABUF lpControlBuffer );
193 /* critical section to protect some non-reentrant net function */
194 static CRITICAL_SECTION csWSgetXXXbyYYY;
195 static CRITICAL_SECTION_DEBUG critsect_debug =
197 0, 0, &csWSgetXXXbyYYY,
198 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
199 0, 0, { (DWORD_PTR)(__FILE__ ": csWSgetXXXbyYYY") }
201 static CRITICAL_SECTION csWSgetXXXbyYYY = { &critsect_debug, -1, 0, 0, 0, 0 };
203 union generic_unix_sockaddr
205 struct sockaddr addr;
206 char data[128]; /* should be big enough for all families */
209 static inline const char *debugstr_sockaddr( const struct WS_sockaddr *a )
211 if (!a) return "(nil)";
212 switch (a->sa_family)
214 case WS_AF_INET:
215 return wine_dbg_sprintf("{ family AF_INET, address %s, port %d }",
216 inet_ntoa(((const struct sockaddr_in *)a)->sin_addr),
217 ntohs(((const struct sockaddr_in *)a)->sin_port));
218 case WS_AF_INET6:
220 char buf[46];
221 const char *p;
222 struct WS_sockaddr_in6 *sin = (struct WS_sockaddr_in6 *)a;
224 p = WS_inet_ntop( WS_AF_INET6, &sin->sin6_addr, buf, sizeof(buf) );
225 if (!p)
226 p = "(unknown IPv6 address)";
227 return wine_dbg_sprintf("{ family AF_INET6, address %s, port %d }",
228 p, ntohs(sin->sin6_port));
230 case WS_AF_IRDA:
232 DWORD addr;
234 memcpy( &addr, ((const SOCKADDR_IRDA *)a)->irdaDeviceID, sizeof(addr) );
235 addr = ntohl( addr );
236 return wine_dbg_sprintf("{ family AF_IRDA, addr %08x, name %s }",
237 addr,
238 ((const SOCKADDR_IRDA *)a)->irdaServiceName);
240 default:
241 return wine_dbg_sprintf("{ family %d }", a->sa_family);
245 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
246 #define SOCKET2HANDLE(s) ((HANDLE)(s))
247 #define HANDLE2SOCKET(h) ((SOCKET)(h))
249 /****************************************************************
250 * Async IO declarations
251 ****************************************************************/
253 typedef struct ws2_async
255 HANDLE hSocket;
256 int type;
257 LPWSAOVERLAPPED user_overlapped;
258 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
259 IO_STATUS_BLOCK local_iosb;
260 struct WS_sockaddr *addr;
261 union
263 int val; /* for send operations */
264 int *ptr; /* for recv operations */
265 } addrlen;
266 DWORD flags;
267 DWORD *lpFlags;
268 WSABUF *control;
269 unsigned int n_iovecs;
270 unsigned int first_iovec;
271 struct iovec iovec[1];
272 } ws2_async;
274 typedef struct ws2_accept_async
276 HANDLE listen_socket;
277 HANDLE accept_socket;
278 LPOVERLAPPED user_overlapped;
279 ULONG_PTR cvalue;
280 PVOID buf; /* buffer to write data to */
281 int data_len;
282 int local_len;
283 int remote_len;
284 struct ws2_async *read;
285 } ws2_accept_async;
287 /****************************************************************/
289 /* ----------------------------------- internal data */
291 /* ws_... struct conversion flags */
293 typedef struct /* WSAAsyncSelect() control struct */
295 HANDLE service, event, sock;
296 HWND hWnd;
297 UINT uMsg;
298 LONG lEvent;
299 } ws_select_info;
301 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
302 #define WS_MAX_UDP_DATAGRAM 1024
303 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
305 /* hostent's, servent's and protent's are stored in one buffer per thread,
306 * as documented on MSDN for the functions that return any of the buffers */
307 struct per_thread_data
309 int opentype;
310 struct WS_hostent *he_buffer;
311 struct WS_servent *se_buffer;
312 struct WS_protoent *pe_buffer;
313 int he_len;
314 int se_len;
315 int pe_len;
318 /* internal: routing description information */
319 struct route {
320 struct in_addr addr;
321 IF_INDEX interface;
322 DWORD metric;
325 static INT num_startup; /* reference counter */
326 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
328 /* function prototypes */
329 static struct WS_hostent *WS_create_he(char *name, int aliases, int addresses, int fill_addresses);
330 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
331 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
332 static struct WS_servent *WS_dup_se(const struct servent* p_se);
334 int WSAIOCTL_GetInterfaceCount(void);
335 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
337 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus, ULONG Information );
339 #define MAP_OPTION(opt) { WS_##opt, opt }
341 static const int ws_sock_map[][2] =
343 MAP_OPTION( SO_DEBUG ),
344 MAP_OPTION( SO_ACCEPTCONN ),
345 MAP_OPTION( SO_REUSEADDR ),
346 MAP_OPTION( SO_KEEPALIVE ),
347 MAP_OPTION( SO_DONTROUTE ),
348 MAP_OPTION( SO_BROADCAST ),
349 MAP_OPTION( SO_LINGER ),
350 MAP_OPTION( SO_OOBINLINE ),
351 MAP_OPTION( SO_SNDBUF ),
352 MAP_OPTION( SO_RCVBUF ),
353 MAP_OPTION( SO_ERROR ),
354 MAP_OPTION( SO_TYPE ),
355 #ifdef SO_RCVTIMEO
356 MAP_OPTION( SO_RCVTIMEO ),
357 #endif
358 #ifdef SO_SNDTIMEO
359 MAP_OPTION( SO_SNDTIMEO ),
360 #endif
363 static const int ws_tcp_map[][2] =
365 #ifdef TCP_NODELAY
366 MAP_OPTION( TCP_NODELAY ),
367 #endif
370 static const int ws_ip_map[][2] =
372 MAP_OPTION( IP_MULTICAST_IF ),
373 MAP_OPTION( IP_MULTICAST_TTL ),
374 MAP_OPTION( IP_MULTICAST_LOOP ),
375 MAP_OPTION( IP_ADD_MEMBERSHIP ),
376 MAP_OPTION( IP_DROP_MEMBERSHIP ),
377 MAP_OPTION( IP_OPTIONS ),
378 #ifdef IP_HDRINCL
379 MAP_OPTION( IP_HDRINCL ),
380 #endif
381 MAP_OPTION( IP_TOS ),
382 MAP_OPTION( IP_TTL ),
383 #ifdef IP_PKTINFO
384 MAP_OPTION( IP_PKTINFO ),
385 #endif
386 #ifdef IP_UNICAST_IF
387 MAP_OPTION( IP_UNICAST_IF ),
388 #endif
391 static const int ws_ipv6_map[][2] =
393 #ifdef IPV6_ADD_MEMBERSHIP
394 MAP_OPTION( IPV6_ADD_MEMBERSHIP ),
395 #endif
396 #ifdef IPV6_DROP_MEMBERSHIP
397 MAP_OPTION( IPV6_DROP_MEMBERSHIP ),
398 #endif
399 MAP_OPTION( IPV6_MULTICAST_IF ),
400 MAP_OPTION( IPV6_MULTICAST_HOPS ),
401 MAP_OPTION( IPV6_MULTICAST_LOOP ),
402 MAP_OPTION( IPV6_UNICAST_HOPS ),
403 MAP_OPTION( IPV6_V6ONLY ),
406 static const int ws_af_map[][2] =
408 MAP_OPTION( AF_UNSPEC ),
409 MAP_OPTION( AF_INET ),
410 MAP_OPTION( AF_INET6 ),
411 #ifdef HAVE_IPX
412 MAP_OPTION( AF_IPX ),
413 #endif
414 #ifdef AF_IRDA
415 MAP_OPTION( AF_IRDA ),
416 #endif
417 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
420 static const int ws_socktype_map[][2] =
422 MAP_OPTION( SOCK_DGRAM ),
423 MAP_OPTION( SOCK_STREAM ),
424 MAP_OPTION( SOCK_RAW ),
425 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
428 static const int ws_proto_map[][2] =
430 MAP_OPTION( IPPROTO_IP ),
431 MAP_OPTION( IPPROTO_TCP ),
432 MAP_OPTION( IPPROTO_UDP ),
433 MAP_OPTION( IPPROTO_ICMP ),
434 MAP_OPTION( IPPROTO_IGMP ),
435 MAP_OPTION( IPPROTO_RAW ),
436 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
439 static const int ws_aiflag_map[][2] =
441 MAP_OPTION( AI_PASSIVE ),
442 MAP_OPTION( AI_CANONNAME ),
443 MAP_OPTION( AI_NUMERICHOST ),
444 MAP_OPTION( AI_ADDRCONFIG ),
447 static const int ws_niflag_map[][2] =
449 MAP_OPTION( NI_NOFQDN ),
450 MAP_OPTION( NI_NUMERICHOST ),
451 MAP_OPTION( NI_NAMEREQD ),
452 MAP_OPTION( NI_NUMERICSERV ),
453 MAP_OPTION( NI_DGRAM ),
456 static const int ws_eai_map[][2] =
458 MAP_OPTION( EAI_AGAIN ),
459 MAP_OPTION( EAI_BADFLAGS ),
460 MAP_OPTION( EAI_FAIL ),
461 MAP_OPTION( EAI_FAMILY ),
462 MAP_OPTION( EAI_MEMORY ),
463 /* Note: EAI_NODATA is deprecated, but still
464 * used by Windows and Linux... We map the newer
465 * EAI_NONAME to EAI_NODATA for now until Windows
466 * changes too.
468 #ifdef EAI_NODATA
469 MAP_OPTION( EAI_NODATA ),
470 #endif
471 #ifdef EAI_NONAME
472 { WS_EAI_NODATA, EAI_NONAME },
473 #endif
475 MAP_OPTION( EAI_SERVICE ),
476 MAP_OPTION( EAI_SOCKTYPE ),
477 { 0, 0 }
480 static const char magic_loopback_addr[] = {127, 12, 34, 56};
482 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
483 static inline WSACMSGHDR *fill_control_message(int level, int type, WSACMSGHDR *current, ULONG *maxsize, void *data, int len)
485 ULONG msgsize = sizeof(WSACMSGHDR) + WSA_CMSG_ALIGN(len);
486 char *ptr = (char *) current + sizeof(WSACMSGHDR);
488 /* Make sure there is at least enough room for this entry */
489 if (msgsize > *maxsize)
490 return NULL;
491 *maxsize -= msgsize;
492 /* Fill in the entry */
493 current->cmsg_len = sizeof(WSACMSGHDR) + len;
494 current->cmsg_level = level;
495 current->cmsg_type = type;
496 memcpy(ptr, data, len);
497 /* Return the pointer to where next entry should go */
498 return (WSACMSGHDR *) (ptr + WSA_CMSG_ALIGN(len));
501 static inline int convert_control_headers(struct msghdr *hdr, WSABUF *control)
503 #ifdef IP_PKTINFO
504 WSACMSGHDR *cmsg_win = (WSACMSGHDR *) control->buf, *ptr;
505 ULONG ctlsize = control->len;
506 struct cmsghdr *cmsg_unix;
508 ptr = cmsg_win;
509 /* Loop over all the headers, converting as appropriate */
510 for (cmsg_unix = CMSG_FIRSTHDR(hdr); cmsg_unix != NULL; cmsg_unix = CMSG_NXTHDR(hdr, cmsg_unix))
512 switch(cmsg_unix->cmsg_level)
514 case IPPROTO_IP:
515 switch(cmsg_unix->cmsg_type)
517 case IP_PKTINFO:
519 /* Convert the Unix IP_PKTINFO structure to the Windows version */
520 struct in_pktinfo *data_unix = (struct in_pktinfo *) CMSG_DATA(cmsg_unix);
521 struct WS_in_pktinfo data_win;
523 memcpy(&data_win.ipi_addr,&data_unix->ipi_addr.s_addr,4); /* 4 bytes = 32 address bits */
524 data_win.ipi_ifindex = data_unix->ipi_ifindex;
525 ptr = fill_control_message(WS_IPPROTO_IP, WS_IP_PKTINFO, ptr, &ctlsize,
526 (void*)&data_win, sizeof(data_win));
527 if (!ptr) goto error;
528 } break;
529 default:
530 FIXME("Unhandled IPPROTO_IP message header type %d\n", cmsg_unix->cmsg_type);
531 break;
533 break;
534 default:
535 FIXME("Unhandled message header level %d\n", cmsg_unix->cmsg_level);
536 break;
540 error:
541 /* Set the length of the returned control headers */
542 control->len = (ptr == NULL ? 0 : (char*)ptr - (char*)cmsg_win);
543 return (ptr != NULL);
544 #else /* IP_PKTINFO */
545 control->len = 0;
546 return 1;
547 #endif /* IP_PKTINFO */
549 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
551 /* ----------------------------------- error handling */
553 static NTSTATUS sock_get_ntstatus( int err )
555 switch ( err )
557 case EBADF: return STATUS_INVALID_HANDLE;
558 case EBUSY: return STATUS_DEVICE_BUSY;
559 case EPERM:
560 case EACCES: return STATUS_ACCESS_DENIED;
561 case EFAULT: return STATUS_NO_MEMORY;
562 case EINVAL: return STATUS_INVALID_PARAMETER;
563 case ENFILE:
564 case EMFILE: return STATUS_TOO_MANY_OPENED_FILES;
565 case EWOULDBLOCK: return STATUS_CANT_WAIT;
566 case EINPROGRESS: return STATUS_PENDING;
567 case EALREADY: return STATUS_NETWORK_BUSY;
568 case ENOTSOCK: return STATUS_OBJECT_TYPE_MISMATCH;
569 case EDESTADDRREQ: return STATUS_INVALID_PARAMETER;
570 case EMSGSIZE: return STATUS_BUFFER_OVERFLOW;
571 case EPROTONOSUPPORT:
572 case ESOCKTNOSUPPORT:
573 case EPFNOSUPPORT:
574 case EAFNOSUPPORT:
575 case EPROTOTYPE: return STATUS_NOT_SUPPORTED;
576 case ENOPROTOOPT: return STATUS_INVALID_PARAMETER;
577 case EOPNOTSUPP: return STATUS_NOT_SUPPORTED;
578 case EADDRINUSE: return STATUS_ADDRESS_ALREADY_ASSOCIATED;
579 case EADDRNOTAVAIL: return STATUS_INVALID_PARAMETER;
580 case ECONNREFUSED: return STATUS_CONNECTION_REFUSED;
581 case ESHUTDOWN: return STATUS_PIPE_DISCONNECTED;
582 case ENOTCONN: return STATUS_CONNECTION_DISCONNECTED;
583 case ETIMEDOUT: return STATUS_IO_TIMEOUT;
584 case ENETUNREACH: return STATUS_NETWORK_UNREACHABLE;
585 case ENETDOWN: return STATUS_NETWORK_BUSY;
586 case EPIPE:
587 case ECONNRESET: return STATUS_CONNECTION_RESET;
588 case ECONNABORTED: return STATUS_CONNECTION_ABORTED;
590 case 0: return STATUS_SUCCESS;
591 default:
592 WARN("Unknown errno %d!\n", err);
593 return STATUS_UNSUCCESSFUL;
597 static UINT sock_get_error( int err )
599 switch(err)
601 case EINTR: return WSAEINTR;
602 case EBADF: return WSAEBADF;
603 case EPERM:
604 case EACCES: return WSAEACCES;
605 case EFAULT: return WSAEFAULT;
606 case EINVAL: return WSAEINVAL;
607 case EMFILE: return WSAEMFILE;
608 case EWOULDBLOCK: return WSAEWOULDBLOCK;
609 case EINPROGRESS: return WSAEINPROGRESS;
610 case EALREADY: return WSAEALREADY;
611 case ENOTSOCK: return WSAENOTSOCK;
612 case EDESTADDRREQ: return WSAEDESTADDRREQ;
613 case EMSGSIZE: return WSAEMSGSIZE;
614 case EPROTOTYPE: return WSAEPROTOTYPE;
615 case ENOPROTOOPT: return WSAENOPROTOOPT;
616 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
617 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
618 case EOPNOTSUPP: return WSAEOPNOTSUPP;
619 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
620 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
621 case EADDRINUSE: return WSAEADDRINUSE;
622 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
623 case ENETDOWN: return WSAENETDOWN;
624 case ENETUNREACH: return WSAENETUNREACH;
625 case ENETRESET: return WSAENETRESET;
626 case ECONNABORTED: return WSAECONNABORTED;
627 case EPIPE:
628 case ECONNRESET: return WSAECONNRESET;
629 case ENOBUFS: return WSAENOBUFS;
630 case EISCONN: return WSAEISCONN;
631 case ENOTCONN: return WSAENOTCONN;
632 case ESHUTDOWN: return WSAESHUTDOWN;
633 case ETOOMANYREFS: return WSAETOOMANYREFS;
634 case ETIMEDOUT: return WSAETIMEDOUT;
635 case ECONNREFUSED: return WSAECONNREFUSED;
636 case ELOOP: return WSAELOOP;
637 case ENAMETOOLONG: return WSAENAMETOOLONG;
638 case EHOSTDOWN: return WSAEHOSTDOWN;
639 case EHOSTUNREACH: return WSAEHOSTUNREACH;
640 case ENOTEMPTY: return WSAENOTEMPTY;
641 #ifdef EPROCLIM
642 case EPROCLIM: return WSAEPROCLIM;
643 #endif
644 #ifdef EUSERS
645 case EUSERS: return WSAEUSERS;
646 #endif
647 #ifdef EDQUOT
648 case EDQUOT: return WSAEDQUOT;
649 #endif
650 #ifdef ESTALE
651 case ESTALE: return WSAESTALE;
652 #endif
653 #ifdef EREMOTE
654 case EREMOTE: return WSAEREMOTE;
655 #endif
657 /* just in case we ever get here and there are no problems */
658 case 0: return 0;
659 default:
660 WARN("Unknown errno %d!\n", err);
661 return WSAEOPNOTSUPP;
665 static UINT wsaErrno(void)
667 int loc_errno = errno;
668 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
670 return sock_get_error( loc_errno );
673 /* most ws2 overlapped functions return an ntstatus-based error code */
674 static NTSTATUS wsaErrStatus(void)
676 int loc_errno = errno;
677 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
679 return sock_get_ntstatus(loc_errno);
682 static UINT wsaHerrno(int loc_errno)
684 WARN("h_errno %d.\n", loc_errno);
686 switch(loc_errno)
688 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
689 case TRY_AGAIN: return WSATRY_AGAIN;
690 case NO_RECOVERY: return WSANO_RECOVERY;
691 case NO_DATA: return WSANO_DATA;
692 case ENOBUFS: return WSAENOBUFS;
694 case 0: return 0;
695 default:
696 WARN("Unknown h_errno %d!\n", loc_errno);
697 return WSAEOPNOTSUPP;
701 static inline DWORD NtStatusToWSAError( const DWORD status )
703 /* We only need to cover the status codes set by server async request handling */
704 DWORD wserr;
705 switch ( status )
707 case STATUS_SUCCESS: wserr = 0; break;
708 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
709 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
710 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
711 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
712 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
713 case STATUS_NETWORK_BUSY: wserr = WSAEALREADY; break;
714 case STATUS_NETWORK_UNREACHABLE: wserr = WSAENETUNREACH; break;
715 case STATUS_CONNECTION_REFUSED: wserr = WSAECONNREFUSED; break;
716 case STATUS_CONNECTION_DISCONNECTED: wserr = WSAENOTCONN; break;
717 case STATUS_CONNECTION_RESET: wserr = WSAECONNRESET; break;
718 case STATUS_CONNECTION_ABORTED: wserr = WSAECONNABORTED; break;
719 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
720 case STATUS_ADDRESS_ALREADY_ASSOCIATED: wserr = WSAEADDRINUSE; break;
721 case STATUS_IO_TIMEOUT:
722 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
723 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
724 case STATUS_ACCESS_DENIED: wserr = WSAEACCES; break;
725 case STATUS_TOO_MANY_OPENED_FILES: wserr = WSAEMFILE; break;
726 case STATUS_CANT_WAIT: wserr = WSAEWOULDBLOCK; break;
727 case STATUS_BUFFER_OVERFLOW: wserr = WSAEMSGSIZE; break;
728 case STATUS_NOT_SUPPORTED: wserr = WSAEOPNOTSUPP; break;
729 case STATUS_HOST_UNREACHABLE: wserr = WSAEHOSTUNREACH; break;
731 default:
732 wserr = RtlNtStatusToDosError( status );
733 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
735 return wserr;
738 /* set last error code from NT status without mapping WSA errors */
739 static inline unsigned int set_error( unsigned int err )
741 if (err)
743 err = NtStatusToWSAError( err );
744 SetLastError( err );
746 return err;
749 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
751 int fd;
752 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
753 return -1;
754 return fd;
757 static inline void release_sock_fd( SOCKET s, int fd )
759 wine_server_release_fd( SOCKET2HANDLE(s), fd );
762 static void _enable_event( HANDLE s, unsigned int event,
763 unsigned int sstate, unsigned int cstate )
765 SERVER_START_REQ( enable_socket_event )
767 req->handle = wine_server_obj_handle( s );
768 req->mask = event;
769 req->sstate = sstate;
770 req->cstate = cstate;
771 wine_server_call( req );
773 SERVER_END_REQ;
776 static int _is_blocking(SOCKET s)
778 int ret;
779 SERVER_START_REQ( get_socket_event )
781 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
782 req->service = FALSE;
783 req->c_event = 0;
784 wine_server_call( req );
785 ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
787 SERVER_END_REQ;
788 return ret;
791 static unsigned int _get_sock_mask(SOCKET s)
793 unsigned int ret;
794 SERVER_START_REQ( get_socket_event )
796 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
797 req->service = FALSE;
798 req->c_event = 0;
799 wine_server_call( req );
800 ret = reply->mask;
802 SERVER_END_REQ;
803 return ret;
806 static void _sync_sock_state(SOCKET s)
808 /* do a dummy wineserver request in order to let
809 the wineserver run through its select loop once */
810 (void)_is_blocking(s);
813 static int _get_sock_error(SOCKET s, unsigned int bit)
815 int events[FD_MAX_EVENTS];
817 SERVER_START_REQ( get_socket_event )
819 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
820 req->service = FALSE;
821 req->c_event = 0;
822 wine_server_set_reply( req, events, sizeof(events) );
823 wine_server_call( req );
825 SERVER_END_REQ;
826 return events[bit];
829 static struct per_thread_data *get_per_thread_data(void)
831 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
832 /* lazy initialization */
833 if (!ptb)
835 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
836 NtCurrentTeb()->WinSockData = ptb;
838 return ptb;
841 static void free_per_thread_data(void)
843 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
845 if (!ptb) return;
847 /* delete scratch buffers */
848 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
849 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
850 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
851 ptb->he_buffer = NULL;
852 ptb->se_buffer = NULL;
853 ptb->pe_buffer = NULL;
855 HeapFree( GetProcessHeap(), 0, ptb );
856 NtCurrentTeb()->WinSockData = NULL;
859 /***********************************************************************
860 * DllMain (WS2_32.init)
862 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
864 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
865 switch (fdwReason) {
866 case DLL_PROCESS_ATTACH:
867 break;
868 case DLL_PROCESS_DETACH:
869 free_per_thread_data();
870 DeleteCriticalSection(&csWSgetXXXbyYYY);
871 num_startup = 0;
872 break;
873 case DLL_THREAD_DETACH:
874 free_per_thread_data();
875 break;
877 return TRUE;
880 /***********************************************************************
881 * convert_sockopt()
883 * Converts socket flags from Windows format.
884 * Return 1 if converted, 0 if not (error).
886 static int convert_sockopt(INT *level, INT *optname)
888 unsigned int i;
889 switch (*level)
891 case WS_SOL_SOCKET:
892 *level = SOL_SOCKET;
893 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
894 if( ws_sock_map[i][0] == *optname )
896 *optname = ws_sock_map[i][1];
897 return 1;
900 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
901 break;
902 case WS_IPPROTO_TCP:
903 *level = IPPROTO_TCP;
904 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
905 if ( ws_tcp_map[i][0] == *optname )
907 *optname = ws_tcp_map[i][1];
908 return 1;
911 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
912 break;
913 case WS_IPPROTO_IP:
914 *level = IPPROTO_IP;
915 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
916 if (ws_ip_map[i][0] == *optname )
918 *optname = ws_ip_map[i][1];
919 return 1;
922 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
923 break;
924 case WS_IPPROTO_IPV6:
925 *level = IPPROTO_IPV6;
926 for(i=0; i<sizeof(ws_ipv6_map)/sizeof(ws_ipv6_map[0]); i++) {
927 if (ws_ipv6_map[i][0] == *optname )
929 *optname = ws_ipv6_map[i][1];
930 return 1;
933 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname);
934 break;
935 default: FIXME("Unimplemented or unknown socket level\n");
937 return 0;
940 /* ----------------------------------- Per-thread info (or per-process?) */
942 static char *strdup_lower(const char *str)
944 int i;
945 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
947 if (ret)
949 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
950 ret[i] = 0;
952 else SetLastError(WSAENOBUFS);
953 return ret;
956 static inline int sock_error_p(int s)
958 unsigned int optval, optlen;
960 optlen = sizeof(optval);
961 getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
962 if (optval) WARN("\t[%i] error: %d\n", s, optval);
963 return optval != 0;
966 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
967 * from an fd and return the value converted to milli seconds
968 * or -1 if there is an infinite time out */
969 static inline int get_rcvsnd_timeo( int fd, int optname)
971 struct timeval tv;
972 unsigned int len = sizeof(tv);
973 int ret = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
974 if( ret >= 0)
975 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
976 if( ret <= 0 ) /* tv == {0,0} means infinite time out */
977 return -1;
978 return ret;
981 /* macro wrappers for portability */
982 #ifdef SO_RCVTIMEO
983 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
984 #else
985 #define GET_RCVTIMEO(fd) (-1)
986 #endif
988 #ifdef SO_SNDTIMEO
989 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
990 #else
991 #define GET_SNDTIMEO(fd) (-1)
992 #endif
994 /* utility: given an fd, will block until one of the events occurs */
995 static inline int do_block( int fd, int events, int timeout )
997 struct pollfd pfd;
998 int ret;
1000 pfd.fd = fd;
1001 pfd.events = events;
1003 while ((ret = poll(&pfd, 1, timeout)) < 0)
1005 if (errno != EINTR)
1006 return -1;
1008 if( ret == 0 )
1009 return 0;
1010 return pfd.revents;
1013 static int
1014 convert_af_w2u(int windowsaf) {
1015 unsigned int i;
1017 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1018 if (ws_af_map[i][0] == windowsaf)
1019 return ws_af_map[i][1];
1020 FIXME("unhandled Windows address family %d\n", windowsaf);
1021 return -1;
1024 static int
1025 convert_af_u2w(int unixaf) {
1026 unsigned int i;
1028 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1029 if (ws_af_map[i][1] == unixaf)
1030 return ws_af_map[i][0];
1031 FIXME("unhandled UNIX address family %d\n", unixaf);
1032 return -1;
1035 static int
1036 convert_proto_w2u(int windowsproto) {
1037 unsigned int i;
1039 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1040 if (ws_proto_map[i][0] == windowsproto)
1041 return ws_proto_map[i][1];
1042 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
1043 return -1;
1046 static int
1047 convert_proto_u2w(int unixproto) {
1048 unsigned int i;
1050 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1051 if (ws_proto_map[i][1] == unixproto)
1052 return ws_proto_map[i][0];
1053 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
1054 return -1;
1057 static int
1058 convert_socktype_w2u(int windowssocktype) {
1059 unsigned int i;
1061 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1062 if (ws_socktype_map[i][0] == windowssocktype)
1063 return ws_socktype_map[i][1];
1064 FIXME("unhandled Windows socket type %d\n", windowssocktype);
1065 return -1;
1068 static int
1069 convert_socktype_u2w(int unixsocktype) {
1070 unsigned int i;
1072 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1073 if (ws_socktype_map[i][1] == unixsocktype)
1074 return ws_socktype_map[i][0];
1075 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
1076 return -1;
1079 /* ----------------------------------- API -----
1081 * Init / cleanup / error checking.
1084 /***********************************************************************
1085 * WSAStartup (WS2_32.115)
1087 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
1089 TRACE("verReq=%x\n", wVersionRequested);
1091 if (LOBYTE(wVersionRequested) < 1)
1092 return WSAVERNOTSUPPORTED;
1094 if (!lpWSAData) return WSAEINVAL;
1096 num_startup++;
1098 /* that's the whole of the negotiation for now */
1099 lpWSAData->wVersion = wVersionRequested;
1100 /* return winsock information */
1101 lpWSAData->wHighVersion = 0x0202;
1102 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
1103 strcpy(lpWSAData->szSystemStatus, "Running" );
1104 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
1105 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
1106 /* don't do anything with lpWSAData->lpVendorInfo */
1107 /* (some apps don't allocate the space for this field) */
1109 TRACE("succeeded\n");
1110 return 0;
1114 /***********************************************************************
1115 * WSACleanup (WS2_32.116)
1117 INT WINAPI WSACleanup(void)
1119 if (num_startup) {
1120 num_startup--;
1121 return 0;
1123 SetLastError(WSANOTINITIALISED);
1124 return SOCKET_ERROR;
1128 /***********************************************************************
1129 * WSAGetLastError (WS2_32.111)
1131 INT WINAPI WSAGetLastError(void)
1133 return GetLastError();
1136 /***********************************************************************
1137 * WSASetLastError (WS2_32.112)
1139 void WINAPI WSASetLastError(INT iError) {
1140 SetLastError(iError);
1143 static struct WS_hostent *check_buffer_he(int size)
1145 struct per_thread_data * ptb = get_per_thread_data();
1146 if (ptb->he_buffer)
1148 if (ptb->he_len >= size ) return ptb->he_buffer;
1149 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1151 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
1152 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
1153 return ptb->he_buffer;
1156 static struct WS_servent *check_buffer_se(int size)
1158 struct per_thread_data * ptb = get_per_thread_data();
1159 if (ptb->se_buffer)
1161 if (ptb->se_len >= size ) return ptb->se_buffer;
1162 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1164 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
1165 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
1166 return ptb->se_buffer;
1169 static struct WS_protoent *check_buffer_pe(int size)
1171 struct per_thread_data * ptb = get_per_thread_data();
1172 if (ptb->pe_buffer)
1174 if (ptb->pe_len >= size ) return ptb->pe_buffer;
1175 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1177 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
1178 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
1179 return ptb->pe_buffer;
1182 /* ----------------------------------- i/o APIs */
1184 static inline BOOL supported_pf(int pf)
1186 switch (pf)
1188 case WS_AF_INET:
1189 case WS_AF_INET6:
1190 return TRUE;
1191 #ifdef HAVE_IPX
1192 case WS_AF_IPX:
1193 return TRUE;
1194 #endif
1195 #ifdef HAVE_IRDA
1196 case WS_AF_IRDA:
1197 return TRUE;
1198 #endif
1199 default:
1200 return FALSE;
1205 /**********************************************************************/
1207 /* Returns the length of the converted address if successful, 0 if it was too small to
1208 * start with.
1210 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
1211 union generic_unix_sockaddr *uaddr)
1213 unsigned int uaddrlen = 0;
1215 switch (wsaddr->sa_family)
1217 #ifdef HAVE_IPX
1218 case WS_AF_IPX:
1220 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
1221 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
1223 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
1224 return 0;
1226 uaddrlen = sizeof(struct sockaddr_ipx);
1227 memset( uaddr, 0, uaddrlen );
1228 uipx->sipx_family=AF_IPX;
1229 uipx->sipx_port=wsipx->sa_socket;
1230 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1231 * in one go
1233 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
1234 #ifdef IPX_FRAME_NONE
1235 uipx->sipx_type=IPX_FRAME_NONE;
1236 #endif
1237 break;
1239 #endif
1240 case WS_AF_INET6: {
1241 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
1242 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
1244 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1245 * scope_id, one without.
1247 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
1248 uaddrlen = sizeof(struct sockaddr_in6);
1249 memset( uaddr, 0, uaddrlen );
1250 uin6->sin6_family = AF_INET6;
1251 uin6->sin6_port = win6->sin6_port;
1252 uin6->sin6_flowinfo = win6->sin6_flowinfo;
1253 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1254 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
1255 #endif
1256 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
1257 break;
1259 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
1260 return 0;
1262 case WS_AF_INET: {
1263 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
1264 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
1266 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
1267 return 0;
1268 uaddrlen = sizeof(struct sockaddr_in);
1269 memset( uaddr, 0, uaddrlen );
1270 uin->sin_family = AF_INET;
1271 uin->sin_port = win->sin_port;
1272 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
1273 break;
1275 #ifdef HAVE_IRDA
1276 case WS_AF_IRDA: {
1277 struct sockaddr_irda *uin = (struct sockaddr_irda *)uaddr;
1278 const SOCKADDR_IRDA *win = (const SOCKADDR_IRDA *)wsaddr;
1280 if (wsaddrlen < sizeof(SOCKADDR_IRDA))
1281 return 0;
1282 uaddrlen = sizeof(struct sockaddr_irda);
1283 memset( uaddr, 0, uaddrlen );
1284 uin->sir_family = AF_IRDA;
1285 if (!strncmp( win->irdaServiceName, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1287 unsigned int lsap_sel = 0;
1289 sscanf( win->irdaServiceName, "LSAP-SEL%u", &lsap_sel );
1290 uin->sir_lsap_sel = lsap_sel;
1292 else
1294 uin->sir_lsap_sel = LSAP_ANY;
1295 memcpy( uin->sir_name, win->irdaServiceName, 25 );
1297 memcpy( &uin->sir_addr, win->irdaDeviceID, sizeof(uin->sir_addr) );
1298 break;
1300 #endif
1301 case WS_AF_UNSPEC: {
1302 /* Try to determine the needed space by the passed windows sockaddr space */
1303 switch (wsaddrlen) {
1304 default: /* likely a ipv4 address */
1305 case sizeof(struct WS_sockaddr_in):
1306 uaddrlen = sizeof(struct sockaddr_in);
1307 break;
1308 #ifdef HAVE_IPX
1309 case sizeof(struct WS_sockaddr_ipx):
1310 uaddrlen = sizeof(struct sockaddr_ipx);
1311 break;
1312 #endif
1313 #ifdef HAVE_IRDA
1314 case sizeof(SOCKADDR_IRDA):
1315 uaddrlen = sizeof(struct sockaddr_irda);
1316 break;
1317 #endif
1318 case sizeof(struct WS_sockaddr_in6):
1319 case sizeof(struct WS_sockaddr_in6_old):
1320 uaddrlen = sizeof(struct sockaddr_in6);
1321 break;
1323 memset( uaddr, 0, uaddrlen );
1324 break;
1326 default:
1327 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
1328 return 0;
1330 return uaddrlen;
1333 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
1335 switch (uaddr->sa_family)
1337 #ifdef HAVE_IPX
1338 case AF_IPX:
1339 FIXME("don't know how to tell if IPX socket is bound, assuming it is!\n");
1340 return TRUE;
1341 #endif
1342 case AF_INET6:
1344 static const struct sockaddr_in6 emptyAddr;
1345 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
1346 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
1348 case AF_INET:
1350 static const struct sockaddr_in emptyAddr;
1351 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
1352 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
1354 case AF_UNSPEC:
1355 return FALSE;
1356 default:
1357 FIXME("unknown address family %d\n", uaddr->sa_family);
1358 return TRUE;
1362 /* Returns 0 if successful, -1 if the buffer is too small */
1363 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
1365 int res;
1367 switch(uaddr->sa_family)
1369 #ifdef HAVE_IPX
1370 case AF_IPX:
1372 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
1373 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
1375 res=-1;
1376 switch (*wsaddrlen) /* how much can we copy? */
1378 default:
1379 res=0; /* enough */
1380 *wsaddrlen = sizeof(*wsipx);
1381 wsipx->sa_socket=uipx->sipx_port;
1382 /* fall through */
1383 case 13:
1384 case 12:
1385 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
1386 /* fall through */
1387 case 11:
1388 case 10:
1389 case 9:
1390 case 8:
1391 case 7:
1392 case 6:
1393 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1394 /* fall through */
1395 case 5:
1396 case 4:
1397 case 3:
1398 case 2:
1399 wsipx->sa_family=WS_AF_IPX;
1400 /* fall through */
1401 case 1:
1402 case 0:
1403 /* way too small */
1404 break;
1407 break;
1408 #endif
1409 #ifdef HAVE_IRDA
1410 case AF_IRDA: {
1411 const struct sockaddr_irda *uin = (const struct sockaddr_irda *)uaddr;
1412 SOCKADDR_IRDA *win = (SOCKADDR_IRDA *)wsaddr;
1414 if (*wsaddrlen < sizeof(SOCKADDR_IRDA))
1415 return -1;
1416 win->irdaAddressFamily = WS_AF_IRDA;
1417 memcpy( win->irdaDeviceID, &uin->sir_addr, sizeof(win->irdaDeviceID) );
1418 if (uin->sir_lsap_sel != LSAP_ANY)
1419 sprintf( win->irdaServiceName, "LSAP-SEL%u", uin->sir_lsap_sel );
1420 else
1421 memcpy( win->irdaServiceName, uin->sir_name,
1422 sizeof(win->irdaServiceName) );
1423 return 0;
1425 #endif
1426 case AF_INET6: {
1427 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1428 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1430 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1431 return -1;
1432 win6old->sin6_family = WS_AF_INET6;
1433 win6old->sin6_port = uin6->sin6_port;
1434 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1435 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1436 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1437 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1438 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1439 win6->sin6_scope_id = uin6->sin6_scope_id;
1440 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1442 else
1443 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1444 #else
1445 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1446 #endif
1447 return 0;
1449 case AF_INET: {
1450 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1451 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1453 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1454 return -1;
1455 win->sin_family = WS_AF_INET;
1456 win->sin_port = uin->sin_port;
1457 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1458 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1459 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1460 return 0;
1462 case AF_UNSPEC: {
1463 memset(wsaddr,0,*wsaddrlen);
1464 return 0;
1466 default:
1467 FIXME("Unknown address family %d\n", uaddr->sa_family);
1468 return -1;
1470 return res;
1473 /**************************************************************************
1474 * Functions for handling overlapped I/O
1475 **************************************************************************/
1477 /* user APC called upon async completion */
1478 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1480 ws2_async *wsa = arg;
1482 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
1483 iosb->Information, wsa->user_overlapped,
1484 wsa->flags );
1485 HeapFree( GetProcessHeap(), 0, wsa );
1488 /***********************************************************************
1489 * WS2_recv (INTERNAL)
1491 * Workhorse for both synchronous and asynchronous recv() operations.
1493 static int WS2_recv( int fd, struct ws2_async *wsa )
1495 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1496 char pktbuf[512];
1497 #endif
1498 struct msghdr hdr;
1499 union generic_unix_sockaddr unix_sockaddr;
1500 int n;
1502 hdr.msg_name = NULL;
1504 if (wsa->addr)
1506 hdr.msg_namelen = sizeof(unix_sockaddr);
1507 hdr.msg_name = &unix_sockaddr;
1509 else
1510 hdr.msg_namelen = 0;
1512 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1513 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1514 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1515 hdr.msg_accrights = NULL;
1516 hdr.msg_accrightslen = 0;
1517 #else
1518 hdr.msg_control = pktbuf;
1519 hdr.msg_controllen = sizeof(pktbuf);
1520 hdr.msg_flags = 0;
1521 #endif
1523 if ( (n = recvmsg(fd, &hdr, wsa->flags)) == -1 )
1524 return -1;
1526 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1527 if (wsa->control)
1529 ERR("Message control headers cannot be properly supported on this system.\n");
1530 wsa->control->len = 0;
1532 #else
1533 if (wsa->control && !convert_control_headers(&hdr, wsa->control))
1535 WARN("Application passed insufficient room for control headers.\n");
1536 *wsa->lpFlags |= WS_MSG_CTRUNC;
1537 errno = EMSGSIZE;
1538 return -1;
1540 #endif
1542 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
1543 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
1545 * quoting linux 2.6 net/ipv4/tcp.c:
1546 * "According to UNIX98, msg_name/msg_namelen are ignored
1547 * on connected socket. I was just happy when found this 8) --ANK"
1549 * likewise MSDN says that lpFrom and lpFromlen are ignored for
1550 * connection-oriented sockets, so don't try to update lpFrom.
1552 if (wsa->addr && hdr.msg_namelen)
1553 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
1555 return n;
1558 /***********************************************************************
1559 * WS2_async_recv (INTERNAL)
1561 * Handler for overlapped recv() operations.
1563 static NTSTATUS WS2_async_recv( void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1565 ws2_async* wsa = user;
1566 int result = 0, fd;
1568 switch (status)
1570 case STATUS_ALERTED:
1571 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
1572 break;
1574 result = WS2_recv( fd, wsa );
1575 wine_server_release_fd( wsa->hSocket, fd );
1576 if (result >= 0)
1578 status = STATUS_SUCCESS;
1579 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1581 else
1583 if (errno == EINTR || errno == EAGAIN)
1585 status = STATUS_PENDING;
1586 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1588 else
1590 result = 0;
1591 status = wsaErrStatus();
1594 break;
1596 if (status != STATUS_PENDING)
1598 iosb->u.Status = status;
1599 iosb->Information = result;
1600 *apc = ws2_async_apc;
1602 return status;
1605 /* user APC called upon async accept completion */
1606 static void WINAPI ws2_async_accept_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1608 struct ws2_accept_async *wsa = arg;
1610 HeapFree( GetProcessHeap(), 0, wsa->read );
1611 HeapFree( GetProcessHeap(), 0, wsa );
1614 /***********************************************************************
1615 * WS2_async_accept_recv (INTERNAL)
1617 * This function is used to finish the read part of an accept request. It is
1618 * needed to place the completion on the correct socket (listener).
1620 static NTSTATUS WS2_async_accept_recv( void *arg, IO_STATUS_BLOCK *iosb, NTSTATUS status, void **apc )
1622 void *junk;
1623 struct ws2_accept_async *wsa = arg;
1625 status = WS2_async_recv( wsa->read, iosb, status, &junk );
1626 if (status == STATUS_PENDING)
1627 return status;
1629 if (wsa->user_overlapped->hEvent)
1630 SetEvent(wsa->user_overlapped->hEvent);
1631 if (wsa->cvalue)
1632 WS_AddCompletion( HANDLE2SOCKET(wsa->listen_socket), wsa->cvalue, iosb->u.Status, iosb->Information );
1634 *apc = ws2_async_accept_apc;
1635 return status;
1638 /***********************************************************************
1639 * WS2_async_accept (INTERNAL)
1641 * This is the function called to satisfy the AcceptEx callback
1643 static NTSTATUS WS2_async_accept( void *arg, IO_STATUS_BLOCK *iosb, NTSTATUS status, void **apc )
1645 struct ws2_accept_async *wsa = arg;
1646 int len;
1647 char *addr;
1649 TRACE("status: 0x%x listen: %p, accept: %p\n", status, wsa->listen_socket, wsa->accept_socket);
1651 if (status == STATUS_ALERTED)
1653 SERVER_START_REQ( accept_into_socket )
1655 req->lhandle = wine_server_obj_handle( wsa->listen_socket );
1656 req->ahandle = wine_server_obj_handle( wsa->accept_socket );
1657 status = wine_server_call( req );
1659 SERVER_END_REQ;
1661 if (status == STATUS_CANT_WAIT)
1662 return STATUS_PENDING;
1664 if (status == STATUS_INVALID_HANDLE)
1666 FIXME("AcceptEx accepting socket closed but request was not cancelled\n");
1667 status = STATUS_CANCELLED;
1670 else if (status == STATUS_HANDLES_CLOSED)
1671 status = STATUS_CANCELLED; /* strange windows behavior */
1673 if (status != STATUS_SUCCESS)
1674 goto finish;
1676 /* WS2 Spec says size param is extra 16 bytes long...what do we put in it? */
1677 addr = ((char *)wsa->buf) + wsa->data_len;
1678 len = wsa->local_len - sizeof(int);
1679 WS_getsockname(HANDLE2SOCKET(wsa->accept_socket),
1680 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
1681 *(int *)addr = len;
1683 addr += wsa->local_len;
1684 len = wsa->remote_len - sizeof(int);
1685 WS_getpeername(HANDLE2SOCKET(wsa->accept_socket),
1686 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
1687 *(int *)addr = len;
1689 if (!wsa->read)
1690 goto finish;
1692 SERVER_START_REQ( register_async )
1694 req->type = ASYNC_TYPE_READ;
1695 req->async.handle = wine_server_obj_handle( wsa->accept_socket );
1696 req->async.callback = wine_server_client_ptr( WS2_async_accept_recv );
1697 req->async.iosb = wine_server_client_ptr( iosb );
1698 req->async.arg = wine_server_client_ptr( wsa );
1699 status = wine_server_call( req );
1701 SERVER_END_REQ;
1703 if (status != STATUS_PENDING)
1704 goto finish;
1706 return STATUS_SUCCESS;
1708 finish:
1709 iosb->u.Status = status;
1710 iosb->Information = 0;
1712 if (wsa->user_overlapped->hEvent)
1713 SetEvent(wsa->user_overlapped->hEvent);
1714 if (wsa->cvalue)
1715 WS_AddCompletion( HANDLE2SOCKET(wsa->listen_socket), wsa->cvalue, iosb->u.Status, iosb->Information );
1717 *apc = ws2_async_accept_apc;
1718 return status;
1721 /***********************************************************************
1722 * WS2_send (INTERNAL)
1724 * Workhorse for both synchronous and asynchronous send() operations.
1726 static int WS2_send( int fd, struct ws2_async *wsa )
1728 struct msghdr hdr;
1729 union generic_unix_sockaddr unix_addr;
1730 int n, ret;
1732 hdr.msg_name = NULL;
1733 hdr.msg_namelen = 0;
1735 if (wsa->addr)
1737 hdr.msg_name = &unix_addr;
1738 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
1739 if ( !hdr.msg_namelen )
1741 errno = EFAULT;
1742 return -1;
1745 #if defined(HAVE_IPX) && defined(SOL_IPX)
1746 if(wsa->addr->sa_family == WS_AF_IPX)
1748 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
1749 int val=0;
1750 unsigned int len=sizeof(int);
1752 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
1753 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
1754 * the packet type and then we can retrieve it using getsockopt. After that we can set the
1755 * ipx type in the sockaddr_opx structure with the stored value.
1757 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
1758 uipx->sipx_type = val;
1760 #endif
1763 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1764 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1765 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1766 hdr.msg_accrights = NULL;
1767 hdr.msg_accrightslen = 0;
1768 #else
1769 hdr.msg_control = NULL;
1770 hdr.msg_controllen = 0;
1771 hdr.msg_flags = 0;
1772 #endif
1774 ret = sendmsg(fd, &hdr, wsa->flags);
1775 if (ret >= 0)
1777 n = ret;
1778 while (wsa->first_iovec < wsa->n_iovecs && wsa->iovec[wsa->first_iovec].iov_len <= n)
1779 n -= wsa->iovec[wsa->first_iovec++].iov_len;
1780 if (wsa->first_iovec < wsa->n_iovecs)
1782 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
1783 wsa->iovec[wsa->first_iovec].iov_len -= n;
1786 return ret;
1789 /***********************************************************************
1790 * WS2_async_send (INTERNAL)
1792 * Handler for overlapped send() operations.
1794 static NTSTATUS WS2_async_send(void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1796 ws2_async* wsa = user;
1797 int result = 0, fd;
1799 switch (status)
1801 case STATUS_ALERTED:
1802 if ( wsa->n_iovecs <= wsa->first_iovec )
1804 /* Nothing to do */
1805 status = STATUS_SUCCESS;
1806 break;
1808 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
1809 break;
1811 /* check to see if the data is ready (non-blocking) */
1812 result = WS2_send( fd, wsa );
1813 wine_server_release_fd( wsa->hSocket, fd );
1815 if (result >= 0)
1817 if (wsa->first_iovec < wsa->n_iovecs)
1818 status = STATUS_PENDING;
1819 else
1820 status = STATUS_SUCCESS;
1822 iosb->Information += result;
1824 else if (errno == EINTR || errno == EAGAIN)
1826 status = STATUS_PENDING;
1828 else
1830 status = wsaErrStatus();
1832 break;
1834 if (status != STATUS_PENDING)
1836 iosb->u.Status = status;
1837 *apc = ws2_async_apc;
1839 return status;
1842 /***********************************************************************
1843 * WS2_async_shutdown (INTERNAL)
1845 * Handler for shutdown() operations on overlapped sockets.
1847 static NTSTATUS WS2_async_shutdown( void* user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc )
1849 ws2_async* wsa = user;
1850 int fd, err = 1;
1852 switch (status)
1854 case STATUS_ALERTED:
1855 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
1856 break;
1858 switch ( wsa->type )
1860 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
1861 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
1863 status = err ? wsaErrStatus() : STATUS_SUCCESS;
1864 wine_server_release_fd( wsa->hSocket, fd );
1865 break;
1867 iosb->u.Status = status;
1868 iosb->Information = 0;
1869 *apc = ws2_async_apc;
1870 return status;
1873 /***********************************************************************
1874 * WS2_register_async_shutdown (INTERNAL)
1876 * Helper function for WS_shutdown() on overlapped sockets.
1878 static int WS2_register_async_shutdown( SOCKET s, int type )
1880 struct ws2_async *wsa;
1881 NTSTATUS status;
1883 TRACE("s %ld type %d\n", s, type);
1885 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
1886 if ( !wsa )
1887 return WSAEFAULT;
1889 wsa->hSocket = SOCKET2HANDLE(s);
1890 wsa->type = type;
1891 wsa->completion_func = NULL;
1893 SERVER_START_REQ( register_async )
1895 req->type = type;
1896 req->async.handle = wine_server_obj_handle( wsa->hSocket );
1897 req->async.callback = wine_server_client_ptr( WS2_async_shutdown );
1898 req->async.iosb = wine_server_client_ptr( &wsa->local_iosb );
1899 req->async.arg = wine_server_client_ptr( wsa );
1900 req->async.cvalue = 0;
1901 status = wine_server_call( req );
1903 SERVER_END_REQ;
1905 if (status != STATUS_PENDING)
1907 HeapFree( GetProcessHeap(), 0, wsa );
1908 return NtStatusToWSAError( status );
1910 return 0;
1913 /***********************************************************************
1914 * accept (WS2_32.1)
1916 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr,
1917 int *addrlen32)
1919 NTSTATUS status;
1920 SOCKET as;
1921 BOOL is_blocking;
1923 TRACE("socket %04lx\n", s );
1924 is_blocking = _is_blocking(s);
1926 do {
1927 /* try accepting first (if there is a deferred connection) */
1928 SERVER_START_REQ( accept_socket )
1930 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1931 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
1932 req->attributes = OBJ_INHERIT;
1933 status = wine_server_call( req );
1934 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
1936 SERVER_END_REQ;
1937 if (!status)
1939 if (addr) WS_getpeername(as, addr, addrlen32);
1940 return as;
1942 if (is_blocking && status == STATUS_CANT_WAIT)
1944 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1945 /* block here */
1946 do_block(fd, POLLIN, -1);
1947 _sync_sock_state(s); /* let wineserver notice connection */
1948 release_sock_fd( s, fd );
1950 } while (is_blocking && status == STATUS_CANT_WAIT);
1952 set_error(status);
1953 return INVALID_SOCKET;
1956 /***********************************************************************
1957 * AcceptEx
1959 static BOOL WINAPI WS2_AcceptEx(SOCKET listener, SOCKET acceptor, PVOID dest, DWORD dest_len,
1960 DWORD local_addr_len, DWORD rem_addr_len, LPDWORD received,
1961 LPOVERLAPPED overlapped)
1963 DWORD status;
1964 struct ws2_accept_async *wsa;
1965 int fd;
1966 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
1968 TRACE("(%lx, %lx, %p, %d, %d, %d, %p, %p)\n", listener, acceptor, dest, dest_len, local_addr_len,
1969 rem_addr_len, received, overlapped);
1971 if (!dest)
1973 SetLastError(WSAEINVAL);
1974 return FALSE;
1977 if (!overlapped)
1979 SetLastError(WSA_INVALID_PARAMETER);
1980 return FALSE;
1983 fd = get_sock_fd( listener, FILE_READ_DATA, NULL );
1984 if (fd == -1)
1986 SetLastError(WSAENOTSOCK);
1987 return FALSE;
1989 release_sock_fd( listener, fd );
1991 fd = get_sock_fd( acceptor, FILE_READ_DATA, NULL );
1992 if (fd == -1)
1994 SetLastError(WSAEINVAL);
1995 return FALSE;
1997 release_sock_fd( acceptor, fd );
1999 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
2000 if(!wsa)
2002 SetLastError(WSAEFAULT);
2003 return FALSE;
2006 wsa->listen_socket = SOCKET2HANDLE(listener);
2007 wsa->accept_socket = SOCKET2HANDLE(acceptor);
2008 wsa->user_overlapped = overlapped;
2009 wsa->cvalue = cvalue;
2010 wsa->buf = dest;
2011 wsa->data_len = dest_len;
2012 wsa->local_len = local_addr_len;
2013 wsa->remote_len = rem_addr_len;
2014 wsa->read = NULL;
2016 if (wsa->data_len)
2018 /* set up a read request if we need it */
2019 wsa->read = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[1]) );
2020 if (!wsa->read)
2022 HeapFree( GetProcessHeap(), 0, wsa );
2023 SetLastError(WSAEFAULT);
2024 return FALSE;
2027 wsa->read->hSocket = wsa->accept_socket;
2028 wsa->read->flags = 0;
2029 wsa->read->lpFlags = &wsa->read->flags;
2030 wsa->read->addr = NULL;
2031 wsa->read->addrlen.ptr = NULL;
2032 wsa->read->control = NULL;
2033 wsa->read->n_iovecs = 1;
2034 wsa->read->first_iovec = 0;
2035 wsa->read->iovec[0].iov_base = wsa->buf;
2036 wsa->read->iovec[0].iov_len = wsa->data_len;
2039 SERVER_START_REQ( register_async )
2041 req->type = ASYNC_TYPE_READ;
2042 req->async.handle = wine_server_obj_handle( SOCKET2HANDLE(listener) );
2043 req->async.callback = wine_server_client_ptr( WS2_async_accept );
2044 req->async.iosb = wine_server_client_ptr( overlapped );
2045 req->async.arg = wine_server_client_ptr( wsa );
2046 /* We don't set event or completion since we may also have to read */
2047 status = wine_server_call( req );
2049 SERVER_END_REQ;
2051 if(status != STATUS_PENDING)
2053 HeapFree( GetProcessHeap(), 0, wsa->read );
2054 HeapFree( GetProcessHeap(), 0, wsa );
2057 SetLastError( NtStatusToWSAError(status) );
2058 return FALSE;
2061 /***********************************************************************
2062 * GetAcceptExSockaddrs
2064 static void WINAPI WS2_GetAcceptExSockaddrs(PVOID buffer, DWORD data_size, DWORD local_size, DWORD remote_size,
2065 struct WS_sockaddr **local_addr, LPINT local_addr_len,
2066 struct WS_sockaddr **remote_addr, LPINT remote_addr_len)
2068 char *cbuf = buffer;
2069 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer, data_size, local_size, remote_size, local_addr,
2070 local_addr_len, remote_addr, remote_addr_len );
2071 cbuf += data_size;
2073 *local_addr_len = *(int *) cbuf;
2074 *local_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2076 cbuf += local_size;
2078 *remote_addr_len = *(int *) cbuf;
2079 *remote_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2082 /***********************************************************************
2083 * WSARecvMsg
2085 * Perform a receive operation that is capable of returning message
2086 * control headers. It is important to note that the WSAMSG parameter
2087 * must remain valid throughout the operation, even when an overlapped
2088 * receive is performed.
2090 static int WINAPI WS2_WSARecvMsg( SOCKET s, LPWSAMSG msg, LPDWORD lpNumberOfBytesRecvd,
2091 LPWSAOVERLAPPED lpOverlapped,
2092 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2094 if (!msg)
2096 SetLastError( WSAEFAULT );
2097 return SOCKET_ERROR;
2100 return WS2_recv_base( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesRecvd,
2101 &msg->dwFlags, msg->name, &msg->namelen,
2102 lpOverlapped, lpCompletionRoutine, &msg->Control );
2105 /***********************************************************************
2106 * bind (WS2_32.2)
2108 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
2110 int fd = get_sock_fd( s, 0, NULL );
2111 int res = SOCKET_ERROR;
2113 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2115 if (fd != -1)
2117 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
2119 SetLastError(WSAEAFNOSUPPORT);
2121 else
2123 union generic_unix_sockaddr uaddr;
2124 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2125 if (!uaddrlen)
2127 SetLastError(WSAEFAULT);
2129 else
2131 #ifdef IPV6_V6ONLY
2132 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
2133 if (name->sa_family == WS_AF_INET6 &&
2134 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
2136 int enable = 1;
2137 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
2139 release_sock_fd( s, fd );
2140 SetLastError(WSAEAFNOSUPPORT);
2141 return SOCKET_ERROR;
2144 #endif
2145 if (name->sa_family == WS_AF_INET)
2147 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2148 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2150 /* Trying to bind to the default host interface, using
2151 * INADDR_ANY instead*/
2152 WARN("Trying to bind to magic IP address, using "
2153 "INADDR_ANY instead.\n");
2154 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
2157 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
2159 int loc_errno = errno;
2160 WARN("\tfailure - errno = %i\n", errno);
2161 errno = loc_errno;
2162 switch (errno)
2164 case EBADF:
2165 SetLastError(WSAENOTSOCK);
2166 break;
2167 case EADDRNOTAVAIL:
2168 SetLastError(WSAEINVAL);
2169 break;
2170 default:
2171 SetLastError(wsaErrno());
2172 break;
2175 else
2177 res=0; /* success */
2181 release_sock_fd( s, fd );
2183 return res;
2186 /***********************************************************************
2187 * closesocket (WS2_32.3)
2189 int WINAPI WS_closesocket(SOCKET s)
2191 TRACE("socket %04lx\n", s);
2192 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
2193 return SOCKET_ERROR;
2196 static int do_connect(int fd, const struct WS_sockaddr* name, int namelen)
2198 union generic_unix_sockaddr uaddr;
2199 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2201 if (!uaddrlen)
2202 return WSAEFAULT;
2204 if (name->sa_family == WS_AF_INET)
2206 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2207 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2209 /* Trying to connect to magic replace-loopback address,
2210 * assuming we really want to connect to localhost */
2211 TRACE("Trying to connect to magic IP address, using "
2212 "INADDR_LOOPBACK instead.\n");
2213 in4->sin_addr.s_addr = htonl(WS_INADDR_LOOPBACK);
2217 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
2218 return 0;
2220 return wsaErrno();
2223 /***********************************************************************
2224 * connect (WS2_32.4)
2226 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
2228 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2230 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2232 if (fd != -1)
2234 int ret = do_connect(fd, name, namelen);
2235 if (ret == 0)
2236 goto connect_success;
2238 if (ret == WSAEINPROGRESS)
2240 /* tell wineserver that a connection is in progress */
2241 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2242 FD_CONNECT,
2243 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2244 if (_is_blocking(s))
2246 int result;
2247 /* block here */
2248 do_block(fd, POLLIN | POLLOUT, -1);
2249 _sync_sock_state(s); /* let wineserver notice connection */
2250 /* retrieve any error codes from it */
2251 result = _get_sock_error(s, FD_CONNECT_BIT);
2252 if (result)
2253 SetLastError(NtStatusToWSAError(result));
2254 else
2256 goto connect_success;
2259 else
2261 SetLastError(WSAEWOULDBLOCK);
2264 else
2266 SetLastError(ret);
2268 release_sock_fd( s, fd );
2270 return SOCKET_ERROR;
2272 connect_success:
2273 release_sock_fd( s, fd );
2274 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2275 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2276 FD_CONNECT|FD_WINE_LISTENING);
2277 return 0;
2280 /***********************************************************************
2281 * WSAConnect (WS2_32.30)
2283 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
2284 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
2285 LPQOS lpSQOS, LPQOS lpGQOS )
2287 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
2288 FIXME("unsupported parameters!\n");
2289 return WS_connect( s, name, namelen );
2292 /***********************************************************************
2293 * ConnectEx
2295 static BOOL WINAPI WS2_ConnectEx(SOCKET s, const struct WS_sockaddr* name, int namelen,
2296 PVOID sendBuf, DWORD sendBufLen, LPDWORD sent, LPOVERLAPPED ov)
2298 int fd, ret, status;
2300 if (!ov)
2302 SetLastError( ERROR_INVALID_PARAMETER );
2303 return FALSE;
2306 fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2307 if (fd == -1)
2309 SetLastError( WSAENOTSOCK );
2310 return FALSE;
2313 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
2314 s, name, debugstr_sockaddr(name), namelen, sendBuf, sendBufLen, ov);
2316 /* FIXME: technically the socket has to be bound */
2317 ret = do_connect(fd, name, namelen);
2318 if (ret == 0)
2320 WSABUF wsabuf;
2322 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2323 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2324 FD_CONNECT|FD_WINE_LISTENING);
2326 wsabuf.len = sendBufLen;
2327 wsabuf.buf = (char*) sendBuf;
2329 /* WSASend takes care of completion if need be */
2330 if (WSASend(s, &wsabuf, sendBuf ? 1 : 0, sent, 0, ov, NULL) != SOCKET_ERROR)
2331 goto connection_success;
2333 else if (ret == WSAEINPROGRESS)
2335 struct ws2_async *wsa;
2336 ULONG_PTR cvalue = (((ULONG_PTR)ov->hEvent & 1) == 0) ? (ULONG_PTR)ov : 0;
2338 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2339 FD_CONNECT,
2340 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2342 /* Indirectly call WSASend */
2343 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) )))
2345 SetLastError(WSAEFAULT);
2347 else
2349 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)ov;
2350 iosb->u.Status = STATUS_PENDING;
2351 iosb->Information = 0;
2353 wsa->hSocket = SOCKET2HANDLE(s);
2354 wsa->addr = NULL;
2355 wsa->addrlen.val = 0;
2356 wsa->flags = 0;
2357 wsa->lpFlags = &wsa->flags;
2358 wsa->control = NULL;
2359 wsa->n_iovecs = sendBuf ? 1 : 0;
2360 wsa->first_iovec = 0;
2361 wsa->completion_func = NULL;
2362 wsa->iovec[0].iov_base = sendBuf;
2363 wsa->iovec[0].iov_len = sendBufLen;
2365 SERVER_START_REQ( register_async )
2367 req->type = ASYNC_TYPE_WRITE;
2368 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2369 req->async.callback = wine_server_client_ptr( WS2_async_send );
2370 req->async.iosb = wine_server_client_ptr( iosb );
2371 req->async.arg = wine_server_client_ptr( wsa );
2372 req->async.event = wine_server_obj_handle( ov->hEvent );
2373 req->async.cvalue = cvalue;
2374 status = wine_server_call( req );
2376 SERVER_END_REQ;
2378 if (status != STATUS_PENDING) HeapFree(GetProcessHeap(), 0, wsa);
2380 /* If the connect already failed */
2381 if (status == STATUS_PIPE_DISCONNECTED)
2382 status = _get_sock_error(s, FD_CONNECT_BIT);
2383 SetLastError( NtStatusToWSAError(status) );
2386 else
2388 SetLastError(ret);
2391 release_sock_fd( s, fd );
2392 return FALSE;
2394 connection_success:
2395 release_sock_fd( s, fd );
2396 return TRUE;
2400 /***********************************************************************
2401 * getpeername (WS2_32.5)
2403 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
2405 int fd;
2406 int res;
2408 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, namelen?*namelen:0);
2410 fd = get_sock_fd( s, 0, NULL );
2411 res = SOCKET_ERROR;
2413 if (fd != -1)
2415 union generic_unix_sockaddr uaddr;
2416 unsigned int uaddrlen = sizeof(uaddr);
2418 if (getpeername(fd, &uaddr.addr, &uaddrlen) == 0)
2420 if (!name || !namelen)
2421 SetLastError(WSAEFAULT);
2422 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
2423 /* The buffer was too small */
2424 SetLastError(WSAEFAULT);
2425 else
2426 res = 0;
2428 else
2429 SetLastError(wsaErrno());
2430 release_sock_fd( s, fd );
2432 return res;
2435 /***********************************************************************
2436 * getsockname (WS2_32.6)
2438 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
2440 int fd;
2441 int res;
2443 TRACE("socket: %04lx, ptr %p, len %8x\n", s, name, *namelen);
2445 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
2446 if( (name == NULL) || (namelen == NULL) )
2448 SetLastError( WSAEFAULT );
2449 return SOCKET_ERROR;
2452 fd = get_sock_fd( s, 0, NULL );
2453 res = SOCKET_ERROR;
2455 if (fd != -1)
2457 union generic_unix_sockaddr uaddr;
2458 unsigned int uaddrlen = sizeof(uaddr);
2460 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
2462 SetLastError(wsaErrno());
2464 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
2466 SetLastError(WSAEINVAL);
2468 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
2470 /* The buffer was too small */
2471 SetLastError(WSAEFAULT);
2473 else
2475 res=0;
2477 release_sock_fd( s, fd );
2479 return res;
2482 /***********************************************************************
2483 * getsockopt (WS2_32.7)
2485 INT WINAPI WS_getsockopt(SOCKET s, INT level,
2486 INT optname, char *optval, INT *optlen)
2488 int fd;
2489 INT ret = 0;
2491 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
2492 s, level, optname, optval, *optlen);
2494 switch(level)
2496 case WS_SOL_SOCKET:
2498 switch(optname)
2500 /* Handle common cases. The special cases are below, sorted
2501 * alphabetically */
2502 case WS_SO_ACCEPTCONN:
2503 case WS_SO_BROADCAST:
2504 case WS_SO_DEBUG:
2505 case WS_SO_ERROR:
2506 case WS_SO_KEEPALIVE:
2507 case WS_SO_OOBINLINE:
2508 case WS_SO_RCVBUF:
2509 case WS_SO_REUSEADDR:
2510 case WS_SO_SNDBUF:
2511 case WS_SO_TYPE:
2512 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2513 return SOCKET_ERROR;
2514 convert_sockopt(&level, &optname);
2515 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2517 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2518 ret = SOCKET_ERROR;
2520 release_sock_fd( s, fd );
2521 return ret;
2523 case WS_SO_DONTLINGER:
2525 struct linger lingval;
2526 unsigned int len = sizeof(struct linger);
2528 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
2530 SetLastError(WSAEFAULT);
2531 return SOCKET_ERROR;
2533 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2534 return SOCKET_ERROR;
2536 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
2538 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2539 ret = SOCKET_ERROR;
2541 else
2543 *(BOOL *)optval = (lingval.l_onoff) ? FALSE : TRUE;
2544 *optlen = sizeof(BOOL);
2547 release_sock_fd( s, fd );
2548 return ret;
2551 case WS_SO_CONNECT_TIME:
2553 static int pretendtime = 0;
2554 struct WS_sockaddr addr;
2555 int len = sizeof(addr);
2557 if (!optlen || *optlen < sizeof(DWORD) || !optval)
2559 SetLastError(WSAEFAULT);
2560 return SOCKET_ERROR;
2562 if (WS_getpeername(s, &addr, &len) == SOCKET_ERROR)
2563 *(DWORD *)optval = ~0u;
2564 else
2566 if (!pretendtime) FIXME("WS_SO_CONNECT_TIME - faking results\n");
2567 *(DWORD *)optval = pretendtime++;
2569 *optlen = sizeof(DWORD);
2570 return ret;
2572 /* As mentioned in setsockopt, Windows ignores this, so we
2573 * always return true here */
2574 case WS_SO_DONTROUTE:
2575 if (!optlen || *optlen < sizeof(BOOL) || !optval)
2577 SetLastError(WSAEFAULT);
2578 return SOCKET_ERROR;
2580 *(BOOL *)optval = TRUE;
2581 *optlen = sizeof(BOOL);
2582 return 0;
2584 case WS_SO_LINGER:
2586 struct linger lingval;
2587 int so_type;
2588 unsigned int len = sizeof(struct linger), slen = sizeof(int);
2590 /* struct linger and LINGER have different sizes */
2591 if (!optlen || *optlen < sizeof(LINGER) || !optval)
2593 SetLastError(WSAEFAULT);
2594 return SOCKET_ERROR;
2596 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2597 return SOCKET_ERROR;
2599 if ((getsockopt(fd, SOL_SOCKET, SO_TYPE, &so_type, &slen) == 0 && so_type == SOCK_DGRAM))
2601 SetLastError(WSAENOPROTOOPT);
2602 ret = SOCKET_ERROR;
2604 else if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0)
2606 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2607 ret = SOCKET_ERROR;
2609 else
2611 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
2612 ((LINGER *)optval)->l_linger = lingval.l_linger;
2613 *optlen = sizeof(struct linger);
2616 release_sock_fd( s, fd );
2617 return ret;
2620 case WS_SO_MAX_MSG_SIZE:
2621 if (!optlen || *optlen < sizeof(int) || !optval)
2623 SetLastError(WSAEFAULT);
2624 return SOCKET_ERROR;
2626 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
2627 *(int *)optval = 65507;
2628 *optlen = sizeof(int);
2629 return 0;
2631 /* SO_OPENTYPE does not require a valid socket handle. */
2632 case WS_SO_OPENTYPE:
2633 if (!optlen || *optlen < sizeof(int) || !optval)
2635 SetLastError(WSAEFAULT);
2636 return SOCKET_ERROR;
2638 *(int *)optval = get_per_thread_data()->opentype;
2639 *optlen = sizeof(int);
2640 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
2641 return 0;
2643 #ifdef SO_RCVTIMEO
2644 case WS_SO_RCVTIMEO:
2645 #endif
2646 #ifdef SO_SNDTIMEO
2647 case WS_SO_SNDTIMEO:
2648 #endif
2649 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
2651 struct timeval tv;
2652 unsigned int len = sizeof(struct timeval);
2654 if (!optlen || *optlen < sizeof(int)|| !optval)
2656 SetLastError(WSAEFAULT);
2657 return SOCKET_ERROR;
2659 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2660 return SOCKET_ERROR;
2662 convert_sockopt(&level, &optname);
2663 if (getsockopt(fd, level, optname, &tv, &len) != 0 )
2665 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2666 ret = SOCKET_ERROR;
2668 else
2670 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
2671 *optlen = sizeof(int);
2674 release_sock_fd( s, fd );
2675 return ret;
2677 #endif
2678 default:
2679 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
2680 SetLastError(WSAENOPROTOOPT);
2681 return SOCKET_ERROR;
2682 } /* end switch(optname) */
2683 }/* end case WS_SOL_SOCKET */
2684 #ifdef HAVE_IPX
2685 case NSPROTO_IPX:
2687 struct WS_sockaddr_ipx addr;
2688 IPX_ADDRESS_DATA *data;
2689 int namelen;
2690 switch(optname)
2692 case IPX_PTYPE:
2693 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
2694 #ifdef SOL_IPX
2695 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (unsigned int*)optlen) == -1)
2697 ret = SOCKET_ERROR;
2699 #else
2701 struct ipx val;
2702 socklen_t len=sizeof(struct ipx);
2703 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
2704 ret = SOCKET_ERROR;
2705 else
2706 *optval = (int)val.ipx_pt;
2708 #endif
2709 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
2710 release_sock_fd( s, fd );
2711 return ret;
2713 case IPX_ADDRESS:
2715 * On a Win2000 system with one network card there are usually
2716 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
2717 * Using this call you can then retrieve info about this all.
2718 * In case of Linux it is a bit different. Usually you have
2719 * only "one" device active and further it is not possible to
2720 * query things like the linkspeed.
2722 FIXME("IPX_ADDRESS\n");
2723 namelen = sizeof(struct WS_sockaddr_ipx);
2724 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
2725 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
2727 data = (IPX_ADDRESS_DATA*)optval;
2728 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
2729 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
2730 data->adapternum = 0;
2731 data->wan = FALSE; /* We are not on a wan for now .. */
2732 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
2733 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
2734 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
2735 * note 1MB = 1000kB in this case */
2736 return 0;
2738 case IPX_MAX_ADAPTER_NUM:
2739 FIXME("IPX_MAX_ADAPTER_NUM\n");
2740 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
2741 return 0;
2743 default:
2744 FIXME("IPX optname:%x\n", optname);
2745 return SOCKET_ERROR;
2746 }/* end switch(optname) */
2747 } /* end case NSPROTO_IPX */
2748 #endif
2750 #ifdef HAVE_IRDA
2751 case WS_SOL_IRLMP:
2752 switch(optname)
2754 case WS_IRLMP_ENUMDEVICES:
2756 static const int MAX_IRDA_DEVICES = 10;
2757 char buf[sizeof(struct irda_device_list) +
2758 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
2759 int fd, res;
2760 socklen_t len = sizeof(buf);
2762 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2763 return SOCKET_ERROR;
2764 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
2765 if (res < 0)
2767 SetLastError(wsaErrno());
2768 return SOCKET_ERROR;
2770 else
2772 struct irda_device_list *src = (struct irda_device_list *)buf;
2773 DEVICELIST *dst = (DEVICELIST *)optval;
2774 INT needed = sizeof(DEVICELIST), i;
2776 if (src->len > 0)
2777 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
2778 if (*optlen < needed)
2780 SetLastError(WSAEFAULT);
2781 return SOCKET_ERROR;
2783 *optlen = needed;
2784 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
2785 dst->numDevice = src->len;
2786 for (i = 0; i < src->len; i++)
2788 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
2789 src->dev[i].saddr, src->dev[i].daddr,
2790 src->dev[i].info, src->dev[i].hints[0],
2791 src->dev[i].hints[1]);
2792 memcpy( dst->Device[i].irdaDeviceID,
2793 &src->dev[i].daddr,
2794 sizeof(dst->Device[i].irdaDeviceID) ) ;
2795 memcpy( dst->Device[i].irdaDeviceName,
2796 src->dev[i].info,
2797 sizeof(dst->Device[i].irdaDeviceName) ) ;
2798 memcpy( &dst->Device[i].irdaDeviceHints1,
2799 &src->dev[i].hints[0],
2800 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
2801 memcpy( &dst->Device[i].irdaDeviceHints2,
2802 &src->dev[i].hints[1],
2803 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
2804 dst->Device[i].irdaCharSet = src->dev[i].charset;
2806 return 0;
2809 default:
2810 FIXME("IrDA optname:0x%x\n", optname);
2811 return SOCKET_ERROR;
2813 break; /* case WS_SOL_IRLMP */
2814 #endif
2816 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
2817 case WS_IPPROTO_TCP:
2818 switch(optname)
2820 case WS_TCP_NODELAY:
2821 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2822 return SOCKET_ERROR;
2823 convert_sockopt(&level, &optname);
2824 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2826 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2827 ret = SOCKET_ERROR;
2829 release_sock_fd( s, fd );
2830 return ret;
2832 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
2833 return SOCKET_ERROR;
2835 case WS_IPPROTO_IP:
2836 switch(optname)
2838 case WS_IP_ADD_MEMBERSHIP:
2839 case WS_IP_DROP_MEMBERSHIP:
2840 #ifdef IP_HDRINCL
2841 case WS_IP_HDRINCL:
2842 #endif
2843 case WS_IP_MULTICAST_IF:
2844 case WS_IP_MULTICAST_LOOP:
2845 case WS_IP_MULTICAST_TTL:
2846 case WS_IP_OPTIONS:
2847 #ifdef IP_PKTINFO
2848 case WS_IP_PKTINFO:
2849 #endif
2850 case WS_IP_TOS:
2851 case WS_IP_TTL:
2852 #ifdef IP_UNICAST_IF
2853 case WS_IP_UNICAST_IF:
2854 #endif
2855 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2856 return SOCKET_ERROR;
2857 convert_sockopt(&level, &optname);
2858 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2860 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2861 ret = SOCKET_ERROR;
2863 release_sock_fd( s, fd );
2864 return ret;
2865 case WS_IP_DONTFRAGMENT:
2866 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
2867 *(BOOL*)optval = FALSE;
2868 return 0;
2870 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
2871 return SOCKET_ERROR;
2873 case WS_IPPROTO_IPV6:
2874 switch(optname)
2876 #ifdef IPV6_ADD_MEMBERSHIP
2877 case WS_IPV6_ADD_MEMBERSHIP:
2878 #endif
2879 #ifdef IPV6_DROP_MEMBERSHIP
2880 case WS_IPV6_DROP_MEMBERSHIP:
2881 #endif
2882 case WS_IPV6_MULTICAST_IF:
2883 case WS_IPV6_MULTICAST_HOPS:
2884 case WS_IPV6_MULTICAST_LOOP:
2885 case WS_IPV6_UNICAST_HOPS:
2886 case WS_IPV6_V6ONLY:
2887 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2888 return SOCKET_ERROR;
2889 convert_sockopt(&level, &optname);
2890 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2892 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2893 ret = SOCKET_ERROR;
2895 release_sock_fd( s, fd );
2896 return ret;
2897 case WS_IPV6_DONTFRAG:
2898 FIXME("WS_IPV6_DONTFRAG is always false!\n");
2899 *(BOOL*)optval = FALSE;
2900 return 0;
2902 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
2903 return SOCKET_ERROR;
2905 default:
2906 WARN("Unknown level: 0x%08x\n", level);
2907 SetLastError(WSAEINVAL);
2908 return SOCKET_ERROR;
2909 } /* end switch(level) */
2912 /***********************************************************************
2913 * htonl (WS2_32.8)
2915 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
2917 return htonl(hostlong);
2921 /***********************************************************************
2922 * htons (WS2_32.9)
2924 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
2926 return htons(hostshort);
2929 /***********************************************************************
2930 * WSAHtonl (WS2_32.46)
2931 * From MSDN description of error codes, this function should also
2932 * check if WinSock has been initialized and the socket is a valid
2933 * socket. But why? This function only translates a host byte order
2934 * u_long into a network byte order u_long...
2936 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
2938 if (lpnetlong)
2940 *lpnetlong = htonl(hostlong);
2941 return 0;
2943 WSASetLastError(WSAEFAULT);
2944 return SOCKET_ERROR;
2947 /***********************************************************************
2948 * WSAHtons (WS2_32.47)
2949 * From MSDN description of error codes, this function should also
2950 * check if WinSock has been initialized and the socket is a valid
2951 * socket. But why? This function only translates a host byte order
2952 * u_short into a network byte order u_short...
2954 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
2957 if (lpnetshort)
2959 *lpnetshort = htons(hostshort);
2960 return 0;
2962 WSASetLastError(WSAEFAULT);
2963 return SOCKET_ERROR;
2967 /***********************************************************************
2968 * inet_addr (WS2_32.11)
2970 WS_u_long WINAPI WS_inet_addr(const char *cp)
2972 if (!cp) return INADDR_NONE;
2973 return inet_addr(cp);
2977 /***********************************************************************
2978 * ntohl (WS2_32.14)
2980 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
2982 return ntohl(netlong);
2986 /***********************************************************************
2987 * ntohs (WS2_32.15)
2989 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
2991 return ntohs(netshort);
2995 /***********************************************************************
2996 * inet_ntoa (WS2_32.12)
2998 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
3000 /* use "buffer for dummies" here because some applications have a
3001 * propensity to decode addresses in ws_hostent structure without
3002 * saving them first...
3004 static char dbuffer[16]; /* Yes, 16: 4*3 digits + 3 '.' + 1 '\0' */
3006 char* s = inet_ntoa(*((struct in_addr*)&in));
3007 if( s )
3009 strcpy(dbuffer, s);
3010 return dbuffer;
3012 SetLastError(wsaErrno());
3013 return NULL;
3016 static const char *debugstr_wsaioctl(DWORD ioctl)
3018 const char *buf_type, *family;
3020 switch(ioctl & 0x18000000)
3022 case WS_IOC_WS2:
3023 family = "IOC_WS2";
3024 break;
3025 case WS_IOC_PROTOCOL:
3026 family = "IOC_PROTOCOL";
3027 break;
3028 case WS_IOC_VENDOR:
3029 family = "IOC_VENDOR";
3030 break;
3031 default: /* WS_IOC_UNIX */
3033 BYTE size = (ioctl >> 16) & WS_IOCPARM_MASK;
3034 char x = (ioctl & 0xff00) >> 8;
3035 BYTE y = ioctl & 0xff;
3036 char args[14];
3038 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3040 case WS_IOC_VOID:
3041 buf_type = "_IO";
3042 sprintf(args, "%d, %d", x, y);
3043 break;
3044 case WS_IOC_IN:
3045 buf_type = "_IOW";
3046 sprintf(args, "'%c', %d, %d", x, y, size);
3047 break;
3048 case WS_IOC_OUT:
3049 buf_type = "_IOR";
3050 sprintf(args, "'%c', %d, %d", x, y, size);
3051 break;
3052 default:
3053 buf_type = "?";
3054 sprintf(args, "'%c', %d, %d", x, y, size);
3055 break;
3057 return wine_dbg_sprintf("%s(%s)", buf_type, args);
3061 /* We are different from WS_IOC_UNIX. */
3062 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3064 case WS_IOC_VOID:
3065 buf_type = "_WSAIO";
3066 break;
3067 case WS_IOC_INOUT:
3068 buf_type = "_WSAIORW";
3069 break;
3070 case WS_IOC_IN:
3071 buf_type = "_WSAIOW";
3072 break;
3073 case WS_IOC_OUT:
3074 buf_type = "_WSAIOR";
3075 break;
3076 default:
3077 buf_type = "?";
3078 break;
3081 return wine_dbg_sprintf("%s(%s, %d)", buf_type, family,
3082 (USHORT)(ioctl & 0xffff));
3085 /**********************************************************************
3086 * WSAIoctl (WS2_32.50)
3089 INT WINAPI WSAIoctl(SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size, LPVOID out_buff,
3090 DWORD out_size, LPDWORD ret_size, LPWSAOVERLAPPED overlapped,
3091 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
3093 int fd;
3094 DWORD status = 0, total = 0;
3096 TRACE("%ld, 0x%08x, %p, %d, %p, %d, %p, %p, %p\n",
3097 s, code, in_buff, in_size, out_buff, out_size, ret_size, overlapped, completion);
3099 switch (code)
3101 case WS_FIONBIO:
3102 if (in_size != sizeof(WS_u_long) || IS_INTRESOURCE(in_buff))
3104 WSASetLastError(WSAEFAULT);
3105 return SOCKET_ERROR;
3107 if (_get_sock_mask(s))
3109 /* AsyncSelect()'ed sockets are always nonblocking */
3110 if (!*(WS_u_long *)in_buff) status = WSAEINVAL;
3111 break;
3113 if (*(WS_u_long *)in_buff)
3114 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
3115 else
3116 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
3117 break;
3119 case WS_FIONREAD:
3121 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
3123 WSASetLastError(WSAEFAULT);
3124 return SOCKET_ERROR;
3126 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3127 if (ioctl(fd, FIONREAD, out_buff ) == -1)
3128 status = (errno == EBADF) ? WSAENOTSOCK : wsaErrno();
3129 release_sock_fd( s, fd );
3130 break;
3133 case WS_SIOCATMARK:
3135 unsigned int oob = 0, oobsize = sizeof(int), atmark = 0;
3136 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
3138 WSASetLastError(WSAEFAULT);
3139 return SOCKET_ERROR;
3141 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3142 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
3143 if ((getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &oob, &oobsize ) == -1)
3144 || (!oob && ioctl(fd, SIOCATMARK, &atmark ) == -1))
3145 status = (errno == EBADF) ? WSAENOTSOCK : wsaErrno();
3146 else
3148 /* The SIOCATMARK value read from ioctl() is reversed
3149 * because BSD returns TRUE if it's in the OOB mark
3150 * while Windows returns TRUE if there are NO OOB bytes.
3152 (*(WS_u_long *) out_buff) = oob | !atmark;
3155 release_sock_fd( s, fd );
3156 break;
3159 case WS_FIOASYNC:
3160 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
3161 SetLastError(WSAEINVAL);
3162 return SOCKET_ERROR;
3164 case WS_SIO_GET_INTERFACE_LIST:
3166 INTERFACE_INFO* intArray = out_buff;
3167 DWORD size, numInt = 0, apiReturn;
3169 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
3171 if (!out_buff || !ret_size)
3173 WSASetLastError(WSAEFAULT);
3174 return SOCKET_ERROR;
3177 fd = get_sock_fd( s, 0, NULL );
3178 if (fd == -1) return SOCKET_ERROR;
3180 apiReturn = GetAdaptersInfo(NULL, &size);
3181 if (apiReturn == ERROR_BUFFER_OVERFLOW)
3183 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
3185 if (table)
3187 if (GetAdaptersInfo(table, &size) == NO_ERROR)
3189 PIP_ADAPTER_INFO ptr;
3191 if (size*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > out_size)
3193 WARN("Buffer too small = %u, out_size = %u\n", size, out_size);
3194 HeapFree(GetProcessHeap(),0,table);
3195 release_sock_fd( s, fd );
3196 status = WSAEFAULT;
3197 break;
3199 for (ptr = table, numInt = 0; ptr;
3200 ptr = ptr->Next, intArray++, numInt++)
3202 unsigned int addr, mask, bcast;
3203 struct ifreq ifInfo;
3205 /* Socket Status Flags */
3206 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
3207 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
3209 ERR("Error obtaining status flags for socket!\n");
3210 HeapFree(GetProcessHeap(),0,table);
3211 release_sock_fd( s, fd );
3212 status = WSAEINVAL;
3213 break;
3215 else
3217 /* set flags; the values of IFF_* are not the same
3218 under Linux and Windows, therefore must generate
3219 new flags */
3220 intArray->iiFlags = 0;
3221 if (ifInfo.ifr_flags & IFF_BROADCAST)
3222 intArray->iiFlags |= WS_IFF_BROADCAST;
3223 #ifdef IFF_POINTOPOINT
3224 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
3225 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
3226 #endif
3227 if (ifInfo.ifr_flags & IFF_LOOPBACK)
3228 intArray->iiFlags |= WS_IFF_LOOPBACK;
3229 if (ifInfo.ifr_flags & IFF_UP)
3230 intArray->iiFlags |= WS_IFF_UP;
3231 if (ifInfo.ifr_flags & IFF_MULTICAST)
3232 intArray->iiFlags |= WS_IFF_MULTICAST;
3235 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
3236 mask = inet_addr(ptr->IpAddressList.IpMask.String);
3237 bcast = addr | ~mask;
3238 intArray->iiAddress.AddressIn.sin_family = AF_INET;
3239 intArray->iiAddress.AddressIn.sin_port = 0;
3240 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
3241 addr;
3242 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
3243 intArray->iiNetmask.AddressIn.sin_port = 0;
3244 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
3245 mask;
3246 intArray->iiBroadcastAddress.AddressIn.sin_family =
3247 AF_INET;
3248 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
3249 intArray->iiBroadcastAddress.AddressIn.sin_addr.
3250 WS_s_addr = bcast;
3253 else
3255 ERR("Unable to get interface table!\n");
3256 status = WSAEINVAL;
3258 HeapFree(GetProcessHeap(),0,table);
3260 else status = WSAEINVAL;
3262 else if (apiReturn != ERROR_NO_DATA)
3264 ERR("Unable to get interface table!\n");
3265 status = WSAEINVAL;
3267 /* Calculate the size of the array being returned */
3268 total = sizeof(INTERFACE_INFO) * numInt;
3269 release_sock_fd( s, fd );
3270 break;
3273 case WS_SIO_ADDRESS_LIST_CHANGE:
3274 FIXME("-> SIO_ADDRESS_LIST_CHANGE request: stub\n");
3275 /* FIXME: error and return code depend on whether socket was created
3276 * with WSA_FLAG_OVERLAPPED, but there is no easy way to get this */
3277 break;
3279 case WS_SIO_ADDRESS_LIST_QUERY:
3281 DWORD size;
3283 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
3285 if (!ret_size)
3287 WSASetLastError(WSAEFAULT);
3288 return SOCKET_ERROR;
3291 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
3293 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
3294 DWORD num;
3296 if (!table || GetAdaptersInfo(table, &size))
3298 HeapFree(GetProcessHeap(), 0, table);
3299 status = WSAEINVAL;
3300 break;
3303 for (p = table, num = 0; p; p = p->Next)
3304 if (p->IpAddressList.IpAddress.String[0]) num++;
3306 total = sizeof(SOCKET_ADDRESS_LIST) + sizeof(SOCKET_ADDRESS) * (num - 1);
3307 total += sizeof(SOCKADDR) * num;
3309 if (total > out_size)
3311 HeapFree(GetProcessHeap(), 0, table);
3312 status = WSAEFAULT;
3313 break;
3316 if (out_buff)
3318 unsigned int i;
3319 SOCKET_ADDRESS *sa;
3320 SOCKET_ADDRESS_LIST *sa_list = out_buff;
3321 SOCKADDR_IN *sockaddr;
3323 sa = sa_list->Address;
3324 sockaddr = (SOCKADDR_IN *)((char *)sa + num * sizeof(SOCKET_ADDRESS));
3325 sa_list->iAddressCount = num;
3327 for (p = table, i = 0; p; p = p->Next)
3329 if (!p->IpAddressList.IpAddress.String[0]) continue;
3331 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
3332 sa[i].iSockaddrLength = sizeof(SOCKADDR);
3334 sockaddr[i].sin_family = AF_INET;
3335 sockaddr[i].sin_port = 0;
3336 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
3337 i++;
3341 HeapFree(GetProcessHeap(), 0, table);
3343 else
3345 WARN("unable to get IP address list\n");
3346 status = WSAEINVAL;
3348 break;
3351 case WS_SIO_FLUSH:
3352 FIXME("SIO_FLUSH: stub.\n");
3353 break;
3355 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
3357 static const GUID connectex_guid = WSAID_CONNECTEX;
3358 static const GUID disconnectex_guid = WSAID_DISCONNECTEX;
3359 static const GUID acceptex_guid = WSAID_ACCEPTEX;
3360 static const GUID getaccepexsockaddrs_guid = WSAID_GETACCEPTEXSOCKADDRS;
3361 static const GUID transmitfile_guid = WSAID_TRANSMITFILE;
3362 static const GUID transmitpackets_guid = WSAID_TRANSMITPACKETS;
3363 static const GUID wsarecvmsg_guid = WSAID_WSARECVMSG;
3364 static const GUID wsasendmsg_guid = WSAID_WSASENDMSG;
3366 if ( IsEqualGUID(&connectex_guid, in_buff) )
3368 *(LPFN_CONNECTEX *)out_buff = WS2_ConnectEx;
3369 break;
3371 else if ( IsEqualGUID(&disconnectex_guid, in_buff) )
3373 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented DisconnectEx\n");
3375 else if ( IsEqualGUID(&acceptex_guid, in_buff) )
3377 *(LPFN_ACCEPTEX *)out_buff = WS2_AcceptEx;
3378 break;
3380 else if ( IsEqualGUID(&getaccepexsockaddrs_guid, in_buff) )
3382 *(LPFN_GETACCEPTEXSOCKADDRS *)out_buff = WS2_GetAcceptExSockaddrs;
3383 break;
3385 else if ( IsEqualGUID(&transmitfile_guid, in_buff) )
3387 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitFile\n");
3389 else if ( IsEqualGUID(&transmitpackets_guid, in_buff) )
3391 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitPackets\n");
3393 else if ( IsEqualGUID(&wsarecvmsg_guid, in_buff) )
3395 *(LPFN_WSARECVMSG *)out_buff = WS2_WSARecvMsg;
3396 break;
3398 else if ( IsEqualGUID(&wsasendmsg_guid, in_buff) )
3400 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented WSASendMsg\n");
3402 else
3403 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff));
3405 status = WSAEOPNOTSUPP;
3406 break;
3408 case WS_SIO_KEEPALIVE_VALS:
3410 struct tcp_keepalive *k;
3411 int keepalive, keepidle, keepintvl;
3413 if (!in_buff || in_size < sizeof(struct tcp_keepalive))
3415 WSASetLastError(WSAEFAULT);
3416 return SOCKET_ERROR;
3419 k = in_buff;
3420 keepalive = k->onoff ? 1 : 0;
3421 keepidle = max( 1, (k->keepalivetime + 500) / 1000 );
3422 keepintvl = max( 1, (k->keepaliveinterval + 500) / 1000 );
3424 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
3426 fd = get_sock_fd(s, 0, NULL);
3427 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
3428 status = WSAEINVAL;
3429 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
3430 /* these values need to be set only if SO_KEEPALIVE is enabled */
3431 else if(keepalive)
3433 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
3434 status = WSAEINVAL;
3435 else if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
3436 status = WSAEINVAL;
3438 #else
3439 else
3440 FIXME("ignoring keepalive interval and timeout\n");
3441 #endif
3442 release_sock_fd(s, fd);
3443 break;
3445 case WS_SIO_ROUTING_INTERFACE_QUERY:
3447 struct WS_sockaddr *daddr = (struct WS_sockaddr *)in_buff;
3448 struct WS_sockaddr_in *daddr_in = (struct WS_sockaddr_in *)daddr;
3449 struct WS_sockaddr_in *saddr_in = out_buff;
3450 MIB_IPFORWARDROW row;
3451 PMIB_IPADDRTABLE ipAddrTable = NULL;
3452 DWORD size, i, found_index;
3454 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
3456 if (!in_buff || in_size < sizeof(struct WS_sockaddr) ||
3457 !out_buff || out_size < sizeof(struct WS_sockaddr_in) || !ret_size)
3459 WSASetLastError(WSAEFAULT);
3460 return SOCKET_ERROR;
3462 if (daddr->sa_family != AF_INET)
3464 FIXME("unsupported address family %d\n", daddr->sa_family);
3465 status = WSAEAFNOSUPPORT;
3466 break;
3468 if (GetBestRoute(daddr_in->sin_addr.S_un.S_addr, 0, &row) != NOERROR ||
3469 GetIpAddrTable(NULL, &size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
3471 status = WSAEFAULT;
3472 break;
3474 ipAddrTable = HeapAlloc(GetProcessHeap(), 0, size);
3475 if (GetIpAddrTable(ipAddrTable, &size, FALSE))
3477 HeapFree(GetProcessHeap(), 0, ipAddrTable);
3478 status = WSAEFAULT;
3479 break;
3481 for (i = 0, found_index = ipAddrTable->dwNumEntries;
3482 i < ipAddrTable->dwNumEntries; i++)
3484 if (ipAddrTable->table[i].dwIndex == row.dwForwardIfIndex)
3485 found_index = i;
3487 if (found_index == ipAddrTable->dwNumEntries)
3489 ERR("no matching IP address for interface %d\n",
3490 row.dwForwardIfIndex);
3491 HeapFree(GetProcessHeap(), 0, ipAddrTable);
3492 status = WSAEFAULT;
3493 break;
3495 saddr_in->sin_family = AF_INET;
3496 saddr_in->sin_addr.S_un.S_addr = ipAddrTable->table[found_index].dwAddr;
3497 saddr_in->sin_port = 0;
3498 total = sizeof(struct WS_sockaddr_in);
3499 HeapFree(GetProcessHeap(), 0, ipAddrTable);
3500 break;
3502 case WS_SIO_SET_COMPATIBILITY_MODE:
3503 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
3504 status = WSAEOPNOTSUPP;
3505 break;
3506 case WS_SIO_UDP_CONNRESET:
3507 FIXME("WS_SIO_UDP_CONNRESET stub\n");
3508 break;
3509 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
3510 WSASetLastError(WSAEOPNOTSUPP);
3511 return SOCKET_ERROR;
3512 default:
3513 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code));
3514 status = WSAEOPNOTSUPP;
3515 break;
3518 if (completion)
3520 FIXME( "completion routine %p not supported\n", completion );
3522 else if (overlapped)
3524 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
3525 overlapped->Internal = status;
3526 overlapped->InternalHigh = total;
3527 if (overlapped->hEvent) NtSetEvent( overlapped->hEvent, NULL );
3528 if (cvalue) WS_AddCompletion( HANDLE2SOCKET(s), cvalue, status, total );
3531 if (!status)
3533 if (ret_size) *ret_size = total;
3534 return 0;
3536 SetLastError( status );
3537 return SOCKET_ERROR;
3541 /***********************************************************************
3542 * ioctlsocket (WS2_32.10)
3544 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
3546 DWORD ret_size;
3547 return WSAIoctl( s, cmd, argp, sizeof(WS_u_long), argp, sizeof(WS_u_long), &ret_size, NULL, NULL );
3550 /***********************************************************************
3551 * listen (WS2_32.13)
3553 int WINAPI WS_listen(SOCKET s, int backlog)
3555 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
3557 TRACE("socket %04lx, backlog %d\n", s, backlog);
3558 if (fd != -1)
3560 if (listen(fd, backlog) == 0)
3562 release_sock_fd( s, fd );
3563 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
3564 FD_WINE_LISTENING,
3565 FD_CONNECT|FD_WINE_CONNECTED);
3566 return 0;
3568 SetLastError(wsaErrno());
3569 release_sock_fd( s, fd );
3571 return SOCKET_ERROR;
3574 /***********************************************************************
3575 * recv (WS2_32.16)
3577 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
3579 DWORD n, dwFlags = flags;
3580 WSABUF wsabuf;
3582 wsabuf.len = len;
3583 wsabuf.buf = buf;
3585 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
3586 return SOCKET_ERROR;
3587 else
3588 return n;
3591 /***********************************************************************
3592 * recvfrom (WS2_32.17)
3594 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
3595 struct WS_sockaddr *from, int *fromlen)
3597 DWORD n, dwFlags = flags;
3598 WSABUF wsabuf;
3600 wsabuf.len = len;
3601 wsabuf.buf = buf;
3603 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL, NULL) == SOCKET_ERROR )
3604 return SOCKET_ERROR;
3605 else
3606 return n;
3609 /* allocate a poll array for the corresponding fd sets */
3610 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
3611 const WS_fd_set *exceptfds, int *count_ptr )
3613 unsigned int i, j = 0, count = 0;
3614 struct pollfd *fds;
3616 if (readfds) count += readfds->fd_count;
3617 if (writefds) count += writefds->fd_count;
3618 if (exceptfds) count += exceptfds->fd_count;
3619 *count_ptr = count;
3620 if (!count)
3622 SetLastError(WSAEINVAL);
3623 return NULL;
3625 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0]))))
3627 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
3628 return NULL;
3630 if (readfds)
3631 for (i = 0; i < readfds->fd_count; i++, j++)
3633 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
3634 if (fds[j].fd == -1) goto failed;
3635 fds[j].events = POLLIN;
3636 fds[j].revents = 0;
3638 if (writefds)
3639 for (i = 0; i < writefds->fd_count; i++, j++)
3641 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
3642 if (fds[j].fd == -1) goto failed;
3643 fds[j].events = POLLOUT;
3644 fds[j].revents = 0;
3646 if (exceptfds)
3647 for (i = 0; i < exceptfds->fd_count; i++, j++)
3649 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
3650 if (fds[j].fd == -1) goto failed;
3651 fds[j].events = POLLHUP;
3652 fds[j].revents = 0;
3654 return fds;
3656 failed:
3657 count = j;
3658 j = 0;
3659 if (readfds)
3660 for (i = 0; i < readfds->fd_count && j < count; i++, j++)
3661 release_sock_fd( readfds->fd_array[i], fds[j].fd );
3662 if (writefds)
3663 for (i = 0; i < writefds->fd_count && j < count; i++, j++)
3664 release_sock_fd( writefds->fd_array[i], fds[j].fd );
3665 if (exceptfds)
3666 for (i = 0; i < exceptfds->fd_count && j < count; i++, j++)
3667 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
3668 HeapFree( GetProcessHeap(), 0, fds );
3669 return NULL;
3672 /* release the file descriptor obtained in fd_sets_to_poll */
3673 /* must be called with the original fd_set arrays, before calling get_poll_results */
3674 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
3675 const WS_fd_set *exceptfds, struct pollfd *fds )
3677 unsigned int i, j = 0;
3679 if (readfds)
3681 for (i = 0; i < readfds->fd_count; i++, j++)
3682 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
3684 if (writefds)
3686 for (i = 0; i < writefds->fd_count; i++, j++)
3687 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
3689 if (exceptfds)
3691 for (i = 0; i < exceptfds->fd_count; i++, j++)
3692 if (fds[j].fd != -1)
3694 /* make sure we have a real error before releasing the fd */
3695 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
3696 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
3701 /* map the poll results back into the Windows fd sets */
3702 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
3703 const struct pollfd *fds )
3705 unsigned int i, j = 0, k, total = 0;
3707 if (readfds)
3709 for (i = k = 0; i < readfds->fd_count; i++, j++)
3710 if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
3711 readfds->fd_count = k;
3712 total += k;
3714 if (writefds)
3716 for (i = k = 0; i < writefds->fd_count; i++, j++)
3717 if ((fds[j].revents & POLLOUT) && !(fds[j].revents & POLLHUP))
3718 writefds->fd_array[k++] = writefds->fd_array[i];
3719 writefds->fd_count = k;
3720 total += k;
3722 if (exceptfds)
3724 for (i = k = 0; i < exceptfds->fd_count; i++, j++)
3725 if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
3726 exceptfds->fd_count = k;
3727 total += k;
3729 return total;
3733 /***********************************************************************
3734 * select (WS2_32.18)
3736 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
3737 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
3738 const struct WS_timeval* ws_timeout)
3740 struct pollfd *pollfds;
3741 struct timeval tv1, tv2;
3742 int torig = 0;
3743 int count, ret, timeout = -1;
3745 TRACE("read %p, write %p, excp %p timeout %p\n",
3746 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
3748 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )))
3749 return SOCKET_ERROR;
3751 if (ws_timeout)
3753 torig = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
3754 timeout = torig;
3755 gettimeofday( &tv1, 0 );
3758 while ((ret = poll( pollfds, count, timeout )) < 0)
3760 if (errno == EINTR)
3762 if (!ws_timeout) continue;
3763 gettimeofday( &tv2, 0 );
3765 tv2.tv_sec -= tv1.tv_sec;
3766 tv2.tv_usec -= tv1.tv_usec;
3767 if (tv2.tv_usec < 0)
3769 tv2.tv_usec += 1000000;
3770 tv2.tv_sec -= 1;
3773 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
3774 if (timeout <= 0) break;
3775 } else break;
3777 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
3779 if (ret == -1) SetLastError(wsaErrno());
3780 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
3781 HeapFree( GetProcessHeap(), 0, pollfds );
3782 return ret;
3785 /* helper to send completion messages for client-only i/o operation case */
3786 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
3787 ULONG Information )
3789 SERVER_START_REQ( add_fd_completion )
3791 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
3792 req->cvalue = CompletionValue;
3793 req->status = CompletionStatus;
3794 req->information = Information;
3795 wine_server_call( req );
3797 SERVER_END_REQ;
3801 /***********************************************************************
3802 * send (WS2_32.19)
3804 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
3806 DWORD n;
3807 WSABUF wsabuf;
3809 wsabuf.len = len;
3810 wsabuf.buf = (char*) buf;
3812 if ( WS2_sendto( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
3813 return SOCKET_ERROR;
3814 else
3815 return n;
3818 /***********************************************************************
3819 * WSASend (WS2_32.72)
3821 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3822 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
3823 LPWSAOVERLAPPED lpOverlapped,
3824 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3826 return WS2_sendto( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
3827 NULL, 0, lpOverlapped, lpCompletionRoutine );
3830 /***********************************************************************
3831 * WSASendDisconnect (WS2_32.73)
3833 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
3835 return WS_shutdown( s, SD_SEND );
3839 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3840 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
3841 const struct WS_sockaddr *to, int tolen,
3842 LPWSAOVERLAPPED lpOverlapped,
3843 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3845 unsigned int i, options;
3846 int n, fd, err;
3847 struct ws2_async *wsa = NULL;
3848 int totalLength = 0;
3849 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
3850 DWORD bytes_sent;
3852 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
3853 s, lpBuffers, dwBufferCount, dwFlags,
3854 to, tolen, lpOverlapped, lpCompletionRoutine);
3856 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
3857 TRACE( "fd=%d, options=%x\n", fd, options );
3859 if ( fd == -1 ) return SOCKET_ERROR;
3861 if (!lpOverlapped && !lpNumberOfBytesSent)
3863 err = WSAEFAULT;
3864 goto error;
3866 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
3868 err = WSAEFAULT;
3869 goto error;
3872 wsa->hSocket = SOCKET2HANDLE(s);
3873 wsa->addr = (struct WS_sockaddr *)to;
3874 wsa->addrlen.val = tolen;
3875 wsa->flags = dwFlags;
3876 wsa->lpFlags = &wsa->flags;
3877 wsa->control = NULL;
3878 wsa->n_iovecs = dwBufferCount;
3879 wsa->first_iovec = 0;
3880 for ( i = 0; i < dwBufferCount; i++ )
3882 wsa->iovec[i].iov_base = lpBuffers[i].buf;
3883 wsa->iovec[i].iov_len = lpBuffers[i].len;
3884 totalLength += lpBuffers[i].len;
3887 for (;;)
3889 n = WS2_send( fd, wsa );
3890 if (n != -1 || errno != EINTR) break;
3892 if (n == -1 && errno != EAGAIN)
3894 err = wsaErrno();
3895 goto error;
3898 if ((lpOverlapped || lpCompletionRoutine) &&
3899 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
3901 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
3903 wsa->user_overlapped = lpOverlapped;
3904 wsa->completion_func = lpCompletionRoutine;
3905 release_sock_fd( s, fd );
3907 if (n == -1 || n < totalLength)
3909 iosb->u.Status = STATUS_PENDING;
3910 iosb->Information = n == -1 ? 0 : n;
3912 SERVER_START_REQ( register_async )
3914 req->type = ASYNC_TYPE_WRITE;
3915 req->async.handle = wine_server_obj_handle( wsa->hSocket );
3916 req->async.callback = wine_server_client_ptr( WS2_async_send );
3917 req->async.iosb = wine_server_client_ptr( iosb );
3918 req->async.arg = wine_server_client_ptr( wsa );
3919 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
3920 req->async.cvalue = cvalue;
3921 err = wine_server_call( req );
3923 SERVER_END_REQ;
3925 /* Enable the event only after starting the async. The server will deliver it as soon as
3926 the async is done. */
3927 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
3929 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
3930 WSASetLastError( NtStatusToWSAError( err ));
3931 return SOCKET_ERROR;
3934 iosb->u.Status = STATUS_SUCCESS;
3935 iosb->Information = n;
3936 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = n;
3937 if (!wsa->completion_func)
3939 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
3940 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
3941 HeapFree( GetProcessHeap(), 0, wsa );
3943 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
3944 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
3945 WSASetLastError(0);
3946 return 0;
3949 if ( _is_blocking(s) )
3951 /* On a blocking non-overlapped stream socket,
3952 * sending blocks until the entire buffer is sent. */
3953 DWORD timeout_start = GetTickCount();
3955 bytes_sent = n == -1 ? 0 : n;
3957 while (wsa->first_iovec < wsa->n_iovecs)
3959 struct pollfd pfd;
3960 int timeout = GET_SNDTIMEO(fd);
3962 if (timeout != -1)
3964 timeout -= GetTickCount() - timeout_start;
3965 if (timeout < 0) timeout = 0;
3968 pfd.fd = fd;
3969 pfd.events = POLLOUT;
3971 if (!timeout || !poll( &pfd, 1, timeout ))
3973 err = WSAETIMEDOUT;
3974 goto error; /* msdn says a timeout in send is fatal */
3977 n = WS2_send( fd, wsa );
3978 if (n == -1 && errno != EAGAIN && errno != EINTR)
3980 err = wsaErrno();
3981 goto error;
3984 if (n >= 0)
3985 bytes_sent += n;
3988 else /* non-blocking */
3990 if (n < totalLength)
3991 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
3992 if (n == -1)
3994 err = WSAEWOULDBLOCK;
3995 goto error;
3997 bytes_sent = n;
4000 TRACE(" -> %i bytes\n", bytes_sent);
4002 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = bytes_sent;
4003 HeapFree( GetProcessHeap(), 0, wsa );
4004 release_sock_fd( s, fd );
4005 WSASetLastError(0);
4006 return 0;
4008 error:
4009 HeapFree( GetProcessHeap(), 0, wsa );
4010 release_sock_fd( s, fd );
4011 WARN(" -> ERROR %d\n", err);
4012 WSASetLastError(err);
4013 return SOCKET_ERROR;
4016 /***********************************************************************
4017 * WSASendTo (WS2_32.74)
4019 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4020 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4021 const struct WS_sockaddr *to, int tolen,
4022 LPWSAOVERLAPPED lpOverlapped,
4023 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4025 return WS2_sendto( s, lpBuffers, dwBufferCount,
4026 lpNumberOfBytesSent, dwFlags,
4027 to, tolen,
4028 lpOverlapped, lpCompletionRoutine );
4031 /***********************************************************************
4032 * sendto (WS2_32.20)
4034 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
4035 const struct WS_sockaddr *to, int tolen)
4037 DWORD n;
4038 WSABUF wsabuf;
4040 wsabuf.len = len;
4041 wsabuf.buf = (char*) buf;
4043 if ( WS2_sendto(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
4044 return SOCKET_ERROR;
4045 else
4046 return n;
4049 /***********************************************************************
4050 * setsockopt (WS2_32.21)
4052 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
4053 const char *optval, int optlen)
4055 int fd;
4056 int woptval;
4057 struct linger linger;
4058 struct timeval tval;
4060 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
4061 s, level, optname, optval, optlen);
4063 /* some broken apps pass the value directly instead of a pointer to it */
4064 if(optlen && IS_INTRESOURCE(optval))
4066 SetLastError(WSAEFAULT);
4067 return SOCKET_ERROR;
4070 switch(level)
4072 case WS_SOL_SOCKET:
4073 switch(optname)
4075 /* Some options need some conversion before they can be sent to
4076 * setsockopt. The conversions are done here, then they will fall though
4077 * to the general case. Special options that are not passed to
4078 * setsockopt follow below that.*/
4080 case WS_SO_DONTLINGER:
4081 if (!optval)
4083 SetLastError(WSAEFAULT);
4084 return SOCKET_ERROR;
4086 linger.l_onoff = *((const int*)optval) ? 0: 1;
4087 linger.l_linger = 0;
4088 level = SOL_SOCKET;
4089 optname = SO_LINGER;
4090 optval = (char*)&linger;
4091 optlen = sizeof(struct linger);
4092 break;
4094 case WS_SO_LINGER:
4095 if (!optval)
4097 SetLastError(WSAEFAULT);
4098 return SOCKET_ERROR;
4100 linger.l_onoff = ((LINGER*)optval)->l_onoff;
4101 linger.l_linger = ((LINGER*)optval)->l_linger;
4102 level = SOL_SOCKET;
4103 optname = SO_LINGER;
4104 optval = (char*)&linger;
4105 optlen = sizeof(struct linger);
4106 break;
4108 case WS_SO_RCVBUF:
4109 if (*(const int*)optval < 2048)
4111 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
4112 return 0;
4114 /* Fall through */
4116 /* The options listed here don't need any special handling. Thanks to
4117 * the conversion happening above, options from there will fall through
4118 * to this, too.*/
4119 case WS_SO_ACCEPTCONN:
4120 case WS_SO_BROADCAST:
4121 case WS_SO_ERROR:
4122 case WS_SO_KEEPALIVE:
4123 case WS_SO_OOBINLINE:
4124 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
4125 * however, using it the BSD way fixes bug 8513 and seems to be what
4126 * most programmers assume, anyway */
4127 case WS_SO_REUSEADDR:
4128 case WS_SO_SNDBUF:
4129 case WS_SO_TYPE:
4130 convert_sockopt(&level, &optname);
4131 break;
4133 /* SO_DEBUG is a privileged operation, ignore it. */
4134 case WS_SO_DEBUG:
4135 TRACE("Ignoring SO_DEBUG\n");
4136 return 0;
4138 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
4139 * socket. According to MSDN, this option is silently ignored.*/
4140 case WS_SO_DONTROUTE:
4141 TRACE("Ignoring SO_DONTROUTE\n");
4142 return 0;
4144 /* Stops two sockets from being bound to the same port. Always happens
4145 * on unix systems, so just drop it. */
4146 case WS_SO_EXCLUSIVEADDRUSE:
4147 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
4148 return 0;
4150 /* After a ConnectEx call succeeds, the socket can't be used with half of the
4151 * normal winsock functions on windows. We don't have that problem. */
4152 case WS_SO_UPDATE_CONNECT_CONTEXT:
4153 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
4154 return 0;
4156 /* After a AcceptEx call succeeds, the socket can't be used with half of the
4157 * normal winsock functions on windows. We don't have that problem. */
4158 case WS_SO_UPDATE_ACCEPT_CONTEXT:
4159 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
4160 return 0;
4162 /* SO_OPENTYPE does not require a valid socket handle. */
4163 case WS_SO_OPENTYPE:
4164 if (!optlen || optlen < sizeof(int) || !optval)
4166 SetLastError(WSAEFAULT);
4167 return SOCKET_ERROR;
4169 get_per_thread_data()->opentype = *(const int *)optval;
4170 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
4171 return 0;
4173 #ifdef SO_RCVTIMEO
4174 case WS_SO_RCVTIMEO:
4175 #endif
4176 #ifdef SO_SNDTIMEO
4177 case WS_SO_SNDTIMEO:
4178 #endif
4179 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
4180 if (optval && optlen == sizeof(UINT32)) {
4181 /* WinSock passes milliseconds instead of struct timeval */
4182 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
4183 tval.tv_sec = *(const UINT32*)optval / 1000;
4184 /* min of 500 milliseconds */
4185 if (tval.tv_sec == 0 && tval.tv_usec && tval.tv_usec < 500000)
4186 tval.tv_usec = 500000;
4187 optlen = sizeof(struct timeval);
4188 optval = (char*)&tval;
4189 } else if (optlen == sizeof(struct timeval)) {
4190 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
4191 } else {
4192 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
4193 return 0;
4195 convert_sockopt(&level, &optname);
4196 break;
4197 #endif
4199 default:
4200 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
4201 SetLastError(WSAENOPROTOOPT);
4202 return SOCKET_ERROR;
4204 break; /* case WS_SOL_SOCKET */
4206 #ifdef HAVE_IPX
4207 case NSPROTO_IPX:
4208 switch(optname)
4210 case IPX_PTYPE:
4211 fd = get_sock_fd( s, 0, NULL );
4212 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", *(const int*)optval, fd);
4214 /* We try to set the ipx type on ipx socket level. */
4215 #ifdef SOL_IPX
4216 if(setsockopt(fd, SOL_IPX, IPX_TYPE, optval, optlen) == -1)
4218 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
4219 release_sock_fd( s, fd );
4220 return SOCKET_ERROR;
4222 #else
4224 struct ipx val;
4225 /* Should we retrieve val using a getsockopt call and then
4226 * set the modified one? */
4227 val.ipx_pt = *optval;
4228 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
4230 #endif
4231 release_sock_fd( s, fd );
4232 return 0;
4234 case IPX_FILTERPTYPE:
4235 /* Sets the receive filter packet type, at the moment we don't support it */
4236 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
4237 /* Returning 0 is better for now than returning a SOCKET_ERROR */
4238 return 0;
4240 default:
4241 FIXME("opt_name:%x\n", optname);
4242 return SOCKET_ERROR;
4244 break; /* case NSPROTO_IPX */
4245 #endif
4247 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
4248 case WS_IPPROTO_TCP:
4249 switch(optname)
4251 case WS_TCP_NODELAY:
4252 convert_sockopt(&level, &optname);
4253 break;
4254 default:
4255 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
4256 return SOCKET_ERROR;
4258 break;
4260 case WS_IPPROTO_IP:
4261 switch(optname)
4263 case WS_IP_ADD_MEMBERSHIP:
4264 case WS_IP_DROP_MEMBERSHIP:
4265 #ifdef IP_HDRINCL
4266 case WS_IP_HDRINCL:
4267 #endif
4268 case WS_IP_MULTICAST_IF:
4269 case WS_IP_MULTICAST_LOOP:
4270 case WS_IP_MULTICAST_TTL:
4271 case WS_IP_OPTIONS:
4272 #ifdef IP_PKTINFO
4273 case WS_IP_PKTINFO:
4274 #endif
4275 case WS_IP_TOS:
4276 case WS_IP_TTL:
4277 #ifdef IP_UNICAST_IF
4278 case WS_IP_UNICAST_IF:
4279 #endif
4280 convert_sockopt(&level, &optname);
4281 break;
4282 case WS_IP_DONTFRAGMENT:
4283 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
4284 return 0;
4285 default:
4286 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
4287 return SOCKET_ERROR;
4289 break;
4291 case WS_IPPROTO_IPV6:
4292 switch(optname)
4294 #ifdef IPV6_ADD_MEMBERSHIP
4295 case WS_IPV6_ADD_MEMBERSHIP:
4296 #endif
4297 #ifdef IPV6_DROP_MEMBERSHIP
4298 case WS_IPV6_DROP_MEMBERSHIP:
4299 #endif
4300 case WS_IPV6_MULTICAST_IF:
4301 case WS_IPV6_MULTICAST_HOPS:
4302 case WS_IPV6_MULTICAST_LOOP:
4303 case WS_IPV6_UNICAST_HOPS:
4304 case WS_IPV6_V6ONLY:
4305 convert_sockopt(&level, &optname);
4306 break;
4307 case WS_IPV6_DONTFRAG:
4308 FIXME("IPV6_DONTFRAG is silently ignored!\n");
4309 return 0;
4310 case WS_IPV6_PROTECTION_LEVEL:
4311 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
4312 return 0;
4313 default:
4314 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
4315 return SOCKET_ERROR;
4317 break;
4319 default:
4320 WARN("Unknown level: 0x%08x\n", level);
4321 SetLastError(WSAEINVAL);
4322 return SOCKET_ERROR;
4323 } /* end switch(level) */
4325 /* avoid endianness issues if argument is a 16-bit int */
4326 if (optval && optlen < sizeof(int))
4328 woptval= *((const INT16 *) optval);
4329 optval= (char*) &woptval;
4330 optlen=sizeof(int);
4332 fd = get_sock_fd( s, 0, NULL );
4333 if (fd == -1) return SOCKET_ERROR;
4335 if (setsockopt(fd, level, optname, optval, optlen) == 0)
4337 release_sock_fd( s, fd );
4338 return 0;
4340 TRACE("Setting socket error, %d\n", wsaErrno());
4341 SetLastError(wsaErrno());
4342 release_sock_fd( s, fd );
4344 return SOCKET_ERROR;
4347 /***********************************************************************
4348 * shutdown (WS2_32.22)
4350 int WINAPI WS_shutdown(SOCKET s, int how)
4352 int fd, err = WSAENOTSOCK;
4353 unsigned int options, clear_flags = 0;
4355 fd = get_sock_fd( s, 0, &options );
4356 TRACE("socket %04lx, how %i %x\n", s, how, options );
4358 if (fd == -1)
4359 return SOCKET_ERROR;
4361 switch( how )
4363 case 0: /* drop receives */
4364 clear_flags |= FD_READ;
4365 break;
4366 case 1: /* drop sends */
4367 clear_flags |= FD_WRITE;
4368 break;
4369 case 2: /* drop all */
4370 clear_flags |= FD_READ|FD_WRITE;
4371 /*fall through */
4372 default:
4373 clear_flags |= FD_WINE_LISTENING;
4376 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
4378 switch ( how )
4380 case SD_RECEIVE:
4381 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
4382 break;
4383 case SD_SEND:
4384 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
4385 break;
4386 case SD_BOTH:
4387 default:
4388 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
4389 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
4390 break;
4392 if (err) goto error;
4394 else /* non-overlapped mode */
4396 if ( shutdown( fd, how ) )
4398 err = wsaErrno();
4399 goto error;
4403 release_sock_fd( s, fd );
4404 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
4405 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
4406 return 0;
4408 error:
4409 release_sock_fd( s, fd );
4410 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
4411 WSASetLastError( err );
4412 return SOCKET_ERROR;
4415 /***********************************************************************
4416 * socket (WS2_32.23)
4418 SOCKET WINAPI WS_socket(int af, int type, int protocol)
4420 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
4422 return WSASocketA( af, type, protocol, NULL, 0,
4423 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
4427 /***********************************************************************
4428 * gethostbyaddr (WS2_32.51)
4430 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
4432 struct WS_hostent *retval = NULL;
4433 struct hostent* host;
4435 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4436 char *extrabuf;
4437 int ebufsize=1024;
4438 struct hostent hostentry;
4439 int locerr=ENOBUFS;
4440 host = NULL;
4441 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
4442 while(extrabuf) {
4443 int res = gethostbyaddr_r(addr, len, type,
4444 &hostentry, extrabuf, ebufsize, &host, &locerr);
4445 if( res != ERANGE) break;
4446 ebufsize *=2;
4447 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
4449 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
4450 #else
4451 EnterCriticalSection( &csWSgetXXXbyYYY );
4452 host = gethostbyaddr(addr, len, type);
4453 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
4454 #endif
4455 if( host != NULL ) retval = WS_dup_he(host);
4456 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4457 HeapFree(GetProcessHeap(),0,extrabuf);
4458 #else
4459 LeaveCriticalSection( &csWSgetXXXbyYYY );
4460 #endif
4461 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
4462 return retval;
4465 /***********************************************************************
4466 * WS_get_local_ips (INTERNAL)
4468 * Returns the list of local IP addresses by going through the network
4469 * adapters and using the local routing table to sort the addresses
4470 * from highest routing priority to lowest routing priority. This
4471 * functionality is inferred from the description for obtaining local
4472 * IP addresses given in the Knowledge Base Article Q160215.
4474 * Please note that the returned hostent is only freed when the thread
4475 * closes and is replaced if another hostent is requested.
4477 static struct WS_hostent* WS_get_local_ips( char *hostname )
4479 int last_metric, numroutes = 0, i, j;
4480 PIP_ADAPTER_INFO adapters = NULL, k;
4481 struct WS_hostent *hostlist = NULL;
4482 PMIB_IPFORWARDTABLE routes = NULL;
4483 struct route *route_addrs = NULL;
4484 DWORD adap_size, route_size;
4486 /* Obtain the size of the adapter list and routing table, also allocate memory */
4487 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
4488 return NULL;
4489 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
4490 return NULL;
4491 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
4492 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
4493 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
4494 if (adapters == NULL || routes == NULL || route_addrs == NULL)
4495 goto cleanup;
4496 /* Obtain the adapter list and the full routing table */
4497 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
4498 goto cleanup;
4499 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
4500 goto cleanup;
4501 /* Store the interface associated with each route */
4502 for (i = 0; i < routes->dwNumEntries; i++)
4504 IF_INDEX ifindex;
4505 DWORD ifmetric, exists = FALSE;
4507 if (routes->table[i].u1.ForwardType != MIB_IPROUTE_TYPE_DIRECT)
4508 continue;
4509 ifindex = routes->table[i].dwForwardIfIndex;
4510 ifmetric = routes->table[i].dwForwardMetric1;
4511 /* Only store the lowest valued metric for an interface */
4512 for (j = 0; j < numroutes; j++)
4514 if (route_addrs[j].interface == ifindex)
4516 if (route_addrs[j].metric > ifmetric)
4517 route_addrs[j].metric = ifmetric;
4518 exists = TRUE;
4521 if (exists)
4522 continue;
4523 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
4524 if (route_addrs == NULL)
4525 goto cleanup; /* Memory allocation error, fail gracefully */
4526 route_addrs[numroutes].interface = ifindex;
4527 route_addrs[numroutes].metric = ifmetric;
4528 /* If no IP is found in the next step (for whatever reason)
4529 * then fall back to the magic loopback address.
4531 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
4532 numroutes++;
4534 if (numroutes == 0)
4535 goto cleanup; /* No routes, fall back to the Magic IP */
4536 /* Find the IP address associated with each found interface */
4537 for (i = 0; i < numroutes; i++)
4539 for (k = adapters; k != NULL; k = k->Next)
4541 char *ip = k->IpAddressList.IpAddress.String;
4543 if (route_addrs[i].interface == k->Index)
4544 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
4547 /* Allocate a hostent and enough memory for all the IPs,
4548 * including the NULL at the end of the list.
4550 hostlist = WS_create_he(hostname, 1, numroutes+1, TRUE);
4551 if (hostlist == NULL)
4552 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
4553 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
4554 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
4555 hostlist->h_addrtype = AF_INET;
4556 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
4557 /* Reorder the entries when placing them in the host list, Windows expects
4558 * the IP list in order from highest priority to lowest (the critical thing
4559 * is that most applications expect the first IP to be the default route).
4561 last_metric = -1;
4562 for (i = 0; i < numroutes; i++)
4564 struct in_addr addr;
4565 int metric = 0xFFFF;
4567 memcpy(&addr, magic_loopback_addr, 4);
4568 for (j = 0; j < numroutes; j++)
4570 int this_metric = route_addrs[j].metric;
4572 if (this_metric > last_metric && this_metric < metric)
4574 addr = route_addrs[j].addr;
4575 metric = this_metric;
4578 last_metric = metric;
4579 (*(struct in_addr *) hostlist->h_addr_list[i]) = addr;
4582 /* Cleanup all allocated memory except the address list,
4583 * the address list is used by the calling app.
4585 cleanup:
4586 HeapFree(GetProcessHeap(), 0, route_addrs);
4587 HeapFree(GetProcessHeap(), 0, adapters);
4588 HeapFree(GetProcessHeap(), 0, routes);
4589 return hostlist;
4592 /***********************************************************************
4593 * gethostbyname (WS2_32.52)
4595 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
4597 struct WS_hostent *retval = NULL;
4598 struct hostent* host;
4599 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4600 char *extrabuf;
4601 int ebufsize=1024;
4602 struct hostent hostentry;
4603 int locerr = ENOBUFS;
4604 #endif
4605 char hostname[100];
4606 if(!num_startup) {
4607 SetLastError(WSANOTINITIALISED);
4608 return NULL;
4610 if( gethostname( hostname, 100) == -1) {
4611 SetLastError( WSAENOBUFS); /* appropriate ? */
4612 return retval;
4614 if( !name || !name[0]) {
4615 name = hostname;
4617 /* If the hostname of the local machine is requested then return the
4618 * complete list of local IP addresses */
4619 if(strcmp(name, hostname) == 0)
4620 retval = WS_get_local_ips(hostname);
4621 /* If any other hostname was requested (or the routing table lookup failed)
4622 * then return the IP found by the host OS */
4623 if(retval == NULL)
4625 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4626 host = NULL;
4627 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
4628 while(extrabuf) {
4629 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
4630 if( res != ERANGE) break;
4631 ebufsize *=2;
4632 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
4634 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
4635 #else
4636 EnterCriticalSection( &csWSgetXXXbyYYY );
4637 host = gethostbyname(name);
4638 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
4639 #endif
4640 if (host) retval = WS_dup_he(host);
4641 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4642 HeapFree(GetProcessHeap(),0,extrabuf);
4643 #else
4644 LeaveCriticalSection( &csWSgetXXXbyYYY );
4645 #endif
4647 if (retval && retval->h_addr_list[0][0] == 127 &&
4648 strcmp(name, "localhost") != 0)
4650 /* hostname != "localhost" but has loopback address. replace by our
4651 * special address.*/
4652 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
4654 TRACE( "%s ret %p\n", debugstr_a(name), retval );
4655 return retval;
4659 /***********************************************************************
4660 * getprotobyname (WS2_32.53)
4662 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
4664 struct WS_protoent* retval = NULL;
4665 #ifdef HAVE_GETPROTOBYNAME
4666 struct protoent* proto;
4667 EnterCriticalSection( &csWSgetXXXbyYYY );
4668 if( (proto = getprotobyname(name)) != NULL )
4670 retval = WS_dup_pe(proto);
4672 else {
4673 MESSAGE("protocol %s not found; You might want to add "
4674 "this to /etc/protocols\n", debugstr_a(name) );
4675 SetLastError(WSANO_DATA);
4677 LeaveCriticalSection( &csWSgetXXXbyYYY );
4678 #endif
4679 TRACE( "%s ret %p\n", debugstr_a(name), retval );
4680 return retval;
4684 /***********************************************************************
4685 * getprotobynumber (WS2_32.54)
4687 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
4689 struct WS_protoent* retval = NULL;
4690 #ifdef HAVE_GETPROTOBYNUMBER
4691 struct protoent* proto;
4692 EnterCriticalSection( &csWSgetXXXbyYYY );
4693 if( (proto = getprotobynumber(number)) != NULL )
4695 retval = WS_dup_pe(proto);
4697 else {
4698 MESSAGE("protocol number %d not found; You might want to add "
4699 "this to /etc/protocols\n", number );
4700 SetLastError(WSANO_DATA);
4702 LeaveCriticalSection( &csWSgetXXXbyYYY );
4703 #endif
4704 TRACE("%i ret %p\n", number, retval);
4705 return retval;
4709 /***********************************************************************
4710 * getservbyname (WS2_32.55)
4712 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
4714 struct WS_servent* retval = NULL;
4715 struct servent* serv;
4716 char *name_str;
4717 char *proto_str = NULL;
4719 if (!(name_str = strdup_lower(name))) return NULL;
4721 if (proto && *proto)
4723 if (!(proto_str = strdup_lower(proto)))
4725 HeapFree( GetProcessHeap(), 0, name_str );
4726 return NULL;
4730 EnterCriticalSection( &csWSgetXXXbyYYY );
4731 serv = getservbyname(name_str, proto_str);
4732 if( serv != NULL )
4734 retval = WS_dup_se(serv);
4736 else SetLastError(WSANO_DATA);
4737 LeaveCriticalSection( &csWSgetXXXbyYYY );
4738 HeapFree( GetProcessHeap(), 0, proto_str );
4739 HeapFree( GetProcessHeap(), 0, name_str );
4740 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
4741 return retval;
4744 /***********************************************************************
4745 * freeaddrinfo (WS2_32.@)
4747 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
4749 while (res) {
4750 struct WS_addrinfo *next;
4752 HeapFree(GetProcessHeap(),0,res->ai_canonname);
4753 HeapFree(GetProcessHeap(),0,res->ai_addr);
4754 next = res->ai_next;
4755 HeapFree(GetProcessHeap(),0,res);
4756 res = next;
4760 /* helper functions for getaddrinfo()/getnameinfo() */
4761 static int convert_aiflag_w2u(int winflags) {
4762 unsigned int i;
4763 int unixflags = 0;
4765 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
4766 if (ws_aiflag_map[i][0] & winflags) {
4767 unixflags |= ws_aiflag_map[i][1];
4768 winflags &= ~ws_aiflag_map[i][0];
4770 if (winflags)
4771 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
4772 return unixflags;
4775 static int convert_niflag_w2u(int winflags) {
4776 unsigned int i;
4777 int unixflags = 0;
4779 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
4780 if (ws_niflag_map[i][0] & winflags) {
4781 unixflags |= ws_niflag_map[i][1];
4782 winflags &= ~ws_niflag_map[i][0];
4784 if (winflags)
4785 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
4786 return unixflags;
4789 static int convert_aiflag_u2w(int unixflags) {
4790 unsigned int i;
4791 int winflags = 0;
4793 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
4794 if (ws_aiflag_map[i][1] & unixflags) {
4795 winflags |= ws_aiflag_map[i][0];
4796 unixflags &= ~ws_aiflag_map[i][1];
4798 if (unixflags) /* will warn usually */
4799 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
4800 return winflags;
4803 static int convert_eai_u2w(int unixret) {
4804 int i;
4806 for (i=0;ws_eai_map[i][0];i++)
4807 if (ws_eai_map[i][1] == unixret)
4808 return ws_eai_map[i][0];
4809 return unixret;
4812 static char *get_hostname(void)
4814 char *ret;
4815 DWORD size = 0;
4817 GetComputerNameExA( ComputerNamePhysicalDnsHostname, NULL, &size );
4818 if (GetLastError() != ERROR_MORE_DATA) return NULL;
4819 if (!(ret = HeapAlloc( GetProcessHeap(), 0, size ))) return NULL;
4820 if (!GetComputerNameExA( ComputerNamePhysicalDnsHostname, ret, &size ))
4822 HeapFree( GetProcessHeap(), 0, ret );
4823 return NULL;
4825 return ret;
4828 /***********************************************************************
4829 * getaddrinfo (WS2_32.@)
4831 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
4833 #ifdef HAVE_GETADDRINFO
4834 struct addrinfo *unixaires = NULL;
4835 int result;
4836 struct addrinfo unixhints, *punixhints = NULL;
4837 char *hostname = NULL;
4838 const char *node;
4840 if (!nodename && !servname) return WSAHOST_NOT_FOUND;
4842 if (!nodename)
4843 node = NULL;
4844 else if (!nodename[0])
4846 node = hostname = get_hostname();
4847 if (!node) return WSA_NOT_ENOUGH_MEMORY;
4849 else
4850 node = nodename;
4852 if (hints) {
4853 punixhints = &unixhints;
4855 memset(&unixhints, 0, sizeof(unixhints));
4856 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
4857 if (hints->ai_family == 0) /* wildcard, specific to getaddrinfo() */
4858 punixhints->ai_family = 0;
4859 else
4860 punixhints->ai_family = convert_af_w2u(hints->ai_family);
4861 if (hints->ai_socktype == 0) /* wildcard, specific to getaddrinfo() */
4862 punixhints->ai_socktype = 0;
4863 else
4864 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
4865 if (hints->ai_protocol == 0) /* wildcard, specific to getaddrinfo() */
4866 punixhints->ai_protocol = 0;
4867 else
4868 punixhints->ai_protocol = convert_proto_w2u(hints->ai_protocol);
4871 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
4872 result = getaddrinfo(node, servname, punixhints, &unixaires);
4874 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
4875 HeapFree(GetProcessHeap(), 0, hostname);
4877 if (!result) {
4878 struct addrinfo *xuai = unixaires;
4879 struct WS_addrinfo **xai = res;
4881 *xai = NULL;
4882 while (xuai) {
4883 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
4884 int len;
4886 if (!ai)
4887 goto outofmem;
4889 *xai = ai;xai = &ai->ai_next;
4890 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
4891 ai->ai_family = convert_af_u2w(xuai->ai_family);
4892 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
4893 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
4894 if (xuai->ai_canonname) {
4895 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
4896 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
4897 if (!ai->ai_canonname)
4898 goto outofmem;
4899 strcpy(ai->ai_canonname,xuai->ai_canonname);
4901 len = xuai->ai_addrlen;
4902 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
4903 if (!ai->ai_addr)
4904 goto outofmem;
4905 ai->ai_addrlen = len;
4906 do {
4907 int winlen = ai->ai_addrlen;
4909 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
4910 ai->ai_addrlen = winlen;
4911 break;
4913 len = 2*len;
4914 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
4915 if (!ai->ai_addr)
4916 goto outofmem;
4917 ai->ai_addrlen = len;
4918 } while (1);
4919 xuai = xuai->ai_next;
4921 freeaddrinfo(unixaires);
4922 } else {
4923 result = convert_eai_u2w(result);
4924 *res = NULL;
4926 return result;
4928 outofmem:
4929 if (*res) WS_freeaddrinfo(*res);
4930 if (unixaires) freeaddrinfo(unixaires);
4931 *res = NULL;
4932 return WSA_NOT_ENOUGH_MEMORY;
4933 #else
4934 FIXME("getaddrinfo() failed, not found during buildtime.\n");
4935 return EAI_FAIL;
4936 #endif
4939 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
4941 struct WS_addrinfoW *ret;
4943 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
4944 ret->ai_flags = ai->ai_flags;
4945 ret->ai_family = ai->ai_family;
4946 ret->ai_socktype = ai->ai_socktype;
4947 ret->ai_protocol = ai->ai_protocol;
4948 ret->ai_addrlen = ai->ai_addrlen;
4949 ret->ai_canonname = NULL;
4950 ret->ai_addr = NULL;
4951 ret->ai_next = NULL;
4952 if (ai->ai_canonname)
4954 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
4955 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
4957 HeapFree(GetProcessHeap(), 0, ret);
4958 return NULL;
4960 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
4962 if (ai->ai_addr)
4964 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
4966 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
4967 HeapFree(GetProcessHeap(), 0, ret);
4968 return NULL;
4970 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
4972 return ret;
4975 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
4977 struct WS_addrinfoW *ret, *infoW;
4979 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
4980 while (info->ai_next)
4982 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
4984 FreeAddrInfoW(ret);
4985 return NULL;
4987 infoW = infoW->ai_next;
4988 info = info->ai_next;
4990 return ret;
4993 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
4995 struct WS_addrinfo *ret;
4997 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
4998 ret->ai_flags = ai->ai_flags;
4999 ret->ai_family = ai->ai_family;
5000 ret->ai_socktype = ai->ai_socktype;
5001 ret->ai_protocol = ai->ai_protocol;
5002 ret->ai_addrlen = ai->ai_addrlen;
5003 ret->ai_canonname = NULL;
5004 ret->ai_addr = NULL;
5005 ret->ai_next = NULL;
5006 if (ai->ai_canonname)
5008 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
5009 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
5011 HeapFree(GetProcessHeap(), 0, ret);
5012 return NULL;
5014 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
5016 if (ai->ai_addr)
5018 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
5020 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
5021 HeapFree(GetProcessHeap(), 0, ret);
5022 return NULL;
5024 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
5026 return ret;
5029 /***********************************************************************
5030 * GetAddrInfoW (WS2_32.@)
5032 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
5034 int ret, len;
5035 char *nodenameA = NULL, *servnameA = NULL;
5036 struct WS_addrinfo *resA, *hintsA = NULL;
5038 if (nodename)
5040 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
5041 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
5042 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
5044 if (servname)
5046 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
5047 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
5049 HeapFree(GetProcessHeap(), 0, nodenameA);
5050 return EAI_MEMORY;
5052 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
5055 if (hints) hintsA = addrinfo_WtoA(hints);
5056 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
5057 WS_freeaddrinfo(hintsA);
5059 if (!ret)
5061 *res = addrinfo_list_AtoW(resA);
5062 WS_freeaddrinfo(resA);
5065 HeapFree(GetProcessHeap(), 0, nodenameA);
5066 HeapFree(GetProcessHeap(), 0, servnameA);
5067 return ret;
5070 /***********************************************************************
5071 * FreeAddrInfoW (WS2_32.@)
5073 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
5075 while (ai)
5077 ADDRINFOW *next;
5078 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
5079 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
5080 next = ai->ai_next;
5081 HeapFree(GetProcessHeap(), 0, ai);
5082 ai = next;
5086 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
5087 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
5089 #ifdef HAVE_GETNAMEINFO
5090 int ret;
5091 union generic_unix_sockaddr sa_u;
5092 unsigned int size;
5094 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
5095 serv, servlen, flags);
5097 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
5098 if (!size)
5100 WSASetLastError(WSAEFAULT);
5101 return WSA_NOT_ENOUGH_MEMORY;
5103 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
5104 return convert_eai_u2w(ret);
5105 #else
5106 FIXME("getnameinfo() failed, not found during buildtime.\n");
5107 return EAI_FAIL;
5108 #endif
5111 int WINAPI GetNameInfoW(const SOCKADDR *sa, WS_socklen_t salen, PWCHAR host,
5112 DWORD hostlen, PWCHAR serv, DWORD servlen, INT flags)
5114 int ret;
5115 char *hostA = NULL, *servA = NULL;
5117 if (host && (!(hostA = HeapAlloc(GetProcessHeap(), 0, hostlen)))) return EAI_MEMORY;
5118 if (serv && (!(servA = HeapAlloc(GetProcessHeap(), 0, servlen))))
5120 HeapFree(GetProcessHeap(), 0, hostA);
5121 return EAI_MEMORY;
5124 ret = WS_getnameinfo(sa, salen, hostA, hostlen, servA, servlen, flags);
5125 if (!ret)
5127 if (host) MultiByteToWideChar(CP_ACP, 0, hostA, -1, host, hostlen);
5128 if (serv) MultiByteToWideChar(CP_ACP, 0, servA, -1, serv, servlen);
5131 HeapFree(GetProcessHeap(), 0, hostA);
5132 HeapFree(GetProcessHeap(), 0, servA);
5133 return ret;
5136 /***********************************************************************
5137 * getservbyport (WS2_32.56)
5139 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
5141 struct WS_servent* retval = NULL;
5142 #ifdef HAVE_GETSERVBYPORT
5143 struct servent* serv;
5144 char *proto_str = NULL;
5146 if (proto && *proto)
5148 if (!(proto_str = strdup_lower(proto))) return NULL;
5150 EnterCriticalSection( &csWSgetXXXbyYYY );
5151 if( (serv = getservbyport(port, proto_str)) != NULL ) {
5152 retval = WS_dup_se(serv);
5154 else SetLastError(WSANO_DATA);
5155 LeaveCriticalSection( &csWSgetXXXbyYYY );
5156 HeapFree( GetProcessHeap(), 0, proto_str );
5157 #endif
5158 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
5159 return retval;
5163 /***********************************************************************
5164 * gethostname (WS2_32.57)
5166 int WINAPI WS_gethostname(char *name, int namelen)
5168 TRACE("name %p, len %d\n", name, namelen);
5170 if (gethostname(name, namelen) == 0)
5172 TRACE("<- '%s'\n", name);
5173 return 0;
5175 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
5176 TRACE("<- ERROR !\n");
5177 return SOCKET_ERROR;
5181 /* ------------------------------------- Windows sockets extensions -- *
5183 * ------------------------------------------------------------------- */
5185 /***********************************************************************
5186 * WSAEnumNetworkEvents (WS2_32.36)
5188 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
5190 int ret;
5191 int i;
5192 int errors[FD_MAX_EVENTS];
5194 TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
5196 SERVER_START_REQ( get_socket_event )
5198 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5199 req->service = TRUE;
5200 req->c_event = wine_server_obj_handle( hEvent );
5201 wine_server_set_reply( req, errors, sizeof(errors) );
5202 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
5204 SERVER_END_REQ;
5205 if (!ret)
5207 for (i = 0; i < FD_MAX_EVENTS; i++)
5208 lpEvent->iErrorCode[i] = NtStatusToWSAError(errors[i]);
5209 return 0;
5211 SetLastError(WSAEINVAL);
5212 return SOCKET_ERROR;
5215 /***********************************************************************
5216 * WSAEventSelect (WS2_32.39)
5218 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
5220 int ret;
5222 TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
5224 SERVER_START_REQ( set_socket_event )
5226 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5227 req->mask = lEvent;
5228 req->event = wine_server_obj_handle( hEvent );
5229 req->window = 0;
5230 req->msg = 0;
5231 ret = wine_server_call( req );
5233 SERVER_END_REQ;
5234 if (!ret) return 0;
5235 SetLastError(WSAEINVAL);
5236 return SOCKET_ERROR;
5239 /**********************************************************************
5240 * WSAGetOverlappedResult (WS2_32.40)
5242 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
5243 LPDWORD lpcbTransfer, BOOL fWait,
5244 LPDWORD lpdwFlags )
5246 NTSTATUS status;
5248 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
5249 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
5251 if ( lpOverlapped == NULL )
5253 ERR( "Invalid pointer\n" );
5254 WSASetLastError(WSA_INVALID_PARAMETER);
5255 return FALSE;
5258 status = lpOverlapped->Internal;
5259 if (status == STATUS_PENDING)
5261 if (!fWait)
5263 SetLastError( WSA_IO_INCOMPLETE );
5264 return FALSE;
5267 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
5268 INFINITE ) == WAIT_FAILED)
5269 return FALSE;
5270 status = lpOverlapped->Internal;
5273 if ( lpcbTransfer )
5274 *lpcbTransfer = lpOverlapped->InternalHigh;
5276 if ( lpdwFlags )
5277 *lpdwFlags = lpOverlapped->u.s.Offset;
5279 if (status) SetLastError( RtlNtStatusToDosError(status) );
5280 return !status;
5284 /***********************************************************************
5285 * WSAAsyncSelect (WS2_32.101)
5287 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
5289 int ret;
5291 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
5293 SERVER_START_REQ( set_socket_event )
5295 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5296 req->mask = lEvent;
5297 req->event = 0;
5298 req->window = wine_server_user_handle( hWnd );
5299 req->msg = uMsg;
5300 ret = wine_server_call( req );
5302 SERVER_END_REQ;
5303 if (!ret) return 0;
5304 SetLastError(WSAEINVAL);
5305 return SOCKET_ERROR;
5308 /***********************************************************************
5309 * WSACreateEvent (WS2_32.31)
5312 WSAEVENT WINAPI WSACreateEvent(void)
5314 /* Create a manual-reset event, with initial state: unsignaled */
5315 TRACE("\n");
5317 return CreateEventW(NULL, TRUE, FALSE, NULL);
5320 /***********************************************************************
5321 * WSACloseEvent (WS2_32.29)
5324 BOOL WINAPI WSACloseEvent(WSAEVENT event)
5326 TRACE ("event=%p\n", event);
5328 return CloseHandle(event);
5331 /***********************************************************************
5332 * WSASocketA (WS2_32.78)
5335 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
5336 LPWSAPROTOCOL_INFOA lpProtocolInfo,
5337 GROUP g, DWORD dwFlags)
5339 INT len;
5340 WSAPROTOCOL_INFOW info;
5342 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
5343 af, type, protocol, lpProtocolInfo, g, dwFlags);
5345 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
5347 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
5348 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
5349 info.szProtocol, WSAPROTOCOL_LEN + 1);
5351 if (!len)
5353 WSASetLastError( WSAEINVAL);
5354 return SOCKET_ERROR;
5357 return WSASocketW(af, type, protocol, &info, g, dwFlags);
5360 /***********************************************************************
5361 * WSASocketW (WS2_32.79)
5364 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
5365 LPWSAPROTOCOL_INFOW lpProtocolInfo,
5366 GROUP g, DWORD dwFlags)
5368 SOCKET ret;
5371 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
5372 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
5375 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
5376 af, type, protocol, lpProtocolInfo, g, dwFlags );
5378 /* hack for WSADuplicateSocket */
5379 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
5380 ret = lpProtocolInfo->dwCatalogEntryId;
5381 TRACE("\tgot duplicate %04lx\n", ret);
5382 return ret;
5385 /* convert the socket family and type */
5386 af = convert_af_w2u(af);
5387 type = convert_socktype_w2u(type);
5389 if (lpProtocolInfo)
5391 if (af == FROM_PROTOCOL_INFO)
5392 af = lpProtocolInfo->iAddressFamily;
5393 if (type == FROM_PROTOCOL_INFO)
5394 type = lpProtocolInfo->iSocketType;
5395 if (protocol == FROM_PROTOCOL_INFO)
5396 protocol = lpProtocolInfo->iProtocol;
5399 if ( af == AF_UNSPEC) /* did they not specify the address family? */
5401 if ((protocol == IPPROTO_TCP && type == SOCK_STREAM) ||
5402 (protocol == IPPROTO_UDP && type == SOCK_DGRAM))
5404 af = AF_INET;
5406 else
5408 SetLastError(WSAEPROTOTYPE);
5409 return INVALID_SOCKET;
5413 SERVER_START_REQ( create_socket )
5415 req->family = af;
5416 req->type = type;
5417 req->protocol = protocol;
5418 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
5419 req->attributes = OBJ_INHERIT;
5420 req->flags = dwFlags;
5421 set_error( wine_server_call( req ) );
5422 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
5424 SERVER_END_REQ;
5425 if (ret)
5427 TRACE("\tcreated %04lx\n", ret );
5428 return ret;
5431 if (GetLastError() == WSAEACCES) /* raw socket denied */
5433 if (type == SOCK_RAW)
5434 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
5435 else
5436 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
5437 SetLastError(WSAESOCKTNOSUPPORT);
5440 WARN("\t\tfailed!\n");
5441 return INVALID_SOCKET;
5444 /***********************************************************************
5445 * WSAJoinLeaf (WS2_32.58)
5448 SOCKET WINAPI WSAJoinLeaf(
5449 SOCKET s,
5450 const struct WS_sockaddr *addr,
5451 int addrlen,
5452 LPWSABUF lpCallerData,
5453 LPWSABUF lpCalleeData,
5454 LPQOS lpSQOS,
5455 LPQOS lpGQOS,
5456 DWORD dwFlags)
5458 FIXME("stub.\n");
5459 return INVALID_SOCKET;
5462 /***********************************************************************
5463 * __WSAFDIsSet (WS2_32.151)
5465 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
5467 int i = set->fd_count;
5469 TRACE("(%ld,%p(%i))\n", s, set, i);
5471 while (i--)
5472 if (set->fd_array[i] == s) return 1;
5473 return 0;
5476 /***********************************************************************
5477 * WSAIsBlocking (WS2_32.114)
5479 BOOL WINAPI WSAIsBlocking(void)
5481 /* By default WinSock should set all its sockets to non-blocking mode
5482 * and poll in PeekMessage loop when processing "blocking" ones. This
5483 * function is supposed to tell if the program is in this loop. Our
5484 * blocking calls are truly blocking so we always return FALSE.
5486 * Note: It is allowed to call this function without prior WSAStartup().
5489 TRACE("\n");
5490 return FALSE;
5493 /***********************************************************************
5494 * WSACancelBlockingCall (WS2_32.113)
5496 INT WINAPI WSACancelBlockingCall(void)
5498 TRACE("\n");
5499 return 0;
5502 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
5504 FIXME("How was this called?\n");
5505 return x();
5509 /***********************************************************************
5510 * WSASetBlockingHook (WS2_32.109)
5512 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
5514 FARPROC prev = blocking_hook;
5515 blocking_hook = lpBlockFunc;
5516 TRACE("hook %p\n", lpBlockFunc);
5517 return prev;
5521 /***********************************************************************
5522 * WSAUnhookBlockingHook (WS2_32.110)
5524 INT WINAPI WSAUnhookBlockingHook(void)
5526 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
5527 return 0;
5531 /* ----------------------------------- end of API stuff */
5533 /* ----------------------------------- helper functions -
5535 * TODO: Merge WS_dup_..() stuff into one function that
5536 * would operate with a generic structure containing internal
5537 * pointers (via a template of some kind).
5540 static int list_size(char** l, int item_size)
5542 int i,j = 0;
5543 if(l)
5544 { for(i=0;l[i];i++)
5545 j += (item_size) ? item_size : strlen(l[i]) + 1;
5546 j += (i + 1) * sizeof(char*); }
5547 return j;
5550 static int list_dup(char** l_src, char** l_to, int item_size)
5552 char *p;
5553 int i;
5555 for (i = 0; l_src[i]; i++) ;
5556 p = (char *)(l_to + i + 1);
5557 for (i = 0; l_src[i]; i++)
5559 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
5560 memcpy(p, l_src[i], count);
5561 l_to[i] = p;
5562 p += count;
5564 l_to[i] = NULL;
5565 return p - (char *)l_to;
5568 /* ----- hostent */
5570 /* create a hostent entry
5572 * Creates the entry with enough memory for the name, aliases
5573 * addresses, and the address pointers. Also copies the name
5574 * and sets up all the pointers. If "fill_addresses" is set then
5575 * sufficient memory for the addresses is also allocated and the
5576 * address pointers are set to this memory.
5578 * NOTE: The alias and address lists must be allocated with room
5579 * for the NULL item terminating the list. This is true even if
5580 * the list has no items ("aliases" and "addresses" must be
5581 * at least "1", a truly empty list is invalid).
5583 static struct WS_hostent *WS_create_he(char *name, int aliases, int addresses, int fill_addresses)
5585 struct WS_hostent *p_to;
5586 char *p;
5588 int size = (sizeof(struct WS_hostent) +
5589 strlen(name) + 1 +
5590 sizeof(char *)*aliases +
5591 sizeof(char *)*addresses);
5593 /* Allocate enough memory for the addresses */
5594 if (fill_addresses)
5595 size += sizeof(struct in_addr)*addresses;
5597 if (!(p_to = check_buffer_he(size))) return NULL;
5598 memset(p_to, 0, size);
5600 p = (char *)(p_to + 1);
5601 p_to->h_name = p;
5602 strcpy(p, name);
5603 p += strlen(p) + 1;
5605 p_to->h_aliases = (char **)p;
5606 p += sizeof(char *)*aliases;
5607 p_to->h_addr_list = (char **)p;
5608 p += sizeof(char *)*addresses;
5609 if (fill_addresses)
5611 int i;
5613 /* NOTE: h_aliases must be filled in manually, leave these
5614 * pointers NULL (already set to NULL by memset earlier).
5617 /* Fill in the list of address pointers */
5618 for (i = 0; i < addresses; i++)
5619 p_to->h_addr_list[i] = (p += sizeof(struct in_addr));
5620 p += sizeof(struct in_addr);
5622 return p_to;
5625 /* duplicate hostent entry
5626 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
5627 * Ditto for protoent and servent.
5629 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
5631 int addresses = list_size(p_he->h_addr_list, p_he->h_length);
5632 int aliases = list_size(p_he->h_aliases, 0);
5633 struct WS_hostent *p_to;
5635 p_to = WS_create_he(p_he->h_name, aliases, addresses, FALSE);
5637 if (!p_to) return NULL;
5638 p_to->h_addrtype = p_he->h_addrtype;
5639 p_to->h_length = p_he->h_length;
5641 list_dup(p_he->h_aliases, p_to->h_aliases, 0);
5642 list_dup(p_he->h_addr_list, p_to->h_addr_list, p_he->h_length);
5643 return p_to;
5646 /* ----- protoent */
5648 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
5650 char *p;
5651 struct WS_protoent *p_to;
5653 int size = (sizeof(*p_pe) +
5654 strlen(p_pe->p_name) + 1 +
5655 list_size(p_pe->p_aliases, 0));
5657 if (!(p_to = check_buffer_pe(size))) return NULL;
5658 p_to->p_proto = p_pe->p_proto;
5660 p = (char *)(p_to + 1);
5661 p_to->p_name = p;
5662 strcpy(p, p_pe->p_name);
5663 p += strlen(p) + 1;
5665 p_to->p_aliases = (char **)p;
5666 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
5667 return p_to;
5670 /* ----- servent */
5672 static struct WS_servent *WS_dup_se(const struct servent* p_se)
5674 char *p;
5675 struct WS_servent *p_to;
5677 int size = (sizeof(*p_se) +
5678 strlen(p_se->s_proto) + 1 +
5679 strlen(p_se->s_name) + 1 +
5680 list_size(p_se->s_aliases, 0));
5682 if (!(p_to = check_buffer_se(size))) return NULL;
5683 p_to->s_port = p_se->s_port;
5685 p = (char *)(p_to + 1);
5686 p_to->s_name = p;
5687 strcpy(p, p_se->s_name);
5688 p += strlen(p) + 1;
5690 p_to->s_proto = p;
5691 strcpy(p, p_se->s_proto);
5692 p += strlen(p) + 1;
5694 p_to->s_aliases = (char **)p;
5695 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
5696 return p_to;
5700 /***********************************************************************
5701 * WSARecv (WS2_32.67)
5703 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5704 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
5705 LPWSAOVERLAPPED lpOverlapped,
5706 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
5708 return WS2_recv_base(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
5709 NULL, NULL, lpOverlapped, lpCompletionRoutine, NULL);
5712 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5713 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
5714 struct WS_sockaddr *lpFrom,
5715 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
5716 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
5717 LPWSABUF lpControlBuffer )
5719 unsigned int i, options;
5720 int n, fd, err;
5721 struct ws2_async *wsa;
5722 DWORD timeout_start = GetTickCount();
5723 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
5725 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
5726 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
5727 (lpFromlen ? *lpFromlen : -1),
5728 lpOverlapped, lpCompletionRoutine);
5730 fd = get_sock_fd( s, FILE_READ_DATA, &options );
5731 TRACE( "fd=%d, options=%x\n", fd, options );
5733 if (fd == -1) return SOCKET_ERROR;
5735 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
5737 err = WSAEFAULT;
5738 goto error;
5741 wsa->hSocket = SOCKET2HANDLE(s);
5742 wsa->flags = *lpFlags;
5743 wsa->lpFlags = lpFlags;
5744 wsa->addr = lpFrom;
5745 wsa->addrlen.ptr = lpFromlen;
5746 wsa->control = lpControlBuffer;
5747 wsa->n_iovecs = dwBufferCount;
5748 wsa->first_iovec = 0;
5749 for (i = 0; i < dwBufferCount; i++)
5751 /* check buffer first to trigger write watches */
5752 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
5754 err = WSAEFAULT;
5755 goto error;
5757 wsa->iovec[i].iov_base = lpBuffers[i].buf;
5758 wsa->iovec[i].iov_len = lpBuffers[i].len;
5761 for (;;)
5763 n = WS2_recv( fd, wsa );
5764 if (n == -1)
5766 if (errno == EINTR) continue;
5767 if (errno != EAGAIN)
5769 int loc_errno = errno;
5770 err = wsaErrno();
5771 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
5772 goto error;
5775 else if (lpNumberOfBytesRecvd) *lpNumberOfBytesRecvd = n;
5777 if ((lpOverlapped || lpCompletionRoutine) &&
5778 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
5780 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
5782 wsa->user_overlapped = lpOverlapped;
5783 wsa->completion_func = lpCompletionRoutine;
5784 release_sock_fd( s, fd );
5786 if (n == -1)
5788 iosb->u.Status = STATUS_PENDING;
5789 iosb->Information = 0;
5791 SERVER_START_REQ( register_async )
5793 req->type = ASYNC_TYPE_READ;
5794 req->async.handle = wine_server_obj_handle( wsa->hSocket );
5795 req->async.callback = wine_server_client_ptr( WS2_async_recv );
5796 req->async.iosb = wine_server_client_ptr( iosb );
5797 req->async.arg = wine_server_client_ptr( wsa );
5798 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
5799 req->async.cvalue = cvalue;
5800 err = wine_server_call( req );
5802 SERVER_END_REQ;
5804 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
5805 WSASetLastError( NtStatusToWSAError( err ));
5806 return SOCKET_ERROR;
5809 iosb->u.Status = STATUS_SUCCESS;
5810 iosb->Information = n;
5811 if (!wsa->completion_func)
5813 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
5814 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
5815 HeapFree( GetProcessHeap(), 0, wsa );
5817 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
5818 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
5819 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5820 return 0;
5823 if (n != -1) break;
5825 if ( _is_blocking(s) )
5827 struct pollfd pfd;
5828 int timeout = GET_RCVTIMEO(fd);
5829 if (timeout != -1)
5831 timeout -= GetTickCount() - timeout_start;
5832 if (timeout < 0) timeout = 0;
5835 pfd.fd = fd;
5836 pfd.events = POLLIN;
5837 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
5839 if (!timeout || !poll( &pfd, 1, timeout ))
5841 err = WSAETIMEDOUT;
5842 /* a timeout is not fatal */
5843 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5844 goto error;
5847 else
5849 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5850 err = WSAEWOULDBLOCK;
5851 goto error;
5855 TRACE(" -> %i bytes\n", n);
5856 HeapFree( GetProcessHeap(), 0, wsa );
5857 release_sock_fd( s, fd );
5858 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5860 return 0;
5862 error:
5863 HeapFree( GetProcessHeap(), 0, wsa );
5864 release_sock_fd( s, fd );
5865 WARN(" -> ERROR %d\n", err);
5866 WSASetLastError( err );
5867 return SOCKET_ERROR;
5870 /***********************************************************************
5871 * WSARecvFrom (WS2_32.69)
5873 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5874 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
5875 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
5876 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5879 return WS2_recv_base( s, lpBuffers, dwBufferCount,
5880 lpNumberOfBytesRecvd, lpFlags,
5881 lpFrom, lpFromlen,
5882 lpOverlapped, lpCompletionRoutine, NULL );
5885 /***********************************************************************
5886 * WSCInstallProvider (WS2_32.88)
5888 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
5889 LPCWSTR lpszProviderDllPath,
5890 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
5891 DWORD dwNumberOfEntries,
5892 LPINT lpErrno )
5894 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
5895 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
5896 dwNumberOfEntries, lpErrno);
5897 *lpErrno = 0;
5898 return 0;
5902 /***********************************************************************
5903 * WSCDeinstallProvider (WS2_32.83)
5905 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
5907 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
5908 *lpErrno = 0;
5909 return 0;
5913 /***********************************************************************
5914 * WSAAccept (WS2_32.26)
5916 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
5917 LPCONDITIONPROC lpfnCondition, DWORD_PTR dwCallbackData)
5920 int ret = 0, size = 0;
5921 WSABUF CallerId, CallerData, CalleeId, CalleeData;
5922 /* QOS SQOS, GQOS; */
5923 GROUP g;
5924 SOCKET cs;
5925 SOCKADDR src_addr, dst_addr;
5927 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
5928 s, addr, addrlen, lpfnCondition, dwCallbackData);
5931 size = sizeof(src_addr);
5932 cs = WS_accept(s, &src_addr, &size);
5934 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
5936 if (!lpfnCondition) return cs;
5938 CallerId.buf = (char *)&src_addr;
5939 CallerId.len = sizeof(src_addr);
5941 CallerData.buf = NULL;
5942 CallerData.len = 0;
5944 WS_getsockname(cs, &dst_addr, &size);
5946 CalleeId.buf = (char *)&dst_addr;
5947 CalleeId.len = sizeof(dst_addr);
5950 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
5951 &CalleeId, &CalleeData, &g, dwCallbackData);
5953 switch (ret)
5955 case CF_ACCEPT:
5956 if (addr && addrlen)
5957 memcpy(addr, &src_addr, (*addrlen > size) ? size : *addrlen );
5958 return cs;
5959 case CF_DEFER:
5960 SERVER_START_REQ( set_socket_deferred )
5962 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5963 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
5964 if ( !wine_server_call_err ( req ) )
5966 SetLastError( WSATRY_AGAIN );
5967 WS_closesocket( cs );
5970 SERVER_END_REQ;
5971 return SOCKET_ERROR;
5972 case CF_REJECT:
5973 WS_closesocket(cs);
5974 SetLastError(WSAECONNREFUSED);
5975 return SOCKET_ERROR;
5976 default:
5977 FIXME("Unknown return type from Condition function\n");
5978 SetLastError(WSAENOTSOCK);
5979 return SOCKET_ERROR;
5983 /***********************************************************************
5984 * WSADuplicateSocketA (WS2_32.32)
5986 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
5988 HANDLE hProcess;
5990 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
5991 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
5992 /* FIXME: WS_getsockopt(s, WS_SOL_SOCKET, SO_PROTOCOL_INFO, lpProtocolInfo, sizeof(*lpProtocolInfo)); */
5993 /* I don't know what the real Windoze does next, this is a hack */
5994 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
5995 * the target use the global duplicate, or we could copy a reference to us to the structure
5996 * and let the target duplicate it from us, but let's do it as simple as possible */
5997 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
5998 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
5999 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
6000 0, FALSE, DUPLICATE_SAME_ACCESS);
6001 CloseHandle(hProcess);
6002 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
6003 return 0;
6006 /***********************************************************************
6007 * WSADuplicateSocketW (WS2_32.33)
6009 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
6011 HANDLE hProcess;
6013 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
6015 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
6016 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
6017 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
6018 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
6019 0, FALSE, DUPLICATE_SAME_ACCESS);
6020 CloseHandle(hProcess);
6021 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
6022 return 0;
6025 /***********************************************************************
6026 * WSAInstallServiceClassA (WS2_32.48)
6028 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
6030 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
6031 WSASetLastError(WSAEACCES);
6032 return SOCKET_ERROR;
6035 /***********************************************************************
6036 * WSAInstallServiceClassW (WS2_32.49)
6038 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
6040 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
6041 WSASetLastError(WSAEACCES);
6042 return SOCKET_ERROR;
6045 /***********************************************************************
6046 * WSARemoveServiceClass (WS2_32.70)
6048 int WINAPI WSARemoveServiceClass(LPGUID info)
6050 FIXME("Request to remove service %p\n",info);
6051 WSASetLastError(WSATYPE_NOT_FOUND);
6052 return SOCKET_ERROR;
6055 /***********************************************************************
6056 * inet_ntop (WS2_32.@)
6058 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
6060 #ifdef HAVE_INET_NTOP
6061 struct WS_in6_addr *in6;
6062 struct WS_in_addr *in;
6063 PCSTR pdst;
6065 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
6066 if (!buffer)
6068 WSASetLastError( STATUS_INVALID_PARAMETER );
6069 return NULL;
6072 switch (family)
6074 case WS_AF_INET:
6076 in = addr;
6077 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
6078 break;
6080 case WS_AF_INET6:
6082 in6 = addr;
6083 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
6084 break;
6086 default:
6087 WSASetLastError( WSAEAFNOSUPPORT );
6088 return NULL;
6091 if (!pdst) WSASetLastError( STATUS_INVALID_PARAMETER );
6092 return pdst;
6093 #else
6094 FIXME( "not supported on this platform\n" );
6095 WSASetLastError( WSAEAFNOSUPPORT );
6096 return NULL;
6097 #endif
6100 /***********************************************************************
6101 * WSAStringToAddressA (WS2_32.80)
6103 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
6104 INT AddressFamily,
6105 LPWSAPROTOCOL_INFOA lpProtocolInfo,
6106 LPSOCKADDR lpAddress,
6107 LPINT lpAddressLength)
6109 INT res=0;
6110 LPSTR workBuffer=NULL,ptrPort;
6112 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
6113 lpProtocolInfo, lpAddress, lpAddressLength );
6115 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
6117 if (!AddressString)
6119 WSASetLastError(WSAEINVAL);
6120 return SOCKET_ERROR;
6123 if (lpProtocolInfo)
6124 FIXME("ProtocolInfo not implemented.\n");
6126 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
6127 strlen(AddressString) + 1);
6128 if (!workBuffer)
6130 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6131 return SOCKET_ERROR;
6134 strcpy(workBuffer, AddressString);
6136 switch(AddressFamily)
6138 case WS_AF_INET:
6140 struct in_addr inetaddr;
6142 /* If lpAddressLength is too small, tell caller the size we need */
6143 if (*lpAddressLength < sizeof(SOCKADDR_IN))
6145 *lpAddressLength = sizeof(SOCKADDR_IN);
6146 res = WSAEFAULT;
6147 break;
6149 *lpAddressLength = sizeof(SOCKADDR_IN);
6150 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
6152 ((LPSOCKADDR_IN)lpAddress)->sin_family = AF_INET;
6154 ptrPort = strchr(workBuffer, ':');
6155 if(ptrPort)
6157 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
6158 *ptrPort = '\0';
6160 else
6162 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
6165 if(inet_aton(workBuffer, &inetaddr) > 0)
6167 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
6168 res = 0;
6170 else
6171 res = WSAEINVAL;
6173 break;
6176 case WS_AF_INET6:
6178 struct in6_addr inetaddr;
6179 /* If lpAddressLength is too small, tell caller the size we need */
6180 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
6182 *lpAddressLength = sizeof(SOCKADDR_IN6);
6183 res = WSAEFAULT;
6184 break;
6186 #ifdef HAVE_INET_PTON
6187 *lpAddressLength = sizeof(SOCKADDR_IN6);
6188 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
6190 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
6192 /* This one is a bit tricky. An IPv6 address contains colons, so the
6193 * check from IPv4 doesn't work like that. However, IPv6 addresses that
6194 * contain a port are written with braces like [fd12:3456:7890::1]:12345
6195 * so what we will do is to look for ']', check if the next char is a
6196 * colon, and if it is, parse the port as in IPv4. */
6198 ptrPort = strchr(workBuffer, ']');
6199 if(ptrPort && *(++ptrPort) == ':')
6201 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort+1));
6202 *ptrPort = '\0';
6204 else
6206 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
6209 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
6211 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
6212 sizeof(struct in6_addr));
6213 res = 0;
6215 else
6216 #endif /* HAVE_INET_PTON */
6217 res = WSAEINVAL;
6219 break;
6221 default:
6222 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
6223 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
6224 res = WSAEINVAL;
6227 HeapFree(GetProcessHeap(), 0, workBuffer);
6229 if (!res) return 0;
6230 WSASetLastError(res);
6231 return SOCKET_ERROR;
6234 /***********************************************************************
6235 * WSAStringToAddressW (WS2_32.81)
6237 * Does anybody know if this function allows to use Hebrew/Arabic/Chinese... digits?
6238 * If this should be the case, it would be required to map these digits
6239 * to Unicode digits (0-9) using FoldString first.
6241 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
6242 INT AddressFamily,
6243 LPWSAPROTOCOL_INFOW lpProtocolInfo,
6244 LPSOCKADDR lpAddress,
6245 LPINT lpAddressLength)
6247 INT sBuffer,res=0;
6248 LPSTR workBuffer=NULL;
6249 WSAPROTOCOL_INFOA infoA;
6250 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
6252 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
6253 lpAddress, lpAddressLength );
6255 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
6257 /* if ProtocolInfo is available - convert to ANSI variant */
6258 if (lpProtocolInfo)
6260 lpProtoInfoA = &infoA;
6261 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
6263 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
6264 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
6266 WSASetLastError( WSAEINVAL);
6267 return SOCKET_ERROR;
6271 if (AddressString)
6273 /* Translate AddressString to ANSI code page - assumes that only
6274 standard digits 0-9 are used with this API call */
6275 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
6276 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
6278 if (workBuffer)
6280 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
6281 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
6282 lpAddress,lpAddressLength);
6283 HeapFree( GetProcessHeap(), 0, workBuffer );
6284 return res;
6286 else
6287 res = WSA_NOT_ENOUGH_MEMORY;
6289 else
6290 res = WSAEINVAL;
6292 WSASetLastError(res);
6293 return SOCKET_ERROR;
6296 /***********************************************************************
6297 * WSAAddressToStringA (WS2_32.27)
6299 * See WSAAddressToStringW
6301 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
6302 LPWSAPROTOCOL_INFOA info, LPSTR string,
6303 LPDWORD lenstr )
6305 DWORD size;
6306 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
6307 CHAR *p;
6309 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
6311 if (!sockaddr) return SOCKET_ERROR;
6312 if (!string || !lenstr) return SOCKET_ERROR;
6314 switch(sockaddr->sa_family)
6316 case WS_AF_INET:
6317 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
6318 sprintf( buffer, "%u.%u.%u.%u:%u",
6319 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
6320 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
6321 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
6322 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
6323 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
6325 p = strchr( buffer, ':' );
6326 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
6327 break;
6329 case WS_AF_INET6:
6331 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
6333 buffer[0] = 0;
6334 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
6335 if ((sockaddr6->sin6_port))
6336 strcpy(buffer, "[");
6337 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, buffer+strlen(buffer), sizeof(buffer)))
6339 WSASetLastError(WSAEINVAL);
6340 return SOCKET_ERROR;
6342 if ((sockaddr6->sin6_scope_id))
6343 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
6344 if ((sockaddr6->sin6_port))
6345 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
6346 break;
6349 default:
6350 WSASetLastError(WSAEINVAL);
6351 return SOCKET_ERROR;
6354 size = strlen( buffer ) + 1;
6356 if (*lenstr < size)
6358 *lenstr = size;
6359 WSASetLastError(WSAEFAULT);
6360 return SOCKET_ERROR;
6363 *lenstr = size;
6364 strcpy( string, buffer );
6365 return 0;
6368 /***********************************************************************
6369 * WSAAddressToStringW (WS2_32.28)
6371 * Convert a sockaddr address into a readable address string.
6373 * PARAMS
6374 * sockaddr [I] Pointer to a sockaddr structure.
6375 * len [I] Size of the sockaddr structure.
6376 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
6377 * string [I/O] Pointer to a buffer to receive the address string.
6378 * lenstr [I/O] Size of the receive buffer in WCHARs.
6380 * RETURNS
6381 * Success: 0
6382 * Failure: SOCKET_ERROR
6384 * NOTES
6385 * The 'info' parameter is ignored.
6387 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
6388 LPWSAPROTOCOL_INFOW info, LPWSTR string,
6389 LPDWORD lenstr )
6391 INT ret;
6392 DWORD size;
6393 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
6394 CHAR bufAddr[54];
6396 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
6398 size = *lenstr;
6399 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
6401 if (ret) return ret;
6403 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
6405 if (*lenstr < size)
6407 *lenstr = size;
6408 WSASetLastError(WSAEFAULT);
6409 return SOCKET_ERROR;
6412 *lenstr = size;
6413 lstrcpyW( string, buffer );
6414 return 0;
6417 /***********************************************************************
6418 * WSAEnumNameSpaceProvidersA (WS2_32.34)
6420 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
6422 FIXME( "(%p %p) Stub!\n", len, buffer );
6423 return 0;
6426 /***********************************************************************
6427 * WSAEnumNameSpaceProvidersW (WS2_32.35)
6429 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
6431 FIXME( "(%p %p) Stub!\n", len, buffer );
6432 return 0;
6435 /***********************************************************************
6436 * WSAGetQOSByName (WS2_32.41)
6438 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
6440 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
6441 return FALSE;
6444 /***********************************************************************
6445 * WSAGetServiceClassInfoA (WS2_32.42)
6447 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
6448 LPWSASERVICECLASSINFOA info )
6450 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
6451 len, info );
6452 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6453 return SOCKET_ERROR;
6456 /***********************************************************************
6457 * WSAGetServiceClassInfoW (WS2_32.43)
6459 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
6460 LPWSASERVICECLASSINFOW info )
6462 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
6463 len, info );
6464 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6465 return SOCKET_ERROR;
6468 /***********************************************************************
6469 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
6471 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
6473 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
6474 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6475 return SOCKET_ERROR;
6478 /***********************************************************************
6479 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
6481 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
6483 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
6484 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6485 return SOCKET_ERROR;
6488 /***********************************************************************
6489 * WSALookupServiceBeginA (WS2_32.59)
6491 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
6492 DWORD dwControlFlags,
6493 LPHANDLE lphLookup)
6495 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
6496 lphLookup);
6497 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6498 return SOCKET_ERROR;
6501 /***********************************************************************
6502 * WSALookupServiceBeginW (WS2_32.60)
6504 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
6505 DWORD dwControlFlags,
6506 LPHANDLE lphLookup)
6508 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
6509 lphLookup);
6510 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6511 return SOCKET_ERROR;
6514 /***********************************************************************
6515 * WSALookupServiceEnd (WS2_32.61)
6517 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
6519 FIXME("(%p) Stub!\n", lookup );
6520 return 0;
6523 /***********************************************************************
6524 * WSALookupServiceNextA (WS2_32.62)
6526 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
6528 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
6529 WSASetLastError(WSA_E_NO_MORE);
6530 return SOCKET_ERROR;
6533 /***********************************************************************
6534 * WSALookupServiceNextW (WS2_32.63)
6536 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
6538 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
6539 WSASetLastError(WSA_E_NO_MORE);
6540 return SOCKET_ERROR;
6543 /***********************************************************************
6544 * WSANtohl (WS2_32.64)
6546 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
6548 TRACE( "(0x%04lx 0x%08x %p)\n", s, netlong, lphostlong );
6550 if (!lphostlong) return WSAEFAULT;
6552 *lphostlong = ntohl( netlong );
6553 return 0;
6556 /***********************************************************************
6557 * WSANtohs (WS2_32.65)
6559 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
6561 TRACE( "(0x%04lx 0x%08x %p)\n", s, netshort, lphostshort );
6563 if (!lphostshort) return WSAEFAULT;
6565 *lphostshort = ntohs( netshort );
6566 return 0;
6569 /***********************************************************************
6570 * WSAProviderConfigChange (WS2_32.66)
6572 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
6573 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
6575 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
6576 return SOCKET_ERROR;
6579 /***********************************************************************
6580 * WSARecvDisconnect (WS2_32.68)
6582 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
6584 TRACE( "(0x%04lx %p)\n", s, disconnectdata );
6586 return WS_shutdown( s, 0 );
6589 /***********************************************************************
6590 * WSASetServiceA (WS2_32.76)
6592 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
6594 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
6595 return 0;
6598 /***********************************************************************
6599 * WSASetServiceW (WS2_32.77)
6601 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
6603 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
6604 return 0;
6607 /***********************************************************************
6608 * WSCEnableNSProvider (WS2_32.84)
6610 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
6612 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
6613 return 0;
6616 /***********************************************************************
6617 * WSCGetProviderPath (WS2_32.86)
6619 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
6621 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
6623 if (!errcode || !provider || !len) return WSAEFAULT;
6625 *errcode = WSAEINVAL;
6626 return SOCKET_ERROR;
6629 /***********************************************************************
6630 * WSCInstallNameSpace (WS2_32.87)
6632 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
6633 DWORD version, LPGUID provider )
6635 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
6636 namespace, version, debugstr_guid(provider) );
6637 return 0;
6640 /***********************************************************************
6641 * WSCUnInstallNameSpace (WS2_32.89)
6643 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
6645 FIXME("(%p) Stub!\n", lpProviderId);
6646 return NO_ERROR;
6649 /***********************************************************************
6650 * WSCWriteProviderOrder (WS2_32.91)
6652 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
6654 FIXME("(%p 0x%08x) Stub!\n", entry, number);
6655 return 0;
6658 /***********************************************************************
6659 * WSANSPIoctl (WS2_32.91)
6661 INT WINAPI WSANSPIoctl( HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer,
6662 DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer,
6663 LPDWORD lpcbBytesReturned, LPWSACOMPLETION lpCompletion )
6665 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup, dwControlCode,
6666 lpvInBuffer, cbInBuffer, lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpCompletion);
6667 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6668 return SOCKET_ERROR;