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).
28 #include "wine/port.h"
33 #include <sys/types.h>
37 #ifdef HAVE_SYS_IOCTL_H
38 # include <sys/ioctl.h>
40 #ifdef HAVE_SYS_FILIO_H
41 # include <sys/filio.h>
43 #ifdef HAVE_SYS_SOCKIO_H
44 # include <sys/sockio.h>
48 # include <sys/so_ioctl.h>
51 #ifdef HAVE_SYS_PARAM_H
52 # include <sys/param.h>
58 #ifdef HAVE_SYS_WAIT_H
59 # include <sys/wait.h>
64 #ifdef HAVE_SYS_SOCKET_H
65 #include <sys/socket.h>
67 #ifdef HAVE_NETINET_IN_H
68 # include <netinet/in.h>
70 #ifdef HAVE_NETINET_TCP_H
71 # include <netinet/tcp.h>
73 #ifdef HAVE_ARPA_INET_H
74 # include <arpa/inet.h>
86 #ifdef HAVE_ARPA_NAMESER_H
87 # include <arpa/nameser.h>
96 #ifdef HAVE_NETIPX_IPX_H
97 # include <netipx/ipx.h>
99 #elif defined(HAVE_LINUX_IPX_H)
100 # ifdef HAVE_ASM_TYPES_H
101 # include <asm/types.h>
103 # ifdef HAVE_LINUX_TYPES_H
104 # include <linux/types.h>
106 # include <linux/ipx.h>
110 #ifdef HAVE_LINUX_IRDA_H
111 # ifdef HAVE_LINUX_TYPES_H
112 # include <linux/types.h>
114 # include <linux/irda.h>
121 #ifdef HAVE_SYS_POLL_H
122 # include <sys/poll.h>
124 #ifdef HAVE_SYS_TIME_H
125 # include <sys/time.h>
128 #define NONAMELESSUNION
129 #define NONAMELESSSTRUCT
130 #include "ntstatus.h"
131 #define WIN32_NO_STATUS
136 #include "winerror.h"
138 #include "winsock2.h"
140 #include "ws2tcpip.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"
154 # include "wsnwlink.h"
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__ */
164 #define INADDR_NONE ~0UL
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)
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));
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) );
226 p = "(unknown IPv6 address)";
227 return wine_dbg_sprintf("{ family AF_INET6, address %s, port %d }",
228 p, ntohs(sin->sin6_port));
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 }",
238 ((const SOCKADDR_IRDA *)a)->irdaServiceName);
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
257 LPWSAOVERLAPPED user_overlapped;
258 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
259 IO_STATUS_BLOCK local_iosb;
260 struct WS_sockaddr *addr;
263 int val; /* for send operations */
264 int *ptr; /* for recv operations */
269 unsigned int n_iovecs;
270 unsigned int first_iovec;
271 struct iovec iovec[1];
274 typedef struct ws2_accept_async
276 HANDLE listen_socket;
277 HANDLE accept_socket;
278 LPOVERLAPPED user_overlapped;
280 PVOID buf; /* buffer to write data to */
284 struct ws2_async *read;
287 /****************************************************************/
289 /* ----------------------------------- internal data */
291 /* ws_... struct conversion flags */
293 typedef struct /* WSAAsyncSelect() control struct */
295 HANDLE service, event, sock;
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
310 struct WS_hostent *he_buffer;
311 struct WS_servent *se_buffer;
312 struct WS_protoent *pe_buffer;
318 /* internal: routing description information */
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 ),
356 MAP_OPTION( SO_RCVTIMEO ),
359 MAP_OPTION( SO_SNDTIMEO ),
363 static const int ws_tcp_map[][2] =
366 MAP_OPTION( TCP_NODELAY ),
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 ),
379 MAP_OPTION( IP_HDRINCL ),
381 MAP_OPTION( IP_TOS ),
382 MAP_OPTION( IP_TTL ),
384 MAP_OPTION( IP_PKTINFO ),
387 MAP_OPTION( IP_UNICAST_IF ),
391 static const int ws_ipv6_map[][2] =
393 #ifdef IPV6_ADD_MEMBERSHIP
394 MAP_OPTION( IPV6_ADD_MEMBERSHIP ),
396 #ifdef IPV6_DROP_MEMBERSHIP
397 MAP_OPTION( IPV6_DROP_MEMBERSHIP ),
399 MAP_OPTION( IPV6_MULTICAST_IF ),
400 MAP_OPTION( IPV6_MULTICAST_HOPS ),
401 MAP_OPTION( IPV6_MULTICAST_LOOP ),
402 MAP_OPTION( IPV6_UNICAST_HOPS ),
403 MAP_OPTION( IPV6_V6ONLY ),
404 #ifdef IPV6_UNICAST_IF
405 MAP_OPTION( IPV6_UNICAST_IF ),
409 static const int ws_af_map[][2] =
411 MAP_OPTION( AF_UNSPEC ),
412 MAP_OPTION( AF_INET ),
413 MAP_OPTION( AF_INET6 ),
415 MAP_OPTION( AF_IPX ),
418 MAP_OPTION( AF_IRDA ),
420 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
423 static const int ws_socktype_map[][2] =
425 MAP_OPTION( SOCK_DGRAM ),
426 MAP_OPTION( SOCK_STREAM ),
427 MAP_OPTION( SOCK_RAW ),
428 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
431 static const int ws_proto_map[][2] =
433 MAP_OPTION( IPPROTO_IP ),
434 MAP_OPTION( IPPROTO_TCP ),
435 MAP_OPTION( IPPROTO_UDP ),
436 MAP_OPTION( IPPROTO_ICMP ),
437 MAP_OPTION( IPPROTO_IGMP ),
438 MAP_OPTION( IPPROTO_RAW ),
439 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
442 static const int ws_aiflag_map[][2] =
444 MAP_OPTION( AI_PASSIVE ),
445 MAP_OPTION( AI_CANONNAME ),
446 MAP_OPTION( AI_NUMERICHOST ),
447 MAP_OPTION( AI_ADDRCONFIG ),
450 static const int ws_niflag_map[][2] =
452 MAP_OPTION( NI_NOFQDN ),
453 MAP_OPTION( NI_NUMERICHOST ),
454 MAP_OPTION( NI_NAMEREQD ),
455 MAP_OPTION( NI_NUMERICSERV ),
456 MAP_OPTION( NI_DGRAM ),
459 static const int ws_eai_map[][2] =
461 MAP_OPTION( EAI_AGAIN ),
462 MAP_OPTION( EAI_BADFLAGS ),
463 MAP_OPTION( EAI_FAIL ),
464 MAP_OPTION( EAI_FAMILY ),
465 MAP_OPTION( EAI_MEMORY ),
466 /* Note: EAI_NODATA is deprecated, but still
467 * used by Windows and Linux... We map the newer
468 * EAI_NONAME to EAI_NODATA for now until Windows
472 MAP_OPTION( EAI_NODATA ),
475 { WS_EAI_NODATA, EAI_NONAME },
478 MAP_OPTION( EAI_SERVICE ),
479 MAP_OPTION( EAI_SOCKTYPE ),
483 static const char magic_loopback_addr[] = {127, 12, 34, 56};
485 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
486 static inline WSACMSGHDR *fill_control_message(int level, int type, WSACMSGHDR *current, ULONG *maxsize, void *data, int len)
488 ULONG msgsize = sizeof(WSACMSGHDR) + WSA_CMSG_ALIGN(len);
489 char *ptr = (char *) current + sizeof(WSACMSGHDR);
491 /* Make sure there is at least enough room for this entry */
492 if (msgsize > *maxsize)
495 /* Fill in the entry */
496 current->cmsg_len = sizeof(WSACMSGHDR) + len;
497 current->cmsg_level = level;
498 current->cmsg_type = type;
499 memcpy(ptr, data, len);
500 /* Return the pointer to where next entry should go */
501 return (WSACMSGHDR *) (ptr + WSA_CMSG_ALIGN(len));
504 static inline int convert_control_headers(struct msghdr *hdr, WSABUF *control)
507 WSACMSGHDR *cmsg_win = (WSACMSGHDR *) control->buf, *ptr;
508 ULONG ctlsize = control->len;
509 struct cmsghdr *cmsg_unix;
512 /* Loop over all the headers, converting as appropriate */
513 for (cmsg_unix = CMSG_FIRSTHDR(hdr); cmsg_unix != NULL; cmsg_unix = CMSG_NXTHDR(hdr, cmsg_unix))
515 switch(cmsg_unix->cmsg_level)
518 switch(cmsg_unix->cmsg_type)
522 /* Convert the Unix IP_PKTINFO structure to the Windows version */
523 struct in_pktinfo *data_unix = (struct in_pktinfo *) CMSG_DATA(cmsg_unix);
524 struct WS_in_pktinfo data_win;
526 memcpy(&data_win.ipi_addr,&data_unix->ipi_addr.s_addr,4); /* 4 bytes = 32 address bits */
527 data_win.ipi_ifindex = data_unix->ipi_ifindex;
528 ptr = fill_control_message(WS_IPPROTO_IP, WS_IP_PKTINFO, ptr, &ctlsize,
529 (void*)&data_win, sizeof(data_win));
530 if (!ptr) goto error;
533 FIXME("Unhandled IPPROTO_IP message header type %d\n", cmsg_unix->cmsg_type);
538 FIXME("Unhandled message header level %d\n", cmsg_unix->cmsg_level);
544 /* Set the length of the returned control headers */
545 control->len = (ptr == NULL ? 0 : (char*)ptr - (char*)cmsg_win);
546 return (ptr != NULL);
547 #else /* IP_PKTINFO */
550 #endif /* IP_PKTINFO */
552 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
554 /* ----------------------------------- error handling */
556 static NTSTATUS sock_get_ntstatus( int err )
560 case EBADF: return STATUS_INVALID_HANDLE;
561 case EBUSY: return STATUS_DEVICE_BUSY;
563 case EACCES: return STATUS_ACCESS_DENIED;
564 case EFAULT: return STATUS_NO_MEMORY;
565 case EINVAL: return STATUS_INVALID_PARAMETER;
567 case EMFILE: return STATUS_TOO_MANY_OPENED_FILES;
568 case EWOULDBLOCK: return STATUS_CANT_WAIT;
569 case EINPROGRESS: return STATUS_PENDING;
570 case EALREADY: return STATUS_NETWORK_BUSY;
571 case ENOTSOCK: return STATUS_OBJECT_TYPE_MISMATCH;
572 case EDESTADDRREQ: return STATUS_INVALID_PARAMETER;
573 case EMSGSIZE: return STATUS_BUFFER_OVERFLOW;
574 case EPROTONOSUPPORT:
575 case ESOCKTNOSUPPORT:
578 case EPROTOTYPE: return STATUS_NOT_SUPPORTED;
579 case ENOPROTOOPT: return STATUS_INVALID_PARAMETER;
580 case EOPNOTSUPP: return STATUS_NOT_SUPPORTED;
581 case EADDRINUSE: return STATUS_ADDRESS_ALREADY_ASSOCIATED;
582 case EADDRNOTAVAIL: return STATUS_INVALID_PARAMETER;
583 case ECONNREFUSED: return STATUS_CONNECTION_REFUSED;
584 case ESHUTDOWN: return STATUS_PIPE_DISCONNECTED;
585 case ENOTCONN: return STATUS_CONNECTION_DISCONNECTED;
586 case ETIMEDOUT: return STATUS_IO_TIMEOUT;
587 case ENETUNREACH: return STATUS_NETWORK_UNREACHABLE;
588 case ENETDOWN: return STATUS_NETWORK_BUSY;
590 case ECONNRESET: return STATUS_CONNECTION_RESET;
591 case ECONNABORTED: return STATUS_CONNECTION_ABORTED;
593 case 0: return STATUS_SUCCESS;
595 WARN("Unknown errno %d!\n", err);
596 return STATUS_UNSUCCESSFUL;
600 static UINT sock_get_error( int err )
604 case EINTR: return WSAEINTR;
605 case EBADF: return WSAEBADF;
607 case EACCES: return WSAEACCES;
608 case EFAULT: return WSAEFAULT;
609 case EINVAL: return WSAEINVAL;
610 case EMFILE: return WSAEMFILE;
611 case EWOULDBLOCK: return WSAEWOULDBLOCK;
612 case EINPROGRESS: return WSAEINPROGRESS;
613 case EALREADY: return WSAEALREADY;
614 case ENOTSOCK: return WSAENOTSOCK;
615 case EDESTADDRREQ: return WSAEDESTADDRREQ;
616 case EMSGSIZE: return WSAEMSGSIZE;
617 case EPROTOTYPE: return WSAEPROTOTYPE;
618 case ENOPROTOOPT: return WSAENOPROTOOPT;
619 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
620 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
621 case EOPNOTSUPP: return WSAEOPNOTSUPP;
622 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
623 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
624 case EADDRINUSE: return WSAEADDRINUSE;
625 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
626 case ENETDOWN: return WSAENETDOWN;
627 case ENETUNREACH: return WSAENETUNREACH;
628 case ENETRESET: return WSAENETRESET;
629 case ECONNABORTED: return WSAECONNABORTED;
631 case ECONNRESET: return WSAECONNRESET;
632 case ENOBUFS: return WSAENOBUFS;
633 case EISCONN: return WSAEISCONN;
634 case ENOTCONN: return WSAENOTCONN;
635 case ESHUTDOWN: return WSAESHUTDOWN;
636 case ETOOMANYREFS: return WSAETOOMANYREFS;
637 case ETIMEDOUT: return WSAETIMEDOUT;
638 case ECONNREFUSED: return WSAECONNREFUSED;
639 case ELOOP: return WSAELOOP;
640 case ENAMETOOLONG: return WSAENAMETOOLONG;
641 case EHOSTDOWN: return WSAEHOSTDOWN;
642 case EHOSTUNREACH: return WSAEHOSTUNREACH;
643 case ENOTEMPTY: return WSAENOTEMPTY;
645 case EPROCLIM: return WSAEPROCLIM;
648 case EUSERS: return WSAEUSERS;
651 case EDQUOT: return WSAEDQUOT;
654 case ESTALE: return WSAESTALE;
657 case EREMOTE: return WSAEREMOTE;
660 /* just in case we ever get here and there are no problems */
663 WARN("Unknown errno %d!\n", err);
664 return WSAEOPNOTSUPP;
668 static UINT wsaErrno(void)
670 int loc_errno = errno;
671 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
673 return sock_get_error( loc_errno );
676 /* most ws2 overlapped functions return an ntstatus-based error code */
677 static NTSTATUS wsaErrStatus(void)
679 int loc_errno = errno;
680 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
682 return sock_get_ntstatus(loc_errno);
685 static UINT wsaHerrno(int loc_errno)
687 WARN("h_errno %d.\n", loc_errno);
691 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
692 case TRY_AGAIN: return WSATRY_AGAIN;
693 case NO_RECOVERY: return WSANO_RECOVERY;
694 case NO_DATA: return WSANO_DATA;
695 case ENOBUFS: return WSAENOBUFS;
699 WARN("Unknown h_errno %d!\n", loc_errno);
700 return WSAEOPNOTSUPP;
704 static inline DWORD NtStatusToWSAError( const DWORD status )
706 /* We only need to cover the status codes set by server async request handling */
710 case STATUS_SUCCESS: wserr = 0; break;
711 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
712 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
713 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
714 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
715 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
716 case STATUS_NETWORK_BUSY: wserr = WSAEALREADY; break;
717 case STATUS_NETWORK_UNREACHABLE: wserr = WSAENETUNREACH; break;
718 case STATUS_CONNECTION_REFUSED: wserr = WSAECONNREFUSED; break;
719 case STATUS_CONNECTION_DISCONNECTED: wserr = WSAENOTCONN; break;
720 case STATUS_CONNECTION_RESET: wserr = WSAECONNRESET; break;
721 case STATUS_CONNECTION_ABORTED: wserr = WSAECONNABORTED; break;
722 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
723 case STATUS_ADDRESS_ALREADY_ASSOCIATED: wserr = WSAEADDRINUSE; break;
724 case STATUS_IO_TIMEOUT:
725 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
726 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
727 case STATUS_ACCESS_DENIED: wserr = WSAEACCES; break;
728 case STATUS_TOO_MANY_OPENED_FILES: wserr = WSAEMFILE; break;
729 case STATUS_CANT_WAIT: wserr = WSAEWOULDBLOCK; break;
730 case STATUS_BUFFER_OVERFLOW: wserr = WSAEMSGSIZE; break;
731 case STATUS_NOT_SUPPORTED: wserr = WSAEOPNOTSUPP; break;
732 case STATUS_HOST_UNREACHABLE: wserr = WSAEHOSTUNREACH; break;
735 wserr = RtlNtStatusToDosError( status );
736 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
741 /* set last error code from NT status without mapping WSA errors */
742 static inline unsigned int set_error( unsigned int err )
746 err = NtStatusToWSAError( err );
752 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
755 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
760 static inline void release_sock_fd( SOCKET s, int fd )
762 wine_server_release_fd( SOCKET2HANDLE(s), fd );
765 static void _enable_event( HANDLE s, unsigned int event,
766 unsigned int sstate, unsigned int cstate )
768 SERVER_START_REQ( enable_socket_event )
770 req->handle = wine_server_obj_handle( s );
772 req->sstate = sstate;
773 req->cstate = cstate;
774 wine_server_call( req );
779 static int _is_blocking(SOCKET s)
782 SERVER_START_REQ( get_socket_event )
784 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
785 req->service = FALSE;
787 wine_server_call( req );
788 ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
794 static unsigned int _get_sock_mask(SOCKET s)
797 SERVER_START_REQ( get_socket_event )
799 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
800 req->service = FALSE;
802 wine_server_call( req );
809 static void _sync_sock_state(SOCKET s)
811 /* do a dummy wineserver request in order to let
812 the wineserver run through its select loop once */
813 (void)_is_blocking(s);
816 static int _get_sock_error(SOCKET s, unsigned int bit)
818 int events[FD_MAX_EVENTS];
820 SERVER_START_REQ( get_socket_event )
822 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
823 req->service = FALSE;
825 wine_server_set_reply( req, events, sizeof(events) );
826 wine_server_call( req );
832 static struct per_thread_data *get_per_thread_data(void)
834 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
835 /* lazy initialization */
838 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
839 NtCurrentTeb()->WinSockData = ptb;
844 static void free_per_thread_data(void)
846 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
850 /* delete scratch buffers */
851 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
852 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
853 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
854 ptb->he_buffer = NULL;
855 ptb->se_buffer = NULL;
856 ptb->pe_buffer = NULL;
858 HeapFree( GetProcessHeap(), 0, ptb );
859 NtCurrentTeb()->WinSockData = NULL;
862 /***********************************************************************
863 * DllMain (WS2_32.init)
865 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
867 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
869 case DLL_PROCESS_ATTACH:
871 case DLL_PROCESS_DETACH:
872 free_per_thread_data();
873 DeleteCriticalSection(&csWSgetXXXbyYYY);
876 case DLL_THREAD_DETACH:
877 free_per_thread_data();
883 /***********************************************************************
886 * Converts socket flags from Windows format.
887 * Return 1 if converted, 0 if not (error).
889 static int convert_sockopt(INT *level, INT *optname)
896 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
897 if( ws_sock_map[i][0] == *optname )
899 *optname = ws_sock_map[i][1];
903 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
906 *level = IPPROTO_TCP;
907 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
908 if ( ws_tcp_map[i][0] == *optname )
910 *optname = ws_tcp_map[i][1];
914 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
918 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
919 if (ws_ip_map[i][0] == *optname )
921 *optname = ws_ip_map[i][1];
925 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
927 case WS_IPPROTO_IPV6:
928 *level = IPPROTO_IPV6;
929 for(i=0; i<sizeof(ws_ipv6_map)/sizeof(ws_ipv6_map[0]); i++) {
930 if (ws_ipv6_map[i][0] == *optname )
932 *optname = ws_ipv6_map[i][1];
936 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname);
938 default: FIXME("Unimplemented or unknown socket level\n");
943 /* ----------------------------------- Per-thread info (or per-process?) */
945 static char *strdup_lower(const char *str)
948 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
952 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
955 else SetLastError(WSAENOBUFS);
959 static inline int sock_error_p(int s)
961 unsigned int optval, optlen;
963 optlen = sizeof(optval);
964 getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
965 if (optval) WARN("\t[%i] error: %d\n", s, optval);
969 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
970 * from an fd and return the value converted to milli seconds
971 * or -1 if there is an infinite time out */
972 static inline int get_rcvsnd_timeo( int fd, int optname)
975 unsigned int len = sizeof(tv);
976 int ret = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
978 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
979 if( ret <= 0 ) /* tv == {0,0} means infinite time out */
984 /* macro wrappers for portability */
986 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
988 #define GET_RCVTIMEO(fd) (-1)
992 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
994 #define GET_SNDTIMEO(fd) (-1)
997 /* utility: given an fd, will block until one of the events occurs */
998 static inline int do_block( int fd, int events, int timeout )
1004 pfd.events = events;
1006 while ((ret = poll(&pfd, 1, timeout)) < 0)
1017 convert_af_w2u(int windowsaf) {
1020 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1021 if (ws_af_map[i][0] == windowsaf)
1022 return ws_af_map[i][1];
1023 FIXME("unhandled Windows address family %d\n", windowsaf);
1028 convert_af_u2w(int unixaf) {
1031 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1032 if (ws_af_map[i][1] == unixaf)
1033 return ws_af_map[i][0];
1034 FIXME("unhandled UNIX address family %d\n", unixaf);
1039 convert_proto_w2u(int windowsproto) {
1042 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1043 if (ws_proto_map[i][0] == windowsproto)
1044 return ws_proto_map[i][1];
1045 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
1050 convert_proto_u2w(int unixproto) {
1053 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1054 if (ws_proto_map[i][1] == unixproto)
1055 return ws_proto_map[i][0];
1056 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
1061 convert_socktype_w2u(int windowssocktype) {
1064 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1065 if (ws_socktype_map[i][0] == windowssocktype)
1066 return ws_socktype_map[i][1];
1067 FIXME("unhandled Windows socket type %d\n", windowssocktype);
1072 convert_socktype_u2w(int unixsocktype) {
1075 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1076 if (ws_socktype_map[i][1] == unixsocktype)
1077 return ws_socktype_map[i][0];
1078 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
1082 /* ----------------------------------- API -----
1084 * Init / cleanup / error checking.
1087 /***********************************************************************
1088 * WSAStartup (WS2_32.115)
1090 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
1092 TRACE("verReq=%x\n", wVersionRequested);
1094 if (LOBYTE(wVersionRequested) < 1)
1095 return WSAVERNOTSUPPORTED;
1097 if (!lpWSAData) return WSAEINVAL;
1101 /* that's the whole of the negotiation for now */
1102 lpWSAData->wVersion = wVersionRequested;
1103 /* return winsock information */
1104 lpWSAData->wHighVersion = 0x0202;
1105 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
1106 strcpy(lpWSAData->szSystemStatus, "Running" );
1107 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
1108 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
1109 /* don't do anything with lpWSAData->lpVendorInfo */
1110 /* (some apps don't allocate the space for this field) */
1112 TRACE("succeeded\n");
1117 /***********************************************************************
1118 * WSACleanup (WS2_32.116)
1120 INT WINAPI WSACleanup(void)
1126 SetLastError(WSANOTINITIALISED);
1127 return SOCKET_ERROR;
1131 /***********************************************************************
1132 * WSAGetLastError (WS2_32.111)
1134 INT WINAPI WSAGetLastError(void)
1136 return GetLastError();
1139 /***********************************************************************
1140 * WSASetLastError (WS2_32.112)
1142 void WINAPI WSASetLastError(INT iError) {
1143 SetLastError(iError);
1146 static struct WS_hostent *check_buffer_he(int size)
1148 struct per_thread_data * ptb = get_per_thread_data();
1151 if (ptb->he_len >= size ) return ptb->he_buffer;
1152 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1154 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
1155 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
1156 return ptb->he_buffer;
1159 static struct WS_servent *check_buffer_se(int size)
1161 struct per_thread_data * ptb = get_per_thread_data();
1164 if (ptb->se_len >= size ) return ptb->se_buffer;
1165 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1167 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
1168 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
1169 return ptb->se_buffer;
1172 static struct WS_protoent *check_buffer_pe(int size)
1174 struct per_thread_data * ptb = get_per_thread_data();
1177 if (ptb->pe_len >= size ) return ptb->pe_buffer;
1178 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1180 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
1181 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
1182 return ptb->pe_buffer;
1185 /* ----------------------------------- i/o APIs */
1187 static inline BOOL supported_pf(int pf)
1208 /**********************************************************************/
1210 /* Returns the length of the converted address if successful, 0 if it was too small to
1213 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
1214 union generic_unix_sockaddr *uaddr)
1216 unsigned int uaddrlen = 0;
1218 switch (wsaddr->sa_family)
1223 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
1224 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
1226 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
1229 uaddrlen = sizeof(struct sockaddr_ipx);
1230 memset( uaddr, 0, uaddrlen );
1231 uipx->sipx_family=AF_IPX;
1232 uipx->sipx_port=wsipx->sa_socket;
1233 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1236 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
1237 #ifdef IPX_FRAME_NONE
1238 uipx->sipx_type=IPX_FRAME_NONE;
1244 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
1245 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
1247 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1248 * scope_id, one without.
1250 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
1251 uaddrlen = sizeof(struct sockaddr_in6);
1252 memset( uaddr, 0, uaddrlen );
1253 uin6->sin6_family = AF_INET6;
1254 uin6->sin6_port = win6->sin6_port;
1255 uin6->sin6_flowinfo = win6->sin6_flowinfo;
1256 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1257 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
1259 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
1262 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
1266 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
1267 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
1269 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
1271 uaddrlen = sizeof(struct sockaddr_in);
1272 memset( uaddr, 0, uaddrlen );
1273 uin->sin_family = AF_INET;
1274 uin->sin_port = win->sin_port;
1275 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
1280 struct sockaddr_irda *uin = (struct sockaddr_irda *)uaddr;
1281 const SOCKADDR_IRDA *win = (const SOCKADDR_IRDA *)wsaddr;
1283 if (wsaddrlen < sizeof(SOCKADDR_IRDA))
1285 uaddrlen = sizeof(struct sockaddr_irda);
1286 memset( uaddr, 0, uaddrlen );
1287 uin->sir_family = AF_IRDA;
1288 if (!strncmp( win->irdaServiceName, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1290 unsigned int lsap_sel = 0;
1292 sscanf( win->irdaServiceName, "LSAP-SEL%u", &lsap_sel );
1293 uin->sir_lsap_sel = lsap_sel;
1297 uin->sir_lsap_sel = LSAP_ANY;
1298 memcpy( uin->sir_name, win->irdaServiceName, 25 );
1300 memcpy( &uin->sir_addr, win->irdaDeviceID, sizeof(uin->sir_addr) );
1304 case WS_AF_UNSPEC: {
1305 /* Try to determine the needed space by the passed windows sockaddr space */
1306 switch (wsaddrlen) {
1307 default: /* likely a ipv4 address */
1308 case sizeof(struct WS_sockaddr_in):
1309 uaddrlen = sizeof(struct sockaddr_in);
1312 case sizeof(struct WS_sockaddr_ipx):
1313 uaddrlen = sizeof(struct sockaddr_ipx);
1317 case sizeof(SOCKADDR_IRDA):
1318 uaddrlen = sizeof(struct sockaddr_irda);
1321 case sizeof(struct WS_sockaddr_in6):
1322 case sizeof(struct WS_sockaddr_in6_old):
1323 uaddrlen = sizeof(struct sockaddr_in6);
1326 memset( uaddr, 0, uaddrlen );
1330 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
1336 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
1338 switch (uaddr->sa_family)
1342 FIXME("don't know how to tell if IPX socket is bound, assuming it is!\n");
1347 static const struct sockaddr_in6 emptyAddr;
1348 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
1349 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
1353 static const struct sockaddr_in emptyAddr;
1354 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
1355 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
1360 FIXME("unknown address family %d\n", uaddr->sa_family);
1365 /* Returns 0 if successful, -1 if the buffer is too small */
1366 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
1370 switch(uaddr->sa_family)
1375 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
1376 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
1379 switch (*wsaddrlen) /* how much can we copy? */
1383 *wsaddrlen = sizeof(*wsipx);
1384 wsipx->sa_socket=uipx->sipx_port;
1388 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
1396 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1402 wsipx->sa_family=WS_AF_IPX;
1414 const struct sockaddr_irda *uin = (const struct sockaddr_irda *)uaddr;
1415 SOCKADDR_IRDA *win = (SOCKADDR_IRDA *)wsaddr;
1417 if (*wsaddrlen < sizeof(SOCKADDR_IRDA))
1419 win->irdaAddressFamily = WS_AF_IRDA;
1420 memcpy( win->irdaDeviceID, &uin->sir_addr, sizeof(win->irdaDeviceID) );
1421 if (uin->sir_lsap_sel != LSAP_ANY)
1422 sprintf( win->irdaServiceName, "LSAP-SEL%u", uin->sir_lsap_sel );
1424 memcpy( win->irdaServiceName, uin->sir_name,
1425 sizeof(win->irdaServiceName) );
1430 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1431 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1433 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1435 win6old->sin6_family = WS_AF_INET6;
1436 win6old->sin6_port = uin6->sin6_port;
1437 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1438 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1439 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1440 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1441 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1442 win6->sin6_scope_id = uin6->sin6_scope_id;
1443 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1446 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1448 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1453 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1454 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1456 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1458 win->sin_family = WS_AF_INET;
1459 win->sin_port = uin->sin_port;
1460 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1461 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1462 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1466 memset(wsaddr,0,*wsaddrlen);
1470 FIXME("Unknown address family %d\n", uaddr->sa_family);
1476 /**************************************************************************
1477 * Functions for handling overlapped I/O
1478 **************************************************************************/
1480 /* user APC called upon async completion */
1481 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1483 ws2_async *wsa = arg;
1485 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
1486 iosb->Information, wsa->user_overlapped,
1488 HeapFree( GetProcessHeap(), 0, wsa );
1491 /***********************************************************************
1492 * WS2_recv (INTERNAL)
1494 * Workhorse for both synchronous and asynchronous recv() operations.
1496 static int WS2_recv( int fd, struct ws2_async *wsa )
1498 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1502 union generic_unix_sockaddr unix_sockaddr;
1505 hdr.msg_name = NULL;
1509 hdr.msg_namelen = sizeof(unix_sockaddr);
1510 hdr.msg_name = &unix_sockaddr;
1513 hdr.msg_namelen = 0;
1515 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1516 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1517 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1518 hdr.msg_accrights = NULL;
1519 hdr.msg_accrightslen = 0;
1521 hdr.msg_control = pktbuf;
1522 hdr.msg_controllen = sizeof(pktbuf);
1526 if ( (n = recvmsg(fd, &hdr, wsa->flags)) == -1 )
1529 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1532 ERR("Message control headers cannot be properly supported on this system.\n");
1533 wsa->control->len = 0;
1536 if (wsa->control && !convert_control_headers(&hdr, wsa->control))
1538 WARN("Application passed insufficient room for control headers.\n");
1539 *wsa->lpFlags |= WS_MSG_CTRUNC;
1545 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
1546 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
1548 * quoting linux 2.6 net/ipv4/tcp.c:
1549 * "According to UNIX98, msg_name/msg_namelen are ignored
1550 * on connected socket. I was just happy when found this 8) --ANK"
1552 * likewise MSDN says that lpFrom and lpFromlen are ignored for
1553 * connection-oriented sockets, so don't try to update lpFrom.
1555 if (wsa->addr && hdr.msg_namelen)
1556 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
1561 /***********************************************************************
1562 * WS2_async_recv (INTERNAL)
1564 * Handler for overlapped recv() operations.
1566 static NTSTATUS WS2_async_recv( void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1568 ws2_async* wsa = user;
1573 case STATUS_ALERTED:
1574 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
1577 result = WS2_recv( fd, wsa );
1578 wine_server_release_fd( wsa->hSocket, fd );
1581 status = STATUS_SUCCESS;
1582 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1586 if (errno == EINTR || errno == EAGAIN)
1588 status = STATUS_PENDING;
1589 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1594 status = wsaErrStatus();
1599 if (status != STATUS_PENDING)
1601 iosb->u.Status = status;
1602 iosb->Information = result;
1603 *apc = ws2_async_apc;
1608 /* user APC called upon async accept completion */
1609 static void WINAPI ws2_async_accept_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1611 struct ws2_accept_async *wsa = arg;
1613 HeapFree( GetProcessHeap(), 0, wsa->read );
1614 HeapFree( GetProcessHeap(), 0, wsa );
1617 /***********************************************************************
1618 * WS2_async_accept_recv (INTERNAL)
1620 * This function is used to finish the read part of an accept request. It is
1621 * needed to place the completion on the correct socket (listener).
1623 static NTSTATUS WS2_async_accept_recv( void *arg, IO_STATUS_BLOCK *iosb, NTSTATUS status, void **apc )
1626 struct ws2_accept_async *wsa = arg;
1628 status = WS2_async_recv( wsa->read, iosb, status, &junk );
1629 if (status == STATUS_PENDING)
1632 if (wsa->user_overlapped->hEvent)
1633 SetEvent(wsa->user_overlapped->hEvent);
1635 WS_AddCompletion( HANDLE2SOCKET(wsa->listen_socket), wsa->cvalue, iosb->u.Status, iosb->Information );
1637 *apc = ws2_async_accept_apc;
1641 /***********************************************************************
1642 * WS2_async_accept (INTERNAL)
1644 * This is the function called to satisfy the AcceptEx callback
1646 static NTSTATUS WS2_async_accept( void *arg, IO_STATUS_BLOCK *iosb, NTSTATUS status, void **apc )
1648 struct ws2_accept_async *wsa = arg;
1652 TRACE("status: 0x%x listen: %p, accept: %p\n", status, wsa->listen_socket, wsa->accept_socket);
1654 if (status == STATUS_ALERTED)
1656 SERVER_START_REQ( accept_into_socket )
1658 req->lhandle = wine_server_obj_handle( wsa->listen_socket );
1659 req->ahandle = wine_server_obj_handle( wsa->accept_socket );
1660 status = wine_server_call( req );
1664 if (status == STATUS_CANT_WAIT)
1665 return STATUS_PENDING;
1667 if (status == STATUS_INVALID_HANDLE)
1669 FIXME("AcceptEx accepting socket closed but request was not cancelled\n");
1670 status = STATUS_CANCELLED;
1673 else if (status == STATUS_HANDLES_CLOSED)
1674 status = STATUS_CANCELLED; /* strange windows behavior */
1676 if (status != STATUS_SUCCESS)
1679 /* WS2 Spec says size param is extra 16 bytes long...what do we put in it? */
1680 addr = ((char *)wsa->buf) + wsa->data_len;
1681 len = wsa->local_len - sizeof(int);
1682 WS_getsockname(HANDLE2SOCKET(wsa->accept_socket),
1683 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
1686 addr += wsa->local_len;
1687 len = wsa->remote_len - sizeof(int);
1688 WS_getpeername(HANDLE2SOCKET(wsa->accept_socket),
1689 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
1695 SERVER_START_REQ( register_async )
1697 req->type = ASYNC_TYPE_READ;
1698 req->async.handle = wine_server_obj_handle( wsa->accept_socket );
1699 req->async.callback = wine_server_client_ptr( WS2_async_accept_recv );
1700 req->async.iosb = wine_server_client_ptr( iosb );
1701 req->async.arg = wine_server_client_ptr( wsa );
1702 status = wine_server_call( req );
1706 if (status != STATUS_PENDING)
1709 return STATUS_SUCCESS;
1712 iosb->u.Status = status;
1713 iosb->Information = 0;
1715 if (wsa->user_overlapped->hEvent)
1716 SetEvent(wsa->user_overlapped->hEvent);
1718 WS_AddCompletion( HANDLE2SOCKET(wsa->listen_socket), wsa->cvalue, iosb->u.Status, iosb->Information );
1720 *apc = ws2_async_accept_apc;
1724 /***********************************************************************
1725 * WS2_send (INTERNAL)
1727 * Workhorse for both synchronous and asynchronous send() operations.
1729 static int WS2_send( int fd, struct ws2_async *wsa )
1732 union generic_unix_sockaddr unix_addr;
1735 hdr.msg_name = NULL;
1736 hdr.msg_namelen = 0;
1740 hdr.msg_name = &unix_addr;
1741 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
1742 if ( !hdr.msg_namelen )
1748 #if defined(HAVE_IPX) && defined(SOL_IPX)
1749 if(wsa->addr->sa_family == WS_AF_IPX)
1751 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
1753 unsigned int len=sizeof(int);
1755 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
1756 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
1757 * the packet type and then we can retrieve it using getsockopt. After that we can set the
1758 * ipx type in the sockaddr_opx structure with the stored value.
1760 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
1761 uipx->sipx_type = val;
1766 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1767 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1768 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1769 hdr.msg_accrights = NULL;
1770 hdr.msg_accrightslen = 0;
1772 hdr.msg_control = NULL;
1773 hdr.msg_controllen = 0;
1777 ret = sendmsg(fd, &hdr, wsa->flags);
1781 while (wsa->first_iovec < wsa->n_iovecs && wsa->iovec[wsa->first_iovec].iov_len <= n)
1782 n -= wsa->iovec[wsa->first_iovec++].iov_len;
1783 if (wsa->first_iovec < wsa->n_iovecs)
1785 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
1786 wsa->iovec[wsa->first_iovec].iov_len -= n;
1792 /***********************************************************************
1793 * WS2_async_send (INTERNAL)
1795 * Handler for overlapped send() operations.
1797 static NTSTATUS WS2_async_send(void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1799 ws2_async* wsa = user;
1804 case STATUS_ALERTED:
1805 if ( wsa->n_iovecs <= wsa->first_iovec )
1808 status = STATUS_SUCCESS;
1811 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
1814 /* check to see if the data is ready (non-blocking) */
1815 result = WS2_send( fd, wsa );
1816 wine_server_release_fd( wsa->hSocket, fd );
1820 if (wsa->first_iovec < wsa->n_iovecs)
1821 status = STATUS_PENDING;
1823 status = STATUS_SUCCESS;
1825 iosb->Information += result;
1827 else if (errno == EINTR || errno == EAGAIN)
1829 status = STATUS_PENDING;
1833 status = wsaErrStatus();
1837 if (status != STATUS_PENDING)
1839 iosb->u.Status = status;
1840 *apc = ws2_async_apc;
1845 /***********************************************************************
1846 * WS2_async_shutdown (INTERNAL)
1848 * Handler for shutdown() operations on overlapped sockets.
1850 static NTSTATUS WS2_async_shutdown( void* user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc )
1852 ws2_async* wsa = user;
1857 case STATUS_ALERTED:
1858 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
1861 switch ( wsa->type )
1863 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
1864 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
1866 status = err ? wsaErrStatus() : STATUS_SUCCESS;
1867 wine_server_release_fd( wsa->hSocket, fd );
1870 iosb->u.Status = status;
1871 iosb->Information = 0;
1872 *apc = ws2_async_apc;
1876 /***********************************************************************
1877 * WS2_register_async_shutdown (INTERNAL)
1879 * Helper function for WS_shutdown() on overlapped sockets.
1881 static int WS2_register_async_shutdown( SOCKET s, int type )
1883 struct ws2_async *wsa;
1886 TRACE("s %ld type %d\n", s, type);
1888 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
1892 wsa->hSocket = SOCKET2HANDLE(s);
1894 wsa->completion_func = NULL;
1896 SERVER_START_REQ( register_async )
1899 req->async.handle = wine_server_obj_handle( wsa->hSocket );
1900 req->async.callback = wine_server_client_ptr( WS2_async_shutdown );
1901 req->async.iosb = wine_server_client_ptr( &wsa->local_iosb );
1902 req->async.arg = wine_server_client_ptr( wsa );
1903 req->async.cvalue = 0;
1904 status = wine_server_call( req );
1908 if (status != STATUS_PENDING)
1910 HeapFree( GetProcessHeap(), 0, wsa );
1911 return NtStatusToWSAError( status );
1916 /***********************************************************************
1919 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr,
1926 TRACE("socket %04lx\n", s );
1927 is_blocking = _is_blocking(s);
1930 /* try accepting first (if there is a deferred connection) */
1931 SERVER_START_REQ( accept_socket )
1933 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1934 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
1935 req->attributes = OBJ_INHERIT;
1936 status = wine_server_call( req );
1937 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
1942 if (addr) WS_getpeername(as, addr, addrlen32);
1945 if (is_blocking && status == STATUS_CANT_WAIT)
1947 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1949 do_block(fd, POLLIN, -1);
1950 _sync_sock_state(s); /* let wineserver notice connection */
1951 release_sock_fd( s, fd );
1953 } while (is_blocking && status == STATUS_CANT_WAIT);
1956 return INVALID_SOCKET;
1959 /***********************************************************************
1962 static BOOL WINAPI WS2_AcceptEx(SOCKET listener, SOCKET acceptor, PVOID dest, DWORD dest_len,
1963 DWORD local_addr_len, DWORD rem_addr_len, LPDWORD received,
1964 LPOVERLAPPED overlapped)
1967 struct ws2_accept_async *wsa;
1969 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
1971 TRACE("(%lx, %lx, %p, %d, %d, %d, %p, %p)\n", listener, acceptor, dest, dest_len, local_addr_len,
1972 rem_addr_len, received, overlapped);
1976 SetLastError(WSAEINVAL);
1982 SetLastError(WSA_INVALID_PARAMETER);
1986 fd = get_sock_fd( listener, FILE_READ_DATA, NULL );
1989 SetLastError(WSAENOTSOCK);
1992 release_sock_fd( listener, fd );
1994 fd = get_sock_fd( acceptor, FILE_READ_DATA, NULL );
1997 SetLastError(WSAEINVAL);
2000 release_sock_fd( acceptor, fd );
2002 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
2005 SetLastError(WSAEFAULT);
2009 wsa->listen_socket = SOCKET2HANDLE(listener);
2010 wsa->accept_socket = SOCKET2HANDLE(acceptor);
2011 wsa->user_overlapped = overlapped;
2012 wsa->cvalue = cvalue;
2014 wsa->data_len = dest_len;
2015 wsa->local_len = local_addr_len;
2016 wsa->remote_len = rem_addr_len;
2021 /* set up a read request if we need it */
2022 wsa->read = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[1]) );
2025 HeapFree( GetProcessHeap(), 0, wsa );
2026 SetLastError(WSAEFAULT);
2030 wsa->read->hSocket = wsa->accept_socket;
2031 wsa->read->flags = 0;
2032 wsa->read->lpFlags = &wsa->read->flags;
2033 wsa->read->addr = NULL;
2034 wsa->read->addrlen.ptr = NULL;
2035 wsa->read->control = NULL;
2036 wsa->read->n_iovecs = 1;
2037 wsa->read->first_iovec = 0;
2038 wsa->read->iovec[0].iov_base = wsa->buf;
2039 wsa->read->iovec[0].iov_len = wsa->data_len;
2042 SERVER_START_REQ( register_async )
2044 req->type = ASYNC_TYPE_READ;
2045 req->async.handle = wine_server_obj_handle( SOCKET2HANDLE(listener) );
2046 req->async.callback = wine_server_client_ptr( WS2_async_accept );
2047 req->async.iosb = wine_server_client_ptr( overlapped );
2048 req->async.arg = wine_server_client_ptr( wsa );
2049 /* We don't set event or completion since we may also have to read */
2050 status = wine_server_call( req );
2054 if(status != STATUS_PENDING)
2056 HeapFree( GetProcessHeap(), 0, wsa->read );
2057 HeapFree( GetProcessHeap(), 0, wsa );
2060 SetLastError( NtStatusToWSAError(status) );
2064 /***********************************************************************
2065 * GetAcceptExSockaddrs
2067 static void WINAPI WS2_GetAcceptExSockaddrs(PVOID buffer, DWORD data_size, DWORD local_size, DWORD remote_size,
2068 struct WS_sockaddr **local_addr, LPINT local_addr_len,
2069 struct WS_sockaddr **remote_addr, LPINT remote_addr_len)
2071 char *cbuf = buffer;
2072 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer, data_size, local_size, remote_size, local_addr,
2073 local_addr_len, remote_addr, remote_addr_len );
2076 *local_addr_len = *(int *) cbuf;
2077 *local_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2081 *remote_addr_len = *(int *) cbuf;
2082 *remote_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2085 /***********************************************************************
2088 * Perform a receive operation that is capable of returning message
2089 * control headers. It is important to note that the WSAMSG parameter
2090 * must remain valid throughout the operation, even when an overlapped
2091 * receive is performed.
2093 static int WINAPI WS2_WSARecvMsg( SOCKET s, LPWSAMSG msg, LPDWORD lpNumberOfBytesRecvd,
2094 LPWSAOVERLAPPED lpOverlapped,
2095 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2099 SetLastError( WSAEFAULT );
2100 return SOCKET_ERROR;
2103 return WS2_recv_base( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesRecvd,
2104 &msg->dwFlags, msg->name, &msg->namelen,
2105 lpOverlapped, lpCompletionRoutine, &msg->Control );
2108 /***********************************************************************
2111 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
2113 int fd = get_sock_fd( s, 0, NULL );
2114 int res = SOCKET_ERROR;
2116 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2120 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
2122 SetLastError(WSAEAFNOSUPPORT);
2126 union generic_unix_sockaddr uaddr;
2127 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2130 SetLastError(WSAEFAULT);
2135 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
2136 if (name->sa_family == WS_AF_INET6 &&
2137 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
2140 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
2142 release_sock_fd( s, fd );
2143 SetLastError(WSAEAFNOSUPPORT);
2144 return SOCKET_ERROR;
2148 if (name->sa_family == WS_AF_INET)
2150 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2151 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2153 /* Trying to bind to the default host interface, using
2154 * INADDR_ANY instead*/
2155 WARN("Trying to bind to magic IP address, using "
2156 "INADDR_ANY instead.\n");
2157 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
2160 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
2162 int loc_errno = errno;
2163 WARN("\tfailure - errno = %i\n", errno);
2168 SetLastError(WSAENOTSOCK);
2171 SetLastError(WSAEINVAL);
2174 SetLastError(wsaErrno());
2180 res=0; /* success */
2184 release_sock_fd( s, fd );
2189 /***********************************************************************
2190 * closesocket (WS2_32.3)
2192 int WINAPI WS_closesocket(SOCKET s)
2194 TRACE("socket %04lx\n", s);
2195 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
2196 return SOCKET_ERROR;
2199 static int do_connect(int fd, const struct WS_sockaddr* name, int namelen)
2201 union generic_unix_sockaddr uaddr;
2202 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2207 if (name->sa_family == WS_AF_INET)
2209 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2210 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2212 /* Trying to connect to magic replace-loopback address,
2213 * assuming we really want to connect to localhost */
2214 TRACE("Trying to connect to magic IP address, using "
2215 "INADDR_LOOPBACK instead.\n");
2216 in4->sin_addr.s_addr = htonl(WS_INADDR_LOOPBACK);
2220 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
2226 /***********************************************************************
2227 * connect (WS2_32.4)
2229 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
2231 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2233 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2237 int ret = do_connect(fd, name, namelen);
2239 goto connect_success;
2241 if (ret == WSAEINPROGRESS)
2243 /* tell wineserver that a connection is in progress */
2244 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2246 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2247 if (_is_blocking(s))
2251 do_block(fd, POLLIN | POLLOUT, -1);
2252 _sync_sock_state(s); /* let wineserver notice connection */
2253 /* retrieve any error codes from it */
2254 result = _get_sock_error(s, FD_CONNECT_BIT);
2256 SetLastError(NtStatusToWSAError(result));
2259 goto connect_success;
2264 SetLastError(WSAEWOULDBLOCK);
2271 release_sock_fd( s, fd );
2273 return SOCKET_ERROR;
2276 release_sock_fd( s, fd );
2277 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2278 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2279 FD_CONNECT|FD_WINE_LISTENING);
2283 /***********************************************************************
2284 * WSAConnect (WS2_32.30)
2286 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
2287 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
2288 LPQOS lpSQOS, LPQOS lpGQOS )
2290 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
2291 FIXME("unsupported parameters!\n");
2292 return WS_connect( s, name, namelen );
2295 /***********************************************************************
2298 static BOOL WINAPI WS2_ConnectEx(SOCKET s, const struct WS_sockaddr* name, int namelen,
2299 PVOID sendBuf, DWORD sendBufLen, LPDWORD sent, LPOVERLAPPED ov)
2301 int fd, ret, status;
2305 SetLastError( ERROR_INVALID_PARAMETER );
2309 fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2312 SetLastError( WSAENOTSOCK );
2316 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
2317 s, name, debugstr_sockaddr(name), namelen, sendBuf, sendBufLen, ov);
2319 /* FIXME: technically the socket has to be bound */
2320 ret = do_connect(fd, name, namelen);
2325 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2326 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2327 FD_CONNECT|FD_WINE_LISTENING);
2329 wsabuf.len = sendBufLen;
2330 wsabuf.buf = (char*) sendBuf;
2332 /* WSASend takes care of completion if need be */
2333 if (WSASend(s, &wsabuf, sendBuf ? 1 : 0, sent, 0, ov, NULL) != SOCKET_ERROR)
2334 goto connection_success;
2336 else if (ret == WSAEINPROGRESS)
2338 struct ws2_async *wsa;
2339 ULONG_PTR cvalue = (((ULONG_PTR)ov->hEvent & 1) == 0) ? (ULONG_PTR)ov : 0;
2341 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2343 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2345 /* Indirectly call WSASend */
2346 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) )))
2348 SetLastError(WSAEFAULT);
2352 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)ov;
2353 iosb->u.Status = STATUS_PENDING;
2354 iosb->Information = 0;
2356 wsa->hSocket = SOCKET2HANDLE(s);
2358 wsa->addrlen.val = 0;
2360 wsa->lpFlags = &wsa->flags;
2361 wsa->control = NULL;
2362 wsa->n_iovecs = sendBuf ? 1 : 0;
2363 wsa->first_iovec = 0;
2364 wsa->completion_func = NULL;
2365 wsa->iovec[0].iov_base = sendBuf;
2366 wsa->iovec[0].iov_len = sendBufLen;
2368 SERVER_START_REQ( register_async )
2370 req->type = ASYNC_TYPE_WRITE;
2371 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2372 req->async.callback = wine_server_client_ptr( WS2_async_send );
2373 req->async.iosb = wine_server_client_ptr( iosb );
2374 req->async.arg = wine_server_client_ptr( wsa );
2375 req->async.event = wine_server_obj_handle( ov->hEvent );
2376 req->async.cvalue = cvalue;
2377 status = wine_server_call( req );
2381 if (status != STATUS_PENDING) HeapFree(GetProcessHeap(), 0, wsa);
2383 /* If the connect already failed */
2384 if (status == STATUS_PIPE_DISCONNECTED)
2385 status = _get_sock_error(s, FD_CONNECT_BIT);
2386 SetLastError( NtStatusToWSAError(status) );
2394 release_sock_fd( s, fd );
2398 release_sock_fd( s, fd );
2403 /***********************************************************************
2404 * getpeername (WS2_32.5)
2406 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
2411 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, namelen?*namelen:0);
2413 fd = get_sock_fd( s, 0, NULL );
2418 union generic_unix_sockaddr uaddr;
2419 unsigned int uaddrlen = sizeof(uaddr);
2421 if (getpeername(fd, &uaddr.addr, &uaddrlen) == 0)
2423 if (!name || !namelen)
2424 SetLastError(WSAEFAULT);
2425 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
2426 /* The buffer was too small */
2427 SetLastError(WSAEFAULT);
2432 SetLastError(wsaErrno());
2433 release_sock_fd( s, fd );
2438 /***********************************************************************
2439 * getsockname (WS2_32.6)
2441 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
2446 TRACE("socket: %04lx, ptr %p, len %8x\n", s, name, *namelen);
2448 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
2449 if( (name == NULL) || (namelen == NULL) )
2451 SetLastError( WSAEFAULT );
2452 return SOCKET_ERROR;
2455 fd = get_sock_fd( s, 0, NULL );
2460 union generic_unix_sockaddr uaddr;
2461 unsigned int uaddrlen = sizeof(uaddr);
2463 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
2465 SetLastError(wsaErrno());
2467 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
2469 SetLastError(WSAEINVAL);
2471 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
2473 /* The buffer was too small */
2474 SetLastError(WSAEFAULT);
2480 release_sock_fd( s, fd );
2485 /***********************************************************************
2486 * getsockopt (WS2_32.7)
2488 INT WINAPI WS_getsockopt(SOCKET s, INT level,
2489 INT optname, char *optval, INT *optlen)
2494 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
2495 s, level, optname, optval, *optlen);
2503 /* Handle common cases. The special cases are below, sorted
2505 case WS_SO_ACCEPTCONN:
2506 case WS_SO_BROADCAST:
2509 case WS_SO_KEEPALIVE:
2510 case WS_SO_OOBINLINE:
2512 case WS_SO_REUSEADDR:
2515 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2516 return SOCKET_ERROR;
2517 convert_sockopt(&level, &optname);
2518 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2520 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2523 release_sock_fd( s, fd );
2526 case WS_SO_DONTLINGER:
2528 struct linger lingval;
2529 unsigned int len = sizeof(struct linger);
2531 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
2533 SetLastError(WSAEFAULT);
2534 return SOCKET_ERROR;
2536 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2537 return SOCKET_ERROR;
2539 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
2541 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2546 *(BOOL *)optval = (lingval.l_onoff) ? FALSE : TRUE;
2547 *optlen = sizeof(BOOL);
2550 release_sock_fd( s, fd );
2554 case WS_SO_CONNECT_TIME:
2556 static int pretendtime = 0;
2557 struct WS_sockaddr addr;
2558 int len = sizeof(addr);
2560 if (!optlen || *optlen < sizeof(DWORD) || !optval)
2562 SetLastError(WSAEFAULT);
2563 return SOCKET_ERROR;
2565 if (WS_getpeername(s, &addr, &len) == SOCKET_ERROR)
2566 *(DWORD *)optval = ~0u;
2569 if (!pretendtime) FIXME("WS_SO_CONNECT_TIME - faking results\n");
2570 *(DWORD *)optval = pretendtime++;
2572 *optlen = sizeof(DWORD);
2575 /* As mentioned in setsockopt, Windows ignores this, so we
2576 * always return true here */
2577 case WS_SO_DONTROUTE:
2578 if (!optlen || *optlen < sizeof(BOOL) || !optval)
2580 SetLastError(WSAEFAULT);
2581 return SOCKET_ERROR;
2583 *(BOOL *)optval = TRUE;
2584 *optlen = sizeof(BOOL);
2589 struct linger lingval;
2591 unsigned int len = sizeof(struct linger), slen = sizeof(int);
2593 /* struct linger and LINGER have different sizes */
2594 if (!optlen || *optlen < sizeof(LINGER) || !optval)
2596 SetLastError(WSAEFAULT);
2597 return SOCKET_ERROR;
2599 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2600 return SOCKET_ERROR;
2602 if ((getsockopt(fd, SOL_SOCKET, SO_TYPE, &so_type, &slen) == 0 && so_type == SOCK_DGRAM))
2604 SetLastError(WSAENOPROTOOPT);
2607 else if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0)
2609 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2614 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
2615 ((LINGER *)optval)->l_linger = lingval.l_linger;
2616 *optlen = sizeof(struct linger);
2619 release_sock_fd( s, fd );
2623 case WS_SO_MAX_MSG_SIZE:
2624 if (!optlen || *optlen < sizeof(int) || !optval)
2626 SetLastError(WSAEFAULT);
2627 return SOCKET_ERROR;
2629 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
2630 *(int *)optval = 65507;
2631 *optlen = sizeof(int);
2634 /* SO_OPENTYPE does not require a valid socket handle. */
2635 case WS_SO_OPENTYPE:
2636 if (!optlen || *optlen < sizeof(int) || !optval)
2638 SetLastError(WSAEFAULT);
2639 return SOCKET_ERROR;
2641 *(int *)optval = get_per_thread_data()->opentype;
2642 *optlen = sizeof(int);
2643 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
2647 case WS_SO_RCVTIMEO:
2650 case WS_SO_SNDTIMEO:
2652 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
2655 unsigned int len = sizeof(struct timeval);
2657 if (!optlen || *optlen < sizeof(int)|| !optval)
2659 SetLastError(WSAEFAULT);
2660 return SOCKET_ERROR;
2662 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2663 return SOCKET_ERROR;
2665 convert_sockopt(&level, &optname);
2666 if (getsockopt(fd, level, optname, &tv, &len) != 0 )
2668 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2673 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
2674 *optlen = sizeof(int);
2677 release_sock_fd( s, fd );
2682 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
2683 SetLastError(WSAENOPROTOOPT);
2684 return SOCKET_ERROR;
2685 } /* end switch(optname) */
2686 }/* end case WS_SOL_SOCKET */
2690 struct WS_sockaddr_ipx addr;
2691 IPX_ADDRESS_DATA *data;
2696 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
2698 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (unsigned int*)optlen) == -1)
2705 socklen_t len=sizeof(struct ipx);
2706 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
2709 *optval = (int)val.ipx_pt;
2712 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
2713 release_sock_fd( s, fd );
2718 * On a Win2000 system with one network card there are usually
2719 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
2720 * Using this call you can then retrieve info about this all.
2721 * In case of Linux it is a bit different. Usually you have
2722 * only "one" device active and further it is not possible to
2723 * query things like the linkspeed.
2725 FIXME("IPX_ADDRESS\n");
2726 namelen = sizeof(struct WS_sockaddr_ipx);
2727 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
2728 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
2730 data = (IPX_ADDRESS_DATA*)optval;
2731 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
2732 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
2733 data->adapternum = 0;
2734 data->wan = FALSE; /* We are not on a wan for now .. */
2735 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
2736 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
2737 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
2738 * note 1MB = 1000kB in this case */
2741 case IPX_MAX_ADAPTER_NUM:
2742 FIXME("IPX_MAX_ADAPTER_NUM\n");
2743 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
2747 FIXME("IPX optname:%x\n", optname);
2748 return SOCKET_ERROR;
2749 }/* end switch(optname) */
2750 } /* end case NSPROTO_IPX */
2757 case WS_IRLMP_ENUMDEVICES:
2759 static const int MAX_IRDA_DEVICES = 10;
2760 char buf[sizeof(struct irda_device_list) +
2761 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
2763 socklen_t len = sizeof(buf);
2765 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2766 return SOCKET_ERROR;
2767 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
2770 SetLastError(wsaErrno());
2771 return SOCKET_ERROR;
2775 struct irda_device_list *src = (struct irda_device_list *)buf;
2776 DEVICELIST *dst = (DEVICELIST *)optval;
2777 INT needed = sizeof(DEVICELIST), i;
2780 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
2781 if (*optlen < needed)
2783 SetLastError(WSAEFAULT);
2784 return SOCKET_ERROR;
2787 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
2788 dst->numDevice = src->len;
2789 for (i = 0; i < src->len; i++)
2791 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
2792 src->dev[i].saddr, src->dev[i].daddr,
2793 src->dev[i].info, src->dev[i].hints[0],
2794 src->dev[i].hints[1]);
2795 memcpy( dst->Device[i].irdaDeviceID,
2797 sizeof(dst->Device[i].irdaDeviceID) ) ;
2798 memcpy( dst->Device[i].irdaDeviceName,
2800 sizeof(dst->Device[i].irdaDeviceName) ) ;
2801 memcpy( &dst->Device[i].irdaDeviceHints1,
2802 &src->dev[i].hints[0],
2803 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
2804 memcpy( &dst->Device[i].irdaDeviceHints2,
2805 &src->dev[i].hints[1],
2806 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
2807 dst->Device[i].irdaCharSet = src->dev[i].charset;
2813 FIXME("IrDA optname:0x%x\n", optname);
2814 return SOCKET_ERROR;
2816 break; /* case WS_SOL_IRLMP */
2819 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
2820 case WS_IPPROTO_TCP:
2823 case WS_TCP_NODELAY:
2824 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2825 return SOCKET_ERROR;
2826 convert_sockopt(&level, &optname);
2827 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2829 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2832 release_sock_fd( s, fd );
2835 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
2836 return SOCKET_ERROR;
2841 case WS_IP_ADD_MEMBERSHIP:
2842 case WS_IP_DROP_MEMBERSHIP:
2846 case WS_IP_MULTICAST_IF:
2847 case WS_IP_MULTICAST_LOOP:
2848 case WS_IP_MULTICAST_TTL:
2855 #ifdef IP_UNICAST_IF
2856 case WS_IP_UNICAST_IF:
2858 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2859 return SOCKET_ERROR;
2860 convert_sockopt(&level, &optname);
2861 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2863 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2866 release_sock_fd( s, fd );
2868 case WS_IP_DONTFRAGMENT:
2869 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
2870 *(BOOL*)optval = FALSE;
2873 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
2874 return SOCKET_ERROR;
2876 case WS_IPPROTO_IPV6:
2879 #ifdef IPV6_ADD_MEMBERSHIP
2880 case WS_IPV6_ADD_MEMBERSHIP:
2882 #ifdef IPV6_DROP_MEMBERSHIP
2883 case WS_IPV6_DROP_MEMBERSHIP:
2885 case WS_IPV6_MULTICAST_IF:
2886 case WS_IPV6_MULTICAST_HOPS:
2887 case WS_IPV6_MULTICAST_LOOP:
2888 case WS_IPV6_UNICAST_HOPS:
2889 case WS_IPV6_V6ONLY:
2890 #ifdef IPV6_UNICAST_IF
2891 case WS_IPV6_UNICAST_IF:
2893 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2894 return SOCKET_ERROR;
2895 convert_sockopt(&level, &optname);
2896 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2898 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2901 release_sock_fd( s, fd );
2903 case WS_IPV6_DONTFRAG:
2904 FIXME("WS_IPV6_DONTFRAG is always false!\n");
2905 *(BOOL*)optval = FALSE;
2908 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
2909 return SOCKET_ERROR;
2912 WARN("Unknown level: 0x%08x\n", level);
2913 SetLastError(WSAEINVAL);
2914 return SOCKET_ERROR;
2915 } /* end switch(level) */
2918 /***********************************************************************
2921 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
2923 return htonl(hostlong);
2927 /***********************************************************************
2930 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
2932 return htons(hostshort);
2935 /***********************************************************************
2936 * WSAHtonl (WS2_32.46)
2937 * From MSDN description of error codes, this function should also
2938 * check if WinSock has been initialized and the socket is a valid
2939 * socket. But why? This function only translates a host byte order
2940 * u_long into a network byte order u_long...
2942 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
2946 *lpnetlong = htonl(hostlong);
2949 WSASetLastError(WSAEFAULT);
2950 return SOCKET_ERROR;
2953 /***********************************************************************
2954 * WSAHtons (WS2_32.47)
2955 * From MSDN description of error codes, this function should also
2956 * check if WinSock has been initialized and the socket is a valid
2957 * socket. But why? This function only translates a host byte order
2958 * u_short into a network byte order u_short...
2960 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
2965 *lpnetshort = htons(hostshort);
2968 WSASetLastError(WSAEFAULT);
2969 return SOCKET_ERROR;
2973 /***********************************************************************
2974 * inet_addr (WS2_32.11)
2976 WS_u_long WINAPI WS_inet_addr(const char *cp)
2978 if (!cp) return INADDR_NONE;
2979 return inet_addr(cp);
2983 /***********************************************************************
2986 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
2988 return ntohl(netlong);
2992 /***********************************************************************
2995 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
2997 return ntohs(netshort);
3001 /***********************************************************************
3002 * inet_ntoa (WS2_32.12)
3004 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
3006 /* use "buffer for dummies" here because some applications have a
3007 * propensity to decode addresses in ws_hostent structure without
3008 * saving them first...
3010 static char dbuffer[16]; /* Yes, 16: 4*3 digits + 3 '.' + 1 '\0' */
3012 char* s = inet_ntoa(*((struct in_addr*)&in));
3018 SetLastError(wsaErrno());
3022 static const char *debugstr_wsaioctl(DWORD ioctl)
3024 const char *buf_type, *family;
3026 switch(ioctl & 0x18000000)
3031 case WS_IOC_PROTOCOL:
3032 family = "IOC_PROTOCOL";
3035 family = "IOC_VENDOR";
3037 default: /* WS_IOC_UNIX */
3039 BYTE size = (ioctl >> 16) & WS_IOCPARM_MASK;
3040 char x = (ioctl & 0xff00) >> 8;
3041 BYTE y = ioctl & 0xff;
3044 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3048 sprintf(args, "%d, %d", x, y);
3052 sprintf(args, "'%c', %d, %d", x, y, size);
3056 sprintf(args, "'%c', %d, %d", x, y, size);
3060 sprintf(args, "'%c', %d, %d", x, y, size);
3063 return wine_dbg_sprintf("%s(%s)", buf_type, args);
3067 /* We are different from WS_IOC_UNIX. */
3068 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3071 buf_type = "_WSAIO";
3074 buf_type = "_WSAIORW";
3077 buf_type = "_WSAIOW";
3080 buf_type = "_WSAIOR";
3087 return wine_dbg_sprintf("%s(%s, %d)", buf_type, family,
3088 (USHORT)(ioctl & 0xffff));
3091 /**********************************************************************
3092 * WSAIoctl (WS2_32.50)
3095 INT WINAPI WSAIoctl(SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size, LPVOID out_buff,
3096 DWORD out_size, LPDWORD ret_size, LPWSAOVERLAPPED overlapped,
3097 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
3100 DWORD status = 0, total = 0;
3102 TRACE("%ld, 0x%08x, %p, %d, %p, %d, %p, %p, %p\n",
3103 s, code, in_buff, in_size, out_buff, out_size, ret_size, overlapped, completion);
3108 if (in_size != sizeof(WS_u_long) || IS_INTRESOURCE(in_buff))
3110 WSASetLastError(WSAEFAULT);
3111 return SOCKET_ERROR;
3113 if (_get_sock_mask(s))
3115 /* AsyncSelect()'ed sockets are always nonblocking */
3116 if (!*(WS_u_long *)in_buff) status = WSAEINVAL;
3119 if (*(WS_u_long *)in_buff)
3120 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
3122 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
3127 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
3129 WSASetLastError(WSAEFAULT);
3130 return SOCKET_ERROR;
3132 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3133 if (ioctl(fd, FIONREAD, out_buff ) == -1)
3134 status = (errno == EBADF) ? WSAENOTSOCK : wsaErrno();
3135 release_sock_fd( s, fd );
3141 unsigned int oob = 0, oobsize = sizeof(int), atmark = 0;
3142 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
3144 WSASetLastError(WSAEFAULT);
3145 return SOCKET_ERROR;
3147 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3148 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
3149 if ((getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &oob, &oobsize ) == -1)
3150 || (!oob && ioctl(fd, SIOCATMARK, &atmark ) == -1))
3151 status = (errno == EBADF) ? WSAENOTSOCK : wsaErrno();
3154 /* The SIOCATMARK value read from ioctl() is reversed
3155 * because BSD returns TRUE if it's in the OOB mark
3156 * while Windows returns TRUE if there are NO OOB bytes.
3158 (*(WS_u_long *) out_buff) = oob | !atmark;
3161 release_sock_fd( s, fd );
3166 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
3167 SetLastError(WSAEINVAL);
3168 return SOCKET_ERROR;
3170 case WS_SIO_GET_INTERFACE_LIST:
3172 INTERFACE_INFO* intArray = out_buff;
3173 DWORD size, numInt = 0, apiReturn;
3175 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
3177 if (!out_buff || !ret_size)
3179 WSASetLastError(WSAEFAULT);
3180 return SOCKET_ERROR;
3183 fd = get_sock_fd( s, 0, NULL );
3184 if (fd == -1) return SOCKET_ERROR;
3186 apiReturn = GetAdaptersInfo(NULL, &size);
3187 if (apiReturn == ERROR_BUFFER_OVERFLOW)
3189 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
3193 if (GetAdaptersInfo(table, &size) == NO_ERROR)
3195 PIP_ADAPTER_INFO ptr;
3197 if (size*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > out_size)
3199 WARN("Buffer too small = %u, out_size = %u\n", size, out_size);
3200 HeapFree(GetProcessHeap(),0,table);
3201 release_sock_fd( s, fd );
3205 for (ptr = table, numInt = 0; ptr;
3206 ptr = ptr->Next, intArray++, numInt++)
3208 unsigned int addr, mask, bcast;
3209 struct ifreq ifInfo;
3211 /* Socket Status Flags */
3212 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
3213 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
3215 ERR("Error obtaining status flags for socket!\n");
3216 HeapFree(GetProcessHeap(),0,table);
3217 release_sock_fd( s, fd );
3223 /* set flags; the values of IFF_* are not the same
3224 under Linux and Windows, therefore must generate
3226 intArray->iiFlags = 0;
3227 if (ifInfo.ifr_flags & IFF_BROADCAST)
3228 intArray->iiFlags |= WS_IFF_BROADCAST;
3229 #ifdef IFF_POINTOPOINT
3230 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
3231 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
3233 if (ifInfo.ifr_flags & IFF_LOOPBACK)
3234 intArray->iiFlags |= WS_IFF_LOOPBACK;
3235 if (ifInfo.ifr_flags & IFF_UP)
3236 intArray->iiFlags |= WS_IFF_UP;
3237 if (ifInfo.ifr_flags & IFF_MULTICAST)
3238 intArray->iiFlags |= WS_IFF_MULTICAST;
3241 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
3242 mask = inet_addr(ptr->IpAddressList.IpMask.String);
3243 bcast = addr | ~mask;
3244 intArray->iiAddress.AddressIn.sin_family = AF_INET;
3245 intArray->iiAddress.AddressIn.sin_port = 0;
3246 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
3248 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
3249 intArray->iiNetmask.AddressIn.sin_port = 0;
3250 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
3252 intArray->iiBroadcastAddress.AddressIn.sin_family =
3254 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
3255 intArray->iiBroadcastAddress.AddressIn.sin_addr.
3261 ERR("Unable to get interface table!\n");
3264 HeapFree(GetProcessHeap(),0,table);
3266 else status = WSAEINVAL;
3268 else if (apiReturn != ERROR_NO_DATA)
3270 ERR("Unable to get interface table!\n");
3273 /* Calculate the size of the array being returned */
3274 total = sizeof(INTERFACE_INFO) * numInt;
3275 release_sock_fd( s, fd );
3279 case WS_SIO_ADDRESS_LIST_CHANGE:
3280 FIXME("-> SIO_ADDRESS_LIST_CHANGE request: stub\n");
3281 /* FIXME: error and return code depend on whether socket was created
3282 * with WSA_FLAG_OVERLAPPED, but there is no easy way to get this */
3285 case WS_SIO_ADDRESS_LIST_QUERY:
3289 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
3293 WSASetLastError(WSAEFAULT);
3294 return SOCKET_ERROR;
3297 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
3299 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
3302 if (!table || GetAdaptersInfo(table, &size))
3304 HeapFree(GetProcessHeap(), 0, table);
3309 for (p = table, num = 0; p; p = p->Next)
3310 if (p->IpAddressList.IpAddress.String[0]) num++;
3312 total = sizeof(SOCKET_ADDRESS_LIST) + sizeof(SOCKET_ADDRESS) * (num - 1);
3313 total += sizeof(SOCKADDR) * num;
3315 if (total > out_size)
3317 HeapFree(GetProcessHeap(), 0, table);
3326 SOCKET_ADDRESS_LIST *sa_list = out_buff;
3327 SOCKADDR_IN *sockaddr;
3329 sa = sa_list->Address;
3330 sockaddr = (SOCKADDR_IN *)((char *)sa + num * sizeof(SOCKET_ADDRESS));
3331 sa_list->iAddressCount = num;
3333 for (p = table, i = 0; p; p = p->Next)
3335 if (!p->IpAddressList.IpAddress.String[0]) continue;
3337 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
3338 sa[i].iSockaddrLength = sizeof(SOCKADDR);
3340 sockaddr[i].sin_family = AF_INET;
3341 sockaddr[i].sin_port = 0;
3342 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
3347 HeapFree(GetProcessHeap(), 0, table);
3351 WARN("unable to get IP address list\n");
3358 FIXME("SIO_FLUSH: stub.\n");
3361 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
3363 static const GUID connectex_guid = WSAID_CONNECTEX;
3364 static const GUID disconnectex_guid = WSAID_DISCONNECTEX;
3365 static const GUID acceptex_guid = WSAID_ACCEPTEX;
3366 static const GUID getaccepexsockaddrs_guid = WSAID_GETACCEPTEXSOCKADDRS;
3367 static const GUID transmitfile_guid = WSAID_TRANSMITFILE;
3368 static const GUID transmitpackets_guid = WSAID_TRANSMITPACKETS;
3369 static const GUID wsarecvmsg_guid = WSAID_WSARECVMSG;
3370 static const GUID wsasendmsg_guid = WSAID_WSASENDMSG;
3372 if ( IsEqualGUID(&connectex_guid, in_buff) )
3374 *(LPFN_CONNECTEX *)out_buff = WS2_ConnectEx;
3377 else if ( IsEqualGUID(&disconnectex_guid, in_buff) )
3379 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented DisconnectEx\n");
3381 else if ( IsEqualGUID(&acceptex_guid, in_buff) )
3383 *(LPFN_ACCEPTEX *)out_buff = WS2_AcceptEx;
3386 else if ( IsEqualGUID(&getaccepexsockaddrs_guid, in_buff) )
3388 *(LPFN_GETACCEPTEXSOCKADDRS *)out_buff = WS2_GetAcceptExSockaddrs;
3391 else if ( IsEqualGUID(&transmitfile_guid, in_buff) )
3393 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitFile\n");
3395 else if ( IsEqualGUID(&transmitpackets_guid, in_buff) )
3397 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitPackets\n");
3399 else if ( IsEqualGUID(&wsarecvmsg_guid, in_buff) )
3401 *(LPFN_WSARECVMSG *)out_buff = WS2_WSARecvMsg;
3404 else if ( IsEqualGUID(&wsasendmsg_guid, in_buff) )
3406 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented WSASendMsg\n");
3409 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff));
3411 status = WSAEOPNOTSUPP;
3414 case WS_SIO_KEEPALIVE_VALS:
3416 struct tcp_keepalive *k;
3417 int keepalive, keepidle, keepintvl;
3419 if (!in_buff || in_size < sizeof(struct tcp_keepalive))
3421 WSASetLastError(WSAEFAULT);
3422 return SOCKET_ERROR;
3426 keepalive = k->onoff ? 1 : 0;
3427 keepidle = max( 1, (k->keepalivetime + 500) / 1000 );
3428 keepintvl = max( 1, (k->keepaliveinterval + 500) / 1000 );
3430 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
3432 fd = get_sock_fd(s, 0, NULL);
3433 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
3435 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
3436 /* these values need to be set only if SO_KEEPALIVE is enabled */
3439 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
3441 else if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
3446 FIXME("ignoring keepalive interval and timeout\n");
3448 release_sock_fd(s, fd);
3451 case WS_SIO_ROUTING_INTERFACE_QUERY:
3453 struct WS_sockaddr *daddr = (struct WS_sockaddr *)in_buff;
3454 struct WS_sockaddr_in *daddr_in = (struct WS_sockaddr_in *)daddr;
3455 struct WS_sockaddr_in *saddr_in = out_buff;
3456 MIB_IPFORWARDROW row;
3457 PMIB_IPADDRTABLE ipAddrTable = NULL;
3458 DWORD size, i, found_index;
3460 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
3462 if (!in_buff || in_size < sizeof(struct WS_sockaddr) ||
3463 !out_buff || out_size < sizeof(struct WS_sockaddr_in) || !ret_size)
3465 WSASetLastError(WSAEFAULT);
3466 return SOCKET_ERROR;
3468 if (daddr->sa_family != AF_INET)
3470 FIXME("unsupported address family %d\n", daddr->sa_family);
3471 status = WSAEAFNOSUPPORT;
3474 if (GetBestRoute(daddr_in->sin_addr.S_un.S_addr, 0, &row) != NOERROR ||
3475 GetIpAddrTable(NULL, &size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
3480 ipAddrTable = HeapAlloc(GetProcessHeap(), 0, size);
3481 if (GetIpAddrTable(ipAddrTable, &size, FALSE))
3483 HeapFree(GetProcessHeap(), 0, ipAddrTable);
3487 for (i = 0, found_index = ipAddrTable->dwNumEntries;
3488 i < ipAddrTable->dwNumEntries; i++)
3490 if (ipAddrTable->table[i].dwIndex == row.dwForwardIfIndex)
3493 if (found_index == ipAddrTable->dwNumEntries)
3495 ERR("no matching IP address for interface %d\n",
3496 row.dwForwardIfIndex);
3497 HeapFree(GetProcessHeap(), 0, ipAddrTable);
3501 saddr_in->sin_family = AF_INET;
3502 saddr_in->sin_addr.S_un.S_addr = ipAddrTable->table[found_index].dwAddr;
3503 saddr_in->sin_port = 0;
3504 total = sizeof(struct WS_sockaddr_in);
3505 HeapFree(GetProcessHeap(), 0, ipAddrTable);
3508 case WS_SIO_SET_COMPATIBILITY_MODE:
3509 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
3510 status = WSAEOPNOTSUPP;
3512 case WS_SIO_UDP_CONNRESET:
3513 FIXME("WS_SIO_UDP_CONNRESET stub\n");
3515 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
3516 WSASetLastError(WSAEOPNOTSUPP);
3517 return SOCKET_ERROR;
3519 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code));
3520 status = WSAEOPNOTSUPP;
3526 FIXME( "completion routine %p not supported\n", completion );
3528 else if (overlapped)
3530 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
3531 overlapped->Internal = status;
3532 overlapped->InternalHigh = total;
3533 if (overlapped->hEvent) NtSetEvent( overlapped->hEvent, NULL );
3534 if (cvalue) WS_AddCompletion( HANDLE2SOCKET(s), cvalue, status, total );
3539 if (ret_size) *ret_size = total;
3542 SetLastError( status );
3543 return SOCKET_ERROR;
3547 /***********************************************************************
3548 * ioctlsocket (WS2_32.10)
3550 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
3553 return WSAIoctl( s, cmd, argp, sizeof(WS_u_long), argp, sizeof(WS_u_long), &ret_size, NULL, NULL );
3556 /***********************************************************************
3557 * listen (WS2_32.13)
3559 int WINAPI WS_listen(SOCKET s, int backlog)
3561 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
3563 TRACE("socket %04lx, backlog %d\n", s, backlog);
3566 if (listen(fd, backlog) == 0)
3568 release_sock_fd( s, fd );
3569 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
3571 FD_CONNECT|FD_WINE_CONNECTED);
3574 SetLastError(wsaErrno());
3575 release_sock_fd( s, fd );
3577 return SOCKET_ERROR;
3580 /***********************************************************************
3583 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
3585 DWORD n, dwFlags = flags;
3591 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
3592 return SOCKET_ERROR;
3597 /***********************************************************************
3598 * recvfrom (WS2_32.17)
3600 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
3601 struct WS_sockaddr *from, int *fromlen)
3603 DWORD n, dwFlags = flags;
3609 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL, NULL) == SOCKET_ERROR )
3610 return SOCKET_ERROR;
3615 /* allocate a poll array for the corresponding fd sets */
3616 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
3617 const WS_fd_set *exceptfds, int *count_ptr )
3619 unsigned int i, j = 0, count = 0;
3622 if (readfds) count += readfds->fd_count;
3623 if (writefds) count += writefds->fd_count;
3624 if (exceptfds) count += exceptfds->fd_count;
3628 SetLastError(WSAEINVAL);
3631 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0]))))
3633 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
3637 for (i = 0; i < readfds->fd_count; i++, j++)
3639 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
3640 if (fds[j].fd == -1) goto failed;
3641 fds[j].events = POLLIN;
3645 for (i = 0; i < writefds->fd_count; i++, j++)
3647 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
3648 if (fds[j].fd == -1) goto failed;
3649 fds[j].events = POLLOUT;
3653 for (i = 0; i < exceptfds->fd_count; i++, j++)
3655 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
3656 if (fds[j].fd == -1) goto failed;
3657 fds[j].events = POLLHUP;
3666 for (i = 0; i < readfds->fd_count && j < count; i++, j++)
3667 release_sock_fd( readfds->fd_array[i], fds[j].fd );
3669 for (i = 0; i < writefds->fd_count && j < count; i++, j++)
3670 release_sock_fd( writefds->fd_array[i], fds[j].fd );
3672 for (i = 0; i < exceptfds->fd_count && j < count; i++, j++)
3673 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
3674 HeapFree( GetProcessHeap(), 0, fds );
3678 /* release the file descriptor obtained in fd_sets_to_poll */
3679 /* must be called with the original fd_set arrays, before calling get_poll_results */
3680 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
3681 const WS_fd_set *exceptfds, struct pollfd *fds )
3683 unsigned int i, j = 0;
3687 for (i = 0; i < readfds->fd_count; i++, j++)
3688 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
3692 for (i = 0; i < writefds->fd_count; i++, j++)
3693 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
3697 for (i = 0; i < exceptfds->fd_count; i++, j++)
3698 if (fds[j].fd != -1)
3700 /* make sure we have a real error before releasing the fd */
3701 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
3702 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
3707 /* map the poll results back into the Windows fd sets */
3708 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
3709 const struct pollfd *fds )
3711 unsigned int i, j = 0, k, total = 0;
3715 for (i = k = 0; i < readfds->fd_count; i++, j++)
3716 if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
3717 readfds->fd_count = k;
3722 for (i = k = 0; i < writefds->fd_count; i++, j++)
3723 if ((fds[j].revents & POLLOUT) && !(fds[j].revents & POLLHUP))
3724 writefds->fd_array[k++] = writefds->fd_array[i];
3725 writefds->fd_count = k;
3730 for (i = k = 0; i < exceptfds->fd_count; i++, j++)
3731 if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
3732 exceptfds->fd_count = k;
3739 /***********************************************************************
3740 * select (WS2_32.18)
3742 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
3743 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
3744 const struct WS_timeval* ws_timeout)
3746 struct pollfd *pollfds;
3747 struct timeval tv1, tv2;
3749 int count, ret, timeout = -1;
3751 TRACE("read %p, write %p, excp %p timeout %p\n",
3752 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
3754 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )))
3755 return SOCKET_ERROR;
3759 torig = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
3761 gettimeofday( &tv1, 0 );
3764 while ((ret = poll( pollfds, count, timeout )) < 0)
3768 if (!ws_timeout) continue;
3769 gettimeofday( &tv2, 0 );
3771 tv2.tv_sec -= tv1.tv_sec;
3772 tv2.tv_usec -= tv1.tv_usec;
3773 if (tv2.tv_usec < 0)
3775 tv2.tv_usec += 1000000;
3779 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
3780 if (timeout <= 0) break;
3783 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
3785 if (ret == -1) SetLastError(wsaErrno());
3786 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
3787 HeapFree( GetProcessHeap(), 0, pollfds );
3791 /* helper to send completion messages for client-only i/o operation case */
3792 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
3795 SERVER_START_REQ( add_fd_completion )
3797 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
3798 req->cvalue = CompletionValue;
3799 req->status = CompletionStatus;
3800 req->information = Information;
3801 wine_server_call( req );
3807 /***********************************************************************
3810 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
3816 wsabuf.buf = (char*) buf;
3818 if ( WS2_sendto( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
3819 return SOCKET_ERROR;
3824 /***********************************************************************
3825 * WSASend (WS2_32.72)
3827 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3828 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
3829 LPWSAOVERLAPPED lpOverlapped,
3830 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3832 return WS2_sendto( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
3833 NULL, 0, lpOverlapped, lpCompletionRoutine );
3836 /***********************************************************************
3837 * WSASendDisconnect (WS2_32.73)
3839 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
3841 return WS_shutdown( s, SD_SEND );
3845 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3846 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
3847 const struct WS_sockaddr *to, int tolen,
3848 LPWSAOVERLAPPED lpOverlapped,
3849 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3851 unsigned int i, options;
3853 struct ws2_async *wsa = NULL;
3854 int totalLength = 0;
3855 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
3858 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
3859 s, lpBuffers, dwBufferCount, dwFlags,
3860 to, tolen, lpOverlapped, lpCompletionRoutine);
3862 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
3863 TRACE( "fd=%d, options=%x\n", fd, options );
3865 if ( fd == -1 ) return SOCKET_ERROR;
3867 if (!lpOverlapped && !lpNumberOfBytesSent)
3872 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
3878 wsa->hSocket = SOCKET2HANDLE(s);
3879 wsa->addr = (struct WS_sockaddr *)to;
3880 wsa->addrlen.val = tolen;
3881 wsa->flags = dwFlags;
3882 wsa->lpFlags = &wsa->flags;
3883 wsa->control = NULL;
3884 wsa->n_iovecs = dwBufferCount;
3885 wsa->first_iovec = 0;
3886 for ( i = 0; i < dwBufferCount; i++ )
3888 wsa->iovec[i].iov_base = lpBuffers[i].buf;
3889 wsa->iovec[i].iov_len = lpBuffers[i].len;
3890 totalLength += lpBuffers[i].len;
3895 n = WS2_send( fd, wsa );
3896 if (n != -1 || errno != EINTR) break;
3898 if (n == -1 && errno != EAGAIN)
3904 if ((lpOverlapped || lpCompletionRoutine) &&
3905 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
3907 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
3909 wsa->user_overlapped = lpOverlapped;
3910 wsa->completion_func = lpCompletionRoutine;
3911 release_sock_fd( s, fd );
3913 if (n == -1 || n < totalLength)
3915 iosb->u.Status = STATUS_PENDING;
3916 iosb->Information = n == -1 ? 0 : n;
3918 SERVER_START_REQ( register_async )
3920 req->type = ASYNC_TYPE_WRITE;
3921 req->async.handle = wine_server_obj_handle( wsa->hSocket );
3922 req->async.callback = wine_server_client_ptr( WS2_async_send );
3923 req->async.iosb = wine_server_client_ptr( iosb );
3924 req->async.arg = wine_server_client_ptr( wsa );
3925 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
3926 req->async.cvalue = cvalue;
3927 err = wine_server_call( req );
3931 /* Enable the event only after starting the async. The server will deliver it as soon as
3932 the async is done. */
3933 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
3935 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
3936 WSASetLastError( NtStatusToWSAError( err ));
3937 return SOCKET_ERROR;
3940 iosb->u.Status = STATUS_SUCCESS;
3941 iosb->Information = n;
3942 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = n;
3943 if (!wsa->completion_func)
3945 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
3946 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
3947 HeapFree( GetProcessHeap(), 0, wsa );
3949 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
3950 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
3955 if ( _is_blocking(s) )
3957 /* On a blocking non-overlapped stream socket,
3958 * sending blocks until the entire buffer is sent. */
3959 DWORD timeout_start = GetTickCount();
3961 bytes_sent = n == -1 ? 0 : n;
3963 while (wsa->first_iovec < wsa->n_iovecs)
3966 int timeout = GET_SNDTIMEO(fd);
3970 timeout -= GetTickCount() - timeout_start;
3971 if (timeout < 0) timeout = 0;
3975 pfd.events = POLLOUT;
3977 if (!timeout || !poll( &pfd, 1, timeout ))
3980 goto error; /* msdn says a timeout in send is fatal */
3983 n = WS2_send( fd, wsa );
3984 if (n == -1 && errno != EAGAIN && errno != EINTR)
3994 else /* non-blocking */
3996 if (n < totalLength)
3997 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
4000 err = WSAEWOULDBLOCK;
4006 TRACE(" -> %i bytes\n", bytes_sent);
4008 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = bytes_sent;
4009 HeapFree( GetProcessHeap(), 0, wsa );
4010 release_sock_fd( s, fd );
4015 HeapFree( GetProcessHeap(), 0, wsa );
4016 release_sock_fd( s, fd );
4017 WARN(" -> ERROR %d\n", err);
4018 WSASetLastError(err);
4019 return SOCKET_ERROR;
4022 /***********************************************************************
4023 * WSASendTo (WS2_32.74)
4025 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4026 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4027 const struct WS_sockaddr *to, int tolen,
4028 LPWSAOVERLAPPED lpOverlapped,
4029 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4031 return WS2_sendto( s, lpBuffers, dwBufferCount,
4032 lpNumberOfBytesSent, dwFlags,
4034 lpOverlapped, lpCompletionRoutine );
4037 /***********************************************************************
4038 * sendto (WS2_32.20)
4040 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
4041 const struct WS_sockaddr *to, int tolen)
4047 wsabuf.buf = (char*) buf;
4049 if ( WS2_sendto(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
4050 return SOCKET_ERROR;
4055 /***********************************************************************
4056 * setsockopt (WS2_32.21)
4058 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
4059 const char *optval, int optlen)
4063 struct linger linger;
4064 struct timeval tval;
4066 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
4067 s, level, optname, optval, optlen);
4069 /* some broken apps pass the value directly instead of a pointer to it */
4070 if(optlen && IS_INTRESOURCE(optval))
4072 SetLastError(WSAEFAULT);
4073 return SOCKET_ERROR;
4081 /* Some options need some conversion before they can be sent to
4082 * setsockopt. The conversions are done here, then they will fall though
4083 * to the general case. Special options that are not passed to
4084 * setsockopt follow below that.*/
4086 case WS_SO_DONTLINGER:
4089 SetLastError(WSAEFAULT);
4090 return SOCKET_ERROR;
4092 linger.l_onoff = *((const int*)optval) ? 0: 1;
4093 linger.l_linger = 0;
4095 optname = SO_LINGER;
4096 optval = (char*)&linger;
4097 optlen = sizeof(struct linger);
4103 SetLastError(WSAEFAULT);
4104 return SOCKET_ERROR;
4106 linger.l_onoff = ((LINGER*)optval)->l_onoff;
4107 linger.l_linger = ((LINGER*)optval)->l_linger;
4109 optname = SO_LINGER;
4110 optval = (char*)&linger;
4111 optlen = sizeof(struct linger);
4115 if (*(const int*)optval < 2048)
4117 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
4122 /* The options listed here don't need any special handling. Thanks to
4123 * the conversion happening above, options from there will fall through
4125 case WS_SO_ACCEPTCONN:
4126 case WS_SO_BROADCAST:
4128 case WS_SO_KEEPALIVE:
4129 case WS_SO_OOBINLINE:
4130 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
4131 * however, using it the BSD way fixes bug 8513 and seems to be what
4132 * most programmers assume, anyway */
4133 case WS_SO_REUSEADDR:
4136 convert_sockopt(&level, &optname);
4139 /* SO_DEBUG is a privileged operation, ignore it. */
4141 TRACE("Ignoring SO_DEBUG\n");
4144 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
4145 * socket. According to MSDN, this option is silently ignored.*/
4146 case WS_SO_DONTROUTE:
4147 TRACE("Ignoring SO_DONTROUTE\n");
4150 /* Stops two sockets from being bound to the same port. Always happens
4151 * on unix systems, so just drop it. */
4152 case WS_SO_EXCLUSIVEADDRUSE:
4153 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
4156 /* After a ConnectEx call succeeds, the socket can't be used with half of the
4157 * normal winsock functions on windows. We don't have that problem. */
4158 case WS_SO_UPDATE_CONNECT_CONTEXT:
4159 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
4162 /* After a AcceptEx call succeeds, the socket can't be used with half of the
4163 * normal winsock functions on windows. We don't have that problem. */
4164 case WS_SO_UPDATE_ACCEPT_CONTEXT:
4165 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
4168 /* SO_OPENTYPE does not require a valid socket handle. */
4169 case WS_SO_OPENTYPE:
4170 if (!optlen || optlen < sizeof(int) || !optval)
4172 SetLastError(WSAEFAULT);
4173 return SOCKET_ERROR;
4175 get_per_thread_data()->opentype = *(const int *)optval;
4176 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
4180 case WS_SO_RCVTIMEO:
4183 case WS_SO_SNDTIMEO:
4185 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
4186 if (optval && optlen == sizeof(UINT32)) {
4187 /* WinSock passes milliseconds instead of struct timeval */
4188 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
4189 tval.tv_sec = *(const UINT32*)optval / 1000;
4190 /* min of 500 milliseconds */
4191 if (tval.tv_sec == 0 && tval.tv_usec && tval.tv_usec < 500000)
4192 tval.tv_usec = 500000;
4193 optlen = sizeof(struct timeval);
4194 optval = (char*)&tval;
4195 } else if (optlen == sizeof(struct timeval)) {
4196 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
4198 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
4201 convert_sockopt(&level, &optname);
4206 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
4207 SetLastError(WSAENOPROTOOPT);
4208 return SOCKET_ERROR;
4210 break; /* case WS_SOL_SOCKET */
4217 fd = get_sock_fd( s, 0, NULL );
4218 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", *(const int*)optval, fd);
4220 /* We try to set the ipx type on ipx socket level. */
4222 if(setsockopt(fd, SOL_IPX, IPX_TYPE, optval, optlen) == -1)
4224 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
4225 release_sock_fd( s, fd );
4226 return SOCKET_ERROR;
4231 /* Should we retrieve val using a getsockopt call and then
4232 * set the modified one? */
4233 val.ipx_pt = *optval;
4234 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
4237 release_sock_fd( s, fd );
4240 case IPX_FILTERPTYPE:
4241 /* Sets the receive filter packet type, at the moment we don't support it */
4242 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
4243 /* Returning 0 is better for now than returning a SOCKET_ERROR */
4247 FIXME("opt_name:%x\n", optname);
4248 return SOCKET_ERROR;
4250 break; /* case NSPROTO_IPX */
4253 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
4254 case WS_IPPROTO_TCP:
4257 case WS_TCP_NODELAY:
4258 convert_sockopt(&level, &optname);
4261 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
4262 return SOCKET_ERROR;
4269 case WS_IP_ADD_MEMBERSHIP:
4270 case WS_IP_DROP_MEMBERSHIP:
4274 case WS_IP_MULTICAST_IF:
4275 case WS_IP_MULTICAST_LOOP:
4276 case WS_IP_MULTICAST_TTL:
4283 #ifdef IP_UNICAST_IF
4284 case WS_IP_UNICAST_IF:
4286 convert_sockopt(&level, &optname);
4288 case WS_IP_DONTFRAGMENT:
4289 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
4292 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
4293 return SOCKET_ERROR;
4297 case WS_IPPROTO_IPV6:
4300 #ifdef IPV6_ADD_MEMBERSHIP
4301 case WS_IPV6_ADD_MEMBERSHIP:
4303 #ifdef IPV6_DROP_MEMBERSHIP
4304 case WS_IPV6_DROP_MEMBERSHIP:
4306 case WS_IPV6_MULTICAST_IF:
4307 case WS_IPV6_MULTICAST_HOPS:
4308 case WS_IPV6_MULTICAST_LOOP:
4309 case WS_IPV6_UNICAST_HOPS:
4310 case WS_IPV6_V6ONLY:
4311 #ifdef IPV6_UNICAST_IF
4312 case WS_IPV6_UNICAST_IF:
4314 convert_sockopt(&level, &optname);
4316 case WS_IPV6_DONTFRAG:
4317 FIXME("IPV6_DONTFRAG is silently ignored!\n");
4319 case WS_IPV6_PROTECTION_LEVEL:
4320 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
4323 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
4324 return SOCKET_ERROR;
4329 WARN("Unknown level: 0x%08x\n", level);
4330 SetLastError(WSAEINVAL);
4331 return SOCKET_ERROR;
4332 } /* end switch(level) */
4334 /* avoid endianness issues if argument is a 16-bit int */
4335 if (optval && optlen < sizeof(int))
4337 woptval= *((const INT16 *) optval);
4338 optval= (char*) &woptval;
4341 fd = get_sock_fd( s, 0, NULL );
4342 if (fd == -1) return SOCKET_ERROR;
4344 if (setsockopt(fd, level, optname, optval, optlen) == 0)
4346 release_sock_fd( s, fd );
4349 TRACE("Setting socket error, %d\n", wsaErrno());
4350 SetLastError(wsaErrno());
4351 release_sock_fd( s, fd );
4353 return SOCKET_ERROR;
4356 /***********************************************************************
4357 * shutdown (WS2_32.22)
4359 int WINAPI WS_shutdown(SOCKET s, int how)
4361 int fd, err = WSAENOTSOCK;
4362 unsigned int options, clear_flags = 0;
4364 fd = get_sock_fd( s, 0, &options );
4365 TRACE("socket %04lx, how %i %x\n", s, how, options );
4368 return SOCKET_ERROR;
4372 case 0: /* drop receives */
4373 clear_flags |= FD_READ;
4375 case 1: /* drop sends */
4376 clear_flags |= FD_WRITE;
4378 case 2: /* drop all */
4379 clear_flags |= FD_READ|FD_WRITE;
4382 clear_flags |= FD_WINE_LISTENING;
4385 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
4390 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
4393 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
4397 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
4398 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
4401 if (err) goto error;
4403 else /* non-overlapped mode */
4405 if ( shutdown( fd, how ) )
4412 release_sock_fd( s, fd );
4413 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
4414 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
4418 release_sock_fd( s, fd );
4419 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
4420 WSASetLastError( err );
4421 return SOCKET_ERROR;
4424 /***********************************************************************
4425 * socket (WS2_32.23)
4427 SOCKET WINAPI WS_socket(int af, int type, int protocol)
4429 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
4431 return WSASocketA( af, type, protocol, NULL, 0,
4432 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
4436 /***********************************************************************
4437 * gethostbyaddr (WS2_32.51)
4439 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
4441 struct WS_hostent *retval = NULL;
4442 struct hostent* host;
4444 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4447 struct hostent hostentry;
4450 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
4452 int res = gethostbyaddr_r(addr, len, type,
4453 &hostentry, extrabuf, ebufsize, &host, &locerr);
4454 if( res != ERANGE) break;
4456 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
4458 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
4460 EnterCriticalSection( &csWSgetXXXbyYYY );
4461 host = gethostbyaddr(addr, len, type);
4462 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
4464 if( host != NULL ) retval = WS_dup_he(host);
4465 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4466 HeapFree(GetProcessHeap(),0,extrabuf);
4468 LeaveCriticalSection( &csWSgetXXXbyYYY );
4470 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
4474 /***********************************************************************
4475 * WS_get_local_ips (INTERNAL)
4477 * Returns the list of local IP addresses by going through the network
4478 * adapters and using the local routing table to sort the addresses
4479 * from highest routing priority to lowest routing priority. This
4480 * functionality is inferred from the description for obtaining local
4481 * IP addresses given in the Knowledge Base Article Q160215.
4483 * Please note that the returned hostent is only freed when the thread
4484 * closes and is replaced if another hostent is requested.
4486 static struct WS_hostent* WS_get_local_ips( char *hostname )
4488 int last_metric, numroutes = 0, i, j;
4489 PIP_ADAPTER_INFO adapters = NULL, k;
4490 struct WS_hostent *hostlist = NULL;
4491 PMIB_IPFORWARDTABLE routes = NULL;
4492 struct route *route_addrs = NULL;
4493 DWORD adap_size, route_size;
4495 /* Obtain the size of the adapter list and routing table, also allocate memory */
4496 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
4498 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
4500 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
4501 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
4502 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
4503 if (adapters == NULL || routes == NULL || route_addrs == NULL)
4505 /* Obtain the adapter list and the full routing table */
4506 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
4508 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
4510 /* Store the interface associated with each route */
4511 for (i = 0; i < routes->dwNumEntries; i++)
4514 DWORD ifmetric, exists = FALSE;
4516 if (routes->table[i].u1.ForwardType != MIB_IPROUTE_TYPE_DIRECT)
4518 ifindex = routes->table[i].dwForwardIfIndex;
4519 ifmetric = routes->table[i].dwForwardMetric1;
4520 /* Only store the lowest valued metric for an interface */
4521 for (j = 0; j < numroutes; j++)
4523 if (route_addrs[j].interface == ifindex)
4525 if (route_addrs[j].metric > ifmetric)
4526 route_addrs[j].metric = ifmetric;
4532 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
4533 if (route_addrs == NULL)
4534 goto cleanup; /* Memory allocation error, fail gracefully */
4535 route_addrs[numroutes].interface = ifindex;
4536 route_addrs[numroutes].metric = ifmetric;
4537 /* If no IP is found in the next step (for whatever reason)
4538 * then fall back to the magic loopback address.
4540 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
4544 goto cleanup; /* No routes, fall back to the Magic IP */
4545 /* Find the IP address associated with each found interface */
4546 for (i = 0; i < numroutes; i++)
4548 for (k = adapters; k != NULL; k = k->Next)
4550 char *ip = k->IpAddressList.IpAddress.String;
4552 if (route_addrs[i].interface == k->Index)
4553 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
4556 /* Allocate a hostent and enough memory for all the IPs,
4557 * including the NULL at the end of the list.
4559 hostlist = WS_create_he(hostname, 1, numroutes+1, TRUE);
4560 if (hostlist == NULL)
4561 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
4562 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
4563 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
4564 hostlist->h_addrtype = AF_INET;
4565 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
4566 /* Reorder the entries when placing them in the host list, Windows expects
4567 * the IP list in order from highest priority to lowest (the critical thing
4568 * is that most applications expect the first IP to be the default route).
4571 for (i = 0; i < numroutes; i++)
4573 struct in_addr addr;
4574 int metric = 0xFFFF;
4576 memcpy(&addr, magic_loopback_addr, 4);
4577 for (j = 0; j < numroutes; j++)
4579 int this_metric = route_addrs[j].metric;
4581 if (this_metric > last_metric && this_metric < metric)
4583 addr = route_addrs[j].addr;
4584 metric = this_metric;
4587 last_metric = metric;
4588 (*(struct in_addr *) hostlist->h_addr_list[i]) = addr;
4591 /* Cleanup all allocated memory except the address list,
4592 * the address list is used by the calling app.
4595 HeapFree(GetProcessHeap(), 0, route_addrs);
4596 HeapFree(GetProcessHeap(), 0, adapters);
4597 HeapFree(GetProcessHeap(), 0, routes);
4601 /***********************************************************************
4602 * gethostbyname (WS2_32.52)
4604 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
4606 struct WS_hostent *retval = NULL;
4607 struct hostent* host;
4608 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4611 struct hostent hostentry;
4612 int locerr = ENOBUFS;
4616 SetLastError(WSANOTINITIALISED);
4619 if( gethostname( hostname, 100) == -1) {
4620 SetLastError( WSAENOBUFS); /* appropriate ? */
4623 if( !name || !name[0]) {
4626 /* If the hostname of the local machine is requested then return the
4627 * complete list of local IP addresses */
4628 if(strcmp(name, hostname) == 0)
4629 retval = WS_get_local_ips(hostname);
4630 /* If any other hostname was requested (or the routing table lookup failed)
4631 * then return the IP found by the host OS */
4634 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4636 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
4638 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
4639 if( res != ERANGE) break;
4641 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
4643 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
4645 EnterCriticalSection( &csWSgetXXXbyYYY );
4646 host = gethostbyname(name);
4647 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
4649 if (host) retval = WS_dup_he(host);
4650 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4651 HeapFree(GetProcessHeap(),0,extrabuf);
4653 LeaveCriticalSection( &csWSgetXXXbyYYY );
4656 if (retval && retval->h_addr_list[0][0] == 127 &&
4657 strcmp(name, "localhost") != 0)
4659 /* hostname != "localhost" but has loopback address. replace by our
4660 * special address.*/
4661 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
4663 TRACE( "%s ret %p\n", debugstr_a(name), retval );
4668 /***********************************************************************
4669 * getprotobyname (WS2_32.53)
4671 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
4673 struct WS_protoent* retval = NULL;
4674 #ifdef HAVE_GETPROTOBYNAME
4675 struct protoent* proto;
4676 EnterCriticalSection( &csWSgetXXXbyYYY );
4677 if( (proto = getprotobyname(name)) != NULL )
4679 retval = WS_dup_pe(proto);
4682 MESSAGE("protocol %s not found; You might want to add "
4683 "this to /etc/protocols\n", debugstr_a(name) );
4684 SetLastError(WSANO_DATA);
4686 LeaveCriticalSection( &csWSgetXXXbyYYY );
4688 TRACE( "%s ret %p\n", debugstr_a(name), retval );
4693 /***********************************************************************
4694 * getprotobynumber (WS2_32.54)
4696 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
4698 struct WS_protoent* retval = NULL;
4699 #ifdef HAVE_GETPROTOBYNUMBER
4700 struct protoent* proto;
4701 EnterCriticalSection( &csWSgetXXXbyYYY );
4702 if( (proto = getprotobynumber(number)) != NULL )
4704 retval = WS_dup_pe(proto);
4707 MESSAGE("protocol number %d not found; You might want to add "
4708 "this to /etc/protocols\n", number );
4709 SetLastError(WSANO_DATA);
4711 LeaveCriticalSection( &csWSgetXXXbyYYY );
4713 TRACE("%i ret %p\n", number, retval);
4718 /***********************************************************************
4719 * getservbyname (WS2_32.55)
4721 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
4723 struct WS_servent* retval = NULL;
4724 struct servent* serv;
4726 char *proto_str = NULL;
4728 if (!(name_str = strdup_lower(name))) return NULL;
4730 if (proto && *proto)
4732 if (!(proto_str = strdup_lower(proto)))
4734 HeapFree( GetProcessHeap(), 0, name_str );
4739 EnterCriticalSection( &csWSgetXXXbyYYY );
4740 serv = getservbyname(name_str, proto_str);
4743 retval = WS_dup_se(serv);
4745 else SetLastError(WSANO_DATA);
4746 LeaveCriticalSection( &csWSgetXXXbyYYY );
4747 HeapFree( GetProcessHeap(), 0, proto_str );
4748 HeapFree( GetProcessHeap(), 0, name_str );
4749 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
4753 /***********************************************************************
4754 * freeaddrinfo (WS2_32.@)
4756 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
4759 struct WS_addrinfo *next;
4761 HeapFree(GetProcessHeap(),0,res->ai_canonname);
4762 HeapFree(GetProcessHeap(),0,res->ai_addr);
4763 next = res->ai_next;
4764 HeapFree(GetProcessHeap(),0,res);
4769 /* helper functions for getaddrinfo()/getnameinfo() */
4770 static int convert_aiflag_w2u(int winflags) {
4774 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
4775 if (ws_aiflag_map[i][0] & winflags) {
4776 unixflags |= ws_aiflag_map[i][1];
4777 winflags &= ~ws_aiflag_map[i][0];
4780 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
4784 static int convert_niflag_w2u(int winflags) {
4788 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
4789 if (ws_niflag_map[i][0] & winflags) {
4790 unixflags |= ws_niflag_map[i][1];
4791 winflags &= ~ws_niflag_map[i][0];
4794 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
4798 static int convert_aiflag_u2w(int unixflags) {
4802 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
4803 if (ws_aiflag_map[i][1] & unixflags) {
4804 winflags |= ws_aiflag_map[i][0];
4805 unixflags &= ~ws_aiflag_map[i][1];
4807 if (unixflags) /* will warn usually */
4808 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
4812 static int convert_eai_u2w(int unixret) {
4815 for (i=0;ws_eai_map[i][0];i++)
4816 if (ws_eai_map[i][1] == unixret)
4817 return ws_eai_map[i][0];
4821 static char *get_hostname(void)
4826 GetComputerNameExA( ComputerNamePhysicalDnsHostname, NULL, &size );
4827 if (GetLastError() != ERROR_MORE_DATA) return NULL;
4828 if (!(ret = HeapAlloc( GetProcessHeap(), 0, size ))) return NULL;
4829 if (!GetComputerNameExA( ComputerNamePhysicalDnsHostname, ret, &size ))
4831 HeapFree( GetProcessHeap(), 0, ret );
4837 /***********************************************************************
4838 * getaddrinfo (WS2_32.@)
4840 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
4842 #ifdef HAVE_GETADDRINFO
4843 struct addrinfo *unixaires = NULL;
4845 struct addrinfo unixhints, *punixhints = NULL;
4846 char *hostname = NULL;
4849 if (!nodename && !servname) return WSAHOST_NOT_FOUND;
4853 else if (!nodename[0])
4855 node = hostname = get_hostname();
4856 if (!node) return WSA_NOT_ENOUGH_MEMORY;
4862 punixhints = &unixhints;
4864 memset(&unixhints, 0, sizeof(unixhints));
4865 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
4866 if (hints->ai_family == 0) /* wildcard, specific to getaddrinfo() */
4867 punixhints->ai_family = 0;
4869 punixhints->ai_family = convert_af_w2u(hints->ai_family);
4870 if (hints->ai_socktype == 0) /* wildcard, specific to getaddrinfo() */
4871 punixhints->ai_socktype = 0;
4873 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
4874 if (hints->ai_protocol == 0) /* wildcard, specific to getaddrinfo() */
4875 punixhints->ai_protocol = 0;
4877 punixhints->ai_protocol = convert_proto_w2u(hints->ai_protocol);
4880 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
4881 result = getaddrinfo(node, servname, punixhints, &unixaires);
4883 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
4884 HeapFree(GetProcessHeap(), 0, hostname);
4887 struct addrinfo *xuai = unixaires;
4888 struct WS_addrinfo **xai = res;
4892 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
4898 *xai = ai;xai = &ai->ai_next;
4899 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
4900 ai->ai_family = convert_af_u2w(xuai->ai_family);
4901 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
4902 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
4903 if (xuai->ai_canonname) {
4904 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
4905 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
4906 if (!ai->ai_canonname)
4908 strcpy(ai->ai_canonname,xuai->ai_canonname);
4910 len = xuai->ai_addrlen;
4911 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
4914 ai->ai_addrlen = len;
4916 int winlen = ai->ai_addrlen;
4918 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
4919 ai->ai_addrlen = winlen;
4923 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
4926 ai->ai_addrlen = len;
4928 xuai = xuai->ai_next;
4930 freeaddrinfo(unixaires);
4932 result = convert_eai_u2w(result);
4938 if (*res) WS_freeaddrinfo(*res);
4939 if (unixaires) freeaddrinfo(unixaires);
4941 return WSA_NOT_ENOUGH_MEMORY;
4943 FIXME("getaddrinfo() failed, not found during buildtime.\n");
4948 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
4950 struct WS_addrinfoW *ret;
4952 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
4953 ret->ai_flags = ai->ai_flags;
4954 ret->ai_family = ai->ai_family;
4955 ret->ai_socktype = ai->ai_socktype;
4956 ret->ai_protocol = ai->ai_protocol;
4957 ret->ai_addrlen = ai->ai_addrlen;
4958 ret->ai_canonname = NULL;
4959 ret->ai_addr = NULL;
4960 ret->ai_next = NULL;
4961 if (ai->ai_canonname)
4963 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
4964 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
4966 HeapFree(GetProcessHeap(), 0, ret);
4969 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
4973 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
4975 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
4976 HeapFree(GetProcessHeap(), 0, ret);
4979 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
4984 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
4986 struct WS_addrinfoW *ret, *infoW;
4988 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
4989 while (info->ai_next)
4991 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
4996 infoW = infoW->ai_next;
4997 info = info->ai_next;
5002 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
5004 struct WS_addrinfo *ret;
5006 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
5007 ret->ai_flags = ai->ai_flags;
5008 ret->ai_family = ai->ai_family;
5009 ret->ai_socktype = ai->ai_socktype;
5010 ret->ai_protocol = ai->ai_protocol;
5011 ret->ai_addrlen = ai->ai_addrlen;
5012 ret->ai_canonname = NULL;
5013 ret->ai_addr = NULL;
5014 ret->ai_next = NULL;
5015 if (ai->ai_canonname)
5017 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
5018 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
5020 HeapFree(GetProcessHeap(), 0, ret);
5023 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
5027 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
5029 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
5030 HeapFree(GetProcessHeap(), 0, ret);
5033 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
5038 /***********************************************************************
5039 * GetAddrInfoW (WS2_32.@)
5041 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
5044 char *nodenameA = NULL, *servnameA = NULL;
5045 struct WS_addrinfo *resA, *hintsA = NULL;
5049 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
5050 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
5051 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
5055 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
5056 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
5058 HeapFree(GetProcessHeap(), 0, nodenameA);
5061 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
5064 if (hints) hintsA = addrinfo_WtoA(hints);
5065 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
5066 WS_freeaddrinfo(hintsA);
5070 *res = addrinfo_list_AtoW(resA);
5071 WS_freeaddrinfo(resA);
5074 HeapFree(GetProcessHeap(), 0, nodenameA);
5075 HeapFree(GetProcessHeap(), 0, servnameA);
5079 /***********************************************************************
5080 * FreeAddrInfoW (WS2_32.@)
5082 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
5087 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
5088 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
5090 HeapFree(GetProcessHeap(), 0, ai);
5095 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
5096 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
5098 #ifdef HAVE_GETNAMEINFO
5100 union generic_unix_sockaddr sa_u;
5103 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
5104 serv, servlen, flags);
5106 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
5109 WSASetLastError(WSAEFAULT);
5110 return WSA_NOT_ENOUGH_MEMORY;
5112 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
5113 return convert_eai_u2w(ret);
5115 FIXME("getnameinfo() failed, not found during buildtime.\n");
5120 int WINAPI GetNameInfoW(const SOCKADDR *sa, WS_socklen_t salen, PWCHAR host,
5121 DWORD hostlen, PWCHAR serv, DWORD servlen, INT flags)
5124 char *hostA = NULL, *servA = NULL;
5126 if (host && (!(hostA = HeapAlloc(GetProcessHeap(), 0, hostlen)))) return EAI_MEMORY;
5127 if (serv && (!(servA = HeapAlloc(GetProcessHeap(), 0, servlen))))
5129 HeapFree(GetProcessHeap(), 0, hostA);
5133 ret = WS_getnameinfo(sa, salen, hostA, hostlen, servA, servlen, flags);
5136 if (host) MultiByteToWideChar(CP_ACP, 0, hostA, -1, host, hostlen);
5137 if (serv) MultiByteToWideChar(CP_ACP, 0, servA, -1, serv, servlen);
5140 HeapFree(GetProcessHeap(), 0, hostA);
5141 HeapFree(GetProcessHeap(), 0, servA);
5145 /***********************************************************************
5146 * getservbyport (WS2_32.56)
5148 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
5150 struct WS_servent* retval = NULL;
5151 #ifdef HAVE_GETSERVBYPORT
5152 struct servent* serv;
5153 char *proto_str = NULL;
5155 if (proto && *proto)
5157 if (!(proto_str = strdup_lower(proto))) return NULL;
5159 EnterCriticalSection( &csWSgetXXXbyYYY );
5160 if( (serv = getservbyport(port, proto_str)) != NULL ) {
5161 retval = WS_dup_se(serv);
5163 else SetLastError(WSANO_DATA);
5164 LeaveCriticalSection( &csWSgetXXXbyYYY );
5165 HeapFree( GetProcessHeap(), 0, proto_str );
5167 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
5172 /***********************************************************************
5173 * gethostname (WS2_32.57)
5175 int WINAPI WS_gethostname(char *name, int namelen)
5177 TRACE("name %p, len %d\n", name, namelen);
5179 if (gethostname(name, namelen) == 0)
5181 TRACE("<- '%s'\n", name);
5184 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
5185 TRACE("<- ERROR !\n");
5186 return SOCKET_ERROR;
5190 /* ------------------------------------- Windows sockets extensions -- *
5192 * ------------------------------------------------------------------- */
5194 /***********************************************************************
5195 * WSAEnumNetworkEvents (WS2_32.36)
5197 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
5201 int errors[FD_MAX_EVENTS];
5203 TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
5205 SERVER_START_REQ( get_socket_event )
5207 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5208 req->service = TRUE;
5209 req->c_event = wine_server_obj_handle( hEvent );
5210 wine_server_set_reply( req, errors, sizeof(errors) );
5211 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
5216 for (i = 0; i < FD_MAX_EVENTS; i++)
5217 lpEvent->iErrorCode[i] = NtStatusToWSAError(errors[i]);
5220 SetLastError(WSAEINVAL);
5221 return SOCKET_ERROR;
5224 /***********************************************************************
5225 * WSAEventSelect (WS2_32.39)
5227 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
5231 TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
5233 SERVER_START_REQ( set_socket_event )
5235 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5237 req->event = wine_server_obj_handle( hEvent );
5240 ret = wine_server_call( req );
5244 SetLastError(WSAEINVAL);
5245 return SOCKET_ERROR;
5248 /**********************************************************************
5249 * WSAGetOverlappedResult (WS2_32.40)
5251 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
5252 LPDWORD lpcbTransfer, BOOL fWait,
5257 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
5258 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
5260 if ( lpOverlapped == NULL )
5262 ERR( "Invalid pointer\n" );
5263 WSASetLastError(WSA_INVALID_PARAMETER);
5267 status = lpOverlapped->Internal;
5268 if (status == STATUS_PENDING)
5272 SetLastError( WSA_IO_INCOMPLETE );
5276 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
5277 INFINITE ) == WAIT_FAILED)
5279 status = lpOverlapped->Internal;
5283 *lpcbTransfer = lpOverlapped->InternalHigh;
5286 *lpdwFlags = lpOverlapped->u.s.Offset;
5288 if (status) SetLastError( RtlNtStatusToDosError(status) );
5293 /***********************************************************************
5294 * WSAAsyncSelect (WS2_32.101)
5296 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
5300 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
5302 SERVER_START_REQ( set_socket_event )
5304 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5307 req->window = wine_server_user_handle( hWnd );
5309 ret = wine_server_call( req );
5313 SetLastError(WSAEINVAL);
5314 return SOCKET_ERROR;
5317 /***********************************************************************
5318 * WSACreateEvent (WS2_32.31)
5321 WSAEVENT WINAPI WSACreateEvent(void)
5323 /* Create a manual-reset event, with initial state: unsignaled */
5326 return CreateEventW(NULL, TRUE, FALSE, NULL);
5329 /***********************************************************************
5330 * WSACloseEvent (WS2_32.29)
5333 BOOL WINAPI WSACloseEvent(WSAEVENT event)
5335 TRACE ("event=%p\n", event);
5337 return CloseHandle(event);
5340 /***********************************************************************
5341 * WSASocketA (WS2_32.78)
5344 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
5345 LPWSAPROTOCOL_INFOA lpProtocolInfo,
5346 GROUP g, DWORD dwFlags)
5349 WSAPROTOCOL_INFOW info;
5351 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
5352 af, type, protocol, lpProtocolInfo, g, dwFlags);
5354 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
5356 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
5357 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
5358 info.szProtocol, WSAPROTOCOL_LEN + 1);
5362 WSASetLastError( WSAEINVAL);
5363 return SOCKET_ERROR;
5366 return WSASocketW(af, type, protocol, &info, g, dwFlags);
5369 /***********************************************************************
5370 * WSASocketW (WS2_32.79)
5373 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
5374 LPWSAPROTOCOL_INFOW lpProtocolInfo,
5375 GROUP g, DWORD dwFlags)
5380 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
5381 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
5384 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
5385 af, type, protocol, lpProtocolInfo, g, dwFlags );
5387 /* hack for WSADuplicateSocket */
5388 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
5389 ret = lpProtocolInfo->dwCatalogEntryId;
5390 TRACE("\tgot duplicate %04lx\n", ret);
5394 /* convert the socket family and type */
5395 af = convert_af_w2u(af);
5396 type = convert_socktype_w2u(type);
5400 if (af == FROM_PROTOCOL_INFO)
5401 af = lpProtocolInfo->iAddressFamily;
5402 if (type == FROM_PROTOCOL_INFO)
5403 type = lpProtocolInfo->iSocketType;
5404 if (protocol == FROM_PROTOCOL_INFO)
5405 protocol = lpProtocolInfo->iProtocol;
5408 if ( af == AF_UNSPEC) /* did they not specify the address family? */
5410 if ((protocol == IPPROTO_TCP && type == SOCK_STREAM) ||
5411 (protocol == IPPROTO_UDP && type == SOCK_DGRAM))
5417 SetLastError(WSAEPROTOTYPE);
5418 return INVALID_SOCKET;
5422 SERVER_START_REQ( create_socket )
5426 req->protocol = protocol;
5427 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
5428 req->attributes = OBJ_INHERIT;
5429 req->flags = dwFlags;
5430 set_error( wine_server_call( req ) );
5431 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
5436 TRACE("\tcreated %04lx\n", ret );
5440 if (GetLastError() == WSAEACCES) /* raw socket denied */
5442 if (type == SOCK_RAW)
5443 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
5445 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
5446 SetLastError(WSAESOCKTNOSUPPORT);
5449 WARN("\t\tfailed!\n");
5450 return INVALID_SOCKET;
5453 /***********************************************************************
5454 * WSAJoinLeaf (WS2_32.58)
5457 SOCKET WINAPI WSAJoinLeaf(
5459 const struct WS_sockaddr *addr,
5461 LPWSABUF lpCallerData,
5462 LPWSABUF lpCalleeData,
5468 return INVALID_SOCKET;
5471 /***********************************************************************
5472 * __WSAFDIsSet (WS2_32.151)
5474 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
5476 int i = set->fd_count;
5478 TRACE("(%ld,%p(%i))\n", s, set, i);
5481 if (set->fd_array[i] == s) return 1;
5485 /***********************************************************************
5486 * WSAIsBlocking (WS2_32.114)
5488 BOOL WINAPI WSAIsBlocking(void)
5490 /* By default WinSock should set all its sockets to non-blocking mode
5491 * and poll in PeekMessage loop when processing "blocking" ones. This
5492 * function is supposed to tell if the program is in this loop. Our
5493 * blocking calls are truly blocking so we always return FALSE.
5495 * Note: It is allowed to call this function without prior WSAStartup().
5502 /***********************************************************************
5503 * WSACancelBlockingCall (WS2_32.113)
5505 INT WINAPI WSACancelBlockingCall(void)
5511 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
5513 FIXME("How was this called?\n");
5518 /***********************************************************************
5519 * WSASetBlockingHook (WS2_32.109)
5521 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
5523 FARPROC prev = blocking_hook;
5524 blocking_hook = lpBlockFunc;
5525 TRACE("hook %p\n", lpBlockFunc);
5530 /***********************************************************************
5531 * WSAUnhookBlockingHook (WS2_32.110)
5533 INT WINAPI WSAUnhookBlockingHook(void)
5535 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
5540 /* ----------------------------------- end of API stuff */
5542 /* ----------------------------------- helper functions -
5544 * TODO: Merge WS_dup_..() stuff into one function that
5545 * would operate with a generic structure containing internal
5546 * pointers (via a template of some kind).
5549 static int list_size(char** l, int item_size)
5554 j += (item_size) ? item_size : strlen(l[i]) + 1;
5555 j += (i + 1) * sizeof(char*); }
5559 static int list_dup(char** l_src, char** l_to, int item_size)
5564 for (i = 0; l_src[i]; i++) ;
5565 p = (char *)(l_to + i + 1);
5566 for (i = 0; l_src[i]; i++)
5568 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
5569 memcpy(p, l_src[i], count);
5574 return p - (char *)l_to;
5579 /* create a hostent entry
5581 * Creates the entry with enough memory for the name, aliases
5582 * addresses, and the address pointers. Also copies the name
5583 * and sets up all the pointers. If "fill_addresses" is set then
5584 * sufficient memory for the addresses is also allocated and the
5585 * address pointers are set to this memory.
5587 * NOTE: The alias and address lists must be allocated with room
5588 * for the NULL item terminating the list. This is true even if
5589 * the list has no items ("aliases" and "addresses" must be
5590 * at least "1", a truly empty list is invalid).
5592 static struct WS_hostent *WS_create_he(char *name, int aliases, int addresses, int fill_addresses)
5594 struct WS_hostent *p_to;
5597 int size = (sizeof(struct WS_hostent) +
5599 sizeof(char *)*aliases +
5600 sizeof(char *)*addresses);
5602 /* Allocate enough memory for the addresses */
5604 size += sizeof(struct in_addr)*addresses;
5606 if (!(p_to = check_buffer_he(size))) return NULL;
5607 memset(p_to, 0, size);
5609 p = (char *)(p_to + 1);
5614 p_to->h_aliases = (char **)p;
5615 p += sizeof(char *)*aliases;
5616 p_to->h_addr_list = (char **)p;
5617 p += sizeof(char *)*addresses;
5622 /* NOTE: h_aliases must be filled in manually, leave these
5623 * pointers NULL (already set to NULL by memset earlier).
5626 /* Fill in the list of address pointers */
5627 for (i = 0; i < addresses; i++)
5628 p_to->h_addr_list[i] = (p += sizeof(struct in_addr));
5629 p += sizeof(struct in_addr);
5634 /* duplicate hostent entry
5635 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
5636 * Ditto for protoent and servent.
5638 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
5640 int addresses = list_size(p_he->h_addr_list, p_he->h_length);
5641 int aliases = list_size(p_he->h_aliases, 0);
5642 struct WS_hostent *p_to;
5644 p_to = WS_create_he(p_he->h_name, aliases, addresses, FALSE);
5646 if (!p_to) return NULL;
5647 p_to->h_addrtype = p_he->h_addrtype;
5648 p_to->h_length = p_he->h_length;
5650 list_dup(p_he->h_aliases, p_to->h_aliases, 0);
5651 list_dup(p_he->h_addr_list, p_to->h_addr_list, p_he->h_length);
5655 /* ----- protoent */
5657 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
5660 struct WS_protoent *p_to;
5662 int size = (sizeof(*p_pe) +
5663 strlen(p_pe->p_name) + 1 +
5664 list_size(p_pe->p_aliases, 0));
5666 if (!(p_to = check_buffer_pe(size))) return NULL;
5667 p_to->p_proto = p_pe->p_proto;
5669 p = (char *)(p_to + 1);
5671 strcpy(p, p_pe->p_name);
5674 p_to->p_aliases = (char **)p;
5675 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
5681 static struct WS_servent *WS_dup_se(const struct servent* p_se)
5684 struct WS_servent *p_to;
5686 int size = (sizeof(*p_se) +
5687 strlen(p_se->s_proto) + 1 +
5688 strlen(p_se->s_name) + 1 +
5689 list_size(p_se->s_aliases, 0));
5691 if (!(p_to = check_buffer_se(size))) return NULL;
5692 p_to->s_port = p_se->s_port;
5694 p = (char *)(p_to + 1);
5696 strcpy(p, p_se->s_name);
5700 strcpy(p, p_se->s_proto);
5703 p_to->s_aliases = (char **)p;
5704 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
5709 /***********************************************************************
5710 * WSARecv (WS2_32.67)
5712 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5713 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
5714 LPWSAOVERLAPPED lpOverlapped,
5715 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
5717 return WS2_recv_base(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
5718 NULL, NULL, lpOverlapped, lpCompletionRoutine, NULL);
5721 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5722 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
5723 struct WS_sockaddr *lpFrom,
5724 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
5725 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
5726 LPWSABUF lpControlBuffer )
5728 unsigned int i, options;
5730 struct ws2_async *wsa;
5731 DWORD timeout_start = GetTickCount();
5732 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
5734 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
5735 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
5736 (lpFromlen ? *lpFromlen : -1),
5737 lpOverlapped, lpCompletionRoutine);
5739 fd = get_sock_fd( s, FILE_READ_DATA, &options );
5740 TRACE( "fd=%d, options=%x\n", fd, options );
5742 if (fd == -1) return SOCKET_ERROR;
5744 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
5750 wsa->hSocket = SOCKET2HANDLE(s);
5751 wsa->flags = *lpFlags;
5752 wsa->lpFlags = lpFlags;
5754 wsa->addrlen.ptr = lpFromlen;
5755 wsa->control = lpControlBuffer;
5756 wsa->n_iovecs = dwBufferCount;
5757 wsa->first_iovec = 0;
5758 for (i = 0; i < dwBufferCount; i++)
5760 /* check buffer first to trigger write watches */
5761 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
5766 wsa->iovec[i].iov_base = lpBuffers[i].buf;
5767 wsa->iovec[i].iov_len = lpBuffers[i].len;
5772 n = WS2_recv( fd, wsa );
5775 if (errno == EINTR) continue;
5776 if (errno != EAGAIN)
5778 int loc_errno = errno;
5780 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
5784 else if (lpNumberOfBytesRecvd) *lpNumberOfBytesRecvd = n;
5786 if ((lpOverlapped || lpCompletionRoutine) &&
5787 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
5789 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
5791 wsa->user_overlapped = lpOverlapped;
5792 wsa->completion_func = lpCompletionRoutine;
5793 release_sock_fd( s, fd );
5797 iosb->u.Status = STATUS_PENDING;
5798 iosb->Information = 0;
5800 SERVER_START_REQ( register_async )
5802 req->type = ASYNC_TYPE_READ;
5803 req->async.handle = wine_server_obj_handle( wsa->hSocket );
5804 req->async.callback = wine_server_client_ptr( WS2_async_recv );
5805 req->async.iosb = wine_server_client_ptr( iosb );
5806 req->async.arg = wine_server_client_ptr( wsa );
5807 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
5808 req->async.cvalue = cvalue;
5809 err = wine_server_call( req );
5813 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
5814 WSASetLastError( NtStatusToWSAError( err ));
5815 return SOCKET_ERROR;
5818 iosb->u.Status = STATUS_SUCCESS;
5819 iosb->Information = n;
5820 if (!wsa->completion_func)
5822 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
5823 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
5824 HeapFree( GetProcessHeap(), 0, wsa );
5826 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
5827 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
5828 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5834 if ( _is_blocking(s) )
5837 int timeout = GET_RCVTIMEO(fd);
5840 timeout -= GetTickCount() - timeout_start;
5841 if (timeout < 0) timeout = 0;
5845 pfd.events = POLLIN;
5846 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
5848 if (!timeout || !poll( &pfd, 1, timeout ))
5851 /* a timeout is not fatal */
5852 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5858 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5859 err = WSAEWOULDBLOCK;
5864 TRACE(" -> %i bytes\n", n);
5865 HeapFree( GetProcessHeap(), 0, wsa );
5866 release_sock_fd( s, fd );
5867 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5872 HeapFree( GetProcessHeap(), 0, wsa );
5873 release_sock_fd( s, fd );
5874 WARN(" -> ERROR %d\n", err);
5875 WSASetLastError( err );
5876 return SOCKET_ERROR;
5879 /***********************************************************************
5880 * WSARecvFrom (WS2_32.69)
5882 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5883 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
5884 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
5885 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5888 return WS2_recv_base( s, lpBuffers, dwBufferCount,
5889 lpNumberOfBytesRecvd, lpFlags,
5891 lpOverlapped, lpCompletionRoutine, NULL );
5894 /***********************************************************************
5895 * WSCInstallProvider (WS2_32.88)
5897 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
5898 LPCWSTR lpszProviderDllPath,
5899 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
5900 DWORD dwNumberOfEntries,
5903 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
5904 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
5905 dwNumberOfEntries, lpErrno);
5911 /***********************************************************************
5912 * WSCDeinstallProvider (WS2_32.83)
5914 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
5916 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
5922 /***********************************************************************
5923 * WSAAccept (WS2_32.26)
5925 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
5926 LPCONDITIONPROC lpfnCondition, DWORD_PTR dwCallbackData)
5929 int ret = 0, size = 0;
5930 WSABUF CallerId, CallerData, CalleeId, CalleeData;
5931 /* QOS SQOS, GQOS; */
5934 SOCKADDR src_addr, dst_addr;
5936 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
5937 s, addr, addrlen, lpfnCondition, dwCallbackData);
5940 size = sizeof(src_addr);
5941 cs = WS_accept(s, &src_addr, &size);
5943 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
5945 if (!lpfnCondition) return cs;
5947 CallerId.buf = (char *)&src_addr;
5948 CallerId.len = sizeof(src_addr);
5950 CallerData.buf = NULL;
5953 WS_getsockname(cs, &dst_addr, &size);
5955 CalleeId.buf = (char *)&dst_addr;
5956 CalleeId.len = sizeof(dst_addr);
5959 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
5960 &CalleeId, &CalleeData, &g, dwCallbackData);
5965 if (addr && addrlen)
5966 memcpy(addr, &src_addr, (*addrlen > size) ? size : *addrlen );
5969 SERVER_START_REQ( set_socket_deferred )
5971 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5972 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
5973 if ( !wine_server_call_err ( req ) )
5975 SetLastError( WSATRY_AGAIN );
5976 WS_closesocket( cs );
5980 return SOCKET_ERROR;
5983 SetLastError(WSAECONNREFUSED);
5984 return SOCKET_ERROR;
5986 FIXME("Unknown return type from Condition function\n");
5987 SetLastError(WSAENOTSOCK);
5988 return SOCKET_ERROR;
5992 /***********************************************************************
5993 * WSADuplicateSocketA (WS2_32.32)
5995 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
5999 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
6000 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
6001 /* FIXME: WS_getsockopt(s, WS_SOL_SOCKET, SO_PROTOCOL_INFO, lpProtocolInfo, sizeof(*lpProtocolInfo)); */
6002 /* I don't know what the real Windoze does next, this is a hack */
6003 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
6004 * the target use the global duplicate, or we could copy a reference to us to the structure
6005 * and let the target duplicate it from us, but let's do it as simple as possible */
6006 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
6007 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
6008 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
6009 0, FALSE, DUPLICATE_SAME_ACCESS);
6010 CloseHandle(hProcess);
6011 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
6015 /***********************************************************************
6016 * WSADuplicateSocketW (WS2_32.33)
6018 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
6022 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
6024 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
6025 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
6026 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
6027 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
6028 0, FALSE, DUPLICATE_SAME_ACCESS);
6029 CloseHandle(hProcess);
6030 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
6034 /***********************************************************************
6035 * WSAInstallServiceClassA (WS2_32.48)
6037 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
6039 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
6040 WSASetLastError(WSAEACCES);
6041 return SOCKET_ERROR;
6044 /***********************************************************************
6045 * WSAInstallServiceClassW (WS2_32.49)
6047 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
6049 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
6050 WSASetLastError(WSAEACCES);
6051 return SOCKET_ERROR;
6054 /***********************************************************************
6055 * WSARemoveServiceClass (WS2_32.70)
6057 int WINAPI WSARemoveServiceClass(LPGUID info)
6059 FIXME("Request to remove service %p\n",info);
6060 WSASetLastError(WSATYPE_NOT_FOUND);
6061 return SOCKET_ERROR;
6064 /***********************************************************************
6065 * inet_ntop (WS2_32.@)
6067 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
6069 #ifdef HAVE_INET_NTOP
6070 struct WS_in6_addr *in6;
6071 struct WS_in_addr *in;
6074 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
6077 WSASetLastError( STATUS_INVALID_PARAMETER );
6086 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
6092 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
6096 WSASetLastError( WSAEAFNOSUPPORT );
6100 if (!pdst) WSASetLastError( STATUS_INVALID_PARAMETER );
6103 FIXME( "not supported on this platform\n" );
6104 WSASetLastError( WSAEAFNOSUPPORT );
6109 /***********************************************************************
6110 * WSAStringToAddressA (WS2_32.80)
6112 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
6114 LPWSAPROTOCOL_INFOA lpProtocolInfo,
6115 LPSOCKADDR lpAddress,
6116 LPINT lpAddressLength)
6119 LPSTR workBuffer=NULL,ptrPort;
6121 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
6122 lpProtocolInfo, lpAddress, lpAddressLength );
6124 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
6128 WSASetLastError(WSAEINVAL);
6129 return SOCKET_ERROR;
6133 FIXME("ProtocolInfo not implemented.\n");
6135 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
6136 strlen(AddressString) + 1);
6139 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6140 return SOCKET_ERROR;
6143 strcpy(workBuffer, AddressString);
6145 switch(AddressFamily)
6149 struct in_addr inetaddr;
6151 /* If lpAddressLength is too small, tell caller the size we need */
6152 if (*lpAddressLength < sizeof(SOCKADDR_IN))
6154 *lpAddressLength = sizeof(SOCKADDR_IN);
6158 *lpAddressLength = sizeof(SOCKADDR_IN);
6159 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
6161 ((LPSOCKADDR_IN)lpAddress)->sin_family = AF_INET;
6163 ptrPort = strchr(workBuffer, ':');
6166 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
6171 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
6174 if(inet_aton(workBuffer, &inetaddr) > 0)
6176 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
6187 struct in6_addr inetaddr;
6188 /* If lpAddressLength is too small, tell caller the size we need */
6189 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
6191 *lpAddressLength = sizeof(SOCKADDR_IN6);
6195 #ifdef HAVE_INET_PTON
6196 *lpAddressLength = sizeof(SOCKADDR_IN6);
6197 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
6199 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
6201 /* This one is a bit tricky. An IPv6 address contains colons, so the
6202 * check from IPv4 doesn't work like that. However, IPv6 addresses that
6203 * contain a port are written with braces like [fd12:3456:7890::1]:12345
6204 * so what we will do is to look for ']', check if the next char is a
6205 * colon, and if it is, parse the port as in IPv4. */
6207 ptrPort = strchr(workBuffer, ']');
6208 if(ptrPort && *(++ptrPort) == ':')
6210 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort+1));
6215 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
6218 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
6220 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
6221 sizeof(struct in6_addr));
6225 #endif /* HAVE_INET_PTON */
6231 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
6232 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
6236 HeapFree(GetProcessHeap(), 0, workBuffer);
6239 WSASetLastError(res);
6240 return SOCKET_ERROR;
6243 /***********************************************************************
6244 * WSAStringToAddressW (WS2_32.81)
6246 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
6247 * If this should be the case, it would be required to map these digits
6248 * to Unicode digits (0-9) using FoldString first.
6250 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
6252 LPWSAPROTOCOL_INFOW lpProtocolInfo,
6253 LPSOCKADDR lpAddress,
6254 LPINT lpAddressLength)
6257 LPSTR workBuffer=NULL;
6258 WSAPROTOCOL_INFOA infoA;
6259 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
6261 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
6262 lpAddress, lpAddressLength );
6264 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
6266 /* if ProtocolInfo is available - convert to ANSI variant */
6269 lpProtoInfoA = &infoA;
6270 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
6272 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
6273 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
6275 WSASetLastError( WSAEINVAL);
6276 return SOCKET_ERROR;
6282 /* Translate AddressString to ANSI code page - assumes that only
6283 standard digits 0-9 are used with this API call */
6284 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
6285 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
6289 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
6290 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
6291 lpAddress,lpAddressLength);
6292 HeapFree( GetProcessHeap(), 0, workBuffer );
6296 res = WSA_NOT_ENOUGH_MEMORY;
6301 WSASetLastError(res);
6302 return SOCKET_ERROR;
6305 /***********************************************************************
6306 * WSAAddressToStringA (WS2_32.27)
6308 * See WSAAddressToStringW
6310 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
6311 LPWSAPROTOCOL_INFOA info, LPSTR string,
6315 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
6318 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
6320 if (!sockaddr) return SOCKET_ERROR;
6321 if (!string || !lenstr) return SOCKET_ERROR;
6323 switch(sockaddr->sa_family)
6326 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
6327 sprintf( buffer, "%u.%u.%u.%u:%u",
6328 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
6329 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
6330 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
6331 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
6332 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
6334 p = strchr( buffer, ':' );
6335 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
6340 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
6343 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
6344 if ((sockaddr6->sin6_port))
6345 strcpy(buffer, "[");
6346 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, buffer+strlen(buffer), sizeof(buffer)))
6348 WSASetLastError(WSAEINVAL);
6349 return SOCKET_ERROR;
6351 if ((sockaddr6->sin6_scope_id))
6352 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
6353 if ((sockaddr6->sin6_port))
6354 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
6359 WSASetLastError(WSAEINVAL);
6360 return SOCKET_ERROR;
6363 size = strlen( buffer ) + 1;
6368 WSASetLastError(WSAEFAULT);
6369 return SOCKET_ERROR;
6373 strcpy( string, buffer );
6377 /***********************************************************************
6378 * WSAAddressToStringW (WS2_32.28)
6380 * Convert a sockaddr address into a readable address string.
6383 * sockaddr [I] Pointer to a sockaddr structure.
6384 * len [I] Size of the sockaddr structure.
6385 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
6386 * string [I/O] Pointer to a buffer to receive the address string.
6387 * lenstr [I/O] Size of the receive buffer in WCHARs.
6391 * Failure: SOCKET_ERROR
6394 * The 'info' parameter is ignored.
6396 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
6397 LPWSAPROTOCOL_INFOW info, LPWSTR string,
6402 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
6405 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
6408 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
6410 if (ret) return ret;
6412 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
6417 WSASetLastError(WSAEFAULT);
6418 return SOCKET_ERROR;
6422 lstrcpyW( string, buffer );
6426 /***********************************************************************
6427 * WSAEnumNameSpaceProvidersA (WS2_32.34)
6429 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
6431 FIXME( "(%p %p) Stub!\n", len, buffer );
6435 /***********************************************************************
6436 * WSAEnumNameSpaceProvidersW (WS2_32.35)
6438 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
6440 FIXME( "(%p %p) Stub!\n", len, buffer );
6444 /***********************************************************************
6445 * WSAGetQOSByName (WS2_32.41)
6447 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
6449 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
6453 /***********************************************************************
6454 * WSAGetServiceClassInfoA (WS2_32.42)
6456 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
6457 LPWSASERVICECLASSINFOA info )
6459 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
6461 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6462 return SOCKET_ERROR;
6465 /***********************************************************************
6466 * WSAGetServiceClassInfoW (WS2_32.43)
6468 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
6469 LPWSASERVICECLASSINFOW info )
6471 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
6473 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6474 return SOCKET_ERROR;
6477 /***********************************************************************
6478 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
6480 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
6482 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
6483 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6484 return SOCKET_ERROR;
6487 /***********************************************************************
6488 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
6490 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
6492 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
6493 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6494 return SOCKET_ERROR;
6497 /***********************************************************************
6498 * WSALookupServiceBeginA (WS2_32.59)
6500 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
6501 DWORD dwControlFlags,
6504 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
6506 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6507 return SOCKET_ERROR;
6510 /***********************************************************************
6511 * WSALookupServiceBeginW (WS2_32.60)
6513 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
6514 DWORD dwControlFlags,
6517 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
6519 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6520 return SOCKET_ERROR;
6523 /***********************************************************************
6524 * WSALookupServiceEnd (WS2_32.61)
6526 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
6528 FIXME("(%p) Stub!\n", lookup );
6532 /***********************************************************************
6533 * WSALookupServiceNextA (WS2_32.62)
6535 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
6537 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
6538 WSASetLastError(WSA_E_NO_MORE);
6539 return SOCKET_ERROR;
6542 /***********************************************************************
6543 * WSALookupServiceNextW (WS2_32.63)
6545 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
6547 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
6548 WSASetLastError(WSA_E_NO_MORE);
6549 return SOCKET_ERROR;
6552 /***********************************************************************
6553 * WSANtohl (WS2_32.64)
6555 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
6557 TRACE( "(0x%04lx 0x%08x %p)\n", s, netlong, lphostlong );
6559 if (!lphostlong) return WSAEFAULT;
6561 *lphostlong = ntohl( netlong );
6565 /***********************************************************************
6566 * WSANtohs (WS2_32.65)
6568 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
6570 TRACE( "(0x%04lx 0x%08x %p)\n", s, netshort, lphostshort );
6572 if (!lphostshort) return WSAEFAULT;
6574 *lphostshort = ntohs( netshort );
6578 /***********************************************************************
6579 * WSAProviderConfigChange (WS2_32.66)
6581 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
6582 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
6584 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
6585 return SOCKET_ERROR;
6588 /***********************************************************************
6589 * WSARecvDisconnect (WS2_32.68)
6591 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
6593 TRACE( "(0x%04lx %p)\n", s, disconnectdata );
6595 return WS_shutdown( s, 0 );
6598 /***********************************************************************
6599 * WSASetServiceA (WS2_32.76)
6601 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
6603 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
6607 /***********************************************************************
6608 * WSASetServiceW (WS2_32.77)
6610 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
6612 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
6616 /***********************************************************************
6617 * WSCEnableNSProvider (WS2_32.84)
6619 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
6621 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
6625 /***********************************************************************
6626 * WSCGetProviderPath (WS2_32.86)
6628 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
6630 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
6632 if (!errcode || !provider || !len) return WSAEFAULT;
6634 *errcode = WSAEINVAL;
6635 return SOCKET_ERROR;
6638 /***********************************************************************
6639 * WSCInstallNameSpace (WS2_32.87)
6641 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
6642 DWORD version, LPGUID provider )
6644 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
6645 namespace, version, debugstr_guid(provider) );
6649 /***********************************************************************
6650 * WSCUnInstallNameSpace (WS2_32.89)
6652 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
6654 FIXME("(%p) Stub!\n", lpProviderId);
6658 /***********************************************************************
6659 * WSCWriteProviderOrder (WS2_32.91)
6661 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
6663 FIXME("(%p 0x%08x) Stub!\n", entry, number);
6667 /***********************************************************************
6668 * WSANSPIoctl (WS2_32.91)
6670 INT WINAPI WSANSPIoctl( HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer,
6671 DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer,
6672 LPDWORD lpcbBytesReturned, LPWSACOMPLETION lpCompletion )
6674 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup, dwControlCode,
6675 lpvInBuffer, cbInBuffer, lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpCompletion);
6676 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6677 return SOCKET_ERROR;