mscoree: Implement CLRRuntimeHost_ExecuteInDefaultAppDomain.
[wine/multimedia.git] / dlls / ws2_32 / socket.c
blobd3a45905f1ca276873f2151af635ecae98cfb14a
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
388 static const int ws_ipv6_map[][2] =
390 #ifdef IPV6_ADD_MEMBERSHIP
391 MAP_OPTION( IPV6_ADD_MEMBERSHIP ),
392 #endif
393 #ifdef IPV6_DROP_MEMBERSHIP
394 MAP_OPTION( IPV6_DROP_MEMBERSHIP ),
395 #endif
396 MAP_OPTION( IPV6_MULTICAST_IF ),
397 MAP_OPTION( IPV6_MULTICAST_HOPS ),
398 MAP_OPTION( IPV6_MULTICAST_LOOP ),
399 MAP_OPTION( IPV6_UNICAST_HOPS ),
400 MAP_OPTION( IPV6_V6ONLY ),
403 static const int ws_af_map[][2] =
405 MAP_OPTION( AF_UNSPEC ),
406 MAP_OPTION( AF_INET ),
407 MAP_OPTION( AF_INET6 ),
408 #ifdef HAVE_IPX
409 MAP_OPTION( AF_IPX ),
410 #endif
411 #ifdef AF_IRDA
412 MAP_OPTION( AF_IRDA ),
413 #endif
414 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
417 static const int ws_socktype_map[][2] =
419 MAP_OPTION( SOCK_DGRAM ),
420 MAP_OPTION( SOCK_STREAM ),
421 MAP_OPTION( SOCK_RAW ),
422 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
425 static const int ws_proto_map[][2] =
427 MAP_OPTION( IPPROTO_IP ),
428 MAP_OPTION( IPPROTO_TCP ),
429 MAP_OPTION( IPPROTO_UDP ),
430 MAP_OPTION( IPPROTO_ICMP ),
431 MAP_OPTION( IPPROTO_IGMP ),
432 MAP_OPTION( IPPROTO_RAW ),
433 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
436 static const int ws_aiflag_map[][2] =
438 MAP_OPTION( AI_PASSIVE ),
439 MAP_OPTION( AI_CANONNAME ),
440 MAP_OPTION( AI_NUMERICHOST ),
441 MAP_OPTION( AI_ADDRCONFIG ),
444 static const int ws_niflag_map[][2] =
446 MAP_OPTION( NI_NOFQDN ),
447 MAP_OPTION( NI_NUMERICHOST ),
448 MAP_OPTION( NI_NAMEREQD ),
449 MAP_OPTION( NI_NUMERICSERV ),
450 MAP_OPTION( NI_DGRAM ),
453 static const int ws_eai_map[][2] =
455 MAP_OPTION( EAI_AGAIN ),
456 MAP_OPTION( EAI_BADFLAGS ),
457 MAP_OPTION( EAI_FAIL ),
458 MAP_OPTION( EAI_FAMILY ),
459 MAP_OPTION( EAI_MEMORY ),
460 /* Note: EAI_NODATA is deprecated, but still
461 * used by Windows and Linux... We map the newer
462 * EAI_NONAME to EAI_NODATA for now until Windows
463 * changes too.
465 #ifdef EAI_NODATA
466 MAP_OPTION( EAI_NODATA ),
467 #endif
468 #ifdef EAI_NONAME
469 { WS_EAI_NODATA, EAI_NONAME },
470 #endif
472 MAP_OPTION( EAI_SERVICE ),
473 MAP_OPTION( EAI_SOCKTYPE ),
474 { 0, 0 }
477 static const char magic_loopback_addr[] = {127, 12, 34, 56};
479 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
480 static inline WSACMSGHDR *fill_control_message(int level, int type, WSACMSGHDR *current, ULONG *maxsize, void *data, int len)
482 ULONG msgsize = sizeof(WSACMSGHDR) + WSA_CMSG_ALIGN(len);
483 char *ptr = (char *) current + sizeof(WSACMSGHDR);
485 /* Make sure there is at least enough room for this entry */
486 if (msgsize > *maxsize)
487 return NULL;
488 *maxsize -= msgsize;
489 /* Fill in the entry */
490 current->cmsg_len = sizeof(WSACMSGHDR) + len;
491 current->cmsg_level = level;
492 current->cmsg_type = type;
493 memcpy(ptr, data, len);
494 /* Return the pointer to where next entry should go */
495 return (WSACMSGHDR *) (ptr + WSA_CMSG_ALIGN(len));
498 static inline int convert_control_headers(struct msghdr *hdr, WSABUF *control)
500 #ifdef IP_PKTINFO
501 WSACMSGHDR *cmsg_win = (WSACMSGHDR *) control->buf, *ptr;
502 ULONG ctlsize = control->len;
503 struct cmsghdr *cmsg_unix;
505 ptr = cmsg_win;
506 /* Loop over all the headers, converting as appropriate */
507 for (cmsg_unix = CMSG_FIRSTHDR(hdr); cmsg_unix != NULL; cmsg_unix = CMSG_NXTHDR(hdr, cmsg_unix))
509 switch(cmsg_unix->cmsg_level)
511 case IPPROTO_IP:
512 switch(cmsg_unix->cmsg_type)
514 case IP_PKTINFO:
516 /* Convert the Unix IP_PKTINFO structure to the Windows version */
517 struct in_pktinfo *data_unix = (struct in_pktinfo *) CMSG_DATA(cmsg_unix);
518 struct WS_in_pktinfo data_win;
520 memcpy(&data_win.ipi_addr,&data_unix->ipi_addr.s_addr,4); /* 4 bytes = 32 address bits */
521 data_win.ipi_ifindex = data_unix->ipi_ifindex;
522 ptr = fill_control_message(WS_IPPROTO_IP, WS_IP_PKTINFO, ptr, &ctlsize,
523 (void*)&data_win, sizeof(data_win));
524 if (!ptr) goto error;
525 } break;
526 default:
527 FIXME("Unhandled IPPROTO_IP message header type %d\n", cmsg_unix->cmsg_type);
528 break;
530 break;
531 default:
532 FIXME("Unhandled message header level %d\n", cmsg_unix->cmsg_level);
533 break;
537 error:
538 /* Set the length of the returned control headers */
539 control->len = (ptr == NULL ? 0 : (char*)ptr - (char*)cmsg_win);
540 return (ptr != NULL);
541 #else /* IP_PKTINFO */
542 control->len = 0;
543 return 1;
544 #endif /* IP_PKTINFO */
546 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
548 /* ----------------------------------- error handling */
550 static NTSTATUS sock_get_ntstatus( int err )
552 switch ( err )
554 case EBADF: return STATUS_INVALID_HANDLE;
555 case EBUSY: return STATUS_DEVICE_BUSY;
556 case EPERM:
557 case EACCES: return STATUS_ACCESS_DENIED;
558 case EFAULT: return STATUS_NO_MEMORY;
559 case EINVAL: return STATUS_INVALID_PARAMETER;
560 case ENFILE:
561 case EMFILE: return STATUS_TOO_MANY_OPENED_FILES;
562 case EWOULDBLOCK: return STATUS_CANT_WAIT;
563 case EINPROGRESS: return STATUS_PENDING;
564 case EALREADY: return STATUS_NETWORK_BUSY;
565 case ENOTSOCK: return STATUS_OBJECT_TYPE_MISMATCH;
566 case EDESTADDRREQ: return STATUS_INVALID_PARAMETER;
567 case EMSGSIZE: return STATUS_BUFFER_OVERFLOW;
568 case EPROTONOSUPPORT:
569 case ESOCKTNOSUPPORT:
570 case EPFNOSUPPORT:
571 case EAFNOSUPPORT:
572 case EPROTOTYPE: return STATUS_NOT_SUPPORTED;
573 case ENOPROTOOPT: return STATUS_INVALID_PARAMETER;
574 case EOPNOTSUPP: return STATUS_NOT_SUPPORTED;
575 case EADDRINUSE: return STATUS_ADDRESS_ALREADY_ASSOCIATED;
576 case EADDRNOTAVAIL: return STATUS_INVALID_PARAMETER;
577 case ECONNREFUSED: return STATUS_CONNECTION_REFUSED;
578 case ESHUTDOWN: return STATUS_PIPE_DISCONNECTED;
579 case ENOTCONN: return STATUS_CONNECTION_DISCONNECTED;
580 case ETIMEDOUT: return STATUS_IO_TIMEOUT;
581 case ENETUNREACH: return STATUS_NETWORK_UNREACHABLE;
582 case ENETDOWN: return STATUS_NETWORK_BUSY;
583 case EPIPE:
584 case ECONNRESET: return STATUS_CONNECTION_RESET;
585 case ECONNABORTED: return STATUS_CONNECTION_ABORTED;
587 case 0: return STATUS_SUCCESS;
588 default:
589 WARN("Unknown errno %d!\n", err);
590 return STATUS_UNSUCCESSFUL;
594 static UINT sock_get_error( int err )
596 switch(err)
598 case EINTR: return WSAEINTR;
599 case EBADF: return WSAEBADF;
600 case EPERM:
601 case EACCES: return WSAEACCES;
602 case EFAULT: return WSAEFAULT;
603 case EINVAL: return WSAEINVAL;
604 case EMFILE: return WSAEMFILE;
605 case EWOULDBLOCK: return WSAEWOULDBLOCK;
606 case EINPROGRESS: return WSAEINPROGRESS;
607 case EALREADY: return WSAEALREADY;
608 case ENOTSOCK: return WSAENOTSOCK;
609 case EDESTADDRREQ: return WSAEDESTADDRREQ;
610 case EMSGSIZE: return WSAEMSGSIZE;
611 case EPROTOTYPE: return WSAEPROTOTYPE;
612 case ENOPROTOOPT: return WSAENOPROTOOPT;
613 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
614 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
615 case EOPNOTSUPP: return WSAEOPNOTSUPP;
616 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
617 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
618 case EADDRINUSE: return WSAEADDRINUSE;
619 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
620 case ENETDOWN: return WSAENETDOWN;
621 case ENETUNREACH: return WSAENETUNREACH;
622 case ENETRESET: return WSAENETRESET;
623 case ECONNABORTED: return WSAECONNABORTED;
624 case EPIPE:
625 case ECONNRESET: return WSAECONNRESET;
626 case ENOBUFS: return WSAENOBUFS;
627 case EISCONN: return WSAEISCONN;
628 case ENOTCONN: return WSAENOTCONN;
629 case ESHUTDOWN: return WSAESHUTDOWN;
630 case ETOOMANYREFS: return WSAETOOMANYREFS;
631 case ETIMEDOUT: return WSAETIMEDOUT;
632 case ECONNREFUSED: return WSAECONNREFUSED;
633 case ELOOP: return WSAELOOP;
634 case ENAMETOOLONG: return WSAENAMETOOLONG;
635 case EHOSTDOWN: return WSAEHOSTDOWN;
636 case EHOSTUNREACH: return WSAEHOSTUNREACH;
637 case ENOTEMPTY: return WSAENOTEMPTY;
638 #ifdef EPROCLIM
639 case EPROCLIM: return WSAEPROCLIM;
640 #endif
641 #ifdef EUSERS
642 case EUSERS: return WSAEUSERS;
643 #endif
644 #ifdef EDQUOT
645 case EDQUOT: return WSAEDQUOT;
646 #endif
647 #ifdef ESTALE
648 case ESTALE: return WSAESTALE;
649 #endif
650 #ifdef EREMOTE
651 case EREMOTE: return WSAEREMOTE;
652 #endif
654 /* just in case we ever get here and there are no problems */
655 case 0: return 0;
656 default:
657 WARN("Unknown errno %d!\n", err);
658 return WSAEOPNOTSUPP;
662 static UINT wsaErrno(void)
664 int loc_errno = errno;
665 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
667 return sock_get_error( loc_errno );
670 /* most ws2 overlapped functions return an ntstatus-based error code */
671 static NTSTATUS wsaErrStatus(void)
673 int loc_errno = errno;
674 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
676 return sock_get_ntstatus(loc_errno);
679 static UINT wsaHerrno(int loc_errno)
681 WARN("h_errno %d.\n", loc_errno);
683 switch(loc_errno)
685 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
686 case TRY_AGAIN: return WSATRY_AGAIN;
687 case NO_RECOVERY: return WSANO_RECOVERY;
688 case NO_DATA: return WSANO_DATA;
689 case ENOBUFS: return WSAENOBUFS;
691 case 0: return 0;
692 default:
693 WARN("Unknown h_errno %d!\n", loc_errno);
694 return WSAEOPNOTSUPP;
698 static inline DWORD NtStatusToWSAError( const DWORD status )
700 /* We only need to cover the status codes set by server async request handling */
701 DWORD wserr;
702 switch ( status )
704 case STATUS_SUCCESS: wserr = 0; break;
705 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
706 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
707 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
708 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
709 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
710 case STATUS_NETWORK_BUSY: wserr = WSAEALREADY; break;
711 case STATUS_NETWORK_UNREACHABLE: wserr = WSAENETUNREACH; break;
712 case STATUS_CONNECTION_REFUSED: wserr = WSAECONNREFUSED; break;
713 case STATUS_CONNECTION_DISCONNECTED: wserr = WSAENOTCONN; break;
714 case STATUS_CONNECTION_RESET: wserr = WSAECONNRESET; break;
715 case STATUS_CONNECTION_ABORTED: wserr = WSAECONNABORTED; break;
716 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
717 case STATUS_ADDRESS_ALREADY_ASSOCIATED: wserr = WSAEADDRINUSE; break;
718 case STATUS_IO_TIMEOUT:
719 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
720 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
721 case STATUS_ACCESS_DENIED: wserr = WSAEACCES; break;
722 case STATUS_TOO_MANY_OPENED_FILES: wserr = WSAEMFILE; break;
723 case STATUS_CANT_WAIT: wserr = WSAEWOULDBLOCK; break;
724 case STATUS_BUFFER_OVERFLOW: wserr = WSAEMSGSIZE; break;
725 case STATUS_NOT_SUPPORTED: wserr = WSAEOPNOTSUPP; break;
726 case STATUS_HOST_UNREACHABLE: wserr = WSAEHOSTUNREACH; break;
728 default:
729 wserr = RtlNtStatusToDosError( status );
730 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
732 return wserr;
735 /* set last error code from NT status without mapping WSA errors */
736 static inline unsigned int set_error( unsigned int err )
738 if (err)
740 err = NtStatusToWSAError( err );
741 SetLastError( err );
743 return err;
746 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
748 int fd;
749 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
750 return -1;
751 return fd;
754 static inline void release_sock_fd( SOCKET s, int fd )
756 wine_server_release_fd( SOCKET2HANDLE(s), fd );
759 static void _enable_event( HANDLE s, unsigned int event,
760 unsigned int sstate, unsigned int cstate )
762 SERVER_START_REQ( enable_socket_event )
764 req->handle = wine_server_obj_handle( s );
765 req->mask = event;
766 req->sstate = sstate;
767 req->cstate = cstate;
768 wine_server_call( req );
770 SERVER_END_REQ;
773 static int _is_blocking(SOCKET s)
775 int ret;
776 SERVER_START_REQ( get_socket_event )
778 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
779 req->service = FALSE;
780 req->c_event = 0;
781 wine_server_call( req );
782 ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
784 SERVER_END_REQ;
785 return ret;
788 static unsigned int _get_sock_mask(SOCKET s)
790 unsigned int ret;
791 SERVER_START_REQ( get_socket_event )
793 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
794 req->service = FALSE;
795 req->c_event = 0;
796 wine_server_call( req );
797 ret = reply->mask;
799 SERVER_END_REQ;
800 return ret;
803 static void _sync_sock_state(SOCKET s)
805 /* do a dummy wineserver request in order to let
806 the wineserver run through its select loop once */
807 (void)_is_blocking(s);
810 static int _get_sock_error(SOCKET s, unsigned int bit)
812 int events[FD_MAX_EVENTS];
814 SERVER_START_REQ( get_socket_event )
816 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
817 req->service = FALSE;
818 req->c_event = 0;
819 wine_server_set_reply( req, events, sizeof(events) );
820 wine_server_call( req );
822 SERVER_END_REQ;
823 return events[bit];
826 static struct per_thread_data *get_per_thread_data(void)
828 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
829 /* lazy initialization */
830 if (!ptb)
832 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
833 NtCurrentTeb()->WinSockData = ptb;
835 return ptb;
838 static void free_per_thread_data(void)
840 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
842 if (!ptb) return;
844 /* delete scratch buffers */
845 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
846 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
847 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
848 ptb->he_buffer = NULL;
849 ptb->se_buffer = NULL;
850 ptb->pe_buffer = NULL;
852 HeapFree( GetProcessHeap(), 0, ptb );
853 NtCurrentTeb()->WinSockData = NULL;
856 /***********************************************************************
857 * DllMain (WS2_32.init)
859 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
861 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
862 switch (fdwReason) {
863 case DLL_PROCESS_ATTACH:
864 break;
865 case DLL_PROCESS_DETACH:
866 free_per_thread_data();
867 DeleteCriticalSection(&csWSgetXXXbyYYY);
868 num_startup = 0;
869 break;
870 case DLL_THREAD_DETACH:
871 free_per_thread_data();
872 break;
874 return TRUE;
877 /***********************************************************************
878 * convert_sockopt()
880 * Converts socket flags from Windows format.
881 * Return 1 if converted, 0 if not (error).
883 static int convert_sockopt(INT *level, INT *optname)
885 unsigned int i;
886 switch (*level)
888 case WS_SOL_SOCKET:
889 *level = SOL_SOCKET;
890 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
891 if( ws_sock_map[i][0] == *optname )
893 *optname = ws_sock_map[i][1];
894 return 1;
897 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
898 break;
899 case WS_IPPROTO_TCP:
900 *level = IPPROTO_TCP;
901 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
902 if ( ws_tcp_map[i][0] == *optname )
904 *optname = ws_tcp_map[i][1];
905 return 1;
908 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
909 break;
910 case WS_IPPROTO_IP:
911 *level = IPPROTO_IP;
912 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
913 if (ws_ip_map[i][0] == *optname )
915 *optname = ws_ip_map[i][1];
916 return 1;
919 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
920 break;
921 case WS_IPPROTO_IPV6:
922 *level = IPPROTO_IPV6;
923 for(i=0; i<sizeof(ws_ipv6_map)/sizeof(ws_ipv6_map[0]); i++) {
924 if (ws_ipv6_map[i][0] == *optname )
926 *optname = ws_ipv6_map[i][1];
927 return 1;
930 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname);
931 break;
932 default: FIXME("Unimplemented or unknown socket level\n");
934 return 0;
937 /* ----------------------------------- Per-thread info (or per-process?) */
939 static char *strdup_lower(const char *str)
941 int i;
942 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
944 if (ret)
946 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
947 ret[i] = 0;
949 else SetLastError(WSAENOBUFS);
950 return ret;
953 static inline int sock_error_p(int s)
955 unsigned int optval, optlen;
957 optlen = sizeof(optval);
958 getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
959 if (optval) WARN("\t[%i] error: %d\n", s, optval);
960 return optval != 0;
963 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
964 * from an fd and return the value converted to milli seconds
965 * or -1 if there is an infinite time out */
966 static inline int get_rcvsnd_timeo( int fd, int optname)
968 struct timeval tv;
969 unsigned int len = sizeof(tv);
970 int ret = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
971 if( ret >= 0)
972 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
973 if( ret <= 0 ) /* tv == {0,0} means infinite time out */
974 return -1;
975 return ret;
978 /* macro wrappers for portability */
979 #ifdef SO_RCVTIMEO
980 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
981 #else
982 #define GET_RCVTIMEO(fd) (-1)
983 #endif
985 #ifdef SO_SNDTIMEO
986 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
987 #else
988 #define GET_SNDTIMEO(fd) (-1)
989 #endif
991 /* utility: given an fd, will block until one of the events occurs */
992 static inline int do_block( int fd, int events, int timeout )
994 struct pollfd pfd;
995 int ret;
997 pfd.fd = fd;
998 pfd.events = events;
1000 while ((ret = poll(&pfd, 1, timeout)) < 0)
1002 if (errno != EINTR)
1003 return -1;
1005 if( ret == 0 )
1006 return 0;
1007 return pfd.revents;
1010 static int
1011 convert_af_w2u(int windowsaf) {
1012 unsigned int i;
1014 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1015 if (ws_af_map[i][0] == windowsaf)
1016 return ws_af_map[i][1];
1017 FIXME("unhandled Windows address family %d\n", windowsaf);
1018 return -1;
1021 static int
1022 convert_af_u2w(int unixaf) {
1023 unsigned int i;
1025 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1026 if (ws_af_map[i][1] == unixaf)
1027 return ws_af_map[i][0];
1028 FIXME("unhandled UNIX address family %d\n", unixaf);
1029 return -1;
1032 static int
1033 convert_proto_w2u(int windowsproto) {
1034 unsigned int i;
1036 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1037 if (ws_proto_map[i][0] == windowsproto)
1038 return ws_proto_map[i][1];
1039 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
1040 return -1;
1043 static int
1044 convert_proto_u2w(int unixproto) {
1045 unsigned int i;
1047 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1048 if (ws_proto_map[i][1] == unixproto)
1049 return ws_proto_map[i][0];
1050 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
1051 return -1;
1054 static int
1055 convert_socktype_w2u(int windowssocktype) {
1056 unsigned int i;
1058 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1059 if (ws_socktype_map[i][0] == windowssocktype)
1060 return ws_socktype_map[i][1];
1061 FIXME("unhandled Windows socket type %d\n", windowssocktype);
1062 return -1;
1065 static int
1066 convert_socktype_u2w(int unixsocktype) {
1067 unsigned int i;
1069 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1070 if (ws_socktype_map[i][1] == unixsocktype)
1071 return ws_socktype_map[i][0];
1072 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
1073 return -1;
1076 /* ----------------------------------- API -----
1078 * Init / cleanup / error checking.
1081 /***********************************************************************
1082 * WSAStartup (WS2_32.115)
1084 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
1086 TRACE("verReq=%x\n", wVersionRequested);
1088 if (LOBYTE(wVersionRequested) < 1)
1089 return WSAVERNOTSUPPORTED;
1091 if (!lpWSAData) return WSAEINVAL;
1093 num_startup++;
1095 /* that's the whole of the negotiation for now */
1096 lpWSAData->wVersion = wVersionRequested;
1097 /* return winsock information */
1098 lpWSAData->wHighVersion = 0x0202;
1099 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
1100 strcpy(lpWSAData->szSystemStatus, "Running" );
1101 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
1102 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
1103 /* don't do anything with lpWSAData->lpVendorInfo */
1104 /* (some apps don't allocate the space for this field) */
1106 TRACE("succeeded\n");
1107 return 0;
1111 /***********************************************************************
1112 * WSACleanup (WS2_32.116)
1114 INT WINAPI WSACleanup(void)
1116 if (num_startup) {
1117 num_startup--;
1118 return 0;
1120 SetLastError(WSANOTINITIALISED);
1121 return SOCKET_ERROR;
1125 /***********************************************************************
1126 * WSAGetLastError (WS2_32.111)
1128 INT WINAPI WSAGetLastError(void)
1130 return GetLastError();
1133 /***********************************************************************
1134 * WSASetLastError (WS2_32.112)
1136 void WINAPI WSASetLastError(INT iError) {
1137 SetLastError(iError);
1140 static struct WS_hostent *check_buffer_he(int size)
1142 struct per_thread_data * ptb = get_per_thread_data();
1143 if (ptb->he_buffer)
1145 if (ptb->he_len >= size ) return ptb->he_buffer;
1146 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1148 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
1149 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
1150 return ptb->he_buffer;
1153 static struct WS_servent *check_buffer_se(int size)
1155 struct per_thread_data * ptb = get_per_thread_data();
1156 if (ptb->se_buffer)
1158 if (ptb->se_len >= size ) return ptb->se_buffer;
1159 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1161 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
1162 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
1163 return ptb->se_buffer;
1166 static struct WS_protoent *check_buffer_pe(int size)
1168 struct per_thread_data * ptb = get_per_thread_data();
1169 if (ptb->pe_buffer)
1171 if (ptb->pe_len >= size ) return ptb->pe_buffer;
1172 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1174 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
1175 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
1176 return ptb->pe_buffer;
1179 /* ----------------------------------- i/o APIs */
1181 static inline BOOL supported_pf(int pf)
1183 switch (pf)
1185 case WS_AF_INET:
1186 case WS_AF_INET6:
1187 return TRUE;
1188 #ifdef HAVE_IPX
1189 case WS_AF_IPX:
1190 return TRUE;
1191 #endif
1192 #ifdef HAVE_IRDA
1193 case WS_AF_IRDA:
1194 return TRUE;
1195 #endif
1196 default:
1197 return FALSE;
1202 /**********************************************************************/
1204 /* Returns the length of the converted address if successful, 0 if it was too small to
1205 * start with.
1207 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
1208 union generic_unix_sockaddr *uaddr)
1210 unsigned int uaddrlen = 0;
1212 switch (wsaddr->sa_family)
1214 #ifdef HAVE_IPX
1215 case WS_AF_IPX:
1217 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
1218 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
1220 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
1221 return 0;
1223 uaddrlen = sizeof(struct sockaddr_ipx);
1224 memset( uaddr, 0, uaddrlen );
1225 uipx->sipx_family=AF_IPX;
1226 uipx->sipx_port=wsipx->sa_socket;
1227 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1228 * in one go
1230 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
1231 #ifdef IPX_FRAME_NONE
1232 uipx->sipx_type=IPX_FRAME_NONE;
1233 #endif
1234 break;
1236 #endif
1237 case WS_AF_INET6: {
1238 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
1239 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
1241 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1242 * scope_id, one without.
1244 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
1245 uaddrlen = sizeof(struct sockaddr_in6);
1246 memset( uaddr, 0, uaddrlen );
1247 uin6->sin6_family = AF_INET6;
1248 uin6->sin6_port = win6->sin6_port;
1249 uin6->sin6_flowinfo = win6->sin6_flowinfo;
1250 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1251 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
1252 #endif
1253 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
1254 break;
1256 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
1257 return 0;
1259 case WS_AF_INET: {
1260 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
1261 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
1263 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
1264 return 0;
1265 uaddrlen = sizeof(struct sockaddr_in);
1266 memset( uaddr, 0, uaddrlen );
1267 uin->sin_family = AF_INET;
1268 uin->sin_port = win->sin_port;
1269 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
1270 break;
1272 #ifdef HAVE_IRDA
1273 case WS_AF_IRDA: {
1274 struct sockaddr_irda *uin = (struct sockaddr_irda *)uaddr;
1275 const SOCKADDR_IRDA *win = (const SOCKADDR_IRDA *)wsaddr;
1277 if (wsaddrlen < sizeof(SOCKADDR_IRDA))
1278 return 0;
1279 uaddrlen = sizeof(struct sockaddr_irda);
1280 memset( uaddr, 0, uaddrlen );
1281 uin->sir_family = AF_IRDA;
1282 if (!strncmp( win->irdaServiceName, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1284 unsigned int lsap_sel = 0;
1286 sscanf( win->irdaServiceName, "LSAP-SEL%u", &lsap_sel );
1287 uin->sir_lsap_sel = lsap_sel;
1289 else
1291 uin->sir_lsap_sel = LSAP_ANY;
1292 memcpy( uin->sir_name, win->irdaServiceName, 25 );
1294 memcpy( &uin->sir_addr, win->irdaDeviceID, sizeof(uin->sir_addr) );
1295 break;
1297 #endif
1298 case WS_AF_UNSPEC: {
1299 /* Try to determine the needed space by the passed windows sockaddr space */
1300 switch (wsaddrlen) {
1301 default: /* likely a ipv4 address */
1302 case sizeof(struct WS_sockaddr_in):
1303 uaddrlen = sizeof(struct sockaddr_in);
1304 break;
1305 #ifdef HAVE_IPX
1306 case sizeof(struct WS_sockaddr_ipx):
1307 uaddrlen = sizeof(struct sockaddr_ipx);
1308 break;
1309 #endif
1310 #ifdef HAVE_IRDA
1311 case sizeof(SOCKADDR_IRDA):
1312 uaddrlen = sizeof(struct sockaddr_irda);
1313 break;
1314 #endif
1315 case sizeof(struct WS_sockaddr_in6):
1316 case sizeof(struct WS_sockaddr_in6_old):
1317 uaddrlen = sizeof(struct sockaddr_in6);
1318 break;
1320 memset( uaddr, 0, uaddrlen );
1321 break;
1323 default:
1324 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
1325 return 0;
1327 return uaddrlen;
1330 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
1332 switch (uaddr->sa_family)
1334 #ifdef HAVE_IPX
1335 case AF_IPX:
1336 FIXME("don't know how to tell if IPX socket is bound, assuming it is!\n");
1337 return TRUE;
1338 #endif
1339 case AF_INET6:
1341 static const struct sockaddr_in6 emptyAddr;
1342 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
1343 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
1345 case AF_INET:
1347 static const struct sockaddr_in emptyAddr;
1348 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
1349 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
1351 case AF_UNSPEC:
1352 return FALSE;
1353 default:
1354 FIXME("unknown address family %d\n", uaddr->sa_family);
1355 return TRUE;
1359 /* Returns 0 if successful, -1 if the buffer is too small */
1360 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
1362 int res;
1364 switch(uaddr->sa_family)
1366 #ifdef HAVE_IPX
1367 case AF_IPX:
1369 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
1370 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
1372 res=-1;
1373 switch (*wsaddrlen) /* how much can we copy? */
1375 default:
1376 res=0; /* enough */
1377 *wsaddrlen = sizeof(*wsipx);
1378 wsipx->sa_socket=uipx->sipx_port;
1379 /* fall through */
1380 case 13:
1381 case 12:
1382 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
1383 /* fall through */
1384 case 11:
1385 case 10:
1386 case 9:
1387 case 8:
1388 case 7:
1389 case 6:
1390 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1391 /* fall through */
1392 case 5:
1393 case 4:
1394 case 3:
1395 case 2:
1396 wsipx->sa_family=WS_AF_IPX;
1397 /* fall through */
1398 case 1:
1399 case 0:
1400 /* way too small */
1401 break;
1404 break;
1405 #endif
1406 #ifdef HAVE_IRDA
1407 case AF_IRDA: {
1408 const struct sockaddr_irda *uin = (const struct sockaddr_irda *)uaddr;
1409 SOCKADDR_IRDA *win = (SOCKADDR_IRDA *)wsaddr;
1411 if (*wsaddrlen < sizeof(SOCKADDR_IRDA))
1412 return -1;
1413 win->irdaAddressFamily = WS_AF_IRDA;
1414 memcpy( win->irdaDeviceID, &uin->sir_addr, sizeof(win->irdaDeviceID) );
1415 if (uin->sir_lsap_sel != LSAP_ANY)
1416 sprintf( win->irdaServiceName, "LSAP-SEL%u", uin->sir_lsap_sel );
1417 else
1418 memcpy( win->irdaServiceName, uin->sir_name,
1419 sizeof(win->irdaServiceName) );
1420 return 0;
1422 #endif
1423 case AF_INET6: {
1424 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1425 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1427 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1428 return -1;
1429 win6old->sin6_family = WS_AF_INET6;
1430 win6old->sin6_port = uin6->sin6_port;
1431 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1432 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1433 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1434 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1435 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1436 win6->sin6_scope_id = uin6->sin6_scope_id;
1437 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1439 else
1440 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1441 #else
1442 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1443 #endif
1444 return 0;
1446 case AF_INET: {
1447 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1448 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1450 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1451 return -1;
1452 win->sin_family = WS_AF_INET;
1453 win->sin_port = uin->sin_port;
1454 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1455 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1456 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1457 return 0;
1459 case AF_UNSPEC: {
1460 memset(wsaddr,0,*wsaddrlen);
1461 return 0;
1463 default:
1464 FIXME("Unknown address family %d\n", uaddr->sa_family);
1465 return -1;
1467 return res;
1470 /**************************************************************************
1471 * Functions for handling overlapped I/O
1472 **************************************************************************/
1474 /* user APC called upon async completion */
1475 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1477 ws2_async *wsa = arg;
1479 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
1480 iosb->Information, wsa->user_overlapped,
1481 wsa->flags );
1482 HeapFree( GetProcessHeap(), 0, wsa );
1485 /***********************************************************************
1486 * WS2_recv (INTERNAL)
1488 * Workhorse for both synchronous and asynchronous recv() operations.
1490 static int WS2_recv( int fd, struct ws2_async *wsa )
1492 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1493 char pktbuf[512];
1494 #endif
1495 struct msghdr hdr;
1496 union generic_unix_sockaddr unix_sockaddr;
1497 int n;
1499 hdr.msg_name = NULL;
1501 if (wsa->addr)
1503 hdr.msg_namelen = sizeof(unix_sockaddr);
1504 hdr.msg_name = &unix_sockaddr;
1506 else
1507 hdr.msg_namelen = 0;
1509 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1510 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1511 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1512 hdr.msg_accrights = NULL;
1513 hdr.msg_accrightslen = 0;
1514 #else
1515 hdr.msg_control = pktbuf;
1516 hdr.msg_controllen = sizeof(pktbuf);
1517 hdr.msg_flags = 0;
1518 #endif
1520 if ( (n = recvmsg(fd, &hdr, wsa->flags)) == -1 )
1521 return -1;
1523 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1524 if (wsa->control)
1526 ERR("Message control headers cannot be properly supported on this system.\n");
1527 wsa->control->len = 0;
1529 #else
1530 if (wsa->control && !convert_control_headers(&hdr, wsa->control))
1532 WARN("Application passed insufficient room for control headers.\n");
1533 *wsa->lpFlags |= WS_MSG_CTRUNC;
1534 errno = EMSGSIZE;
1535 return -1;
1537 #endif
1539 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
1540 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
1542 * quoting linux 2.6 net/ipv4/tcp.c:
1543 * "According to UNIX98, msg_name/msg_namelen are ignored
1544 * on connected socket. I was just happy when found this 8) --ANK"
1546 * likewise MSDN says that lpFrom and lpFromlen are ignored for
1547 * connection-oriented sockets, so don't try to update lpFrom.
1549 if (wsa->addr && hdr.msg_namelen)
1550 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
1552 return n;
1555 /***********************************************************************
1556 * WS2_async_recv (INTERNAL)
1558 * Handler for overlapped recv() operations.
1560 static NTSTATUS WS2_async_recv( void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1562 ws2_async* wsa = user;
1563 int result = 0, fd;
1565 switch (status)
1567 case STATUS_ALERTED:
1568 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
1569 break;
1571 result = WS2_recv( fd, wsa );
1572 wine_server_release_fd( wsa->hSocket, fd );
1573 if (result >= 0)
1575 status = STATUS_SUCCESS;
1576 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1578 else
1580 if (errno == EINTR || errno == EAGAIN)
1582 status = STATUS_PENDING;
1583 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1585 else
1587 result = 0;
1588 status = wsaErrStatus();
1591 break;
1593 if (status != STATUS_PENDING)
1595 iosb->u.Status = status;
1596 iosb->Information = result;
1597 *apc = ws2_async_apc;
1599 return status;
1602 /* user APC called upon async accept completion */
1603 static void WINAPI ws2_async_accept_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1605 struct ws2_accept_async *wsa = arg;
1607 HeapFree( GetProcessHeap(), 0, wsa->read );
1608 HeapFree( GetProcessHeap(), 0, wsa );
1611 /***********************************************************************
1612 * WS2_async_accept_recv (INTERNAL)
1614 * This function is used to finish the read part of an accept request. It is
1615 * needed to place the completion on the correct socket (listener).
1617 static NTSTATUS WS2_async_accept_recv( void *arg, IO_STATUS_BLOCK *iosb, NTSTATUS status, void **apc )
1619 void *junk;
1620 struct ws2_accept_async *wsa = arg;
1622 status = WS2_async_recv( wsa->read, iosb, status, &junk );
1623 if (status == STATUS_PENDING)
1624 return status;
1626 if (wsa->user_overlapped->hEvent)
1627 SetEvent(wsa->user_overlapped->hEvent);
1628 if (wsa->cvalue)
1629 WS_AddCompletion( HANDLE2SOCKET(wsa->listen_socket), wsa->cvalue, iosb->u.Status, iosb->Information );
1631 *apc = ws2_async_accept_apc;
1632 return status;
1635 /***********************************************************************
1636 * WS2_async_accept (INTERNAL)
1638 * This is the function called to satisfy the AcceptEx callback
1640 static NTSTATUS WS2_async_accept( void *arg, IO_STATUS_BLOCK *iosb, NTSTATUS status, void **apc )
1642 struct ws2_accept_async *wsa = arg;
1643 int len;
1644 char *addr;
1646 TRACE("status: 0x%x listen: %p, accept: %p\n", status, wsa->listen_socket, wsa->accept_socket);
1648 if (status == STATUS_ALERTED)
1650 SERVER_START_REQ( accept_into_socket )
1652 req->lhandle = wine_server_obj_handle( wsa->listen_socket );
1653 req->ahandle = wine_server_obj_handle( wsa->accept_socket );
1654 status = wine_server_call( req );
1656 SERVER_END_REQ;
1658 if (status == STATUS_CANT_WAIT)
1659 return STATUS_PENDING;
1661 if (status == STATUS_INVALID_HANDLE)
1663 FIXME("AcceptEx accepting socket closed but request was not cancelled\n");
1664 status = STATUS_CANCELLED;
1667 else if (status == STATUS_HANDLES_CLOSED)
1668 status = STATUS_CANCELLED; /* strange windows behavior */
1670 if (status != STATUS_SUCCESS)
1671 goto finish;
1673 /* WS2 Spec says size param is extra 16 bytes long...what do we put in it? */
1674 addr = ((char *)wsa->buf) + wsa->data_len;
1675 len = wsa->local_len - sizeof(int);
1676 WS_getsockname(HANDLE2SOCKET(wsa->accept_socket),
1677 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
1678 *(int *)addr = len;
1680 addr += wsa->local_len;
1681 len = wsa->remote_len - sizeof(int);
1682 WS_getpeername(HANDLE2SOCKET(wsa->accept_socket),
1683 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
1684 *(int *)addr = len;
1686 if (!wsa->read)
1687 goto finish;
1689 SERVER_START_REQ( register_async )
1691 req->type = ASYNC_TYPE_READ;
1692 req->async.handle = wine_server_obj_handle( wsa->accept_socket );
1693 req->async.callback = wine_server_client_ptr( WS2_async_accept_recv );
1694 req->async.iosb = wine_server_client_ptr( iosb );
1695 req->async.arg = wine_server_client_ptr( wsa );
1696 status = wine_server_call( req );
1698 SERVER_END_REQ;
1700 if (status != STATUS_PENDING)
1701 goto finish;
1703 return STATUS_SUCCESS;
1705 finish:
1706 iosb->u.Status = status;
1707 iosb->Information = 0;
1709 if (wsa->user_overlapped->hEvent)
1710 SetEvent(wsa->user_overlapped->hEvent);
1711 if (wsa->cvalue)
1712 WS_AddCompletion( HANDLE2SOCKET(wsa->listen_socket), wsa->cvalue, iosb->u.Status, iosb->Information );
1714 *apc = ws2_async_accept_apc;
1715 return status;
1718 /***********************************************************************
1719 * WS2_send (INTERNAL)
1721 * Workhorse for both synchronous and asynchronous send() operations.
1723 static int WS2_send( int fd, struct ws2_async *wsa )
1725 struct msghdr hdr;
1726 union generic_unix_sockaddr unix_addr;
1727 int n, ret;
1729 hdr.msg_name = NULL;
1730 hdr.msg_namelen = 0;
1732 if (wsa->addr)
1734 hdr.msg_name = &unix_addr;
1735 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
1736 if ( !hdr.msg_namelen )
1738 errno = EFAULT;
1739 return -1;
1742 #if defined(HAVE_IPX) && defined(SOL_IPX)
1743 if(wsa->addr->sa_family == WS_AF_IPX)
1745 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
1746 int val=0;
1747 unsigned int len=sizeof(int);
1749 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
1750 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
1751 * the packet type and then we can retrieve it using getsockopt. After that we can set the
1752 * ipx type in the sockaddr_opx structure with the stored value.
1754 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
1755 uipx->sipx_type = val;
1757 #endif
1760 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1761 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1762 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1763 hdr.msg_accrights = NULL;
1764 hdr.msg_accrightslen = 0;
1765 #else
1766 hdr.msg_control = NULL;
1767 hdr.msg_controllen = 0;
1768 hdr.msg_flags = 0;
1769 #endif
1771 ret = sendmsg(fd, &hdr, wsa->flags);
1772 if (ret >= 0)
1774 n = ret;
1775 while (wsa->first_iovec < wsa->n_iovecs && wsa->iovec[wsa->first_iovec].iov_len <= n)
1776 n -= wsa->iovec[wsa->first_iovec++].iov_len;
1777 if (wsa->first_iovec < wsa->n_iovecs)
1779 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
1780 wsa->iovec[wsa->first_iovec].iov_len -= n;
1783 return ret;
1786 /***********************************************************************
1787 * WS2_async_send (INTERNAL)
1789 * Handler for overlapped send() operations.
1791 static NTSTATUS WS2_async_send(void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1793 ws2_async* wsa = user;
1794 int result = 0, fd;
1796 switch (status)
1798 case STATUS_ALERTED:
1799 if ( wsa->n_iovecs <= wsa->first_iovec )
1801 /* Nothing to do */
1802 status = STATUS_SUCCESS;
1803 break;
1805 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
1806 break;
1808 /* check to see if the data is ready (non-blocking) */
1809 result = WS2_send( fd, wsa );
1810 wine_server_release_fd( wsa->hSocket, fd );
1812 if (result >= 0)
1814 if (wsa->first_iovec < wsa->n_iovecs)
1815 status = STATUS_PENDING;
1816 else
1817 status = STATUS_SUCCESS;
1819 iosb->Information += result;
1821 else if (errno == EINTR || errno == EAGAIN)
1823 status = STATUS_PENDING;
1825 else
1827 status = wsaErrStatus();
1829 break;
1831 if (status != STATUS_PENDING)
1833 iosb->u.Status = status;
1834 *apc = ws2_async_apc;
1836 return status;
1839 /***********************************************************************
1840 * WS2_async_shutdown (INTERNAL)
1842 * Handler for shutdown() operations on overlapped sockets.
1844 static NTSTATUS WS2_async_shutdown( void* user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc )
1846 ws2_async* wsa = user;
1847 int fd, err = 1;
1849 switch (status)
1851 case STATUS_ALERTED:
1852 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
1853 break;
1855 switch ( wsa->type )
1857 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
1858 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
1860 status = err ? wsaErrStatus() : STATUS_SUCCESS;
1861 wine_server_release_fd( wsa->hSocket, fd );
1862 break;
1864 iosb->u.Status = status;
1865 iosb->Information = 0;
1866 *apc = ws2_async_apc;
1867 return status;
1870 /***********************************************************************
1871 * WS2_register_async_shutdown (INTERNAL)
1873 * Helper function for WS_shutdown() on overlapped sockets.
1875 static int WS2_register_async_shutdown( SOCKET s, int type )
1877 struct ws2_async *wsa;
1878 NTSTATUS status;
1880 TRACE("s %ld type %d\n", s, type);
1882 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
1883 if ( !wsa )
1884 return WSAEFAULT;
1886 wsa->hSocket = SOCKET2HANDLE(s);
1887 wsa->type = type;
1888 wsa->completion_func = NULL;
1890 SERVER_START_REQ( register_async )
1892 req->type = type;
1893 req->async.handle = wine_server_obj_handle( wsa->hSocket );
1894 req->async.callback = wine_server_client_ptr( WS2_async_shutdown );
1895 req->async.iosb = wine_server_client_ptr( &wsa->local_iosb );
1896 req->async.arg = wine_server_client_ptr( wsa );
1897 req->async.cvalue = 0;
1898 status = wine_server_call( req );
1900 SERVER_END_REQ;
1902 if (status != STATUS_PENDING)
1904 HeapFree( GetProcessHeap(), 0, wsa );
1905 return NtStatusToWSAError( status );
1907 return 0;
1910 /***********************************************************************
1911 * accept (WS2_32.1)
1913 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr,
1914 int *addrlen32)
1916 NTSTATUS status;
1917 SOCKET as;
1918 BOOL is_blocking;
1920 TRACE("socket %04lx\n", s );
1921 is_blocking = _is_blocking(s);
1923 do {
1924 /* try accepting first (if there is a deferred connection) */
1925 SERVER_START_REQ( accept_socket )
1927 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1928 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
1929 req->attributes = OBJ_INHERIT;
1930 status = wine_server_call( req );
1931 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
1933 SERVER_END_REQ;
1934 if (!status)
1936 if (addr) WS_getpeername(as, addr, addrlen32);
1937 return as;
1939 if (is_blocking && status == STATUS_CANT_WAIT)
1941 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1942 /* block here */
1943 do_block(fd, POLLIN, -1);
1944 _sync_sock_state(s); /* let wineserver notice connection */
1945 release_sock_fd( s, fd );
1947 } while (is_blocking && status == STATUS_CANT_WAIT);
1949 set_error(status);
1950 return INVALID_SOCKET;
1953 /***********************************************************************
1954 * AcceptEx
1956 static BOOL WINAPI WS2_AcceptEx(SOCKET listener, SOCKET acceptor, PVOID dest, DWORD dest_len,
1957 DWORD local_addr_len, DWORD rem_addr_len, LPDWORD received,
1958 LPOVERLAPPED overlapped)
1960 DWORD status;
1961 struct ws2_accept_async *wsa;
1962 int fd;
1963 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
1965 TRACE("(%lx, %lx, %p, %d, %d, %d, %p, %p)\n", listener, acceptor, dest, dest_len, local_addr_len,
1966 rem_addr_len, received, overlapped);
1968 if (!dest)
1970 SetLastError(WSAEINVAL);
1971 return FALSE;
1974 if (!overlapped)
1976 SetLastError(WSA_INVALID_PARAMETER);
1977 return FALSE;
1980 fd = get_sock_fd( listener, FILE_READ_DATA, NULL );
1981 if (fd == -1)
1983 SetLastError(WSAENOTSOCK);
1984 return FALSE;
1986 release_sock_fd( listener, fd );
1988 fd = get_sock_fd( acceptor, FILE_READ_DATA, NULL );
1989 if (fd == -1)
1991 SetLastError(WSAEINVAL);
1992 return FALSE;
1994 release_sock_fd( acceptor, fd );
1996 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
1997 if(!wsa)
1999 SetLastError(WSAEFAULT);
2000 return FALSE;
2003 wsa->listen_socket = SOCKET2HANDLE(listener);
2004 wsa->accept_socket = SOCKET2HANDLE(acceptor);
2005 wsa->user_overlapped = overlapped;
2006 wsa->cvalue = cvalue;
2007 wsa->buf = dest;
2008 wsa->data_len = dest_len;
2009 wsa->local_len = local_addr_len;
2010 wsa->remote_len = rem_addr_len;
2011 wsa->read = NULL;
2013 if (wsa->data_len)
2015 /* set up a read request if we need it */
2016 wsa->read = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[1]) );
2017 if (!wsa->read)
2019 HeapFree( GetProcessHeap(), 0, wsa );
2020 SetLastError(WSAEFAULT);
2021 return FALSE;
2024 wsa->read->hSocket = wsa->accept_socket;
2025 wsa->read->flags = 0;
2026 wsa->read->lpFlags = &wsa->read->flags;
2027 wsa->read->addr = NULL;
2028 wsa->read->addrlen.ptr = NULL;
2029 wsa->read->control = NULL;
2030 wsa->read->n_iovecs = 1;
2031 wsa->read->first_iovec = 0;
2032 wsa->read->iovec[0].iov_base = wsa->buf;
2033 wsa->read->iovec[0].iov_len = wsa->data_len;
2036 SERVER_START_REQ( register_async )
2038 req->type = ASYNC_TYPE_READ;
2039 req->async.handle = wine_server_obj_handle( SOCKET2HANDLE(listener) );
2040 req->async.callback = wine_server_client_ptr( WS2_async_accept );
2041 req->async.iosb = wine_server_client_ptr( overlapped );
2042 req->async.arg = wine_server_client_ptr( wsa );
2043 /* We don't set event or completion since we may also have to read */
2044 status = wine_server_call( req );
2046 SERVER_END_REQ;
2048 if(status != STATUS_PENDING)
2050 HeapFree( GetProcessHeap(), 0, wsa->read );
2051 HeapFree( GetProcessHeap(), 0, wsa );
2054 SetLastError( NtStatusToWSAError(status) );
2055 return FALSE;
2058 /***********************************************************************
2059 * GetAcceptExSockaddrs
2061 static void WINAPI WS2_GetAcceptExSockaddrs(PVOID buffer, DWORD data_size, DWORD local_size, DWORD remote_size,
2062 struct WS_sockaddr **local_addr, LPINT local_addr_len,
2063 struct WS_sockaddr **remote_addr, LPINT remote_addr_len)
2065 char *cbuf = buffer;
2066 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer, data_size, local_size, remote_size, local_addr,
2067 local_addr_len, remote_addr, remote_addr_len );
2068 cbuf += data_size;
2070 *local_addr_len = *(int *) cbuf;
2071 *local_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2073 cbuf += local_size;
2075 *remote_addr_len = *(int *) cbuf;
2076 *remote_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2079 /***********************************************************************
2080 * WSARecvMsg
2082 * Perform a receive operation that is capable of returning message
2083 * control headers. It is important to note that the WSAMSG parameter
2084 * must remain valid throughout the operation, even when an overlapped
2085 * receive is performed.
2087 static int WINAPI WS2_WSARecvMsg( SOCKET s, LPWSAMSG msg, LPDWORD lpNumberOfBytesRecvd,
2088 LPWSAOVERLAPPED lpOverlapped,
2089 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2091 if (!msg)
2093 SetLastError( WSAEFAULT );
2094 return SOCKET_ERROR;
2097 return WS2_recv_base( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesRecvd,
2098 &msg->dwFlags, msg->name, &msg->namelen,
2099 lpOverlapped, lpCompletionRoutine, &msg->Control );
2102 /***********************************************************************
2103 * bind (WS2_32.2)
2105 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
2107 int fd = get_sock_fd( s, 0, NULL );
2108 int res = SOCKET_ERROR;
2110 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2112 if (fd != -1)
2114 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
2116 SetLastError(WSAEAFNOSUPPORT);
2118 else
2120 union generic_unix_sockaddr uaddr;
2121 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2122 if (!uaddrlen)
2124 SetLastError(WSAEFAULT);
2126 else
2128 #ifdef IPV6_V6ONLY
2129 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
2130 if (name->sa_family == WS_AF_INET6 &&
2131 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
2133 int enable = 1;
2134 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
2136 release_sock_fd( s, fd );
2137 SetLastError(WSAEAFNOSUPPORT);
2138 return SOCKET_ERROR;
2141 #endif
2142 if (name->sa_family == WS_AF_INET)
2144 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2145 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2147 /* Trying to bind to the default host interface, using
2148 * INADDR_ANY instead*/
2149 WARN("Trying to bind to magic IP address, using "
2150 "INADDR_ANY instead.\n");
2151 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
2154 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
2156 int loc_errno = errno;
2157 WARN("\tfailure - errno = %i\n", errno);
2158 errno = loc_errno;
2159 switch (errno)
2161 case EBADF:
2162 SetLastError(WSAENOTSOCK);
2163 break;
2164 case EADDRNOTAVAIL:
2165 SetLastError(WSAEINVAL);
2166 break;
2167 default:
2168 SetLastError(wsaErrno());
2169 break;
2172 else
2174 res=0; /* success */
2178 release_sock_fd( s, fd );
2180 return res;
2183 /***********************************************************************
2184 * closesocket (WS2_32.3)
2186 int WINAPI WS_closesocket(SOCKET s)
2188 TRACE("socket %04lx\n", s);
2189 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
2190 return SOCKET_ERROR;
2193 static int do_connect(int fd, const struct WS_sockaddr* name, int namelen)
2195 union generic_unix_sockaddr uaddr;
2196 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2198 if (!uaddrlen)
2199 return WSAEFAULT;
2201 if (name->sa_family == WS_AF_INET)
2203 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2204 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2206 /* Trying to connect to magic replace-loopback address,
2207 * assuming we really want to connect to localhost */
2208 TRACE("Trying to connect to magic IP address, using "
2209 "INADDR_LOOPBACK instead.\n");
2210 in4->sin_addr.s_addr = htonl(WS_INADDR_LOOPBACK);
2214 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
2215 return 0;
2217 return wsaErrno();
2220 /***********************************************************************
2221 * connect (WS2_32.4)
2223 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
2225 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2227 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2229 if (fd != -1)
2231 int ret = do_connect(fd, name, namelen);
2232 if (ret == 0)
2233 goto connect_success;
2235 if (ret == WSAEINPROGRESS)
2237 /* tell wineserver that a connection is in progress */
2238 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2239 FD_CONNECT,
2240 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2241 if (_is_blocking(s))
2243 int result;
2244 /* block here */
2245 do_block(fd, POLLIN | POLLOUT, -1);
2246 _sync_sock_state(s); /* let wineserver notice connection */
2247 /* retrieve any error codes from it */
2248 result = _get_sock_error(s, FD_CONNECT_BIT);
2249 if (result)
2250 SetLastError(NtStatusToWSAError(result));
2251 else
2253 goto connect_success;
2256 else
2258 SetLastError(WSAEWOULDBLOCK);
2261 else
2263 SetLastError(ret);
2265 release_sock_fd( s, fd );
2267 return SOCKET_ERROR;
2269 connect_success:
2270 release_sock_fd( s, fd );
2271 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2272 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2273 FD_CONNECT|FD_WINE_LISTENING);
2274 return 0;
2277 /***********************************************************************
2278 * WSAConnect (WS2_32.30)
2280 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
2281 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
2282 LPQOS lpSQOS, LPQOS lpGQOS )
2284 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
2285 FIXME("unsupported parameters!\n");
2286 return WS_connect( s, name, namelen );
2289 /***********************************************************************
2290 * ConnectEx
2292 static BOOL WINAPI WS2_ConnectEx(SOCKET s, const struct WS_sockaddr* name, int namelen,
2293 PVOID sendBuf, DWORD sendBufLen, LPDWORD sent, LPOVERLAPPED ov)
2295 int fd, ret, status;
2297 if (!ov)
2299 SetLastError( ERROR_INVALID_PARAMETER );
2300 return FALSE;
2303 fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2304 if (fd == -1)
2306 SetLastError( WSAENOTSOCK );
2307 return FALSE;
2310 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
2311 s, name, debugstr_sockaddr(name), namelen, sendBuf, sendBufLen, ov);
2313 /* FIXME: technically the socket has to be bound */
2314 ret = do_connect(fd, name, namelen);
2315 if (ret == 0)
2317 WSABUF wsabuf;
2319 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2320 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2321 FD_CONNECT|FD_WINE_LISTENING);
2323 wsabuf.len = sendBufLen;
2324 wsabuf.buf = (char*) sendBuf;
2326 /* WSASend takes care of completion if need be */
2327 if (WSASend(s, &wsabuf, sendBuf ? 1 : 0, sent, 0, ov, NULL) != SOCKET_ERROR)
2328 goto connection_success;
2330 else if (ret == WSAEINPROGRESS)
2332 struct ws2_async *wsa;
2333 ULONG_PTR cvalue = (((ULONG_PTR)ov->hEvent & 1) == 0) ? (ULONG_PTR)ov : 0;
2335 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2336 FD_CONNECT,
2337 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2339 /* Indirectly call WSASend */
2340 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) )))
2342 SetLastError(WSAEFAULT);
2344 else
2346 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)ov;
2347 iosb->u.Status = STATUS_PENDING;
2348 iosb->Information = 0;
2350 wsa->hSocket = SOCKET2HANDLE(s);
2351 wsa->addr = NULL;
2352 wsa->addrlen.val = 0;
2353 wsa->flags = 0;
2354 wsa->lpFlags = &wsa->flags;
2355 wsa->control = NULL;
2356 wsa->n_iovecs = sendBuf ? 1 : 0;
2357 wsa->first_iovec = 0;
2358 wsa->completion_func = NULL;
2359 wsa->iovec[0].iov_base = sendBuf;
2360 wsa->iovec[0].iov_len = sendBufLen;
2362 SERVER_START_REQ( register_async )
2364 req->type = ASYNC_TYPE_WRITE;
2365 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2366 req->async.callback = wine_server_client_ptr( WS2_async_send );
2367 req->async.iosb = wine_server_client_ptr( iosb );
2368 req->async.arg = wine_server_client_ptr( wsa );
2369 req->async.event = wine_server_obj_handle( ov->hEvent );
2370 req->async.cvalue = cvalue;
2371 status = wine_server_call( req );
2373 SERVER_END_REQ;
2375 if (status != STATUS_PENDING) HeapFree(GetProcessHeap(), 0, wsa);
2377 /* If the connect already failed */
2378 if (status == STATUS_PIPE_DISCONNECTED)
2379 status = _get_sock_error(s, FD_CONNECT_BIT);
2380 SetLastError( NtStatusToWSAError(status) );
2383 else
2385 SetLastError(ret);
2388 release_sock_fd( s, fd );
2389 return FALSE;
2391 connection_success:
2392 release_sock_fd( s, fd );
2393 return TRUE;
2397 /***********************************************************************
2398 * getpeername (WS2_32.5)
2400 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
2402 int fd;
2403 int res;
2405 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, namelen?*namelen:0);
2407 fd = get_sock_fd( s, 0, NULL );
2408 res = SOCKET_ERROR;
2410 if (fd != -1)
2412 union generic_unix_sockaddr uaddr;
2413 unsigned int uaddrlen = sizeof(uaddr);
2415 if (getpeername(fd, &uaddr.addr, &uaddrlen) == 0)
2417 if (!name || !namelen)
2418 SetLastError(WSAEFAULT);
2419 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
2420 /* The buffer was too small */
2421 SetLastError(WSAEFAULT);
2422 else
2423 res = 0;
2425 else
2426 SetLastError(wsaErrno());
2427 release_sock_fd( s, fd );
2429 return res;
2432 /***********************************************************************
2433 * getsockname (WS2_32.6)
2435 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
2437 int fd;
2438 int res;
2440 TRACE("socket: %04lx, ptr %p, len %8x\n", s, name, *namelen);
2442 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
2443 if( (name == NULL) || (namelen == NULL) )
2445 SetLastError( WSAEFAULT );
2446 return SOCKET_ERROR;
2449 fd = get_sock_fd( s, 0, NULL );
2450 res = SOCKET_ERROR;
2452 if (fd != -1)
2454 union generic_unix_sockaddr uaddr;
2455 unsigned int uaddrlen = sizeof(uaddr);
2457 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
2459 SetLastError(wsaErrno());
2461 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
2463 SetLastError(WSAEINVAL);
2465 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
2467 /* The buffer was too small */
2468 SetLastError(WSAEFAULT);
2470 else
2472 res=0;
2474 release_sock_fd( s, fd );
2476 return res;
2479 /***********************************************************************
2480 * getsockopt (WS2_32.7)
2482 INT WINAPI WS_getsockopt(SOCKET s, INT level,
2483 INT optname, char *optval, INT *optlen)
2485 int fd;
2486 INT ret = 0;
2488 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
2489 s, level, optname, optval, *optlen);
2491 switch(level)
2493 case WS_SOL_SOCKET:
2495 switch(optname)
2497 /* Handle common cases. The special cases are below, sorted
2498 * alphabetically */
2499 case WS_SO_ACCEPTCONN:
2500 case WS_SO_BROADCAST:
2501 case WS_SO_DEBUG:
2502 case WS_SO_ERROR:
2503 case WS_SO_KEEPALIVE:
2504 case WS_SO_OOBINLINE:
2505 case WS_SO_RCVBUF:
2506 case WS_SO_REUSEADDR:
2507 case WS_SO_SNDBUF:
2508 case WS_SO_TYPE:
2509 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2510 return SOCKET_ERROR;
2511 convert_sockopt(&level, &optname);
2512 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2514 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2515 ret = SOCKET_ERROR;
2517 release_sock_fd( s, fd );
2518 return ret;
2520 case WS_SO_DONTLINGER:
2522 struct linger lingval;
2523 unsigned int len = sizeof(struct linger);
2525 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
2527 SetLastError(WSAEFAULT);
2528 return SOCKET_ERROR;
2530 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2531 return SOCKET_ERROR;
2533 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
2535 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2536 ret = SOCKET_ERROR;
2538 else
2540 *(BOOL *)optval = (lingval.l_onoff) ? FALSE : TRUE;
2541 *optlen = sizeof(BOOL);
2544 release_sock_fd( s, fd );
2545 return ret;
2548 case WS_SO_CONNECT_TIME:
2550 static int pretendtime = 0;
2551 struct WS_sockaddr addr;
2552 int len = sizeof(addr);
2554 if (!optlen || *optlen < sizeof(DWORD) || !optval)
2556 SetLastError(WSAEFAULT);
2557 return SOCKET_ERROR;
2559 if (WS_getpeername(s, &addr, &len) == SOCKET_ERROR)
2560 *(DWORD *)optval = ~0u;
2561 else
2563 if (!pretendtime) FIXME("WS_SO_CONNECT_TIME - faking results\n");
2564 *(DWORD *)optval = pretendtime++;
2566 *optlen = sizeof(DWORD);
2567 return ret;
2569 /* As mentioned in setsockopt, Windows ignores this, so we
2570 * always return true here */
2571 case WS_SO_DONTROUTE:
2572 if (!optlen || *optlen < sizeof(BOOL) || !optval)
2574 SetLastError(WSAEFAULT);
2575 return SOCKET_ERROR;
2577 *(BOOL *)optval = TRUE;
2578 *optlen = sizeof(BOOL);
2579 return 0;
2581 case WS_SO_LINGER:
2583 struct linger lingval;
2584 int so_type;
2585 unsigned int len = sizeof(struct linger), slen = sizeof(int);
2587 /* struct linger and LINGER have different sizes */
2588 if (!optlen || *optlen < sizeof(LINGER) || !optval)
2590 SetLastError(WSAEFAULT);
2591 return SOCKET_ERROR;
2593 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2594 return SOCKET_ERROR;
2596 if ((getsockopt(fd, SOL_SOCKET, SO_TYPE, &so_type, &slen) == 0 && so_type == SOCK_DGRAM))
2598 SetLastError(WSAENOPROTOOPT);
2599 ret = SOCKET_ERROR;
2601 else if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0)
2603 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2604 ret = SOCKET_ERROR;
2606 else
2608 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
2609 ((LINGER *)optval)->l_linger = lingval.l_linger;
2610 *optlen = sizeof(struct linger);
2613 release_sock_fd( s, fd );
2614 return ret;
2617 case WS_SO_MAX_MSG_SIZE:
2618 if (!optlen || *optlen < sizeof(int) || !optval)
2620 SetLastError(WSAEFAULT);
2621 return SOCKET_ERROR;
2623 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
2624 *(int *)optval = 65507;
2625 *optlen = sizeof(int);
2626 return 0;
2628 /* SO_OPENTYPE does not require a valid socket handle. */
2629 case WS_SO_OPENTYPE:
2630 if (!optlen || *optlen < sizeof(int) || !optval)
2632 SetLastError(WSAEFAULT);
2633 return SOCKET_ERROR;
2635 *(int *)optval = get_per_thread_data()->opentype;
2636 *optlen = sizeof(int);
2637 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
2638 return 0;
2640 #ifdef SO_RCVTIMEO
2641 case WS_SO_RCVTIMEO:
2642 #endif
2643 #ifdef SO_SNDTIMEO
2644 case WS_SO_SNDTIMEO:
2645 #endif
2646 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
2648 struct timeval tv;
2649 unsigned int len = sizeof(struct timeval);
2651 if (!optlen || *optlen < sizeof(int)|| !optval)
2653 SetLastError(WSAEFAULT);
2654 return SOCKET_ERROR;
2656 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2657 return SOCKET_ERROR;
2659 convert_sockopt(&level, &optname);
2660 if (getsockopt(fd, level, optname, &tv, &len) != 0 )
2662 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2663 ret = SOCKET_ERROR;
2665 else
2667 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
2668 *optlen = sizeof(int);
2671 release_sock_fd( s, fd );
2672 return ret;
2674 #endif
2675 default:
2676 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
2677 SetLastError(WSAENOPROTOOPT);
2678 return SOCKET_ERROR;
2679 } /* end switch(optname) */
2680 }/* end case WS_SOL_SOCKET */
2681 #ifdef HAVE_IPX
2682 case NSPROTO_IPX:
2684 struct WS_sockaddr_ipx addr;
2685 IPX_ADDRESS_DATA *data;
2686 int namelen;
2687 switch(optname)
2689 case IPX_PTYPE:
2690 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
2691 #ifdef SOL_IPX
2692 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (unsigned int*)optlen) == -1)
2694 ret = SOCKET_ERROR;
2696 #else
2698 struct ipx val;
2699 socklen_t len=sizeof(struct ipx);
2700 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
2701 ret = SOCKET_ERROR;
2702 else
2703 *optval = (int)val.ipx_pt;
2705 #endif
2706 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
2707 release_sock_fd( s, fd );
2708 return ret;
2710 case IPX_ADDRESS:
2712 * On a Win2000 system with one network card there are usually
2713 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
2714 * Using this call you can then retrieve info about this all.
2715 * In case of Linux it is a bit different. Usually you have
2716 * only "one" device active and further it is not possible to
2717 * query things like the linkspeed.
2719 FIXME("IPX_ADDRESS\n");
2720 namelen = sizeof(struct WS_sockaddr_ipx);
2721 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
2722 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
2724 data = (IPX_ADDRESS_DATA*)optval;
2725 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
2726 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
2727 data->adapternum = 0;
2728 data->wan = FALSE; /* We are not on a wan for now .. */
2729 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
2730 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
2731 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
2732 * note 1MB = 1000kB in this case */
2733 return 0;
2735 case IPX_MAX_ADAPTER_NUM:
2736 FIXME("IPX_MAX_ADAPTER_NUM\n");
2737 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
2738 return 0;
2740 default:
2741 FIXME("IPX optname:%x\n", optname);
2742 return SOCKET_ERROR;
2743 }/* end switch(optname) */
2744 } /* end case NSPROTO_IPX */
2745 #endif
2747 #ifdef HAVE_IRDA
2748 case WS_SOL_IRLMP:
2749 switch(optname)
2751 case WS_IRLMP_ENUMDEVICES:
2753 static const int MAX_IRDA_DEVICES = 10;
2754 char buf[sizeof(struct irda_device_list) +
2755 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
2756 int fd, res;
2757 socklen_t len = sizeof(buf);
2759 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2760 return SOCKET_ERROR;
2761 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
2762 if (res < 0)
2764 SetLastError(wsaErrno());
2765 return SOCKET_ERROR;
2767 else
2769 struct irda_device_list *src = (struct irda_device_list *)buf;
2770 DEVICELIST *dst = (DEVICELIST *)optval;
2771 INT needed = sizeof(DEVICELIST), i;
2773 if (src->len > 0)
2774 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
2775 if (*optlen < needed)
2777 SetLastError(WSAEFAULT);
2778 return SOCKET_ERROR;
2780 *optlen = needed;
2781 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
2782 dst->numDevice = src->len;
2783 for (i = 0; i < src->len; i++)
2785 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
2786 src->dev[i].saddr, src->dev[i].daddr,
2787 src->dev[i].info, src->dev[i].hints[0],
2788 src->dev[i].hints[1]);
2789 memcpy( dst->Device[i].irdaDeviceID,
2790 &src->dev[i].daddr,
2791 sizeof(dst->Device[i].irdaDeviceID) ) ;
2792 memcpy( dst->Device[i].irdaDeviceName,
2793 src->dev[i].info,
2794 sizeof(dst->Device[i].irdaDeviceName) ) ;
2795 memcpy( &dst->Device[i].irdaDeviceHints1,
2796 &src->dev[i].hints[0],
2797 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
2798 memcpy( &dst->Device[i].irdaDeviceHints2,
2799 &src->dev[i].hints[1],
2800 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
2801 dst->Device[i].irdaCharSet = src->dev[i].charset;
2803 return 0;
2806 default:
2807 FIXME("IrDA optname:0x%x\n", optname);
2808 return SOCKET_ERROR;
2810 break; /* case WS_SOL_IRLMP */
2811 #endif
2813 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
2814 case WS_IPPROTO_TCP:
2815 switch(optname)
2817 case WS_TCP_NODELAY:
2818 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2819 return SOCKET_ERROR;
2820 convert_sockopt(&level, &optname);
2821 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2823 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2824 ret = SOCKET_ERROR;
2826 release_sock_fd( s, fd );
2827 return ret;
2829 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
2830 return SOCKET_ERROR;
2832 case WS_IPPROTO_IP:
2833 switch(optname)
2835 case WS_IP_ADD_MEMBERSHIP:
2836 case WS_IP_DROP_MEMBERSHIP:
2837 #ifdef IP_HDRINCL
2838 case WS_IP_HDRINCL:
2839 #endif
2840 case WS_IP_MULTICAST_IF:
2841 case WS_IP_MULTICAST_LOOP:
2842 case WS_IP_MULTICAST_TTL:
2843 case WS_IP_OPTIONS:
2844 #ifdef IP_PKTINFO
2845 case WS_IP_PKTINFO:
2846 #endif
2847 case WS_IP_TOS:
2848 case WS_IP_TTL:
2849 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2850 return SOCKET_ERROR;
2851 convert_sockopt(&level, &optname);
2852 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2854 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2855 ret = SOCKET_ERROR;
2857 release_sock_fd( s, fd );
2858 return ret;
2859 case WS_IP_DONTFRAGMENT:
2860 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
2861 *(BOOL*)optval = FALSE;
2862 return 0;
2864 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
2865 return SOCKET_ERROR;
2867 case WS_IPPROTO_IPV6:
2868 switch(optname)
2870 #ifdef IPV6_ADD_MEMBERSHIP
2871 case WS_IPV6_ADD_MEMBERSHIP:
2872 #endif
2873 #ifdef IPV6_DROP_MEMBERSHIP
2874 case WS_IPV6_DROP_MEMBERSHIP:
2875 #endif
2876 case WS_IPV6_MULTICAST_IF:
2877 case WS_IPV6_MULTICAST_HOPS:
2878 case WS_IPV6_MULTICAST_LOOP:
2879 case WS_IPV6_UNICAST_HOPS:
2880 case WS_IPV6_V6ONLY:
2881 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2882 return SOCKET_ERROR;
2883 convert_sockopt(&level, &optname);
2884 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2886 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2887 ret = SOCKET_ERROR;
2889 release_sock_fd( s, fd );
2890 return ret;
2891 case WS_IPV6_DONTFRAG:
2892 FIXME("WS_IPV6_DONTFRAG is always false!\n");
2893 *(BOOL*)optval = FALSE;
2894 return 0;
2896 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
2897 return SOCKET_ERROR;
2899 default:
2900 WARN("Unknown level: 0x%08x\n", level);
2901 SetLastError(WSAEINVAL);
2902 return SOCKET_ERROR;
2903 } /* end switch(level) */
2906 /***********************************************************************
2907 * htonl (WS2_32.8)
2909 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
2911 return htonl(hostlong);
2915 /***********************************************************************
2916 * htons (WS2_32.9)
2918 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
2920 return htons(hostshort);
2923 /***********************************************************************
2924 * WSAHtonl (WS2_32.46)
2925 * From MSDN description of error codes, this function should also
2926 * check if WinSock has been initialized and the socket is a valid
2927 * socket. But why? This function only translates a host byte order
2928 * u_long into a network byte order u_long...
2930 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
2932 if (lpnetlong)
2934 *lpnetlong = htonl(hostlong);
2935 return 0;
2937 WSASetLastError(WSAEFAULT);
2938 return SOCKET_ERROR;
2941 /***********************************************************************
2942 * WSAHtons (WS2_32.47)
2943 * From MSDN description of error codes, this function should also
2944 * check if WinSock has been initialized and the socket is a valid
2945 * socket. But why? This function only translates a host byte order
2946 * u_short into a network byte order u_short...
2948 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
2951 if (lpnetshort)
2953 *lpnetshort = htons(hostshort);
2954 return 0;
2956 WSASetLastError(WSAEFAULT);
2957 return SOCKET_ERROR;
2961 /***********************************************************************
2962 * inet_addr (WS2_32.11)
2964 WS_u_long WINAPI WS_inet_addr(const char *cp)
2966 if (!cp) return INADDR_NONE;
2967 return inet_addr(cp);
2971 /***********************************************************************
2972 * ntohl (WS2_32.14)
2974 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
2976 return ntohl(netlong);
2980 /***********************************************************************
2981 * ntohs (WS2_32.15)
2983 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
2985 return ntohs(netshort);
2989 /***********************************************************************
2990 * inet_ntoa (WS2_32.12)
2992 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
2994 /* use "buffer for dummies" here because some applications have a
2995 * propensity to decode addresses in ws_hostent structure without
2996 * saving them first...
2998 static char dbuffer[16]; /* Yes, 16: 4*3 digits + 3 '.' + 1 '\0' */
3000 char* s = inet_ntoa(*((struct in_addr*)&in));
3001 if( s )
3003 strcpy(dbuffer, s);
3004 return dbuffer;
3006 SetLastError(wsaErrno());
3007 return NULL;
3010 static const char *debugstr_wsaioctl(DWORD ioctl)
3012 const char *buf_type, *family;
3014 switch(ioctl & 0x18000000)
3016 case WS_IOC_WS2:
3017 family = "IOC_WS2";
3018 break;
3019 case WS_IOC_PROTOCOL:
3020 family = "IOC_PROTOCOL";
3021 break;
3022 case WS_IOC_VENDOR:
3023 family = "IOC_VENDOR";
3024 break;
3025 default: /* WS_IOC_UNIX */
3027 BYTE size = (ioctl >> 16) & WS_IOCPARM_MASK;
3028 char x = (ioctl & 0xff00) >> 8;
3029 BYTE y = ioctl & 0xff;
3030 char args[14];
3032 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3034 case WS_IOC_VOID:
3035 buf_type = "_IO";
3036 sprintf(args, "%d, %d", x, y);
3037 break;
3038 case WS_IOC_IN:
3039 buf_type = "_IOW";
3040 sprintf(args, "'%c', %d, %d", x, y, size);
3041 break;
3042 case WS_IOC_OUT:
3043 buf_type = "_IOR";
3044 sprintf(args, "'%c', %d, %d", x, y, size);
3045 break;
3046 default:
3047 buf_type = "?";
3048 sprintf(args, "'%c', %d, %d", x, y, size);
3049 break;
3051 return wine_dbg_sprintf("%s(%s)", buf_type, args);
3055 /* We are different from WS_IOC_UNIX. */
3056 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3058 case WS_IOC_VOID:
3059 buf_type = "_WSAIO";
3060 break;
3061 case WS_IOC_INOUT:
3062 buf_type = "_WSAIORW";
3063 break;
3064 case WS_IOC_IN:
3065 buf_type = "_WSAIOW";
3066 break;
3067 case WS_IOC_OUT:
3068 buf_type = "_WSAIOR";
3069 break;
3070 default:
3071 buf_type = "?";
3072 break;
3075 return wine_dbg_sprintf("%s(%s, %d)", buf_type, family,
3076 (USHORT)(ioctl & 0xffff));
3079 /**********************************************************************
3080 * WSAIoctl (WS2_32.50)
3083 INT WINAPI WSAIoctl(SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size, LPVOID out_buff,
3084 DWORD out_size, LPDWORD ret_size, LPWSAOVERLAPPED overlapped,
3085 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
3087 int fd;
3088 DWORD status = 0, total = 0;
3090 TRACE("%ld, 0x%08x, %p, %d, %p, %d, %p, %p, %p\n",
3091 s, code, in_buff, in_size, out_buff, out_size, ret_size, overlapped, completion);
3093 switch (code)
3095 case WS_FIONBIO:
3096 if (in_size != sizeof(WS_u_long) || IS_INTRESOURCE(in_buff))
3098 WSASetLastError(WSAEFAULT);
3099 return SOCKET_ERROR;
3101 if (_get_sock_mask(s))
3103 /* AsyncSelect()'ed sockets are always nonblocking */
3104 if (!*(WS_u_long *)in_buff) status = WSAEINVAL;
3105 break;
3107 if (*(WS_u_long *)in_buff)
3108 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
3109 else
3110 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
3111 break;
3113 case WS_FIONREAD:
3115 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
3117 WSASetLastError(WSAEFAULT);
3118 return SOCKET_ERROR;
3120 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3121 if (ioctl(fd, FIONREAD, out_buff ) == -1)
3122 status = (errno == EBADF) ? WSAENOTSOCK : wsaErrno();
3123 release_sock_fd( s, fd );
3124 break;
3127 case WS_SIOCATMARK:
3129 unsigned int oob = 0, oobsize = sizeof(int), atmark = 0;
3130 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
3132 WSASetLastError(WSAEFAULT);
3133 return SOCKET_ERROR;
3135 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3136 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
3137 if ((getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &oob, &oobsize ) == -1)
3138 || (!oob && ioctl(fd, SIOCATMARK, &atmark ) == -1))
3139 status = (errno == EBADF) ? WSAENOTSOCK : wsaErrno();
3140 else
3142 /* The SIOCATMARK value read from ioctl() is reversed
3143 * because BSD returns TRUE if it's in the OOB mark
3144 * while Windows returns TRUE if there are NO OOB bytes.
3146 (*(WS_u_long *) out_buff) = oob | !atmark;
3149 release_sock_fd( s, fd );
3150 break;
3153 case WS_FIOASYNC:
3154 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
3155 SetLastError(WSAEINVAL);
3156 return SOCKET_ERROR;
3158 case WS_SIO_GET_INTERFACE_LIST:
3160 INTERFACE_INFO* intArray = out_buff;
3161 DWORD size, numInt = 0, apiReturn;
3163 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
3165 if (!out_buff || !ret_size)
3167 WSASetLastError(WSAEFAULT);
3168 return SOCKET_ERROR;
3171 fd = get_sock_fd( s, 0, NULL );
3172 if (fd == -1) return SOCKET_ERROR;
3174 apiReturn = GetAdaptersInfo(NULL, &size);
3175 if (apiReturn == ERROR_BUFFER_OVERFLOW)
3177 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
3179 if (table)
3181 if (GetAdaptersInfo(table, &size) == NO_ERROR)
3183 PIP_ADAPTER_INFO ptr;
3185 if (size*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > out_size)
3187 WARN("Buffer too small = %u, out_size = %u\n", size, out_size);
3188 HeapFree(GetProcessHeap(),0,table);
3189 release_sock_fd( s, fd );
3190 status = WSAEFAULT;
3191 break;
3193 for (ptr = table, numInt = 0; ptr;
3194 ptr = ptr->Next, intArray++, numInt++)
3196 unsigned int addr, mask, bcast;
3197 struct ifreq ifInfo;
3199 /* Socket Status Flags */
3200 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
3201 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
3203 ERR("Error obtaining status flags for socket!\n");
3204 HeapFree(GetProcessHeap(),0,table);
3205 release_sock_fd( s, fd );
3206 status = WSAEINVAL;
3207 break;
3209 else
3211 /* set flags; the values of IFF_* are not the same
3212 under Linux and Windows, therefore must generate
3213 new flags */
3214 intArray->iiFlags = 0;
3215 if (ifInfo.ifr_flags & IFF_BROADCAST)
3216 intArray->iiFlags |= WS_IFF_BROADCAST;
3217 #ifdef IFF_POINTOPOINT
3218 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
3219 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
3220 #endif
3221 if (ifInfo.ifr_flags & IFF_LOOPBACK)
3222 intArray->iiFlags |= WS_IFF_LOOPBACK;
3223 if (ifInfo.ifr_flags & IFF_UP)
3224 intArray->iiFlags |= WS_IFF_UP;
3225 if (ifInfo.ifr_flags & IFF_MULTICAST)
3226 intArray->iiFlags |= WS_IFF_MULTICAST;
3229 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
3230 mask = inet_addr(ptr->IpAddressList.IpMask.String);
3231 bcast = addr | ~mask;
3232 intArray->iiAddress.AddressIn.sin_family = AF_INET;
3233 intArray->iiAddress.AddressIn.sin_port = 0;
3234 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
3235 addr;
3236 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
3237 intArray->iiNetmask.AddressIn.sin_port = 0;
3238 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
3239 mask;
3240 intArray->iiBroadcastAddress.AddressIn.sin_family =
3241 AF_INET;
3242 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
3243 intArray->iiBroadcastAddress.AddressIn.sin_addr.
3244 WS_s_addr = bcast;
3247 else
3249 ERR("Unable to get interface table!\n");
3250 status = WSAEINVAL;
3252 HeapFree(GetProcessHeap(),0,table);
3254 else status = WSAEINVAL;
3256 else if (apiReturn != ERROR_NO_DATA)
3258 ERR("Unable to get interface table!\n");
3259 status = WSAEINVAL;
3261 /* Calculate the size of the array being returned */
3262 total = sizeof(INTERFACE_INFO) * numInt;
3263 release_sock_fd( s, fd );
3264 break;
3267 case WS_SIO_ADDRESS_LIST_CHANGE:
3268 FIXME("-> SIO_ADDRESS_LIST_CHANGE request: stub\n");
3269 /* FIXME: error and return code depend on whether socket was created
3270 * with WSA_FLAG_OVERLAPPED, but there is no easy way to get this */
3271 break;
3273 case WS_SIO_ADDRESS_LIST_QUERY:
3275 DWORD size;
3277 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
3279 if (!ret_size)
3281 WSASetLastError(WSAEFAULT);
3282 return SOCKET_ERROR;
3285 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
3287 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
3288 DWORD num;
3290 if (!table || GetAdaptersInfo(table, &size))
3292 HeapFree(GetProcessHeap(), 0, table);
3293 status = WSAEINVAL;
3294 break;
3297 for (p = table, num = 0; p; p = p->Next)
3298 if (p->IpAddressList.IpAddress.String[0]) num++;
3300 total = sizeof(SOCKET_ADDRESS_LIST) + sizeof(SOCKET_ADDRESS) * (num - 1);
3301 total += sizeof(SOCKADDR) * num;
3303 if (total > out_size)
3305 HeapFree(GetProcessHeap(), 0, table);
3306 status = WSAEFAULT;
3307 break;
3310 if (out_buff)
3312 unsigned int i;
3313 SOCKET_ADDRESS *sa;
3314 SOCKET_ADDRESS_LIST *sa_list = out_buff;
3315 SOCKADDR_IN *sockaddr;
3317 sa = sa_list->Address;
3318 sockaddr = (SOCKADDR_IN *)((char *)sa + num * sizeof(SOCKET_ADDRESS));
3319 sa_list->iAddressCount = num;
3321 for (p = table, i = 0; p; p = p->Next)
3323 if (!p->IpAddressList.IpAddress.String[0]) continue;
3325 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
3326 sa[i].iSockaddrLength = sizeof(SOCKADDR);
3328 sockaddr[i].sin_family = AF_INET;
3329 sockaddr[i].sin_port = 0;
3330 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
3331 i++;
3335 HeapFree(GetProcessHeap(), 0, table);
3337 else
3339 WARN("unable to get IP address list\n");
3340 status = WSAEINVAL;
3342 break;
3345 case WS_SIO_FLUSH:
3346 FIXME("SIO_FLUSH: stub.\n");
3347 break;
3349 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
3351 static const GUID connectex_guid = WSAID_CONNECTEX;
3352 static const GUID disconnectex_guid = WSAID_DISCONNECTEX;
3353 static const GUID acceptex_guid = WSAID_ACCEPTEX;
3354 static const GUID getaccepexsockaddrs_guid = WSAID_GETACCEPTEXSOCKADDRS;
3355 static const GUID transmitfile_guid = WSAID_TRANSMITFILE;
3356 static const GUID transmitpackets_guid = WSAID_TRANSMITPACKETS;
3357 static const GUID wsarecvmsg_guid = WSAID_WSARECVMSG;
3358 static const GUID wsasendmsg_guid = WSAID_WSASENDMSG;
3360 if ( IsEqualGUID(&connectex_guid, in_buff) )
3362 *(LPFN_CONNECTEX *)out_buff = WS2_ConnectEx;
3363 break;
3365 else if ( IsEqualGUID(&disconnectex_guid, in_buff) )
3367 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented DisconnectEx\n");
3369 else if ( IsEqualGUID(&acceptex_guid, in_buff) )
3371 *(LPFN_ACCEPTEX *)out_buff = WS2_AcceptEx;
3372 break;
3374 else if ( IsEqualGUID(&getaccepexsockaddrs_guid, in_buff) )
3376 *(LPFN_GETACCEPTEXSOCKADDRS *)out_buff = WS2_GetAcceptExSockaddrs;
3377 break;
3379 else if ( IsEqualGUID(&transmitfile_guid, in_buff) )
3381 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitFile\n");
3383 else if ( IsEqualGUID(&transmitpackets_guid, in_buff) )
3385 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitPackets\n");
3387 else if ( IsEqualGUID(&wsarecvmsg_guid, in_buff) )
3389 *(LPFN_WSARECVMSG *)out_buff = WS2_WSARecvMsg;
3390 break;
3392 else if ( IsEqualGUID(&wsasendmsg_guid, in_buff) )
3394 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented WSASendMsg\n");
3396 else
3397 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff));
3399 status = WSAEOPNOTSUPP;
3400 break;
3402 case WS_SIO_KEEPALIVE_VALS:
3404 struct tcp_keepalive *k;
3405 int keepalive, keepidle, keepintvl;
3407 if (!in_buff || in_size < sizeof(struct tcp_keepalive))
3409 WSASetLastError(WSAEFAULT);
3410 return SOCKET_ERROR;
3413 k = in_buff;
3414 keepalive = k->onoff ? 1 : 0;
3415 keepidle = max( 1, (k->keepalivetime + 500) / 1000 );
3416 keepintvl = max( 1, (k->keepaliveinterval + 500) / 1000 );
3418 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
3420 fd = get_sock_fd(s, 0, NULL);
3421 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
3422 status = WSAEINVAL;
3423 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
3424 /* these values need to be set only if SO_KEEPALIVE is enabled */
3425 else if(keepalive)
3427 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
3428 status = WSAEINVAL;
3429 else if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
3430 status = WSAEINVAL;
3432 #else
3433 else
3434 FIXME("ignoring keepalive interval and timeout\n");
3435 #endif
3436 release_sock_fd(s, fd);
3437 break;
3439 case WS_SIO_ROUTING_INTERFACE_QUERY:
3441 struct WS_sockaddr *daddr = (struct WS_sockaddr *)in_buff;
3442 struct WS_sockaddr_in *daddr_in = (struct WS_sockaddr_in *)daddr;
3443 struct WS_sockaddr_in *saddr_in = out_buff;
3444 MIB_IPFORWARDROW row;
3445 PMIB_IPADDRTABLE ipAddrTable = NULL;
3446 DWORD size, i, found_index;
3448 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
3450 if (!in_buff || in_size < sizeof(struct WS_sockaddr) ||
3451 !out_buff || out_size < sizeof(struct WS_sockaddr_in) || !ret_size)
3453 WSASetLastError(WSAEFAULT);
3454 return SOCKET_ERROR;
3456 if (daddr->sa_family != AF_INET)
3458 FIXME("unsupported address family %d\n", daddr->sa_family);
3459 status = WSAEAFNOSUPPORT;
3460 break;
3462 if (GetBestRoute(daddr_in->sin_addr.S_un.S_addr, 0, &row) != NOERROR ||
3463 GetIpAddrTable(NULL, &size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
3465 status = WSAEFAULT;
3466 break;
3468 ipAddrTable = HeapAlloc(GetProcessHeap(), 0, size);
3469 if (GetIpAddrTable(ipAddrTable, &size, FALSE))
3471 HeapFree(GetProcessHeap(), 0, ipAddrTable);
3472 status = WSAEFAULT;
3473 break;
3475 for (i = 0, found_index = ipAddrTable->dwNumEntries;
3476 i < ipAddrTable->dwNumEntries; i++)
3478 if (ipAddrTable->table[i].dwIndex == row.dwForwardIfIndex)
3479 found_index = i;
3481 if (found_index == ipAddrTable->dwNumEntries)
3483 ERR("no matching IP address for interface %d\n",
3484 row.dwForwardIfIndex);
3485 HeapFree(GetProcessHeap(), 0, ipAddrTable);
3486 status = WSAEFAULT;
3487 break;
3489 saddr_in->sin_family = AF_INET;
3490 saddr_in->sin_addr.S_un.S_addr = ipAddrTable->table[found_index].dwAddr;
3491 saddr_in->sin_port = 0;
3492 total = sizeof(struct WS_sockaddr_in);
3493 HeapFree(GetProcessHeap(), 0, ipAddrTable);
3494 break;
3496 case WS_SIO_SET_COMPATIBILITY_MODE:
3497 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
3498 status = WSAEOPNOTSUPP;
3499 break;
3500 case WS_SIO_UDP_CONNRESET:
3501 FIXME("WS_SIO_UDP_CONNRESET stub\n");
3502 break;
3503 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
3504 WSASetLastError(WSAEOPNOTSUPP);
3505 return SOCKET_ERROR;
3506 default:
3507 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code));
3508 status = WSAEOPNOTSUPP;
3509 break;
3512 if (completion)
3514 FIXME( "completion routine %p not supported\n", completion );
3516 else if (overlapped)
3518 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
3519 overlapped->Internal = status;
3520 overlapped->InternalHigh = total;
3521 if (overlapped->hEvent) NtSetEvent( overlapped->hEvent, NULL );
3522 if (cvalue) WS_AddCompletion( HANDLE2SOCKET(s), cvalue, status, total );
3525 if (!status)
3527 if (ret_size) *ret_size = total;
3528 return 0;
3530 SetLastError( status );
3531 return SOCKET_ERROR;
3535 /***********************************************************************
3536 * ioctlsocket (WS2_32.10)
3538 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
3540 DWORD ret_size;
3541 return WSAIoctl( s, cmd, argp, sizeof(WS_u_long), argp, sizeof(WS_u_long), &ret_size, NULL, NULL );
3544 /***********************************************************************
3545 * listen (WS2_32.13)
3547 int WINAPI WS_listen(SOCKET s, int backlog)
3549 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
3551 TRACE("socket %04lx, backlog %d\n", s, backlog);
3552 if (fd != -1)
3554 if (listen(fd, backlog) == 0)
3556 release_sock_fd( s, fd );
3557 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
3558 FD_WINE_LISTENING,
3559 FD_CONNECT|FD_WINE_CONNECTED);
3560 return 0;
3562 SetLastError(wsaErrno());
3563 release_sock_fd( s, fd );
3565 return SOCKET_ERROR;
3568 /***********************************************************************
3569 * recv (WS2_32.16)
3571 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
3573 DWORD n, dwFlags = flags;
3574 WSABUF wsabuf;
3576 wsabuf.len = len;
3577 wsabuf.buf = buf;
3579 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
3580 return SOCKET_ERROR;
3581 else
3582 return n;
3585 /***********************************************************************
3586 * recvfrom (WS2_32.17)
3588 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
3589 struct WS_sockaddr *from, int *fromlen)
3591 DWORD n, dwFlags = flags;
3592 WSABUF wsabuf;
3594 wsabuf.len = len;
3595 wsabuf.buf = buf;
3597 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL, NULL) == SOCKET_ERROR )
3598 return SOCKET_ERROR;
3599 else
3600 return n;
3603 /* allocate a poll array for the corresponding fd sets */
3604 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
3605 const WS_fd_set *exceptfds, int *count_ptr )
3607 unsigned int i, j = 0, count = 0;
3608 struct pollfd *fds;
3610 if (readfds) count += readfds->fd_count;
3611 if (writefds) count += writefds->fd_count;
3612 if (exceptfds) count += exceptfds->fd_count;
3613 *count_ptr = count;
3614 if (!count)
3616 SetLastError(WSAEINVAL);
3617 return NULL;
3619 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0]))))
3621 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
3622 return NULL;
3624 if (readfds)
3625 for (i = 0; i < readfds->fd_count; i++, j++)
3627 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
3628 if (fds[j].fd == -1) goto failed;
3629 fds[j].events = POLLIN;
3630 fds[j].revents = 0;
3632 if (writefds)
3633 for (i = 0; i < writefds->fd_count; i++, j++)
3635 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
3636 if (fds[j].fd == -1) goto failed;
3637 fds[j].events = POLLOUT;
3638 fds[j].revents = 0;
3640 if (exceptfds)
3641 for (i = 0; i < exceptfds->fd_count; i++, j++)
3643 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
3644 if (fds[j].fd == -1) goto failed;
3645 fds[j].events = POLLHUP;
3646 fds[j].revents = 0;
3648 return fds;
3650 failed:
3651 count = j;
3652 j = 0;
3653 if (readfds)
3654 for (i = 0; i < readfds->fd_count && j < count; i++, j++)
3655 release_sock_fd( readfds->fd_array[i], fds[j].fd );
3656 if (writefds)
3657 for (i = 0; i < writefds->fd_count && j < count; i++, j++)
3658 release_sock_fd( writefds->fd_array[i], fds[j].fd );
3659 if (exceptfds)
3660 for (i = 0; i < exceptfds->fd_count && j < count; i++, j++)
3661 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
3662 HeapFree( GetProcessHeap(), 0, fds );
3663 return NULL;
3666 /* release the file descriptor obtained in fd_sets_to_poll */
3667 /* must be called with the original fd_set arrays, before calling get_poll_results */
3668 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
3669 const WS_fd_set *exceptfds, struct pollfd *fds )
3671 unsigned int i, j = 0;
3673 if (readfds)
3675 for (i = 0; i < readfds->fd_count; i++, j++)
3676 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
3678 if (writefds)
3680 for (i = 0; i < writefds->fd_count; i++, j++)
3681 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
3683 if (exceptfds)
3685 for (i = 0; i < exceptfds->fd_count; i++, j++)
3686 if (fds[j].fd != -1)
3688 /* make sure we have a real error before releasing the fd */
3689 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
3690 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
3695 /* map the poll results back into the Windows fd sets */
3696 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
3697 const struct pollfd *fds )
3699 unsigned int i, j = 0, k, total = 0;
3701 if (readfds)
3703 for (i = k = 0; i < readfds->fd_count; i++, j++)
3704 if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
3705 readfds->fd_count = k;
3706 total += k;
3708 if (writefds)
3710 for (i = k = 0; i < writefds->fd_count; i++, j++)
3711 if ((fds[j].revents & POLLOUT) && !(fds[j].revents & POLLHUP))
3712 writefds->fd_array[k++] = writefds->fd_array[i];
3713 writefds->fd_count = k;
3714 total += k;
3716 if (exceptfds)
3718 for (i = k = 0; i < exceptfds->fd_count; i++, j++)
3719 if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
3720 exceptfds->fd_count = k;
3721 total += k;
3723 return total;
3727 /***********************************************************************
3728 * select (WS2_32.18)
3730 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
3731 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
3732 const struct WS_timeval* ws_timeout)
3734 struct pollfd *pollfds;
3735 struct timeval tv1, tv2;
3736 int torig = 0;
3737 int count, ret, timeout = -1;
3739 TRACE("read %p, write %p, excp %p timeout %p\n",
3740 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
3742 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )))
3743 return SOCKET_ERROR;
3745 if (ws_timeout)
3747 torig = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
3748 timeout = torig;
3749 gettimeofday( &tv1, 0 );
3752 while ((ret = poll( pollfds, count, timeout )) < 0)
3754 if (errno == EINTR)
3756 if (!ws_timeout) continue;
3757 gettimeofday( &tv2, 0 );
3759 tv2.tv_sec -= tv1.tv_sec;
3760 tv2.tv_usec -= tv1.tv_usec;
3761 if (tv2.tv_usec < 0)
3763 tv2.tv_usec += 1000000;
3764 tv2.tv_sec -= 1;
3767 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
3768 if (timeout <= 0) break;
3769 } else break;
3771 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
3773 if (ret == -1) SetLastError(wsaErrno());
3774 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
3775 HeapFree( GetProcessHeap(), 0, pollfds );
3776 return ret;
3779 /* helper to send completion messages for client-only i/o operation case */
3780 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
3781 ULONG Information )
3783 SERVER_START_REQ( add_fd_completion )
3785 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
3786 req->cvalue = CompletionValue;
3787 req->status = CompletionStatus;
3788 req->information = Information;
3789 wine_server_call( req );
3791 SERVER_END_REQ;
3795 /***********************************************************************
3796 * send (WS2_32.19)
3798 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
3800 DWORD n;
3801 WSABUF wsabuf;
3803 wsabuf.len = len;
3804 wsabuf.buf = (char*) buf;
3806 if ( WS2_sendto( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
3807 return SOCKET_ERROR;
3808 else
3809 return n;
3812 /***********************************************************************
3813 * WSASend (WS2_32.72)
3815 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3816 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
3817 LPWSAOVERLAPPED lpOverlapped,
3818 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3820 return WS2_sendto( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
3821 NULL, 0, lpOverlapped, lpCompletionRoutine );
3824 /***********************************************************************
3825 * WSASendDisconnect (WS2_32.73)
3827 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
3829 return WS_shutdown( s, SD_SEND );
3833 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3834 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
3835 const struct WS_sockaddr *to, int tolen,
3836 LPWSAOVERLAPPED lpOverlapped,
3837 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3839 unsigned int i, options;
3840 int n, fd, err;
3841 struct ws2_async *wsa = NULL;
3842 int totalLength = 0;
3843 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
3844 DWORD bytes_sent;
3846 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
3847 s, lpBuffers, dwBufferCount, dwFlags,
3848 to, tolen, lpOverlapped, lpCompletionRoutine);
3850 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
3851 TRACE( "fd=%d, options=%x\n", fd, options );
3853 if ( fd == -1 ) return SOCKET_ERROR;
3855 if (!lpOverlapped && !lpNumberOfBytesSent)
3857 err = WSAEFAULT;
3858 goto error;
3860 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
3862 err = WSAEFAULT;
3863 goto error;
3866 wsa->hSocket = SOCKET2HANDLE(s);
3867 wsa->addr = (struct WS_sockaddr *)to;
3868 wsa->addrlen.val = tolen;
3869 wsa->flags = dwFlags;
3870 wsa->lpFlags = &wsa->flags;
3871 wsa->control = NULL;
3872 wsa->n_iovecs = dwBufferCount;
3873 wsa->first_iovec = 0;
3874 for ( i = 0; i < dwBufferCount; i++ )
3876 wsa->iovec[i].iov_base = lpBuffers[i].buf;
3877 wsa->iovec[i].iov_len = lpBuffers[i].len;
3878 totalLength += lpBuffers[i].len;
3881 for (;;)
3883 n = WS2_send( fd, wsa );
3884 if (n != -1 || errno != EINTR) break;
3886 if (n == -1 && errno != EAGAIN)
3888 err = wsaErrno();
3889 goto error;
3892 if ((lpOverlapped || lpCompletionRoutine) &&
3893 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
3895 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
3897 wsa->user_overlapped = lpOverlapped;
3898 wsa->completion_func = lpCompletionRoutine;
3899 release_sock_fd( s, fd );
3901 if (n == -1 || n < totalLength)
3903 iosb->u.Status = STATUS_PENDING;
3904 iosb->Information = n == -1 ? 0 : n;
3906 SERVER_START_REQ( register_async )
3908 req->type = ASYNC_TYPE_WRITE;
3909 req->async.handle = wine_server_obj_handle( wsa->hSocket );
3910 req->async.callback = wine_server_client_ptr( WS2_async_send );
3911 req->async.iosb = wine_server_client_ptr( iosb );
3912 req->async.arg = wine_server_client_ptr( wsa );
3913 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
3914 req->async.cvalue = cvalue;
3915 err = wine_server_call( req );
3917 SERVER_END_REQ;
3919 /* Enable the event only after starting the async. The server will deliver it as soon as
3920 the async is done. */
3921 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
3923 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
3924 WSASetLastError( NtStatusToWSAError( err ));
3925 return SOCKET_ERROR;
3928 iosb->u.Status = STATUS_SUCCESS;
3929 iosb->Information = n;
3930 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = n;
3931 if (!wsa->completion_func)
3933 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
3934 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
3935 HeapFree( GetProcessHeap(), 0, wsa );
3937 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
3938 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
3939 WSASetLastError(0);
3940 return 0;
3943 if ( _is_blocking(s) )
3945 /* On a blocking non-overlapped stream socket,
3946 * sending blocks until the entire buffer is sent. */
3947 DWORD timeout_start = GetTickCount();
3949 bytes_sent = n == -1 ? 0 : n;
3951 while (wsa->first_iovec < wsa->n_iovecs)
3953 struct pollfd pfd;
3954 int timeout = GET_SNDTIMEO(fd);
3956 if (timeout != -1)
3958 timeout -= GetTickCount() - timeout_start;
3959 if (timeout < 0) timeout = 0;
3962 pfd.fd = fd;
3963 pfd.events = POLLOUT;
3965 if (!timeout || !poll( &pfd, 1, timeout ))
3967 err = WSAETIMEDOUT;
3968 goto error; /* msdn says a timeout in send is fatal */
3971 n = WS2_send( fd, wsa );
3972 if (n == -1 && errno != EAGAIN && errno != EINTR)
3974 err = wsaErrno();
3975 goto error;
3978 if (n >= 0)
3979 bytes_sent += n;
3982 else /* non-blocking */
3984 if (n < totalLength)
3985 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
3986 if (n == -1)
3988 err = WSAEWOULDBLOCK;
3989 goto error;
3991 bytes_sent = n;
3994 TRACE(" -> %i bytes\n", bytes_sent);
3996 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = bytes_sent;
3997 HeapFree( GetProcessHeap(), 0, wsa );
3998 release_sock_fd( s, fd );
3999 WSASetLastError(0);
4000 return 0;
4002 error:
4003 HeapFree( GetProcessHeap(), 0, wsa );
4004 release_sock_fd( s, fd );
4005 WARN(" -> ERROR %d\n", err);
4006 WSASetLastError(err);
4007 return SOCKET_ERROR;
4010 /***********************************************************************
4011 * WSASendTo (WS2_32.74)
4013 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4014 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4015 const struct WS_sockaddr *to, int tolen,
4016 LPWSAOVERLAPPED lpOverlapped,
4017 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4019 return WS2_sendto( s, lpBuffers, dwBufferCount,
4020 lpNumberOfBytesSent, dwFlags,
4021 to, tolen,
4022 lpOverlapped, lpCompletionRoutine );
4025 /***********************************************************************
4026 * sendto (WS2_32.20)
4028 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
4029 const struct WS_sockaddr *to, int tolen)
4031 DWORD n;
4032 WSABUF wsabuf;
4034 wsabuf.len = len;
4035 wsabuf.buf = (char*) buf;
4037 if ( WS2_sendto(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
4038 return SOCKET_ERROR;
4039 else
4040 return n;
4043 /***********************************************************************
4044 * setsockopt (WS2_32.21)
4046 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
4047 const char *optval, int optlen)
4049 int fd;
4050 int woptval;
4051 struct linger linger;
4052 struct timeval tval;
4054 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
4055 s, level, optname, optval, optlen);
4057 /* some broken apps pass the value directly instead of a pointer to it */
4058 if(optlen && IS_INTRESOURCE(optval))
4060 SetLastError(WSAEFAULT);
4061 return SOCKET_ERROR;
4064 switch(level)
4066 case WS_SOL_SOCKET:
4067 switch(optname)
4069 /* Some options need some conversion before they can be sent to
4070 * setsockopt. The conversions are done here, then they will fall though
4071 * to the general case. Special options that are not passed to
4072 * setsockopt follow below that.*/
4074 case WS_SO_DONTLINGER:
4075 if (!optval)
4077 SetLastError(WSAEFAULT);
4078 return SOCKET_ERROR;
4080 linger.l_onoff = *((const int*)optval) ? 0: 1;
4081 linger.l_linger = 0;
4082 level = SOL_SOCKET;
4083 optname = SO_LINGER;
4084 optval = (char*)&linger;
4085 optlen = sizeof(struct linger);
4086 break;
4088 case WS_SO_LINGER:
4089 if (!optval)
4091 SetLastError(WSAEFAULT);
4092 return SOCKET_ERROR;
4094 linger.l_onoff = ((LINGER*)optval)->l_onoff;
4095 linger.l_linger = ((LINGER*)optval)->l_linger;
4096 level = SOL_SOCKET;
4097 optname = SO_LINGER;
4098 optval = (char*)&linger;
4099 optlen = sizeof(struct linger);
4100 break;
4102 case WS_SO_RCVBUF:
4103 if (*(const int*)optval < 2048)
4105 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
4106 return 0;
4108 /* Fall through */
4110 /* The options listed here don't need any special handling. Thanks to
4111 * the conversion happening above, options from there will fall through
4112 * to this, too.*/
4113 case WS_SO_ACCEPTCONN:
4114 case WS_SO_BROADCAST:
4115 case WS_SO_ERROR:
4116 case WS_SO_KEEPALIVE:
4117 case WS_SO_OOBINLINE:
4118 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
4119 * however, using it the BSD way fixes bug 8513 and seems to be what
4120 * most programmers assume, anyway */
4121 case WS_SO_REUSEADDR:
4122 case WS_SO_SNDBUF:
4123 case WS_SO_TYPE:
4124 convert_sockopt(&level, &optname);
4125 break;
4127 /* SO_DEBUG is a privileged operation, ignore it. */
4128 case WS_SO_DEBUG:
4129 TRACE("Ignoring SO_DEBUG\n");
4130 return 0;
4132 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
4133 * socket. According to MSDN, this option is silently ignored.*/
4134 case WS_SO_DONTROUTE:
4135 TRACE("Ignoring SO_DONTROUTE\n");
4136 return 0;
4138 /* Stops two sockets from being bound to the same port. Always happens
4139 * on unix systems, so just drop it. */
4140 case WS_SO_EXCLUSIVEADDRUSE:
4141 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
4142 return 0;
4144 /* After a ConnectEx call succeeds, the socket can't be used with half of the
4145 * normal winsock functions on windows. We don't have that problem. */
4146 case WS_SO_UPDATE_CONNECT_CONTEXT:
4147 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
4148 return 0;
4150 /* After a AcceptEx 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_ACCEPT_CONTEXT:
4153 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
4154 return 0;
4156 /* SO_OPENTYPE does not require a valid socket handle. */
4157 case WS_SO_OPENTYPE:
4158 if (!optlen || optlen < sizeof(int) || !optval)
4160 SetLastError(WSAEFAULT);
4161 return SOCKET_ERROR;
4163 get_per_thread_data()->opentype = *(const int *)optval;
4164 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
4165 return 0;
4167 #ifdef SO_RCVTIMEO
4168 case WS_SO_RCVTIMEO:
4169 #endif
4170 #ifdef SO_SNDTIMEO
4171 case WS_SO_SNDTIMEO:
4172 #endif
4173 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
4174 if (optval && optlen == sizeof(UINT32)) {
4175 /* WinSock passes milliseconds instead of struct timeval */
4176 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
4177 tval.tv_sec = *(const UINT32*)optval / 1000;
4178 /* min of 500 milliseconds */
4179 if (tval.tv_sec == 0 && tval.tv_usec && tval.tv_usec < 500000)
4180 tval.tv_usec = 500000;
4181 optlen = sizeof(struct timeval);
4182 optval = (char*)&tval;
4183 } else if (optlen == sizeof(struct timeval)) {
4184 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
4185 } else {
4186 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
4187 return 0;
4189 convert_sockopt(&level, &optname);
4190 break;
4191 #endif
4193 default:
4194 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
4195 SetLastError(WSAENOPROTOOPT);
4196 return SOCKET_ERROR;
4198 break; /* case WS_SOL_SOCKET */
4200 #ifdef HAVE_IPX
4201 case NSPROTO_IPX:
4202 switch(optname)
4204 case IPX_PTYPE:
4205 fd = get_sock_fd( s, 0, NULL );
4206 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", *(const int*)optval, fd);
4208 /* We try to set the ipx type on ipx socket level. */
4209 #ifdef SOL_IPX
4210 if(setsockopt(fd, SOL_IPX, IPX_TYPE, optval, optlen) == -1)
4212 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
4213 release_sock_fd( s, fd );
4214 return SOCKET_ERROR;
4216 #else
4218 struct ipx val;
4219 /* Should we retrieve val using a getsockopt call and then
4220 * set the modified one? */
4221 val.ipx_pt = *optval;
4222 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
4224 #endif
4225 release_sock_fd( s, fd );
4226 return 0;
4228 case IPX_FILTERPTYPE:
4229 /* Sets the receive filter packet type, at the moment we don't support it */
4230 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
4231 /* Returning 0 is better for now than returning a SOCKET_ERROR */
4232 return 0;
4234 default:
4235 FIXME("opt_name:%x\n", optname);
4236 return SOCKET_ERROR;
4238 break; /* case NSPROTO_IPX */
4239 #endif
4241 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
4242 case WS_IPPROTO_TCP:
4243 switch(optname)
4245 case WS_TCP_NODELAY:
4246 convert_sockopt(&level, &optname);
4247 break;
4248 default:
4249 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
4250 return SOCKET_ERROR;
4252 break;
4254 case WS_IPPROTO_IP:
4255 switch(optname)
4257 case WS_IP_ADD_MEMBERSHIP:
4258 case WS_IP_DROP_MEMBERSHIP:
4259 #ifdef IP_HDRINCL
4260 case WS_IP_HDRINCL:
4261 #endif
4262 case WS_IP_MULTICAST_IF:
4263 case WS_IP_MULTICAST_LOOP:
4264 case WS_IP_MULTICAST_TTL:
4265 case WS_IP_OPTIONS:
4266 #ifdef IP_PKTINFO
4267 case WS_IP_PKTINFO:
4268 #endif
4269 case WS_IP_TOS:
4270 case WS_IP_TTL:
4271 convert_sockopt(&level, &optname);
4272 break;
4273 case WS_IP_DONTFRAGMENT:
4274 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
4275 return 0;
4276 default:
4277 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
4278 return SOCKET_ERROR;
4280 break;
4282 case WS_IPPROTO_IPV6:
4283 switch(optname)
4285 #ifdef IPV6_ADD_MEMBERSHIP
4286 case WS_IPV6_ADD_MEMBERSHIP:
4287 #endif
4288 #ifdef IPV6_DROP_MEMBERSHIP
4289 case WS_IPV6_DROP_MEMBERSHIP:
4290 #endif
4291 case WS_IPV6_MULTICAST_IF:
4292 case WS_IPV6_MULTICAST_HOPS:
4293 case WS_IPV6_MULTICAST_LOOP:
4294 case WS_IPV6_UNICAST_HOPS:
4295 case WS_IPV6_V6ONLY:
4296 convert_sockopt(&level, &optname);
4297 break;
4298 case WS_IPV6_DONTFRAG:
4299 FIXME("IPV6_DONTFRAG is silently ignored!\n");
4300 return 0;
4301 default:
4302 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
4303 return SOCKET_ERROR;
4305 break;
4307 default:
4308 WARN("Unknown level: 0x%08x\n", level);
4309 SetLastError(WSAEINVAL);
4310 return SOCKET_ERROR;
4311 } /* end switch(level) */
4313 /* avoid endianness issues if argument is a 16-bit int */
4314 if (optval && optlen < sizeof(int))
4316 woptval= *((const INT16 *) optval);
4317 optval= (char*) &woptval;
4318 optlen=sizeof(int);
4320 fd = get_sock_fd( s, 0, NULL );
4321 if (fd == -1) return SOCKET_ERROR;
4323 if (setsockopt(fd, level, optname, optval, optlen) == 0)
4325 release_sock_fd( s, fd );
4326 return 0;
4328 TRACE("Setting socket error, %d\n", wsaErrno());
4329 SetLastError(wsaErrno());
4330 release_sock_fd( s, fd );
4332 return SOCKET_ERROR;
4335 /***********************************************************************
4336 * shutdown (WS2_32.22)
4338 int WINAPI WS_shutdown(SOCKET s, int how)
4340 int fd, err = WSAENOTSOCK;
4341 unsigned int options, clear_flags = 0;
4343 fd = get_sock_fd( s, 0, &options );
4344 TRACE("socket %04lx, how %i %x\n", s, how, options );
4346 if (fd == -1)
4347 return SOCKET_ERROR;
4349 switch( how )
4351 case 0: /* drop receives */
4352 clear_flags |= FD_READ;
4353 break;
4354 case 1: /* drop sends */
4355 clear_flags |= FD_WRITE;
4356 break;
4357 case 2: /* drop all */
4358 clear_flags |= FD_READ|FD_WRITE;
4359 /*fall through */
4360 default:
4361 clear_flags |= FD_WINE_LISTENING;
4364 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
4366 switch ( how )
4368 case SD_RECEIVE:
4369 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
4370 break;
4371 case SD_SEND:
4372 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
4373 break;
4374 case SD_BOTH:
4375 default:
4376 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
4377 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
4378 break;
4380 if (err) goto error;
4382 else /* non-overlapped mode */
4384 if ( shutdown( fd, how ) )
4386 err = wsaErrno();
4387 goto error;
4391 release_sock_fd( s, fd );
4392 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
4393 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
4394 return 0;
4396 error:
4397 release_sock_fd( s, fd );
4398 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
4399 WSASetLastError( err );
4400 return SOCKET_ERROR;
4403 /***********************************************************************
4404 * socket (WS2_32.23)
4406 SOCKET WINAPI WS_socket(int af, int type, int protocol)
4408 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
4410 return WSASocketA( af, type, protocol, NULL, 0,
4411 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
4415 /***********************************************************************
4416 * gethostbyaddr (WS2_32.51)
4418 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
4420 struct WS_hostent *retval = NULL;
4421 struct hostent* host;
4423 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4424 char *extrabuf;
4425 int ebufsize=1024;
4426 struct hostent hostentry;
4427 int locerr=ENOBUFS;
4428 host = NULL;
4429 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
4430 while(extrabuf) {
4431 int res = gethostbyaddr_r(addr, len, type,
4432 &hostentry, extrabuf, ebufsize, &host, &locerr);
4433 if( res != ERANGE) break;
4434 ebufsize *=2;
4435 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
4437 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
4438 #else
4439 EnterCriticalSection( &csWSgetXXXbyYYY );
4440 host = gethostbyaddr(addr, len, type);
4441 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
4442 #endif
4443 if( host != NULL ) retval = WS_dup_he(host);
4444 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4445 HeapFree(GetProcessHeap(),0,extrabuf);
4446 #else
4447 LeaveCriticalSection( &csWSgetXXXbyYYY );
4448 #endif
4449 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
4450 return retval;
4453 /***********************************************************************
4454 * WS_get_local_ips (INTERNAL)
4456 * Returns the list of local IP addresses by going through the network
4457 * adapters and using the local routing table to sort the addresses
4458 * from highest routing priority to lowest routing priority. This
4459 * functionality is inferred from the description for obtaining local
4460 * IP addresses given in the Knowledge Base Article Q160215.
4462 * Please note that the returned hostent is only freed when the thread
4463 * closes and is replaced if another hostent is requested.
4465 static struct WS_hostent* WS_get_local_ips( char *hostname )
4467 int last_metric, numroutes = 0, i, j;
4468 PIP_ADAPTER_INFO adapters = NULL, k;
4469 struct WS_hostent *hostlist = NULL;
4470 PMIB_IPFORWARDTABLE routes = NULL;
4471 struct route *route_addrs = NULL;
4472 DWORD adap_size, route_size;
4474 /* Obtain the size of the adapter list and routing table, also allocate memory */
4475 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
4476 return NULL;
4477 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
4478 return NULL;
4479 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
4480 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
4481 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
4482 if (adapters == NULL || routes == NULL || route_addrs == NULL)
4483 goto cleanup;
4484 /* Obtain the adapter list and the full routing table */
4485 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
4486 goto cleanup;
4487 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
4488 goto cleanup;
4489 /* Store the interface associated with each route */
4490 for (i = 0; i < routes->dwNumEntries; i++)
4492 IF_INDEX ifindex;
4493 DWORD ifmetric, exists = FALSE;
4495 if (routes->table[i].u1.ForwardType != MIB_IPROUTE_TYPE_DIRECT)
4496 continue;
4497 ifindex = routes->table[i].dwForwardIfIndex;
4498 ifmetric = routes->table[i].dwForwardMetric1;
4499 /* Only store the lowest valued metric for an interface */
4500 for (j = 0; j < numroutes; j++)
4502 if (route_addrs[j].interface == ifindex)
4504 if (route_addrs[j].metric > ifmetric)
4505 route_addrs[j].metric = ifmetric;
4506 exists = TRUE;
4509 if (exists)
4510 continue;
4511 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
4512 if (route_addrs == NULL)
4513 goto cleanup; /* Memory allocation error, fail gracefully */
4514 route_addrs[numroutes].interface = ifindex;
4515 route_addrs[numroutes].metric = ifmetric;
4516 /* If no IP is found in the next step (for whatever reason)
4517 * then fall back to the magic loopback address.
4519 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
4520 numroutes++;
4522 if (numroutes == 0)
4523 goto cleanup; /* No routes, fall back to the Magic IP */
4524 /* Find the IP address associated with each found interface */
4525 for (i = 0; i < numroutes; i++)
4527 for (k = adapters; k != NULL; k = k->Next)
4529 char *ip = k->IpAddressList.IpAddress.String;
4531 if (route_addrs[i].interface == k->Index)
4532 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
4535 /* Allocate a hostent and enough memory for all the IPs,
4536 * including the NULL at the end of the list.
4538 hostlist = WS_create_he(hostname, 1, numroutes+1, TRUE);
4539 if (hostlist == NULL)
4540 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
4541 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
4542 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
4543 hostlist->h_addrtype = AF_INET;
4544 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
4545 /* Reorder the entries when placing them in the host list, Windows expects
4546 * the IP list in order from highest priority to lowest (the critical thing
4547 * is that most applications expect the first IP to be the default route).
4549 last_metric = -1;
4550 for (i = 0; i < numroutes; i++)
4552 struct in_addr addr;
4553 int metric = 0xFFFF;
4555 memcpy(&addr, magic_loopback_addr, 4);
4556 for (j = 0; j < numroutes; j++)
4558 int this_metric = route_addrs[j].metric;
4560 if (this_metric > last_metric && this_metric < metric)
4562 addr = route_addrs[j].addr;
4563 metric = this_metric;
4566 last_metric = metric;
4567 (*(struct in_addr *) hostlist->h_addr_list[i]) = addr;
4570 /* Cleanup all allocated memory except the address list,
4571 * the address list is used by the calling app.
4573 cleanup:
4574 HeapFree(GetProcessHeap(), 0, route_addrs);
4575 HeapFree(GetProcessHeap(), 0, adapters);
4576 HeapFree(GetProcessHeap(), 0, routes);
4577 return hostlist;
4580 /***********************************************************************
4581 * gethostbyname (WS2_32.52)
4583 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
4585 struct WS_hostent *retval = NULL;
4586 struct hostent* host;
4587 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4588 char *extrabuf;
4589 int ebufsize=1024;
4590 struct hostent hostentry;
4591 int locerr = ENOBUFS;
4592 #endif
4593 char hostname[100];
4594 if(!num_startup) {
4595 SetLastError(WSANOTINITIALISED);
4596 return NULL;
4598 if( gethostname( hostname, 100) == -1) {
4599 SetLastError( WSAENOBUFS); /* appropriate ? */
4600 return retval;
4602 if( !name || !name[0]) {
4603 name = hostname;
4605 /* If the hostname of the local machine is requested then return the
4606 * complete list of local IP addresses */
4607 if(strcmp(name, hostname) == 0)
4608 retval = WS_get_local_ips(hostname);
4609 /* If any other hostname was requested (or the routing table lookup failed)
4610 * then return the IP found by the host OS */
4611 if(retval == NULL)
4613 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4614 host = NULL;
4615 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
4616 while(extrabuf) {
4617 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
4618 if( res != ERANGE) break;
4619 ebufsize *=2;
4620 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
4622 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
4623 #else
4624 EnterCriticalSection( &csWSgetXXXbyYYY );
4625 host = gethostbyname(name);
4626 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
4627 #endif
4628 if (host) retval = WS_dup_he(host);
4629 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4630 HeapFree(GetProcessHeap(),0,extrabuf);
4631 #else
4632 LeaveCriticalSection( &csWSgetXXXbyYYY );
4633 #endif
4635 if (retval && retval->h_addr_list[0][0] == 127 &&
4636 strcmp(name, "localhost") != 0)
4638 /* hostname != "localhost" but has loopback address. replace by our
4639 * special address.*/
4640 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
4642 TRACE( "%s ret %p\n", debugstr_a(name), retval );
4643 return retval;
4647 /***********************************************************************
4648 * getprotobyname (WS2_32.53)
4650 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
4652 struct WS_protoent* retval = NULL;
4653 #ifdef HAVE_GETPROTOBYNAME
4654 struct protoent* proto;
4655 EnterCriticalSection( &csWSgetXXXbyYYY );
4656 if( (proto = getprotobyname(name)) != NULL )
4658 retval = WS_dup_pe(proto);
4660 else {
4661 MESSAGE("protocol %s not found; You might want to add "
4662 "this to /etc/protocols\n", debugstr_a(name) );
4663 SetLastError(WSANO_DATA);
4665 LeaveCriticalSection( &csWSgetXXXbyYYY );
4666 #endif
4667 TRACE( "%s ret %p\n", debugstr_a(name), retval );
4668 return retval;
4672 /***********************************************************************
4673 * getprotobynumber (WS2_32.54)
4675 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
4677 struct WS_protoent* retval = NULL;
4678 #ifdef HAVE_GETPROTOBYNUMBER
4679 struct protoent* proto;
4680 EnterCriticalSection( &csWSgetXXXbyYYY );
4681 if( (proto = getprotobynumber(number)) != NULL )
4683 retval = WS_dup_pe(proto);
4685 else {
4686 MESSAGE("protocol number %d not found; You might want to add "
4687 "this to /etc/protocols\n", number );
4688 SetLastError(WSANO_DATA);
4690 LeaveCriticalSection( &csWSgetXXXbyYYY );
4691 #endif
4692 TRACE("%i ret %p\n", number, retval);
4693 return retval;
4697 /***********************************************************************
4698 * getservbyname (WS2_32.55)
4700 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
4702 struct WS_servent* retval = NULL;
4703 struct servent* serv;
4704 char *name_str;
4705 char *proto_str = NULL;
4707 if (!(name_str = strdup_lower(name))) return NULL;
4709 if (proto && *proto)
4711 if (!(proto_str = strdup_lower(proto)))
4713 HeapFree( GetProcessHeap(), 0, name_str );
4714 return NULL;
4718 EnterCriticalSection( &csWSgetXXXbyYYY );
4719 serv = getservbyname(name_str, proto_str);
4720 if( serv != NULL )
4722 retval = WS_dup_se(serv);
4724 else SetLastError(WSANO_DATA);
4725 LeaveCriticalSection( &csWSgetXXXbyYYY );
4726 HeapFree( GetProcessHeap(), 0, proto_str );
4727 HeapFree( GetProcessHeap(), 0, name_str );
4728 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
4729 return retval;
4732 /***********************************************************************
4733 * freeaddrinfo (WS2_32.@)
4735 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
4737 while (res) {
4738 struct WS_addrinfo *next;
4740 HeapFree(GetProcessHeap(),0,res->ai_canonname);
4741 HeapFree(GetProcessHeap(),0,res->ai_addr);
4742 next = res->ai_next;
4743 HeapFree(GetProcessHeap(),0,res);
4744 res = next;
4748 /* helper functions for getaddrinfo()/getnameinfo() */
4749 static int convert_aiflag_w2u(int winflags) {
4750 unsigned int i;
4751 int unixflags = 0;
4753 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
4754 if (ws_aiflag_map[i][0] & winflags) {
4755 unixflags |= ws_aiflag_map[i][1];
4756 winflags &= ~ws_aiflag_map[i][0];
4758 if (winflags)
4759 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
4760 return unixflags;
4763 static int convert_niflag_w2u(int winflags) {
4764 unsigned int i;
4765 int unixflags = 0;
4767 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
4768 if (ws_niflag_map[i][0] & winflags) {
4769 unixflags |= ws_niflag_map[i][1];
4770 winflags &= ~ws_niflag_map[i][0];
4772 if (winflags)
4773 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
4774 return unixflags;
4777 static int convert_aiflag_u2w(int unixflags) {
4778 unsigned int i;
4779 int winflags = 0;
4781 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
4782 if (ws_aiflag_map[i][1] & unixflags) {
4783 winflags |= ws_aiflag_map[i][0];
4784 unixflags &= ~ws_aiflag_map[i][1];
4786 if (unixflags) /* will warn usually */
4787 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
4788 return winflags;
4791 static int convert_eai_u2w(int unixret) {
4792 int i;
4794 for (i=0;ws_eai_map[i][0];i++)
4795 if (ws_eai_map[i][1] == unixret)
4796 return ws_eai_map[i][0];
4797 return unixret;
4800 static char *get_hostname(void)
4802 char *ret;
4803 DWORD size = 0;
4805 GetComputerNameExA( ComputerNamePhysicalDnsHostname, NULL, &size );
4806 if (GetLastError() != ERROR_MORE_DATA) return NULL;
4807 if (!(ret = HeapAlloc( GetProcessHeap(), 0, size ))) return NULL;
4808 if (!GetComputerNameExA( ComputerNamePhysicalDnsHostname, ret, &size ))
4810 HeapFree( GetProcessHeap(), 0, ret );
4811 return NULL;
4813 return ret;
4816 /***********************************************************************
4817 * getaddrinfo (WS2_32.@)
4819 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
4821 #ifdef HAVE_GETADDRINFO
4822 struct addrinfo *unixaires = NULL;
4823 int result;
4824 struct addrinfo unixhints, *punixhints = NULL;
4825 char *hostname = NULL;
4826 const char *node;
4828 if (!nodename && !servname) return WSAHOST_NOT_FOUND;
4830 if (!nodename)
4831 node = NULL;
4832 else if (!nodename[0])
4834 node = hostname = get_hostname();
4835 if (!node) return WSA_NOT_ENOUGH_MEMORY;
4837 else
4838 node = nodename;
4840 if (hints) {
4841 punixhints = &unixhints;
4843 memset(&unixhints, 0, sizeof(unixhints));
4844 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
4845 if (hints->ai_family == 0) /* wildcard, specific to getaddrinfo() */
4846 punixhints->ai_family = 0;
4847 else
4848 punixhints->ai_family = convert_af_w2u(hints->ai_family);
4849 if (hints->ai_socktype == 0) /* wildcard, specific to getaddrinfo() */
4850 punixhints->ai_socktype = 0;
4851 else
4852 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
4853 if (hints->ai_protocol == 0) /* wildcard, specific to getaddrinfo() */
4854 punixhints->ai_protocol = 0;
4855 else
4856 punixhints->ai_protocol = convert_proto_w2u(hints->ai_protocol);
4859 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
4860 result = getaddrinfo(node, servname, punixhints, &unixaires);
4862 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
4863 HeapFree(GetProcessHeap(), 0, hostname);
4865 if (!result) {
4866 struct addrinfo *xuai = unixaires;
4867 struct WS_addrinfo **xai = res;
4869 *xai = NULL;
4870 while (xuai) {
4871 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
4872 int len;
4874 if (!ai)
4875 goto outofmem;
4877 *xai = ai;xai = &ai->ai_next;
4878 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
4879 ai->ai_family = convert_af_u2w(xuai->ai_family);
4880 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
4881 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
4882 if (xuai->ai_canonname) {
4883 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
4884 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
4885 if (!ai->ai_canonname)
4886 goto outofmem;
4887 strcpy(ai->ai_canonname,xuai->ai_canonname);
4889 len = xuai->ai_addrlen;
4890 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
4891 if (!ai->ai_addr)
4892 goto outofmem;
4893 ai->ai_addrlen = len;
4894 do {
4895 int winlen = ai->ai_addrlen;
4897 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
4898 ai->ai_addrlen = winlen;
4899 break;
4901 len = 2*len;
4902 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
4903 if (!ai->ai_addr)
4904 goto outofmem;
4905 ai->ai_addrlen = len;
4906 } while (1);
4907 xuai = xuai->ai_next;
4909 freeaddrinfo(unixaires);
4910 } else {
4911 result = convert_eai_u2w(result);
4912 *res = NULL;
4914 return result;
4916 outofmem:
4917 if (*res) WS_freeaddrinfo(*res);
4918 if (unixaires) freeaddrinfo(unixaires);
4919 *res = NULL;
4920 return WSA_NOT_ENOUGH_MEMORY;
4921 #else
4922 FIXME("getaddrinfo() failed, not found during buildtime.\n");
4923 return EAI_FAIL;
4924 #endif
4927 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
4929 struct WS_addrinfoW *ret;
4931 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
4932 ret->ai_flags = ai->ai_flags;
4933 ret->ai_family = ai->ai_family;
4934 ret->ai_socktype = ai->ai_socktype;
4935 ret->ai_protocol = ai->ai_protocol;
4936 ret->ai_addrlen = ai->ai_addrlen;
4937 ret->ai_canonname = NULL;
4938 ret->ai_addr = NULL;
4939 ret->ai_next = NULL;
4940 if (ai->ai_canonname)
4942 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
4943 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
4945 HeapFree(GetProcessHeap(), 0, ret);
4946 return NULL;
4948 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
4950 if (ai->ai_addr)
4952 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
4954 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
4955 HeapFree(GetProcessHeap(), 0, ret);
4956 return NULL;
4958 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
4960 return ret;
4963 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
4965 struct WS_addrinfoW *ret, *infoW;
4967 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
4968 while (info->ai_next)
4970 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
4972 FreeAddrInfoW(ret);
4973 return NULL;
4975 infoW = infoW->ai_next;
4976 info = info->ai_next;
4978 return ret;
4981 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
4983 struct WS_addrinfo *ret;
4985 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
4986 ret->ai_flags = ai->ai_flags;
4987 ret->ai_family = ai->ai_family;
4988 ret->ai_socktype = ai->ai_socktype;
4989 ret->ai_protocol = ai->ai_protocol;
4990 ret->ai_addrlen = ai->ai_addrlen;
4991 ret->ai_canonname = NULL;
4992 ret->ai_addr = NULL;
4993 ret->ai_next = NULL;
4994 if (ai->ai_canonname)
4996 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
4997 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
4999 HeapFree(GetProcessHeap(), 0, ret);
5000 return NULL;
5002 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
5004 if (ai->ai_addr)
5006 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
5008 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
5009 HeapFree(GetProcessHeap(), 0, ret);
5010 return NULL;
5012 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
5014 return ret;
5017 /***********************************************************************
5018 * GetAddrInfoW (WS2_32.@)
5020 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
5022 int ret, len;
5023 char *nodenameA = NULL, *servnameA = NULL;
5024 struct WS_addrinfo *resA, *hintsA = NULL;
5026 if (nodename)
5028 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
5029 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
5030 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
5032 if (servname)
5034 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
5035 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
5037 HeapFree(GetProcessHeap(), 0, nodenameA);
5038 return EAI_MEMORY;
5040 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
5043 if (hints) hintsA = addrinfo_WtoA(hints);
5044 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
5045 WS_freeaddrinfo(hintsA);
5047 if (!ret)
5049 *res = addrinfo_list_AtoW(resA);
5050 WS_freeaddrinfo(resA);
5053 HeapFree(GetProcessHeap(), 0, nodenameA);
5054 HeapFree(GetProcessHeap(), 0, servnameA);
5055 return ret;
5058 /***********************************************************************
5059 * FreeAddrInfoW (WS2_32.@)
5061 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
5063 while (ai)
5065 ADDRINFOW *next;
5066 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
5067 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
5068 next = ai->ai_next;
5069 HeapFree(GetProcessHeap(), 0, ai);
5070 ai = next;
5074 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
5075 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
5077 #ifdef HAVE_GETNAMEINFO
5078 int ret;
5079 union generic_unix_sockaddr sa_u;
5080 unsigned int size;
5082 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
5083 serv, servlen, flags);
5085 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
5086 if (!size)
5088 WSASetLastError(WSAEFAULT);
5089 return WSA_NOT_ENOUGH_MEMORY;
5091 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
5092 return convert_eai_u2w(ret);
5093 #else
5094 FIXME("getnameinfo() failed, not found during buildtime.\n");
5095 return EAI_FAIL;
5096 #endif
5099 int WINAPI GetNameInfoW(const SOCKADDR *sa, WS_socklen_t salen, PWCHAR host,
5100 DWORD hostlen, PWCHAR serv, DWORD servlen, INT flags)
5102 int ret;
5103 char *hostA = NULL, *servA = NULL;
5105 if (host && (!(hostA = HeapAlloc(GetProcessHeap(), 0, hostlen)))) return EAI_MEMORY;
5106 if (serv && (!(servA = HeapAlloc(GetProcessHeap(), 0, servlen))))
5108 HeapFree(GetProcessHeap(), 0, hostA);
5109 return EAI_MEMORY;
5112 ret = WS_getnameinfo(sa, salen, hostA, hostlen, servA, servlen, flags);
5113 if (!ret)
5115 if (host) MultiByteToWideChar(CP_ACP, 0, hostA, -1, host, hostlen);
5116 if (serv) MultiByteToWideChar(CP_ACP, 0, servA, -1, serv, servlen);
5119 HeapFree(GetProcessHeap(), 0, hostA);
5120 HeapFree(GetProcessHeap(), 0, servA);
5121 return ret;
5124 /***********************************************************************
5125 * getservbyport (WS2_32.56)
5127 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
5129 struct WS_servent* retval = NULL;
5130 #ifdef HAVE_GETSERVBYPORT
5131 struct servent* serv;
5132 char *proto_str = NULL;
5134 if (proto && *proto)
5136 if (!(proto_str = strdup_lower(proto))) return NULL;
5138 EnterCriticalSection( &csWSgetXXXbyYYY );
5139 if( (serv = getservbyport(port, proto_str)) != NULL ) {
5140 retval = WS_dup_se(serv);
5142 else SetLastError(WSANO_DATA);
5143 LeaveCriticalSection( &csWSgetXXXbyYYY );
5144 HeapFree( GetProcessHeap(), 0, proto_str );
5145 #endif
5146 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
5147 return retval;
5151 /***********************************************************************
5152 * gethostname (WS2_32.57)
5154 int WINAPI WS_gethostname(char *name, int namelen)
5156 TRACE("name %p, len %d\n", name, namelen);
5158 if (gethostname(name, namelen) == 0)
5160 TRACE("<- '%s'\n", name);
5161 return 0;
5163 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
5164 TRACE("<- ERROR !\n");
5165 return SOCKET_ERROR;
5169 /* ------------------------------------- Windows sockets extensions -- *
5171 * ------------------------------------------------------------------- */
5173 /***********************************************************************
5174 * WSAEnumNetworkEvents (WS2_32.36)
5176 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
5178 int ret;
5179 int i;
5180 int errors[FD_MAX_EVENTS];
5182 TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
5184 SERVER_START_REQ( get_socket_event )
5186 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5187 req->service = TRUE;
5188 req->c_event = wine_server_obj_handle( hEvent );
5189 wine_server_set_reply( req, errors, sizeof(errors) );
5190 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
5192 SERVER_END_REQ;
5193 if (!ret)
5195 for (i = 0; i < FD_MAX_EVENTS; i++)
5196 lpEvent->iErrorCode[i] = NtStatusToWSAError(errors[i]);
5197 return 0;
5199 SetLastError(WSAEINVAL);
5200 return SOCKET_ERROR;
5203 /***********************************************************************
5204 * WSAEventSelect (WS2_32.39)
5206 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
5208 int ret;
5210 TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
5212 SERVER_START_REQ( set_socket_event )
5214 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5215 req->mask = lEvent;
5216 req->event = wine_server_obj_handle( hEvent );
5217 req->window = 0;
5218 req->msg = 0;
5219 ret = wine_server_call( req );
5221 SERVER_END_REQ;
5222 if (!ret) return 0;
5223 SetLastError(WSAEINVAL);
5224 return SOCKET_ERROR;
5227 /**********************************************************************
5228 * WSAGetOverlappedResult (WS2_32.40)
5230 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
5231 LPDWORD lpcbTransfer, BOOL fWait,
5232 LPDWORD lpdwFlags )
5234 NTSTATUS status;
5236 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
5237 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
5239 if ( lpOverlapped == NULL )
5241 ERR( "Invalid pointer\n" );
5242 WSASetLastError(WSA_INVALID_PARAMETER);
5243 return FALSE;
5246 status = lpOverlapped->Internal;
5247 if (status == STATUS_PENDING)
5249 if (!fWait)
5251 SetLastError( WSA_IO_INCOMPLETE );
5252 return FALSE;
5255 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
5256 INFINITE ) == WAIT_FAILED)
5257 return FALSE;
5258 status = lpOverlapped->Internal;
5261 if ( lpcbTransfer )
5262 *lpcbTransfer = lpOverlapped->InternalHigh;
5264 if ( lpdwFlags )
5265 *lpdwFlags = lpOverlapped->u.s.Offset;
5267 if (status) SetLastError( RtlNtStatusToDosError(status) );
5268 return !status;
5272 /***********************************************************************
5273 * WSAAsyncSelect (WS2_32.101)
5275 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
5277 int ret;
5279 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
5281 SERVER_START_REQ( set_socket_event )
5283 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5284 req->mask = lEvent;
5285 req->event = 0;
5286 req->window = wine_server_user_handle( hWnd );
5287 req->msg = uMsg;
5288 ret = wine_server_call( req );
5290 SERVER_END_REQ;
5291 if (!ret) return 0;
5292 SetLastError(WSAEINVAL);
5293 return SOCKET_ERROR;
5296 /***********************************************************************
5297 * WSACreateEvent (WS2_32.31)
5300 WSAEVENT WINAPI WSACreateEvent(void)
5302 /* Create a manual-reset event, with initial state: unsignaled */
5303 TRACE("\n");
5305 return CreateEventW(NULL, TRUE, FALSE, NULL);
5308 /***********************************************************************
5309 * WSACloseEvent (WS2_32.29)
5312 BOOL WINAPI WSACloseEvent(WSAEVENT event)
5314 TRACE ("event=%p\n", event);
5316 return CloseHandle(event);
5319 /***********************************************************************
5320 * WSASocketA (WS2_32.78)
5323 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
5324 LPWSAPROTOCOL_INFOA lpProtocolInfo,
5325 GROUP g, DWORD dwFlags)
5327 INT len;
5328 WSAPROTOCOL_INFOW info;
5330 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
5331 af, type, protocol, lpProtocolInfo, g, dwFlags);
5333 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
5335 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
5336 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
5337 info.szProtocol, WSAPROTOCOL_LEN + 1);
5339 if (!len)
5341 WSASetLastError( WSAEINVAL);
5342 return SOCKET_ERROR;
5345 return WSASocketW(af, type, protocol, &info, g, dwFlags);
5348 /***********************************************************************
5349 * WSASocketW (WS2_32.79)
5352 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
5353 LPWSAPROTOCOL_INFOW lpProtocolInfo,
5354 GROUP g, DWORD dwFlags)
5356 SOCKET ret;
5359 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
5360 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
5363 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
5364 af, type, protocol, lpProtocolInfo, g, dwFlags );
5366 /* hack for WSADuplicateSocket */
5367 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
5368 ret = lpProtocolInfo->dwCatalogEntryId;
5369 TRACE("\tgot duplicate %04lx\n", ret);
5370 return ret;
5373 /* convert the socket family and type */
5374 af = convert_af_w2u(af);
5375 type = convert_socktype_w2u(type);
5377 if (lpProtocolInfo)
5379 if (af == FROM_PROTOCOL_INFO)
5380 af = lpProtocolInfo->iAddressFamily;
5381 if (type == FROM_PROTOCOL_INFO)
5382 type = lpProtocolInfo->iSocketType;
5383 if (protocol == FROM_PROTOCOL_INFO)
5384 protocol = lpProtocolInfo->iProtocol;
5387 if ( af == AF_UNSPEC) /* did they not specify the address family? */
5389 if ((protocol == IPPROTO_TCP && type == SOCK_STREAM) ||
5390 (protocol == IPPROTO_UDP && type == SOCK_DGRAM))
5392 af = AF_INET;
5394 else
5396 SetLastError(WSAEPROTOTYPE);
5397 return INVALID_SOCKET;
5401 SERVER_START_REQ( create_socket )
5403 req->family = af;
5404 req->type = type;
5405 req->protocol = protocol;
5406 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
5407 req->attributes = OBJ_INHERIT;
5408 req->flags = dwFlags;
5409 set_error( wine_server_call( req ) );
5410 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
5412 SERVER_END_REQ;
5413 if (ret)
5415 TRACE("\tcreated %04lx\n", ret );
5416 return ret;
5419 if (GetLastError() == WSAEACCES) /* raw socket denied */
5421 if (type == SOCK_RAW)
5422 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
5423 else
5424 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
5425 SetLastError(WSAESOCKTNOSUPPORT);
5428 WARN("\t\tfailed!\n");
5429 return INVALID_SOCKET;
5432 /***********************************************************************
5433 * WSAJoinLeaf (WS2_32.58)
5436 SOCKET WINAPI WSAJoinLeaf(
5437 SOCKET s,
5438 const struct WS_sockaddr *addr,
5439 int addrlen,
5440 LPWSABUF lpCallerData,
5441 LPWSABUF lpCalleeData,
5442 LPQOS lpSQOS,
5443 LPQOS lpGQOS,
5444 DWORD dwFlags)
5446 FIXME("stub.\n");
5447 return INVALID_SOCKET;
5450 /***********************************************************************
5451 * __WSAFDIsSet (WS2_32.151)
5453 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
5455 int i = set->fd_count;
5457 TRACE("(%ld,%p(%i))\n", s, set, i);
5459 while (i--)
5460 if (set->fd_array[i] == s) return 1;
5461 return 0;
5464 /***********************************************************************
5465 * WSAIsBlocking (WS2_32.114)
5467 BOOL WINAPI WSAIsBlocking(void)
5469 /* By default WinSock should set all its sockets to non-blocking mode
5470 * and poll in PeekMessage loop when processing "blocking" ones. This
5471 * function is supposed to tell if the program is in this loop. Our
5472 * blocking calls are truly blocking so we always return FALSE.
5474 * Note: It is allowed to call this function without prior WSAStartup().
5477 TRACE("\n");
5478 return FALSE;
5481 /***********************************************************************
5482 * WSACancelBlockingCall (WS2_32.113)
5484 INT WINAPI WSACancelBlockingCall(void)
5486 TRACE("\n");
5487 return 0;
5490 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
5492 FIXME("How was this called?\n");
5493 return x();
5497 /***********************************************************************
5498 * WSASetBlockingHook (WS2_32.109)
5500 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
5502 FARPROC prev = blocking_hook;
5503 blocking_hook = lpBlockFunc;
5504 TRACE("hook %p\n", lpBlockFunc);
5505 return prev;
5509 /***********************************************************************
5510 * WSAUnhookBlockingHook (WS2_32.110)
5512 INT WINAPI WSAUnhookBlockingHook(void)
5514 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
5515 return 0;
5519 /* ----------------------------------- end of API stuff */
5521 /* ----------------------------------- helper functions -
5523 * TODO: Merge WS_dup_..() stuff into one function that
5524 * would operate with a generic structure containing internal
5525 * pointers (via a template of some kind).
5528 static int list_size(char** l, int item_size)
5530 int i,j = 0;
5531 if(l)
5532 { for(i=0;l[i];i++)
5533 j += (item_size) ? item_size : strlen(l[i]) + 1;
5534 j += (i + 1) * sizeof(char*); }
5535 return j;
5538 static int list_dup(char** l_src, char** l_to, int item_size)
5540 char *p;
5541 int i;
5543 for (i = 0; l_src[i]; i++) ;
5544 p = (char *)(l_to + i + 1);
5545 for (i = 0; l_src[i]; i++)
5547 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
5548 memcpy(p, l_src[i], count);
5549 l_to[i] = p;
5550 p += count;
5552 l_to[i] = NULL;
5553 return p - (char *)l_to;
5556 /* ----- hostent */
5558 /* create a hostent entry
5560 * Creates the entry with enough memory for the name, aliases
5561 * addresses, and the address pointers. Also copies the name
5562 * and sets up all the pointers. If "fill_addresses" is set then
5563 * sufficient memory for the addresses is also allocated and the
5564 * address pointers are set to this memory.
5566 * NOTE: The alias and address lists must be allocated with room
5567 * for the NULL item terminating the list. This is true even if
5568 * the list has no items ("aliases" and "addresses" must be
5569 * at least "1", a truly empty list is invalid).
5571 static struct WS_hostent *WS_create_he(char *name, int aliases, int addresses, int fill_addresses)
5573 struct WS_hostent *p_to;
5574 char *p;
5576 int size = (sizeof(struct WS_hostent) +
5577 strlen(name) + 1 +
5578 sizeof(char *)*aliases +
5579 sizeof(char *)*addresses);
5581 /* Allocate enough memory for the addresses */
5582 if (fill_addresses)
5583 size += sizeof(struct in_addr)*addresses;
5585 if (!(p_to = check_buffer_he(size))) return NULL;
5586 memset(p_to, 0, size);
5588 p = (char *)(p_to + 1);
5589 p_to->h_name = p;
5590 strcpy(p, name);
5591 p += strlen(p) + 1;
5593 p_to->h_aliases = (char **)p;
5594 p += sizeof(char *)*aliases;
5595 p_to->h_addr_list = (char **)p;
5596 p += sizeof(char *)*addresses;
5597 if (fill_addresses)
5599 int i;
5601 /* NOTE: h_aliases must be filled in manually, leave these
5602 * pointers NULL (already set to NULL by memset earlier).
5605 /* Fill in the list of address pointers */
5606 for (i = 0; i < addresses; i++)
5607 p_to->h_addr_list[i] = (p += sizeof(struct in_addr));
5608 p += sizeof(struct in_addr);
5610 return p_to;
5613 /* duplicate hostent entry
5614 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
5615 * Ditto for protoent and servent.
5617 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
5619 int addresses = list_size(p_he->h_addr_list, p_he->h_length);
5620 int aliases = list_size(p_he->h_aliases, 0);
5621 struct WS_hostent *p_to;
5623 p_to = WS_create_he(p_he->h_name, aliases, addresses, FALSE);
5625 if (!p_to) return NULL;
5626 p_to->h_addrtype = p_he->h_addrtype;
5627 p_to->h_length = p_he->h_length;
5629 list_dup(p_he->h_aliases, p_to->h_aliases, 0);
5630 list_dup(p_he->h_addr_list, p_to->h_addr_list, p_he->h_length);
5631 return p_to;
5634 /* ----- protoent */
5636 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
5638 char *p;
5639 struct WS_protoent *p_to;
5641 int size = (sizeof(*p_pe) +
5642 strlen(p_pe->p_name) + 1 +
5643 list_size(p_pe->p_aliases, 0));
5645 if (!(p_to = check_buffer_pe(size))) return NULL;
5646 p_to->p_proto = p_pe->p_proto;
5648 p = (char *)(p_to + 1);
5649 p_to->p_name = p;
5650 strcpy(p, p_pe->p_name);
5651 p += strlen(p) + 1;
5653 p_to->p_aliases = (char **)p;
5654 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
5655 return p_to;
5658 /* ----- servent */
5660 static struct WS_servent *WS_dup_se(const struct servent* p_se)
5662 char *p;
5663 struct WS_servent *p_to;
5665 int size = (sizeof(*p_se) +
5666 strlen(p_se->s_proto) + 1 +
5667 strlen(p_se->s_name) + 1 +
5668 list_size(p_se->s_aliases, 0));
5670 if (!(p_to = check_buffer_se(size))) return NULL;
5671 p_to->s_port = p_se->s_port;
5673 p = (char *)(p_to + 1);
5674 p_to->s_name = p;
5675 strcpy(p, p_se->s_name);
5676 p += strlen(p) + 1;
5678 p_to->s_proto = p;
5679 strcpy(p, p_se->s_proto);
5680 p += strlen(p) + 1;
5682 p_to->s_aliases = (char **)p;
5683 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
5684 return p_to;
5688 /***********************************************************************
5689 * WSARecv (WS2_32.67)
5691 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5692 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
5693 LPWSAOVERLAPPED lpOverlapped,
5694 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
5696 return WS2_recv_base(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
5697 NULL, NULL, lpOverlapped, lpCompletionRoutine, NULL);
5700 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5701 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
5702 struct WS_sockaddr *lpFrom,
5703 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
5704 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
5705 LPWSABUF lpControlBuffer )
5707 unsigned int i, options;
5708 int n, fd, err;
5709 struct ws2_async *wsa;
5710 DWORD timeout_start = GetTickCount();
5711 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
5713 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
5714 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
5715 (lpFromlen ? *lpFromlen : -1),
5716 lpOverlapped, lpCompletionRoutine);
5718 fd = get_sock_fd( s, FILE_READ_DATA, &options );
5719 TRACE( "fd=%d, options=%x\n", fd, options );
5721 if (fd == -1) return SOCKET_ERROR;
5723 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
5725 err = WSAEFAULT;
5726 goto error;
5729 wsa->hSocket = SOCKET2HANDLE(s);
5730 wsa->flags = *lpFlags;
5731 wsa->lpFlags = lpFlags;
5732 wsa->addr = lpFrom;
5733 wsa->addrlen.ptr = lpFromlen;
5734 wsa->control = lpControlBuffer;
5735 wsa->n_iovecs = dwBufferCount;
5736 wsa->first_iovec = 0;
5737 for (i = 0; i < dwBufferCount; i++)
5739 /* check buffer first to trigger write watches */
5740 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
5742 err = WSAEFAULT;
5743 goto error;
5745 wsa->iovec[i].iov_base = lpBuffers[i].buf;
5746 wsa->iovec[i].iov_len = lpBuffers[i].len;
5749 for (;;)
5751 n = WS2_recv( fd, wsa );
5752 if (n == -1)
5754 if (errno == EINTR) continue;
5755 if (errno != EAGAIN)
5757 int loc_errno = errno;
5758 err = wsaErrno();
5759 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
5760 goto error;
5763 else if (lpNumberOfBytesRecvd) *lpNumberOfBytesRecvd = n;
5765 if ((lpOverlapped || lpCompletionRoutine) &&
5766 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
5768 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
5770 wsa->user_overlapped = lpOverlapped;
5771 wsa->completion_func = lpCompletionRoutine;
5772 release_sock_fd( s, fd );
5774 if (n == -1)
5776 iosb->u.Status = STATUS_PENDING;
5777 iosb->Information = 0;
5779 SERVER_START_REQ( register_async )
5781 req->type = ASYNC_TYPE_READ;
5782 req->async.handle = wine_server_obj_handle( wsa->hSocket );
5783 req->async.callback = wine_server_client_ptr( WS2_async_recv );
5784 req->async.iosb = wine_server_client_ptr( iosb );
5785 req->async.arg = wine_server_client_ptr( wsa );
5786 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
5787 req->async.cvalue = cvalue;
5788 err = wine_server_call( req );
5790 SERVER_END_REQ;
5792 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
5793 WSASetLastError( NtStatusToWSAError( err ));
5794 return SOCKET_ERROR;
5797 iosb->u.Status = STATUS_SUCCESS;
5798 iosb->Information = n;
5799 if (!wsa->completion_func)
5801 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
5802 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
5803 HeapFree( GetProcessHeap(), 0, wsa );
5805 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
5806 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
5807 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5808 return 0;
5811 if (n != -1) break;
5813 if ( _is_blocking(s) )
5815 struct pollfd pfd;
5816 int timeout = GET_RCVTIMEO(fd);
5817 if (timeout != -1)
5819 timeout -= GetTickCount() - timeout_start;
5820 if (timeout < 0) timeout = 0;
5823 pfd.fd = fd;
5824 pfd.events = POLLIN;
5825 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
5827 if (!timeout || !poll( &pfd, 1, timeout ))
5829 err = WSAETIMEDOUT;
5830 /* a timeout is not fatal */
5831 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5832 goto error;
5835 else
5837 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5838 err = WSAEWOULDBLOCK;
5839 goto error;
5843 TRACE(" -> %i bytes\n", n);
5844 HeapFree( GetProcessHeap(), 0, wsa );
5845 release_sock_fd( s, fd );
5846 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5848 return 0;
5850 error:
5851 HeapFree( GetProcessHeap(), 0, wsa );
5852 release_sock_fd( s, fd );
5853 WARN(" -> ERROR %d\n", err);
5854 WSASetLastError( err );
5855 return SOCKET_ERROR;
5858 /***********************************************************************
5859 * WSARecvFrom (WS2_32.69)
5861 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5862 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
5863 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
5864 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5867 return WS2_recv_base( s, lpBuffers, dwBufferCount,
5868 lpNumberOfBytesRecvd, lpFlags,
5869 lpFrom, lpFromlen,
5870 lpOverlapped, lpCompletionRoutine, NULL );
5873 /***********************************************************************
5874 * WSCInstallProvider (WS2_32.88)
5876 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
5877 LPCWSTR lpszProviderDllPath,
5878 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
5879 DWORD dwNumberOfEntries,
5880 LPINT lpErrno )
5882 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
5883 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
5884 dwNumberOfEntries, lpErrno);
5885 *lpErrno = 0;
5886 return 0;
5890 /***********************************************************************
5891 * WSCDeinstallProvider (WS2_32.83)
5893 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
5895 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
5896 *lpErrno = 0;
5897 return 0;
5901 /***********************************************************************
5902 * WSAAccept (WS2_32.26)
5904 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
5905 LPCONDITIONPROC lpfnCondition, DWORD_PTR dwCallbackData)
5908 int ret = 0, size = 0;
5909 WSABUF CallerId, CallerData, CalleeId, CalleeData;
5910 /* QOS SQOS, GQOS; */
5911 GROUP g;
5912 SOCKET cs;
5913 SOCKADDR src_addr, dst_addr;
5915 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
5916 s, addr, addrlen, lpfnCondition, dwCallbackData);
5919 size = sizeof(src_addr);
5920 cs = WS_accept(s, &src_addr, &size);
5922 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
5924 if (!lpfnCondition) return cs;
5926 CallerId.buf = (char *)&src_addr;
5927 CallerId.len = sizeof(src_addr);
5929 CallerData.buf = NULL;
5930 CallerData.len = 0;
5932 WS_getsockname(cs, &dst_addr, &size);
5934 CalleeId.buf = (char *)&dst_addr;
5935 CalleeId.len = sizeof(dst_addr);
5938 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
5939 &CalleeId, &CalleeData, &g, dwCallbackData);
5941 switch (ret)
5943 case CF_ACCEPT:
5944 if (addr && addrlen)
5945 memcpy(addr, &src_addr, (*addrlen > size) ? size : *addrlen );
5946 return cs;
5947 case CF_DEFER:
5948 SERVER_START_REQ( set_socket_deferred )
5950 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5951 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
5952 if ( !wine_server_call_err ( req ) )
5954 SetLastError( WSATRY_AGAIN );
5955 WS_closesocket( cs );
5958 SERVER_END_REQ;
5959 return SOCKET_ERROR;
5960 case CF_REJECT:
5961 WS_closesocket(cs);
5962 SetLastError(WSAECONNREFUSED);
5963 return SOCKET_ERROR;
5964 default:
5965 FIXME("Unknown return type from Condition function\n");
5966 SetLastError(WSAENOTSOCK);
5967 return SOCKET_ERROR;
5971 /***********************************************************************
5972 * WSADuplicateSocketA (WS2_32.32)
5974 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
5976 HANDLE hProcess;
5978 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
5979 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
5980 /* FIXME: WS_getsockopt(s, WS_SOL_SOCKET, SO_PROTOCOL_INFO, lpProtocolInfo, sizeof(*lpProtocolInfo)); */
5981 /* I don't know what the real Windoze does next, this is a hack */
5982 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
5983 * the target use the global duplicate, or we could copy a reference to us to the structure
5984 * and let the target duplicate it from us, but let's do it as simple as possible */
5985 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
5986 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
5987 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
5988 0, FALSE, DUPLICATE_SAME_ACCESS);
5989 CloseHandle(hProcess);
5990 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
5991 return 0;
5994 /***********************************************************************
5995 * WSADuplicateSocketW (WS2_32.33)
5997 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
5999 HANDLE hProcess;
6001 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
6003 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
6004 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
6005 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
6006 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
6007 0, FALSE, DUPLICATE_SAME_ACCESS);
6008 CloseHandle(hProcess);
6009 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
6010 return 0;
6013 /***********************************************************************
6014 * WSAInstallServiceClassA (WS2_32.48)
6016 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
6018 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
6019 WSASetLastError(WSAEACCES);
6020 return SOCKET_ERROR;
6023 /***********************************************************************
6024 * WSAInstallServiceClassW (WS2_32.49)
6026 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
6028 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
6029 WSASetLastError(WSAEACCES);
6030 return SOCKET_ERROR;
6033 /***********************************************************************
6034 * WSARemoveServiceClass (WS2_32.70)
6036 int WINAPI WSARemoveServiceClass(LPGUID info)
6038 FIXME("Request to remove service %p\n",info);
6039 WSASetLastError(WSATYPE_NOT_FOUND);
6040 return SOCKET_ERROR;
6043 /***********************************************************************
6044 * inet_ntop (WS2_32.@)
6046 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
6048 #ifdef HAVE_INET_NTOP
6049 struct WS_in6_addr *in6;
6050 struct WS_in_addr *in;
6051 PCSTR pdst;
6053 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
6054 if (!buffer)
6056 WSASetLastError( STATUS_INVALID_PARAMETER );
6057 return NULL;
6060 switch (family)
6062 case WS_AF_INET:
6064 in = addr;
6065 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
6066 break;
6068 case WS_AF_INET6:
6070 in6 = addr;
6071 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
6072 break;
6074 default:
6075 WSASetLastError( WSAEAFNOSUPPORT );
6076 return NULL;
6079 if (!pdst) WSASetLastError( STATUS_INVALID_PARAMETER );
6080 return pdst;
6081 #else
6082 FIXME( "not supported on this platform\n" );
6083 WSASetLastError( WSAEAFNOSUPPORT );
6084 return NULL;
6085 #endif
6088 /***********************************************************************
6089 * WSAStringToAddressA (WS2_32.80)
6091 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
6092 INT AddressFamily,
6093 LPWSAPROTOCOL_INFOA lpProtocolInfo,
6094 LPSOCKADDR lpAddress,
6095 LPINT lpAddressLength)
6097 INT res=0;
6098 LPSTR workBuffer=NULL,ptrPort;
6100 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
6101 lpProtocolInfo, lpAddress, lpAddressLength );
6103 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
6105 if (!AddressString)
6107 WSASetLastError(WSAEINVAL);
6108 return SOCKET_ERROR;
6111 if (lpProtocolInfo)
6112 FIXME("ProtocolInfo not implemented.\n");
6114 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
6115 strlen(AddressString) + 1);
6116 if (!workBuffer)
6118 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6119 return SOCKET_ERROR;
6122 strcpy(workBuffer, AddressString);
6124 switch(AddressFamily)
6126 case WS_AF_INET:
6128 struct in_addr inetaddr;
6130 /* If lpAddressLength is too small, tell caller the size we need */
6131 if (*lpAddressLength < sizeof(SOCKADDR_IN))
6133 *lpAddressLength = sizeof(SOCKADDR_IN);
6134 res = WSAEFAULT;
6135 break;
6137 *lpAddressLength = sizeof(SOCKADDR_IN);
6138 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
6140 ((LPSOCKADDR_IN)lpAddress)->sin_family = AF_INET;
6142 ptrPort = strchr(workBuffer, ':');
6143 if(ptrPort)
6145 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
6146 *ptrPort = '\0';
6148 else
6150 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
6153 if(inet_aton(workBuffer, &inetaddr) > 0)
6155 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
6156 res = 0;
6158 else
6159 res = WSAEINVAL;
6161 break;
6164 case WS_AF_INET6:
6166 struct in6_addr inetaddr;
6167 /* If lpAddressLength is too small, tell caller the size we need */
6168 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
6170 *lpAddressLength = sizeof(SOCKADDR_IN6);
6171 res = WSAEFAULT;
6172 break;
6174 #ifdef HAVE_INET_PTON
6175 *lpAddressLength = sizeof(SOCKADDR_IN6);
6176 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
6178 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
6180 /* This one is a bit tricky. An IPv6 address contains colons, so the
6181 * check from IPv4 doesn't work like that. However, IPv6 addresses that
6182 * contain a port are written with braces like [fd12:3456:7890::1]:12345
6183 * so what we will do is to look for ']', check if the next char is a
6184 * colon, and if it is, parse the port as in IPv4. */
6186 ptrPort = strchr(workBuffer, ']');
6187 if(ptrPort && *(++ptrPort) == ':')
6189 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort+1));
6190 *ptrPort = '\0';
6192 else
6194 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
6197 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
6199 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
6200 sizeof(struct in6_addr));
6201 res = 0;
6203 else
6204 #endif /* HAVE_INET_PTON */
6205 res = WSAEINVAL;
6207 break;
6209 default:
6210 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
6211 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
6212 res = WSAEINVAL;
6215 HeapFree(GetProcessHeap(), 0, workBuffer);
6217 if (!res) return 0;
6218 WSASetLastError(res);
6219 return SOCKET_ERROR;
6222 /***********************************************************************
6223 * WSAStringToAddressW (WS2_32.81)
6225 * Does anybody know if this function allows to use Hebrew/Arabic/Chinese... digits?
6226 * If this should be the case, it would be required to map these digits
6227 * to Unicode digits (0-9) using FoldString first.
6229 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
6230 INT AddressFamily,
6231 LPWSAPROTOCOL_INFOW lpProtocolInfo,
6232 LPSOCKADDR lpAddress,
6233 LPINT lpAddressLength)
6235 INT sBuffer,res=0;
6236 LPSTR workBuffer=NULL;
6237 WSAPROTOCOL_INFOA infoA;
6238 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
6240 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
6241 lpAddress, lpAddressLength );
6243 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
6245 /* if ProtocolInfo is available - convert to ANSI variant */
6246 if (lpProtocolInfo)
6248 lpProtoInfoA = &infoA;
6249 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
6251 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
6252 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
6254 WSASetLastError( WSAEINVAL);
6255 return SOCKET_ERROR;
6259 if (AddressString)
6261 /* Translate AddressString to ANSI code page - assumes that only
6262 standard digits 0-9 are used with this API call */
6263 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
6264 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
6266 if (workBuffer)
6268 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
6269 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
6270 lpAddress,lpAddressLength);
6271 HeapFree( GetProcessHeap(), 0, workBuffer );
6272 return res;
6274 else
6275 res = WSA_NOT_ENOUGH_MEMORY;
6277 else
6278 res = WSAEINVAL;
6280 WSASetLastError(res);
6281 return SOCKET_ERROR;
6284 /***********************************************************************
6285 * WSAAddressToStringA (WS2_32.27)
6287 * See WSAAddressToStringW
6289 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
6290 LPWSAPROTOCOL_INFOA info, LPSTR string,
6291 LPDWORD lenstr )
6293 DWORD size;
6294 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
6295 CHAR *p;
6297 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
6299 if (!sockaddr) return SOCKET_ERROR;
6300 if (!string || !lenstr) return SOCKET_ERROR;
6302 switch(sockaddr->sa_family)
6304 case WS_AF_INET:
6305 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
6306 sprintf( buffer, "%u.%u.%u.%u:%u",
6307 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
6308 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
6309 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
6310 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
6311 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
6313 p = strchr( buffer, ':' );
6314 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
6315 break;
6317 case WS_AF_INET6:
6319 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
6321 buffer[0] = 0;
6322 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
6323 if ((sockaddr6->sin6_port))
6324 strcpy(buffer, "[");
6325 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, buffer+strlen(buffer), sizeof(buffer)))
6327 WSASetLastError(WSAEINVAL);
6328 return SOCKET_ERROR;
6330 if ((sockaddr6->sin6_scope_id))
6331 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
6332 if ((sockaddr6->sin6_port))
6333 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
6334 break;
6337 default:
6338 WSASetLastError(WSAEINVAL);
6339 return SOCKET_ERROR;
6342 size = strlen( buffer ) + 1;
6344 if (*lenstr < size)
6346 *lenstr = size;
6347 WSASetLastError(WSAEFAULT);
6348 return SOCKET_ERROR;
6351 *lenstr = size;
6352 strcpy( string, buffer );
6353 return 0;
6356 /***********************************************************************
6357 * WSAAddressToStringW (WS2_32.28)
6359 * Convert a sockaddr address into a readable address string.
6361 * PARAMS
6362 * sockaddr [I] Pointer to a sockaddr structure.
6363 * len [I] Size of the sockaddr structure.
6364 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
6365 * string [I/O] Pointer to a buffer to receive the address string.
6366 * lenstr [I/O] Size of the receive buffer in WCHARs.
6368 * RETURNS
6369 * Success: 0
6370 * Failure: SOCKET_ERROR
6372 * NOTES
6373 * The 'info' parameter is ignored.
6375 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
6376 LPWSAPROTOCOL_INFOW info, LPWSTR string,
6377 LPDWORD lenstr )
6379 INT ret;
6380 DWORD size;
6381 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
6382 CHAR bufAddr[54];
6384 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
6386 size = *lenstr;
6387 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
6389 if (ret) return ret;
6391 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
6393 if (*lenstr < size)
6395 *lenstr = size;
6396 WSASetLastError(WSAEFAULT);
6397 return SOCKET_ERROR;
6400 *lenstr = size;
6401 lstrcpyW( string, buffer );
6402 return 0;
6405 /***********************************************************************
6406 * WSAEnumNameSpaceProvidersA (WS2_32.34)
6408 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
6410 FIXME( "(%p %p) Stub!\n", len, buffer );
6411 return 0;
6414 /***********************************************************************
6415 * WSAEnumNameSpaceProvidersW (WS2_32.35)
6417 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
6419 FIXME( "(%p %p) Stub!\n", len, buffer );
6420 return 0;
6423 /***********************************************************************
6424 * WSAGetQOSByName (WS2_32.41)
6426 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
6428 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
6429 return FALSE;
6432 /***********************************************************************
6433 * WSAGetServiceClassInfoA (WS2_32.42)
6435 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
6436 LPWSASERVICECLASSINFOA info )
6438 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
6439 len, info );
6440 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6441 return SOCKET_ERROR;
6444 /***********************************************************************
6445 * WSAGetServiceClassInfoW (WS2_32.43)
6447 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
6448 LPWSASERVICECLASSINFOW 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 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
6459 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
6461 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
6462 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6463 return SOCKET_ERROR;
6466 /***********************************************************************
6467 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
6469 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
6471 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
6472 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6473 return SOCKET_ERROR;
6476 /***********************************************************************
6477 * WSALookupServiceBeginA (WS2_32.59)
6479 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
6480 DWORD dwControlFlags,
6481 LPHANDLE lphLookup)
6483 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
6484 lphLookup);
6485 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6486 return SOCKET_ERROR;
6489 /***********************************************************************
6490 * WSALookupServiceBeginW (WS2_32.60)
6492 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
6493 DWORD dwControlFlags,
6494 LPHANDLE lphLookup)
6496 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
6497 lphLookup);
6498 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6499 return SOCKET_ERROR;
6502 /***********************************************************************
6503 * WSALookupServiceEnd (WS2_32.61)
6505 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
6507 FIXME("(%p) Stub!\n", lookup );
6508 return 0;
6511 /***********************************************************************
6512 * WSALookupServiceNextA (WS2_32.62)
6514 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
6516 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
6517 WSASetLastError(WSA_E_NO_MORE);
6518 return SOCKET_ERROR;
6521 /***********************************************************************
6522 * WSALookupServiceNextW (WS2_32.63)
6524 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
6526 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
6527 WSASetLastError(WSA_E_NO_MORE);
6528 return SOCKET_ERROR;
6531 /***********************************************************************
6532 * WSANtohl (WS2_32.64)
6534 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
6536 TRACE( "(0x%04lx 0x%08x %p)\n", s, netlong, lphostlong );
6538 if (!lphostlong) return WSAEFAULT;
6540 *lphostlong = ntohl( netlong );
6541 return 0;
6544 /***********************************************************************
6545 * WSANtohs (WS2_32.65)
6547 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
6549 TRACE( "(0x%04lx 0x%08x %p)\n", s, netshort, lphostshort );
6551 if (!lphostshort) return WSAEFAULT;
6553 *lphostshort = ntohs( netshort );
6554 return 0;
6557 /***********************************************************************
6558 * WSAProviderConfigChange (WS2_32.66)
6560 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
6561 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
6563 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
6564 return SOCKET_ERROR;
6567 /***********************************************************************
6568 * WSARecvDisconnect (WS2_32.68)
6570 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
6572 TRACE( "(0x%04lx %p)\n", s, disconnectdata );
6574 return WS_shutdown( s, 0 );
6577 /***********************************************************************
6578 * WSASetServiceA (WS2_32.76)
6580 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
6582 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
6583 return 0;
6586 /***********************************************************************
6587 * WSASetServiceW (WS2_32.77)
6589 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
6591 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
6592 return 0;
6595 /***********************************************************************
6596 * WSCEnableNSProvider (WS2_32.84)
6598 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
6600 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
6601 return 0;
6604 /***********************************************************************
6605 * WSCGetProviderPath (WS2_32.86)
6607 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
6609 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
6611 if (!errcode || !provider || !len) return WSAEFAULT;
6613 *errcode = WSAEINVAL;
6614 return SOCKET_ERROR;
6617 /***********************************************************************
6618 * WSCInstallNameSpace (WS2_32.87)
6620 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
6621 DWORD version, LPGUID provider )
6623 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
6624 namespace, version, debugstr_guid(provider) );
6625 return 0;
6628 /***********************************************************************
6629 * WSCUnInstallNameSpace (WS2_32.89)
6631 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
6633 FIXME("(%p) Stub!\n", lpProviderId);
6634 return NO_ERROR;
6637 /***********************************************************************
6638 * WSCWriteProviderOrder (WS2_32.91)
6640 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
6642 FIXME("(%p 0x%08x) Stub!\n", entry, number);
6643 return 0;
6646 /***********************************************************************
6647 * WSANSPIoctl (WS2_32.91)
6649 INT WINAPI WSANSPIoctl( HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer,
6650 DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer,
6651 LPDWORD lpcbBytesReturned, LPWSACOMPLETION lpCompletion )
6653 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup, dwControlCode,
6654 lpvInBuffer, cbInBuffer, lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpCompletion);
6655 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6656 return SOCKET_ERROR;