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 /* The APC has finished but no completion should be sent for the operation yet, additional processing
1710 * needs to be performed by WS2_async_accept_recv() first. */
1711 return STATUS_MORE_PROCESSING_REQUIRED;
1714 iosb->u.Status = status;
1715 iosb->Information = 0;
1717 if (wsa->user_overlapped->hEvent)
1718 SetEvent(wsa->user_overlapped->hEvent);
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 req->async.cvalue = cvalue;
2050 /* We don't set event since we may also have to read */
2051 status = wine_server_call( req );
2055 if(status != STATUS_PENDING)
2057 HeapFree( GetProcessHeap(), 0, wsa->read );
2058 HeapFree( GetProcessHeap(), 0, wsa );
2061 SetLastError( NtStatusToWSAError(status) );
2065 /***********************************************************************
2066 * GetAcceptExSockaddrs
2068 static void WINAPI WS2_GetAcceptExSockaddrs(PVOID buffer, DWORD data_size, DWORD local_size, DWORD remote_size,
2069 struct WS_sockaddr **local_addr, LPINT local_addr_len,
2070 struct WS_sockaddr **remote_addr, LPINT remote_addr_len)
2072 char *cbuf = buffer;
2073 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer, data_size, local_size, remote_size, local_addr,
2074 local_addr_len, remote_addr, remote_addr_len );
2077 *local_addr_len = *(int *) cbuf;
2078 *local_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2082 *remote_addr_len = *(int *) cbuf;
2083 *remote_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2086 /***********************************************************************
2089 * Perform a receive operation that is capable of returning message
2090 * control headers. It is important to note that the WSAMSG parameter
2091 * must remain valid throughout the operation, even when an overlapped
2092 * receive is performed.
2094 static int WINAPI WS2_WSARecvMsg( SOCKET s, LPWSAMSG msg, LPDWORD lpNumberOfBytesRecvd,
2095 LPWSAOVERLAPPED lpOverlapped,
2096 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2100 SetLastError( WSAEFAULT );
2101 return SOCKET_ERROR;
2104 return WS2_recv_base( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesRecvd,
2105 &msg->dwFlags, msg->name, &msg->namelen,
2106 lpOverlapped, lpCompletionRoutine, &msg->Control );
2109 /***********************************************************************
2112 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
2114 int fd = get_sock_fd( s, 0, NULL );
2115 int res = SOCKET_ERROR;
2117 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2121 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
2123 SetLastError(WSAEAFNOSUPPORT);
2127 union generic_unix_sockaddr uaddr;
2128 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2131 SetLastError(WSAEFAULT);
2136 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
2137 if (name->sa_family == WS_AF_INET6 &&
2138 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
2141 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
2143 release_sock_fd( s, fd );
2144 SetLastError(WSAEAFNOSUPPORT);
2145 return SOCKET_ERROR;
2149 if (name->sa_family == WS_AF_INET)
2151 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2152 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2154 /* Trying to bind to the default host interface, using
2155 * INADDR_ANY instead*/
2156 WARN("Trying to bind to magic IP address, using "
2157 "INADDR_ANY instead.\n");
2158 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
2161 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
2163 int loc_errno = errno;
2164 WARN("\tfailure - errno = %i\n", errno);
2169 SetLastError(WSAENOTSOCK);
2172 SetLastError(WSAEINVAL);
2175 SetLastError(wsaErrno());
2181 res=0; /* success */
2185 release_sock_fd( s, fd );
2190 /***********************************************************************
2191 * closesocket (WS2_32.3)
2193 int WINAPI WS_closesocket(SOCKET s)
2195 TRACE("socket %04lx\n", s);
2196 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
2197 return SOCKET_ERROR;
2200 static int do_connect(int fd, const struct WS_sockaddr* name, int namelen)
2202 union generic_unix_sockaddr uaddr;
2203 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2208 if (name->sa_family == WS_AF_INET)
2210 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2211 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2213 /* Trying to connect to magic replace-loopback address,
2214 * assuming we really want to connect to localhost */
2215 TRACE("Trying to connect to magic IP address, using "
2216 "INADDR_LOOPBACK instead.\n");
2217 in4->sin_addr.s_addr = htonl(WS_INADDR_LOOPBACK);
2221 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
2227 /***********************************************************************
2228 * connect (WS2_32.4)
2230 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
2232 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2234 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2238 int ret = do_connect(fd, name, namelen);
2240 goto connect_success;
2242 if (ret == WSAEINPROGRESS)
2244 /* tell wineserver that a connection is in progress */
2245 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2247 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2248 if (_is_blocking(s))
2252 do_block(fd, POLLIN | POLLOUT, -1);
2253 _sync_sock_state(s); /* let wineserver notice connection */
2254 /* retrieve any error codes from it */
2255 result = _get_sock_error(s, FD_CONNECT_BIT);
2257 SetLastError(NtStatusToWSAError(result));
2260 goto connect_success;
2265 SetLastError(WSAEWOULDBLOCK);
2272 release_sock_fd( s, fd );
2274 return SOCKET_ERROR;
2277 release_sock_fd( s, fd );
2278 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2279 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2280 FD_CONNECT|FD_WINE_LISTENING);
2284 /***********************************************************************
2285 * WSAConnect (WS2_32.30)
2287 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
2288 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
2289 LPQOS lpSQOS, LPQOS lpGQOS )
2291 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
2292 FIXME("unsupported parameters!\n");
2293 return WS_connect( s, name, namelen );
2296 /***********************************************************************
2299 static BOOL WINAPI WS2_ConnectEx(SOCKET s, const struct WS_sockaddr* name, int namelen,
2300 PVOID sendBuf, DWORD sendBufLen, LPDWORD sent, LPOVERLAPPED ov)
2302 int fd, ret, status;
2306 SetLastError( ERROR_INVALID_PARAMETER );
2310 fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2313 SetLastError( WSAENOTSOCK );
2317 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
2318 s, name, debugstr_sockaddr(name), namelen, sendBuf, sendBufLen, ov);
2320 /* FIXME: technically the socket has to be bound */
2321 ret = do_connect(fd, name, namelen);
2326 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2327 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2328 FD_CONNECT|FD_WINE_LISTENING);
2330 wsabuf.len = sendBufLen;
2331 wsabuf.buf = (char*) sendBuf;
2333 /* WSASend takes care of completion if need be */
2334 if (WSASend(s, &wsabuf, sendBuf ? 1 : 0, sent, 0, ov, NULL) != SOCKET_ERROR)
2335 goto connection_success;
2337 else if (ret == WSAEINPROGRESS)
2339 struct ws2_async *wsa;
2340 ULONG_PTR cvalue = (((ULONG_PTR)ov->hEvent & 1) == 0) ? (ULONG_PTR)ov : 0;
2342 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2344 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2346 /* Indirectly call WSASend */
2347 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) )))
2349 SetLastError(WSAEFAULT);
2353 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)ov;
2354 iosb->u.Status = STATUS_PENDING;
2355 iosb->Information = 0;
2357 wsa->hSocket = SOCKET2HANDLE(s);
2359 wsa->addrlen.val = 0;
2361 wsa->lpFlags = &wsa->flags;
2362 wsa->control = NULL;
2363 wsa->n_iovecs = sendBuf ? 1 : 0;
2364 wsa->first_iovec = 0;
2365 wsa->completion_func = NULL;
2366 wsa->iovec[0].iov_base = sendBuf;
2367 wsa->iovec[0].iov_len = sendBufLen;
2369 SERVER_START_REQ( register_async )
2371 req->type = ASYNC_TYPE_WRITE;
2372 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2373 req->async.callback = wine_server_client_ptr( WS2_async_send );
2374 req->async.iosb = wine_server_client_ptr( iosb );
2375 req->async.arg = wine_server_client_ptr( wsa );
2376 req->async.event = wine_server_obj_handle( ov->hEvent );
2377 req->async.cvalue = cvalue;
2378 status = wine_server_call( req );
2382 if (status != STATUS_PENDING) HeapFree(GetProcessHeap(), 0, wsa);
2384 /* If the connect already failed */
2385 if (status == STATUS_PIPE_DISCONNECTED)
2386 status = _get_sock_error(s, FD_CONNECT_BIT);
2387 SetLastError( NtStatusToWSAError(status) );
2395 release_sock_fd( s, fd );
2399 release_sock_fd( s, fd );
2404 /***********************************************************************
2405 * getpeername (WS2_32.5)
2407 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
2412 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, namelen?*namelen:0);
2414 fd = get_sock_fd( s, 0, NULL );
2419 union generic_unix_sockaddr uaddr;
2420 unsigned int uaddrlen = sizeof(uaddr);
2422 if (getpeername(fd, &uaddr.addr, &uaddrlen) == 0)
2424 if (!name || !namelen)
2425 SetLastError(WSAEFAULT);
2426 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
2427 /* The buffer was too small */
2428 SetLastError(WSAEFAULT);
2433 SetLastError(wsaErrno());
2434 release_sock_fd( s, fd );
2439 /***********************************************************************
2440 * getsockname (WS2_32.6)
2442 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
2447 TRACE("socket: %04lx, ptr %p, len %8x\n", s, name, *namelen);
2449 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
2450 if( (name == NULL) || (namelen == NULL) )
2452 SetLastError( WSAEFAULT );
2453 return SOCKET_ERROR;
2456 fd = get_sock_fd( s, 0, NULL );
2461 union generic_unix_sockaddr uaddr;
2462 unsigned int uaddrlen = sizeof(uaddr);
2464 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
2466 SetLastError(wsaErrno());
2468 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
2470 SetLastError(WSAEINVAL);
2472 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
2474 /* The buffer was too small */
2475 SetLastError(WSAEFAULT);
2481 release_sock_fd( s, fd );
2486 /***********************************************************************
2487 * getsockopt (WS2_32.7)
2489 INT WINAPI WS_getsockopt(SOCKET s, INT level,
2490 INT optname, char *optval, INT *optlen)
2495 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
2496 s, level, optname, optval, *optlen);
2504 /* Handle common cases. The special cases are below, sorted
2506 case WS_SO_ACCEPTCONN:
2507 case WS_SO_BROADCAST:
2510 case WS_SO_KEEPALIVE:
2511 case WS_SO_OOBINLINE:
2513 case WS_SO_REUSEADDR:
2516 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2517 return SOCKET_ERROR;
2518 convert_sockopt(&level, &optname);
2519 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2521 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2524 release_sock_fd( s, fd );
2527 case WS_SO_DONTLINGER:
2529 struct linger lingval;
2530 unsigned int len = sizeof(struct linger);
2532 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
2534 SetLastError(WSAEFAULT);
2535 return SOCKET_ERROR;
2537 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2538 return SOCKET_ERROR;
2540 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
2542 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2547 *(BOOL *)optval = (lingval.l_onoff) ? FALSE : TRUE;
2548 *optlen = sizeof(BOOL);
2551 release_sock_fd( s, fd );
2555 case WS_SO_CONNECT_TIME:
2557 static int pretendtime = 0;
2558 struct WS_sockaddr addr;
2559 int len = sizeof(addr);
2561 if (!optlen || *optlen < sizeof(DWORD) || !optval)
2563 SetLastError(WSAEFAULT);
2564 return SOCKET_ERROR;
2566 if (WS_getpeername(s, &addr, &len) == SOCKET_ERROR)
2567 *(DWORD *)optval = ~0u;
2570 if (!pretendtime) FIXME("WS_SO_CONNECT_TIME - faking results\n");
2571 *(DWORD *)optval = pretendtime++;
2573 *optlen = sizeof(DWORD);
2576 /* As mentioned in setsockopt, Windows ignores this, so we
2577 * always return true here */
2578 case WS_SO_DONTROUTE:
2579 if (!optlen || *optlen < sizeof(BOOL) || !optval)
2581 SetLastError(WSAEFAULT);
2582 return SOCKET_ERROR;
2584 *(BOOL *)optval = TRUE;
2585 *optlen = sizeof(BOOL);
2590 struct linger lingval;
2592 unsigned int len = sizeof(struct linger), slen = sizeof(int);
2594 /* struct linger and LINGER have different sizes */
2595 if (!optlen || *optlen < sizeof(LINGER) || !optval)
2597 SetLastError(WSAEFAULT);
2598 return SOCKET_ERROR;
2600 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2601 return SOCKET_ERROR;
2603 if ((getsockopt(fd, SOL_SOCKET, SO_TYPE, &so_type, &slen) == 0 && so_type == SOCK_DGRAM))
2605 SetLastError(WSAENOPROTOOPT);
2608 else if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0)
2610 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2615 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
2616 ((LINGER *)optval)->l_linger = lingval.l_linger;
2617 *optlen = sizeof(struct linger);
2620 release_sock_fd( s, fd );
2624 case WS_SO_MAX_MSG_SIZE:
2625 if (!optlen || *optlen < sizeof(int) || !optval)
2627 SetLastError(WSAEFAULT);
2628 return SOCKET_ERROR;
2630 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
2631 *(int *)optval = 65507;
2632 *optlen = sizeof(int);
2635 /* SO_OPENTYPE does not require a valid socket handle. */
2636 case WS_SO_OPENTYPE:
2637 if (!optlen || *optlen < sizeof(int) || !optval)
2639 SetLastError(WSAEFAULT);
2640 return SOCKET_ERROR;
2642 *(int *)optval = get_per_thread_data()->opentype;
2643 *optlen = sizeof(int);
2644 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
2648 case WS_SO_RCVTIMEO:
2651 case WS_SO_SNDTIMEO:
2653 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
2656 unsigned int len = sizeof(struct timeval);
2658 if (!optlen || *optlen < sizeof(int)|| !optval)
2660 SetLastError(WSAEFAULT);
2661 return SOCKET_ERROR;
2663 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2664 return SOCKET_ERROR;
2666 convert_sockopt(&level, &optname);
2667 if (getsockopt(fd, level, optname, &tv, &len) != 0 )
2669 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2674 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
2675 *optlen = sizeof(int);
2678 release_sock_fd( s, fd );
2683 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
2684 SetLastError(WSAENOPROTOOPT);
2685 return SOCKET_ERROR;
2686 } /* end switch(optname) */
2687 }/* end case WS_SOL_SOCKET */
2691 struct WS_sockaddr_ipx addr;
2692 IPX_ADDRESS_DATA *data;
2697 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
2699 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (unsigned int*)optlen) == -1)
2706 socklen_t len=sizeof(struct ipx);
2707 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
2710 *optval = (int)val.ipx_pt;
2713 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
2714 release_sock_fd( s, fd );
2719 * On a Win2000 system with one network card there are usually
2720 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
2721 * Using this call you can then retrieve info about this all.
2722 * In case of Linux it is a bit different. Usually you have
2723 * only "one" device active and further it is not possible to
2724 * query things like the linkspeed.
2726 FIXME("IPX_ADDRESS\n");
2727 namelen = sizeof(struct WS_sockaddr_ipx);
2728 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
2729 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
2731 data = (IPX_ADDRESS_DATA*)optval;
2732 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
2733 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
2734 data->adapternum = 0;
2735 data->wan = FALSE; /* We are not on a wan for now .. */
2736 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
2737 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
2738 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
2739 * note 1MB = 1000kB in this case */
2742 case IPX_MAX_ADAPTER_NUM:
2743 FIXME("IPX_MAX_ADAPTER_NUM\n");
2744 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
2748 FIXME("IPX optname:%x\n", optname);
2749 return SOCKET_ERROR;
2750 }/* end switch(optname) */
2751 } /* end case NSPROTO_IPX */
2758 case WS_IRLMP_ENUMDEVICES:
2760 static const int MAX_IRDA_DEVICES = 10;
2761 char buf[sizeof(struct irda_device_list) +
2762 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
2764 socklen_t len = sizeof(buf);
2766 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2767 return SOCKET_ERROR;
2768 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
2771 SetLastError(wsaErrno());
2772 return SOCKET_ERROR;
2776 struct irda_device_list *src = (struct irda_device_list *)buf;
2777 DEVICELIST *dst = (DEVICELIST *)optval;
2778 INT needed = sizeof(DEVICELIST), i;
2781 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
2782 if (*optlen < needed)
2784 SetLastError(WSAEFAULT);
2785 return SOCKET_ERROR;
2788 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
2789 dst->numDevice = src->len;
2790 for (i = 0; i < src->len; i++)
2792 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
2793 src->dev[i].saddr, src->dev[i].daddr,
2794 src->dev[i].info, src->dev[i].hints[0],
2795 src->dev[i].hints[1]);
2796 memcpy( dst->Device[i].irdaDeviceID,
2798 sizeof(dst->Device[i].irdaDeviceID) ) ;
2799 memcpy( dst->Device[i].irdaDeviceName,
2801 sizeof(dst->Device[i].irdaDeviceName) ) ;
2802 memcpy( &dst->Device[i].irdaDeviceHints1,
2803 &src->dev[i].hints[0],
2804 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
2805 memcpy( &dst->Device[i].irdaDeviceHints2,
2806 &src->dev[i].hints[1],
2807 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
2808 dst->Device[i].irdaCharSet = src->dev[i].charset;
2814 FIXME("IrDA optname:0x%x\n", optname);
2815 return SOCKET_ERROR;
2817 break; /* case WS_SOL_IRLMP */
2820 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
2821 case WS_IPPROTO_TCP:
2824 case WS_TCP_NODELAY:
2825 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2826 return SOCKET_ERROR;
2827 convert_sockopt(&level, &optname);
2828 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2830 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2833 release_sock_fd( s, fd );
2836 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
2837 return SOCKET_ERROR;
2842 case WS_IP_ADD_MEMBERSHIP:
2843 case WS_IP_DROP_MEMBERSHIP:
2847 case WS_IP_MULTICAST_IF:
2848 case WS_IP_MULTICAST_LOOP:
2849 case WS_IP_MULTICAST_TTL:
2856 #ifdef IP_UNICAST_IF
2857 case WS_IP_UNICAST_IF:
2859 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2860 return SOCKET_ERROR;
2861 convert_sockopt(&level, &optname);
2862 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2864 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2867 release_sock_fd( s, fd );
2869 case WS_IP_DONTFRAGMENT:
2870 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
2871 *(BOOL*)optval = FALSE;
2874 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
2875 return SOCKET_ERROR;
2877 case WS_IPPROTO_IPV6:
2880 #ifdef IPV6_ADD_MEMBERSHIP
2881 case WS_IPV6_ADD_MEMBERSHIP:
2883 #ifdef IPV6_DROP_MEMBERSHIP
2884 case WS_IPV6_DROP_MEMBERSHIP:
2886 case WS_IPV6_MULTICAST_IF:
2887 case WS_IPV6_MULTICAST_HOPS:
2888 case WS_IPV6_MULTICAST_LOOP:
2889 case WS_IPV6_UNICAST_HOPS:
2890 case WS_IPV6_V6ONLY:
2891 #ifdef IPV6_UNICAST_IF
2892 case WS_IPV6_UNICAST_IF:
2894 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2895 return SOCKET_ERROR;
2896 convert_sockopt(&level, &optname);
2897 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2899 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2902 release_sock_fd( s, fd );
2904 case WS_IPV6_DONTFRAG:
2905 FIXME("WS_IPV6_DONTFRAG is always false!\n");
2906 *(BOOL*)optval = FALSE;
2909 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
2910 return SOCKET_ERROR;
2913 WARN("Unknown level: 0x%08x\n", level);
2914 SetLastError(WSAEINVAL);
2915 return SOCKET_ERROR;
2916 } /* end switch(level) */
2919 /***********************************************************************
2922 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
2924 return htonl(hostlong);
2928 /***********************************************************************
2931 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
2933 return htons(hostshort);
2936 /***********************************************************************
2937 * WSAHtonl (WS2_32.46)
2938 * From MSDN description of error codes, this function should also
2939 * check if WinSock has been initialized and the socket is a valid
2940 * socket. But why? This function only translates a host byte order
2941 * u_long into a network byte order u_long...
2943 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
2947 *lpnetlong = htonl(hostlong);
2950 WSASetLastError(WSAEFAULT);
2951 return SOCKET_ERROR;
2954 /***********************************************************************
2955 * WSAHtons (WS2_32.47)
2956 * From MSDN description of error codes, this function should also
2957 * check if WinSock has been initialized and the socket is a valid
2958 * socket. But why? This function only translates a host byte order
2959 * u_short into a network byte order u_short...
2961 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
2966 *lpnetshort = htons(hostshort);
2969 WSASetLastError(WSAEFAULT);
2970 return SOCKET_ERROR;
2974 /***********************************************************************
2975 * inet_addr (WS2_32.11)
2977 WS_u_long WINAPI WS_inet_addr(const char *cp)
2979 if (!cp) return INADDR_NONE;
2980 return inet_addr(cp);
2984 /***********************************************************************
2987 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
2989 return ntohl(netlong);
2993 /***********************************************************************
2996 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
2998 return ntohs(netshort);
3002 /***********************************************************************
3003 * inet_ntoa (WS2_32.12)
3005 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
3007 /* use "buffer for dummies" here because some applications have a
3008 * propensity to decode addresses in ws_hostent structure without
3009 * saving them first...
3011 static char dbuffer[16]; /* Yes, 16: 4*3 digits + 3 '.' + 1 '\0' */
3013 char* s = inet_ntoa(*((struct in_addr*)&in));
3019 SetLastError(wsaErrno());
3023 static const char *debugstr_wsaioctl(DWORD ioctl)
3025 const char *buf_type, *family;
3027 switch(ioctl & 0x18000000)
3032 case WS_IOC_PROTOCOL:
3033 family = "IOC_PROTOCOL";
3036 family = "IOC_VENDOR";
3038 default: /* WS_IOC_UNIX */
3040 BYTE size = (ioctl >> 16) & WS_IOCPARM_MASK;
3041 char x = (ioctl & 0xff00) >> 8;
3042 BYTE y = ioctl & 0xff;
3045 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3049 sprintf(args, "%d, %d", x, y);
3053 sprintf(args, "'%c', %d, %d", x, y, size);
3057 sprintf(args, "'%c', %d, %d", x, y, size);
3061 sprintf(args, "'%c', %d, %d", x, y, size);
3064 return wine_dbg_sprintf("%s(%s)", buf_type, args);
3068 /* We are different from WS_IOC_UNIX. */
3069 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3072 buf_type = "_WSAIO";
3075 buf_type = "_WSAIORW";
3078 buf_type = "_WSAIOW";
3081 buf_type = "_WSAIOR";
3088 return wine_dbg_sprintf("%s(%s, %d)", buf_type, family,
3089 (USHORT)(ioctl & 0xffff));
3092 /**********************************************************************
3093 * WSAIoctl (WS2_32.50)
3096 INT WINAPI WSAIoctl(SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size, LPVOID out_buff,
3097 DWORD out_size, LPDWORD ret_size, LPWSAOVERLAPPED overlapped,
3098 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
3101 DWORD status = 0, total = 0;
3103 TRACE("%ld, 0x%08x, %p, %d, %p, %d, %p, %p, %p\n",
3104 s, code, in_buff, in_size, out_buff, out_size, ret_size, overlapped, completion);
3109 if (in_size != sizeof(WS_u_long) || IS_INTRESOURCE(in_buff))
3111 WSASetLastError(WSAEFAULT);
3112 return SOCKET_ERROR;
3114 if (_get_sock_mask(s))
3116 /* AsyncSelect()'ed sockets are always nonblocking */
3117 if (!*(WS_u_long *)in_buff) status = WSAEINVAL;
3120 if (*(WS_u_long *)in_buff)
3121 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
3123 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
3128 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
3130 WSASetLastError(WSAEFAULT);
3131 return SOCKET_ERROR;
3133 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3134 if (ioctl(fd, FIONREAD, out_buff ) == -1)
3135 status = (errno == EBADF) ? WSAENOTSOCK : wsaErrno();
3136 release_sock_fd( s, fd );
3142 unsigned int oob = 0, oobsize = sizeof(int), atmark = 0;
3143 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
3145 WSASetLastError(WSAEFAULT);
3146 return SOCKET_ERROR;
3148 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3149 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
3150 if ((getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &oob, &oobsize ) == -1)
3151 || (!oob && ioctl(fd, SIOCATMARK, &atmark ) == -1))
3152 status = (errno == EBADF) ? WSAENOTSOCK : wsaErrno();
3155 /* The SIOCATMARK value read from ioctl() is reversed
3156 * because BSD returns TRUE if it's in the OOB mark
3157 * while Windows returns TRUE if there are NO OOB bytes.
3159 (*(WS_u_long *) out_buff) = oob | !atmark;
3162 release_sock_fd( s, fd );
3167 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
3168 SetLastError(WSAEINVAL);
3169 return SOCKET_ERROR;
3171 case WS_SIO_GET_INTERFACE_LIST:
3173 INTERFACE_INFO* intArray = out_buff;
3174 DWORD size, numInt = 0, apiReturn;
3176 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
3178 if (!out_buff || !ret_size)
3180 WSASetLastError(WSAEFAULT);
3181 return SOCKET_ERROR;
3184 fd = get_sock_fd( s, 0, NULL );
3185 if (fd == -1) return SOCKET_ERROR;
3187 apiReturn = GetAdaptersInfo(NULL, &size);
3188 if (apiReturn == ERROR_BUFFER_OVERFLOW)
3190 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
3194 if (GetAdaptersInfo(table, &size) == NO_ERROR)
3196 PIP_ADAPTER_INFO ptr;
3198 if (size*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > out_size)
3200 WARN("Buffer too small = %u, out_size = %u\n", size, out_size);
3201 HeapFree(GetProcessHeap(),0,table);
3202 release_sock_fd( s, fd );
3206 for (ptr = table, numInt = 0; ptr;
3207 ptr = ptr->Next, intArray++, numInt++)
3209 unsigned int addr, mask, bcast;
3210 struct ifreq ifInfo;
3212 /* Socket Status Flags */
3213 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
3214 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
3216 ERR("Error obtaining status flags for socket!\n");
3217 HeapFree(GetProcessHeap(),0,table);
3218 release_sock_fd( s, fd );
3224 /* set flags; the values of IFF_* are not the same
3225 under Linux and Windows, therefore must generate
3227 intArray->iiFlags = 0;
3228 if (ifInfo.ifr_flags & IFF_BROADCAST)
3229 intArray->iiFlags |= WS_IFF_BROADCAST;
3230 #ifdef IFF_POINTOPOINT
3231 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
3232 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
3234 if (ifInfo.ifr_flags & IFF_LOOPBACK)
3235 intArray->iiFlags |= WS_IFF_LOOPBACK;
3236 if (ifInfo.ifr_flags & IFF_UP)
3237 intArray->iiFlags |= WS_IFF_UP;
3238 if (ifInfo.ifr_flags & IFF_MULTICAST)
3239 intArray->iiFlags |= WS_IFF_MULTICAST;
3242 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
3243 mask = inet_addr(ptr->IpAddressList.IpMask.String);
3244 bcast = addr | ~mask;
3245 intArray->iiAddress.AddressIn.sin_family = AF_INET;
3246 intArray->iiAddress.AddressIn.sin_port = 0;
3247 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
3249 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
3250 intArray->iiNetmask.AddressIn.sin_port = 0;
3251 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
3253 intArray->iiBroadcastAddress.AddressIn.sin_family =
3255 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
3256 intArray->iiBroadcastAddress.AddressIn.sin_addr.
3262 ERR("Unable to get interface table!\n");
3265 HeapFree(GetProcessHeap(),0,table);
3267 else status = WSAEINVAL;
3269 else if (apiReturn != ERROR_NO_DATA)
3271 ERR("Unable to get interface table!\n");
3274 /* Calculate the size of the array being returned */
3275 total = sizeof(INTERFACE_INFO) * numInt;
3276 release_sock_fd( s, fd );
3280 case WS_SIO_ADDRESS_LIST_CHANGE:
3281 FIXME("-> SIO_ADDRESS_LIST_CHANGE request: stub\n");
3282 /* FIXME: error and return code depend on whether socket was created
3283 * with WSA_FLAG_OVERLAPPED, but there is no easy way to get this */
3286 case WS_SIO_ADDRESS_LIST_QUERY:
3290 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
3294 WSASetLastError(WSAEFAULT);
3295 return SOCKET_ERROR;
3298 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
3300 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
3303 if (!table || GetAdaptersInfo(table, &size))
3305 HeapFree(GetProcessHeap(), 0, table);
3310 for (p = table, num = 0; p; p = p->Next)
3311 if (p->IpAddressList.IpAddress.String[0]) num++;
3313 total = sizeof(SOCKET_ADDRESS_LIST) + sizeof(SOCKET_ADDRESS) * (num - 1);
3314 total += sizeof(SOCKADDR) * num;
3316 if (total > out_size)
3318 HeapFree(GetProcessHeap(), 0, table);
3327 SOCKET_ADDRESS_LIST *sa_list = out_buff;
3328 SOCKADDR_IN *sockaddr;
3330 sa = sa_list->Address;
3331 sockaddr = (SOCKADDR_IN *)((char *)sa + num * sizeof(SOCKET_ADDRESS));
3332 sa_list->iAddressCount = num;
3334 for (p = table, i = 0; p; p = p->Next)
3336 if (!p->IpAddressList.IpAddress.String[0]) continue;
3338 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
3339 sa[i].iSockaddrLength = sizeof(SOCKADDR);
3341 sockaddr[i].sin_family = AF_INET;
3342 sockaddr[i].sin_port = 0;
3343 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
3348 HeapFree(GetProcessHeap(), 0, table);
3352 WARN("unable to get IP address list\n");
3359 FIXME("SIO_FLUSH: stub.\n");
3362 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
3364 static const GUID connectex_guid = WSAID_CONNECTEX;
3365 static const GUID disconnectex_guid = WSAID_DISCONNECTEX;
3366 static const GUID acceptex_guid = WSAID_ACCEPTEX;
3367 static const GUID getaccepexsockaddrs_guid = WSAID_GETACCEPTEXSOCKADDRS;
3368 static const GUID transmitfile_guid = WSAID_TRANSMITFILE;
3369 static const GUID transmitpackets_guid = WSAID_TRANSMITPACKETS;
3370 static const GUID wsarecvmsg_guid = WSAID_WSARECVMSG;
3371 static const GUID wsasendmsg_guid = WSAID_WSASENDMSG;
3373 if ( IsEqualGUID(&connectex_guid, in_buff) )
3375 *(LPFN_CONNECTEX *)out_buff = WS2_ConnectEx;
3378 else if ( IsEqualGUID(&disconnectex_guid, in_buff) )
3380 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented DisconnectEx\n");
3382 else if ( IsEqualGUID(&acceptex_guid, in_buff) )
3384 *(LPFN_ACCEPTEX *)out_buff = WS2_AcceptEx;
3387 else if ( IsEqualGUID(&getaccepexsockaddrs_guid, in_buff) )
3389 *(LPFN_GETACCEPTEXSOCKADDRS *)out_buff = WS2_GetAcceptExSockaddrs;
3392 else if ( IsEqualGUID(&transmitfile_guid, in_buff) )
3394 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitFile\n");
3396 else if ( IsEqualGUID(&transmitpackets_guid, in_buff) )
3398 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitPackets\n");
3400 else if ( IsEqualGUID(&wsarecvmsg_guid, in_buff) )
3402 *(LPFN_WSARECVMSG *)out_buff = WS2_WSARecvMsg;
3405 else if ( IsEqualGUID(&wsasendmsg_guid, in_buff) )
3407 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented WSASendMsg\n");
3410 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff));
3412 status = WSAEOPNOTSUPP;
3415 case WS_SIO_KEEPALIVE_VALS:
3417 struct tcp_keepalive *k;
3418 int keepalive, keepidle, keepintvl;
3420 if (!in_buff || in_size < sizeof(struct tcp_keepalive))
3422 WSASetLastError(WSAEFAULT);
3423 return SOCKET_ERROR;
3427 keepalive = k->onoff ? 1 : 0;
3428 keepidle = max( 1, (k->keepalivetime + 500) / 1000 );
3429 keepintvl = max( 1, (k->keepaliveinterval + 500) / 1000 );
3431 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
3433 fd = get_sock_fd(s, 0, NULL);
3434 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
3436 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
3437 /* these values need to be set only if SO_KEEPALIVE is enabled */
3440 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
3442 else if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
3447 FIXME("ignoring keepalive interval and timeout\n");
3449 release_sock_fd(s, fd);
3452 case WS_SIO_ROUTING_INTERFACE_QUERY:
3454 struct WS_sockaddr *daddr = (struct WS_sockaddr *)in_buff;
3455 struct WS_sockaddr_in *daddr_in = (struct WS_sockaddr_in *)daddr;
3456 struct WS_sockaddr_in *saddr_in = out_buff;
3457 MIB_IPFORWARDROW row;
3458 PMIB_IPADDRTABLE ipAddrTable = NULL;
3459 DWORD size, i, found_index;
3461 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
3463 if (!in_buff || in_size < sizeof(struct WS_sockaddr) ||
3464 !out_buff || out_size < sizeof(struct WS_sockaddr_in) || !ret_size)
3466 WSASetLastError(WSAEFAULT);
3467 return SOCKET_ERROR;
3469 if (daddr->sa_family != AF_INET)
3471 FIXME("unsupported address family %d\n", daddr->sa_family);
3472 status = WSAEAFNOSUPPORT;
3475 if (GetBestRoute(daddr_in->sin_addr.S_un.S_addr, 0, &row) != NOERROR ||
3476 GetIpAddrTable(NULL, &size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
3481 ipAddrTable = HeapAlloc(GetProcessHeap(), 0, size);
3482 if (GetIpAddrTable(ipAddrTable, &size, FALSE))
3484 HeapFree(GetProcessHeap(), 0, ipAddrTable);
3488 for (i = 0, found_index = ipAddrTable->dwNumEntries;
3489 i < ipAddrTable->dwNumEntries; i++)
3491 if (ipAddrTable->table[i].dwIndex == row.dwForwardIfIndex)
3494 if (found_index == ipAddrTable->dwNumEntries)
3496 ERR("no matching IP address for interface %d\n",
3497 row.dwForwardIfIndex);
3498 HeapFree(GetProcessHeap(), 0, ipAddrTable);
3502 saddr_in->sin_family = AF_INET;
3503 saddr_in->sin_addr.S_un.S_addr = ipAddrTable->table[found_index].dwAddr;
3504 saddr_in->sin_port = 0;
3505 total = sizeof(struct WS_sockaddr_in);
3506 HeapFree(GetProcessHeap(), 0, ipAddrTable);
3509 case WS_SIO_SET_COMPATIBILITY_MODE:
3510 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
3511 status = WSAEOPNOTSUPP;
3513 case WS_SIO_UDP_CONNRESET:
3514 FIXME("WS_SIO_UDP_CONNRESET stub\n");
3516 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
3517 WSASetLastError(WSAEOPNOTSUPP);
3518 return SOCKET_ERROR;
3520 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code));
3521 status = WSAEOPNOTSUPP;
3527 FIXME( "completion routine %p not supported\n", completion );
3529 else if (overlapped)
3531 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
3532 overlapped->Internal = status;
3533 overlapped->InternalHigh = total;
3534 if (overlapped->hEvent) NtSetEvent( overlapped->hEvent, NULL );
3535 if (cvalue) WS_AddCompletion( HANDLE2SOCKET(s), cvalue, status, total );
3540 if (ret_size) *ret_size = total;
3543 SetLastError( status );
3544 return SOCKET_ERROR;
3548 /***********************************************************************
3549 * ioctlsocket (WS2_32.10)
3551 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
3554 return WSAIoctl( s, cmd, argp, sizeof(WS_u_long), argp, sizeof(WS_u_long), &ret_size, NULL, NULL );
3557 /***********************************************************************
3558 * listen (WS2_32.13)
3560 int WINAPI WS_listen(SOCKET s, int backlog)
3562 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
3564 TRACE("socket %04lx, backlog %d\n", s, backlog);
3567 if (listen(fd, backlog) == 0)
3569 release_sock_fd( s, fd );
3570 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
3572 FD_CONNECT|FD_WINE_CONNECTED);
3575 SetLastError(wsaErrno());
3576 release_sock_fd( s, fd );
3578 return SOCKET_ERROR;
3581 /***********************************************************************
3584 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
3586 DWORD n, dwFlags = flags;
3592 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
3593 return SOCKET_ERROR;
3598 /***********************************************************************
3599 * recvfrom (WS2_32.17)
3601 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
3602 struct WS_sockaddr *from, int *fromlen)
3604 DWORD n, dwFlags = flags;
3610 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL, NULL) == SOCKET_ERROR )
3611 return SOCKET_ERROR;
3616 /* allocate a poll array for the corresponding fd sets */
3617 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
3618 const WS_fd_set *exceptfds, int *count_ptr )
3620 unsigned int i, j = 0, count = 0;
3623 if (readfds) count += readfds->fd_count;
3624 if (writefds) count += writefds->fd_count;
3625 if (exceptfds) count += exceptfds->fd_count;
3629 SetLastError(WSAEINVAL);
3632 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0]))))
3634 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
3638 for (i = 0; i < readfds->fd_count; i++, j++)
3640 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
3641 if (fds[j].fd == -1) goto failed;
3642 fds[j].events = POLLIN;
3646 for (i = 0; i < writefds->fd_count; i++, j++)
3648 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
3649 if (fds[j].fd == -1) goto failed;
3650 fds[j].events = POLLOUT;
3654 for (i = 0; i < exceptfds->fd_count; i++, j++)
3656 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
3657 if (fds[j].fd == -1) goto failed;
3658 fds[j].events = POLLHUP;
3667 for (i = 0; i < readfds->fd_count && j < count; i++, j++)
3668 release_sock_fd( readfds->fd_array[i], fds[j].fd );
3670 for (i = 0; i < writefds->fd_count && j < count; i++, j++)
3671 release_sock_fd( writefds->fd_array[i], fds[j].fd );
3673 for (i = 0; i < exceptfds->fd_count && j < count; i++, j++)
3674 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
3675 HeapFree( GetProcessHeap(), 0, fds );
3679 /* release the file descriptor obtained in fd_sets_to_poll */
3680 /* must be called with the original fd_set arrays, before calling get_poll_results */
3681 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
3682 const WS_fd_set *exceptfds, struct pollfd *fds )
3684 unsigned int i, j = 0;
3688 for (i = 0; i < readfds->fd_count; i++, j++)
3689 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
3693 for (i = 0; i < writefds->fd_count; i++, j++)
3694 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
3698 for (i = 0; i < exceptfds->fd_count; i++, j++)
3699 if (fds[j].fd != -1)
3701 /* make sure we have a real error before releasing the fd */
3702 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
3703 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
3708 /* map the poll results back into the Windows fd sets */
3709 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
3710 const struct pollfd *fds )
3712 unsigned int i, j = 0, k, total = 0;
3716 for (i = k = 0; i < readfds->fd_count; i++, j++)
3717 if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
3718 readfds->fd_count = k;
3723 for (i = k = 0; i < writefds->fd_count; i++, j++)
3724 if ((fds[j].revents & POLLOUT) && !(fds[j].revents & POLLHUP))
3725 writefds->fd_array[k++] = writefds->fd_array[i];
3726 writefds->fd_count = k;
3731 for (i = k = 0; i < exceptfds->fd_count; i++, j++)
3732 if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
3733 exceptfds->fd_count = k;
3740 /***********************************************************************
3741 * select (WS2_32.18)
3743 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
3744 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
3745 const struct WS_timeval* ws_timeout)
3747 struct pollfd *pollfds;
3748 struct timeval tv1, tv2;
3750 int count, ret, timeout = -1;
3752 TRACE("read %p, write %p, excp %p timeout %p\n",
3753 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
3755 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )))
3756 return SOCKET_ERROR;
3760 torig = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
3762 gettimeofday( &tv1, 0 );
3765 while ((ret = poll( pollfds, count, timeout )) < 0)
3769 if (!ws_timeout) continue;
3770 gettimeofday( &tv2, 0 );
3772 tv2.tv_sec -= tv1.tv_sec;
3773 tv2.tv_usec -= tv1.tv_usec;
3774 if (tv2.tv_usec < 0)
3776 tv2.tv_usec += 1000000;
3780 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
3781 if (timeout <= 0) break;
3784 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
3786 if (ret == -1) SetLastError(wsaErrno());
3787 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
3788 HeapFree( GetProcessHeap(), 0, pollfds );
3792 /* helper to send completion messages for client-only i/o operation case */
3793 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
3796 SERVER_START_REQ( add_fd_completion )
3798 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
3799 req->cvalue = CompletionValue;
3800 req->status = CompletionStatus;
3801 req->information = Information;
3802 wine_server_call( req );
3808 /***********************************************************************
3811 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
3817 wsabuf.buf = (char*) buf;
3819 if ( WS2_sendto( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
3820 return SOCKET_ERROR;
3825 /***********************************************************************
3826 * WSASend (WS2_32.72)
3828 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3829 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
3830 LPWSAOVERLAPPED lpOverlapped,
3831 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3833 return WS2_sendto( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
3834 NULL, 0, lpOverlapped, lpCompletionRoutine );
3837 /***********************************************************************
3838 * WSASendDisconnect (WS2_32.73)
3840 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
3842 return WS_shutdown( s, SD_SEND );
3846 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3847 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
3848 const struct WS_sockaddr *to, int tolen,
3849 LPWSAOVERLAPPED lpOverlapped,
3850 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3852 unsigned int i, options;
3854 struct ws2_async *wsa = NULL;
3855 int totalLength = 0;
3856 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
3859 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
3860 s, lpBuffers, dwBufferCount, dwFlags,
3861 to, tolen, lpOverlapped, lpCompletionRoutine);
3863 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
3864 TRACE( "fd=%d, options=%x\n", fd, options );
3866 if ( fd == -1 ) return SOCKET_ERROR;
3868 if (!lpOverlapped && !lpNumberOfBytesSent)
3873 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
3879 wsa->hSocket = SOCKET2HANDLE(s);
3880 wsa->addr = (struct WS_sockaddr *)to;
3881 wsa->addrlen.val = tolen;
3882 wsa->flags = dwFlags;
3883 wsa->lpFlags = &wsa->flags;
3884 wsa->control = NULL;
3885 wsa->n_iovecs = dwBufferCount;
3886 wsa->first_iovec = 0;
3887 for ( i = 0; i < dwBufferCount; i++ )
3889 wsa->iovec[i].iov_base = lpBuffers[i].buf;
3890 wsa->iovec[i].iov_len = lpBuffers[i].len;
3891 totalLength += lpBuffers[i].len;
3896 n = WS2_send( fd, wsa );
3897 if (n != -1 || errno != EINTR) break;
3899 if (n == -1 && errno != EAGAIN)
3905 if ((lpOverlapped || lpCompletionRoutine) &&
3906 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
3908 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
3910 wsa->user_overlapped = lpOverlapped;
3911 wsa->completion_func = lpCompletionRoutine;
3912 release_sock_fd( s, fd );
3914 if (n == -1 || n < totalLength)
3916 iosb->u.Status = STATUS_PENDING;
3917 iosb->Information = n == -1 ? 0 : n;
3919 SERVER_START_REQ( register_async )
3921 req->type = ASYNC_TYPE_WRITE;
3922 req->async.handle = wine_server_obj_handle( wsa->hSocket );
3923 req->async.callback = wine_server_client_ptr( WS2_async_send );
3924 req->async.iosb = wine_server_client_ptr( iosb );
3925 req->async.arg = wine_server_client_ptr( wsa );
3926 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
3927 req->async.cvalue = cvalue;
3928 err = wine_server_call( req );
3932 /* Enable the event only after starting the async. The server will deliver it as soon as
3933 the async is done. */
3934 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
3936 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
3937 WSASetLastError( NtStatusToWSAError( err ));
3938 return SOCKET_ERROR;
3941 iosb->u.Status = STATUS_SUCCESS;
3942 iosb->Information = n;
3943 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = n;
3944 if (!wsa->completion_func)
3946 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
3947 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
3948 HeapFree( GetProcessHeap(), 0, wsa );
3950 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
3951 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
3956 if ( _is_blocking(s) )
3958 /* On a blocking non-overlapped stream socket,
3959 * sending blocks until the entire buffer is sent. */
3960 DWORD timeout_start = GetTickCount();
3962 bytes_sent = n == -1 ? 0 : n;
3964 while (wsa->first_iovec < wsa->n_iovecs)
3967 int timeout = GET_SNDTIMEO(fd);
3971 timeout -= GetTickCount() - timeout_start;
3972 if (timeout < 0) timeout = 0;
3976 pfd.events = POLLOUT;
3978 if (!timeout || !poll( &pfd, 1, timeout ))
3981 goto error; /* msdn says a timeout in send is fatal */
3984 n = WS2_send( fd, wsa );
3985 if (n == -1 && errno != EAGAIN && errno != EINTR)
3995 else /* non-blocking */
3997 if (n < totalLength)
3998 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
4001 err = WSAEWOULDBLOCK;
4007 TRACE(" -> %i bytes\n", bytes_sent);
4009 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = bytes_sent;
4010 HeapFree( GetProcessHeap(), 0, wsa );
4011 release_sock_fd( s, fd );
4016 HeapFree( GetProcessHeap(), 0, wsa );
4017 release_sock_fd( s, fd );
4018 WARN(" -> ERROR %d\n", err);
4019 WSASetLastError(err);
4020 return SOCKET_ERROR;
4023 /***********************************************************************
4024 * WSASendTo (WS2_32.74)
4026 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4027 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4028 const struct WS_sockaddr *to, int tolen,
4029 LPWSAOVERLAPPED lpOverlapped,
4030 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4032 return WS2_sendto( s, lpBuffers, dwBufferCount,
4033 lpNumberOfBytesSent, dwFlags,
4035 lpOverlapped, lpCompletionRoutine );
4038 /***********************************************************************
4039 * sendto (WS2_32.20)
4041 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
4042 const struct WS_sockaddr *to, int tolen)
4048 wsabuf.buf = (char*) buf;
4050 if ( WS2_sendto(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
4051 return SOCKET_ERROR;
4056 /***********************************************************************
4057 * setsockopt (WS2_32.21)
4059 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
4060 const char *optval, int optlen)
4064 struct linger linger;
4065 struct timeval tval;
4067 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
4068 s, level, optname, optval, optlen);
4070 /* some broken apps pass the value directly instead of a pointer to it */
4071 if(optlen && IS_INTRESOURCE(optval))
4073 SetLastError(WSAEFAULT);
4074 return SOCKET_ERROR;
4082 /* Some options need some conversion before they can be sent to
4083 * setsockopt. The conversions are done here, then they will fall though
4084 * to the general case. Special options that are not passed to
4085 * setsockopt follow below that.*/
4087 case WS_SO_DONTLINGER:
4090 SetLastError(WSAEFAULT);
4091 return SOCKET_ERROR;
4093 linger.l_onoff = *((const int*)optval) ? 0: 1;
4094 linger.l_linger = 0;
4096 optname = SO_LINGER;
4097 optval = (char*)&linger;
4098 optlen = sizeof(struct linger);
4104 SetLastError(WSAEFAULT);
4105 return SOCKET_ERROR;
4107 linger.l_onoff = ((LINGER*)optval)->l_onoff;
4108 linger.l_linger = ((LINGER*)optval)->l_linger;
4110 optname = SO_LINGER;
4111 optval = (char*)&linger;
4112 optlen = sizeof(struct linger);
4116 if (*(const int*)optval < 2048)
4118 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
4123 /* The options listed here don't need any special handling. Thanks to
4124 * the conversion happening above, options from there will fall through
4126 case WS_SO_ACCEPTCONN:
4127 case WS_SO_BROADCAST:
4129 case WS_SO_KEEPALIVE:
4130 case WS_SO_OOBINLINE:
4131 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
4132 * however, using it the BSD way fixes bug 8513 and seems to be what
4133 * most programmers assume, anyway */
4134 case WS_SO_REUSEADDR:
4137 convert_sockopt(&level, &optname);
4140 /* SO_DEBUG is a privileged operation, ignore it. */
4142 TRACE("Ignoring SO_DEBUG\n");
4145 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
4146 * socket. According to MSDN, this option is silently ignored.*/
4147 case WS_SO_DONTROUTE:
4148 TRACE("Ignoring SO_DONTROUTE\n");
4151 /* Stops two sockets from being bound to the same port. Always happens
4152 * on unix systems, so just drop it. */
4153 case WS_SO_EXCLUSIVEADDRUSE:
4154 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
4157 /* After a ConnectEx call succeeds, the socket can't be used with half of the
4158 * normal winsock functions on windows. We don't have that problem. */
4159 case WS_SO_UPDATE_CONNECT_CONTEXT:
4160 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
4163 /* After a AcceptEx call succeeds, the socket can't be used with half of the
4164 * normal winsock functions on windows. We don't have that problem. */
4165 case WS_SO_UPDATE_ACCEPT_CONTEXT:
4166 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
4169 /* SO_OPENTYPE does not require a valid socket handle. */
4170 case WS_SO_OPENTYPE:
4171 if (!optlen || optlen < sizeof(int) || !optval)
4173 SetLastError(WSAEFAULT);
4174 return SOCKET_ERROR;
4176 get_per_thread_data()->opentype = *(const int *)optval;
4177 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
4181 case WS_SO_RCVTIMEO:
4184 case WS_SO_SNDTIMEO:
4186 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
4187 if (optval && optlen == sizeof(UINT32)) {
4188 /* WinSock passes milliseconds instead of struct timeval */
4189 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
4190 tval.tv_sec = *(const UINT32*)optval / 1000;
4191 /* min of 500 milliseconds */
4192 if (tval.tv_sec == 0 && tval.tv_usec && tval.tv_usec < 500000)
4193 tval.tv_usec = 500000;
4194 optlen = sizeof(struct timeval);
4195 optval = (char*)&tval;
4196 } else if (optlen == sizeof(struct timeval)) {
4197 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
4199 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
4202 convert_sockopt(&level, &optname);
4207 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
4208 SetLastError(WSAENOPROTOOPT);
4209 return SOCKET_ERROR;
4211 break; /* case WS_SOL_SOCKET */
4218 fd = get_sock_fd( s, 0, NULL );
4219 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", *(const int*)optval, fd);
4221 /* We try to set the ipx type on ipx socket level. */
4223 if(setsockopt(fd, SOL_IPX, IPX_TYPE, optval, optlen) == -1)
4225 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
4226 release_sock_fd( s, fd );
4227 return SOCKET_ERROR;
4232 /* Should we retrieve val using a getsockopt call and then
4233 * set the modified one? */
4234 val.ipx_pt = *optval;
4235 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
4238 release_sock_fd( s, fd );
4241 case IPX_FILTERPTYPE:
4242 /* Sets the receive filter packet type, at the moment we don't support it */
4243 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
4244 /* Returning 0 is better for now than returning a SOCKET_ERROR */
4248 FIXME("opt_name:%x\n", optname);
4249 return SOCKET_ERROR;
4251 break; /* case NSPROTO_IPX */
4254 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
4255 case WS_IPPROTO_TCP:
4258 case WS_TCP_NODELAY:
4259 convert_sockopt(&level, &optname);
4262 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
4263 return SOCKET_ERROR;
4270 case WS_IP_ADD_MEMBERSHIP:
4271 case WS_IP_DROP_MEMBERSHIP:
4275 case WS_IP_MULTICAST_IF:
4276 case WS_IP_MULTICAST_LOOP:
4277 case WS_IP_MULTICAST_TTL:
4284 #ifdef IP_UNICAST_IF
4285 case WS_IP_UNICAST_IF:
4287 convert_sockopt(&level, &optname);
4289 case WS_IP_DONTFRAGMENT:
4290 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
4293 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
4294 return SOCKET_ERROR;
4298 case WS_IPPROTO_IPV6:
4301 #ifdef IPV6_ADD_MEMBERSHIP
4302 case WS_IPV6_ADD_MEMBERSHIP:
4304 #ifdef IPV6_DROP_MEMBERSHIP
4305 case WS_IPV6_DROP_MEMBERSHIP:
4307 case WS_IPV6_MULTICAST_IF:
4308 case WS_IPV6_MULTICAST_HOPS:
4309 case WS_IPV6_MULTICAST_LOOP:
4310 case WS_IPV6_UNICAST_HOPS:
4311 case WS_IPV6_V6ONLY:
4312 #ifdef IPV6_UNICAST_IF
4313 case WS_IPV6_UNICAST_IF:
4315 convert_sockopt(&level, &optname);
4317 case WS_IPV6_DONTFRAG:
4318 FIXME("IPV6_DONTFRAG is silently ignored!\n");
4320 case WS_IPV6_PROTECTION_LEVEL:
4321 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
4324 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
4325 return SOCKET_ERROR;
4330 WARN("Unknown level: 0x%08x\n", level);
4331 SetLastError(WSAEINVAL);
4332 return SOCKET_ERROR;
4333 } /* end switch(level) */
4335 /* avoid endianness issues if argument is a 16-bit int */
4336 if (optval && optlen < sizeof(int))
4338 woptval= *((const INT16 *) optval);
4339 optval= (char*) &woptval;
4342 fd = get_sock_fd( s, 0, NULL );
4343 if (fd == -1) return SOCKET_ERROR;
4345 if (setsockopt(fd, level, optname, optval, optlen) == 0)
4347 release_sock_fd( s, fd );
4350 TRACE("Setting socket error, %d\n", wsaErrno());
4351 SetLastError(wsaErrno());
4352 release_sock_fd( s, fd );
4354 return SOCKET_ERROR;
4357 /***********************************************************************
4358 * shutdown (WS2_32.22)
4360 int WINAPI WS_shutdown(SOCKET s, int how)
4362 int fd, err = WSAENOTSOCK;
4363 unsigned int options, clear_flags = 0;
4365 fd = get_sock_fd( s, 0, &options );
4366 TRACE("socket %04lx, how %i %x\n", s, how, options );
4369 return SOCKET_ERROR;
4373 case 0: /* drop receives */
4374 clear_flags |= FD_READ;
4376 case 1: /* drop sends */
4377 clear_flags |= FD_WRITE;
4379 case 2: /* drop all */
4380 clear_flags |= FD_READ|FD_WRITE;
4383 clear_flags |= FD_WINE_LISTENING;
4386 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
4391 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
4394 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
4398 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
4399 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
4402 if (err) goto error;
4404 else /* non-overlapped mode */
4406 if ( shutdown( fd, how ) )
4413 release_sock_fd( s, fd );
4414 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
4415 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
4419 release_sock_fd( s, fd );
4420 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
4421 WSASetLastError( err );
4422 return SOCKET_ERROR;
4425 /***********************************************************************
4426 * socket (WS2_32.23)
4428 SOCKET WINAPI WS_socket(int af, int type, int protocol)
4430 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
4432 return WSASocketA( af, type, protocol, NULL, 0,
4433 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
4437 /***********************************************************************
4438 * gethostbyaddr (WS2_32.51)
4440 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
4442 struct WS_hostent *retval = NULL;
4443 struct hostent* host;
4445 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4448 struct hostent hostentry;
4451 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
4453 int res = gethostbyaddr_r(addr, len, type,
4454 &hostentry, extrabuf, ebufsize, &host, &locerr);
4455 if( res != ERANGE) break;
4457 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
4459 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
4461 EnterCriticalSection( &csWSgetXXXbyYYY );
4462 host = gethostbyaddr(addr, len, type);
4463 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
4465 if( host != NULL ) retval = WS_dup_he(host);
4466 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4467 HeapFree(GetProcessHeap(),0,extrabuf);
4469 LeaveCriticalSection( &csWSgetXXXbyYYY );
4471 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
4475 /***********************************************************************
4476 * WS_get_local_ips (INTERNAL)
4478 * Returns the list of local IP addresses by going through the network
4479 * adapters and using the local routing table to sort the addresses
4480 * from highest routing priority to lowest routing priority. This
4481 * functionality is inferred from the description for obtaining local
4482 * IP addresses given in the Knowledge Base Article Q160215.
4484 * Please note that the returned hostent is only freed when the thread
4485 * closes and is replaced if another hostent is requested.
4487 static struct WS_hostent* WS_get_local_ips( char *hostname )
4489 int last_metric, numroutes = 0, i, j;
4490 PIP_ADAPTER_INFO adapters = NULL, k;
4491 struct WS_hostent *hostlist = NULL;
4492 PMIB_IPFORWARDTABLE routes = NULL;
4493 struct route *route_addrs = NULL;
4494 DWORD adap_size, route_size;
4496 /* Obtain the size of the adapter list and routing table, also allocate memory */
4497 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
4499 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
4501 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
4502 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
4503 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
4504 if (adapters == NULL || routes == NULL || route_addrs == NULL)
4506 /* Obtain the adapter list and the full routing table */
4507 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
4509 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
4511 /* Store the interface associated with each route */
4512 for (i = 0; i < routes->dwNumEntries; i++)
4515 DWORD ifmetric, exists = FALSE;
4517 if (routes->table[i].u1.ForwardType != MIB_IPROUTE_TYPE_DIRECT)
4519 ifindex = routes->table[i].dwForwardIfIndex;
4520 ifmetric = routes->table[i].dwForwardMetric1;
4521 /* Only store the lowest valued metric for an interface */
4522 for (j = 0; j < numroutes; j++)
4524 if (route_addrs[j].interface == ifindex)
4526 if (route_addrs[j].metric > ifmetric)
4527 route_addrs[j].metric = ifmetric;
4533 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
4534 if (route_addrs == NULL)
4535 goto cleanup; /* Memory allocation error, fail gracefully */
4536 route_addrs[numroutes].interface = ifindex;
4537 route_addrs[numroutes].metric = ifmetric;
4538 /* If no IP is found in the next step (for whatever reason)
4539 * then fall back to the magic loopback address.
4541 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
4545 goto cleanup; /* No routes, fall back to the Magic IP */
4546 /* Find the IP address associated with each found interface */
4547 for (i = 0; i < numroutes; i++)
4549 for (k = adapters; k != NULL; k = k->Next)
4551 char *ip = k->IpAddressList.IpAddress.String;
4553 if (route_addrs[i].interface == k->Index)
4554 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
4557 /* Allocate a hostent and enough memory for all the IPs,
4558 * including the NULL at the end of the list.
4560 hostlist = WS_create_he(hostname, 1, numroutes+1, TRUE);
4561 if (hostlist == NULL)
4562 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
4563 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
4564 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
4565 hostlist->h_addrtype = AF_INET;
4566 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
4567 /* Reorder the entries when placing them in the host list, Windows expects
4568 * the IP list in order from highest priority to lowest (the critical thing
4569 * is that most applications expect the first IP to be the default route).
4572 for (i = 0; i < numroutes; i++)
4574 struct in_addr addr;
4575 int metric = 0xFFFF;
4577 memcpy(&addr, magic_loopback_addr, 4);
4578 for (j = 0; j < numroutes; j++)
4580 int this_metric = route_addrs[j].metric;
4582 if (this_metric > last_metric && this_metric < metric)
4584 addr = route_addrs[j].addr;
4585 metric = this_metric;
4588 last_metric = metric;
4589 (*(struct in_addr *) hostlist->h_addr_list[i]) = addr;
4592 /* Cleanup all allocated memory except the address list,
4593 * the address list is used by the calling app.
4596 HeapFree(GetProcessHeap(), 0, route_addrs);
4597 HeapFree(GetProcessHeap(), 0, adapters);
4598 HeapFree(GetProcessHeap(), 0, routes);
4602 /***********************************************************************
4603 * gethostbyname (WS2_32.52)
4605 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
4607 struct WS_hostent *retval = NULL;
4608 struct hostent* host;
4609 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4612 struct hostent hostentry;
4613 int locerr = ENOBUFS;
4617 SetLastError(WSANOTINITIALISED);
4620 if( gethostname( hostname, 100) == -1) {
4621 SetLastError( WSAENOBUFS); /* appropriate ? */
4624 if( !name || !name[0]) {
4627 /* If the hostname of the local machine is requested then return the
4628 * complete list of local IP addresses */
4629 if(strcmp(name, hostname) == 0)
4630 retval = WS_get_local_ips(hostname);
4631 /* If any other hostname was requested (or the routing table lookup failed)
4632 * then return the IP found by the host OS */
4635 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4637 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
4639 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
4640 if( res != ERANGE) break;
4642 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
4644 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
4646 EnterCriticalSection( &csWSgetXXXbyYYY );
4647 host = gethostbyname(name);
4648 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
4650 if (host) retval = WS_dup_he(host);
4651 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4652 HeapFree(GetProcessHeap(),0,extrabuf);
4654 LeaveCriticalSection( &csWSgetXXXbyYYY );
4657 if (retval && retval->h_addr_list[0][0] == 127 &&
4658 strcmp(name, "localhost") != 0)
4660 /* hostname != "localhost" but has loopback address. replace by our
4661 * special address.*/
4662 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
4664 TRACE( "%s ret %p\n", debugstr_a(name), retval );
4669 /***********************************************************************
4670 * getprotobyname (WS2_32.53)
4672 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
4674 struct WS_protoent* retval = NULL;
4675 #ifdef HAVE_GETPROTOBYNAME
4676 struct protoent* proto;
4677 EnterCriticalSection( &csWSgetXXXbyYYY );
4678 if( (proto = getprotobyname(name)) != NULL )
4680 retval = WS_dup_pe(proto);
4683 MESSAGE("protocol %s not found; You might want to add "
4684 "this to /etc/protocols\n", debugstr_a(name) );
4685 SetLastError(WSANO_DATA);
4687 LeaveCriticalSection( &csWSgetXXXbyYYY );
4689 TRACE( "%s ret %p\n", debugstr_a(name), retval );
4694 /***********************************************************************
4695 * getprotobynumber (WS2_32.54)
4697 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
4699 struct WS_protoent* retval = NULL;
4700 #ifdef HAVE_GETPROTOBYNUMBER
4701 struct protoent* proto;
4702 EnterCriticalSection( &csWSgetXXXbyYYY );
4703 if( (proto = getprotobynumber(number)) != NULL )
4705 retval = WS_dup_pe(proto);
4708 MESSAGE("protocol number %d not found; You might want to add "
4709 "this to /etc/protocols\n", number );
4710 SetLastError(WSANO_DATA);
4712 LeaveCriticalSection( &csWSgetXXXbyYYY );
4714 TRACE("%i ret %p\n", number, retval);
4719 /***********************************************************************
4720 * getservbyname (WS2_32.55)
4722 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
4724 struct WS_servent* retval = NULL;
4725 struct servent* serv;
4727 char *proto_str = NULL;
4729 if (!(name_str = strdup_lower(name))) return NULL;
4731 if (proto && *proto)
4733 if (!(proto_str = strdup_lower(proto)))
4735 HeapFree( GetProcessHeap(), 0, name_str );
4740 EnterCriticalSection( &csWSgetXXXbyYYY );
4741 serv = getservbyname(name_str, proto_str);
4744 retval = WS_dup_se(serv);
4746 else SetLastError(WSANO_DATA);
4747 LeaveCriticalSection( &csWSgetXXXbyYYY );
4748 HeapFree( GetProcessHeap(), 0, proto_str );
4749 HeapFree( GetProcessHeap(), 0, name_str );
4750 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
4754 /***********************************************************************
4755 * freeaddrinfo (WS2_32.@)
4757 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
4760 struct WS_addrinfo *next;
4762 HeapFree(GetProcessHeap(),0,res->ai_canonname);
4763 HeapFree(GetProcessHeap(),0,res->ai_addr);
4764 next = res->ai_next;
4765 HeapFree(GetProcessHeap(),0,res);
4770 /* helper functions for getaddrinfo()/getnameinfo() */
4771 static int convert_aiflag_w2u(int winflags) {
4775 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
4776 if (ws_aiflag_map[i][0] & winflags) {
4777 unixflags |= ws_aiflag_map[i][1];
4778 winflags &= ~ws_aiflag_map[i][0];
4781 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
4785 static int convert_niflag_w2u(int winflags) {
4789 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
4790 if (ws_niflag_map[i][0] & winflags) {
4791 unixflags |= ws_niflag_map[i][1];
4792 winflags &= ~ws_niflag_map[i][0];
4795 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
4799 static int convert_aiflag_u2w(int unixflags) {
4803 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
4804 if (ws_aiflag_map[i][1] & unixflags) {
4805 winflags |= ws_aiflag_map[i][0];
4806 unixflags &= ~ws_aiflag_map[i][1];
4808 if (unixflags) /* will warn usually */
4809 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
4813 static int convert_eai_u2w(int unixret) {
4816 for (i=0;ws_eai_map[i][0];i++)
4817 if (ws_eai_map[i][1] == unixret)
4818 return ws_eai_map[i][0];
4822 static char *get_hostname(void)
4827 GetComputerNameExA( ComputerNamePhysicalDnsHostname, NULL, &size );
4828 if (GetLastError() != ERROR_MORE_DATA) return NULL;
4829 if (!(ret = HeapAlloc( GetProcessHeap(), 0, size ))) return NULL;
4830 if (!GetComputerNameExA( ComputerNamePhysicalDnsHostname, ret, &size ))
4832 HeapFree( GetProcessHeap(), 0, ret );
4838 /***********************************************************************
4839 * getaddrinfo (WS2_32.@)
4841 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
4843 #ifdef HAVE_GETADDRINFO
4844 struct addrinfo *unixaires = NULL;
4846 struct addrinfo unixhints, *punixhints = NULL;
4847 char *hostname = NULL;
4850 if (!nodename && !servname) return WSAHOST_NOT_FOUND;
4854 else if (!nodename[0])
4856 node = hostname = get_hostname();
4857 if (!node) return WSA_NOT_ENOUGH_MEMORY;
4863 punixhints = &unixhints;
4865 memset(&unixhints, 0, sizeof(unixhints));
4866 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
4867 if (hints->ai_family == 0) /* wildcard, specific to getaddrinfo() */
4868 punixhints->ai_family = 0;
4870 punixhints->ai_family = convert_af_w2u(hints->ai_family);
4871 if (hints->ai_socktype == 0) /* wildcard, specific to getaddrinfo() */
4872 punixhints->ai_socktype = 0;
4874 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
4875 if (hints->ai_protocol == 0) /* wildcard, specific to getaddrinfo() */
4876 punixhints->ai_protocol = 0;
4878 punixhints->ai_protocol = convert_proto_w2u(hints->ai_protocol);
4881 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
4882 result = getaddrinfo(node, servname, punixhints, &unixaires);
4884 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
4885 HeapFree(GetProcessHeap(), 0, hostname);
4888 struct addrinfo *xuai = unixaires;
4889 struct WS_addrinfo **xai = res;
4893 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
4899 *xai = ai;xai = &ai->ai_next;
4900 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
4901 ai->ai_family = convert_af_u2w(xuai->ai_family);
4902 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
4903 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
4904 if (xuai->ai_canonname) {
4905 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
4906 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
4907 if (!ai->ai_canonname)
4909 strcpy(ai->ai_canonname,xuai->ai_canonname);
4911 len = xuai->ai_addrlen;
4912 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
4915 ai->ai_addrlen = len;
4917 int winlen = ai->ai_addrlen;
4919 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
4920 ai->ai_addrlen = winlen;
4924 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
4927 ai->ai_addrlen = len;
4929 xuai = xuai->ai_next;
4931 freeaddrinfo(unixaires);
4933 result = convert_eai_u2w(result);
4939 if (*res) WS_freeaddrinfo(*res);
4940 if (unixaires) freeaddrinfo(unixaires);
4942 return WSA_NOT_ENOUGH_MEMORY;
4944 FIXME("getaddrinfo() failed, not found during buildtime.\n");
4949 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
4951 struct WS_addrinfoW *ret;
4953 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
4954 ret->ai_flags = ai->ai_flags;
4955 ret->ai_family = ai->ai_family;
4956 ret->ai_socktype = ai->ai_socktype;
4957 ret->ai_protocol = ai->ai_protocol;
4958 ret->ai_addrlen = ai->ai_addrlen;
4959 ret->ai_canonname = NULL;
4960 ret->ai_addr = NULL;
4961 ret->ai_next = NULL;
4962 if (ai->ai_canonname)
4964 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
4965 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
4967 HeapFree(GetProcessHeap(), 0, ret);
4970 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
4974 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
4976 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
4977 HeapFree(GetProcessHeap(), 0, ret);
4980 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
4985 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
4987 struct WS_addrinfoW *ret, *infoW;
4989 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
4990 while (info->ai_next)
4992 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
4997 infoW = infoW->ai_next;
4998 info = info->ai_next;
5003 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
5005 struct WS_addrinfo *ret;
5007 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
5008 ret->ai_flags = ai->ai_flags;
5009 ret->ai_family = ai->ai_family;
5010 ret->ai_socktype = ai->ai_socktype;
5011 ret->ai_protocol = ai->ai_protocol;
5012 ret->ai_addrlen = ai->ai_addrlen;
5013 ret->ai_canonname = NULL;
5014 ret->ai_addr = NULL;
5015 ret->ai_next = NULL;
5016 if (ai->ai_canonname)
5018 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
5019 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
5021 HeapFree(GetProcessHeap(), 0, ret);
5024 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
5028 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
5030 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
5031 HeapFree(GetProcessHeap(), 0, ret);
5034 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
5039 /***********************************************************************
5040 * GetAddrInfoW (WS2_32.@)
5042 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
5045 char *nodenameA = NULL, *servnameA = NULL;
5046 struct WS_addrinfo *resA, *hintsA = NULL;
5050 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
5051 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
5052 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
5056 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
5057 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
5059 HeapFree(GetProcessHeap(), 0, nodenameA);
5062 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
5065 if (hints) hintsA = addrinfo_WtoA(hints);
5066 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
5067 WS_freeaddrinfo(hintsA);
5071 *res = addrinfo_list_AtoW(resA);
5072 WS_freeaddrinfo(resA);
5075 HeapFree(GetProcessHeap(), 0, nodenameA);
5076 HeapFree(GetProcessHeap(), 0, servnameA);
5080 /***********************************************************************
5081 * FreeAddrInfoW (WS2_32.@)
5083 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
5088 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
5089 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
5091 HeapFree(GetProcessHeap(), 0, ai);
5096 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
5097 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
5099 #ifdef HAVE_GETNAMEINFO
5101 union generic_unix_sockaddr sa_u;
5104 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
5105 serv, servlen, flags);
5107 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
5110 WSASetLastError(WSAEFAULT);
5111 return WSA_NOT_ENOUGH_MEMORY;
5113 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
5114 return convert_eai_u2w(ret);
5116 FIXME("getnameinfo() failed, not found during buildtime.\n");
5121 int WINAPI GetNameInfoW(const SOCKADDR *sa, WS_socklen_t salen, PWCHAR host,
5122 DWORD hostlen, PWCHAR serv, DWORD servlen, INT flags)
5125 char *hostA = NULL, *servA = NULL;
5127 if (host && (!(hostA = HeapAlloc(GetProcessHeap(), 0, hostlen)))) return EAI_MEMORY;
5128 if (serv && (!(servA = HeapAlloc(GetProcessHeap(), 0, servlen))))
5130 HeapFree(GetProcessHeap(), 0, hostA);
5134 ret = WS_getnameinfo(sa, salen, hostA, hostlen, servA, servlen, flags);
5137 if (host) MultiByteToWideChar(CP_ACP, 0, hostA, -1, host, hostlen);
5138 if (serv) MultiByteToWideChar(CP_ACP, 0, servA, -1, serv, servlen);
5141 HeapFree(GetProcessHeap(), 0, hostA);
5142 HeapFree(GetProcessHeap(), 0, servA);
5146 /***********************************************************************
5147 * getservbyport (WS2_32.56)
5149 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
5151 struct WS_servent* retval = NULL;
5152 #ifdef HAVE_GETSERVBYPORT
5153 struct servent* serv;
5154 char *proto_str = NULL;
5156 if (proto && *proto)
5158 if (!(proto_str = strdup_lower(proto))) return NULL;
5160 EnterCriticalSection( &csWSgetXXXbyYYY );
5161 if( (serv = getservbyport(port, proto_str)) != NULL ) {
5162 retval = WS_dup_se(serv);
5164 else SetLastError(WSANO_DATA);
5165 LeaveCriticalSection( &csWSgetXXXbyYYY );
5166 HeapFree( GetProcessHeap(), 0, proto_str );
5168 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
5173 /***********************************************************************
5174 * gethostname (WS2_32.57)
5176 int WINAPI WS_gethostname(char *name, int namelen)
5178 TRACE("name %p, len %d\n", name, namelen);
5180 if (gethostname(name, namelen) == 0)
5182 TRACE("<- '%s'\n", name);
5185 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
5186 TRACE("<- ERROR !\n");
5187 return SOCKET_ERROR;
5191 /* ------------------------------------- Windows sockets extensions -- *
5193 * ------------------------------------------------------------------- */
5195 /***********************************************************************
5196 * WSAEnumNetworkEvents (WS2_32.36)
5198 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
5202 int errors[FD_MAX_EVENTS];
5204 TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
5206 SERVER_START_REQ( get_socket_event )
5208 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5209 req->service = TRUE;
5210 req->c_event = wine_server_obj_handle( hEvent );
5211 wine_server_set_reply( req, errors, sizeof(errors) );
5212 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
5217 for (i = 0; i < FD_MAX_EVENTS; i++)
5218 lpEvent->iErrorCode[i] = NtStatusToWSAError(errors[i]);
5221 SetLastError(WSAEINVAL);
5222 return SOCKET_ERROR;
5225 /***********************************************************************
5226 * WSAEventSelect (WS2_32.39)
5228 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
5232 TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
5234 SERVER_START_REQ( set_socket_event )
5236 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5238 req->event = wine_server_obj_handle( hEvent );
5241 ret = wine_server_call( req );
5245 SetLastError(WSAEINVAL);
5246 return SOCKET_ERROR;
5249 /**********************************************************************
5250 * WSAGetOverlappedResult (WS2_32.40)
5252 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
5253 LPDWORD lpcbTransfer, BOOL fWait,
5258 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
5259 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
5261 if ( lpOverlapped == NULL )
5263 ERR( "Invalid pointer\n" );
5264 WSASetLastError(WSA_INVALID_PARAMETER);
5268 status = lpOverlapped->Internal;
5269 if (status == STATUS_PENDING)
5273 SetLastError( WSA_IO_INCOMPLETE );
5277 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
5278 INFINITE ) == WAIT_FAILED)
5280 status = lpOverlapped->Internal;
5284 *lpcbTransfer = lpOverlapped->InternalHigh;
5287 *lpdwFlags = lpOverlapped->u.s.Offset;
5289 if (status) SetLastError( RtlNtStatusToDosError(status) );
5294 /***********************************************************************
5295 * WSAAsyncSelect (WS2_32.101)
5297 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
5301 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
5303 SERVER_START_REQ( set_socket_event )
5305 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5308 req->window = wine_server_user_handle( hWnd );
5310 ret = wine_server_call( req );
5314 SetLastError(WSAEINVAL);
5315 return SOCKET_ERROR;
5318 /***********************************************************************
5319 * WSACreateEvent (WS2_32.31)
5322 WSAEVENT WINAPI WSACreateEvent(void)
5324 /* Create a manual-reset event, with initial state: unsignaled */
5327 return CreateEventW(NULL, TRUE, FALSE, NULL);
5330 /***********************************************************************
5331 * WSACloseEvent (WS2_32.29)
5334 BOOL WINAPI WSACloseEvent(WSAEVENT event)
5336 TRACE ("event=%p\n", event);
5338 return CloseHandle(event);
5341 /***********************************************************************
5342 * WSASocketA (WS2_32.78)
5345 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
5346 LPWSAPROTOCOL_INFOA lpProtocolInfo,
5347 GROUP g, DWORD dwFlags)
5350 WSAPROTOCOL_INFOW info;
5352 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
5353 af, type, protocol, lpProtocolInfo, g, dwFlags);
5355 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
5357 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
5358 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
5359 info.szProtocol, WSAPROTOCOL_LEN + 1);
5363 WSASetLastError( WSAEINVAL);
5364 return SOCKET_ERROR;
5367 return WSASocketW(af, type, protocol, &info, g, dwFlags);
5370 /***********************************************************************
5371 * WSASocketW (WS2_32.79)
5374 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
5375 LPWSAPROTOCOL_INFOW lpProtocolInfo,
5376 GROUP g, DWORD dwFlags)
5381 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
5382 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
5385 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
5386 af, type, protocol, lpProtocolInfo, g, dwFlags );
5388 /* hack for WSADuplicateSocket */
5389 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
5390 ret = lpProtocolInfo->dwCatalogEntryId;
5391 TRACE("\tgot duplicate %04lx\n", ret);
5395 /* convert the socket family and type */
5396 af = convert_af_w2u(af);
5397 type = convert_socktype_w2u(type);
5401 if (af == FROM_PROTOCOL_INFO)
5402 af = lpProtocolInfo->iAddressFamily;
5403 if (type == FROM_PROTOCOL_INFO)
5404 type = lpProtocolInfo->iSocketType;
5405 if (protocol == FROM_PROTOCOL_INFO)
5406 protocol = lpProtocolInfo->iProtocol;
5409 if ( af == AF_UNSPEC) /* did they not specify the address family? */
5411 if ((protocol == IPPROTO_TCP && type == SOCK_STREAM) ||
5412 (protocol == IPPROTO_UDP && type == SOCK_DGRAM))
5418 SetLastError(WSAEPROTOTYPE);
5419 return INVALID_SOCKET;
5423 SERVER_START_REQ( create_socket )
5427 req->protocol = protocol;
5428 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
5429 req->attributes = OBJ_INHERIT;
5430 req->flags = dwFlags;
5431 set_error( wine_server_call( req ) );
5432 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
5437 TRACE("\tcreated %04lx\n", ret );
5441 if (GetLastError() == WSAEACCES) /* raw socket denied */
5443 if (type == SOCK_RAW)
5444 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
5446 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
5447 SetLastError(WSAESOCKTNOSUPPORT);
5450 WARN("\t\tfailed!\n");
5451 return INVALID_SOCKET;
5454 /***********************************************************************
5455 * WSAJoinLeaf (WS2_32.58)
5458 SOCKET WINAPI WSAJoinLeaf(
5460 const struct WS_sockaddr *addr,
5462 LPWSABUF lpCallerData,
5463 LPWSABUF lpCalleeData,
5469 return INVALID_SOCKET;
5472 /***********************************************************************
5473 * __WSAFDIsSet (WS2_32.151)
5475 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
5477 int i = set->fd_count;
5479 TRACE("(%ld,%p(%i))\n", s, set, i);
5482 if (set->fd_array[i] == s) return 1;
5486 /***********************************************************************
5487 * WSAIsBlocking (WS2_32.114)
5489 BOOL WINAPI WSAIsBlocking(void)
5491 /* By default WinSock should set all its sockets to non-blocking mode
5492 * and poll in PeekMessage loop when processing "blocking" ones. This
5493 * function is supposed to tell if the program is in this loop. Our
5494 * blocking calls are truly blocking so we always return FALSE.
5496 * Note: It is allowed to call this function without prior WSAStartup().
5503 /***********************************************************************
5504 * WSACancelBlockingCall (WS2_32.113)
5506 INT WINAPI WSACancelBlockingCall(void)
5512 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
5514 FIXME("How was this called?\n");
5519 /***********************************************************************
5520 * WSASetBlockingHook (WS2_32.109)
5522 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
5524 FARPROC prev = blocking_hook;
5525 blocking_hook = lpBlockFunc;
5526 TRACE("hook %p\n", lpBlockFunc);
5531 /***********************************************************************
5532 * WSAUnhookBlockingHook (WS2_32.110)
5534 INT WINAPI WSAUnhookBlockingHook(void)
5536 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
5541 /* ----------------------------------- end of API stuff */
5543 /* ----------------------------------- helper functions -
5545 * TODO: Merge WS_dup_..() stuff into one function that
5546 * would operate with a generic structure containing internal
5547 * pointers (via a template of some kind).
5550 static int list_size(char** l, int item_size)
5555 j += (item_size) ? item_size : strlen(l[i]) + 1;
5556 j += (i + 1) * sizeof(char*); }
5560 static int list_dup(char** l_src, char** l_to, int item_size)
5565 for (i = 0; l_src[i]; i++) ;
5566 p = (char *)(l_to + i + 1);
5567 for (i = 0; l_src[i]; i++)
5569 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
5570 memcpy(p, l_src[i], count);
5575 return p - (char *)l_to;
5580 /* create a hostent entry
5582 * Creates the entry with enough memory for the name, aliases
5583 * addresses, and the address pointers. Also copies the name
5584 * and sets up all the pointers. If "fill_addresses" is set then
5585 * sufficient memory for the addresses is also allocated and the
5586 * address pointers are set to this memory.
5588 * NOTE: The alias and address lists must be allocated with room
5589 * for the NULL item terminating the list. This is true even if
5590 * the list has no items ("aliases" and "addresses" must be
5591 * at least "1", a truly empty list is invalid).
5593 static struct WS_hostent *WS_create_he(char *name, int aliases, int addresses, int fill_addresses)
5595 struct WS_hostent *p_to;
5598 int size = (sizeof(struct WS_hostent) +
5600 sizeof(char *)*aliases +
5601 sizeof(char *)*addresses);
5603 /* Allocate enough memory for the addresses */
5605 size += sizeof(struct in_addr)*addresses;
5607 if (!(p_to = check_buffer_he(size))) return NULL;
5608 memset(p_to, 0, size);
5610 p = (char *)(p_to + 1);
5615 p_to->h_aliases = (char **)p;
5616 p += sizeof(char *)*aliases;
5617 p_to->h_addr_list = (char **)p;
5618 p += sizeof(char *)*addresses;
5623 /* NOTE: h_aliases must be filled in manually, leave these
5624 * pointers NULL (already set to NULL by memset earlier).
5627 /* Fill in the list of address pointers */
5628 for (i = 0; i < addresses; i++)
5629 p_to->h_addr_list[i] = (p += sizeof(struct in_addr));
5630 p += sizeof(struct in_addr);
5635 /* duplicate hostent entry
5636 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
5637 * Ditto for protoent and servent.
5639 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
5641 int addresses = list_size(p_he->h_addr_list, p_he->h_length);
5642 int aliases = list_size(p_he->h_aliases, 0);
5643 struct WS_hostent *p_to;
5645 p_to = WS_create_he(p_he->h_name, aliases, addresses, FALSE);
5647 if (!p_to) return NULL;
5648 p_to->h_addrtype = p_he->h_addrtype;
5649 p_to->h_length = p_he->h_length;
5651 list_dup(p_he->h_aliases, p_to->h_aliases, 0);
5652 list_dup(p_he->h_addr_list, p_to->h_addr_list, p_he->h_length);
5656 /* ----- protoent */
5658 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
5661 struct WS_protoent *p_to;
5663 int size = (sizeof(*p_pe) +
5664 strlen(p_pe->p_name) + 1 +
5665 list_size(p_pe->p_aliases, 0));
5667 if (!(p_to = check_buffer_pe(size))) return NULL;
5668 p_to->p_proto = p_pe->p_proto;
5670 p = (char *)(p_to + 1);
5672 strcpy(p, p_pe->p_name);
5675 p_to->p_aliases = (char **)p;
5676 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
5682 static struct WS_servent *WS_dup_se(const struct servent* p_se)
5685 struct WS_servent *p_to;
5687 int size = (sizeof(*p_se) +
5688 strlen(p_se->s_proto) + 1 +
5689 strlen(p_se->s_name) + 1 +
5690 list_size(p_se->s_aliases, 0));
5692 if (!(p_to = check_buffer_se(size))) return NULL;
5693 p_to->s_port = p_se->s_port;
5695 p = (char *)(p_to + 1);
5697 strcpy(p, p_se->s_name);
5701 strcpy(p, p_se->s_proto);
5704 p_to->s_aliases = (char **)p;
5705 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
5710 /***********************************************************************
5711 * WSARecv (WS2_32.67)
5713 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5714 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
5715 LPWSAOVERLAPPED lpOverlapped,
5716 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
5718 return WS2_recv_base(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
5719 NULL, NULL, lpOverlapped, lpCompletionRoutine, NULL);
5722 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5723 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
5724 struct WS_sockaddr *lpFrom,
5725 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
5726 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
5727 LPWSABUF lpControlBuffer )
5729 unsigned int i, options;
5731 struct ws2_async *wsa;
5732 DWORD timeout_start = GetTickCount();
5733 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
5735 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
5736 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
5737 (lpFromlen ? *lpFromlen : -1),
5738 lpOverlapped, lpCompletionRoutine);
5740 fd = get_sock_fd( s, FILE_READ_DATA, &options );
5741 TRACE( "fd=%d, options=%x\n", fd, options );
5743 if (fd == -1) return SOCKET_ERROR;
5745 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
5751 wsa->hSocket = SOCKET2HANDLE(s);
5752 wsa->flags = *lpFlags;
5753 wsa->lpFlags = lpFlags;
5755 wsa->addrlen.ptr = lpFromlen;
5756 wsa->control = lpControlBuffer;
5757 wsa->n_iovecs = dwBufferCount;
5758 wsa->first_iovec = 0;
5759 for (i = 0; i < dwBufferCount; i++)
5761 /* check buffer first to trigger write watches */
5762 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
5767 wsa->iovec[i].iov_base = lpBuffers[i].buf;
5768 wsa->iovec[i].iov_len = lpBuffers[i].len;
5773 n = WS2_recv( fd, wsa );
5776 if (errno == EINTR) continue;
5777 if (errno != EAGAIN)
5779 int loc_errno = errno;
5781 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
5785 else if (lpNumberOfBytesRecvd) *lpNumberOfBytesRecvd = n;
5787 if ((lpOverlapped || lpCompletionRoutine) &&
5788 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
5790 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
5792 wsa->user_overlapped = lpOverlapped;
5793 wsa->completion_func = lpCompletionRoutine;
5794 release_sock_fd( s, fd );
5798 iosb->u.Status = STATUS_PENDING;
5799 iosb->Information = 0;
5801 SERVER_START_REQ( register_async )
5803 req->type = ASYNC_TYPE_READ;
5804 req->async.handle = wine_server_obj_handle( wsa->hSocket );
5805 req->async.callback = wine_server_client_ptr( WS2_async_recv );
5806 req->async.iosb = wine_server_client_ptr( iosb );
5807 req->async.arg = wine_server_client_ptr( wsa );
5808 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
5809 req->async.cvalue = cvalue;
5810 err = wine_server_call( req );
5814 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
5815 WSASetLastError( NtStatusToWSAError( err ));
5816 return SOCKET_ERROR;
5819 iosb->u.Status = STATUS_SUCCESS;
5820 iosb->Information = n;
5821 if (!wsa->completion_func)
5823 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
5824 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
5825 HeapFree( GetProcessHeap(), 0, wsa );
5827 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
5828 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
5829 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5835 if ( _is_blocking(s) )
5838 int timeout = GET_RCVTIMEO(fd);
5841 timeout -= GetTickCount() - timeout_start;
5842 if (timeout < 0) timeout = 0;
5846 pfd.events = POLLIN;
5847 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
5849 if (!timeout || !poll( &pfd, 1, timeout ))
5852 /* a timeout is not fatal */
5853 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5859 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5860 err = WSAEWOULDBLOCK;
5865 TRACE(" -> %i bytes\n", n);
5866 HeapFree( GetProcessHeap(), 0, wsa );
5867 release_sock_fd( s, fd );
5868 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5873 HeapFree( GetProcessHeap(), 0, wsa );
5874 release_sock_fd( s, fd );
5875 WARN(" -> ERROR %d\n", err);
5876 WSASetLastError( err );
5877 return SOCKET_ERROR;
5880 /***********************************************************************
5881 * WSARecvFrom (WS2_32.69)
5883 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5884 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
5885 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
5886 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5889 return WS2_recv_base( s, lpBuffers, dwBufferCount,
5890 lpNumberOfBytesRecvd, lpFlags,
5892 lpOverlapped, lpCompletionRoutine, NULL );
5895 /***********************************************************************
5896 * WSCInstallProvider (WS2_32.88)
5898 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
5899 LPCWSTR lpszProviderDllPath,
5900 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
5901 DWORD dwNumberOfEntries,
5904 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
5905 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
5906 dwNumberOfEntries, lpErrno);
5912 /***********************************************************************
5913 * WSCDeinstallProvider (WS2_32.83)
5915 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
5917 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
5923 /***********************************************************************
5924 * WSAAccept (WS2_32.26)
5926 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
5927 LPCONDITIONPROC lpfnCondition, DWORD_PTR dwCallbackData)
5930 int ret = 0, size = 0;
5931 WSABUF CallerId, CallerData, CalleeId, CalleeData;
5932 /* QOS SQOS, GQOS; */
5935 SOCKADDR src_addr, dst_addr;
5937 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
5938 s, addr, addrlen, lpfnCondition, dwCallbackData);
5941 size = sizeof(src_addr);
5942 cs = WS_accept(s, &src_addr, &size);
5944 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
5946 if (!lpfnCondition) return cs;
5948 CallerId.buf = (char *)&src_addr;
5949 CallerId.len = sizeof(src_addr);
5951 CallerData.buf = NULL;
5954 WS_getsockname(cs, &dst_addr, &size);
5956 CalleeId.buf = (char *)&dst_addr;
5957 CalleeId.len = sizeof(dst_addr);
5960 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
5961 &CalleeId, &CalleeData, &g, dwCallbackData);
5966 if (addr && addrlen)
5967 memcpy(addr, &src_addr, (*addrlen > size) ? size : *addrlen );
5970 SERVER_START_REQ( set_socket_deferred )
5972 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5973 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
5974 if ( !wine_server_call_err ( req ) )
5976 SetLastError( WSATRY_AGAIN );
5977 WS_closesocket( cs );
5981 return SOCKET_ERROR;
5984 SetLastError(WSAECONNREFUSED);
5985 return SOCKET_ERROR;
5987 FIXME("Unknown return type from Condition function\n");
5988 SetLastError(WSAENOTSOCK);
5989 return SOCKET_ERROR;
5993 /***********************************************************************
5994 * WSADuplicateSocketA (WS2_32.32)
5996 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
6000 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
6001 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
6002 /* FIXME: WS_getsockopt(s, WS_SOL_SOCKET, SO_PROTOCOL_INFO, lpProtocolInfo, sizeof(*lpProtocolInfo)); */
6003 /* I don't know what the real Windoze does next, this is a hack */
6004 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
6005 * the target use the global duplicate, or we could copy a reference to us to the structure
6006 * and let the target duplicate it from us, but let's do it as simple as possible */
6007 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
6008 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
6009 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
6010 0, FALSE, DUPLICATE_SAME_ACCESS);
6011 CloseHandle(hProcess);
6012 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
6016 /***********************************************************************
6017 * WSADuplicateSocketW (WS2_32.33)
6019 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
6023 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
6025 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
6026 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
6027 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
6028 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
6029 0, FALSE, DUPLICATE_SAME_ACCESS);
6030 CloseHandle(hProcess);
6031 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
6035 /***********************************************************************
6036 * WSAInstallServiceClassA (WS2_32.48)
6038 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
6040 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
6041 WSASetLastError(WSAEACCES);
6042 return SOCKET_ERROR;
6045 /***********************************************************************
6046 * WSAInstallServiceClassW (WS2_32.49)
6048 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
6050 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
6051 WSASetLastError(WSAEACCES);
6052 return SOCKET_ERROR;
6055 /***********************************************************************
6056 * WSARemoveServiceClass (WS2_32.70)
6058 int WINAPI WSARemoveServiceClass(LPGUID info)
6060 FIXME("Request to remove service %p\n",info);
6061 WSASetLastError(WSATYPE_NOT_FOUND);
6062 return SOCKET_ERROR;
6065 /***********************************************************************
6066 * inet_ntop (WS2_32.@)
6068 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
6070 #ifdef HAVE_INET_NTOP
6071 struct WS_in6_addr *in6;
6072 struct WS_in_addr *in;
6075 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
6078 WSASetLastError( STATUS_INVALID_PARAMETER );
6087 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
6093 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
6097 WSASetLastError( WSAEAFNOSUPPORT );
6101 if (!pdst) WSASetLastError( STATUS_INVALID_PARAMETER );
6104 FIXME( "not supported on this platform\n" );
6105 WSASetLastError( WSAEAFNOSUPPORT );
6110 /***********************************************************************
6111 * WSAStringToAddressA (WS2_32.80)
6113 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
6115 LPWSAPROTOCOL_INFOA lpProtocolInfo,
6116 LPSOCKADDR lpAddress,
6117 LPINT lpAddressLength)
6120 LPSTR workBuffer=NULL,ptrPort;
6122 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
6123 lpProtocolInfo, lpAddress, lpAddressLength );
6125 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
6129 WSASetLastError(WSAEINVAL);
6130 return SOCKET_ERROR;
6134 FIXME("ProtocolInfo not implemented.\n");
6136 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
6137 strlen(AddressString) + 1);
6140 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6141 return SOCKET_ERROR;
6144 strcpy(workBuffer, AddressString);
6146 switch(AddressFamily)
6150 struct in_addr inetaddr;
6152 /* If lpAddressLength is too small, tell caller the size we need */
6153 if (*lpAddressLength < sizeof(SOCKADDR_IN))
6155 *lpAddressLength = sizeof(SOCKADDR_IN);
6159 *lpAddressLength = sizeof(SOCKADDR_IN);
6160 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
6162 ((LPSOCKADDR_IN)lpAddress)->sin_family = AF_INET;
6164 ptrPort = strchr(workBuffer, ':');
6167 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
6172 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
6175 if(inet_aton(workBuffer, &inetaddr) > 0)
6177 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
6188 struct in6_addr inetaddr;
6189 /* If lpAddressLength is too small, tell caller the size we need */
6190 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
6192 *lpAddressLength = sizeof(SOCKADDR_IN6);
6196 #ifdef HAVE_INET_PTON
6197 *lpAddressLength = sizeof(SOCKADDR_IN6);
6198 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
6200 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
6202 /* This one is a bit tricky. An IPv6 address contains colons, so the
6203 * check from IPv4 doesn't work like that. However, IPv6 addresses that
6204 * contain a port are written with braces like [fd12:3456:7890::1]:12345
6205 * so what we will do is to look for ']', check if the next char is a
6206 * colon, and if it is, parse the port as in IPv4. */
6208 ptrPort = strchr(workBuffer, ']');
6209 if(ptrPort && *(++ptrPort) == ':')
6211 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort+1));
6216 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
6219 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
6221 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
6222 sizeof(struct in6_addr));
6226 #endif /* HAVE_INET_PTON */
6232 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
6233 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
6237 HeapFree(GetProcessHeap(), 0, workBuffer);
6240 WSASetLastError(res);
6241 return SOCKET_ERROR;
6244 /***********************************************************************
6245 * WSAStringToAddressW (WS2_32.81)
6247 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
6248 * If this should be the case, it would be required to map these digits
6249 * to Unicode digits (0-9) using FoldString first.
6251 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
6253 LPWSAPROTOCOL_INFOW lpProtocolInfo,
6254 LPSOCKADDR lpAddress,
6255 LPINT lpAddressLength)
6258 LPSTR workBuffer=NULL;
6259 WSAPROTOCOL_INFOA infoA;
6260 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
6262 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
6263 lpAddress, lpAddressLength );
6265 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
6267 /* if ProtocolInfo is available - convert to ANSI variant */
6270 lpProtoInfoA = &infoA;
6271 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
6273 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
6274 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
6276 WSASetLastError( WSAEINVAL);
6277 return SOCKET_ERROR;
6283 /* Translate AddressString to ANSI code page - assumes that only
6284 standard digits 0-9 are used with this API call */
6285 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
6286 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
6290 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
6291 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
6292 lpAddress,lpAddressLength);
6293 HeapFree( GetProcessHeap(), 0, workBuffer );
6297 res = WSA_NOT_ENOUGH_MEMORY;
6302 WSASetLastError(res);
6303 return SOCKET_ERROR;
6306 /***********************************************************************
6307 * WSAAddressToStringA (WS2_32.27)
6309 * See WSAAddressToStringW
6311 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
6312 LPWSAPROTOCOL_INFOA info, LPSTR string,
6316 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
6319 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
6321 if (!sockaddr) return SOCKET_ERROR;
6322 if (!string || !lenstr) return SOCKET_ERROR;
6324 switch(sockaddr->sa_family)
6327 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
6328 sprintf( buffer, "%u.%u.%u.%u:%u",
6329 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
6330 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
6331 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
6332 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
6333 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
6335 p = strchr( buffer, ':' );
6336 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
6341 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
6344 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
6345 if ((sockaddr6->sin6_port))
6346 strcpy(buffer, "[");
6347 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, buffer+strlen(buffer), sizeof(buffer)))
6349 WSASetLastError(WSAEINVAL);
6350 return SOCKET_ERROR;
6352 if ((sockaddr6->sin6_scope_id))
6353 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
6354 if ((sockaddr6->sin6_port))
6355 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
6360 WSASetLastError(WSAEINVAL);
6361 return SOCKET_ERROR;
6364 size = strlen( buffer ) + 1;
6369 WSASetLastError(WSAEFAULT);
6370 return SOCKET_ERROR;
6374 strcpy( string, buffer );
6378 /***********************************************************************
6379 * WSAAddressToStringW (WS2_32.28)
6381 * Convert a sockaddr address into a readable address string.
6384 * sockaddr [I] Pointer to a sockaddr structure.
6385 * len [I] Size of the sockaddr structure.
6386 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
6387 * string [I/O] Pointer to a buffer to receive the address string.
6388 * lenstr [I/O] Size of the receive buffer in WCHARs.
6392 * Failure: SOCKET_ERROR
6395 * The 'info' parameter is ignored.
6397 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
6398 LPWSAPROTOCOL_INFOW info, LPWSTR string,
6403 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
6406 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
6409 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
6411 if (ret) return ret;
6413 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
6418 WSASetLastError(WSAEFAULT);
6419 return SOCKET_ERROR;
6423 lstrcpyW( string, buffer );
6427 /***********************************************************************
6428 * WSAEnumNameSpaceProvidersA (WS2_32.34)
6430 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
6432 FIXME( "(%p %p) Stub!\n", len, buffer );
6436 /***********************************************************************
6437 * WSAEnumNameSpaceProvidersW (WS2_32.35)
6439 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
6441 FIXME( "(%p %p) Stub!\n", len, buffer );
6445 /***********************************************************************
6446 * WSAGetQOSByName (WS2_32.41)
6448 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
6450 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
6454 /***********************************************************************
6455 * WSAGetServiceClassInfoA (WS2_32.42)
6457 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
6458 LPWSASERVICECLASSINFOA info )
6460 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
6462 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6463 return SOCKET_ERROR;
6466 /***********************************************************************
6467 * WSAGetServiceClassInfoW (WS2_32.43)
6469 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
6470 LPWSASERVICECLASSINFOW info )
6472 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
6474 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6475 return SOCKET_ERROR;
6478 /***********************************************************************
6479 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
6481 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
6483 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
6484 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6485 return SOCKET_ERROR;
6488 /***********************************************************************
6489 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
6491 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
6493 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
6494 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6495 return SOCKET_ERROR;
6498 /***********************************************************************
6499 * WSALookupServiceBeginA (WS2_32.59)
6501 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
6502 DWORD dwControlFlags,
6505 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
6507 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6508 return SOCKET_ERROR;
6511 /***********************************************************************
6512 * WSALookupServiceBeginW (WS2_32.60)
6514 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
6515 DWORD dwControlFlags,
6518 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
6520 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6521 return SOCKET_ERROR;
6524 /***********************************************************************
6525 * WSALookupServiceEnd (WS2_32.61)
6527 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
6529 FIXME("(%p) Stub!\n", lookup );
6533 /***********************************************************************
6534 * WSALookupServiceNextA (WS2_32.62)
6536 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
6538 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
6539 WSASetLastError(WSA_E_NO_MORE);
6540 return SOCKET_ERROR;
6543 /***********************************************************************
6544 * WSALookupServiceNextW (WS2_32.63)
6546 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
6548 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
6549 WSASetLastError(WSA_E_NO_MORE);
6550 return SOCKET_ERROR;
6553 /***********************************************************************
6554 * WSANtohl (WS2_32.64)
6556 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
6558 TRACE( "(0x%04lx 0x%08x %p)\n", s, netlong, lphostlong );
6560 if (!lphostlong) return WSAEFAULT;
6562 *lphostlong = ntohl( netlong );
6566 /***********************************************************************
6567 * WSANtohs (WS2_32.65)
6569 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
6571 TRACE( "(0x%04lx 0x%08x %p)\n", s, netshort, lphostshort );
6573 if (!lphostshort) return WSAEFAULT;
6575 *lphostshort = ntohs( netshort );
6579 /***********************************************************************
6580 * WSAProviderConfigChange (WS2_32.66)
6582 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
6583 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
6585 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
6586 return SOCKET_ERROR;
6589 /***********************************************************************
6590 * WSARecvDisconnect (WS2_32.68)
6592 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
6594 TRACE( "(0x%04lx %p)\n", s, disconnectdata );
6596 return WS_shutdown( s, 0 );
6599 /***********************************************************************
6600 * WSASetServiceA (WS2_32.76)
6602 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
6604 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
6608 /***********************************************************************
6609 * WSASetServiceW (WS2_32.77)
6611 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
6613 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
6617 /***********************************************************************
6618 * WSCEnableNSProvider (WS2_32.84)
6620 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
6622 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
6626 /***********************************************************************
6627 * WSCGetProviderPath (WS2_32.86)
6629 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
6631 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
6633 if (!errcode || !provider || !len) return WSAEFAULT;
6635 *errcode = WSAEINVAL;
6636 return SOCKET_ERROR;
6639 /***********************************************************************
6640 * WSCInstallNameSpace (WS2_32.87)
6642 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
6643 DWORD version, LPGUID provider )
6645 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
6646 namespace, version, debugstr_guid(provider) );
6650 /***********************************************************************
6651 * WSCUnInstallNameSpace (WS2_32.89)
6653 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
6655 FIXME("(%p) Stub!\n", lpProviderId);
6659 /***********************************************************************
6660 * WSCWriteProviderOrder (WS2_32.91)
6662 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
6664 FIXME("(%p 0x%08x) Stub!\n", entry, number);
6668 /***********************************************************************
6669 * WSANSPIoctl (WS2_32.91)
6671 INT WINAPI WSANSPIoctl( HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer,
6672 DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer,
6673 LPDWORD lpcbBytesReturned, LPWSACOMPLETION lpCompletion )
6675 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup, dwControlCode,
6676 lpvInBuffer, cbInBuffer, lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpCompletion);
6677 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6678 return SOCKET_ERROR;