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>
79 #ifdef HAVE_SYS_ERRNO_H
80 #include <sys/errno.h>
89 #ifdef HAVE_ARPA_NAMESER_H
90 # include <arpa/nameser.h>
99 #ifdef HAVE_NETIPX_IPX_H
100 # include <netipx/ipx.h>
102 #elif defined(HAVE_LINUX_IPX_H)
103 # ifdef HAVE_ASM_TYPES_H
104 # include <asm/types.h>
106 # ifdef HAVE_LINUX_TYPES_H
107 # include <linux/types.h>
109 # include <linux/ipx.h>
113 #ifdef HAVE_LINUX_IRDA_H
114 # ifdef HAVE_LINUX_TYPES_H
115 # include <linux/types.h>
117 # include <linux/irda.h>
124 #ifdef HAVE_SYS_POLL_H
125 # include <sys/poll.h>
127 #ifdef HAVE_SYS_TIME_H
128 # include <sys/time.h>
131 #define NONAMELESSUNION
132 #define NONAMELESSSTRUCT
133 #include "ntstatus.h"
134 #define WIN32_NO_STATUS
139 #include "winerror.h"
141 #include "winsock2.h"
143 #include "ws2tcpip.h"
149 #include "iphlpapi.h"
150 #include "wine/server.h"
151 #include "wine/debug.h"
152 #include "wine/exception.h"
153 #include "wine/unicode.h"
156 # include "wsnwlink.h"
160 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
161 # define sipx_network sipx_addr.x_net
162 # define sipx_node sipx_addr.x_host.c_host
163 #endif /* __FreeBSD__ */
166 #define INADDR_NONE ~0UL
169 WINE_DEFAULT_DEBUG_CHANNEL(winsock);
170 WINE_DECLARE_DEBUG_CHANNEL(winediag);
174 * The actual definition of WSASendTo, wrapped in a different function name
175 * so that internal calls from ws2_32 itself will not trigger programs like
176 * Garena, which hooks WSASendTo/WSARecvFrom calls.
178 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
179 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
180 const struct WS_sockaddr *to, int tolen,
181 LPWSAOVERLAPPED lpOverlapped,
182 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine );
185 * Internal fundamental receive function, essentially WSARecvFrom with an
186 * additional parameter to support message control headers.
188 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
189 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
190 struct WS_sockaddr *lpFrom,
191 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
192 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
193 LPWSABUF lpControlBuffer );
195 /* critical section to protect some non-reentrant net function */
196 static CRITICAL_SECTION csWSgetXXXbyYYY;
197 static CRITICAL_SECTION_DEBUG critsect_debug =
199 0, 0, &csWSgetXXXbyYYY,
200 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
201 0, 0, { (DWORD_PTR)(__FILE__ ": csWSgetXXXbyYYY") }
203 static CRITICAL_SECTION csWSgetXXXbyYYY = { &critsect_debug, -1, 0, 0, 0, 0 };
205 union generic_unix_sockaddr
207 struct sockaddr addr;
208 char data[128]; /* should be big enough for all families */
211 static inline const char *debugstr_sockaddr( const struct WS_sockaddr *a )
213 if (!a) return "(nil)";
214 switch (a->sa_family)
217 return wine_dbg_sprintf("{ family AF_INET, address %s, port %d }",
218 inet_ntoa(((const struct sockaddr_in *)a)->sin_addr),
219 ntohs(((const struct sockaddr_in *)a)->sin_port));
224 struct WS_sockaddr_in6 *sin = (struct WS_sockaddr_in6 *)a;
226 p = WS_inet_ntop( WS_AF_INET6, &sin->sin6_addr, buf, sizeof(buf) );
228 p = "(unknown IPv6 address)";
229 return wine_dbg_sprintf("{ family AF_INET6, address %s, port %d }",
230 p, ntohs(sin->sin6_port));
236 memcpy( &addr, ((const SOCKADDR_IRDA *)a)->irdaDeviceID, sizeof(addr) );
237 addr = ntohl( addr );
238 return wine_dbg_sprintf("{ family AF_IRDA, addr %08x, name %s }",
240 ((const SOCKADDR_IRDA *)a)->irdaServiceName);
243 return wine_dbg_sprintf("{ family %d }", a->sa_family);
247 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
248 #define SOCKET2HANDLE(s) ((HANDLE)(s))
249 #define HANDLE2SOCKET(h) ((SOCKET)(h))
251 /****************************************************************
252 * Async IO declarations
253 ****************************************************************/
255 typedef struct ws2_async
259 LPWSAOVERLAPPED user_overlapped;
260 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
261 IO_STATUS_BLOCK local_iosb;
262 struct WS_sockaddr *addr;
265 int val; /* for send operations */
266 int *ptr; /* for recv operations */
271 unsigned int n_iovecs;
272 unsigned int first_iovec;
273 struct iovec iovec[1];
276 typedef struct ws2_accept_async
278 HANDLE listen_socket;
279 HANDLE accept_socket;
280 LPOVERLAPPED user_overlapped;
282 PVOID buf; /* buffer to write data to */
286 struct ws2_async *read;
289 /****************************************************************/
291 /* ----------------------------------- internal data */
293 /* ws_... struct conversion flags */
295 typedef struct /* WSAAsyncSelect() control struct */
297 HANDLE service, event, sock;
303 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
304 #define WS_MAX_UDP_DATAGRAM 1024
305 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
307 /* hostent's, servent's and protent's are stored in one buffer per thread,
308 * as documented on MSDN for the functions that return any of the buffers */
309 struct per_thread_data
312 struct WS_hostent *he_buffer;
313 struct WS_servent *se_buffer;
314 struct WS_protoent *pe_buffer;
320 /* internal: routing description information */
327 static INT num_startup; /* reference counter */
328 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
330 /* function prototypes */
331 static struct WS_hostent *WS_create_he(char *name, int aliases, int addresses, int fill_addresses);
332 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
333 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
334 static struct WS_servent *WS_dup_se(const struct servent* p_se);
336 int WSAIOCTL_GetInterfaceCount(void);
337 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
339 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus, ULONG Information );
341 #define MAP_OPTION(opt) { WS_##opt, opt }
343 static const int ws_sock_map[][2] =
345 MAP_OPTION( SO_DEBUG ),
346 MAP_OPTION( SO_ACCEPTCONN ),
347 MAP_OPTION( SO_REUSEADDR ),
348 MAP_OPTION( SO_KEEPALIVE ),
349 MAP_OPTION( SO_DONTROUTE ),
350 MAP_OPTION( SO_BROADCAST ),
351 MAP_OPTION( SO_LINGER ),
352 MAP_OPTION( SO_OOBINLINE ),
353 MAP_OPTION( SO_SNDBUF ),
354 MAP_OPTION( SO_RCVBUF ),
355 MAP_OPTION( SO_ERROR ),
356 MAP_OPTION( SO_TYPE ),
358 MAP_OPTION( SO_RCVTIMEO ),
361 MAP_OPTION( SO_SNDTIMEO ),
365 static const int ws_tcp_map[][2] =
368 MAP_OPTION( TCP_NODELAY ),
372 static const int ws_ip_map[][2] =
374 MAP_OPTION( IP_MULTICAST_IF ),
375 MAP_OPTION( IP_MULTICAST_TTL ),
376 MAP_OPTION( IP_MULTICAST_LOOP ),
377 MAP_OPTION( IP_ADD_MEMBERSHIP ),
378 MAP_OPTION( IP_DROP_MEMBERSHIP ),
379 MAP_OPTION( IP_OPTIONS ),
381 MAP_OPTION( IP_HDRINCL ),
383 MAP_OPTION( IP_TOS ),
384 MAP_OPTION( IP_TTL ),
386 MAP_OPTION( IP_PKTINFO ),
390 static const int ws_ipv6_map[][2] =
392 #ifdef IPV6_ADD_MEMBERSHIP
393 MAP_OPTION( IPV6_ADD_MEMBERSHIP ),
395 #ifdef IPV6_DROP_MEMBERSHIP
396 MAP_OPTION( IPV6_DROP_MEMBERSHIP ),
398 MAP_OPTION( IPV6_MULTICAST_IF ),
399 MAP_OPTION( IPV6_MULTICAST_HOPS ),
400 MAP_OPTION( IPV6_MULTICAST_LOOP ),
401 MAP_OPTION( IPV6_UNICAST_HOPS ),
402 MAP_OPTION( IPV6_V6ONLY ),
405 static const int ws_af_map[][2] =
407 MAP_OPTION( AF_UNSPEC ),
408 MAP_OPTION( AF_INET ),
409 MAP_OPTION( AF_INET6 ),
411 MAP_OPTION( AF_IPX ),
414 MAP_OPTION( AF_IRDA ),
416 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
419 static const int ws_socktype_map[][2] =
421 MAP_OPTION( SOCK_DGRAM ),
422 MAP_OPTION( SOCK_STREAM ),
423 MAP_OPTION( SOCK_RAW ),
424 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
427 static const int ws_proto_map[][2] =
429 MAP_OPTION( IPPROTO_IP ),
430 MAP_OPTION( IPPROTO_TCP ),
431 MAP_OPTION( IPPROTO_UDP ),
432 MAP_OPTION( IPPROTO_ICMP ),
433 MAP_OPTION( IPPROTO_IGMP ),
434 MAP_OPTION( IPPROTO_RAW ),
435 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
438 static const int ws_aiflag_map[][2] =
440 MAP_OPTION( AI_PASSIVE ),
441 MAP_OPTION( AI_CANONNAME ),
442 MAP_OPTION( AI_NUMERICHOST ),
443 MAP_OPTION( AI_ADDRCONFIG ),
446 static const int ws_niflag_map[][2] =
448 MAP_OPTION( NI_NOFQDN ),
449 MAP_OPTION( NI_NUMERICHOST ),
450 MAP_OPTION( NI_NAMEREQD ),
451 MAP_OPTION( NI_NUMERICSERV ),
452 MAP_OPTION( NI_DGRAM ),
455 static const int ws_eai_map[][2] =
457 MAP_OPTION( EAI_AGAIN ),
458 MAP_OPTION( EAI_BADFLAGS ),
459 MAP_OPTION( EAI_FAIL ),
460 MAP_OPTION( EAI_FAMILY ),
461 MAP_OPTION( EAI_MEMORY ),
462 /* Note: EAI_NODATA is deprecated, but still
463 * used by Windows and Linux... We map the newer
464 * EAI_NONAME to EAI_NODATA for now until Windows
468 MAP_OPTION( EAI_NODATA ),
471 { WS_EAI_NODATA, EAI_NONAME },
474 MAP_OPTION( EAI_SERVICE ),
475 MAP_OPTION( EAI_SOCKTYPE ),
479 static const char magic_loopback_addr[] = {127, 12, 34, 56};
481 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
482 static inline WSACMSGHDR *fill_control_message(int level, int type, WSACMSGHDR *current, ULONG *maxsize, void *data, int len)
484 ULONG msgsize = sizeof(WSACMSGHDR) + WSA_CMSG_ALIGN(len);
485 char *ptr = (char *) current + sizeof(WSACMSGHDR);
487 /* Make sure there is at least enough room for this entry */
488 if (msgsize > *maxsize)
491 /* Fill in the entry */
492 current->cmsg_len = sizeof(WSACMSGHDR) + len;
493 current->cmsg_level = level;
494 current->cmsg_type = type;
495 memcpy(ptr, data, len);
496 /* Return the pointer to where next entry should go */
497 return (WSACMSGHDR *) (ptr + WSA_CMSG_ALIGN(len));
500 static inline int convert_control_headers(struct msghdr *hdr, WSABUF *control)
503 WSACMSGHDR *cmsg_win = (WSACMSGHDR *) control->buf, *ptr;
504 ULONG ctlsize = control->len;
505 struct cmsghdr *cmsg_unix;
508 /* Loop over all the headers, converting as appropriate */
509 for (cmsg_unix = CMSG_FIRSTHDR(hdr); cmsg_unix != NULL; cmsg_unix = CMSG_NXTHDR(hdr, cmsg_unix))
511 switch(cmsg_unix->cmsg_level)
514 switch(cmsg_unix->cmsg_type)
518 /* Convert the Unix IP_PKTINFO structure to the Windows version */
519 struct in_pktinfo *data_unix = (struct in_pktinfo *) CMSG_DATA(cmsg_unix);
520 struct WS_in_pktinfo data_win;
522 memcpy(&data_win.ipi_addr,&data_unix->ipi_addr.s_addr,4); /* 4 bytes = 32 address bits */
523 data_win.ipi_ifindex = data_unix->ipi_ifindex;
524 ptr = fill_control_message(WS_IPPROTO_IP, WS_IP_PKTINFO, ptr, &ctlsize,
525 (void*)&data_win, sizeof(data_win));
526 if (!ptr) goto error;
529 FIXME("Unhandled IPPROTO_IP message header type %d\n", cmsg_unix->cmsg_type);
534 FIXME("Unhandled message header level %d\n", cmsg_unix->cmsg_level);
540 /* Set the length of the returned control headers */
541 control->len = (ptr == NULL ? 0 : (char*)ptr - (char*)cmsg_win);
542 return (ptr != NULL);
543 #else /* IP_PKTINFO */
546 #endif /* IP_PKTINFO */
548 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
550 /* ----------------------------------- error handling */
552 static NTSTATUS sock_get_ntstatus( int err )
556 case EBADF: return STATUS_INVALID_HANDLE;
557 case EBUSY: return STATUS_DEVICE_BUSY;
559 case EACCES: return STATUS_ACCESS_DENIED;
560 case EFAULT: return STATUS_NO_MEMORY;
561 case EINVAL: return STATUS_INVALID_PARAMETER;
563 case EMFILE: return STATUS_TOO_MANY_OPENED_FILES;
564 case EWOULDBLOCK: return STATUS_CANT_WAIT;
565 case EINPROGRESS: return STATUS_PENDING;
566 case EALREADY: return STATUS_NETWORK_BUSY;
567 case ENOTSOCK: return STATUS_OBJECT_TYPE_MISMATCH;
568 case EDESTADDRREQ: return STATUS_INVALID_PARAMETER;
569 case EMSGSIZE: return STATUS_BUFFER_OVERFLOW;
570 case EPROTONOSUPPORT:
571 case ESOCKTNOSUPPORT:
574 case EPROTOTYPE: return STATUS_NOT_SUPPORTED;
575 case ENOPROTOOPT: return STATUS_INVALID_PARAMETER;
576 case EOPNOTSUPP: return STATUS_NOT_SUPPORTED;
577 case EADDRINUSE: return STATUS_ADDRESS_ALREADY_ASSOCIATED;
578 case EADDRNOTAVAIL: return STATUS_INVALID_PARAMETER;
579 case ECONNREFUSED: return STATUS_CONNECTION_REFUSED;
580 case ESHUTDOWN: return STATUS_PIPE_DISCONNECTED;
581 case ENOTCONN: return STATUS_CONNECTION_DISCONNECTED;
582 case ETIMEDOUT: return STATUS_IO_TIMEOUT;
583 case ENETUNREACH: return STATUS_NETWORK_UNREACHABLE;
584 case ENETDOWN: return STATUS_NETWORK_BUSY;
586 case ECONNRESET: return STATUS_CONNECTION_RESET;
587 case ECONNABORTED: return STATUS_CONNECTION_ABORTED;
589 case 0: return STATUS_SUCCESS;
591 WARN("Unknown errno %d!\n", err);
592 return STATUS_UNSUCCESSFUL;
596 static UINT sock_get_error( int err )
600 case EINTR: return WSAEINTR;
601 case EBADF: return WSAEBADF;
603 case EACCES: return WSAEACCES;
604 case EFAULT: return WSAEFAULT;
605 case EINVAL: return WSAEINVAL;
606 case EMFILE: return WSAEMFILE;
607 case EWOULDBLOCK: return WSAEWOULDBLOCK;
608 case EINPROGRESS: return WSAEINPROGRESS;
609 case EALREADY: return WSAEALREADY;
610 case ENOTSOCK: return WSAENOTSOCK;
611 case EDESTADDRREQ: return WSAEDESTADDRREQ;
612 case EMSGSIZE: return WSAEMSGSIZE;
613 case EPROTOTYPE: return WSAEPROTOTYPE;
614 case ENOPROTOOPT: return WSAENOPROTOOPT;
615 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
616 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
617 case EOPNOTSUPP: return WSAEOPNOTSUPP;
618 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
619 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
620 case EADDRINUSE: return WSAEADDRINUSE;
621 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
622 case ENETDOWN: return WSAENETDOWN;
623 case ENETUNREACH: return WSAENETUNREACH;
624 case ENETRESET: return WSAENETRESET;
625 case ECONNABORTED: return WSAECONNABORTED;
627 case ECONNRESET: return WSAECONNRESET;
628 case ENOBUFS: return WSAENOBUFS;
629 case EISCONN: return WSAEISCONN;
630 case ENOTCONN: return WSAENOTCONN;
631 case ESHUTDOWN: return WSAESHUTDOWN;
632 case ETOOMANYREFS: return WSAETOOMANYREFS;
633 case ETIMEDOUT: return WSAETIMEDOUT;
634 case ECONNREFUSED: return WSAECONNREFUSED;
635 case ELOOP: return WSAELOOP;
636 case ENAMETOOLONG: return WSAENAMETOOLONG;
637 case EHOSTDOWN: return WSAEHOSTDOWN;
638 case EHOSTUNREACH: return WSAEHOSTUNREACH;
639 case ENOTEMPTY: return WSAENOTEMPTY;
641 case EPROCLIM: return WSAEPROCLIM;
644 case EUSERS: return WSAEUSERS;
647 case EDQUOT: return WSAEDQUOT;
650 case ESTALE: return WSAESTALE;
653 case EREMOTE: return WSAEREMOTE;
656 /* just in case we ever get here and there are no problems */
659 WARN("Unknown errno %d!\n", err);
660 return WSAEOPNOTSUPP;
664 static UINT wsaErrno(void)
666 int loc_errno = errno;
667 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
669 return sock_get_error( loc_errno );
672 /* most ws2 overlapped functions return an ntstatus-based error code */
673 static NTSTATUS wsaErrStatus(void)
675 int loc_errno = errno;
676 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
678 return sock_get_ntstatus(loc_errno);
681 static UINT wsaHerrno(int loc_errno)
683 WARN("h_errno %d.\n", loc_errno);
687 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
688 case TRY_AGAIN: return WSATRY_AGAIN;
689 case NO_RECOVERY: return WSANO_RECOVERY;
690 case NO_DATA: return WSANO_DATA;
691 case ENOBUFS: return WSAENOBUFS;
695 WARN("Unknown h_errno %d!\n", loc_errno);
696 return WSAEOPNOTSUPP;
700 static inline DWORD NtStatusToWSAError( const DWORD status )
702 /* We only need to cover the status codes set by server async request handling */
706 case STATUS_SUCCESS: wserr = 0; break;
707 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
708 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
709 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
710 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
711 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
712 case STATUS_NETWORK_BUSY: wserr = WSAEALREADY; break;
713 case STATUS_NETWORK_UNREACHABLE: wserr = WSAENETUNREACH; break;
714 case STATUS_CONNECTION_REFUSED: wserr = WSAECONNREFUSED; break;
715 case STATUS_CONNECTION_DISCONNECTED: wserr = WSAENOTCONN; break;
716 case STATUS_CONNECTION_RESET: wserr = WSAECONNRESET; break;
717 case STATUS_CONNECTION_ABORTED: wserr = WSAECONNABORTED; break;
718 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
719 case STATUS_ADDRESS_ALREADY_ASSOCIATED: wserr = WSAEADDRINUSE; break;
720 case STATUS_IO_TIMEOUT:
721 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
722 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
723 case STATUS_ACCESS_DENIED: wserr = WSAEACCES; break;
724 case STATUS_TOO_MANY_OPENED_FILES: wserr = WSAEMFILE; break;
725 case STATUS_CANT_WAIT: wserr = WSAEWOULDBLOCK; break;
726 case STATUS_BUFFER_OVERFLOW: wserr = WSAEMSGSIZE; break;
727 case STATUS_NOT_SUPPORTED: wserr = WSAEOPNOTSUPP; break;
728 case STATUS_HOST_UNREACHABLE: wserr = WSAEHOSTUNREACH; break;
731 wserr = RtlNtStatusToDosError( status );
732 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
737 /* set last error code from NT status without mapping WSA errors */
738 static inline unsigned int set_error( unsigned int err )
742 err = NtStatusToWSAError( err );
748 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
751 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
756 static inline void release_sock_fd( SOCKET s, int fd )
758 wine_server_release_fd( SOCKET2HANDLE(s), fd );
761 static void _enable_event( HANDLE s, unsigned int event,
762 unsigned int sstate, unsigned int cstate )
764 SERVER_START_REQ( enable_socket_event )
766 req->handle = wine_server_obj_handle( s );
768 req->sstate = sstate;
769 req->cstate = cstate;
770 wine_server_call( req );
775 static int _is_blocking(SOCKET s)
778 SERVER_START_REQ( get_socket_event )
780 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
781 req->service = FALSE;
783 wine_server_call( req );
784 ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
790 static unsigned int _get_sock_mask(SOCKET s)
793 SERVER_START_REQ( get_socket_event )
795 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
796 req->service = FALSE;
798 wine_server_call( req );
805 static void _sync_sock_state(SOCKET s)
807 /* do a dummy wineserver request in order to let
808 the wineserver run through its select loop once */
809 (void)_is_blocking(s);
812 static int _get_sock_error(SOCKET s, unsigned int bit)
814 int events[FD_MAX_EVENTS];
816 SERVER_START_REQ( get_socket_event )
818 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
819 req->service = FALSE;
821 wine_server_set_reply( req, events, sizeof(events) );
822 wine_server_call( req );
828 static struct per_thread_data *get_per_thread_data(void)
830 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
831 /* lazy initialization */
834 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
835 NtCurrentTeb()->WinSockData = ptb;
840 static void free_per_thread_data(void)
842 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
846 /* delete scratch buffers */
847 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
848 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
849 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
850 ptb->he_buffer = NULL;
851 ptb->se_buffer = NULL;
852 ptb->pe_buffer = NULL;
854 HeapFree( GetProcessHeap(), 0, ptb );
855 NtCurrentTeb()->WinSockData = NULL;
858 /***********************************************************************
859 * DllMain (WS2_32.init)
861 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
863 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
865 case DLL_PROCESS_ATTACH:
867 case DLL_PROCESS_DETACH:
868 free_per_thread_data();
871 case DLL_THREAD_DETACH:
872 free_per_thread_data();
878 /***********************************************************************
881 * Converts socket flags from Windows format.
882 * Return 1 if converted, 0 if not (error).
884 static int convert_sockopt(INT *level, INT *optname)
891 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
892 if( ws_sock_map[i][0] == *optname )
894 *optname = ws_sock_map[i][1];
898 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
901 *level = IPPROTO_TCP;
902 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
903 if ( ws_tcp_map[i][0] == *optname )
905 *optname = ws_tcp_map[i][1];
909 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
913 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
914 if (ws_ip_map[i][0] == *optname )
916 *optname = ws_ip_map[i][1];
920 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
922 case WS_IPPROTO_IPV6:
923 *level = IPPROTO_IPV6;
924 for(i=0; i<sizeof(ws_ipv6_map)/sizeof(ws_ipv6_map[0]); i++) {
925 if (ws_ipv6_map[i][0] == *optname )
927 *optname = ws_ipv6_map[i][1];
931 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname);
933 default: FIXME("Unimplemented or unknown socket level\n");
938 /* ----------------------------------- Per-thread info (or per-process?) */
940 static char *strdup_lower(const char *str)
943 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
947 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
950 else SetLastError(WSAENOBUFS);
954 static inline int sock_error_p(int s)
956 unsigned int optval, optlen;
958 optlen = sizeof(optval);
959 getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
960 if (optval) WARN("\t[%i] error: %d\n", s, optval);
964 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
965 * from an fd and return the value converted to milli seconds
966 * or -1 if there is an infinite time out */
967 static inline int get_rcvsnd_timeo( int fd, int optname)
970 unsigned int len = sizeof(tv);
971 int ret = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
973 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
974 if( ret <= 0 ) /* tv == {0,0} means infinite time out */
979 /* macro wrappers for portability */
981 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
983 #define GET_RCVTIMEO(fd) (-1)
987 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
989 #define GET_SNDTIMEO(fd) (-1)
992 /* utility: given an fd, will block until one of the events occurs */
993 static inline int do_block( int fd, int events, int timeout )
1001 while ((ret = poll(&pfd, 1, timeout)) < 0)
1012 convert_af_w2u(int windowsaf) {
1015 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1016 if (ws_af_map[i][0] == windowsaf)
1017 return ws_af_map[i][1];
1018 FIXME("unhandled Windows address family %d\n", windowsaf);
1023 convert_af_u2w(int unixaf) {
1026 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1027 if (ws_af_map[i][1] == unixaf)
1028 return ws_af_map[i][0];
1029 FIXME("unhandled UNIX address family %d\n", unixaf);
1034 convert_proto_w2u(int windowsproto) {
1037 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1038 if (ws_proto_map[i][0] == windowsproto)
1039 return ws_proto_map[i][1];
1040 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
1045 convert_proto_u2w(int unixproto) {
1048 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1049 if (ws_proto_map[i][1] == unixproto)
1050 return ws_proto_map[i][0];
1051 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
1056 convert_socktype_w2u(int windowssocktype) {
1059 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1060 if (ws_socktype_map[i][0] == windowssocktype)
1061 return ws_socktype_map[i][1];
1062 FIXME("unhandled Windows socket type %d\n", windowssocktype);
1067 convert_socktype_u2w(int unixsocktype) {
1070 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1071 if (ws_socktype_map[i][1] == unixsocktype)
1072 return ws_socktype_map[i][0];
1073 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
1077 /* ----------------------------------- API -----
1079 * Init / cleanup / error checking.
1082 /***********************************************************************
1083 * WSAStartup (WS2_32.115)
1085 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
1087 TRACE("verReq=%x\n", wVersionRequested);
1089 if (LOBYTE(wVersionRequested) < 1)
1090 return WSAVERNOTSUPPORTED;
1092 if (!lpWSAData) return WSAEINVAL;
1096 /* that's the whole of the negotiation for now */
1097 lpWSAData->wVersion = wVersionRequested;
1098 /* return winsock information */
1099 lpWSAData->wHighVersion = 0x0202;
1100 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
1101 strcpy(lpWSAData->szSystemStatus, "Running" );
1102 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
1103 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
1104 /* don't do anything with lpWSAData->lpVendorInfo */
1105 /* (some apps don't allocate the space for this field) */
1107 TRACE("succeeded\n");
1112 /***********************************************************************
1113 * WSACleanup (WS2_32.116)
1115 INT WINAPI WSACleanup(void)
1121 SetLastError(WSANOTINITIALISED);
1122 return SOCKET_ERROR;
1126 /***********************************************************************
1127 * WSAGetLastError (WS2_32.111)
1129 INT WINAPI WSAGetLastError(void)
1131 return GetLastError();
1134 /***********************************************************************
1135 * WSASetLastError (WS2_32.112)
1137 void WINAPI WSASetLastError(INT iError) {
1138 SetLastError(iError);
1141 static struct WS_hostent *check_buffer_he(int size)
1143 struct per_thread_data * ptb = get_per_thread_data();
1146 if (ptb->he_len >= size ) return ptb->he_buffer;
1147 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1149 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
1150 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
1151 return ptb->he_buffer;
1154 static struct WS_servent *check_buffer_se(int size)
1156 struct per_thread_data * ptb = get_per_thread_data();
1159 if (ptb->se_len >= size ) return ptb->se_buffer;
1160 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1162 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
1163 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
1164 return ptb->se_buffer;
1167 static struct WS_protoent *check_buffer_pe(int size)
1169 struct per_thread_data * ptb = get_per_thread_data();
1172 if (ptb->pe_len >= size ) return ptb->pe_buffer;
1173 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1175 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
1176 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
1177 return ptb->pe_buffer;
1180 /* ----------------------------------- i/o APIs */
1182 static inline BOOL supported_pf(int pf)
1203 /**********************************************************************/
1205 /* Returns the length of the converted address if successful, 0 if it was too small to
1208 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
1209 union generic_unix_sockaddr *uaddr)
1211 unsigned int uaddrlen = 0;
1213 switch (wsaddr->sa_family)
1218 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
1219 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
1221 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
1224 uaddrlen = sizeof(struct sockaddr_ipx);
1225 memset( uaddr, 0, uaddrlen );
1226 uipx->sipx_family=AF_IPX;
1227 uipx->sipx_port=wsipx->sa_socket;
1228 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1231 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
1232 #ifdef IPX_FRAME_NONE
1233 uipx->sipx_type=IPX_FRAME_NONE;
1239 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
1240 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
1242 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1243 * scope_id, one without.
1245 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
1246 uaddrlen = sizeof(struct sockaddr_in6);
1247 memset( uaddr, 0, uaddrlen );
1248 uin6->sin6_family = AF_INET6;
1249 uin6->sin6_port = win6->sin6_port;
1250 uin6->sin6_flowinfo = win6->sin6_flowinfo;
1251 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1252 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
1254 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
1257 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
1261 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
1262 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
1264 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
1266 uaddrlen = sizeof(struct sockaddr_in);
1267 memset( uaddr, 0, uaddrlen );
1268 uin->sin_family = AF_INET;
1269 uin->sin_port = win->sin_port;
1270 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
1275 struct sockaddr_irda *uin = (struct sockaddr_irda *)uaddr;
1276 const SOCKADDR_IRDA *win = (const SOCKADDR_IRDA *)wsaddr;
1278 if (wsaddrlen < sizeof(SOCKADDR_IRDA))
1280 uaddrlen = sizeof(struct sockaddr_irda);
1281 memset( uaddr, 0, uaddrlen );
1282 uin->sir_family = AF_IRDA;
1283 if (!strncmp( win->irdaServiceName, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1285 unsigned int lsap_sel = 0;
1287 sscanf( win->irdaServiceName, "LSAP-SEL%u", &lsap_sel );
1288 uin->sir_lsap_sel = lsap_sel;
1292 uin->sir_lsap_sel = LSAP_ANY;
1293 memcpy( uin->sir_name, win->irdaServiceName, 25 );
1295 memcpy( &uin->sir_addr, win->irdaDeviceID, sizeof(uin->sir_addr) );
1299 case WS_AF_UNSPEC: {
1300 /* Try to determine the needed space by the passed windows sockaddr space */
1301 switch (wsaddrlen) {
1302 default: /* likely a ipv4 address */
1303 case sizeof(struct WS_sockaddr_in):
1304 uaddrlen = sizeof(struct sockaddr_in);
1307 case sizeof(struct WS_sockaddr_ipx):
1308 uaddrlen = sizeof(struct sockaddr_ipx);
1312 case sizeof(SOCKADDR_IRDA):
1313 uaddrlen = sizeof(struct sockaddr_irda);
1316 case sizeof(struct WS_sockaddr_in6):
1317 case sizeof(struct WS_sockaddr_in6_old):
1318 uaddrlen = sizeof(struct sockaddr_in6);
1321 memset( uaddr, 0, uaddrlen );
1325 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
1331 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
1333 switch (uaddr->sa_family)
1337 FIXME("don't know how to tell if IPX socket is bound, assuming it is!\n");
1342 static const struct sockaddr_in6 emptyAddr;
1343 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
1344 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
1348 static const struct sockaddr_in emptyAddr;
1349 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
1350 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
1355 FIXME("unknown address family %d\n", uaddr->sa_family);
1360 /* Returns 0 if successful, -1 if the buffer is too small */
1361 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
1365 switch(uaddr->sa_family)
1370 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
1371 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
1374 switch (*wsaddrlen) /* how much can we copy? */
1378 *wsaddrlen = sizeof(*wsipx);
1379 wsipx->sa_socket=uipx->sipx_port;
1383 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
1391 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1397 wsipx->sa_family=WS_AF_IPX;
1409 const struct sockaddr_irda *uin = (const struct sockaddr_irda *)uaddr;
1410 SOCKADDR_IRDA *win = (SOCKADDR_IRDA *)wsaddr;
1412 if (*wsaddrlen < sizeof(SOCKADDR_IRDA))
1414 win->irdaAddressFamily = WS_AF_IRDA;
1415 memcpy( win->irdaDeviceID, &uin->sir_addr, sizeof(win->irdaDeviceID) );
1416 if (uin->sir_lsap_sel != LSAP_ANY)
1417 sprintf( win->irdaServiceName, "LSAP-SEL%u", uin->sir_lsap_sel );
1419 memcpy( win->irdaServiceName, uin->sir_name,
1420 sizeof(win->irdaServiceName) );
1425 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1426 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1428 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1430 win6old->sin6_family = WS_AF_INET6;
1431 win6old->sin6_port = uin6->sin6_port;
1432 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1433 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1434 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1435 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1436 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1437 win6->sin6_scope_id = uin6->sin6_scope_id;
1438 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1441 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1443 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1448 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1449 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1451 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1453 win->sin_family = WS_AF_INET;
1454 win->sin_port = uin->sin_port;
1455 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1456 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1457 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1461 memset(wsaddr,0,*wsaddrlen);
1465 FIXME("Unknown address family %d\n", uaddr->sa_family);
1471 /**************************************************************************
1472 * Functions for handling overlapped I/O
1473 **************************************************************************/
1475 /* user APC called upon async completion */
1476 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1478 ws2_async *wsa = arg;
1480 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
1481 iosb->Information, wsa->user_overlapped,
1483 HeapFree( GetProcessHeap(), 0, wsa );
1486 /***********************************************************************
1487 * WS2_recv (INTERNAL)
1489 * Workhorse for both synchronous and asynchronous recv() operations.
1491 static int WS2_recv( int fd, struct ws2_async *wsa )
1493 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1497 union generic_unix_sockaddr unix_sockaddr;
1500 hdr.msg_name = NULL;
1504 hdr.msg_namelen = sizeof(unix_sockaddr);
1505 hdr.msg_name = &unix_sockaddr;
1508 hdr.msg_namelen = 0;
1510 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1511 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1512 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1513 hdr.msg_accrights = NULL;
1514 hdr.msg_accrightslen = 0;
1516 hdr.msg_control = pktbuf;
1517 hdr.msg_controllen = sizeof(pktbuf);
1521 if ( (n = recvmsg(fd, &hdr, wsa->flags)) == -1 )
1524 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1527 ERR("Message control headers cannot be properly supported on this system.\n");
1528 wsa->control->len = 0;
1531 if (wsa->control && !convert_control_headers(&hdr, wsa->control))
1533 WARN("Application passed insufficient room for control headers.\n");
1534 *wsa->lpFlags |= WS_MSG_CTRUNC;
1540 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
1541 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
1543 * quoting linux 2.6 net/ipv4/tcp.c:
1544 * "According to UNIX98, msg_name/msg_namelen are ignored
1545 * on connected socket. I was just happy when found this 8) --ANK"
1547 * likewise MSDN says that lpFrom and lpFromlen are ignored for
1548 * connection-oriented sockets, so don't try to update lpFrom.
1550 if (wsa->addr && hdr.msg_namelen)
1551 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
1556 /***********************************************************************
1557 * WS2_async_recv (INTERNAL)
1559 * Handler for overlapped recv() operations.
1561 static NTSTATUS WS2_async_recv( void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1563 ws2_async* wsa = user;
1568 case STATUS_ALERTED:
1569 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
1572 result = WS2_recv( fd, wsa );
1573 wine_server_release_fd( wsa->hSocket, fd );
1576 status = STATUS_SUCCESS;
1577 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1581 if (errno == EINTR || errno == EAGAIN)
1583 status = STATUS_PENDING;
1584 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1589 status = wsaErrStatus();
1594 if (status != STATUS_PENDING)
1596 iosb->u.Status = status;
1597 iosb->Information = result;
1598 *apc = ws2_async_apc;
1603 /* user APC called upon async accept completion */
1604 static void WINAPI ws2_async_accept_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1606 struct ws2_accept_async *wsa = arg;
1608 HeapFree( GetProcessHeap(), 0, wsa->read );
1609 HeapFree( GetProcessHeap(), 0, wsa );
1612 /***********************************************************************
1613 * WS2_async_accept_recv (INTERNAL)
1615 * This function is used to finish the read part of an accept request. It is
1616 * needed to place the completion on the correct socket (listener).
1618 static NTSTATUS WS2_async_accept_recv( void *arg, IO_STATUS_BLOCK *iosb, NTSTATUS status, void **apc )
1621 struct ws2_accept_async *wsa = arg;
1623 status = WS2_async_recv( wsa->read, iosb, status, &junk );
1624 if (status == STATUS_PENDING)
1627 if (wsa->user_overlapped->hEvent)
1628 SetEvent(wsa->user_overlapped->hEvent);
1630 WS_AddCompletion( HANDLE2SOCKET(wsa->listen_socket), wsa->cvalue, iosb->u.Status, iosb->Information );
1632 *apc = ws2_async_accept_apc;
1636 /***********************************************************************
1637 * WS2_async_accept (INTERNAL)
1639 * This is the function called to satisfy the AcceptEx callback
1641 static NTSTATUS WS2_async_accept( void *arg, IO_STATUS_BLOCK *iosb, NTSTATUS status, void **apc )
1643 struct ws2_accept_async *wsa = arg;
1647 TRACE("status: 0x%x listen: %p, accept: %p\n", status, wsa->listen_socket, wsa->accept_socket);
1649 if (status == STATUS_ALERTED)
1651 SERVER_START_REQ( accept_into_socket )
1653 req->lhandle = wine_server_obj_handle( wsa->listen_socket );
1654 req->ahandle = wine_server_obj_handle( wsa->accept_socket );
1655 status = wine_server_call( req );
1659 if (status == STATUS_CANT_WAIT)
1660 return STATUS_PENDING;
1662 if (status == STATUS_INVALID_HANDLE)
1664 FIXME("AcceptEx accepting socket closed but request was not cancelled\n");
1665 status = STATUS_CANCELLED;
1668 else if (status == STATUS_HANDLES_CLOSED)
1669 status = STATUS_CANCELLED; /* strange windows behavior */
1671 if (status != STATUS_SUCCESS)
1674 /* WS2 Spec says size param is extra 16 bytes long...what do we put in it? */
1675 addr = ((char *)wsa->buf) + wsa->data_len;
1676 len = wsa->local_len - sizeof(int);
1677 WS_getpeername(HANDLE2SOCKET(wsa->accept_socket),
1678 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
1681 addr += wsa->local_len;
1682 len = wsa->remote_len - sizeof(int);
1683 WS_getsockname(HANDLE2SOCKET(wsa->accept_socket),
1684 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
1690 SERVER_START_REQ( register_async )
1692 req->type = ASYNC_TYPE_READ;
1693 req->async.handle = wine_server_obj_handle( wsa->accept_socket );
1694 req->async.callback = wine_server_client_ptr( WS2_async_accept_recv );
1695 req->async.iosb = wine_server_client_ptr( iosb );
1696 req->async.arg = wine_server_client_ptr( wsa );
1697 status = wine_server_call( req );
1701 if (status != STATUS_PENDING)
1704 return STATUS_SUCCESS;
1707 iosb->u.Status = status;
1708 iosb->Information = 0;
1710 if (wsa->user_overlapped->hEvent)
1711 SetEvent(wsa->user_overlapped->hEvent);
1713 WS_AddCompletion( HANDLE2SOCKET(wsa->listen_socket), wsa->cvalue, iosb->u.Status, iosb->Information );
1715 *apc = ws2_async_accept_apc;
1719 /***********************************************************************
1720 * WS2_send (INTERNAL)
1722 * Workhorse for both synchronous and asynchronous send() operations.
1724 static int WS2_send( int fd, struct ws2_async *wsa )
1727 union generic_unix_sockaddr unix_addr;
1730 hdr.msg_name = NULL;
1731 hdr.msg_namelen = 0;
1735 hdr.msg_name = &unix_addr;
1736 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
1737 if ( !hdr.msg_namelen )
1743 #if defined(HAVE_IPX) && defined(SOL_IPX)
1744 if(wsa->addr->sa_family == WS_AF_IPX)
1746 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
1748 unsigned int len=sizeof(int);
1750 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
1751 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
1752 * the packet type and then we can retrieve it using getsockopt. After that we can set the
1753 * ipx type in the sockaddr_opx structure with the stored value.
1755 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
1756 uipx->sipx_type = val;
1761 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1762 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1763 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1764 hdr.msg_accrights = NULL;
1765 hdr.msg_accrightslen = 0;
1767 hdr.msg_control = NULL;
1768 hdr.msg_controllen = 0;
1772 ret = sendmsg(fd, &hdr, wsa->flags);
1776 while (wsa->first_iovec < wsa->n_iovecs && wsa->iovec[wsa->first_iovec].iov_len <= n)
1777 n -= wsa->iovec[wsa->first_iovec++].iov_len;
1778 if (wsa->first_iovec < wsa->n_iovecs)
1780 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
1781 wsa->iovec[wsa->first_iovec].iov_len -= n;
1787 /***********************************************************************
1788 * WS2_async_send (INTERNAL)
1790 * Handler for overlapped send() operations.
1792 static NTSTATUS WS2_async_send(void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1794 ws2_async* wsa = user;
1799 case STATUS_ALERTED:
1800 if ( wsa->n_iovecs <= wsa->first_iovec )
1803 status = STATUS_SUCCESS;
1806 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
1809 /* check to see if the data is ready (non-blocking) */
1810 result = WS2_send( fd, wsa );
1811 wine_server_release_fd( wsa->hSocket, fd );
1815 if (wsa->first_iovec < wsa->n_iovecs)
1816 status = STATUS_PENDING;
1818 status = STATUS_SUCCESS;
1820 iosb->Information += result;
1822 else if (errno == EINTR || errno == EAGAIN)
1824 status = STATUS_PENDING;
1828 status = wsaErrStatus();
1832 if (status != STATUS_PENDING)
1834 iosb->u.Status = status;
1835 *apc = ws2_async_apc;
1840 /***********************************************************************
1841 * WS2_async_shutdown (INTERNAL)
1843 * Handler for shutdown() operations on overlapped sockets.
1845 static NTSTATUS WS2_async_shutdown( void* user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc )
1847 ws2_async* wsa = user;
1852 case STATUS_ALERTED:
1853 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
1856 switch ( wsa->type )
1858 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
1859 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
1861 status = err ? wsaErrStatus() : STATUS_SUCCESS;
1862 wine_server_release_fd( wsa->hSocket, fd );
1865 iosb->u.Status = status;
1866 iosb->Information = 0;
1867 *apc = ws2_async_apc;
1871 /***********************************************************************
1872 * WS2_register_async_shutdown (INTERNAL)
1874 * Helper function for WS_shutdown() on overlapped sockets.
1876 static int WS2_register_async_shutdown( SOCKET s, int type )
1878 struct ws2_async *wsa;
1881 TRACE("s %ld type %d\n", s, type);
1883 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
1887 wsa->hSocket = SOCKET2HANDLE(s);
1889 wsa->completion_func = NULL;
1891 SERVER_START_REQ( register_async )
1894 req->async.handle = wine_server_obj_handle( wsa->hSocket );
1895 req->async.callback = wine_server_client_ptr( WS2_async_shutdown );
1896 req->async.iosb = wine_server_client_ptr( &wsa->local_iosb );
1897 req->async.arg = wine_server_client_ptr( wsa );
1898 req->async.cvalue = 0;
1899 status = wine_server_call( req );
1903 if (status != STATUS_PENDING)
1905 HeapFree( GetProcessHeap(), 0, wsa );
1906 return NtStatusToWSAError( status );
1911 /***********************************************************************
1914 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr,
1921 TRACE("socket %04lx\n", s );
1922 is_blocking = _is_blocking(s);
1925 /* try accepting first (if there is a deferred connection) */
1926 SERVER_START_REQ( accept_socket )
1928 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1929 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
1930 req->attributes = OBJ_INHERIT;
1931 status = wine_server_call( req );
1932 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
1937 if (addr) WS_getpeername(as, addr, addrlen32);
1940 if (is_blocking && status == STATUS_CANT_WAIT)
1942 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1944 do_block(fd, POLLIN, -1);
1945 _sync_sock_state(s); /* let wineserver notice connection */
1946 release_sock_fd( s, fd );
1948 } while (is_blocking && status == STATUS_CANT_WAIT);
1951 return INVALID_SOCKET;
1954 /***********************************************************************
1957 static BOOL WINAPI WS2_AcceptEx(SOCKET listener, SOCKET acceptor, PVOID dest, DWORD dest_len,
1958 DWORD local_addr_len, DWORD rem_addr_len, LPDWORD received,
1959 LPOVERLAPPED overlapped)
1962 struct ws2_accept_async *wsa;
1964 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
1966 TRACE("(%lx, %lx, %p, %d, %d, %d, %p, %p)\n", listener, acceptor, dest, dest_len, local_addr_len,
1967 rem_addr_len, received, overlapped);
1971 SetLastError(WSAEINVAL);
1977 SetLastError(WSA_INVALID_PARAMETER);
1981 fd = get_sock_fd( listener, FILE_READ_DATA, NULL );
1984 SetLastError(WSAENOTSOCK);
1987 release_sock_fd( listener, fd );
1989 fd = get_sock_fd( acceptor, FILE_READ_DATA, NULL );
1992 SetLastError(WSAEINVAL);
1995 release_sock_fd( acceptor, fd );
1997 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
2000 SetLastError(WSAEFAULT);
2004 wsa->listen_socket = SOCKET2HANDLE(listener);
2005 wsa->accept_socket = SOCKET2HANDLE(acceptor);
2006 wsa->user_overlapped = overlapped;
2007 wsa->cvalue = cvalue;
2009 wsa->data_len = dest_len;
2010 wsa->local_len = local_addr_len;
2011 wsa->remote_len = rem_addr_len;
2016 /* set up a read request if we need it */
2017 wsa->read = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[1]) );
2020 HeapFree( GetProcessHeap(), 0, wsa );
2021 SetLastError(WSAEFAULT);
2025 wsa->read->hSocket = wsa->accept_socket;
2026 wsa->read->flags = 0;
2027 wsa->read->lpFlags = &wsa->read->flags;
2028 wsa->read->addr = NULL;
2029 wsa->read->addrlen.ptr = NULL;
2030 wsa->read->control = NULL;
2031 wsa->read->n_iovecs = 1;
2032 wsa->read->first_iovec = 0;
2033 wsa->read->iovec[0].iov_base = wsa->buf;
2034 wsa->read->iovec[0].iov_len = wsa->data_len;
2037 SERVER_START_REQ( register_async )
2039 req->type = ASYNC_TYPE_READ;
2040 req->async.handle = wine_server_obj_handle( SOCKET2HANDLE(listener) );
2041 req->async.callback = wine_server_client_ptr( WS2_async_accept );
2042 req->async.iosb = wine_server_client_ptr( overlapped );
2043 req->async.arg = wine_server_client_ptr( wsa );
2044 /* We don't set event or completion since we may also have to read */
2045 status = wine_server_call( req );
2049 if(status != STATUS_PENDING)
2051 HeapFree( GetProcessHeap(), 0, wsa->read );
2052 HeapFree( GetProcessHeap(), 0, wsa );
2055 SetLastError( NtStatusToWSAError(status) );
2059 /***********************************************************************
2060 * GetAcceptExSockaddrs
2062 static void WINAPI WS2_GetAcceptExSockaddrs(PVOID buffer, DWORD data_size, DWORD local_size, DWORD remote_size,
2063 struct WS_sockaddr **local_addr, LPINT local_addr_len,
2064 struct WS_sockaddr **remote_addr, LPINT remote_addr_len)
2066 char *cbuf = buffer;
2067 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer, data_size, local_size, remote_size, local_addr,
2068 local_addr_len, remote_addr, remote_addr_len );
2071 *local_addr_len = *(int *) cbuf;
2072 *local_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2076 *remote_addr_len = *(int *) cbuf;
2077 *remote_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2080 /***********************************************************************
2083 * Perform a receive operation that is capable of returning message
2084 * control headers. It is important to note that the WSAMSG parameter
2085 * must remain valid throughout the operation, even when an overlapped
2086 * receive is performed.
2088 static int WINAPI WS2_WSARecvMsg( SOCKET s, LPWSAMSG msg, LPDWORD lpNumberOfBytesRecvd,
2089 LPWSAOVERLAPPED lpOverlapped,
2090 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2094 SetLastError( WSAEFAULT );
2095 return SOCKET_ERROR;
2098 return WS2_recv_base( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesRecvd,
2099 &msg->dwFlags, msg->name, &msg->namelen,
2100 lpOverlapped, lpCompletionRoutine, &msg->Control );
2103 /***********************************************************************
2106 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
2108 int fd = get_sock_fd( s, 0, NULL );
2109 int res = SOCKET_ERROR;
2111 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2115 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
2117 SetLastError(WSAEAFNOSUPPORT);
2121 union generic_unix_sockaddr uaddr;
2122 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2125 SetLastError(WSAEFAULT);
2130 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
2131 if (name->sa_family == WS_AF_INET6 &&
2132 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
2135 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
2137 release_sock_fd( s, fd );
2138 SetLastError(WSAEAFNOSUPPORT);
2139 return SOCKET_ERROR;
2143 if (name->sa_family == WS_AF_INET)
2145 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2146 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2148 /* Trying to bind to the default host interface, using
2149 * INADDR_ANY instead*/
2150 WARN("Trying to bind to magic IP address, using "
2151 "INADDR_ANY instead.\n");
2152 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
2155 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
2157 int loc_errno = errno;
2158 WARN("\tfailure - errno = %i\n", errno);
2163 SetLastError(WSAENOTSOCK);
2166 SetLastError(WSAEINVAL);
2169 SetLastError(wsaErrno());
2175 res=0; /* success */
2179 release_sock_fd( s, fd );
2184 /***********************************************************************
2185 * closesocket (WS2_32.3)
2187 int WINAPI WS_closesocket(SOCKET s)
2189 TRACE("socket %04lx\n", s);
2190 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
2191 return SOCKET_ERROR;
2194 static int do_connect(int fd, const struct WS_sockaddr* name, int namelen)
2196 union generic_unix_sockaddr uaddr;
2197 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2202 if (name->sa_family == WS_AF_INET)
2204 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2205 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2207 /* Trying to connect to magic replace-loopback address,
2208 * assuming we really want to connect to localhost */
2209 TRACE("Trying to connect to magic IP address, using "
2210 "INADDR_LOOPBACK instead.\n");
2211 in4->sin_addr.s_addr = htonl(WS_INADDR_LOOPBACK);
2215 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
2221 /***********************************************************************
2222 * connect (WS2_32.4)
2224 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
2226 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2228 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2232 int ret = do_connect(fd, name, namelen);
2234 goto connect_success;
2236 if (ret == WSAEINPROGRESS)
2238 /* tell wineserver that a connection is in progress */
2239 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2241 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2242 if (_is_blocking(s))
2246 do_block(fd, POLLIN | POLLOUT, -1);
2247 _sync_sock_state(s); /* let wineserver notice connection */
2248 /* retrieve any error codes from it */
2249 result = _get_sock_error(s, FD_CONNECT_BIT);
2251 SetLastError(NtStatusToWSAError(result));
2254 goto connect_success;
2259 SetLastError(WSAEWOULDBLOCK);
2266 release_sock_fd( s, fd );
2268 return SOCKET_ERROR;
2271 release_sock_fd( s, fd );
2272 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2273 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2274 FD_CONNECT|FD_WINE_LISTENING);
2278 /***********************************************************************
2279 * WSAConnect (WS2_32.30)
2281 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
2282 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
2283 LPQOS lpSQOS, LPQOS lpGQOS )
2285 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
2286 FIXME("unsupported parameters!\n");
2287 return WS_connect( s, name, namelen );
2290 /***********************************************************************
2293 static BOOL WINAPI WS2_ConnectEx(SOCKET s, const struct WS_sockaddr* name, int namelen,
2294 PVOID sendBuf, DWORD sendBufLen, LPDWORD sent, LPOVERLAPPED ov)
2296 int fd, ret, status;
2300 SetLastError( ERROR_INVALID_PARAMETER );
2304 fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2307 SetLastError( WSAENOTSOCK );
2311 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
2312 s, name, debugstr_sockaddr(name), namelen, sendBuf, sendBufLen, ov);
2314 /* FIXME: technically the socket has to be bound */
2315 ret = do_connect(fd, name, namelen);
2320 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2321 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2322 FD_CONNECT|FD_WINE_LISTENING);
2324 wsabuf.len = sendBufLen;
2325 wsabuf.buf = (char*) sendBuf;
2327 /* WSASend takes care of completion if need be */
2328 if (WSASend(s, &wsabuf, sendBuf ? 1 : 0, sent, 0, ov, NULL) != SOCKET_ERROR)
2329 goto connection_success;
2331 else if (ret == WSAEINPROGRESS)
2333 struct ws2_async *wsa;
2334 ULONG_PTR cvalue = (((ULONG_PTR)ov->hEvent & 1) == 0) ? (ULONG_PTR)ov : 0;
2336 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2338 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2340 /* Indirectly call WSASend */
2341 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) )))
2343 SetLastError(WSAEFAULT);
2347 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)ov;
2348 iosb->u.Status = STATUS_PENDING;
2349 iosb->Information = 0;
2351 wsa->hSocket = SOCKET2HANDLE(s);
2353 wsa->addrlen.val = 0;
2355 wsa->lpFlags = &wsa->flags;
2356 wsa->control = NULL;
2357 wsa->n_iovecs = sendBuf ? 1 : 0;
2358 wsa->first_iovec = 0;
2359 wsa->completion_func = NULL;
2360 wsa->iovec[0].iov_base = sendBuf;
2361 wsa->iovec[0].iov_len = sendBufLen;
2363 SERVER_START_REQ( register_async )
2365 req->type = ASYNC_TYPE_WRITE;
2366 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2367 req->async.callback = wine_server_client_ptr( WS2_async_send );
2368 req->async.iosb = wine_server_client_ptr( iosb );
2369 req->async.arg = wine_server_client_ptr( wsa );
2370 req->async.event = wine_server_obj_handle( ov->hEvent );
2371 req->async.cvalue = cvalue;
2372 status = wine_server_call( req );
2376 if (status != STATUS_PENDING) HeapFree(GetProcessHeap(), 0, wsa);
2378 /* If the connect already failed */
2379 if (status == STATUS_PIPE_DISCONNECTED)
2380 status = _get_sock_error(s, FD_CONNECT_BIT);
2381 SetLastError( NtStatusToWSAError(status) );
2389 release_sock_fd( s, fd );
2393 release_sock_fd( s, fd );
2398 /***********************************************************************
2399 * getpeername (WS2_32.5)
2401 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
2406 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, namelen?*namelen:0);
2408 fd = get_sock_fd( s, 0, NULL );
2413 union generic_unix_sockaddr uaddr;
2414 unsigned int uaddrlen = sizeof(uaddr);
2416 if (getpeername(fd, &uaddr.addr, &uaddrlen) == 0)
2418 if (!name || !namelen)
2419 SetLastError(WSAEFAULT);
2420 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
2421 /* The buffer was too small */
2422 SetLastError(WSAEFAULT);
2427 SetLastError(wsaErrno());
2428 release_sock_fd( s, fd );
2433 /***********************************************************************
2434 * getsockname (WS2_32.6)
2436 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
2441 TRACE("socket: %04lx, ptr %p, len %8x\n", s, name, *namelen);
2443 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
2444 if( (name == NULL) || (namelen == NULL) )
2446 SetLastError( WSAEFAULT );
2447 return SOCKET_ERROR;
2450 fd = get_sock_fd( s, 0, NULL );
2455 union generic_unix_sockaddr uaddr;
2456 unsigned int uaddrlen = sizeof(uaddr);
2458 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
2460 SetLastError(wsaErrno());
2462 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
2464 SetLastError(WSAEINVAL);
2466 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
2468 /* The buffer was too small */
2469 SetLastError(WSAEFAULT);
2475 release_sock_fd( s, fd );
2480 /***********************************************************************
2481 * getsockopt (WS2_32.7)
2483 INT WINAPI WS_getsockopt(SOCKET s, INT level,
2484 INT optname, char *optval, INT *optlen)
2489 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
2490 s, level, optname, optval, *optlen);
2498 /* Handle common cases. The special cases are below, sorted
2500 case WS_SO_ACCEPTCONN:
2501 case WS_SO_BROADCAST:
2504 case WS_SO_KEEPALIVE:
2505 case WS_SO_OOBINLINE:
2507 case WS_SO_REUSEADDR:
2510 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2511 return SOCKET_ERROR;
2512 convert_sockopt(&level, &optname);
2513 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2515 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2518 release_sock_fd( s, fd );
2521 case WS_SO_DONTLINGER:
2523 struct linger lingval;
2524 unsigned int len = sizeof(struct linger);
2526 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
2528 SetLastError(WSAEFAULT);
2529 return SOCKET_ERROR;
2531 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2532 return SOCKET_ERROR;
2534 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
2536 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2541 *(BOOL *)optval = (lingval.l_onoff) ? FALSE : TRUE;
2542 *optlen = sizeof(BOOL);
2545 release_sock_fd( s, fd );
2549 case WS_SO_CONNECT_TIME:
2551 static int pretendtime = 0;
2553 if (!pretendtime) FIXME("WS_SO_CONNECT_TIME - faking results\n");
2554 if (!optlen || *optlen < sizeof(DWORD) || !optval)
2556 SetLastError(WSAEFAULT);
2557 return SOCKET_ERROR;
2559 *(DWORD*)optval = pretendtime++;
2560 *optlen = sizeof(DWORD);
2563 /* As mentioned in setsockopt, Windows ignores this, so we
2564 * always return true here */
2565 case WS_SO_DONTROUTE:
2566 if (!optlen || *optlen < sizeof(BOOL) || !optval)
2568 SetLastError(WSAEFAULT);
2569 return SOCKET_ERROR;
2571 *(BOOL *)optval = TRUE;
2572 *optlen = sizeof(BOOL);
2577 struct linger lingval;
2578 unsigned int len = sizeof(struct linger);
2580 /* struct linger and LINGER have different sizes */
2581 if (!optlen || *optlen < sizeof(LINGER) || !optval)
2583 SetLastError(WSAEFAULT);
2584 return SOCKET_ERROR;
2586 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2587 return SOCKET_ERROR;
2589 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
2591 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2596 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
2597 ((LINGER *)optval)->l_linger = lingval.l_linger;
2598 *optlen = sizeof(struct linger);
2601 release_sock_fd( s, fd );
2605 case WS_SO_MAX_MSG_SIZE:
2606 if (!optlen || *optlen < sizeof(int) || !optval)
2608 SetLastError(WSAEFAULT);
2609 return SOCKET_ERROR;
2611 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
2612 *(int *)optval = 65507;
2613 *optlen = sizeof(int);
2616 /* SO_OPENTYPE does not require a valid socket handle. */
2617 case WS_SO_OPENTYPE:
2618 if (!optlen || *optlen < sizeof(int) || !optval)
2620 SetLastError(WSAEFAULT);
2621 return SOCKET_ERROR;
2623 *(int *)optval = get_per_thread_data()->opentype;
2624 *optlen = sizeof(int);
2625 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
2629 case WS_SO_RCVTIMEO:
2632 case WS_SO_SNDTIMEO:
2634 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
2637 unsigned int len = sizeof(struct timeval);
2639 if (!optlen || *optlen < sizeof(int)|| !optval)
2641 SetLastError(WSAEFAULT);
2642 return SOCKET_ERROR;
2644 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2645 return SOCKET_ERROR;
2647 convert_sockopt(&level, &optname);
2648 if (getsockopt(fd, level, optname, &tv, &len) != 0 )
2650 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2655 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
2656 *optlen = sizeof(int);
2659 release_sock_fd( s, fd );
2664 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
2665 SetLastError(WSAENOPROTOOPT);
2666 return SOCKET_ERROR;
2667 } /* end switch(optname) */
2668 }/* end case WS_SOL_SOCKET */
2672 struct WS_sockaddr_ipx addr;
2673 IPX_ADDRESS_DATA *data;
2678 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
2680 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (unsigned int*)optlen) == -1)
2687 socklen_t len=sizeof(struct ipx);
2688 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
2691 *optval = (int)val.ipx_pt;
2694 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
2695 release_sock_fd( s, fd );
2700 * On a Win2000 system with one network card there are usually
2701 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
2702 * Using this call you can then retrieve info about this all.
2703 * In case of Linux it is a bit different. Usually you have
2704 * only "one" device active and further it is not possible to
2705 * query things like the linkspeed.
2707 FIXME("IPX_ADDRESS\n");
2708 namelen = sizeof(struct WS_sockaddr_ipx);
2709 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
2710 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
2712 data = (IPX_ADDRESS_DATA*)optval;
2713 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
2714 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
2715 data->adapternum = 0;
2716 data->wan = FALSE; /* We are not on a wan for now .. */
2717 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
2718 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
2719 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
2720 * note 1MB = 1000kB in this case */
2723 case IPX_MAX_ADAPTER_NUM:
2724 FIXME("IPX_MAX_ADAPTER_NUM\n");
2725 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
2729 FIXME("IPX optname:%x\n", optname);
2730 return SOCKET_ERROR;
2731 }/* end switch(optname) */
2732 } /* end case NSPROTO_IPX */
2739 case WS_IRLMP_ENUMDEVICES:
2741 static const int MAX_IRDA_DEVICES = 10;
2742 char buf[sizeof(struct irda_device_list) +
2743 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
2745 socklen_t len = sizeof(buf);
2747 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2748 return SOCKET_ERROR;
2749 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
2752 SetLastError(wsaErrno());
2753 return SOCKET_ERROR;
2757 struct irda_device_list *src = (struct irda_device_list *)buf;
2758 DEVICELIST *dst = (DEVICELIST *)optval;
2759 INT needed = sizeof(DEVICELIST), i;
2762 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
2763 if (*optlen < needed)
2765 SetLastError(WSAEFAULT);
2766 return SOCKET_ERROR;
2769 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
2770 dst->numDevice = src->len;
2771 for (i = 0; i < src->len; i++)
2773 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
2774 src->dev[i].saddr, src->dev[i].daddr,
2775 src->dev[i].info, src->dev[i].hints[0],
2776 src->dev[i].hints[1]);
2777 memcpy( dst->Device[i].irdaDeviceID,
2779 sizeof(dst->Device[i].irdaDeviceID) ) ;
2780 memcpy( dst->Device[i].irdaDeviceName,
2782 sizeof(dst->Device[i].irdaDeviceName) ) ;
2783 memcpy( &dst->Device[i].irdaDeviceHints1,
2784 &src->dev[i].hints[0],
2785 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
2786 memcpy( &dst->Device[i].irdaDeviceHints2,
2787 &src->dev[i].hints[1],
2788 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
2789 dst->Device[i].irdaCharSet = src->dev[i].charset;
2795 FIXME("IrDA optname:0x%x\n", optname);
2796 return SOCKET_ERROR;
2798 break; /* case WS_SOL_IRLMP */
2801 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
2802 case WS_IPPROTO_TCP:
2805 case WS_TCP_NODELAY:
2806 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2807 return SOCKET_ERROR;
2808 convert_sockopt(&level, &optname);
2809 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2811 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2814 release_sock_fd( s, fd );
2817 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
2818 return SOCKET_ERROR;
2823 case WS_IP_ADD_MEMBERSHIP:
2824 case WS_IP_DROP_MEMBERSHIP:
2828 case WS_IP_MULTICAST_IF:
2829 case WS_IP_MULTICAST_LOOP:
2830 case WS_IP_MULTICAST_TTL:
2837 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2838 return SOCKET_ERROR;
2839 convert_sockopt(&level, &optname);
2840 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2842 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2845 release_sock_fd( s, fd );
2847 case WS_IP_DONTFRAGMENT:
2848 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
2849 *(BOOL*)optval = FALSE;
2852 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
2853 return SOCKET_ERROR;
2855 case WS_IPPROTO_IPV6:
2858 #ifdef IPV6_ADD_MEMBERSHIP
2859 case WS_IPV6_ADD_MEMBERSHIP:
2861 #ifdef IPV6_DROP_MEMBERSHIP
2862 case WS_IPV6_DROP_MEMBERSHIP:
2864 case WS_IPV6_MULTICAST_IF:
2865 case WS_IPV6_MULTICAST_HOPS:
2866 case WS_IPV6_MULTICAST_LOOP:
2867 case WS_IPV6_UNICAST_HOPS:
2868 case WS_IPV6_V6ONLY:
2869 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2870 return SOCKET_ERROR;
2871 convert_sockopt(&level, &optname);
2872 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2874 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2877 release_sock_fd( s, fd );
2879 case WS_IPV6_DONTFRAG:
2880 FIXME("WS_IPV6_DONTFRAG is always false!\n");
2881 *(BOOL*)optval = FALSE;
2884 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
2885 return SOCKET_ERROR;
2888 WARN("Unknown level: 0x%08x\n", level);
2889 SetLastError(WSAEINVAL);
2890 return SOCKET_ERROR;
2891 } /* end switch(level) */
2894 /***********************************************************************
2897 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
2899 return htonl(hostlong);
2903 /***********************************************************************
2906 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
2908 return htons(hostshort);
2911 /***********************************************************************
2912 * WSAHtonl (WS2_32.46)
2913 * From MSDN description of error codes, this function should also
2914 * check if WinSock has been initialized and the socket is a valid
2915 * socket. But why? This function only translates a host byte order
2916 * u_long into a network byte order u_long...
2918 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
2922 *lpnetlong = htonl(hostlong);
2925 WSASetLastError(WSAEFAULT);
2926 return SOCKET_ERROR;
2929 /***********************************************************************
2930 * WSAHtons (WS2_32.47)
2931 * From MSDN description of error codes, this function should also
2932 * check if WinSock has been initialized and the socket is a valid
2933 * socket. But why? This function only translates a host byte order
2934 * u_short into a network byte order u_short...
2936 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
2941 *lpnetshort = htons(hostshort);
2944 WSASetLastError(WSAEFAULT);
2945 return SOCKET_ERROR;
2949 /***********************************************************************
2950 * inet_addr (WS2_32.11)
2952 WS_u_long WINAPI WS_inet_addr(const char *cp)
2954 if (!cp) return INADDR_NONE;
2955 return inet_addr(cp);
2959 /***********************************************************************
2962 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
2964 return ntohl(netlong);
2968 /***********************************************************************
2971 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
2973 return ntohs(netshort);
2977 /***********************************************************************
2978 * inet_ntoa (WS2_32.12)
2980 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
2982 /* use "buffer for dummies" here because some applications have a
2983 * propensity to decode addresses in ws_hostent structure without
2984 * saving them first...
2986 static char dbuffer[16]; /* Yes, 16: 4*3 digits + 3 '.' + 1 '\0' */
2988 char* s = inet_ntoa(*((struct in_addr*)&in));
2994 SetLastError(wsaErrno());
2998 static const char *debugstr_wsaioctl(DWORD ioctl)
3000 const char *buf_type, *family;
3002 switch(ioctl & 0x18000000)
3007 case WS_IOC_PROTOCOL:
3008 family = "IOC_PROTOCOL";
3011 family = "IOC_VENDOR";
3013 default: /* WS_IOC_UNIX */
3015 BYTE size = (ioctl >> 16) & WS_IOCPARM_MASK;
3016 char x = (ioctl & 0xff00) >> 8;
3017 BYTE y = ioctl & 0xff;
3020 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3024 sprintf(args, "%d, %d", x, y);
3028 sprintf(args, "'%c', %d, %d", x, y, size);
3032 sprintf(args, "'%c', %d, %d", x, y, size);
3036 sprintf(args, "'%c', %d, %d", x, y, size);
3039 return wine_dbg_sprintf("%s(%s)", buf_type, args);
3043 /* We are different from WS_IOC_UNIX. */
3044 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3047 buf_type = "_WSAIO";
3050 buf_type = "_WSAIORW";
3053 buf_type = "_WSAIOW";
3056 buf_type = "_WSAIOR";
3063 return wine_dbg_sprintf("%s(%s, %d)", buf_type, family,
3064 (USHORT)(ioctl & 0xffff));
3067 /**********************************************************************
3068 * WSAIoctl (WS2_32.50)
3071 INT WINAPI WSAIoctl(SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size, LPVOID out_buff,
3072 DWORD out_size, LPDWORD ret_size, LPWSAOVERLAPPED overlapped,
3073 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
3076 DWORD status = 0, total = 0;
3078 TRACE("%ld, 0x%08x, %p, %d, %p, %d, %p, %p, %p\n",
3079 s, code, in_buff, in_size, out_buff, out_size, ret_size, overlapped, completion);
3084 if (in_size != sizeof(WS_u_long) || IS_INTRESOURCE(in_buff))
3086 WSASetLastError(WSAEFAULT);
3087 return SOCKET_ERROR;
3089 if (_get_sock_mask(s))
3091 /* AsyncSelect()'ed sockets are always nonblocking */
3092 if (!*(WS_u_long *)in_buff) status = WSAEINVAL;
3095 if (*(WS_u_long *)in_buff)
3096 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
3098 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
3103 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
3105 WSASetLastError(WSAEFAULT);
3106 return SOCKET_ERROR;
3108 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3109 if (ioctl(fd, FIONREAD, out_buff ) == -1)
3110 status = (errno == EBADF) ? WSAENOTSOCK : wsaErrno();
3111 release_sock_fd( s, fd );
3117 unsigned int oob = 0, oobsize = sizeof(int), atmark = 0;
3118 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
3120 WSASetLastError(WSAEFAULT);
3121 return SOCKET_ERROR;
3123 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3124 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
3125 if ((getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &oob, &oobsize ) == -1)
3126 || (!oob && ioctl(fd, SIOCATMARK, &atmark ) == -1))
3127 status = (errno == EBADF) ? WSAENOTSOCK : wsaErrno();
3129 (*(WS_u_long *) out_buff) = oob | atmark;
3130 release_sock_fd( s, fd );
3135 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
3136 SetLastError(WSAEINVAL);
3137 return SOCKET_ERROR;
3139 case WS_SIO_GET_INTERFACE_LIST:
3141 INTERFACE_INFO* intArray = out_buff;
3142 DWORD size, numInt = 0, apiReturn;
3144 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
3146 if (!out_buff || !ret_size)
3148 WSASetLastError(WSAEFAULT);
3149 return SOCKET_ERROR;
3152 fd = get_sock_fd( s, 0, NULL );
3153 if (fd == -1) return SOCKET_ERROR;
3155 apiReturn = GetAdaptersInfo(NULL, &size);
3156 if (apiReturn == ERROR_BUFFER_OVERFLOW)
3158 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
3162 if (GetAdaptersInfo(table, &size) == NO_ERROR)
3164 PIP_ADAPTER_INFO ptr;
3166 if (size*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > out_size)
3168 WARN("Buffer too small = %u, out_size = %u\n", size, out_size);
3169 HeapFree(GetProcessHeap(),0,table);
3170 release_sock_fd( s, fd );
3174 for (ptr = table, numInt = 0; ptr;
3175 ptr = ptr->Next, intArray++, numInt++)
3177 unsigned int addr, mask, bcast;
3178 struct ifreq ifInfo;
3180 /* Socket Status Flags */
3181 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
3182 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
3184 ERR("Error obtaining status flags for socket!\n");
3185 HeapFree(GetProcessHeap(),0,table);
3186 release_sock_fd( s, fd );
3192 /* set flags; the values of IFF_* are not the same
3193 under Linux and Windows, therefore must generate
3195 intArray->iiFlags = 0;
3196 if (ifInfo.ifr_flags & IFF_BROADCAST)
3197 intArray->iiFlags |= WS_IFF_BROADCAST;
3198 #ifdef IFF_POINTOPOINT
3199 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
3200 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
3202 if (ifInfo.ifr_flags & IFF_LOOPBACK)
3203 intArray->iiFlags |= WS_IFF_LOOPBACK;
3204 if (ifInfo.ifr_flags & IFF_UP)
3205 intArray->iiFlags |= WS_IFF_UP;
3206 if (ifInfo.ifr_flags & IFF_MULTICAST)
3207 intArray->iiFlags |= WS_IFF_MULTICAST;
3210 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
3211 mask = inet_addr(ptr->IpAddressList.IpMask.String);
3212 bcast = addr | ~mask;
3213 intArray->iiAddress.AddressIn.sin_family = AF_INET;
3214 intArray->iiAddress.AddressIn.sin_port = 0;
3215 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
3217 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
3218 intArray->iiNetmask.AddressIn.sin_port = 0;
3219 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
3221 intArray->iiBroadcastAddress.AddressIn.sin_family =
3223 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
3224 intArray->iiBroadcastAddress.AddressIn.sin_addr.
3230 ERR("Unable to get interface table!\n");
3233 HeapFree(GetProcessHeap(),0,table);
3235 else status = WSAEINVAL;
3237 else if (apiReturn != ERROR_NO_DATA)
3239 ERR("Unable to get interface table!\n");
3242 /* Calculate the size of the array being returned */
3243 total = sizeof(INTERFACE_INFO) * numInt;
3244 release_sock_fd( s, fd );
3248 case WS_SIO_ADDRESS_LIST_CHANGE:
3249 FIXME("-> SIO_ADDRESS_LIST_CHANGE request: stub\n");
3250 /* FIXME: error and return code depend on whether socket was created
3251 * with WSA_FLAG_OVERLAPPED, but there is no easy way to get this */
3254 case WS_SIO_ADDRESS_LIST_QUERY:
3258 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
3262 WSASetLastError(WSAEFAULT);
3263 return SOCKET_ERROR;
3266 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
3268 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
3271 if (!table || GetAdaptersInfo(table, &size))
3273 HeapFree(GetProcessHeap(), 0, table);
3278 for (p = table, num = 0; p; p = p->Next)
3279 if (p->IpAddressList.IpAddress.String[0]) num++;
3281 total = sizeof(SOCKET_ADDRESS_LIST) + sizeof(SOCKET_ADDRESS) * (num - 1);
3282 total += sizeof(SOCKADDR) * num;
3284 if (total > out_size)
3286 HeapFree(GetProcessHeap(), 0, table);
3295 SOCKET_ADDRESS_LIST *sa_list = out_buff;
3296 SOCKADDR_IN *sockaddr;
3298 sa = sa_list->Address;
3299 sockaddr = (SOCKADDR_IN *)((char *)sa + num * sizeof(SOCKET_ADDRESS));
3300 sa_list->iAddressCount = num;
3302 for (p = table, i = 0; p; p = p->Next)
3304 if (!p->IpAddressList.IpAddress.String[0]) continue;
3306 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
3307 sa[i].iSockaddrLength = sizeof(SOCKADDR);
3309 sockaddr[i].sin_family = AF_INET;
3310 sockaddr[i].sin_port = 0;
3311 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
3316 HeapFree(GetProcessHeap(), 0, table);
3320 WARN("unable to get IP address list\n");
3327 FIXME("SIO_FLUSH: stub.\n");
3330 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
3332 static const GUID connectex_guid = WSAID_CONNECTEX;
3333 static const GUID disconnectex_guid = WSAID_DISCONNECTEX;
3334 static const GUID acceptex_guid = WSAID_ACCEPTEX;
3335 static const GUID getaccepexsockaddrs_guid = WSAID_GETACCEPTEXSOCKADDRS;
3336 static const GUID transmitfile_guid = WSAID_TRANSMITFILE;
3337 static const GUID transmitpackets_guid = WSAID_TRANSMITPACKETS;
3338 static const GUID wsarecvmsg_guid = WSAID_WSARECVMSG;
3339 static const GUID wsasendmsg_guid = WSAID_WSASENDMSG;
3341 if ( IsEqualGUID(&connectex_guid, in_buff) )
3343 *(LPFN_CONNECTEX *)out_buff = WS2_ConnectEx;
3346 else if ( IsEqualGUID(&disconnectex_guid, in_buff) )
3348 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented DisconnectEx\n");
3350 else if ( IsEqualGUID(&acceptex_guid, in_buff) )
3352 *(LPFN_ACCEPTEX *)out_buff = WS2_AcceptEx;
3355 else if ( IsEqualGUID(&getaccepexsockaddrs_guid, in_buff) )
3357 *(LPFN_GETACCEPTEXSOCKADDRS *)out_buff = WS2_GetAcceptExSockaddrs;
3360 else if ( IsEqualGUID(&transmitfile_guid, in_buff) )
3362 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitFile\n");
3364 else if ( IsEqualGUID(&transmitpackets_guid, in_buff) )
3366 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitPackets\n");
3368 else if ( IsEqualGUID(&wsarecvmsg_guid, in_buff) )
3370 *(LPFN_WSARECVMSG *)out_buff = WS2_WSARecvMsg;
3373 else if ( IsEqualGUID(&wsasendmsg_guid, in_buff) )
3375 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented WSASendMsg\n");
3378 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff));
3380 status = WSAEOPNOTSUPP;
3383 case WS_SIO_KEEPALIVE_VALS:
3385 struct tcp_keepalive *k;
3386 int keepalive, keepidle, keepintvl;
3388 if (!in_buff || in_size < sizeof(struct tcp_keepalive))
3390 WSASetLastError(WSAEFAULT);
3391 return SOCKET_ERROR;
3395 keepalive = k->onoff ? 1 : 0;
3396 keepidle = max( 1, (k->keepalivetime + 500) / 1000 );
3397 keepintvl = max( 1, (k->keepaliveinterval + 500) / 1000 );
3399 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
3401 fd = get_sock_fd(s, 0, NULL);
3402 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
3404 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
3405 /* these values need to be set only if SO_KEEPALIVE is enabled */
3408 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
3410 else if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
3415 FIXME("ignoring keepalive interval and timeout\n");
3417 release_sock_fd(s, fd);
3420 case WS_SIO_ROUTING_INTERFACE_QUERY:
3422 struct WS_sockaddr *daddr = (struct WS_sockaddr *)in_buff;
3423 struct WS_sockaddr_in *daddr_in = (struct WS_sockaddr_in *)daddr;
3424 struct WS_sockaddr_in *saddr_in = out_buff;
3425 MIB_IPFORWARDROW row;
3426 PMIB_IPADDRTABLE ipAddrTable = NULL;
3427 DWORD size, i, found_index;
3429 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
3431 if (!in_buff || in_size < sizeof(struct WS_sockaddr) ||
3432 !out_buff || out_size < sizeof(struct WS_sockaddr_in) || !ret_size)
3434 WSASetLastError(WSAEFAULT);
3435 return SOCKET_ERROR;
3437 if (daddr->sa_family != AF_INET)
3439 FIXME("unsupported address family %d\n", daddr->sa_family);
3440 status = WSAEAFNOSUPPORT;
3443 if (GetBestRoute(daddr_in->sin_addr.S_un.S_addr, 0, &row) != NOERROR ||
3444 GetIpAddrTable(NULL, &size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
3449 ipAddrTable = HeapAlloc(GetProcessHeap(), 0, size);
3450 if (GetIpAddrTable(ipAddrTable, &size, FALSE))
3452 HeapFree(GetProcessHeap(), 0, ipAddrTable);
3456 for (i = 0, found_index = ipAddrTable->dwNumEntries;
3457 i < ipAddrTable->dwNumEntries; i++)
3459 if (ipAddrTable->table[i].dwIndex == row.dwForwardIfIndex)
3462 if (found_index == ipAddrTable->dwNumEntries)
3464 ERR("no matching IP address for interface %d\n",
3465 row.dwForwardIfIndex);
3466 HeapFree(GetProcessHeap(), 0, ipAddrTable);
3470 saddr_in->sin_family = AF_INET;
3471 saddr_in->sin_addr.S_un.S_addr = ipAddrTable->table[found_index].dwAddr;
3472 saddr_in->sin_port = 0;
3473 total = sizeof(struct WS_sockaddr_in);
3474 HeapFree(GetProcessHeap(), 0, ipAddrTable);
3477 case WS_SIO_SET_COMPATIBILITY_MODE:
3478 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
3479 status = WSAEOPNOTSUPP;
3481 case WS_SIO_UDP_CONNRESET:
3482 FIXME("WS_SIO_UDP_CONNRESET stub\n");
3484 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
3485 WSASetLastError(WSAEOPNOTSUPP);
3486 return SOCKET_ERROR;
3488 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code));
3489 status = WSAEOPNOTSUPP;
3495 FIXME( "completion routine %p not supported\n", completion );
3497 else if (overlapped)
3499 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
3500 overlapped->Internal = status;
3501 overlapped->InternalHigh = total;
3502 if (overlapped->hEvent) NtSetEvent( overlapped->hEvent, NULL );
3503 if (cvalue) WS_AddCompletion( HANDLE2SOCKET(s), cvalue, status, total );
3508 if (ret_size) *ret_size = total;
3511 SetLastError( status );
3512 return SOCKET_ERROR;
3516 /***********************************************************************
3517 * ioctlsocket (WS2_32.10)
3519 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
3522 return WSAIoctl( s, cmd, argp, sizeof(WS_u_long), argp, sizeof(WS_u_long), &ret_size, NULL, NULL );
3525 /***********************************************************************
3526 * listen (WS2_32.13)
3528 int WINAPI WS_listen(SOCKET s, int backlog)
3530 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
3532 TRACE("socket %04lx, backlog %d\n", s, backlog);
3535 if (listen(fd, backlog) == 0)
3537 release_sock_fd( s, fd );
3538 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
3540 FD_CONNECT|FD_WINE_CONNECTED);
3543 SetLastError(wsaErrno());
3544 release_sock_fd( s, fd );
3546 return SOCKET_ERROR;
3549 /***********************************************************************
3552 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
3554 DWORD n, dwFlags = flags;
3560 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
3561 return SOCKET_ERROR;
3566 /***********************************************************************
3567 * recvfrom (WS2_32.17)
3569 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
3570 struct WS_sockaddr *from, int *fromlen)
3572 DWORD n, dwFlags = flags;
3578 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL, NULL) == SOCKET_ERROR )
3579 return SOCKET_ERROR;
3584 /* allocate a poll array for the corresponding fd sets */
3585 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
3586 const WS_fd_set *exceptfds, int *count_ptr )
3588 unsigned int i, j = 0, count = 0;
3591 if (readfds) count += readfds->fd_count;
3592 if (writefds) count += writefds->fd_count;
3593 if (exceptfds) count += exceptfds->fd_count;
3597 SetLastError(WSAEINVAL);
3600 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0]))))
3602 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
3606 for (i = 0; i < readfds->fd_count; i++, j++)
3608 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
3609 if (fds[j].fd == -1) goto failed;
3610 fds[j].events = POLLIN;
3614 for (i = 0; i < writefds->fd_count; i++, j++)
3616 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
3617 if (fds[j].fd == -1) goto failed;
3618 fds[j].events = POLLOUT;
3622 for (i = 0; i < exceptfds->fd_count; i++, j++)
3624 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
3625 if (fds[j].fd == -1) goto failed;
3626 fds[j].events = POLLHUP;
3635 for (i = 0; i < readfds->fd_count && j < count; i++, j++)
3636 release_sock_fd( readfds->fd_array[i], fds[j].fd );
3638 for (i = 0; i < writefds->fd_count && j < count; i++, j++)
3639 release_sock_fd( writefds->fd_array[i], fds[j].fd );
3641 for (i = 0; i < exceptfds->fd_count && j < count; i++, j++)
3642 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
3643 HeapFree( GetProcessHeap(), 0, fds );
3647 /* release the file descriptor obtained in fd_sets_to_poll */
3648 /* must be called with the original fd_set arrays, before calling get_poll_results */
3649 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
3650 const WS_fd_set *exceptfds, struct pollfd *fds )
3652 unsigned int i, j = 0;
3656 for (i = 0; i < readfds->fd_count; i++, j++)
3657 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
3661 for (i = 0; i < writefds->fd_count; i++, j++)
3662 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
3666 for (i = 0; i < exceptfds->fd_count; i++, j++)
3667 if (fds[j].fd != -1)
3669 /* make sure we have a real error before releasing the fd */
3670 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
3671 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
3676 /* map the poll results back into the Windows fd sets */
3677 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
3678 const struct pollfd *fds )
3680 unsigned int i, j = 0, k, total = 0;
3684 for (i = k = 0; i < readfds->fd_count; i++, j++)
3685 if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
3686 readfds->fd_count = k;
3691 for (i = k = 0; i < writefds->fd_count; i++, j++)
3692 if ((fds[j].revents & POLLOUT) && !(fds[j].revents & POLLHUP))
3693 writefds->fd_array[k++] = writefds->fd_array[i];
3694 writefds->fd_count = k;
3699 for (i = k = 0; i < exceptfds->fd_count; i++, j++)
3700 if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
3701 exceptfds->fd_count = k;
3708 /***********************************************************************
3709 * select (WS2_32.18)
3711 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
3712 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
3713 const struct WS_timeval* ws_timeout)
3715 struct pollfd *pollfds;
3716 struct timeval tv1, tv2;
3718 int count, ret, timeout = -1;
3720 TRACE("read %p, write %p, excp %p timeout %p\n",
3721 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
3723 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )))
3724 return SOCKET_ERROR;
3728 torig = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
3730 gettimeofday( &tv1, 0 );
3733 while ((ret = poll( pollfds, count, timeout )) < 0)
3737 if (!ws_timeout) continue;
3738 gettimeofday( &tv2, 0 );
3740 tv2.tv_sec -= tv1.tv_sec;
3741 tv2.tv_usec -= tv1.tv_usec;
3742 if (tv2.tv_usec < 0)
3744 tv2.tv_usec += 1000000;
3748 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
3749 if (timeout <= 0) break;
3752 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
3754 if (ret == -1) SetLastError(wsaErrno());
3755 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
3756 HeapFree( GetProcessHeap(), 0, pollfds );
3760 /* helper to send completion messages for client-only i/o operation case */
3761 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
3764 SERVER_START_REQ( add_fd_completion )
3766 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
3767 req->cvalue = CompletionValue;
3768 req->status = CompletionStatus;
3769 req->information = Information;
3770 wine_server_call( req );
3776 /***********************************************************************
3779 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
3785 wsabuf.buf = (char*) buf;
3787 if ( WS2_sendto( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
3788 return SOCKET_ERROR;
3793 /***********************************************************************
3794 * WSASend (WS2_32.72)
3796 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3797 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
3798 LPWSAOVERLAPPED lpOverlapped,
3799 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3801 return WS2_sendto( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
3802 NULL, 0, lpOverlapped, lpCompletionRoutine );
3805 /***********************************************************************
3806 * WSASendDisconnect (WS2_32.73)
3808 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
3810 return WS_shutdown( s, SD_SEND );
3814 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3815 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
3816 const struct WS_sockaddr *to, int tolen,
3817 LPWSAOVERLAPPED lpOverlapped,
3818 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3820 unsigned int i, options;
3822 struct ws2_async *wsa = NULL;
3823 int totalLength = 0;
3824 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
3827 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
3828 s, lpBuffers, dwBufferCount, dwFlags,
3829 to, tolen, lpOverlapped, lpCompletionRoutine);
3831 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
3832 TRACE( "fd=%d, options=%x\n", fd, options );
3834 if ( fd == -1 ) return SOCKET_ERROR;
3836 if (!lpOverlapped && !lpNumberOfBytesSent)
3841 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
3847 wsa->hSocket = SOCKET2HANDLE(s);
3848 wsa->addr = (struct WS_sockaddr *)to;
3849 wsa->addrlen.val = tolen;
3850 wsa->flags = dwFlags;
3851 wsa->lpFlags = &wsa->flags;
3852 wsa->control = NULL;
3853 wsa->n_iovecs = dwBufferCount;
3854 wsa->first_iovec = 0;
3855 for ( i = 0; i < dwBufferCount; i++ )
3857 wsa->iovec[i].iov_base = lpBuffers[i].buf;
3858 wsa->iovec[i].iov_len = lpBuffers[i].len;
3859 totalLength += lpBuffers[i].len;
3864 n = WS2_send( fd, wsa );
3865 if (n != -1 || errno != EINTR) break;
3867 if (n == -1 && errno != EAGAIN)
3869 int loc_errno = errno;
3871 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
3875 if ((lpOverlapped || lpCompletionRoutine) &&
3876 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
3878 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
3880 wsa->user_overlapped = lpOverlapped;
3881 wsa->completion_func = lpCompletionRoutine;
3882 release_sock_fd( s, fd );
3884 if (n == -1 || n < totalLength)
3886 iosb->u.Status = STATUS_PENDING;
3887 iosb->Information = n == -1 ? 0 : n;
3889 SERVER_START_REQ( register_async )
3891 req->type = ASYNC_TYPE_WRITE;
3892 req->async.handle = wine_server_obj_handle( wsa->hSocket );
3893 req->async.callback = wine_server_client_ptr( WS2_async_send );
3894 req->async.iosb = wine_server_client_ptr( iosb );
3895 req->async.arg = wine_server_client_ptr( wsa );
3896 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
3897 req->async.cvalue = cvalue;
3898 err = wine_server_call( req );
3902 /* Enable the event only after starting the async. The server will deliver it as soon as
3903 the async is done. */
3904 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
3906 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
3907 WSASetLastError( NtStatusToWSAError( err ));
3908 return SOCKET_ERROR;
3911 iosb->u.Status = STATUS_SUCCESS;
3912 iosb->Information = n;
3913 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = n;
3914 if (!wsa->completion_func)
3916 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
3917 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
3918 HeapFree( GetProcessHeap(), 0, wsa );
3920 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
3921 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
3926 if ( _is_blocking(s) )
3928 /* On a blocking non-overlapped stream socket,
3929 * sending blocks until the entire buffer is sent. */
3930 DWORD timeout_start = GetTickCount();
3932 bytes_sent = n == -1 ? 0 : n;
3934 while (wsa->first_iovec < wsa->n_iovecs)
3937 int timeout = GET_SNDTIMEO(fd);
3941 timeout -= GetTickCount() - timeout_start;
3942 if (timeout < 0) timeout = 0;
3946 pfd.events = POLLOUT;
3948 if (!timeout || !poll( &pfd, 1, timeout ))
3951 goto error; /* msdn says a timeout in send is fatal */
3954 n = WS2_send( fd, wsa );
3955 if (n == -1 && errno != EAGAIN && errno != EINTR)
3965 else /* non-blocking */
3967 if (n < totalLength)
3968 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
3971 err = WSAEWOULDBLOCK;
3977 TRACE(" -> %i bytes\n", bytes_sent);
3979 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = bytes_sent;
3980 HeapFree( GetProcessHeap(), 0, wsa );
3981 release_sock_fd( s, fd );
3986 HeapFree( GetProcessHeap(), 0, wsa );
3987 release_sock_fd( s, fd );
3988 WARN(" -> ERROR %d\n", err);
3989 WSASetLastError(err);
3990 return SOCKET_ERROR;
3993 /***********************************************************************
3994 * WSASendTo (WS2_32.74)
3996 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3997 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
3998 const struct WS_sockaddr *to, int tolen,
3999 LPWSAOVERLAPPED lpOverlapped,
4000 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4002 return WS2_sendto( s, lpBuffers, dwBufferCount,
4003 lpNumberOfBytesSent, dwFlags,
4005 lpOverlapped, lpCompletionRoutine );
4008 /***********************************************************************
4009 * sendto (WS2_32.20)
4011 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
4012 const struct WS_sockaddr *to, int tolen)
4018 wsabuf.buf = (char*) buf;
4020 if ( WS2_sendto(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
4021 return SOCKET_ERROR;
4026 /***********************************************************************
4027 * setsockopt (WS2_32.21)
4029 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
4030 const char *optval, int optlen)
4034 struct linger linger;
4035 struct timeval tval;
4037 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
4038 s, level, optname, optval, optlen);
4040 /* some broken apps pass the value directly instead of a pointer to it */
4041 if(optlen && IS_INTRESOURCE(optval))
4043 SetLastError(WSAEFAULT);
4044 return SOCKET_ERROR;
4052 /* Some options need some conversion before they can be sent to
4053 * setsockopt. The conversions are done here, then they will fall though
4054 * to the general case. Special options that are not passed to
4055 * setsockopt follow below that.*/
4057 case WS_SO_DONTLINGER:
4060 SetLastError(WSAEFAULT);
4061 return SOCKET_ERROR;
4063 linger.l_onoff = *((const int*)optval) ? 0: 1;
4064 linger.l_linger = 0;
4066 optname = SO_LINGER;
4067 optval = (char*)&linger;
4068 optlen = sizeof(struct linger);
4074 SetLastError(WSAEFAULT);
4075 return SOCKET_ERROR;
4077 linger.l_onoff = ((LINGER*)optval)->l_onoff;
4078 linger.l_linger = ((LINGER*)optval)->l_linger;
4080 optname = SO_LINGER;
4081 optval = (char*)&linger;
4082 optlen = sizeof(struct linger);
4086 if (*(const int*)optval < 2048)
4088 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
4093 /* The options listed here don't need any special handling. Thanks to
4094 * the conversion happening above, options from there will fall through
4096 case WS_SO_ACCEPTCONN:
4097 case WS_SO_BROADCAST:
4099 case WS_SO_KEEPALIVE:
4100 case WS_SO_OOBINLINE:
4101 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
4102 * however, using it the BSD way fixes bug 8513 and seems to be what
4103 * most programmers assume, anyway */
4104 case WS_SO_REUSEADDR:
4107 convert_sockopt(&level, &optname);
4110 /* SO_DEBUG is a privileged operation, ignore it. */
4112 TRACE("Ignoring SO_DEBUG\n");
4115 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
4116 * socket. According to MSDN, this option is silently ignored.*/
4117 case WS_SO_DONTROUTE:
4118 TRACE("Ignoring SO_DONTROUTE\n");
4121 /* Stops two sockets from being bound to the same port. Always happens
4122 * on unix systems, so just drop it. */
4123 case WS_SO_EXCLUSIVEADDRUSE:
4124 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
4127 /* After a ConnectEx call succeeds, the socket can't be used with half of the
4128 * normal winsock functions on windows. We don't have that problem. */
4129 case WS_SO_UPDATE_CONNECT_CONTEXT:
4130 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
4133 /* After a AcceptEx call succeeds, the socket can't be used with half of the
4134 * normal winsock functions on windows. We don't have that problem. */
4135 case WS_SO_UPDATE_ACCEPT_CONTEXT:
4136 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
4139 /* SO_OPENTYPE does not require a valid socket handle. */
4140 case WS_SO_OPENTYPE:
4141 if (!optlen || optlen < sizeof(int) || !optval)
4143 SetLastError(WSAEFAULT);
4144 return SOCKET_ERROR;
4146 get_per_thread_data()->opentype = *(const int *)optval;
4147 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
4151 case WS_SO_RCVTIMEO:
4154 case WS_SO_SNDTIMEO:
4156 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
4157 if (optval && optlen == sizeof(UINT32)) {
4158 /* WinSock passes milliseconds instead of struct timeval */
4159 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
4160 tval.tv_sec = *(const UINT32*)optval / 1000;
4161 /* min of 500 milliseconds */
4162 if (tval.tv_sec == 0 && tval.tv_usec && tval.tv_usec < 500000)
4163 tval.tv_usec = 500000;
4164 optlen = sizeof(struct timeval);
4165 optval = (char*)&tval;
4166 } else if (optlen == sizeof(struct timeval)) {
4167 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
4169 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
4172 convert_sockopt(&level, &optname);
4177 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
4178 SetLastError(WSAENOPROTOOPT);
4179 return SOCKET_ERROR;
4181 break; /* case WS_SOL_SOCKET */
4188 fd = get_sock_fd( s, 0, NULL );
4189 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", *(const int*)optval, fd);
4191 /* We try to set the ipx type on ipx socket level. */
4193 if(setsockopt(fd, SOL_IPX, IPX_TYPE, optval, optlen) == -1)
4195 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
4196 release_sock_fd( s, fd );
4197 return SOCKET_ERROR;
4202 /* Should we retrieve val using a getsockopt call and then
4203 * set the modified one? */
4204 val.ipx_pt = *optval;
4205 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
4208 release_sock_fd( s, fd );
4211 case IPX_FILTERPTYPE:
4212 /* Sets the receive filter packet type, at the moment we don't support it */
4213 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
4214 /* Returning 0 is better for now than returning a SOCKET_ERROR */
4218 FIXME("opt_name:%x\n", optname);
4219 return SOCKET_ERROR;
4221 break; /* case NSPROTO_IPX */
4224 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
4225 case WS_IPPROTO_TCP:
4228 case WS_TCP_NODELAY:
4229 convert_sockopt(&level, &optname);
4232 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
4233 return SOCKET_ERROR;
4240 case WS_IP_ADD_MEMBERSHIP:
4241 case WS_IP_DROP_MEMBERSHIP:
4245 case WS_IP_MULTICAST_IF:
4246 case WS_IP_MULTICAST_LOOP:
4247 case WS_IP_MULTICAST_TTL:
4254 convert_sockopt(&level, &optname);
4256 case WS_IP_DONTFRAGMENT:
4257 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
4260 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
4261 return SOCKET_ERROR;
4265 case WS_IPPROTO_IPV6:
4268 #ifdef IPV6_ADD_MEMBERSHIP
4269 case WS_IPV6_ADD_MEMBERSHIP:
4271 #ifdef IPV6_DROP_MEMBERSHIP
4272 case WS_IPV6_DROP_MEMBERSHIP:
4274 case WS_IPV6_MULTICAST_IF:
4275 case WS_IPV6_MULTICAST_HOPS:
4276 case WS_IPV6_MULTICAST_LOOP:
4277 case WS_IPV6_UNICAST_HOPS:
4278 case WS_IPV6_V6ONLY:
4279 convert_sockopt(&level, &optname);
4281 case WS_IPV6_DONTFRAG:
4282 FIXME("IPV6_DONTFRAG is silently ignored!\n");
4285 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
4286 return SOCKET_ERROR;
4291 WARN("Unknown level: 0x%08x\n", level);
4292 SetLastError(WSAEINVAL);
4293 return SOCKET_ERROR;
4294 } /* end switch(level) */
4296 /* avoid endianness issues if argument is a 16-bit int */
4297 if (optval && optlen < sizeof(int))
4299 woptval= *((const INT16 *) optval);
4300 optval= (char*) &woptval;
4303 fd = get_sock_fd( s, 0, NULL );
4304 if (fd == -1) return SOCKET_ERROR;
4306 if (setsockopt(fd, level, optname, optval, optlen) == 0)
4308 release_sock_fd( s, fd );
4311 TRACE("Setting socket error, %d\n", wsaErrno());
4312 SetLastError(wsaErrno());
4313 release_sock_fd( s, fd );
4315 return SOCKET_ERROR;
4318 /***********************************************************************
4319 * shutdown (WS2_32.22)
4321 int WINAPI WS_shutdown(SOCKET s, int how)
4323 int fd, err = WSAENOTSOCK;
4324 unsigned int options, clear_flags = 0;
4326 fd = get_sock_fd( s, 0, &options );
4327 TRACE("socket %04lx, how %i %x\n", s, how, options );
4330 return SOCKET_ERROR;
4334 case 0: /* drop receives */
4335 clear_flags |= FD_READ;
4337 case 1: /* drop sends */
4338 clear_flags |= FD_WRITE;
4340 case 2: /* drop all */
4341 clear_flags |= FD_READ|FD_WRITE;
4343 clear_flags |= FD_WINE_LISTENING;
4346 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
4351 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
4354 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
4358 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
4359 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
4362 if (err) goto error;
4364 else /* non-overlapped mode */
4366 if ( shutdown( fd, how ) )
4373 release_sock_fd( s, fd );
4374 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
4375 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
4379 release_sock_fd( s, fd );
4380 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
4381 WSASetLastError( err );
4382 return SOCKET_ERROR;
4385 /***********************************************************************
4386 * socket (WS2_32.23)
4388 SOCKET WINAPI WS_socket(int af, int type, int protocol)
4390 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
4392 return WSASocketA( af, type, protocol, NULL, 0,
4393 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
4397 /***********************************************************************
4398 * gethostbyaddr (WS2_32.51)
4400 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
4402 struct WS_hostent *retval = NULL;
4403 struct hostent* host;
4405 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4408 struct hostent hostentry;
4411 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
4413 int res = gethostbyaddr_r(addr, len, type,
4414 &hostentry, extrabuf, ebufsize, &host, &locerr);
4415 if( res != ERANGE) break;
4417 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
4419 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
4421 EnterCriticalSection( &csWSgetXXXbyYYY );
4422 host = gethostbyaddr(addr, len, type);
4423 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
4425 if( host != NULL ) retval = WS_dup_he(host);
4426 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4427 HeapFree(GetProcessHeap(),0,extrabuf);
4429 LeaveCriticalSection( &csWSgetXXXbyYYY );
4431 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
4435 /***********************************************************************
4436 * WS_get_local_ips (INTERNAL)
4438 * Returns the list of local IP addresses by going through the network
4439 * adapters and using the local routing table to sort the addresses
4440 * from highest routing priority to lowest routing priority. This
4441 * functionality is inferred from the description for obtaining local
4442 * IP addresses given in the Knowledge Base Article Q160215.
4444 * Please note that the returned hostent is only freed when the thread
4445 * closes and is replaced if another hostent is requested.
4447 static struct WS_hostent* WS_get_local_ips( char *hostname )
4449 int last_metric, numroutes = 0, i, j;
4450 PIP_ADAPTER_INFO adapters = NULL, k;
4451 struct WS_hostent *hostlist = NULL;
4452 PMIB_IPFORWARDTABLE routes = NULL;
4453 struct route *route_addrs = NULL;
4454 DWORD adap_size, route_size;
4456 /* Obtain the size of the adapter list and routing table, also allocate memory */
4457 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
4459 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
4461 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
4462 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
4463 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
4464 if (adapters == NULL || routes == NULL || route_addrs == NULL)
4466 /* Obtain the adapter list and the full routing table */
4467 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
4469 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
4471 /* Store the interface associated with each route */
4472 for (i = 0; i < routes->dwNumEntries; i++)
4474 DWORD ifindex, ifmetric, exists = FALSE;
4476 if (routes->table[i].dwForwardType != MIB_IPROUTE_TYPE_DIRECT)
4478 ifindex = routes->table[i].dwForwardIfIndex;
4479 ifmetric = routes->table[i].dwForwardMetric1;
4480 /* Only store the lowest valued metric for an interface */
4481 for (j = 0; j < numroutes; j++)
4483 if (route_addrs[j].interface == ifindex)
4485 if (route_addrs[j].metric > ifmetric)
4486 route_addrs[j].metric = ifmetric;
4492 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
4493 if (route_addrs == NULL)
4494 goto cleanup; /* Memory allocation error, fail gracefully */
4495 route_addrs[numroutes].interface = ifindex;
4496 route_addrs[numroutes].metric = ifmetric;
4497 /* If no IP is found in the next step (for whatever reason)
4498 * then fall back to the magic loopback address.
4500 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
4504 goto cleanup; /* No routes, fall back to the Magic IP */
4505 /* Find the IP address associated with each found interface */
4506 for (i = 0; i < numroutes; i++)
4508 for (k = adapters; k != NULL; k = k->Next)
4510 char *ip = k->IpAddressList.IpAddress.String;
4512 if (route_addrs[i].interface == k->Index)
4513 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
4516 /* Allocate a hostent and enough memory for all the IPs,
4517 * including the NULL at the end of the list.
4519 hostlist = WS_create_he(hostname, 1, numroutes+1, TRUE);
4520 if (hostlist == NULL)
4521 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
4522 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
4523 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
4524 hostlist->h_addrtype = AF_INET;
4525 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
4526 /* Reorder the entries when placing them in the host list, Windows expects
4527 * the IP list in order from highest priority to lowest (the critical thing
4528 * is that most applications expect the first IP to be the default route).
4531 for (i = 0; i < numroutes; i++)
4533 struct in_addr addr;
4534 int metric = 0xFFFF;
4536 memcpy(&addr, magic_loopback_addr, 4);
4537 for (j = 0; j < numroutes; j++)
4539 int this_metric = route_addrs[j].metric;
4541 if (this_metric > last_metric && this_metric < metric)
4543 addr = route_addrs[j].addr;
4544 metric = this_metric;
4547 last_metric = metric;
4548 (*(struct in_addr *) hostlist->h_addr_list[i]) = addr;
4551 /* Cleanup all allocated memory except the address list,
4552 * the address list is used by the calling app.
4555 HeapFree(GetProcessHeap(), 0, route_addrs);
4556 HeapFree(GetProcessHeap(), 0, adapters);
4557 HeapFree(GetProcessHeap(), 0, routes);
4561 /***********************************************************************
4562 * gethostbyname (WS2_32.52)
4564 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
4566 struct WS_hostent *retval = NULL;
4567 struct hostent* host;
4568 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4571 struct hostent hostentry;
4572 int locerr = ENOBUFS;
4576 SetLastError(WSANOTINITIALISED);
4579 if( gethostname( hostname, 100) == -1) {
4580 SetLastError( WSAENOBUFS); /* appropriate ? */
4583 if( !name || !name[0]) {
4586 /* If the hostname of the local machine is requested then return the
4587 * complete list of local IP addresses */
4588 if(strcmp(name, hostname) == 0)
4589 retval = WS_get_local_ips(hostname);
4590 /* If any other hostname was requested (or the routing table lookup failed)
4591 * then return the IP found by the host OS */
4594 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4596 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
4598 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
4599 if( res != ERANGE) break;
4601 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
4603 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
4605 EnterCriticalSection( &csWSgetXXXbyYYY );
4606 host = gethostbyname(name);
4607 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
4609 if (host) retval = WS_dup_he(host);
4610 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4611 HeapFree(GetProcessHeap(),0,extrabuf);
4613 LeaveCriticalSection( &csWSgetXXXbyYYY );
4616 if (retval && retval->h_addr_list[0][0] == 127 &&
4617 strcmp(name, "localhost") != 0)
4619 /* hostname != "localhost" but has loopback address. replace by our
4620 * special address.*/
4621 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
4623 TRACE( "%s ret %p\n", debugstr_a(name), retval );
4628 /***********************************************************************
4629 * getprotobyname (WS2_32.53)
4631 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
4633 struct WS_protoent* retval = NULL;
4634 #ifdef HAVE_GETPROTOBYNAME
4635 struct protoent* proto;
4636 EnterCriticalSection( &csWSgetXXXbyYYY );
4637 if( (proto = getprotobyname(name)) != NULL )
4639 retval = WS_dup_pe(proto);
4642 MESSAGE("protocol %s not found; You might want to add "
4643 "this to /etc/protocols\n", debugstr_a(name) );
4644 SetLastError(WSANO_DATA);
4646 LeaveCriticalSection( &csWSgetXXXbyYYY );
4648 TRACE( "%s ret %p\n", debugstr_a(name), retval );
4653 /***********************************************************************
4654 * getprotobynumber (WS2_32.54)
4656 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
4658 struct WS_protoent* retval = NULL;
4659 #ifdef HAVE_GETPROTOBYNUMBER
4660 struct protoent* proto;
4661 EnterCriticalSection( &csWSgetXXXbyYYY );
4662 if( (proto = getprotobynumber(number)) != NULL )
4664 retval = WS_dup_pe(proto);
4667 MESSAGE("protocol number %d not found; You might want to add "
4668 "this to /etc/protocols\n", number );
4669 SetLastError(WSANO_DATA);
4671 LeaveCriticalSection( &csWSgetXXXbyYYY );
4673 TRACE("%i ret %p\n", number, retval);
4678 /***********************************************************************
4679 * getservbyname (WS2_32.55)
4681 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
4683 struct WS_servent* retval = NULL;
4684 struct servent* serv;
4686 char *proto_str = NULL;
4688 if (!(name_str = strdup_lower(name))) return NULL;
4690 if (proto && *proto)
4692 if (!(proto_str = strdup_lower(proto)))
4694 HeapFree( GetProcessHeap(), 0, name_str );
4699 EnterCriticalSection( &csWSgetXXXbyYYY );
4700 serv = getservbyname(name_str, proto_str);
4703 retval = WS_dup_se(serv);
4705 else SetLastError(WSANO_DATA);
4706 LeaveCriticalSection( &csWSgetXXXbyYYY );
4707 HeapFree( GetProcessHeap(), 0, proto_str );
4708 HeapFree( GetProcessHeap(), 0, name_str );
4709 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
4713 /***********************************************************************
4714 * freeaddrinfo (WS2_32.@)
4716 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
4719 struct WS_addrinfo *next;
4721 HeapFree(GetProcessHeap(),0,res->ai_canonname);
4722 HeapFree(GetProcessHeap(),0,res->ai_addr);
4723 next = res->ai_next;
4724 HeapFree(GetProcessHeap(),0,res);
4729 /* helper functions for getaddrinfo()/getnameinfo() */
4730 static int convert_aiflag_w2u(int winflags) {
4734 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
4735 if (ws_aiflag_map[i][0] & winflags) {
4736 unixflags |= ws_aiflag_map[i][1];
4737 winflags &= ~ws_aiflag_map[i][0];
4740 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
4744 static int convert_niflag_w2u(int winflags) {
4748 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
4749 if (ws_niflag_map[i][0] & winflags) {
4750 unixflags |= ws_niflag_map[i][1];
4751 winflags &= ~ws_niflag_map[i][0];
4754 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
4758 static int convert_aiflag_u2w(int unixflags) {
4762 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
4763 if (ws_aiflag_map[i][1] & unixflags) {
4764 winflags |= ws_aiflag_map[i][0];
4765 unixflags &= ~ws_aiflag_map[i][1];
4767 if (unixflags) /* will warn usually */
4768 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
4772 static int convert_eai_u2w(int unixret) {
4775 for (i=0;ws_eai_map[i][0];i++)
4776 if (ws_eai_map[i][1] == unixret)
4777 return ws_eai_map[i][0];
4781 /***********************************************************************
4782 * getaddrinfo (WS2_32.@)
4784 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
4786 #ifdef HAVE_GETADDRINFO
4787 struct addrinfo *unixaires = NULL;
4789 struct addrinfo unixhints, *punixhints = NULL;
4790 CHAR *node = NULL, *serv = NULL;
4793 if (!(node = strdup_lower(nodename))) return WSA_NOT_ENOUGH_MEMORY;
4796 if (!(serv = strdup_lower(servname))) {
4797 HeapFree(GetProcessHeap(), 0, node);
4798 return WSA_NOT_ENOUGH_MEMORY;
4803 punixhints = &unixhints;
4805 memset(&unixhints, 0, sizeof(unixhints));
4806 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
4807 if (hints->ai_family == 0) /* wildcard, specific to getaddrinfo() */
4808 punixhints->ai_family = 0;
4810 punixhints->ai_family = convert_af_w2u(hints->ai_family);
4811 if (hints->ai_socktype == 0) /* wildcard, specific to getaddrinfo() */
4812 punixhints->ai_socktype = 0;
4814 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
4815 if (hints->ai_protocol == 0) /* wildcard, specific to getaddrinfo() */
4816 punixhints->ai_protocol = 0;
4818 punixhints->ai_protocol = convert_proto_w2u(hints->ai_protocol);
4821 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
4822 result = getaddrinfo(nodename, servname, punixhints, &unixaires);
4824 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
4826 HeapFree(GetProcessHeap(), 0, node);
4827 HeapFree(GetProcessHeap(), 0, serv);
4830 struct addrinfo *xuai = unixaires;
4831 struct WS_addrinfo **xai = res;
4835 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
4841 *xai = ai;xai = &ai->ai_next;
4842 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
4843 ai->ai_family = convert_af_u2w(xuai->ai_family);
4844 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
4845 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
4846 if (xuai->ai_canonname) {
4847 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
4848 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
4849 if (!ai->ai_canonname)
4851 strcpy(ai->ai_canonname,xuai->ai_canonname);
4853 len = xuai->ai_addrlen;
4854 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
4857 ai->ai_addrlen = len;
4859 int winlen = ai->ai_addrlen;
4861 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
4862 ai->ai_addrlen = winlen;
4866 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
4869 ai->ai_addrlen = len;
4871 xuai = xuai->ai_next;
4873 freeaddrinfo(unixaires);
4875 result = convert_eai_u2w(result);
4881 if (*res) WS_freeaddrinfo(*res);
4882 if (unixaires) freeaddrinfo(unixaires);
4884 return WSA_NOT_ENOUGH_MEMORY;
4886 FIXME("getaddrinfo() failed, not found during buildtime.\n");
4891 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
4893 struct WS_addrinfoW *ret;
4895 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
4896 ret->ai_flags = ai->ai_flags;
4897 ret->ai_family = ai->ai_family;
4898 ret->ai_socktype = ai->ai_socktype;
4899 ret->ai_protocol = ai->ai_protocol;
4900 ret->ai_addrlen = ai->ai_addrlen;
4901 ret->ai_canonname = NULL;
4902 ret->ai_addr = NULL;
4903 ret->ai_next = NULL;
4904 if (ai->ai_canonname)
4906 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
4907 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
4909 HeapFree(GetProcessHeap(), 0, ret);
4912 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
4916 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
4918 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
4919 HeapFree(GetProcessHeap(), 0, ret);
4922 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
4927 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
4929 struct WS_addrinfoW *ret, *infoW;
4931 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
4932 while (info->ai_next)
4934 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
4939 infoW = infoW->ai_next;
4940 info = info->ai_next;
4945 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
4947 struct WS_addrinfo *ret;
4949 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
4950 ret->ai_flags = ai->ai_flags;
4951 ret->ai_family = ai->ai_family;
4952 ret->ai_socktype = ai->ai_socktype;
4953 ret->ai_protocol = ai->ai_protocol;
4954 ret->ai_addrlen = ai->ai_addrlen;
4955 ret->ai_canonname = NULL;
4956 ret->ai_addr = NULL;
4957 ret->ai_next = NULL;
4958 if (ai->ai_canonname)
4960 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
4961 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
4963 HeapFree(GetProcessHeap(), 0, ret);
4966 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
4970 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
4972 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
4973 HeapFree(GetProcessHeap(), 0, ret);
4976 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
4981 /***********************************************************************
4982 * GetAddrInfoW (WS2_32.@)
4984 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
4987 char *nodenameA, *servnameA = NULL;
4988 struct WS_addrinfo *resA, *hintsA = NULL;
4990 if (!nodename) return WSAHOST_NOT_FOUND;
4992 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
4993 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
4994 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
4998 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
4999 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
5001 HeapFree(GetProcessHeap(), 0, nodenameA);
5004 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
5007 if (hints) hintsA = addrinfo_WtoA(hints);
5008 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
5009 WS_freeaddrinfo(hintsA);
5013 *res = addrinfo_list_AtoW(resA);
5014 WS_freeaddrinfo(resA);
5017 HeapFree(GetProcessHeap(), 0, nodenameA);
5018 HeapFree(GetProcessHeap(), 0, servnameA);
5022 /***********************************************************************
5023 * FreeAddrInfoW (WS2_32.@)
5025 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
5030 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
5031 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
5033 HeapFree(GetProcessHeap(), 0, ai);
5038 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
5039 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
5041 #ifdef HAVE_GETNAMEINFO
5043 union generic_unix_sockaddr sa_u;
5046 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
5047 serv, servlen, flags);
5049 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
5052 WSASetLastError(WSAEFAULT);
5053 return WSA_NOT_ENOUGH_MEMORY;
5055 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
5056 return convert_eai_u2w(ret);
5058 FIXME("getnameinfo() failed, not found during buildtime.\n");
5063 int WINAPI GetNameInfoW(const SOCKADDR *sa, WS_socklen_t salen, PWCHAR host,
5064 DWORD hostlen, PWCHAR serv, DWORD servlen, INT flags)
5067 char *hostA = NULL, *servA = NULL;
5069 if (host && (!(hostA = HeapAlloc(GetProcessHeap(), 0, hostlen)))) return EAI_MEMORY;
5070 if (serv && (!(servA = HeapAlloc(GetProcessHeap(), 0, servlen))))
5072 HeapFree(GetProcessHeap(), 0, hostA);
5076 ret = WS_getnameinfo(sa, salen, hostA, hostlen, servA, servlen, flags);
5079 if (host) MultiByteToWideChar(CP_ACP, 0, hostA, -1, host, hostlen);
5080 if (serv) MultiByteToWideChar(CP_ACP, 0, servA, -1, serv, servlen);
5083 HeapFree(GetProcessHeap(), 0, hostA);
5084 HeapFree(GetProcessHeap(), 0, servA);
5088 /***********************************************************************
5089 * getservbyport (WS2_32.56)
5091 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
5093 struct WS_servent* retval = NULL;
5094 #ifdef HAVE_GETSERVBYPORT
5095 struct servent* serv;
5096 char *proto_str = NULL;
5098 if (proto && *proto)
5100 if (!(proto_str = strdup_lower(proto))) return NULL;
5102 EnterCriticalSection( &csWSgetXXXbyYYY );
5103 if( (serv = getservbyport(port, proto_str)) != NULL ) {
5104 retval = WS_dup_se(serv);
5106 else SetLastError(WSANO_DATA);
5107 LeaveCriticalSection( &csWSgetXXXbyYYY );
5108 HeapFree( GetProcessHeap(), 0, proto_str );
5110 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
5115 /***********************************************************************
5116 * gethostname (WS2_32.57)
5118 int WINAPI WS_gethostname(char *name, int namelen)
5120 TRACE("name %p, len %d\n", name, namelen);
5122 if (gethostname(name, namelen) == 0)
5124 TRACE("<- '%s'\n", name);
5127 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
5128 TRACE("<- ERROR !\n");
5129 return SOCKET_ERROR;
5133 /* ------------------------------------- Windows sockets extensions -- *
5135 * ------------------------------------------------------------------- */
5137 /***********************************************************************
5138 * WSAEnumNetworkEvents (WS2_32.36)
5140 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
5144 int errors[FD_MAX_EVENTS];
5146 TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
5148 SERVER_START_REQ( get_socket_event )
5150 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5151 req->service = TRUE;
5152 req->c_event = wine_server_obj_handle( hEvent );
5153 wine_server_set_reply( req, errors, sizeof(errors) );
5154 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
5159 for (i = 0; i < FD_MAX_EVENTS; i++)
5160 lpEvent->iErrorCode[i] = NtStatusToWSAError(errors[i]);
5163 SetLastError(WSAEINVAL);
5164 return SOCKET_ERROR;
5167 /***********************************************************************
5168 * WSAEventSelect (WS2_32.39)
5170 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
5174 TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
5176 SERVER_START_REQ( set_socket_event )
5178 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5180 req->event = wine_server_obj_handle( hEvent );
5183 ret = wine_server_call( req );
5187 SetLastError(WSAEINVAL);
5188 return SOCKET_ERROR;
5191 /**********************************************************************
5192 * WSAGetOverlappedResult (WS2_32.40)
5194 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
5195 LPDWORD lpcbTransfer, BOOL fWait,
5200 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
5201 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
5203 if ( lpOverlapped == NULL )
5205 ERR( "Invalid pointer\n" );
5206 WSASetLastError(WSA_INVALID_PARAMETER);
5210 status = lpOverlapped->Internal;
5211 if (status == STATUS_PENDING)
5215 SetLastError( WSA_IO_INCOMPLETE );
5219 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
5220 INFINITE ) == WAIT_FAILED)
5222 status = lpOverlapped->Internal;
5226 *lpcbTransfer = lpOverlapped->InternalHigh;
5229 *lpdwFlags = lpOverlapped->u.s.Offset;
5231 if (status) SetLastError( RtlNtStatusToDosError(status) );
5236 /***********************************************************************
5237 * WSAAsyncSelect (WS2_32.101)
5239 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
5243 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
5245 SERVER_START_REQ( set_socket_event )
5247 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5250 req->window = wine_server_user_handle( hWnd );
5252 ret = wine_server_call( req );
5256 SetLastError(WSAEINVAL);
5257 return SOCKET_ERROR;
5260 /***********************************************************************
5261 * WSACreateEvent (WS2_32.31)
5264 WSAEVENT WINAPI WSACreateEvent(void)
5266 /* Create a manual-reset event, with initial state: unsignaled */
5269 return CreateEventW(NULL, TRUE, FALSE, NULL);
5272 /***********************************************************************
5273 * WSACloseEvent (WS2_32.29)
5276 BOOL WINAPI WSACloseEvent(WSAEVENT event)
5278 TRACE ("event=%p\n", event);
5280 return CloseHandle(event);
5283 /***********************************************************************
5284 * WSASocketA (WS2_32.78)
5287 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
5288 LPWSAPROTOCOL_INFOA lpProtocolInfo,
5289 GROUP g, DWORD dwFlags)
5292 WSAPROTOCOL_INFOW info;
5294 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
5295 af, type, protocol, lpProtocolInfo, g, dwFlags);
5297 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
5299 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
5300 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
5301 info.szProtocol, WSAPROTOCOL_LEN + 1);
5305 WSASetLastError( WSAEINVAL);
5306 return SOCKET_ERROR;
5309 return WSASocketW(af, type, protocol, &info, g, dwFlags);
5312 /***********************************************************************
5313 * WSASocketW (WS2_32.79)
5316 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
5317 LPWSAPROTOCOL_INFOW lpProtocolInfo,
5318 GROUP g, DWORD dwFlags)
5323 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
5324 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
5327 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
5328 af, type, protocol, lpProtocolInfo, g, dwFlags );
5330 /* hack for WSADuplicateSocket */
5331 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
5332 ret = lpProtocolInfo->dwCatalogEntryId;
5333 TRACE("\tgot duplicate %04lx\n", ret);
5337 /* convert the socket family and type */
5338 af = convert_af_w2u(af);
5339 type = convert_socktype_w2u(type);
5343 if (af == FROM_PROTOCOL_INFO)
5344 af = lpProtocolInfo->iAddressFamily;
5345 if (type == FROM_PROTOCOL_INFO)
5346 type = lpProtocolInfo->iSocketType;
5347 if (protocol == FROM_PROTOCOL_INFO)
5348 protocol = lpProtocolInfo->iProtocol;
5351 if ( af == AF_UNSPEC) /* did they not specify the address family? */
5355 if (type == SOCK_STREAM) { af = AF_INET; break; }
5357 if (type == SOCK_DGRAM) { af = AF_INET; break; }
5358 default: SetLastError(WSAEPROTOTYPE); return INVALID_SOCKET;
5361 SERVER_START_REQ( create_socket )
5365 req->protocol = protocol;
5366 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
5367 req->attributes = OBJ_INHERIT;
5368 req->flags = dwFlags;
5369 set_error( wine_server_call( req ) );
5370 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
5375 TRACE("\tcreated %04lx\n", ret );
5379 if (GetLastError() == WSAEACCES) /* raw socket denied */
5381 if (type == SOCK_RAW)
5382 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
5384 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
5385 SetLastError(WSAESOCKTNOSUPPORT);
5388 WARN("\t\tfailed!\n");
5389 return INVALID_SOCKET;
5392 /***********************************************************************
5393 * WSAJoinLeaf (WS2_32.58)
5396 SOCKET WINAPI WSAJoinLeaf(
5398 const struct WS_sockaddr *addr,
5400 LPWSABUF lpCallerData,
5401 LPWSABUF lpCalleeData,
5407 return INVALID_SOCKET;
5410 /***********************************************************************
5411 * __WSAFDIsSet (WS2_32.151)
5413 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
5415 int i = set->fd_count;
5417 TRACE("(%ld,%p(%i))\n", s, set, i);
5420 if (set->fd_array[i] == s) return 1;
5424 /***********************************************************************
5425 * WSAIsBlocking (WS2_32.114)
5427 BOOL WINAPI WSAIsBlocking(void)
5429 /* By default WinSock should set all its sockets to non-blocking mode
5430 * and poll in PeekMessage loop when processing "blocking" ones. This
5431 * function is supposed to tell if the program is in this loop. Our
5432 * blocking calls are truly blocking so we always return FALSE.
5434 * Note: It is allowed to call this function without prior WSAStartup().
5441 /***********************************************************************
5442 * WSACancelBlockingCall (WS2_32.113)
5444 INT WINAPI WSACancelBlockingCall(void)
5450 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
5452 FIXME("How was this called?\n");
5457 /***********************************************************************
5458 * WSASetBlockingHook (WS2_32.109)
5460 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
5462 FARPROC prev = blocking_hook;
5463 blocking_hook = lpBlockFunc;
5464 TRACE("hook %p\n", lpBlockFunc);
5469 /***********************************************************************
5470 * WSAUnhookBlockingHook (WS2_32.110)
5472 INT WINAPI WSAUnhookBlockingHook(void)
5474 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
5479 /* ----------------------------------- end of API stuff */
5481 /* ----------------------------------- helper functions -
5483 * TODO: Merge WS_dup_..() stuff into one function that
5484 * would operate with a generic structure containing internal
5485 * pointers (via a template of some kind).
5488 static int list_size(char** l, int item_size)
5493 j += (item_size) ? item_size : strlen(l[i]) + 1;
5494 j += (i + 1) * sizeof(char*); }
5498 static int list_dup(char** l_src, char** l_to, int item_size)
5503 for (i = 0; l_src[i]; i++) ;
5504 p = (char *)(l_to + i + 1);
5505 for (i = 0; l_src[i]; i++)
5507 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
5508 memcpy(p, l_src[i], count);
5513 return p - (char *)l_to;
5518 /* create a hostent entry
5520 * Creates the entry with enough memory for the name, aliases
5521 * addresses, and the address pointers. Also copies the name
5522 * and sets up all the pointers. If "fill_addresses" is set then
5523 * sufficient memory for the addresses is also allocated and the
5524 * address pointers are set to this memory.
5526 * NOTE: The alias and address lists must be allocated with room
5527 * for the NULL item terminating the list. This is true even if
5528 * the list has no items ("aliases" and "addresses" must be
5529 * at least "1", a truly empty list is invalid).
5531 static struct WS_hostent *WS_create_he(char *name, int aliases, int addresses, int fill_addresses)
5533 struct WS_hostent *p_to;
5536 int size = (sizeof(struct WS_hostent) +
5538 sizeof(char *)*aliases +
5539 sizeof(char *)*addresses);
5541 /* Allocate enough memory for the addresses */
5543 size += sizeof(struct in_addr)*addresses;
5545 if (!(p_to = check_buffer_he(size))) return NULL;
5546 memset(p_to, 0, size);
5548 p = (char *)(p_to + 1);
5553 p_to->h_aliases = (char **)p;
5554 p += sizeof(char *)*aliases;
5555 p_to->h_addr_list = (char **)p;
5556 p += sizeof(char *)*addresses;
5561 /* NOTE: h_aliases must be filled in manually, leave these
5562 * pointers NULL (already set to NULL by memset earlier).
5565 /* Fill in the list of address pointers */
5566 for (i = 0; i < addresses; i++)
5567 p_to->h_addr_list[i] = (p += sizeof(struct in_addr));
5568 p += sizeof(struct in_addr);
5573 /* duplicate hostent entry
5574 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
5575 * Ditto for protoent and servent.
5577 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
5579 int addresses = list_size(p_he->h_addr_list, p_he->h_length);
5580 int aliases = list_size(p_he->h_aliases, 0);
5581 struct WS_hostent *p_to;
5583 p_to = WS_create_he(p_he->h_name, aliases, addresses, FALSE);
5585 if (!p_to) return NULL;
5586 p_to->h_addrtype = p_he->h_addrtype;
5587 p_to->h_length = p_he->h_length;
5589 list_dup(p_he->h_aliases, p_to->h_aliases, 0);
5590 list_dup(p_he->h_addr_list, p_to->h_addr_list, p_he->h_length);
5594 /* ----- protoent */
5596 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
5599 struct WS_protoent *p_to;
5601 int size = (sizeof(*p_pe) +
5602 strlen(p_pe->p_name) + 1 +
5603 list_size(p_pe->p_aliases, 0));
5605 if (!(p_to = check_buffer_pe(size))) return NULL;
5606 p_to->p_proto = p_pe->p_proto;
5608 p = (char *)(p_to + 1);
5610 strcpy(p, p_pe->p_name);
5613 p_to->p_aliases = (char **)p;
5614 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
5620 static struct WS_servent *WS_dup_se(const struct servent* p_se)
5623 struct WS_servent *p_to;
5625 int size = (sizeof(*p_se) +
5626 strlen(p_se->s_proto) + 1 +
5627 strlen(p_se->s_name) + 1 +
5628 list_size(p_se->s_aliases, 0));
5630 if (!(p_to = check_buffer_se(size))) return NULL;
5631 p_to->s_port = p_se->s_port;
5633 p = (char *)(p_to + 1);
5635 strcpy(p, p_se->s_name);
5639 strcpy(p, p_se->s_proto);
5642 p_to->s_aliases = (char **)p;
5643 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
5648 /***********************************************************************
5649 * WSARecv (WS2_32.67)
5651 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5652 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
5653 LPWSAOVERLAPPED lpOverlapped,
5654 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
5656 return WS2_recv_base(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
5657 NULL, NULL, lpOverlapped, lpCompletionRoutine, NULL);
5660 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5661 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
5662 struct WS_sockaddr *lpFrom,
5663 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
5664 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
5665 LPWSABUF lpControlBuffer )
5667 unsigned int i, options;
5669 struct ws2_async *wsa;
5670 DWORD timeout_start = GetTickCount();
5671 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
5673 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
5674 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
5675 (lpFromlen ? *lpFromlen : -1),
5676 lpOverlapped, lpCompletionRoutine);
5678 fd = get_sock_fd( s, FILE_READ_DATA, &options );
5679 TRACE( "fd=%d, options=%x\n", fd, options );
5681 if (fd == -1) return SOCKET_ERROR;
5683 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
5689 wsa->hSocket = SOCKET2HANDLE(s);
5690 wsa->flags = *lpFlags;
5691 wsa->lpFlags = lpFlags;
5693 wsa->addrlen.ptr = lpFromlen;
5694 wsa->control = lpControlBuffer;
5695 wsa->n_iovecs = dwBufferCount;
5696 wsa->first_iovec = 0;
5697 for (i = 0; i < dwBufferCount; i++)
5699 /* check buffer first to trigger write watches */
5700 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
5705 wsa->iovec[i].iov_base = lpBuffers[i].buf;
5706 wsa->iovec[i].iov_len = lpBuffers[i].len;
5711 n = WS2_recv( fd, wsa );
5714 if (errno == EINTR) continue;
5715 if (errno != EAGAIN)
5717 int loc_errno = errno;
5719 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
5723 else if (lpNumberOfBytesRecvd) *lpNumberOfBytesRecvd = n;
5725 if ((lpOverlapped || lpCompletionRoutine) &&
5726 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
5728 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
5730 wsa->user_overlapped = lpOverlapped;
5731 wsa->completion_func = lpCompletionRoutine;
5732 release_sock_fd( s, fd );
5736 iosb->u.Status = STATUS_PENDING;
5737 iosb->Information = 0;
5739 SERVER_START_REQ( register_async )
5741 req->type = ASYNC_TYPE_READ;
5742 req->async.handle = wine_server_obj_handle( wsa->hSocket );
5743 req->async.callback = wine_server_client_ptr( WS2_async_recv );
5744 req->async.iosb = wine_server_client_ptr( iosb );
5745 req->async.arg = wine_server_client_ptr( wsa );
5746 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
5747 req->async.cvalue = cvalue;
5748 err = wine_server_call( req );
5752 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
5753 WSASetLastError( NtStatusToWSAError( err ));
5754 return SOCKET_ERROR;
5757 iosb->u.Status = STATUS_SUCCESS;
5758 iosb->Information = n;
5759 if (!wsa->completion_func)
5761 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
5762 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
5763 HeapFree( GetProcessHeap(), 0, wsa );
5765 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
5766 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
5767 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5773 if ( _is_blocking(s) )
5776 int timeout = GET_RCVTIMEO(fd);
5779 timeout -= GetTickCount() - timeout_start;
5780 if (timeout < 0) timeout = 0;
5784 pfd.events = POLLIN;
5785 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
5787 if (!timeout || !poll( &pfd, 1, timeout ))
5790 /* a timeout is not fatal */
5791 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5797 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5798 err = WSAEWOULDBLOCK;
5803 TRACE(" -> %i bytes\n", n);
5804 HeapFree( GetProcessHeap(), 0, wsa );
5805 release_sock_fd( s, fd );
5806 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5811 HeapFree( GetProcessHeap(), 0, wsa );
5812 release_sock_fd( s, fd );
5813 WARN(" -> ERROR %d\n", err);
5814 WSASetLastError( err );
5815 return SOCKET_ERROR;
5818 /***********************************************************************
5819 * WSARecvFrom (WS2_32.69)
5821 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5822 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
5823 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
5824 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
5827 return WS2_recv_base( s, lpBuffers, dwBufferCount,
5828 lpNumberOfBytesRecvd, lpFlags,
5830 lpOverlapped, lpCompletionRoutine, NULL );
5833 /***********************************************************************
5834 * WSCInstallProvider (WS2_32.88)
5836 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
5837 LPCWSTR lpszProviderDllPath,
5838 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
5839 DWORD dwNumberOfEntries,
5842 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
5843 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
5844 dwNumberOfEntries, lpErrno);
5850 /***********************************************************************
5851 * WSCDeinstallProvider (WS2_32.83)
5853 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
5855 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
5861 /***********************************************************************
5862 * WSAAccept (WS2_32.26)
5864 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
5865 LPCONDITIONPROC lpfnCondition, DWORD_PTR dwCallbackData)
5868 int ret = 0, size = 0;
5869 WSABUF CallerId, CallerData, CalleeId, CalleeData;
5870 /* QOS SQOS, GQOS; */
5873 SOCKADDR src_addr, dst_addr;
5875 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
5876 s, addr, addrlen, lpfnCondition, dwCallbackData);
5879 size = sizeof(src_addr);
5880 cs = WS_accept(s, &src_addr, &size);
5882 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
5884 if (!lpfnCondition) return cs;
5886 CallerId.buf = (char *)&src_addr;
5887 CallerId.len = sizeof(src_addr);
5889 CallerData.buf = NULL;
5892 WS_getsockname(cs, &dst_addr, &size);
5894 CalleeId.buf = (char *)&dst_addr;
5895 CalleeId.len = sizeof(dst_addr);
5898 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
5899 &CalleeId, &CalleeData, &g, dwCallbackData);
5904 if (addr && addrlen)
5905 memcpy(addr, &src_addr, (*addrlen > size) ? size : *addrlen );
5908 SERVER_START_REQ( set_socket_deferred )
5910 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5911 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
5912 if ( !wine_server_call_err ( req ) )
5914 SetLastError( WSATRY_AGAIN );
5915 WS_closesocket( cs );
5919 return SOCKET_ERROR;
5922 SetLastError(WSAECONNREFUSED);
5923 return SOCKET_ERROR;
5925 FIXME("Unknown return type from Condition function\n");
5926 SetLastError(WSAENOTSOCK);
5927 return SOCKET_ERROR;
5931 /***********************************************************************
5932 * WSADuplicateSocketA (WS2_32.32)
5934 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
5938 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
5939 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
5940 /* FIXME: WS_getsockopt(s, WS_SOL_SOCKET, SO_PROTOCOL_INFO, lpProtocolInfo, sizeof(*lpProtocolInfo)); */
5941 /* I don't know what the real Windoze does next, this is a hack */
5942 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
5943 * the target use the global duplicate, or we could copy a reference to us to the structure
5944 * and let the target duplicate it from us, but let's do it as simple as possible */
5945 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
5946 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
5947 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
5948 0, FALSE, DUPLICATE_SAME_ACCESS);
5949 CloseHandle(hProcess);
5950 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
5954 /***********************************************************************
5955 * WSADuplicateSocketW (WS2_32.33)
5957 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
5961 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
5963 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
5964 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
5965 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
5966 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
5967 0, FALSE, DUPLICATE_SAME_ACCESS);
5968 CloseHandle(hProcess);
5969 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
5973 /***********************************************************************
5974 * WSAInstallServiceClassA (WS2_32.48)
5976 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
5978 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
5979 WSASetLastError(WSAEACCES);
5980 return SOCKET_ERROR;
5983 /***********************************************************************
5984 * WSAInstallServiceClassW (WS2_32.49)
5986 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
5988 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
5989 WSASetLastError(WSAEACCES);
5990 return SOCKET_ERROR;
5993 /***********************************************************************
5994 * WSARemoveServiceClass (WS2_32.70)
5996 int WINAPI WSARemoveServiceClass(LPGUID info)
5998 FIXME("Request to remove service %p\n",info);
5999 WSASetLastError(WSATYPE_NOT_FOUND);
6000 return SOCKET_ERROR;
6003 /***********************************************************************
6004 * inet_ntop (WS2_32.@)
6006 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
6008 #ifdef HAVE_INET_NTOP
6009 struct WS_in6_addr *in6;
6010 struct WS_in_addr *in;
6013 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
6016 WSASetLastError( STATUS_INVALID_PARAMETER );
6025 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
6031 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
6035 WSASetLastError( WSAEAFNOSUPPORT );
6039 if (!pdst) WSASetLastError( STATUS_INVALID_PARAMETER );
6042 FIXME( "not supported on this platform\n" );
6043 WSASetLastError( WSAEAFNOSUPPORT );
6048 /***********************************************************************
6049 * WSAStringToAddressA (WS2_32.80)
6051 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
6053 LPWSAPROTOCOL_INFOA lpProtocolInfo,
6054 LPSOCKADDR lpAddress,
6055 LPINT lpAddressLength)
6058 LPSTR workBuffer=NULL,ptrPort;
6060 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
6061 lpProtocolInfo, lpAddress, lpAddressLength );
6063 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
6067 WSASetLastError(WSAEINVAL);
6068 return SOCKET_ERROR;
6072 FIXME("ProtocolInfo not implemented.\n");
6074 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
6075 strlen(AddressString) + 1);
6078 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6079 return SOCKET_ERROR;
6082 strcpy(workBuffer, AddressString);
6084 switch(AddressFamily)
6088 struct in_addr inetaddr;
6090 /* If lpAddressLength is too small, tell caller the size we need */
6091 if (*lpAddressLength < sizeof(SOCKADDR_IN))
6093 *lpAddressLength = sizeof(SOCKADDR_IN);
6097 *lpAddressLength = sizeof(SOCKADDR_IN);
6098 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
6100 ((LPSOCKADDR_IN)lpAddress)->sin_family = AF_INET;
6102 ptrPort = strchr(workBuffer, ':');
6105 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
6110 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
6113 if(inet_aton(workBuffer, &inetaddr) > 0)
6115 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
6126 struct in6_addr inetaddr;
6127 /* If lpAddressLength is too small, tell caller the size we need */
6128 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
6130 *lpAddressLength = sizeof(SOCKADDR_IN6);
6134 #ifdef HAVE_INET_PTON
6135 *lpAddressLength = sizeof(SOCKADDR_IN6);
6136 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
6138 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
6140 /* This one is a bit tricky. An IPv6 address contains colons, so the
6141 * check from IPv4 doesn't work like that. However, IPv6 addresses that
6142 * contain a port are written with braces like [fd12:3456:7890::1]:12345
6143 * so what we will do is to look for ']', check if the next char is a
6144 * colon, and if it is, parse the port as in IPv4. */
6146 ptrPort = strchr(workBuffer, ']');
6147 if(ptrPort && *(++ptrPort) == ':')
6149 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort+1));
6154 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
6157 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
6159 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
6160 sizeof(struct in6_addr));
6164 #endif /* HAVE_INET_PTON */
6170 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
6171 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
6175 HeapFree(GetProcessHeap(), 0, workBuffer);
6178 WSASetLastError(res);
6179 return SOCKET_ERROR;
6182 /***********************************************************************
6183 * WSAStringToAddressW (WS2_32.81)
6185 * Does anybody know if this function allows to use Hebrew/Arabic/Chinese... digits?
6186 * If this should be the case, it would be required to map these digits
6187 * to Unicode digits (0-9) using FoldString first.
6189 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
6191 LPWSAPROTOCOL_INFOW lpProtocolInfo,
6192 LPSOCKADDR lpAddress,
6193 LPINT lpAddressLength)
6196 LPSTR workBuffer=NULL;
6197 WSAPROTOCOL_INFOA infoA;
6198 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
6200 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
6201 lpAddress, lpAddressLength );
6203 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
6205 /* if ProtocolInfo is available - convert to ANSI variant */
6208 lpProtoInfoA = &infoA;
6209 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
6211 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
6212 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
6214 WSASetLastError( WSAEINVAL);
6215 return SOCKET_ERROR;
6221 /* Translate AddressString to ANSI code page - assumes that only
6222 standard digits 0-9 are used with this API call */
6223 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
6224 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
6228 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
6229 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
6230 lpAddress,lpAddressLength);
6231 HeapFree( GetProcessHeap(), 0, workBuffer );
6235 res = WSA_NOT_ENOUGH_MEMORY;
6240 WSASetLastError(res);
6241 return SOCKET_ERROR;
6244 /***********************************************************************
6245 * WSAAddressToStringA (WS2_32.27)
6247 * See WSAAddressToStringW
6249 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
6250 LPWSAPROTOCOL_INFOA info, LPSTR string,
6254 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
6257 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
6259 if (!sockaddr) return SOCKET_ERROR;
6260 if (!string || !lenstr) return SOCKET_ERROR;
6262 switch(sockaddr->sa_family)
6265 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
6266 sprintf( buffer, "%u.%u.%u.%u:%u",
6267 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
6268 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
6269 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
6270 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
6271 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
6273 p = strchr( buffer, ':' );
6274 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
6279 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
6282 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
6283 if ((sockaddr6->sin6_port))
6284 strcpy(buffer, "[");
6285 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, buffer+strlen(buffer), sizeof(buffer)))
6287 WSASetLastError(WSAEINVAL);
6288 return SOCKET_ERROR;
6290 if ((sockaddr6->sin6_scope_id))
6291 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
6292 if ((sockaddr6->sin6_port))
6293 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
6298 WSASetLastError(WSAEINVAL);
6299 return SOCKET_ERROR;
6302 size = strlen( buffer ) + 1;
6307 WSASetLastError(WSAEFAULT);
6308 return SOCKET_ERROR;
6312 strcpy( string, buffer );
6316 /***********************************************************************
6317 * WSAAddressToStringW (WS2_32.28)
6319 * Convert a sockaddr address into a readable address string.
6322 * sockaddr [I] Pointer to a sockaddr structure.
6323 * len [I] Size of the sockaddr structure.
6324 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
6325 * string [I/O] Pointer to a buffer to receive the address string.
6326 * lenstr [I/O] Size of the receive buffer in WCHARs.
6330 * Failure: SOCKET_ERROR
6333 * The 'info' parameter is ignored.
6335 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
6336 LPWSAPROTOCOL_INFOW info, LPWSTR string,
6341 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
6344 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
6347 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
6349 if (ret) return ret;
6351 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
6356 WSASetLastError(WSAEFAULT);
6357 return SOCKET_ERROR;
6361 lstrcpyW( string, buffer );
6365 /***********************************************************************
6366 * WSAEnumNameSpaceProvidersA (WS2_32.34)
6368 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
6370 FIXME( "(%p %p) Stub!\n", len, buffer );
6374 /***********************************************************************
6375 * WSAEnumNameSpaceProvidersW (WS2_32.35)
6377 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
6379 FIXME( "(%p %p) Stub!\n", len, buffer );
6383 /***********************************************************************
6384 * WSAGetQOSByName (WS2_32.41)
6386 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
6388 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
6392 /***********************************************************************
6393 * WSAGetServiceClassInfoA (WS2_32.42)
6395 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
6396 LPWSASERVICECLASSINFOA info )
6398 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
6400 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6401 return SOCKET_ERROR;
6404 /***********************************************************************
6405 * WSAGetServiceClassInfoW (WS2_32.43)
6407 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
6408 LPWSASERVICECLASSINFOW info )
6410 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
6412 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6413 return SOCKET_ERROR;
6416 /***********************************************************************
6417 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
6419 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
6421 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
6422 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6423 return SOCKET_ERROR;
6426 /***********************************************************************
6427 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
6429 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
6431 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
6432 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6433 return SOCKET_ERROR;
6436 /***********************************************************************
6437 * WSALookupServiceBeginA (WS2_32.59)
6439 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
6440 DWORD dwControlFlags,
6443 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
6445 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6446 return SOCKET_ERROR;
6449 /***********************************************************************
6450 * WSALookupServiceBeginW (WS2_32.60)
6452 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
6453 DWORD dwControlFlags,
6456 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
6458 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6459 return SOCKET_ERROR;
6462 /***********************************************************************
6463 * WSALookupServiceBeginW (WS2_32.61)
6465 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
6467 FIXME("(%p) Stub!\n", lookup );
6471 /***********************************************************************
6472 * WSALookupServiceNextA (WS2_32.62)
6474 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
6476 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
6477 WSASetLastError(WSA_E_NO_MORE);
6478 return SOCKET_ERROR;
6481 /***********************************************************************
6482 * WSALookupServiceNextW (WS2_32.63)
6484 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
6486 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
6487 WSASetLastError(WSA_E_NO_MORE);
6488 return SOCKET_ERROR;
6491 /***********************************************************************
6492 * WSANtohl (WS2_32.64)
6494 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
6496 TRACE( "(0x%04lx 0x%08x %p)\n", s, netlong, lphostlong );
6498 if (!lphostlong) return WSAEFAULT;
6500 *lphostlong = ntohl( netlong );
6504 /***********************************************************************
6505 * WSANtohs (WS2_32.65)
6507 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
6509 TRACE( "(0x%04lx 0x%08x %p)\n", s, netshort, lphostshort );
6511 if (!lphostshort) return WSAEFAULT;
6513 *lphostshort = ntohs( netshort );
6517 /***********************************************************************
6518 * WSAProviderConfigChange (WS2_32.66)
6520 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
6521 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
6523 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
6524 return SOCKET_ERROR;
6527 /***********************************************************************
6528 * WSARecvDisconnect (WS2_32.68)
6530 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
6532 TRACE( "(0x%04lx %p)\n", s, disconnectdata );
6534 return WS_shutdown( s, 0 );
6537 /***********************************************************************
6538 * WSASetServiceA (WS2_32.76)
6540 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
6542 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
6546 /***********************************************************************
6547 * WSASetServiceW (WS2_32.77)
6549 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
6551 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
6555 /***********************************************************************
6556 * WSCEnableNSProvider (WS2_32.84)
6558 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
6560 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
6564 /***********************************************************************
6565 * WSCGetProviderPath (WS2_32.86)
6567 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
6569 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
6571 if (!errcode || !provider || !len) return WSAEFAULT;
6573 *errcode = WSAEINVAL;
6574 return SOCKET_ERROR;
6577 /***********************************************************************
6578 * WSCInstallNameSpace (WS2_32.87)
6580 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
6581 DWORD version, LPGUID provider )
6583 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
6584 namespace, version, debugstr_guid(provider) );
6588 /***********************************************************************
6589 * WSCUnInstallNameSpace (WS2_32.89)
6591 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
6593 FIXME("(%p) Stub!\n", lpProviderId);
6597 /***********************************************************************
6598 * WSCWriteProviderOrder (WS2_32.91)
6600 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
6602 FIXME("(%p 0x%08x) Stub!\n", entry, number);
6606 /***********************************************************************
6607 * WSANSPIoctl (WS2_32.91)
6609 INT WINAPI WSANSPIoctl( HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer,
6610 DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer,
6611 LPDWORD lpcbBytesReturned, LPWSACOMPLETION lpCompletion )
6613 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup, dwControlCode,
6614 lpvInBuffer, cbInBuffer, lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpCompletion);
6615 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6616 return SOCKET_ERROR;