comctl32: Use selected image for listbox/editbox for selected item only.
[wine.git] / dlls / ws2_32 / socket.c
bloba6a1b4c780b055c920e891bb823df5d400daacfd
1 /*
2 * based on Windows Sockets 1.1 specs
4 * Copyright (C) 1993,1994,1996,1997 John Brezak, Erik Bos, Alex Korobka.
5 * Copyright (C) 2005 Marcus Meissner
6 * Copyright (C) 2006-2008 Kai Blin
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 * NOTE: If you make any changes to fix a particular app, make sure
23 * they don't break something else like Netscape or telnet and ftp
24 * clients and servers (www.winsite.com got a lot of those).
27 #include "config.h"
28 #include "wine/port.h"
30 #include <stdarg.h>
31 #include <stdio.h>
32 #include <string.h>
33 #include <sys/types.h>
34 #ifdef HAVE_SYS_IPC_H
35 # include <sys/ipc.h>
36 #endif
37 #ifdef HAVE_SYS_IOCTL_H
38 # include <sys/ioctl.h>
39 #endif
40 #ifdef HAVE_SYS_FILIO_H
41 # include <sys/filio.h>
42 #endif
43 #ifdef HAVE_SYS_SOCKIO_H
44 # include <sys/sockio.h>
45 #endif
47 #if defined(__EMX__)
48 # include <sys/so_ioctl.h>
49 #endif
51 #ifdef HAVE_SYS_PARAM_H
52 # include <sys/param.h>
53 #endif
55 #ifdef HAVE_SYS_MSG_H
56 # include <sys/msg.h>
57 #endif
58 #ifdef HAVE_SYS_WAIT_H
59 # include <sys/wait.h>
60 #endif
61 #ifdef HAVE_SYS_UIO_H
62 # include <sys/uio.h>
63 #endif
64 #ifdef HAVE_SYS_SOCKET_H
65 #include <sys/socket.h>
66 #endif
67 #ifdef HAVE_NETINET_IN_H
68 # include <netinet/in.h>
69 #endif
70 #ifdef HAVE_NETINET_TCP_H
71 # include <netinet/tcp.h>
72 #endif
73 #ifdef HAVE_ARPA_INET_H
74 # include <arpa/inet.h>
75 #endif
76 #include <ctype.h>
77 #include <fcntl.h>
78 #include <errno.h>
79 #ifdef HAVE_NETDB_H
80 #include <netdb.h>
81 #endif
82 #ifdef HAVE_UNISTD_H
83 # include <unistd.h>
84 #endif
85 #include <stdlib.h>
86 #ifdef HAVE_ARPA_NAMESER_H
87 # include <arpa/nameser.h>
88 #endif
89 #ifdef HAVE_RESOLV_H
90 # include <resolv.h>
91 #endif
92 #ifdef HAVE_NET_IF_H
93 # include <net/if.h>
94 #endif
95 #ifdef HAVE_LINUX_FILTER_H
96 # include <linux/filter.h>
97 #endif
99 #ifdef HAVE_NETIPX_IPX_H
100 # include <netipx/ipx.h>
101 # define HAVE_IPX
102 #elif defined(HAVE_LINUX_IPX_H)
103 # ifdef HAVE_ASM_TYPES_H
104 # include <asm/types.h>
105 # endif
106 # ifdef HAVE_LINUX_TYPES_H
107 # include <linux/types.h>
108 # endif
109 # include <linux/ipx.h>
110 # define HAVE_IPX
111 #endif
113 #ifdef HAVE_LINUX_IRDA_H
114 # ifdef HAVE_LINUX_TYPES_H
115 # include <linux/types.h>
116 # endif
117 # include <linux/irda.h>
118 # define HAVE_IRDA
119 #endif
121 #ifdef HAVE_POLL_H
122 #include <poll.h>
123 #endif
124 #ifdef HAVE_SYS_POLL_H
125 # include <sys/poll.h>
126 #endif
127 #ifdef HAVE_SYS_TIME_H
128 # include <sys/time.h>
129 #endif
131 #define NONAMELESSUNION
132 #define NONAMELESSSTRUCT
133 #include "ntstatus.h"
134 #define WIN32_NO_STATUS
135 #include "windef.h"
136 #include "winbase.h"
137 #include "wingdi.h"
138 #include "winuser.h"
139 #include "winerror.h"
140 #include "winnls.h"
141 #include "winsock2.h"
142 #include "mswsock.h"
143 #include "ws2tcpip.h"
144 #include "ws2spi.h"
145 #include "wsipx.h"
146 #include "mstcpip.h"
147 #include "af_irda.h"
148 #include "winnt.h"
149 #define USE_WC_PREFIX /* For CMSG_DATA */
150 #include "iphlpapi.h"
151 #include "wine/server.h"
152 #include "wine/debug.h"
153 #include "wine/exception.h"
154 #include "wine/unicode.h"
156 #ifdef HAVE_IPX
157 # include "wsnwlink.h"
158 #endif
160 #if defined(linux) && !defined(IP_UNICAST_IF)
161 #define IP_UNICAST_IF 50
162 #endif
164 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
165 # define sipx_network sipx_addr.x_net
166 # define sipx_node sipx_addr.x_host.c_host
167 #endif /* __FreeBSD__ */
169 #ifndef INADDR_NONE
170 #define INADDR_NONE ~0UL
171 #endif
173 WINE_DEFAULT_DEBUG_CHANNEL(winsock);
174 WINE_DECLARE_DEBUG_CHANNEL(winediag);
176 #if defined(IP_UNICAST_IF) && defined(SO_ATTACH_FILTER)
177 # define LINUX_BOUND_IF
178 struct interface_filter {
179 struct sock_filter iface_memaddr;
180 struct sock_filter iface_rule;
181 struct sock_filter return_keep;
182 struct sock_filter return_dump;
184 # define FILTER_JUMP_DUMP(here) (u_char)(offsetof(struct interface_filter, return_dump) \
185 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
186 /sizeof(struct sock_filter)
187 # define FILTER_JUMP_KEEP(here) (u_char)(offsetof(struct interface_filter, return_keep) \
188 -offsetof(struct interface_filter, here)-sizeof(struct sock_filter)) \
189 /sizeof(struct sock_filter)
190 static struct interface_filter generic_interface_filter = {
191 BPF_STMT(BPF_LD+BPF_W+BPF_ABS, SKF_AD_OFF+SKF_AD_IFINDEX),
192 BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0xdeadbeef, FILTER_JUMP_KEEP(iface_rule), FILTER_JUMP_DUMP(iface_rule)),
193 BPF_STMT(BPF_RET+BPF_K, (u_int)-1), /* keep packet */
194 BPF_STMT(BPF_RET+BPF_K, 0) /* dump packet */
196 #endif /* LINUX_BOUND_IF */
199 * The actual definition of WSASendTo, wrapped in a different function name
200 * so that internal calls from ws2_32 itself will not trigger programs like
201 * Garena, which hooks WSASendTo/WSARecvFrom calls.
203 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
204 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
205 const struct WS_sockaddr *to, int tolen,
206 LPWSAOVERLAPPED lpOverlapped,
207 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine );
210 * Internal fundamental receive function, essentially WSARecvFrom with an
211 * additional parameter to support message control headers.
213 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
214 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
215 struct WS_sockaddr *lpFrom,
216 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
217 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
218 LPWSABUF lpControlBuffer );
220 /* critical section to protect some non-reentrant net function */
221 static CRITICAL_SECTION csWSgetXXXbyYYY;
222 static CRITICAL_SECTION_DEBUG critsect_debug =
224 0, 0, &csWSgetXXXbyYYY,
225 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
226 0, 0, { (DWORD_PTR)(__FILE__ ": csWSgetXXXbyYYY") }
228 static CRITICAL_SECTION csWSgetXXXbyYYY = { &critsect_debug, -1, 0, 0, 0, 0 };
230 union generic_unix_sockaddr
232 struct sockaddr addr;
233 char data[128]; /* should be big enough for all families */
236 static inline const char *debugstr_sockaddr( const struct WS_sockaddr *a )
238 if (!a) return "(nil)";
239 switch (a->sa_family)
241 case WS_AF_INET:
242 return wine_dbg_sprintf("{ family AF_INET, address %s, port %d }",
243 inet_ntoa(((const struct sockaddr_in *)a)->sin_addr),
244 ntohs(((const struct sockaddr_in *)a)->sin_port));
245 case WS_AF_INET6:
247 char buf[46];
248 const char *p;
249 struct WS_sockaddr_in6 *sin = (struct WS_sockaddr_in6 *)a;
251 p = WS_inet_ntop( WS_AF_INET6, &sin->sin6_addr, buf, sizeof(buf) );
252 if (!p)
253 p = "(unknown IPv6 address)";
254 return wine_dbg_sprintf("{ family AF_INET6, address %s, port %d }",
255 p, ntohs(sin->sin6_port));
257 case WS_AF_IRDA:
259 DWORD addr;
261 memcpy( &addr, ((const SOCKADDR_IRDA *)a)->irdaDeviceID, sizeof(addr) );
262 addr = ntohl( addr );
263 return wine_dbg_sprintf("{ family AF_IRDA, addr %08x, name %s }",
264 addr,
265 ((const SOCKADDR_IRDA *)a)->irdaServiceName);
267 default:
268 return wine_dbg_sprintf("{ family %d }", a->sa_family);
272 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
273 #define SOCKET2HANDLE(s) ((HANDLE)(s))
274 #define HANDLE2SOCKET(h) ((SOCKET)(h))
276 /****************************************************************
277 * Async IO declarations
278 ****************************************************************/
280 typedef struct ws2_async
282 HANDLE hSocket;
283 int type;
284 LPWSAOVERLAPPED user_overlapped;
285 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
286 IO_STATUS_BLOCK local_iosb;
287 struct WS_sockaddr *addr;
288 union
290 int val; /* for send operations */
291 int *ptr; /* for recv operations */
292 } addrlen;
293 DWORD flags;
294 DWORD *lpFlags;
295 WSABUF *control;
296 unsigned int n_iovecs;
297 unsigned int first_iovec;
298 struct iovec iovec[1];
299 } ws2_async;
301 typedef struct ws2_accept_async
303 HANDLE listen_socket;
304 HANDLE accept_socket;
305 LPOVERLAPPED user_overlapped;
306 ULONG_PTR cvalue;
307 PVOID buf; /* buffer to write data to */
308 int data_len;
309 int local_len;
310 int remote_len;
311 struct ws2_async *read;
312 } ws2_accept_async;
314 /****************************************************************/
316 /* ----------------------------------- internal data */
318 /* ws_... struct conversion flags */
320 typedef struct /* WSAAsyncSelect() control struct */
322 HANDLE service, event, sock;
323 HWND hWnd;
324 UINT uMsg;
325 LONG lEvent;
326 } ws_select_info;
328 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
329 #define WS_MAX_UDP_DATAGRAM 1024
330 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
332 /* hostent's, servent's and protent's are stored in one buffer per thread,
333 * as documented on MSDN for the functions that return any of the buffers */
334 struct per_thread_data
336 int opentype;
337 struct WS_hostent *he_buffer;
338 struct WS_servent *se_buffer;
339 struct WS_protoent *pe_buffer;
340 int he_len;
341 int se_len;
342 int pe_len;
345 /* internal: routing description information */
346 struct route {
347 struct in_addr addr;
348 IF_INDEX interface;
349 DWORD metric;
352 static INT num_startup; /* reference counter */
353 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
355 /* function prototypes */
356 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length);
357 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
358 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
359 static struct WS_servent *WS_dup_se(const struct servent* p_se);
361 int WSAIOCTL_GetInterfaceCount(void);
362 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
364 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus, ULONG Information );
366 #define MAP_OPTION(opt) { WS_##opt, opt }
368 static const int ws_sock_map[][2] =
370 MAP_OPTION( SO_DEBUG ),
371 MAP_OPTION( SO_ACCEPTCONN ),
372 MAP_OPTION( SO_REUSEADDR ),
373 MAP_OPTION( SO_KEEPALIVE ),
374 MAP_OPTION( SO_DONTROUTE ),
375 MAP_OPTION( SO_BROADCAST ),
376 MAP_OPTION( SO_LINGER ),
377 MAP_OPTION( SO_OOBINLINE ),
378 MAP_OPTION( SO_SNDBUF ),
379 MAP_OPTION( SO_RCVBUF ),
380 MAP_OPTION( SO_ERROR ),
381 MAP_OPTION( SO_TYPE ),
382 #ifdef SO_RCVTIMEO
383 MAP_OPTION( SO_RCVTIMEO ),
384 #endif
385 #ifdef SO_SNDTIMEO
386 MAP_OPTION( SO_SNDTIMEO ),
387 #endif
390 static const int ws_tcp_map[][2] =
392 #ifdef TCP_NODELAY
393 MAP_OPTION( TCP_NODELAY ),
394 #endif
397 static const int ws_ip_map[][2] =
399 MAP_OPTION( IP_MULTICAST_IF ),
400 MAP_OPTION( IP_MULTICAST_TTL ),
401 MAP_OPTION( IP_MULTICAST_LOOP ),
402 MAP_OPTION( IP_ADD_MEMBERSHIP ),
403 MAP_OPTION( IP_DROP_MEMBERSHIP ),
404 MAP_OPTION( IP_OPTIONS ),
405 #ifdef IP_HDRINCL
406 MAP_OPTION( IP_HDRINCL ),
407 #endif
408 MAP_OPTION( IP_TOS ),
409 MAP_OPTION( IP_TTL ),
410 #ifdef IP_PKTINFO
411 MAP_OPTION( IP_PKTINFO ),
412 #endif
413 #ifdef IP_UNICAST_IF
414 MAP_OPTION( IP_UNICAST_IF ),
415 #endif
418 static const int ws_ipv6_map[][2] =
420 #ifdef IPV6_ADD_MEMBERSHIP
421 MAP_OPTION( IPV6_ADD_MEMBERSHIP ),
422 #endif
423 #ifdef IPV6_DROP_MEMBERSHIP
424 MAP_OPTION( IPV6_DROP_MEMBERSHIP ),
425 #endif
426 MAP_OPTION( IPV6_MULTICAST_IF ),
427 MAP_OPTION( IPV6_MULTICAST_HOPS ),
428 MAP_OPTION( IPV6_MULTICAST_LOOP ),
429 MAP_OPTION( IPV6_UNICAST_HOPS ),
430 MAP_OPTION( IPV6_V6ONLY ),
431 #ifdef IPV6_UNICAST_IF
432 MAP_OPTION( IPV6_UNICAST_IF ),
433 #endif
436 static const int ws_af_map[][2] =
438 MAP_OPTION( AF_UNSPEC ),
439 MAP_OPTION( AF_INET ),
440 MAP_OPTION( AF_INET6 ),
441 #ifdef HAVE_IPX
442 MAP_OPTION( AF_IPX ),
443 #endif
444 #ifdef AF_IRDA
445 MAP_OPTION( AF_IRDA ),
446 #endif
447 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
450 static const int ws_socktype_map[][2] =
452 MAP_OPTION( SOCK_DGRAM ),
453 MAP_OPTION( SOCK_STREAM ),
454 MAP_OPTION( SOCK_RAW ),
455 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
458 static const int ws_proto_map[][2] =
460 MAP_OPTION( IPPROTO_IP ),
461 MAP_OPTION( IPPROTO_TCP ),
462 MAP_OPTION( IPPROTO_UDP ),
463 MAP_OPTION( IPPROTO_ICMP ),
464 MAP_OPTION( IPPROTO_IGMP ),
465 MAP_OPTION( IPPROTO_RAW ),
466 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
469 static const int ws_aiflag_map[][2] =
471 MAP_OPTION( AI_PASSIVE ),
472 MAP_OPTION( AI_CANONNAME ),
473 MAP_OPTION( AI_NUMERICHOST ),
474 MAP_OPTION( AI_ADDRCONFIG ),
477 static const int ws_niflag_map[][2] =
479 MAP_OPTION( NI_NOFQDN ),
480 MAP_OPTION( NI_NUMERICHOST ),
481 MAP_OPTION( NI_NAMEREQD ),
482 MAP_OPTION( NI_NUMERICSERV ),
483 MAP_OPTION( NI_DGRAM ),
486 static const int ws_eai_map[][2] =
488 MAP_OPTION( EAI_AGAIN ),
489 MAP_OPTION( EAI_BADFLAGS ),
490 MAP_OPTION( EAI_FAIL ),
491 MAP_OPTION( EAI_FAMILY ),
492 MAP_OPTION( EAI_MEMORY ),
493 /* Note: EAI_NODATA is deprecated, but still
494 * used by Windows and Linux... We map the newer
495 * EAI_NONAME to EAI_NODATA for now until Windows
496 * changes too.
498 #ifdef EAI_NODATA
499 MAP_OPTION( EAI_NODATA ),
500 #endif
501 #ifdef EAI_NONAME
502 { WS_EAI_NODATA, EAI_NONAME },
503 #endif
505 MAP_OPTION( EAI_SERVICE ),
506 MAP_OPTION( EAI_SOCKTYPE ),
507 { 0, 0 }
510 static const char magic_loopback_addr[] = {127, 12, 34, 56};
512 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
513 static inline WSACMSGHDR *fill_control_message(int level, int type, WSACMSGHDR *current, ULONG *maxsize, void *data, int len)
515 ULONG msgsize = sizeof(WSACMSGHDR) + WSA_CMSG_ALIGN(len);
516 char *ptr = (char *) current + sizeof(WSACMSGHDR);
518 /* Make sure there is at least enough room for this entry */
519 if (msgsize > *maxsize)
520 return NULL;
521 *maxsize -= msgsize;
522 /* Fill in the entry */
523 current->cmsg_len = sizeof(WSACMSGHDR) + len;
524 current->cmsg_level = level;
525 current->cmsg_type = type;
526 memcpy(ptr, data, len);
527 /* Return the pointer to where next entry should go */
528 return (WSACMSGHDR *) (ptr + WSA_CMSG_ALIGN(len));
531 static inline int convert_control_headers(struct msghdr *hdr, WSABUF *control)
533 #ifdef IP_PKTINFO
534 WSACMSGHDR *cmsg_win = (WSACMSGHDR *) control->buf, *ptr;
535 ULONG ctlsize = control->len;
536 struct cmsghdr *cmsg_unix;
538 ptr = cmsg_win;
539 /* Loop over all the headers, converting as appropriate */
540 for (cmsg_unix = CMSG_FIRSTHDR(hdr); cmsg_unix != NULL; cmsg_unix = CMSG_NXTHDR(hdr, cmsg_unix))
542 switch(cmsg_unix->cmsg_level)
544 case IPPROTO_IP:
545 switch(cmsg_unix->cmsg_type)
547 case IP_PKTINFO:
549 /* Convert the Unix IP_PKTINFO structure to the Windows version */
550 struct in_pktinfo *data_unix = (struct in_pktinfo *) CMSG_DATA(cmsg_unix);
551 struct WS_in_pktinfo data_win;
553 memcpy(&data_win.ipi_addr,&data_unix->ipi_addr.s_addr,4); /* 4 bytes = 32 address bits */
554 data_win.ipi_ifindex = data_unix->ipi_ifindex;
555 ptr = fill_control_message(WS_IPPROTO_IP, WS_IP_PKTINFO, ptr, &ctlsize,
556 (void*)&data_win, sizeof(data_win));
557 if (!ptr) goto error;
558 } break;
559 default:
560 FIXME("Unhandled IPPROTO_IP message header type %d\n", cmsg_unix->cmsg_type);
561 break;
563 break;
564 default:
565 FIXME("Unhandled message header level %d\n", cmsg_unix->cmsg_level);
566 break;
570 error:
571 /* Set the length of the returned control headers */
572 control->len = (ptr == NULL ? 0 : (char*)ptr - (char*)cmsg_win);
573 return (ptr != NULL);
574 #else /* IP_PKTINFO */
575 control->len = 0;
576 return 1;
577 #endif /* IP_PKTINFO */
579 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
581 /* ----------------------------------- error handling */
583 static NTSTATUS sock_get_ntstatus( int err )
585 switch ( err )
587 case EBADF: return STATUS_INVALID_HANDLE;
588 case EBUSY: return STATUS_DEVICE_BUSY;
589 case EPERM:
590 case EACCES: return STATUS_ACCESS_DENIED;
591 case EFAULT: return STATUS_NO_MEMORY;
592 case EINVAL: return STATUS_INVALID_PARAMETER;
593 case ENFILE:
594 case EMFILE: return STATUS_TOO_MANY_OPENED_FILES;
595 case EWOULDBLOCK: return STATUS_CANT_WAIT;
596 case EINPROGRESS: return STATUS_PENDING;
597 case EALREADY: return STATUS_NETWORK_BUSY;
598 case ENOTSOCK: return STATUS_OBJECT_TYPE_MISMATCH;
599 case EDESTADDRREQ: return STATUS_INVALID_PARAMETER;
600 case EMSGSIZE: return STATUS_BUFFER_OVERFLOW;
601 case EPROTONOSUPPORT:
602 case ESOCKTNOSUPPORT:
603 case EPFNOSUPPORT:
604 case EAFNOSUPPORT:
605 case EPROTOTYPE: return STATUS_NOT_SUPPORTED;
606 case ENOPROTOOPT: return STATUS_INVALID_PARAMETER;
607 case EOPNOTSUPP: return STATUS_NOT_SUPPORTED;
608 case EADDRINUSE: return STATUS_ADDRESS_ALREADY_ASSOCIATED;
609 case EADDRNOTAVAIL: return STATUS_INVALID_PARAMETER;
610 case ECONNREFUSED: return STATUS_CONNECTION_REFUSED;
611 case ESHUTDOWN: return STATUS_PIPE_DISCONNECTED;
612 case ENOTCONN: return STATUS_CONNECTION_DISCONNECTED;
613 case ETIMEDOUT: return STATUS_IO_TIMEOUT;
614 case ENETUNREACH: return STATUS_NETWORK_UNREACHABLE;
615 case ENETDOWN: return STATUS_NETWORK_BUSY;
616 case EPIPE:
617 case ECONNRESET: return STATUS_CONNECTION_RESET;
618 case ECONNABORTED: return STATUS_CONNECTION_ABORTED;
620 case 0: return STATUS_SUCCESS;
621 default:
622 WARN("Unknown errno %d!\n", err);
623 return STATUS_UNSUCCESSFUL;
627 static UINT sock_get_error( int err )
629 switch(err)
631 case EINTR: return WSAEINTR;
632 case EBADF: return WSAEBADF;
633 case EPERM:
634 case EACCES: return WSAEACCES;
635 case EFAULT: return WSAEFAULT;
636 case EINVAL: return WSAEINVAL;
637 case EMFILE: return WSAEMFILE;
638 case EWOULDBLOCK: return WSAEWOULDBLOCK;
639 case EINPROGRESS: return WSAEINPROGRESS;
640 case EALREADY: return WSAEALREADY;
641 case ENOTSOCK: return WSAENOTSOCK;
642 case EDESTADDRREQ: return WSAEDESTADDRREQ;
643 case EMSGSIZE: return WSAEMSGSIZE;
644 case EPROTOTYPE: return WSAEPROTOTYPE;
645 case ENOPROTOOPT: return WSAENOPROTOOPT;
646 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
647 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
648 case EOPNOTSUPP: return WSAEOPNOTSUPP;
649 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
650 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
651 case EADDRINUSE: return WSAEADDRINUSE;
652 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
653 case ENETDOWN: return WSAENETDOWN;
654 case ENETUNREACH: return WSAENETUNREACH;
655 case ENETRESET: return WSAENETRESET;
656 case ECONNABORTED: return WSAECONNABORTED;
657 case EPIPE:
658 case ECONNRESET: return WSAECONNRESET;
659 case ENOBUFS: return WSAENOBUFS;
660 case EISCONN: return WSAEISCONN;
661 case ENOTCONN: return WSAENOTCONN;
662 case ESHUTDOWN: return WSAESHUTDOWN;
663 case ETOOMANYREFS: return WSAETOOMANYREFS;
664 case ETIMEDOUT: return WSAETIMEDOUT;
665 case ECONNREFUSED: return WSAECONNREFUSED;
666 case ELOOP: return WSAELOOP;
667 case ENAMETOOLONG: return WSAENAMETOOLONG;
668 case EHOSTDOWN: return WSAEHOSTDOWN;
669 case EHOSTUNREACH: return WSAEHOSTUNREACH;
670 case ENOTEMPTY: return WSAENOTEMPTY;
671 #ifdef EPROCLIM
672 case EPROCLIM: return WSAEPROCLIM;
673 #endif
674 #ifdef EUSERS
675 case EUSERS: return WSAEUSERS;
676 #endif
677 #ifdef EDQUOT
678 case EDQUOT: return WSAEDQUOT;
679 #endif
680 #ifdef ESTALE
681 case ESTALE: return WSAESTALE;
682 #endif
683 #ifdef EREMOTE
684 case EREMOTE: return WSAEREMOTE;
685 #endif
687 /* just in case we ever get here and there are no problems */
688 case 0: return 0;
689 default:
690 WARN("Unknown errno %d!\n", err);
691 return WSAEOPNOTSUPP;
695 static UINT wsaErrno(void)
697 int loc_errno = errno;
698 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
700 return sock_get_error( loc_errno );
703 /* most ws2 overlapped functions return an ntstatus-based error code */
704 static NTSTATUS wsaErrStatus(void)
706 int loc_errno = errno;
707 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
709 return sock_get_ntstatus(loc_errno);
712 static UINT wsaHerrno(int loc_errno)
714 WARN("h_errno %d.\n", loc_errno);
716 switch(loc_errno)
718 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
719 case TRY_AGAIN: return WSATRY_AGAIN;
720 case NO_RECOVERY: return WSANO_RECOVERY;
721 case NO_DATA: return WSANO_DATA;
722 case ENOBUFS: return WSAENOBUFS;
724 case 0: return 0;
725 default:
726 WARN("Unknown h_errno %d!\n", loc_errno);
727 return WSAEOPNOTSUPP;
731 static inline DWORD NtStatusToWSAError( const DWORD status )
733 /* We only need to cover the status codes set by server async request handling */
734 DWORD wserr;
735 switch ( status )
737 case STATUS_SUCCESS: wserr = 0; break;
738 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
739 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
740 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
741 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
742 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
743 case STATUS_NETWORK_BUSY: wserr = WSAEALREADY; break;
744 case STATUS_NETWORK_UNREACHABLE: wserr = WSAENETUNREACH; break;
745 case STATUS_CONNECTION_REFUSED: wserr = WSAECONNREFUSED; break;
746 case STATUS_CONNECTION_DISCONNECTED: wserr = WSAENOTCONN; break;
747 case STATUS_CONNECTION_RESET: wserr = WSAECONNRESET; break;
748 case STATUS_CONNECTION_ABORTED: wserr = WSAECONNABORTED; break;
749 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
750 case STATUS_ADDRESS_ALREADY_ASSOCIATED: wserr = WSAEADDRINUSE; break;
751 case STATUS_IO_TIMEOUT:
752 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
753 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
754 case STATUS_ACCESS_DENIED: wserr = WSAEACCES; break;
755 case STATUS_TOO_MANY_OPENED_FILES: wserr = WSAEMFILE; break;
756 case STATUS_CANT_WAIT: wserr = WSAEWOULDBLOCK; break;
757 case STATUS_BUFFER_OVERFLOW: wserr = WSAEMSGSIZE; break;
758 case STATUS_NOT_SUPPORTED: wserr = WSAEOPNOTSUPP; break;
759 case STATUS_HOST_UNREACHABLE: wserr = WSAEHOSTUNREACH; break;
761 default:
762 wserr = RtlNtStatusToDosError( status );
763 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
765 return wserr;
768 /* set last error code from NT status without mapping WSA errors */
769 static inline unsigned int set_error( unsigned int err )
771 if (err)
773 err = NtStatusToWSAError( err );
774 SetLastError( err );
776 return err;
779 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
781 int fd;
782 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
783 return -1;
784 return fd;
787 static inline void release_sock_fd( SOCKET s, int fd )
789 wine_server_release_fd( SOCKET2HANDLE(s), fd );
792 static void _enable_event( HANDLE s, unsigned int event,
793 unsigned int sstate, unsigned int cstate )
795 SERVER_START_REQ( enable_socket_event )
797 req->handle = wine_server_obj_handle( s );
798 req->mask = event;
799 req->sstate = sstate;
800 req->cstate = cstate;
801 wine_server_call( req );
803 SERVER_END_REQ;
806 static NTSTATUS _is_blocking(SOCKET s, BOOL *ret)
808 NTSTATUS status;
809 SERVER_START_REQ( get_socket_event )
811 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
812 req->service = FALSE;
813 req->c_event = 0;
814 status = wine_server_call( req );
815 *ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
817 SERVER_END_REQ;
818 return status;
821 static unsigned int _get_sock_mask(SOCKET s)
823 unsigned int ret;
824 SERVER_START_REQ( get_socket_event )
826 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
827 req->service = FALSE;
828 req->c_event = 0;
829 wine_server_call( req );
830 ret = reply->mask;
832 SERVER_END_REQ;
833 return ret;
836 static void _sync_sock_state(SOCKET s)
838 BOOL dummy;
839 /* do a dummy wineserver request in order to let
840 the wineserver run through its select loop once */
841 (void)_is_blocking(s, &dummy);
844 static int _get_sock_error(SOCKET s, unsigned int bit)
846 int events[FD_MAX_EVENTS];
848 SERVER_START_REQ( get_socket_event )
850 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
851 req->service = FALSE;
852 req->c_event = 0;
853 wine_server_set_reply( req, events, sizeof(events) );
854 wine_server_call( req );
856 SERVER_END_REQ;
857 return events[bit];
860 static struct per_thread_data *get_per_thread_data(void)
862 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
863 /* lazy initialization */
864 if (!ptb)
866 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
867 NtCurrentTeb()->WinSockData = ptb;
869 return ptb;
872 static void free_per_thread_data(void)
874 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
876 if (!ptb) return;
878 /* delete scratch buffers */
879 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
880 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
881 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
882 ptb->he_buffer = NULL;
883 ptb->se_buffer = NULL;
884 ptb->pe_buffer = NULL;
886 HeapFree( GetProcessHeap(), 0, ptb );
887 NtCurrentTeb()->WinSockData = NULL;
890 /***********************************************************************
891 * DllMain (WS2_32.init)
893 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
895 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
896 switch (fdwReason) {
897 case DLL_PROCESS_ATTACH:
898 break;
899 case DLL_PROCESS_DETACH:
900 free_per_thread_data();
901 DeleteCriticalSection(&csWSgetXXXbyYYY);
902 num_startup = 0;
903 break;
904 case DLL_THREAD_DETACH:
905 free_per_thread_data();
906 break;
908 return TRUE;
911 /***********************************************************************
912 * convert_sockopt()
914 * Converts socket flags from Windows format.
915 * Return 1 if converted, 0 if not (error).
917 static int convert_sockopt(INT *level, INT *optname)
919 unsigned int i;
920 switch (*level)
922 case WS_SOL_SOCKET:
923 *level = SOL_SOCKET;
924 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
925 if( ws_sock_map[i][0] == *optname )
927 *optname = ws_sock_map[i][1];
928 return 1;
931 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
932 break;
933 case WS_IPPROTO_TCP:
934 *level = IPPROTO_TCP;
935 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
936 if ( ws_tcp_map[i][0] == *optname )
938 *optname = ws_tcp_map[i][1];
939 return 1;
942 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
943 break;
944 case WS_IPPROTO_IP:
945 *level = IPPROTO_IP;
946 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
947 if (ws_ip_map[i][0] == *optname )
949 *optname = ws_ip_map[i][1];
950 return 1;
953 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
954 break;
955 case WS_IPPROTO_IPV6:
956 *level = IPPROTO_IPV6;
957 for(i=0; i<sizeof(ws_ipv6_map)/sizeof(ws_ipv6_map[0]); i++) {
958 if (ws_ipv6_map[i][0] == *optname )
960 *optname = ws_ipv6_map[i][1];
961 return 1;
964 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname);
965 break;
966 default: FIXME("Unimplemented or unknown socket level\n");
968 return 0;
971 /* ----------------------------------- Per-thread info (or per-process?) */
973 static char *strdup_lower(const char *str)
975 int i;
976 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
978 if (ret)
980 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
981 ret[i] = 0;
983 else SetLastError(WSAENOBUFS);
984 return ret;
987 static inline int sock_error_p(int s)
989 unsigned int optval;
990 socklen_t optlen = sizeof(optval);
991 getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
992 if (optval) WARN("\t[%i] error: %d\n", s, optval);
993 return optval != 0;
996 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
997 * from an fd and return the value converted to milli seconds
998 * or -1 if there is an infinite time out */
999 static inline int get_rcvsnd_timeo( int fd, int optname)
1001 struct timeval tv;
1002 socklen_t len = sizeof(tv);
1003 int ret = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
1004 if( ret >= 0)
1005 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
1006 if( ret <= 0 ) /* tv == {0,0} means infinite time out */
1007 return -1;
1008 return ret;
1011 /* macro wrappers for portability */
1012 #ifdef SO_RCVTIMEO
1013 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
1014 #else
1015 #define GET_RCVTIMEO(fd) (-1)
1016 #endif
1018 #ifdef SO_SNDTIMEO
1019 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
1020 #else
1021 #define GET_SNDTIMEO(fd) (-1)
1022 #endif
1024 /* utility: given an fd, will block until one of the events occurs */
1025 static inline int do_block( int fd, int events, int timeout )
1027 struct pollfd pfd;
1028 int ret;
1030 pfd.fd = fd;
1031 pfd.events = events;
1033 while ((ret = poll(&pfd, 1, timeout)) < 0)
1035 if (errno != EINTR)
1036 return -1;
1038 if( ret == 0 )
1039 return 0;
1040 return pfd.revents;
1043 static int
1044 convert_af_w2u(int windowsaf) {
1045 unsigned int i;
1047 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1048 if (ws_af_map[i][0] == windowsaf)
1049 return ws_af_map[i][1];
1050 FIXME("unhandled Windows address family %d\n", windowsaf);
1051 return -1;
1054 static int
1055 convert_af_u2w(int unixaf) {
1056 unsigned int i;
1058 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
1059 if (ws_af_map[i][1] == unixaf)
1060 return ws_af_map[i][0];
1061 FIXME("unhandled UNIX address family %d\n", unixaf);
1062 return -1;
1065 static int
1066 convert_proto_w2u(int windowsproto) {
1067 unsigned int i;
1069 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1070 if (ws_proto_map[i][0] == windowsproto)
1071 return ws_proto_map[i][1];
1072 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
1073 return -1;
1076 static int
1077 convert_proto_u2w(int unixproto) {
1078 unsigned int i;
1080 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
1081 if (ws_proto_map[i][1] == unixproto)
1082 return ws_proto_map[i][0];
1083 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
1084 return -1;
1087 static int
1088 convert_socktype_w2u(int windowssocktype) {
1089 unsigned int i;
1091 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1092 if (ws_socktype_map[i][0] == windowssocktype)
1093 return ws_socktype_map[i][1];
1094 FIXME("unhandled Windows socket type %d\n", windowssocktype);
1095 return -1;
1098 static int
1099 convert_socktype_u2w(int unixsocktype) {
1100 unsigned int i;
1102 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
1103 if (ws_socktype_map[i][1] == unixsocktype)
1104 return ws_socktype_map[i][0];
1105 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
1106 return -1;
1109 /* ----------------------------------- API -----
1111 * Init / cleanup / error checking.
1114 /***********************************************************************
1115 * WSAStartup (WS2_32.115)
1117 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
1119 TRACE("verReq=%x\n", wVersionRequested);
1121 if (LOBYTE(wVersionRequested) < 1)
1122 return WSAVERNOTSUPPORTED;
1124 if (!lpWSAData) return WSAEINVAL;
1126 num_startup++;
1128 /* that's the whole of the negotiation for now */
1129 lpWSAData->wVersion = wVersionRequested;
1130 /* return winsock information */
1131 lpWSAData->wHighVersion = 0x0202;
1132 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
1133 strcpy(lpWSAData->szSystemStatus, "Running" );
1134 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
1135 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
1136 /* don't do anything with lpWSAData->lpVendorInfo */
1137 /* (some apps don't allocate the space for this field) */
1139 TRACE("succeeded\n");
1140 return 0;
1144 /***********************************************************************
1145 * WSACleanup (WS2_32.116)
1147 INT WINAPI WSACleanup(void)
1149 if (num_startup) {
1150 num_startup--;
1151 return 0;
1153 SetLastError(WSANOTINITIALISED);
1154 return SOCKET_ERROR;
1158 /***********************************************************************
1159 * WSAGetLastError (WS2_32.111)
1161 INT WINAPI WSAGetLastError(void)
1163 return GetLastError();
1166 /***********************************************************************
1167 * WSASetLastError (WS2_32.112)
1169 void WINAPI WSASetLastError(INT iError) {
1170 SetLastError(iError);
1173 static struct WS_hostent *check_buffer_he(int size)
1175 struct per_thread_data * ptb = get_per_thread_data();
1176 if (ptb->he_buffer)
1178 if (ptb->he_len >= size ) return ptb->he_buffer;
1179 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1181 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
1182 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
1183 return ptb->he_buffer;
1186 static struct WS_servent *check_buffer_se(int size)
1188 struct per_thread_data * ptb = get_per_thread_data();
1189 if (ptb->se_buffer)
1191 if (ptb->se_len >= size ) return ptb->se_buffer;
1192 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1194 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
1195 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
1196 return ptb->se_buffer;
1199 static struct WS_protoent *check_buffer_pe(int size)
1201 struct per_thread_data * ptb = get_per_thread_data();
1202 if (ptb->pe_buffer)
1204 if (ptb->pe_len >= size ) return ptb->pe_buffer;
1205 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1207 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
1208 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
1209 return ptb->pe_buffer;
1212 /* ----------------------------------- i/o APIs */
1214 static inline BOOL supported_pf(int pf)
1216 switch (pf)
1218 case WS_AF_INET:
1219 case WS_AF_INET6:
1220 return TRUE;
1221 #ifdef HAVE_IPX
1222 case WS_AF_IPX:
1223 return TRUE;
1224 #endif
1225 #ifdef HAVE_IRDA
1226 case WS_AF_IRDA:
1227 return TRUE;
1228 #endif
1229 default:
1230 return FALSE;
1235 /**********************************************************************/
1237 /* Returns the length of the converted address if successful, 0 if it was too small to
1238 * start with.
1240 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
1241 union generic_unix_sockaddr *uaddr)
1243 unsigned int uaddrlen = 0;
1245 switch (wsaddr->sa_family)
1247 #ifdef HAVE_IPX
1248 case WS_AF_IPX:
1250 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
1251 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
1253 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
1254 return 0;
1256 uaddrlen = sizeof(struct sockaddr_ipx);
1257 memset( uaddr, 0, uaddrlen );
1258 uipx->sipx_family=AF_IPX;
1259 uipx->sipx_port=wsipx->sa_socket;
1260 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1261 * in one go
1263 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
1264 #ifdef IPX_FRAME_NONE
1265 uipx->sipx_type=IPX_FRAME_NONE;
1266 #endif
1267 break;
1269 #endif
1270 case WS_AF_INET6: {
1271 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
1272 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
1274 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1275 * scope_id, one without.
1277 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
1278 uaddrlen = sizeof(struct sockaddr_in6);
1279 memset( uaddr, 0, uaddrlen );
1280 uin6->sin6_family = AF_INET6;
1281 uin6->sin6_port = win6->sin6_port;
1282 uin6->sin6_flowinfo = win6->sin6_flowinfo;
1283 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1284 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
1285 #endif
1286 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
1287 break;
1289 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
1290 return 0;
1292 case WS_AF_INET: {
1293 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
1294 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
1296 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
1297 return 0;
1298 uaddrlen = sizeof(struct sockaddr_in);
1299 memset( uaddr, 0, uaddrlen );
1300 uin->sin_family = AF_INET;
1301 uin->sin_port = win->sin_port;
1302 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
1303 break;
1305 #ifdef HAVE_IRDA
1306 case WS_AF_IRDA: {
1307 struct sockaddr_irda *uin = (struct sockaddr_irda *)uaddr;
1308 const SOCKADDR_IRDA *win = (const SOCKADDR_IRDA *)wsaddr;
1310 if (wsaddrlen < sizeof(SOCKADDR_IRDA))
1311 return 0;
1312 uaddrlen = sizeof(struct sockaddr_irda);
1313 memset( uaddr, 0, uaddrlen );
1314 uin->sir_family = AF_IRDA;
1315 if (!strncmp( win->irdaServiceName, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1317 unsigned int lsap_sel = 0;
1319 sscanf( win->irdaServiceName, "LSAP-SEL%u", &lsap_sel );
1320 uin->sir_lsap_sel = lsap_sel;
1322 else
1324 uin->sir_lsap_sel = LSAP_ANY;
1325 memcpy( uin->sir_name, win->irdaServiceName, 25 );
1327 memcpy( &uin->sir_addr, win->irdaDeviceID, sizeof(uin->sir_addr) );
1328 break;
1330 #endif
1331 case WS_AF_UNSPEC: {
1332 /* Try to determine the needed space by the passed windows sockaddr space */
1333 switch (wsaddrlen) {
1334 default: /* likely a ipv4 address */
1335 case sizeof(struct WS_sockaddr_in):
1336 uaddrlen = sizeof(struct sockaddr_in);
1337 break;
1338 #ifdef HAVE_IPX
1339 case sizeof(struct WS_sockaddr_ipx):
1340 uaddrlen = sizeof(struct sockaddr_ipx);
1341 break;
1342 #endif
1343 #ifdef HAVE_IRDA
1344 case sizeof(SOCKADDR_IRDA):
1345 uaddrlen = sizeof(struct sockaddr_irda);
1346 break;
1347 #endif
1348 case sizeof(struct WS_sockaddr_in6):
1349 case sizeof(struct WS_sockaddr_in6_old):
1350 uaddrlen = sizeof(struct sockaddr_in6);
1351 break;
1353 memset( uaddr, 0, uaddrlen );
1354 break;
1356 default:
1357 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
1358 return 0;
1360 return uaddrlen;
1363 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
1365 switch (uaddr->sa_family)
1367 #ifdef HAVE_IPX
1368 case AF_IPX:
1369 FIXME("don't know how to tell if IPX socket is bound, assuming it is!\n");
1370 return TRUE;
1371 #endif
1372 case AF_INET6:
1374 static const struct sockaddr_in6 emptyAddr;
1375 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
1376 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
1378 case AF_INET:
1380 static const struct sockaddr_in emptyAddr;
1381 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
1382 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
1384 case AF_UNSPEC:
1385 return FALSE;
1386 default:
1387 FIXME("unknown address family %d\n", uaddr->sa_family);
1388 return TRUE;
1392 /* Returns 0 if successful, -1 if the buffer is too small */
1393 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
1395 int res;
1397 switch(uaddr->sa_family)
1399 #ifdef HAVE_IPX
1400 case AF_IPX:
1402 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
1403 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
1405 res=-1;
1406 switch (*wsaddrlen) /* how much can we copy? */
1408 default:
1409 res=0; /* enough */
1410 *wsaddrlen = sizeof(*wsipx);
1411 wsipx->sa_socket=uipx->sipx_port;
1412 /* fall through */
1413 case 13:
1414 case 12:
1415 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
1416 /* fall through */
1417 case 11:
1418 case 10:
1419 case 9:
1420 case 8:
1421 case 7:
1422 case 6:
1423 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1424 /* fall through */
1425 case 5:
1426 case 4:
1427 case 3:
1428 case 2:
1429 wsipx->sa_family=WS_AF_IPX;
1430 /* fall through */
1431 case 1:
1432 case 0:
1433 /* way too small */
1434 break;
1437 break;
1438 #endif
1439 #ifdef HAVE_IRDA
1440 case AF_IRDA: {
1441 const struct sockaddr_irda *uin = (const struct sockaddr_irda *)uaddr;
1442 SOCKADDR_IRDA *win = (SOCKADDR_IRDA *)wsaddr;
1444 if (*wsaddrlen < sizeof(SOCKADDR_IRDA))
1445 return -1;
1446 win->irdaAddressFamily = WS_AF_IRDA;
1447 memcpy( win->irdaDeviceID, &uin->sir_addr, sizeof(win->irdaDeviceID) );
1448 if (uin->sir_lsap_sel != LSAP_ANY)
1449 sprintf( win->irdaServiceName, "LSAP-SEL%u", uin->sir_lsap_sel );
1450 else
1451 memcpy( win->irdaServiceName, uin->sir_name,
1452 sizeof(win->irdaServiceName) );
1453 return 0;
1455 #endif
1456 case AF_INET6: {
1457 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1458 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1460 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1461 return -1;
1462 win6old->sin6_family = WS_AF_INET6;
1463 win6old->sin6_port = uin6->sin6_port;
1464 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1465 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1466 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1467 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1468 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1469 win6->sin6_scope_id = uin6->sin6_scope_id;
1470 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1472 else
1473 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1474 #else
1475 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1476 #endif
1477 return 0;
1479 case AF_INET: {
1480 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1481 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1483 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1484 return -1;
1485 win->sin_family = WS_AF_INET;
1486 win->sin_port = uin->sin_port;
1487 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1488 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1489 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1490 return 0;
1492 case AF_UNSPEC: {
1493 memset(wsaddr,0,*wsaddrlen);
1494 return 0;
1496 default:
1497 FIXME("Unknown address family %d\n", uaddr->sa_family);
1498 return -1;
1500 return res;
1503 /**************************************************************************
1504 * Functions for handling overlapped I/O
1505 **************************************************************************/
1507 /* user APC called upon async completion */
1508 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1510 ws2_async *wsa = arg;
1512 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
1513 iosb->Information, wsa->user_overlapped,
1514 wsa->flags );
1515 HeapFree( GetProcessHeap(), 0, wsa );
1518 /***********************************************************************
1519 * WS2_recv (INTERNAL)
1521 * Workhorse for both synchronous and asynchronous recv() operations.
1523 static int WS2_recv( int fd, struct ws2_async *wsa )
1525 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1526 char pktbuf[512];
1527 #endif
1528 struct msghdr hdr;
1529 union generic_unix_sockaddr unix_sockaddr;
1530 int n;
1532 hdr.msg_name = NULL;
1534 if (wsa->addr)
1536 hdr.msg_namelen = sizeof(unix_sockaddr);
1537 hdr.msg_name = &unix_sockaddr;
1539 else
1540 hdr.msg_namelen = 0;
1542 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1543 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1544 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1545 hdr.msg_accrights = NULL;
1546 hdr.msg_accrightslen = 0;
1547 #else
1548 hdr.msg_control = pktbuf;
1549 hdr.msg_controllen = sizeof(pktbuf);
1550 hdr.msg_flags = 0;
1551 #endif
1553 if ( (n = recvmsg(fd, &hdr, wsa->flags)) == -1 )
1554 return -1;
1556 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1557 if (wsa->control)
1559 ERR("Message control headers cannot be properly supported on this system.\n");
1560 wsa->control->len = 0;
1562 #else
1563 if (wsa->control && !convert_control_headers(&hdr, wsa->control))
1565 WARN("Application passed insufficient room for control headers.\n");
1566 *wsa->lpFlags |= WS_MSG_CTRUNC;
1567 errno = EMSGSIZE;
1568 return -1;
1570 #endif
1572 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
1573 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
1575 * quoting linux 2.6 net/ipv4/tcp.c:
1576 * "According to UNIX98, msg_name/msg_namelen are ignored
1577 * on connected socket. I was just happy when found this 8) --ANK"
1579 * likewise MSDN says that lpFrom and lpFromlen are ignored for
1580 * connection-oriented sockets, so don't try to update lpFrom.
1582 if (wsa->addr && hdr.msg_namelen)
1583 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
1585 return n;
1588 /***********************************************************************
1589 * WS2_async_recv (INTERNAL)
1591 * Handler for overlapped recv() operations.
1593 static NTSTATUS WS2_async_recv( void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1595 ws2_async* wsa = user;
1596 int result = 0, fd;
1598 switch (status)
1600 case STATUS_ALERTED:
1601 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
1602 break;
1604 result = WS2_recv( fd, wsa );
1605 wine_server_release_fd( wsa->hSocket, fd );
1606 if (result >= 0)
1608 status = STATUS_SUCCESS;
1609 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1611 else
1613 if (errno == EINTR || errno == EAGAIN)
1615 status = STATUS_PENDING;
1616 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1618 else
1620 result = 0;
1621 status = wsaErrStatus();
1624 break;
1626 if (status != STATUS_PENDING)
1628 iosb->u.Status = status;
1629 iosb->Information = result;
1630 *apc = ws2_async_apc;
1632 return status;
1635 /* user APC called upon async accept completion */
1636 static void WINAPI ws2_async_accept_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1638 struct ws2_accept_async *wsa = arg;
1640 HeapFree( GetProcessHeap(), 0, wsa->read );
1641 HeapFree( GetProcessHeap(), 0, wsa );
1644 /***********************************************************************
1645 * WS2_async_accept_recv (INTERNAL)
1647 * This function is used to finish the read part of an accept request. It is
1648 * needed to place the completion on the correct socket (listener).
1650 static NTSTATUS WS2_async_accept_recv( void *arg, IO_STATUS_BLOCK *iosb, NTSTATUS status, void **apc )
1652 void *junk;
1653 struct ws2_accept_async *wsa = arg;
1655 status = WS2_async_recv( wsa->read, iosb, status, &junk );
1656 if (status == STATUS_PENDING)
1657 return status;
1659 if (wsa->user_overlapped->hEvent)
1660 SetEvent(wsa->user_overlapped->hEvent);
1661 if (wsa->cvalue)
1662 WS_AddCompletion( HANDLE2SOCKET(wsa->listen_socket), wsa->cvalue, iosb->u.Status, iosb->Information );
1664 *apc = ws2_async_accept_apc;
1665 return status;
1668 /***********************************************************************
1669 * WS2_async_accept (INTERNAL)
1671 * This is the function called to satisfy the AcceptEx callback
1673 static NTSTATUS WS2_async_accept( void *arg, IO_STATUS_BLOCK *iosb, NTSTATUS status, void **apc )
1675 struct ws2_accept_async *wsa = arg;
1676 int len;
1677 char *addr;
1679 TRACE("status: 0x%x listen: %p, accept: %p\n", status, wsa->listen_socket, wsa->accept_socket);
1681 if (status == STATUS_ALERTED)
1683 SERVER_START_REQ( accept_into_socket )
1685 req->lhandle = wine_server_obj_handle( wsa->listen_socket );
1686 req->ahandle = wine_server_obj_handle( wsa->accept_socket );
1687 status = wine_server_call( req );
1689 SERVER_END_REQ;
1691 if (status == STATUS_CANT_WAIT)
1692 return STATUS_PENDING;
1694 if (status == STATUS_INVALID_HANDLE)
1696 FIXME("AcceptEx accepting socket closed but request was not cancelled\n");
1697 status = STATUS_CANCELLED;
1700 else if (status == STATUS_HANDLES_CLOSED)
1701 status = STATUS_CANCELLED; /* strange windows behavior */
1703 if (status != STATUS_SUCCESS)
1704 goto finish;
1706 /* WS2 Spec says size param is extra 16 bytes long...what do we put in it? */
1707 addr = ((char *)wsa->buf) + wsa->data_len;
1708 len = wsa->local_len - sizeof(int);
1709 WS_getsockname(HANDLE2SOCKET(wsa->accept_socket),
1710 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
1711 *(int *)addr = len;
1713 addr += wsa->local_len;
1714 len = wsa->remote_len - sizeof(int);
1715 WS_getpeername(HANDLE2SOCKET(wsa->accept_socket),
1716 (struct WS_sockaddr *)(addr + sizeof(int)), &len);
1717 *(int *)addr = len;
1719 if (!wsa->read)
1720 goto finish;
1722 SERVER_START_REQ( register_async )
1724 req->type = ASYNC_TYPE_READ;
1725 req->async.handle = wine_server_obj_handle( wsa->accept_socket );
1726 req->async.callback = wine_server_client_ptr( WS2_async_accept_recv );
1727 req->async.iosb = wine_server_client_ptr( iosb );
1728 req->async.arg = wine_server_client_ptr( wsa );
1729 status = wine_server_call( req );
1731 SERVER_END_REQ;
1733 if (status != STATUS_PENDING)
1734 goto finish;
1736 /* The APC has finished but no completion should be sent for the operation yet, additional processing
1737 * needs to be performed by WS2_async_accept_recv() first. */
1738 return STATUS_MORE_PROCESSING_REQUIRED;
1740 finish:
1741 iosb->u.Status = status;
1742 iosb->Information = 0;
1744 if (wsa->user_overlapped->hEvent)
1745 SetEvent(wsa->user_overlapped->hEvent);
1747 *apc = ws2_async_accept_apc;
1748 return status;
1751 /***********************************************************************
1752 * WS2_send (INTERNAL)
1754 * Workhorse for both synchronous and asynchronous send() operations.
1756 static int WS2_send( int fd, struct ws2_async *wsa )
1758 struct msghdr hdr;
1759 union generic_unix_sockaddr unix_addr;
1760 int n, ret;
1762 hdr.msg_name = NULL;
1763 hdr.msg_namelen = 0;
1765 if (wsa->addr)
1767 hdr.msg_name = &unix_addr;
1768 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
1769 if ( !hdr.msg_namelen )
1771 errno = EFAULT;
1772 return -1;
1775 #if defined(HAVE_IPX) && defined(SOL_IPX)
1776 if(wsa->addr->sa_family == WS_AF_IPX)
1778 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
1779 int val=0;
1780 socklen_t len = sizeof(int);
1782 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
1783 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
1784 * the packet type and then we can retrieve it using getsockopt. After that we can set the
1785 * ipx type in the sockaddr_opx structure with the stored value.
1787 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
1788 uipx->sipx_type = val;
1790 #endif
1793 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1794 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1795 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1796 hdr.msg_accrights = NULL;
1797 hdr.msg_accrightslen = 0;
1798 #else
1799 hdr.msg_control = NULL;
1800 hdr.msg_controllen = 0;
1801 hdr.msg_flags = 0;
1802 #endif
1804 ret = sendmsg(fd, &hdr, wsa->flags);
1805 if (ret >= 0)
1807 n = ret;
1808 while (wsa->first_iovec < wsa->n_iovecs && wsa->iovec[wsa->first_iovec].iov_len <= n)
1809 n -= wsa->iovec[wsa->first_iovec++].iov_len;
1810 if (wsa->first_iovec < wsa->n_iovecs)
1812 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
1813 wsa->iovec[wsa->first_iovec].iov_len -= n;
1816 return ret;
1819 /***********************************************************************
1820 * WS2_async_send (INTERNAL)
1822 * Handler for overlapped send() operations.
1824 static NTSTATUS WS2_async_send(void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1826 ws2_async* wsa = user;
1827 int result = 0, fd;
1829 switch (status)
1831 case STATUS_ALERTED:
1832 if ( wsa->n_iovecs <= wsa->first_iovec )
1834 /* Nothing to do */
1835 status = STATUS_SUCCESS;
1836 break;
1838 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
1839 break;
1841 /* check to see if the data is ready (non-blocking) */
1842 result = WS2_send( fd, wsa );
1843 wine_server_release_fd( wsa->hSocket, fd );
1845 if (result >= 0)
1847 if (wsa->first_iovec < wsa->n_iovecs)
1848 status = STATUS_PENDING;
1849 else
1850 status = STATUS_SUCCESS;
1852 iosb->Information += result;
1854 else if (errno == EINTR || errno == EAGAIN)
1856 status = STATUS_PENDING;
1858 else
1860 status = wsaErrStatus();
1862 break;
1864 if (status != STATUS_PENDING)
1866 iosb->u.Status = status;
1867 *apc = ws2_async_apc;
1869 return status;
1872 /***********************************************************************
1873 * WS2_async_shutdown (INTERNAL)
1875 * Handler for shutdown() operations on overlapped sockets.
1877 static NTSTATUS WS2_async_shutdown( void* user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc )
1879 ws2_async* wsa = user;
1880 int fd, err = 1;
1882 switch (status)
1884 case STATUS_ALERTED:
1885 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
1886 break;
1888 switch ( wsa->type )
1890 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
1891 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
1893 status = err ? wsaErrStatus() : STATUS_SUCCESS;
1894 wine_server_release_fd( wsa->hSocket, fd );
1895 break;
1897 iosb->u.Status = status;
1898 iosb->Information = 0;
1899 *apc = ws2_async_apc;
1900 return status;
1903 /***********************************************************************
1904 * WS2_register_async_shutdown (INTERNAL)
1906 * Helper function for WS_shutdown() on overlapped sockets.
1908 static int WS2_register_async_shutdown( SOCKET s, int type )
1910 struct ws2_async *wsa;
1911 NTSTATUS status;
1913 TRACE("s %ld type %d\n", s, type);
1915 wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( struct ws2_async, iovec[1] ));
1916 if ( !wsa )
1917 return WSAEFAULT;
1919 wsa->hSocket = SOCKET2HANDLE(s);
1920 wsa->type = type;
1921 wsa->completion_func = NULL;
1923 SERVER_START_REQ( register_async )
1925 req->type = type;
1926 req->async.handle = wine_server_obj_handle( wsa->hSocket );
1927 req->async.callback = wine_server_client_ptr( WS2_async_shutdown );
1928 req->async.iosb = wine_server_client_ptr( &wsa->local_iosb );
1929 req->async.arg = wine_server_client_ptr( wsa );
1930 req->async.cvalue = 0;
1931 status = wine_server_call( req );
1933 SERVER_END_REQ;
1935 if (status != STATUS_PENDING)
1937 HeapFree( GetProcessHeap(), 0, wsa );
1938 return NtStatusToWSAError( status );
1940 return 0;
1943 /***********************************************************************
1944 * accept (WS2_32.1)
1946 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr,
1947 int *addrlen32)
1949 NTSTATUS status;
1950 SOCKET as;
1951 BOOL is_blocking;
1953 TRACE("socket %04lx\n", s );
1954 status = _is_blocking(s, &is_blocking);
1955 if (status)
1957 set_error(status);
1958 return INVALID_SOCKET;
1961 do {
1962 /* try accepting first (if there is a deferred connection) */
1963 SERVER_START_REQ( accept_socket )
1965 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1966 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
1967 req->attributes = OBJ_INHERIT;
1968 status = wine_server_call( req );
1969 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
1971 SERVER_END_REQ;
1972 if (!status)
1974 if (addr) WS_getpeername(as, addr, addrlen32);
1975 return as;
1977 if (is_blocking && status == STATUS_CANT_WAIT)
1979 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1980 /* block here */
1981 do_block(fd, POLLIN, -1);
1982 _sync_sock_state(s); /* let wineserver notice connection */
1983 release_sock_fd( s, fd );
1985 } while (is_blocking && status == STATUS_CANT_WAIT);
1987 set_error(status);
1988 return INVALID_SOCKET;
1991 /***********************************************************************
1992 * AcceptEx
1994 static BOOL WINAPI WS2_AcceptEx(SOCKET listener, SOCKET acceptor, PVOID dest, DWORD dest_len,
1995 DWORD local_addr_len, DWORD rem_addr_len, LPDWORD received,
1996 LPOVERLAPPED overlapped)
1998 DWORD status;
1999 struct ws2_accept_async *wsa;
2000 int fd;
2001 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
2003 TRACE("(%lx, %lx, %p, %d, %d, %d, %p, %p)\n", listener, acceptor, dest, dest_len, local_addr_len,
2004 rem_addr_len, received, overlapped);
2006 if (!dest)
2008 SetLastError(WSAEINVAL);
2009 return FALSE;
2012 if (!overlapped)
2014 SetLastError(WSA_INVALID_PARAMETER);
2015 return FALSE;
2018 fd = get_sock_fd( listener, FILE_READ_DATA, NULL );
2019 if (fd == -1)
2021 SetLastError(WSAENOTSOCK);
2022 return FALSE;
2024 release_sock_fd( listener, fd );
2026 fd = get_sock_fd( acceptor, FILE_READ_DATA, NULL );
2027 if (fd == -1)
2029 SetLastError(WSAEINVAL);
2030 return FALSE;
2032 release_sock_fd( acceptor, fd );
2034 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
2035 if(!wsa)
2037 SetLastError(WSAEFAULT);
2038 return FALSE;
2041 wsa->listen_socket = SOCKET2HANDLE(listener);
2042 wsa->accept_socket = SOCKET2HANDLE(acceptor);
2043 wsa->user_overlapped = overlapped;
2044 wsa->cvalue = cvalue;
2045 wsa->buf = dest;
2046 wsa->data_len = dest_len;
2047 wsa->local_len = local_addr_len;
2048 wsa->remote_len = rem_addr_len;
2049 wsa->read = NULL;
2051 if (wsa->data_len)
2053 /* set up a read request if we need it */
2054 wsa->read = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[1]) );
2055 if (!wsa->read)
2057 HeapFree( GetProcessHeap(), 0, wsa );
2058 SetLastError(WSAEFAULT);
2059 return FALSE;
2062 wsa->read->hSocket = wsa->accept_socket;
2063 wsa->read->flags = 0;
2064 wsa->read->lpFlags = &wsa->read->flags;
2065 wsa->read->addr = NULL;
2066 wsa->read->addrlen.ptr = NULL;
2067 wsa->read->control = NULL;
2068 wsa->read->n_iovecs = 1;
2069 wsa->read->first_iovec = 0;
2070 wsa->read->iovec[0].iov_base = wsa->buf;
2071 wsa->read->iovec[0].iov_len = wsa->data_len;
2074 SERVER_START_REQ( register_async )
2076 req->type = ASYNC_TYPE_READ;
2077 req->async.handle = wine_server_obj_handle( SOCKET2HANDLE(listener) );
2078 req->async.callback = wine_server_client_ptr( WS2_async_accept );
2079 req->async.iosb = wine_server_client_ptr( overlapped );
2080 req->async.arg = wine_server_client_ptr( wsa );
2081 req->async.cvalue = cvalue;
2082 /* We don't set event since we may also have to read */
2083 status = wine_server_call( req );
2085 SERVER_END_REQ;
2087 if(status != STATUS_PENDING)
2089 HeapFree( GetProcessHeap(), 0, wsa->read );
2090 HeapFree( GetProcessHeap(), 0, wsa );
2093 SetLastError( NtStatusToWSAError(status) );
2094 return FALSE;
2097 /***********************************************************************
2098 * GetAcceptExSockaddrs
2100 static void WINAPI WS2_GetAcceptExSockaddrs(PVOID buffer, DWORD data_size, DWORD local_size, DWORD remote_size,
2101 struct WS_sockaddr **local_addr, LPINT local_addr_len,
2102 struct WS_sockaddr **remote_addr, LPINT remote_addr_len)
2104 char *cbuf = buffer;
2105 TRACE("(%p, %d, %d, %d, %p, %p, %p, %p)\n", buffer, data_size, local_size, remote_size, local_addr,
2106 local_addr_len, remote_addr, remote_addr_len );
2107 cbuf += data_size;
2109 *local_addr_len = *(int *) cbuf;
2110 *local_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2112 cbuf += local_size;
2114 *remote_addr_len = *(int *) cbuf;
2115 *remote_addr = (struct WS_sockaddr *)(cbuf + sizeof(int));
2118 /***********************************************************************
2119 * WSARecvMsg
2121 * Perform a receive operation that is capable of returning message
2122 * control headers. It is important to note that the WSAMSG parameter
2123 * must remain valid throughout the operation, even when an overlapped
2124 * receive is performed.
2126 static int WINAPI WS2_WSARecvMsg( SOCKET s, LPWSAMSG msg, LPDWORD lpNumberOfBytesRecvd,
2127 LPWSAOVERLAPPED lpOverlapped,
2128 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2130 if (!msg)
2132 SetLastError( WSAEFAULT );
2133 return SOCKET_ERROR;
2136 return WS2_recv_base( s, msg->lpBuffers, msg->dwBufferCount, lpNumberOfBytesRecvd,
2137 &msg->dwFlags, msg->name, &msg->namelen,
2138 lpOverlapped, lpCompletionRoutine, &msg->Control );
2141 /***********************************************************************
2142 * interface_bind (INTERNAL)
2144 * Take bind() calls on any name corresponding to a local network adapter and restrict the given socket to
2145 * operating only on the specified interface. This restriction consists of two components:
2146 * 1) An outgoing packet restriction suggesting the egress interface for all packets.
2147 * 2) An incoming packet restriction dropping packets not meant for the interface.
2148 * If the function succeeds in placing these restrictions (returns TRUE) then the name for the bind() may
2149 * safely be changed to INADDR_ANY, permitting the transmission and receipt of broadcast packets on the
2150 * socket. This behavior is only relevant to UDP sockets and is needed for applications that expect to be able
2151 * to receive broadcast packets on a socket that is bound to a specific network interface.
2153 static BOOL interface_bind( SOCKET s, int fd, struct sockaddr *addr )
2155 struct sockaddr_in *in_sock = (struct sockaddr_in *) addr;
2156 unsigned int sock_type = 0;
2157 socklen_t optlen = sizeof(sock_type);
2158 in_addr_t bind_addr = in_sock->sin_addr.s_addr;
2159 PIP_ADAPTER_INFO adapters = NULL, adapter;
2160 BOOL ret = FALSE;
2161 DWORD adap_size;
2162 int enable = 1;
2164 if (bind_addr == htonl(WS_INADDR_ANY) || bind_addr == htonl(WS_INADDR_LOOPBACK))
2165 return FALSE; /* Not binding to a network adapter, special interface binding unnecessary. */
2166 if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &sock_type, &optlen) == -1 || sock_type != SOCK_DGRAM)
2167 return FALSE; /* Special interface binding is only necessary for UDP datagrams. */
2168 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
2169 goto cleanup;
2170 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
2171 if (adapters == NULL || GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
2172 goto cleanup;
2173 /* Search the IPv4 adapter list for the appropriate binding interface */
2174 for (adapter = adapters; adapter != NULL; adapter = adapter->Next)
2176 in_addr_t adapter_addr = (in_addr_t) inet_addr(adapter->IpAddressList.IpAddress.String);
2178 if (bind_addr == adapter_addr)
2180 #if defined(IP_BOUND_IF)
2181 /* IP_BOUND_IF sets both the incoming and outgoing restriction at once */
2182 if (setsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &adapter->Index, sizeof(adapter->Index)) != 0)
2183 goto cleanup;
2184 ret = TRUE;
2185 #elif defined(LINUX_BOUND_IF)
2186 in_addr_t ifindex = (in_addr_t) htonl(adapter->Index);
2187 struct interface_filter specific_interface_filter;
2188 struct sock_fprog filter_prog;
2190 if (setsockopt(fd, IPPROTO_IP, IP_UNICAST_IF, &ifindex, sizeof(ifindex)) != 0)
2191 goto cleanup; /* Failed to suggest egress interface */
2192 specific_interface_filter = generic_interface_filter;
2193 specific_interface_filter.iface_rule.k = adapter->Index;
2194 filter_prog.len = sizeof(generic_interface_filter)/sizeof(struct sock_filter);
2195 filter_prog.filter = (struct sock_filter *) &specific_interface_filter;
2196 if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog, sizeof(filter_prog)) != 0)
2197 goto cleanup; /* Failed to specify incoming packet filter */
2198 ret = TRUE;
2199 #else
2200 FIXME("Broadcast packets on interface-bound sockets are not currently supported on this platform, "
2201 "receiving broadcast packets will not work on socket %04lx.\n", s);
2202 #endif
2203 break;
2206 /* Will soon be switching to INADDR_ANY: permit address reuse */
2207 if (ret && setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) == 0)
2208 TRACE("Socket %04lx bound to interface index %d\n", s, adapter->Index);
2209 else
2210 ret = FALSE;
2212 cleanup:
2213 if(!ret)
2214 ERR("Failed to bind to interface, receiving broadcast packets will not work on socket %04lx.\n", s);
2215 HeapFree(GetProcessHeap(), 0, adapters);
2216 return ret;
2219 /***********************************************************************
2220 * bind (WS2_32.2)
2222 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
2224 int fd = get_sock_fd( s, 0, NULL );
2225 int res = SOCKET_ERROR;
2227 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2229 if (fd != -1)
2231 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
2233 SetLastError(WSAEAFNOSUPPORT);
2235 else
2237 union generic_unix_sockaddr uaddr;
2238 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2239 if (!uaddrlen)
2241 SetLastError(WSAEFAULT);
2243 else
2245 #ifdef IPV6_V6ONLY
2246 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
2247 if (name->sa_family == WS_AF_INET6 &&
2248 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
2250 int enable = 1;
2251 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
2253 release_sock_fd( s, fd );
2254 SetLastError(WSAEAFNOSUPPORT);
2255 return SOCKET_ERROR;
2258 #endif
2259 if (name->sa_family == WS_AF_INET)
2261 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2262 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2264 /* Trying to bind to the default host interface, using
2265 * INADDR_ANY instead*/
2266 WARN("Trying to bind to magic IP address, using "
2267 "INADDR_ANY instead.\n");
2268 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
2270 else if (interface_bind(s, fd, &uaddr.addr))
2271 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
2273 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
2275 int loc_errno = errno;
2276 WARN("\tfailure - errno = %i\n", errno);
2277 errno = loc_errno;
2278 switch (errno)
2280 case EBADF:
2281 SetLastError(WSAENOTSOCK);
2282 break;
2283 case EADDRNOTAVAIL:
2284 SetLastError(WSAEINVAL);
2285 break;
2286 default:
2287 SetLastError(wsaErrno());
2288 break;
2291 else
2293 res=0; /* success */
2297 release_sock_fd( s, fd );
2299 return res;
2302 /***********************************************************************
2303 * closesocket (WS2_32.3)
2305 int WINAPI WS_closesocket(SOCKET s)
2307 TRACE("socket %04lx\n", s);
2308 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
2309 return SOCKET_ERROR;
2312 static int do_connect(int fd, const struct WS_sockaddr* name, int namelen)
2314 union generic_unix_sockaddr uaddr;
2315 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
2317 if (!uaddrlen)
2318 return WSAEFAULT;
2320 if (name->sa_family == WS_AF_INET)
2322 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
2323 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
2325 /* Trying to connect to magic replace-loopback address,
2326 * assuming we really want to connect to localhost */
2327 TRACE("Trying to connect to magic IP address, using "
2328 "INADDR_LOOPBACK instead.\n");
2329 in4->sin_addr.s_addr = htonl(WS_INADDR_LOOPBACK);
2333 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
2334 return 0;
2336 return wsaErrno();
2339 /***********************************************************************
2340 * connect (WS2_32.4)
2342 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
2344 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2346 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
2348 if (fd != -1)
2350 NTSTATUS status;
2351 BOOL is_blocking;
2352 int ret = do_connect(fd, name, namelen);
2353 if (ret == 0)
2354 goto connect_success;
2356 if (ret == WSAEINPROGRESS)
2358 /* tell wineserver that a connection is in progress */
2359 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2360 FD_CONNECT,
2361 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2362 status = _is_blocking( s, &is_blocking );
2363 if (status)
2365 release_sock_fd( s, fd );
2366 set_error( status );
2367 return SOCKET_ERROR;
2369 if (is_blocking)
2371 int result;
2372 /* block here */
2373 do_block(fd, POLLIN | POLLOUT, -1);
2374 _sync_sock_state(s); /* let wineserver notice connection */
2375 /* retrieve any error codes from it */
2376 result = _get_sock_error(s, FD_CONNECT_BIT);
2377 if (result)
2378 SetLastError(NtStatusToWSAError(result));
2379 else
2381 goto connect_success;
2384 else
2386 SetLastError(WSAEWOULDBLOCK);
2389 else
2391 SetLastError(ret);
2393 release_sock_fd( s, fd );
2395 return SOCKET_ERROR;
2397 connect_success:
2398 release_sock_fd( s, fd );
2399 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2400 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2401 FD_CONNECT|FD_WINE_LISTENING);
2402 return 0;
2405 /***********************************************************************
2406 * WSAConnect (WS2_32.30)
2408 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
2409 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
2410 LPQOS lpSQOS, LPQOS lpGQOS )
2412 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
2413 FIXME("unsupported parameters!\n");
2414 return WS_connect( s, name, namelen );
2417 /***********************************************************************
2418 * ConnectEx
2420 static BOOL WINAPI WS2_ConnectEx(SOCKET s, const struct WS_sockaddr* name, int namelen,
2421 PVOID sendBuf, DWORD sendBufLen, LPDWORD sent, LPOVERLAPPED ov)
2423 int fd, ret, status;
2425 if (!ov)
2427 SetLastError( ERROR_INVALID_PARAMETER );
2428 return FALSE;
2431 fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2432 if (fd == -1)
2434 SetLastError( WSAENOTSOCK );
2435 return FALSE;
2438 TRACE("socket %04lx, ptr %p %s, length %d, sendptr %p, len %d, ov %p\n",
2439 s, name, debugstr_sockaddr(name), namelen, sendBuf, sendBufLen, ov);
2441 /* FIXME: technically the socket has to be bound */
2442 ret = do_connect(fd, name, namelen);
2443 if (ret == 0)
2445 WSABUF wsabuf;
2447 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2448 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
2449 FD_CONNECT|FD_WINE_LISTENING);
2451 wsabuf.len = sendBufLen;
2452 wsabuf.buf = (char*) sendBuf;
2454 /* WSASend takes care of completion if need be */
2455 if (WSASend(s, &wsabuf, sendBuf ? 1 : 0, sent, 0, ov, NULL) != SOCKET_ERROR)
2456 goto connection_success;
2458 else if (ret == WSAEINPROGRESS)
2460 struct ws2_async *wsa;
2461 ULONG_PTR cvalue = (((ULONG_PTR)ov->hEvent & 1) == 0) ? (ULONG_PTR)ov : 0;
2463 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
2464 FD_CONNECT,
2465 FD_WINE_CONNECTED|FD_WINE_LISTENING);
2467 /* Indirectly call WSASend */
2468 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET( struct ws2_async, iovec[1] ))))
2470 SetLastError(WSAEFAULT);
2472 else
2474 IO_STATUS_BLOCK *iosb = (IO_STATUS_BLOCK *)ov;
2475 iosb->u.Status = STATUS_PENDING;
2476 iosb->Information = 0;
2478 wsa->hSocket = SOCKET2HANDLE(s);
2479 wsa->addr = NULL;
2480 wsa->addrlen.val = 0;
2481 wsa->flags = 0;
2482 wsa->lpFlags = &wsa->flags;
2483 wsa->control = NULL;
2484 wsa->n_iovecs = sendBuf ? 1 : 0;
2485 wsa->first_iovec = 0;
2486 wsa->completion_func = NULL;
2487 wsa->iovec[0].iov_base = sendBuf;
2488 wsa->iovec[0].iov_len = sendBufLen;
2490 SERVER_START_REQ( register_async )
2492 req->type = ASYNC_TYPE_WRITE;
2493 req->async.handle = wine_server_obj_handle( wsa->hSocket );
2494 req->async.callback = wine_server_client_ptr( WS2_async_send );
2495 req->async.iosb = wine_server_client_ptr( iosb );
2496 req->async.arg = wine_server_client_ptr( wsa );
2497 req->async.event = wine_server_obj_handle( ov->hEvent );
2498 req->async.cvalue = cvalue;
2499 status = wine_server_call( req );
2501 SERVER_END_REQ;
2503 if (status != STATUS_PENDING) HeapFree(GetProcessHeap(), 0, wsa);
2505 /* If the connect already failed */
2506 if (status == STATUS_PIPE_DISCONNECTED)
2507 status = _get_sock_error(s, FD_CONNECT_BIT);
2508 SetLastError( NtStatusToWSAError(status) );
2511 else
2513 SetLastError(ret);
2516 release_sock_fd( s, fd );
2517 return FALSE;
2519 connection_success:
2520 release_sock_fd( s, fd );
2521 return TRUE;
2525 /***********************************************************************
2526 * getpeername (WS2_32.5)
2528 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
2530 int fd;
2531 int res;
2533 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
2535 fd = get_sock_fd( s, 0, NULL );
2536 res = SOCKET_ERROR;
2538 if (fd != -1)
2540 union generic_unix_sockaddr uaddr;
2541 socklen_t uaddrlen = sizeof(uaddr);
2543 if (getpeername(fd, &uaddr.addr, &uaddrlen) == 0)
2545 if (!name || !namelen)
2546 SetLastError(WSAEFAULT);
2547 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
2548 /* The buffer was too small */
2549 SetLastError(WSAEFAULT);
2550 else
2551 res = 0;
2553 else
2554 SetLastError(wsaErrno());
2555 release_sock_fd( s, fd );
2557 return res;
2560 /***********************************************************************
2561 * getsockname (WS2_32.6)
2563 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
2565 int fd;
2566 int res;
2568 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, namelen ? *namelen : 0);
2570 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
2571 if( (name == NULL) || (namelen == NULL) )
2573 SetLastError( WSAEFAULT );
2574 return SOCKET_ERROR;
2577 fd = get_sock_fd( s, 0, NULL );
2578 res = SOCKET_ERROR;
2580 if (fd != -1)
2582 union generic_unix_sockaddr uaddr;
2583 socklen_t uaddrlen = sizeof(uaddr);
2585 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
2587 SetLastError(wsaErrno());
2589 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
2591 SetLastError(WSAEINVAL);
2593 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
2595 /* The buffer was too small */
2596 SetLastError(WSAEFAULT);
2598 else
2600 res=0;
2602 release_sock_fd( s, fd );
2604 return res;
2607 /***********************************************************************
2608 * getsockopt (WS2_32.7)
2610 INT WINAPI WS_getsockopt(SOCKET s, INT level,
2611 INT optname, char *optval, INT *optlen)
2613 int fd;
2614 INT ret = 0;
2616 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
2617 s, level, optname, optval, *optlen);
2619 switch(level)
2621 case WS_SOL_SOCKET:
2623 switch(optname)
2625 /* Handle common cases. The special cases are below, sorted
2626 * alphabetically */
2627 case WS_SO_ACCEPTCONN:
2628 case WS_SO_BROADCAST:
2629 case WS_SO_DEBUG:
2630 case WS_SO_ERROR:
2631 case WS_SO_KEEPALIVE:
2632 case WS_SO_OOBINLINE:
2633 case WS_SO_RCVBUF:
2634 case WS_SO_REUSEADDR:
2635 case WS_SO_SNDBUF:
2636 case WS_SO_TYPE:
2637 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2638 return SOCKET_ERROR;
2639 convert_sockopt(&level, &optname);
2640 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
2642 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2643 ret = SOCKET_ERROR;
2645 release_sock_fd( s, fd );
2646 return ret;
2648 case WS_SO_DONTLINGER:
2650 struct linger lingval;
2651 socklen_t len = sizeof(struct linger);
2653 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
2655 SetLastError(WSAEFAULT);
2656 return SOCKET_ERROR;
2658 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2659 return SOCKET_ERROR;
2661 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
2663 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2664 ret = SOCKET_ERROR;
2666 else
2668 *(BOOL *)optval = !lingval.l_onoff;
2669 *optlen = sizeof(BOOL);
2672 release_sock_fd( s, fd );
2673 return ret;
2676 case WS_SO_CONNECT_TIME:
2678 static int pretendtime = 0;
2679 struct WS_sockaddr addr;
2680 int len = sizeof(addr);
2682 if (!optlen || *optlen < sizeof(DWORD) || !optval)
2684 SetLastError(WSAEFAULT);
2685 return SOCKET_ERROR;
2687 if (WS_getpeername(s, &addr, &len) == SOCKET_ERROR)
2688 *(DWORD *)optval = ~0u;
2689 else
2691 if (!pretendtime) FIXME("WS_SO_CONNECT_TIME - faking results\n");
2692 *(DWORD *)optval = pretendtime++;
2694 *optlen = sizeof(DWORD);
2695 return ret;
2697 /* As mentioned in setsockopt, Windows ignores this, so we
2698 * always return true here */
2699 case WS_SO_DONTROUTE:
2700 if (!optlen || *optlen < sizeof(BOOL) || !optval)
2702 SetLastError(WSAEFAULT);
2703 return SOCKET_ERROR;
2705 *(BOOL *)optval = TRUE;
2706 *optlen = sizeof(BOOL);
2707 return 0;
2709 case WS_SO_LINGER:
2711 struct linger lingval;
2712 int so_type;
2713 socklen_t len = sizeof(struct linger), slen = sizeof(int);
2715 /* struct linger and LINGER have different sizes */
2716 if (!optlen || *optlen < sizeof(LINGER) || !optval)
2718 SetLastError(WSAEFAULT);
2719 return SOCKET_ERROR;
2721 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2722 return SOCKET_ERROR;
2724 if ((getsockopt(fd, SOL_SOCKET, SO_TYPE, &so_type, &slen) == 0 && so_type == SOCK_DGRAM))
2726 SetLastError(WSAENOPROTOOPT);
2727 ret = SOCKET_ERROR;
2729 else if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0)
2731 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2732 ret = SOCKET_ERROR;
2734 else
2736 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
2737 ((LINGER *)optval)->l_linger = lingval.l_linger;
2738 *optlen = sizeof(struct linger);
2741 release_sock_fd( s, fd );
2742 return ret;
2745 case WS_SO_MAX_MSG_SIZE:
2746 if (!optlen || *optlen < sizeof(int) || !optval)
2748 SetLastError(WSAEFAULT);
2749 return SOCKET_ERROR;
2751 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
2752 *(int *)optval = 65507;
2753 *optlen = sizeof(int);
2754 return 0;
2756 /* SO_OPENTYPE does not require a valid socket handle. */
2757 case WS_SO_OPENTYPE:
2758 if (!optlen || *optlen < sizeof(int) || !optval)
2760 SetLastError(WSAEFAULT);
2761 return SOCKET_ERROR;
2763 *(int *)optval = get_per_thread_data()->opentype;
2764 *optlen = sizeof(int);
2765 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
2766 return 0;
2768 #ifdef SO_RCVTIMEO
2769 case WS_SO_RCVTIMEO:
2770 #endif
2771 #ifdef SO_SNDTIMEO
2772 case WS_SO_SNDTIMEO:
2773 #endif
2774 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
2776 struct timeval tv;
2777 socklen_t len = sizeof(struct timeval);
2779 if (!optlen || *optlen < sizeof(int)|| !optval)
2781 SetLastError(WSAEFAULT);
2782 return SOCKET_ERROR;
2784 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2785 return SOCKET_ERROR;
2787 convert_sockopt(&level, &optname);
2788 if (getsockopt(fd, level, optname, &tv, &len) != 0 )
2790 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2791 ret = SOCKET_ERROR;
2793 else
2795 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
2796 *optlen = sizeof(int);
2799 release_sock_fd( s, fd );
2800 return ret;
2802 #endif
2803 default:
2804 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
2805 SetLastError(WSAENOPROTOOPT);
2806 return SOCKET_ERROR;
2807 } /* end switch(optname) */
2808 }/* end case WS_SOL_SOCKET */
2809 #ifdef HAVE_IPX
2810 case NSPROTO_IPX:
2812 struct WS_sockaddr_ipx addr;
2813 IPX_ADDRESS_DATA *data;
2814 int namelen;
2815 switch(optname)
2817 case IPX_PTYPE:
2818 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
2819 #ifdef SOL_IPX
2820 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (socklen_t *)optlen) == -1)
2822 ret = SOCKET_ERROR;
2824 #else
2826 struct ipx val;
2827 socklen_t len=sizeof(struct ipx);
2828 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
2829 ret = SOCKET_ERROR;
2830 else
2831 *optval = (int)val.ipx_pt;
2833 #endif
2834 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
2835 release_sock_fd( s, fd );
2836 return ret;
2838 case IPX_ADDRESS:
2840 * On a Win2000 system with one network card there are usually
2841 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
2842 * Using this call you can then retrieve info about this all.
2843 * In case of Linux it is a bit different. Usually you have
2844 * only "one" device active and further it is not possible to
2845 * query things like the linkspeed.
2847 FIXME("IPX_ADDRESS\n");
2848 namelen = sizeof(struct WS_sockaddr_ipx);
2849 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
2850 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
2852 data = (IPX_ADDRESS_DATA*)optval;
2853 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
2854 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
2855 data->adapternum = 0;
2856 data->wan = FALSE; /* We are not on a wan for now .. */
2857 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
2858 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
2859 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
2860 * note 1MB = 1000kB in this case */
2861 return 0;
2863 case IPX_MAX_ADAPTER_NUM:
2864 FIXME("IPX_MAX_ADAPTER_NUM\n");
2865 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
2866 return 0;
2868 default:
2869 FIXME("IPX optname:%x\n", optname);
2870 return SOCKET_ERROR;
2871 }/* end switch(optname) */
2872 } /* end case NSPROTO_IPX */
2873 #endif
2875 #ifdef HAVE_IRDA
2876 case WS_SOL_IRLMP:
2877 switch(optname)
2879 case WS_IRLMP_ENUMDEVICES:
2881 static const int MAX_IRDA_DEVICES = 10;
2882 char buf[sizeof(struct irda_device_list) +
2883 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
2884 int res;
2885 socklen_t len = sizeof(buf);
2887 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2888 return SOCKET_ERROR;
2889 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
2890 if (res < 0)
2892 SetLastError(wsaErrno());
2893 return SOCKET_ERROR;
2895 else
2897 struct irda_device_list *src = (struct irda_device_list *)buf;
2898 DEVICELIST *dst = (DEVICELIST *)optval;
2899 INT needed = sizeof(DEVICELIST);
2900 unsigned int i;
2902 if (src->len > 0)
2903 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
2904 if (*optlen < needed)
2906 SetLastError(WSAEFAULT);
2907 return SOCKET_ERROR;
2909 *optlen = needed;
2910 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
2911 dst->numDevice = src->len;
2912 for (i = 0; i < src->len; i++)
2914 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
2915 src->dev[i].saddr, src->dev[i].daddr,
2916 src->dev[i].info, src->dev[i].hints[0],
2917 src->dev[i].hints[1]);
2918 memcpy( dst->Device[i].irdaDeviceID,
2919 &src->dev[i].daddr,
2920 sizeof(dst->Device[i].irdaDeviceID) ) ;
2921 memcpy( dst->Device[i].irdaDeviceName,
2922 src->dev[i].info,
2923 sizeof(dst->Device[i].irdaDeviceName) ) ;
2924 memcpy( &dst->Device[i].irdaDeviceHints1,
2925 &src->dev[i].hints[0],
2926 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
2927 memcpy( &dst->Device[i].irdaDeviceHints2,
2928 &src->dev[i].hints[1],
2929 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
2930 dst->Device[i].irdaCharSet = src->dev[i].charset;
2932 return 0;
2935 default:
2936 FIXME("IrDA optname:0x%x\n", optname);
2937 return SOCKET_ERROR;
2939 break; /* case WS_SOL_IRLMP */
2940 #endif
2942 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
2943 case WS_IPPROTO_TCP:
2944 switch(optname)
2946 case WS_TCP_NODELAY:
2947 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2948 return SOCKET_ERROR;
2949 convert_sockopt(&level, &optname);
2950 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
2952 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2953 ret = SOCKET_ERROR;
2955 release_sock_fd( s, fd );
2956 return ret;
2958 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
2959 return SOCKET_ERROR;
2961 case WS_IPPROTO_IP:
2962 switch(optname)
2964 case WS_IP_ADD_MEMBERSHIP:
2965 case WS_IP_DROP_MEMBERSHIP:
2966 #ifdef IP_HDRINCL
2967 case WS_IP_HDRINCL:
2968 #endif
2969 case WS_IP_MULTICAST_IF:
2970 case WS_IP_MULTICAST_LOOP:
2971 case WS_IP_MULTICAST_TTL:
2972 case WS_IP_OPTIONS:
2973 #ifdef IP_PKTINFO
2974 case WS_IP_PKTINFO:
2975 #endif
2976 case WS_IP_TOS:
2977 case WS_IP_TTL:
2978 #ifdef IP_UNICAST_IF
2979 case WS_IP_UNICAST_IF:
2980 #endif
2981 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2982 return SOCKET_ERROR;
2983 convert_sockopt(&level, &optname);
2984 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
2986 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2987 ret = SOCKET_ERROR;
2989 release_sock_fd( s, fd );
2990 return ret;
2991 case WS_IP_DONTFRAGMENT:
2992 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
2993 *(BOOL*)optval = FALSE;
2994 return 0;
2996 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
2997 return SOCKET_ERROR;
2999 case WS_IPPROTO_IPV6:
3000 switch(optname)
3002 #ifdef IPV6_ADD_MEMBERSHIP
3003 case WS_IPV6_ADD_MEMBERSHIP:
3004 #endif
3005 #ifdef IPV6_DROP_MEMBERSHIP
3006 case WS_IPV6_DROP_MEMBERSHIP:
3007 #endif
3008 case WS_IPV6_MULTICAST_IF:
3009 case WS_IPV6_MULTICAST_HOPS:
3010 case WS_IPV6_MULTICAST_LOOP:
3011 case WS_IPV6_UNICAST_HOPS:
3012 case WS_IPV6_V6ONLY:
3013 #ifdef IPV6_UNICAST_IF
3014 case WS_IPV6_UNICAST_IF:
3015 #endif
3016 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
3017 return SOCKET_ERROR;
3018 convert_sockopt(&level, &optname);
3019 if (getsockopt(fd, level, optname, optval, (socklen_t *)optlen) != 0 )
3021 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
3022 ret = SOCKET_ERROR;
3024 release_sock_fd( s, fd );
3025 return ret;
3026 case WS_IPV6_DONTFRAG:
3027 FIXME("WS_IPV6_DONTFRAG is always false!\n");
3028 *(BOOL*)optval = FALSE;
3029 return 0;
3031 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
3032 return SOCKET_ERROR;
3034 default:
3035 WARN("Unknown level: 0x%08x\n", level);
3036 SetLastError(WSAEINVAL);
3037 return SOCKET_ERROR;
3038 } /* end switch(level) */
3041 /***********************************************************************
3042 * htonl (WS2_32.8)
3044 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
3046 return htonl(hostlong);
3050 /***********************************************************************
3051 * htons (WS2_32.9)
3053 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
3055 return htons(hostshort);
3058 /***********************************************************************
3059 * WSAHtonl (WS2_32.46)
3060 * From MSDN description of error codes, this function should also
3061 * check if WinSock has been initialized and the socket is a valid
3062 * socket. But why? This function only translates a host byte order
3063 * u_long into a network byte order u_long...
3065 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
3067 if (lpnetlong)
3069 *lpnetlong = htonl(hostlong);
3070 return 0;
3072 WSASetLastError(WSAEFAULT);
3073 return SOCKET_ERROR;
3076 /***********************************************************************
3077 * WSAHtons (WS2_32.47)
3078 * From MSDN description of error codes, this function should also
3079 * check if WinSock has been initialized and the socket is a valid
3080 * socket. But why? This function only translates a host byte order
3081 * u_short into a network byte order u_short...
3083 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
3086 if (lpnetshort)
3088 *lpnetshort = htons(hostshort);
3089 return 0;
3091 WSASetLastError(WSAEFAULT);
3092 return SOCKET_ERROR;
3096 /***********************************************************************
3097 * inet_addr (WS2_32.11)
3099 WS_u_long WINAPI WS_inet_addr(const char *cp)
3101 if (!cp) return INADDR_NONE;
3102 return inet_addr(cp);
3106 /***********************************************************************
3107 * ntohl (WS2_32.14)
3109 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
3111 return ntohl(netlong);
3115 /***********************************************************************
3116 * ntohs (WS2_32.15)
3118 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
3120 return ntohs(netshort);
3124 /***********************************************************************
3125 * inet_ntoa (WS2_32.12)
3127 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
3129 /* use "buffer for dummies" here because some applications have a
3130 * propensity to decode addresses in ws_hostent structure without
3131 * saving them first...
3133 static char dbuffer[16]; /* Yes, 16: 4*3 digits + 3 '.' + 1 '\0' */
3135 char* s = inet_ntoa(*((struct in_addr*)&in));
3136 if( s )
3138 strcpy(dbuffer, s);
3139 return dbuffer;
3141 SetLastError(wsaErrno());
3142 return NULL;
3145 static const char *debugstr_wsaioctl(DWORD ioctl)
3147 const char *buf_type, *family;
3149 switch(ioctl & 0x18000000)
3151 case WS_IOC_WS2:
3152 family = "IOC_WS2";
3153 break;
3154 case WS_IOC_PROTOCOL:
3155 family = "IOC_PROTOCOL";
3156 break;
3157 case WS_IOC_VENDOR:
3158 family = "IOC_VENDOR";
3159 break;
3160 default: /* WS_IOC_UNIX */
3162 BYTE size = (ioctl >> 16) & WS_IOCPARM_MASK;
3163 char x = (ioctl & 0xff00) >> 8;
3164 BYTE y = ioctl & 0xff;
3165 char args[14];
3167 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3169 case WS_IOC_VOID:
3170 buf_type = "_IO";
3171 sprintf(args, "%d, %d", x, y);
3172 break;
3173 case WS_IOC_IN:
3174 buf_type = "_IOW";
3175 sprintf(args, "'%c', %d, %d", x, y, size);
3176 break;
3177 case WS_IOC_OUT:
3178 buf_type = "_IOR";
3179 sprintf(args, "'%c', %d, %d", x, y, size);
3180 break;
3181 default:
3182 buf_type = "?";
3183 sprintf(args, "'%c', %d, %d", x, y, size);
3184 break;
3186 return wine_dbg_sprintf("%s(%s)", buf_type, args);
3190 /* We are different from WS_IOC_UNIX. */
3191 switch (ioctl & (WS_IOC_VOID|WS_IOC_INOUT))
3193 case WS_IOC_VOID:
3194 buf_type = "_WSAIO";
3195 break;
3196 case WS_IOC_INOUT:
3197 buf_type = "_WSAIORW";
3198 break;
3199 case WS_IOC_IN:
3200 buf_type = "_WSAIOW";
3201 break;
3202 case WS_IOC_OUT:
3203 buf_type = "_WSAIOR";
3204 break;
3205 default:
3206 buf_type = "?";
3207 break;
3210 return wine_dbg_sprintf("%s(%s, %d)", buf_type, family,
3211 (USHORT)(ioctl & 0xffff));
3214 /**********************************************************************
3215 * WSAIoctl (WS2_32.50)
3218 INT WINAPI WSAIoctl(SOCKET s, DWORD code, LPVOID in_buff, DWORD in_size, LPVOID out_buff,
3219 DWORD out_size, LPDWORD ret_size, LPWSAOVERLAPPED overlapped,
3220 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
3222 int fd;
3223 DWORD status = 0, total = 0;
3225 TRACE("%ld, 0x%08x, %p, %d, %p, %d, %p, %p, %p\n",
3226 s, code, in_buff, in_size, out_buff, out_size, ret_size, overlapped, completion);
3228 switch (code)
3230 case WS_FIONBIO:
3231 if (in_size != sizeof(WS_u_long) || IS_INTRESOURCE(in_buff))
3233 WSASetLastError(WSAEFAULT);
3234 return SOCKET_ERROR;
3236 if (_get_sock_mask(s))
3238 /* AsyncSelect()'ed sockets are always nonblocking */
3239 if (!*(WS_u_long *)in_buff) status = WSAEINVAL;
3240 break;
3242 if (*(WS_u_long *)in_buff)
3243 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
3244 else
3245 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
3246 break;
3248 case WS_FIONREAD:
3250 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
3252 WSASetLastError(WSAEFAULT);
3253 return SOCKET_ERROR;
3255 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3256 if (ioctl(fd, FIONREAD, out_buff ) == -1)
3257 status = (errno == EBADF) ? WSAENOTSOCK : wsaErrno();
3258 release_sock_fd( s, fd );
3259 break;
3262 case WS_SIOCATMARK:
3264 unsigned int oob = 0, atmark = 0;
3265 socklen_t oobsize = sizeof(int);
3266 if (out_size != sizeof(WS_u_long) || IS_INTRESOURCE(out_buff))
3268 WSASetLastError(WSAEFAULT);
3269 return SOCKET_ERROR;
3271 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
3272 /* SO_OOBINLINE sockets must always return TRUE to SIOCATMARK */
3273 if ((getsockopt(fd, SOL_SOCKET, SO_OOBINLINE, &oob, &oobsize ) == -1)
3274 || (!oob && ioctl(fd, SIOCATMARK, &atmark ) == -1))
3275 status = (errno == EBADF) ? WSAENOTSOCK : wsaErrno();
3276 else
3278 /* The SIOCATMARK value read from ioctl() is reversed
3279 * because BSD returns TRUE if it's in the OOB mark
3280 * while Windows returns TRUE if there are NO OOB bytes.
3282 (*(WS_u_long *) out_buff) = oob | !atmark;
3285 release_sock_fd( s, fd );
3286 break;
3289 case WS_FIOASYNC:
3290 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
3291 SetLastError(WSAEINVAL);
3292 return SOCKET_ERROR;
3294 case WS_SIO_GET_INTERFACE_LIST:
3296 INTERFACE_INFO* intArray = out_buff;
3297 DWORD size, numInt = 0, apiReturn;
3299 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
3301 if (!out_buff || !ret_size)
3303 WSASetLastError(WSAEFAULT);
3304 return SOCKET_ERROR;
3307 fd = get_sock_fd( s, 0, NULL );
3308 if (fd == -1) return SOCKET_ERROR;
3310 apiReturn = GetAdaptersInfo(NULL, &size);
3311 if (apiReturn == ERROR_BUFFER_OVERFLOW)
3313 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
3315 if (table)
3317 if (GetAdaptersInfo(table, &size) == NO_ERROR)
3319 PIP_ADAPTER_INFO ptr;
3321 for (ptr = table, numInt = 0; ptr; ptr = ptr->Next)
3323 unsigned int addr, mask, bcast;
3324 struct ifreq ifInfo;
3326 /* Skip interfaces without an IPv4 address. */
3327 if (ptr->IpAddressList.IpAddress.String[0] == '\0')
3328 continue;
3330 if ((numInt + 1)*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > out_size)
3332 WARN("Buffer too small = %u, out_size = %u\n", numInt + 1, out_size);
3333 status = WSAEFAULT;
3334 break;
3337 /* Socket Status Flags */
3338 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
3339 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
3341 ERR("Error obtaining status flags for socket!\n");
3342 status = WSAEINVAL;
3343 break;
3345 else
3347 /* set flags; the values of IFF_* are not the same
3348 under Linux and Windows, therefore must generate
3349 new flags */
3350 intArray->iiFlags = 0;
3351 if (ifInfo.ifr_flags & IFF_BROADCAST)
3352 intArray->iiFlags |= WS_IFF_BROADCAST;
3353 #ifdef IFF_POINTOPOINT
3354 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
3355 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
3356 #endif
3357 if (ifInfo.ifr_flags & IFF_LOOPBACK)
3358 intArray->iiFlags |= WS_IFF_LOOPBACK;
3359 if (ifInfo.ifr_flags & IFF_UP)
3360 intArray->iiFlags |= WS_IFF_UP;
3361 if (ifInfo.ifr_flags & IFF_MULTICAST)
3362 intArray->iiFlags |= WS_IFF_MULTICAST;
3365 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
3366 mask = inet_addr(ptr->IpAddressList.IpMask.String);
3367 bcast = addr | ~mask;
3368 intArray->iiAddress.AddressIn.sin_family = AF_INET;
3369 intArray->iiAddress.AddressIn.sin_port = 0;
3370 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
3371 addr;
3372 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
3373 intArray->iiNetmask.AddressIn.sin_port = 0;
3374 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
3375 mask;
3376 intArray->iiBroadcastAddress.AddressIn.sin_family =
3377 AF_INET;
3378 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
3379 intArray->iiBroadcastAddress.AddressIn.sin_addr.
3380 WS_s_addr = bcast;
3381 intArray++;
3382 numInt++;
3385 else
3387 ERR("Unable to get interface table!\n");
3388 status = WSAEINVAL;
3390 HeapFree(GetProcessHeap(),0,table);
3392 else status = WSAEINVAL;
3394 else if (apiReturn != ERROR_NO_DATA)
3396 ERR("Unable to get interface table!\n");
3397 status = WSAEINVAL;
3399 /* Calculate the size of the array being returned */
3400 total = sizeof(INTERFACE_INFO) * numInt;
3401 release_sock_fd( s, fd );
3402 break;
3405 case WS_SIO_ADDRESS_LIST_CHANGE:
3406 FIXME("-> SIO_ADDRESS_LIST_CHANGE request: stub\n");
3407 /* FIXME: error and return code depend on whether socket was created
3408 * with WSA_FLAG_OVERLAPPED, but there is no easy way to get this */
3409 break;
3411 case WS_SIO_ADDRESS_LIST_QUERY:
3413 DWORD size;
3415 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
3417 if (!ret_size)
3419 WSASetLastError(WSAEFAULT);
3420 return SOCKET_ERROR;
3423 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
3425 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
3426 DWORD num;
3428 if (!table || GetAdaptersInfo(table, &size))
3430 HeapFree(GetProcessHeap(), 0, table);
3431 status = WSAEINVAL;
3432 break;
3435 for (p = table, num = 0; p; p = p->Next)
3436 if (p->IpAddressList.IpAddress.String[0]) num++;
3438 total = sizeof(SOCKET_ADDRESS_LIST) + sizeof(SOCKET_ADDRESS) * (num - 1);
3439 total += sizeof(SOCKADDR) * num;
3441 if (total > out_size)
3443 HeapFree(GetProcessHeap(), 0, table);
3444 status = WSAEFAULT;
3445 break;
3448 if (out_buff)
3450 unsigned int i;
3451 SOCKET_ADDRESS *sa;
3452 SOCKET_ADDRESS_LIST *sa_list = out_buff;
3453 SOCKADDR_IN *sockaddr;
3455 sa = sa_list->Address;
3456 sockaddr = (SOCKADDR_IN *)((char *)sa + num * sizeof(SOCKET_ADDRESS));
3457 sa_list->iAddressCount = num;
3459 for (p = table, i = 0; p; p = p->Next)
3461 if (!p->IpAddressList.IpAddress.String[0]) continue;
3463 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
3464 sa[i].iSockaddrLength = sizeof(SOCKADDR);
3466 sockaddr[i].sin_family = AF_INET;
3467 sockaddr[i].sin_port = 0;
3468 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
3469 i++;
3473 HeapFree(GetProcessHeap(), 0, table);
3475 else
3477 WARN("unable to get IP address list\n");
3478 status = WSAEINVAL;
3480 break;
3483 case WS_SIO_FLUSH:
3484 FIXME("SIO_FLUSH: stub.\n");
3485 break;
3487 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
3489 static const GUID connectex_guid = WSAID_CONNECTEX;
3490 static const GUID disconnectex_guid = WSAID_DISCONNECTEX;
3491 static const GUID acceptex_guid = WSAID_ACCEPTEX;
3492 static const GUID getaccepexsockaddrs_guid = WSAID_GETACCEPTEXSOCKADDRS;
3493 static const GUID transmitfile_guid = WSAID_TRANSMITFILE;
3494 static const GUID transmitpackets_guid = WSAID_TRANSMITPACKETS;
3495 static const GUID wsarecvmsg_guid = WSAID_WSARECVMSG;
3496 static const GUID wsasendmsg_guid = WSAID_WSASENDMSG;
3498 if ( IsEqualGUID(&connectex_guid, in_buff) )
3500 *(LPFN_CONNECTEX *)out_buff = WS2_ConnectEx;
3501 break;
3503 else if ( IsEqualGUID(&disconnectex_guid, in_buff) )
3505 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented DisconnectEx\n");
3507 else if ( IsEqualGUID(&acceptex_guid, in_buff) )
3509 *(LPFN_ACCEPTEX *)out_buff = WS2_AcceptEx;
3510 break;
3512 else if ( IsEqualGUID(&getaccepexsockaddrs_guid, in_buff) )
3514 *(LPFN_GETACCEPTEXSOCKADDRS *)out_buff = WS2_GetAcceptExSockaddrs;
3515 break;
3517 else if ( IsEqualGUID(&transmitfile_guid, in_buff) )
3519 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitFile\n");
3521 else if ( IsEqualGUID(&transmitpackets_guid, in_buff) )
3523 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented TransmitPackets\n");
3525 else if ( IsEqualGUID(&wsarecvmsg_guid, in_buff) )
3527 *(LPFN_WSARECVMSG *)out_buff = WS2_WSARecvMsg;
3528 break;
3530 else if ( IsEqualGUID(&wsasendmsg_guid, in_buff) )
3532 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER: unimplemented WSASendMsg\n");
3534 else
3535 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(in_buff));
3537 status = WSAEOPNOTSUPP;
3538 break;
3540 case WS_SIO_KEEPALIVE_VALS:
3542 struct tcp_keepalive *k;
3543 int keepalive, keepidle, keepintvl;
3545 if (!in_buff || in_size < sizeof(struct tcp_keepalive))
3547 WSASetLastError(WSAEFAULT);
3548 return SOCKET_ERROR;
3551 k = in_buff;
3552 keepalive = k->onoff ? 1 : 0;
3553 keepidle = max( 1, (k->keepalivetime + 500) / 1000 );
3554 keepintvl = max( 1, (k->keepaliveinterval + 500) / 1000 );
3556 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
3558 fd = get_sock_fd(s, 0, NULL);
3559 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
3560 status = WSAEINVAL;
3561 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
3562 /* these values need to be set only if SO_KEEPALIVE is enabled */
3563 else if(keepalive)
3565 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
3566 status = WSAEINVAL;
3567 else if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
3568 status = WSAEINVAL;
3570 #else
3571 else
3572 FIXME("ignoring keepalive interval and timeout\n");
3573 #endif
3574 release_sock_fd(s, fd);
3575 break;
3577 case WS_SIO_ROUTING_INTERFACE_QUERY:
3579 struct WS_sockaddr *daddr = (struct WS_sockaddr *)in_buff;
3580 struct WS_sockaddr_in *daddr_in = (struct WS_sockaddr_in *)daddr;
3581 struct WS_sockaddr_in *saddr_in = out_buff;
3582 MIB_IPFORWARDROW row;
3583 PMIB_IPADDRTABLE ipAddrTable = NULL;
3584 DWORD size, i, found_index;
3586 TRACE("-> WS_SIO_ROUTING_INTERFACE_QUERY request\n");
3588 if (!in_buff || in_size < sizeof(struct WS_sockaddr) ||
3589 !out_buff || out_size < sizeof(struct WS_sockaddr_in) || !ret_size)
3591 WSASetLastError(WSAEFAULT);
3592 return SOCKET_ERROR;
3594 if (daddr->sa_family != AF_INET)
3596 FIXME("unsupported address family %d\n", daddr->sa_family);
3597 status = WSAEAFNOSUPPORT;
3598 break;
3600 if (GetBestRoute(daddr_in->sin_addr.S_un.S_addr, 0, &row) != NOERROR ||
3601 GetIpAddrTable(NULL, &size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
3603 status = WSAEFAULT;
3604 break;
3606 ipAddrTable = HeapAlloc(GetProcessHeap(), 0, size);
3607 if (GetIpAddrTable(ipAddrTable, &size, FALSE))
3609 HeapFree(GetProcessHeap(), 0, ipAddrTable);
3610 status = WSAEFAULT;
3611 break;
3613 for (i = 0, found_index = ipAddrTable->dwNumEntries;
3614 i < ipAddrTable->dwNumEntries; i++)
3616 if (ipAddrTable->table[i].dwIndex == row.dwForwardIfIndex)
3617 found_index = i;
3619 if (found_index == ipAddrTable->dwNumEntries)
3621 ERR("no matching IP address for interface %d\n",
3622 row.dwForwardIfIndex);
3623 HeapFree(GetProcessHeap(), 0, ipAddrTable);
3624 status = WSAEFAULT;
3625 break;
3627 saddr_in->sin_family = AF_INET;
3628 saddr_in->sin_addr.S_un.S_addr = ipAddrTable->table[found_index].dwAddr;
3629 saddr_in->sin_port = 0;
3630 total = sizeof(struct WS_sockaddr_in);
3631 HeapFree(GetProcessHeap(), 0, ipAddrTable);
3632 break;
3634 case WS_SIO_SET_COMPATIBILITY_MODE:
3635 TRACE("WS_SIO_SET_COMPATIBILITY_MODE ignored\n");
3636 status = WSAEOPNOTSUPP;
3637 break;
3638 case WS_SIO_UDP_CONNRESET:
3639 FIXME("WS_SIO_UDP_CONNRESET stub\n");
3640 break;
3641 case 0x667e: /* Netscape tries hard to use bogus ioctl 0x667e */
3642 WSASetLastError(WSAEOPNOTSUPP);
3643 return SOCKET_ERROR;
3644 default:
3645 FIXME("unsupported WS_IOCTL cmd (%s)\n", debugstr_wsaioctl(code));
3646 status = WSAEOPNOTSUPP;
3647 break;
3650 if (completion)
3652 FIXME( "completion routine %p not supported\n", completion );
3654 else if (overlapped)
3656 ULONG_PTR cvalue = (overlapped && ((ULONG_PTR)overlapped->hEvent & 1) == 0) ? (ULONG_PTR)overlapped : 0;
3657 overlapped->Internal = status;
3658 overlapped->InternalHigh = total;
3659 if (overlapped->hEvent) NtSetEvent( overlapped->hEvent, NULL );
3660 if (cvalue) WS_AddCompletion( HANDLE2SOCKET(s), cvalue, status, total );
3663 if (!status)
3665 if (ret_size) *ret_size = total;
3666 return 0;
3668 SetLastError( status );
3669 return SOCKET_ERROR;
3673 /***********************************************************************
3674 * ioctlsocket (WS2_32.10)
3676 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
3678 DWORD ret_size;
3679 return WSAIoctl( s, cmd, argp, sizeof(WS_u_long), argp, sizeof(WS_u_long), &ret_size, NULL, NULL );
3682 /***********************************************************************
3683 * listen (WS2_32.13)
3685 int WINAPI WS_listen(SOCKET s, int backlog)
3687 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
3689 TRACE("socket %04lx, backlog %d\n", s, backlog);
3690 if (fd != -1)
3692 if (listen(fd, backlog) == 0)
3694 release_sock_fd( s, fd );
3695 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
3696 FD_WINE_LISTENING,
3697 FD_CONNECT|FD_WINE_CONNECTED);
3698 return 0;
3700 SetLastError(wsaErrno());
3701 release_sock_fd( s, fd );
3703 return SOCKET_ERROR;
3706 /***********************************************************************
3707 * recv (WS2_32.16)
3709 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
3711 DWORD n, dwFlags = flags;
3712 WSABUF wsabuf;
3714 wsabuf.len = len;
3715 wsabuf.buf = buf;
3717 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
3718 return SOCKET_ERROR;
3719 else
3720 return n;
3723 /***********************************************************************
3724 * recvfrom (WS2_32.17)
3726 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
3727 struct WS_sockaddr *from, int *fromlen)
3729 DWORD n, dwFlags = flags;
3730 WSABUF wsabuf;
3732 wsabuf.len = len;
3733 wsabuf.buf = buf;
3735 if ( WS2_recv_base(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL, NULL) == SOCKET_ERROR )
3736 return SOCKET_ERROR;
3737 else
3738 return n;
3741 /* allocate a poll array for the corresponding fd sets */
3742 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
3743 const WS_fd_set *exceptfds, int *count_ptr )
3745 unsigned int i, j = 0, count = 0;
3746 struct pollfd *fds;
3748 if (readfds) count += readfds->fd_count;
3749 if (writefds) count += writefds->fd_count;
3750 if (exceptfds) count += exceptfds->fd_count;
3751 *count_ptr = count;
3752 if (!count)
3754 SetLastError(WSAEINVAL);
3755 return NULL;
3757 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0]))))
3759 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
3760 return NULL;
3762 if (readfds)
3763 for (i = 0; i < readfds->fd_count; i++, j++)
3765 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
3766 if (fds[j].fd == -1) goto failed;
3767 fds[j].events = POLLIN;
3768 fds[j].revents = 0;
3770 if (writefds)
3771 for (i = 0; i < writefds->fd_count; i++, j++)
3773 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
3774 if (fds[j].fd == -1) goto failed;
3775 fds[j].events = POLLOUT;
3776 fds[j].revents = 0;
3778 if (exceptfds)
3779 for (i = 0; i < exceptfds->fd_count; i++, j++)
3781 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
3782 if (fds[j].fd == -1) goto failed;
3783 fds[j].events = POLLHUP;
3784 fds[j].revents = 0;
3786 return fds;
3788 failed:
3789 count = j;
3790 j = 0;
3791 if (readfds)
3792 for (i = 0; i < readfds->fd_count && j < count; i++, j++)
3793 release_sock_fd( readfds->fd_array[i], fds[j].fd );
3794 if (writefds)
3795 for (i = 0; i < writefds->fd_count && j < count; i++, j++)
3796 release_sock_fd( writefds->fd_array[i], fds[j].fd );
3797 if (exceptfds)
3798 for (i = 0; i < exceptfds->fd_count && j < count; i++, j++)
3799 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
3800 HeapFree( GetProcessHeap(), 0, fds );
3801 return NULL;
3804 /* release the file descriptor obtained in fd_sets_to_poll */
3805 /* must be called with the original fd_set arrays, before calling get_poll_results */
3806 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
3807 const WS_fd_set *exceptfds, struct pollfd *fds )
3809 unsigned int i, j = 0;
3811 if (readfds)
3813 for (i = 0; i < readfds->fd_count; i++, j++)
3814 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
3816 if (writefds)
3818 for (i = 0; i < writefds->fd_count; i++, j++)
3819 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
3821 if (exceptfds)
3823 for (i = 0; i < exceptfds->fd_count; i++, j++)
3824 if (fds[j].fd != -1)
3826 /* make sure we have a real error before releasing the fd */
3827 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
3828 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
3833 /* map the poll results back into the Windows fd sets */
3834 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
3835 const struct pollfd *fds )
3837 unsigned int i, j = 0, k, total = 0;
3839 if (readfds)
3841 for (i = k = 0; i < readfds->fd_count; i++, j++)
3842 if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
3843 readfds->fd_count = k;
3844 total += k;
3846 if (writefds)
3848 for (i = k = 0; i < writefds->fd_count; i++, j++)
3849 if ((fds[j].revents & POLLOUT) && !(fds[j].revents & POLLHUP))
3850 writefds->fd_array[k++] = writefds->fd_array[i];
3851 writefds->fd_count = k;
3852 total += k;
3854 if (exceptfds)
3856 for (i = k = 0; i < exceptfds->fd_count; i++, j++)
3857 if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
3858 exceptfds->fd_count = k;
3859 total += k;
3861 return total;
3865 /***********************************************************************
3866 * select (WS2_32.18)
3868 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
3869 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
3870 const struct WS_timeval* ws_timeout)
3872 struct pollfd *pollfds;
3873 struct timeval tv1, tv2;
3874 int torig = 0;
3875 int count, ret, timeout = -1;
3877 TRACE("read %p, write %p, excp %p timeout %p\n",
3878 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
3880 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )))
3881 return SOCKET_ERROR;
3883 if (ws_timeout)
3885 torig = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
3886 timeout = torig;
3887 gettimeofday( &tv1, 0 );
3890 while ((ret = poll( pollfds, count, timeout )) < 0)
3892 if (errno == EINTR)
3894 if (!ws_timeout) continue;
3895 gettimeofday( &tv2, 0 );
3897 tv2.tv_sec -= tv1.tv_sec;
3898 tv2.tv_usec -= tv1.tv_usec;
3899 if (tv2.tv_usec < 0)
3901 tv2.tv_usec += 1000000;
3902 tv2.tv_sec -= 1;
3905 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
3906 if (timeout <= 0) break;
3907 } else break;
3909 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
3911 if (ret == -1) SetLastError(wsaErrno());
3912 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
3913 HeapFree( GetProcessHeap(), 0, pollfds );
3914 return ret;
3917 /* helper to send completion messages for client-only i/o operation case */
3918 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
3919 ULONG Information )
3921 SERVER_START_REQ( add_fd_completion )
3923 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
3924 req->cvalue = CompletionValue;
3925 req->status = CompletionStatus;
3926 req->information = Information;
3927 wine_server_call( req );
3929 SERVER_END_REQ;
3933 /***********************************************************************
3934 * send (WS2_32.19)
3936 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
3938 DWORD n;
3939 WSABUF wsabuf;
3941 wsabuf.len = len;
3942 wsabuf.buf = (char*) buf;
3944 if ( WS2_sendto( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
3945 return SOCKET_ERROR;
3946 else
3947 return n;
3950 /***********************************************************************
3951 * WSASend (WS2_32.72)
3953 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3954 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
3955 LPWSAOVERLAPPED lpOverlapped,
3956 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3958 return WS2_sendto( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
3959 NULL, 0, lpOverlapped, lpCompletionRoutine );
3962 /***********************************************************************
3963 * WSASendDisconnect (WS2_32.73)
3965 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
3967 return WS_shutdown( s, SD_SEND );
3971 static int WS2_sendto( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3972 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
3973 const struct WS_sockaddr *to, int tolen,
3974 LPWSAOVERLAPPED lpOverlapped,
3975 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3977 unsigned int i, options;
3978 int n, fd, err;
3979 struct ws2_async *wsa = NULL;
3980 int totalLength = 0;
3981 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
3982 DWORD bytes_sent;
3983 BOOL is_blocking;
3985 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
3986 s, lpBuffers, dwBufferCount, dwFlags,
3987 to, tolen, lpOverlapped, lpCompletionRoutine);
3989 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
3990 TRACE( "fd=%d, options=%x\n", fd, options );
3992 if ( fd == -1 ) return SOCKET_ERROR;
3994 if (!lpOverlapped && !lpNumberOfBytesSent)
3996 err = WSAEFAULT;
3997 goto error;
3999 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
4001 err = WSAEFAULT;
4002 goto error;
4005 wsa->hSocket = SOCKET2HANDLE(s);
4006 wsa->addr = (struct WS_sockaddr *)to;
4007 wsa->addrlen.val = tolen;
4008 wsa->flags = dwFlags;
4009 wsa->lpFlags = &wsa->flags;
4010 wsa->control = NULL;
4011 wsa->n_iovecs = dwBufferCount;
4012 wsa->first_iovec = 0;
4013 for ( i = 0; i < dwBufferCount; i++ )
4015 wsa->iovec[i].iov_base = lpBuffers[i].buf;
4016 wsa->iovec[i].iov_len = lpBuffers[i].len;
4017 totalLength += lpBuffers[i].len;
4020 for (;;)
4022 n = WS2_send( fd, wsa );
4023 if (n != -1 || errno != EINTR) break;
4025 if (n == -1 && errno != EAGAIN)
4027 err = wsaErrno();
4028 goto error;
4031 if ((lpOverlapped || lpCompletionRoutine) &&
4032 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
4034 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
4036 wsa->user_overlapped = lpOverlapped;
4037 wsa->completion_func = lpCompletionRoutine;
4038 release_sock_fd( s, fd );
4040 if (n == -1 || n < totalLength)
4042 iosb->u.Status = STATUS_PENDING;
4043 iosb->Information = n == -1 ? 0 : n;
4045 SERVER_START_REQ( register_async )
4047 req->type = ASYNC_TYPE_WRITE;
4048 req->async.handle = wine_server_obj_handle( wsa->hSocket );
4049 req->async.callback = wine_server_client_ptr( WS2_async_send );
4050 req->async.iosb = wine_server_client_ptr( iosb );
4051 req->async.arg = wine_server_client_ptr( wsa );
4052 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
4053 req->async.cvalue = cvalue;
4054 err = wine_server_call( req );
4056 SERVER_END_REQ;
4058 /* Enable the event only after starting the async. The server will deliver it as soon as
4059 the async is done. */
4060 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
4062 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
4063 WSASetLastError( NtStatusToWSAError( err ));
4064 return SOCKET_ERROR;
4067 iosb->u.Status = STATUS_SUCCESS;
4068 iosb->Information = n;
4069 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = n;
4070 if (!wsa->completion_func)
4072 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
4073 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
4074 HeapFree( GetProcessHeap(), 0, wsa );
4076 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
4077 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
4078 WSASetLastError(0);
4079 return 0;
4082 if ((err = _is_blocking( s, &is_blocking )))
4084 err = NtStatusToWSAError( err );
4085 goto error;
4088 if ( is_blocking )
4090 /* On a blocking non-overlapped stream socket,
4091 * sending blocks until the entire buffer is sent. */
4092 DWORD timeout_start = GetTickCount();
4094 bytes_sent = n == -1 ? 0 : n;
4096 while (wsa->first_iovec < wsa->n_iovecs)
4098 struct pollfd pfd;
4099 int timeout = GET_SNDTIMEO(fd);
4101 if (timeout != -1)
4103 timeout -= GetTickCount() - timeout_start;
4104 if (timeout < 0) timeout = 0;
4107 pfd.fd = fd;
4108 pfd.events = POLLOUT;
4110 if (!timeout || !poll( &pfd, 1, timeout ))
4112 err = WSAETIMEDOUT;
4113 goto error; /* msdn says a timeout in send is fatal */
4116 n = WS2_send( fd, wsa );
4117 if (n == -1 && errno != EAGAIN && errno != EINTR)
4119 err = wsaErrno();
4120 goto error;
4123 if (n >= 0)
4124 bytes_sent += n;
4127 else /* non-blocking */
4129 if (n < totalLength)
4130 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
4131 if (n == -1)
4133 err = WSAEWOULDBLOCK;
4134 goto error;
4136 bytes_sent = n;
4139 TRACE(" -> %i bytes\n", bytes_sent);
4141 if (lpNumberOfBytesSent) *lpNumberOfBytesSent = bytes_sent;
4142 HeapFree( GetProcessHeap(), 0, wsa );
4143 release_sock_fd( s, fd );
4144 WSASetLastError(0);
4145 return 0;
4147 error:
4148 HeapFree( GetProcessHeap(), 0, wsa );
4149 release_sock_fd( s, fd );
4150 WARN(" -> ERROR %d\n", err);
4151 WSASetLastError(err);
4152 return SOCKET_ERROR;
4155 /***********************************************************************
4156 * WSASendTo (WS2_32.74)
4158 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4159 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
4160 const struct WS_sockaddr *to, int tolen,
4161 LPWSAOVERLAPPED lpOverlapped,
4162 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4164 return WS2_sendto( s, lpBuffers, dwBufferCount,
4165 lpNumberOfBytesSent, dwFlags,
4166 to, tolen,
4167 lpOverlapped, lpCompletionRoutine );
4170 /***********************************************************************
4171 * sendto (WS2_32.20)
4173 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
4174 const struct WS_sockaddr *to, int tolen)
4176 DWORD n;
4177 WSABUF wsabuf;
4179 wsabuf.len = len;
4180 wsabuf.buf = (char*) buf;
4182 if ( WS2_sendto(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
4183 return SOCKET_ERROR;
4184 else
4185 return n;
4188 /***********************************************************************
4189 * setsockopt (WS2_32.21)
4191 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
4192 const char *optval, int optlen)
4194 int fd;
4195 int woptval;
4196 struct linger linger;
4197 struct timeval tval;
4199 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
4200 s, level, optname, optval, optlen);
4202 /* some broken apps pass the value directly instead of a pointer to it */
4203 if(optlen && IS_INTRESOURCE(optval))
4205 SetLastError(WSAEFAULT);
4206 return SOCKET_ERROR;
4209 switch(level)
4211 case WS_SOL_SOCKET:
4212 switch(optname)
4214 /* Some options need some conversion before they can be sent to
4215 * setsockopt. The conversions are done here, then they will fall though
4216 * to the general case. Special options that are not passed to
4217 * setsockopt follow below that.*/
4219 case WS_SO_DONTLINGER:
4220 if (!optval)
4222 SetLastError(WSAEFAULT);
4223 return SOCKET_ERROR;
4225 linger.l_onoff = *(const int*)optval == 0;
4226 linger.l_linger = 0;
4227 level = SOL_SOCKET;
4228 optname = SO_LINGER;
4229 optval = (char*)&linger;
4230 optlen = sizeof(struct linger);
4231 break;
4233 case WS_SO_LINGER:
4234 if (!optval)
4236 SetLastError(WSAEFAULT);
4237 return SOCKET_ERROR;
4239 linger.l_onoff = ((LINGER*)optval)->l_onoff;
4240 linger.l_linger = ((LINGER*)optval)->l_linger;
4241 level = SOL_SOCKET;
4242 optname = SO_LINGER;
4243 optval = (char*)&linger;
4244 optlen = sizeof(struct linger);
4245 break;
4247 case WS_SO_RCVBUF:
4248 if (*(const int*)optval < 2048)
4250 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
4251 return 0;
4253 /* Fall through */
4255 /* The options listed here don't need any special handling. Thanks to
4256 * the conversion happening above, options from there will fall through
4257 * to this, too.*/
4258 case WS_SO_ACCEPTCONN:
4259 case WS_SO_BROADCAST:
4260 case WS_SO_ERROR:
4261 case WS_SO_KEEPALIVE:
4262 case WS_SO_OOBINLINE:
4263 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
4264 * however, using it the BSD way fixes bug 8513 and seems to be what
4265 * most programmers assume, anyway */
4266 case WS_SO_REUSEADDR:
4267 case WS_SO_SNDBUF:
4268 case WS_SO_TYPE:
4269 convert_sockopt(&level, &optname);
4270 break;
4272 /* SO_DEBUG is a privileged operation, ignore it. */
4273 case WS_SO_DEBUG:
4274 TRACE("Ignoring SO_DEBUG\n");
4275 return 0;
4277 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
4278 * socket. According to MSDN, this option is silently ignored.*/
4279 case WS_SO_DONTROUTE:
4280 TRACE("Ignoring SO_DONTROUTE\n");
4281 return 0;
4283 /* Stops two sockets from being bound to the same port. Always happens
4284 * on unix systems, so just drop it. */
4285 case WS_SO_EXCLUSIVEADDRUSE:
4286 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
4287 return 0;
4289 /* After a ConnectEx call succeeds, the socket can't be used with half of the
4290 * normal winsock functions on windows. We don't have that problem. */
4291 case WS_SO_UPDATE_CONNECT_CONTEXT:
4292 TRACE("Ignoring SO_UPDATE_CONNECT_CONTEXT, since our sockets are normal\n");
4293 return 0;
4295 /* After a AcceptEx call succeeds, the socket can't be used with half of the
4296 * normal winsock functions on windows. We don't have that problem. */
4297 case WS_SO_UPDATE_ACCEPT_CONTEXT:
4298 TRACE("Ignoring SO_UPDATE_ACCEPT_CONTEXT, since our sockets are normal\n");
4299 return 0;
4301 /* SO_OPENTYPE does not require a valid socket handle. */
4302 case WS_SO_OPENTYPE:
4303 if (!optlen || optlen < sizeof(int) || !optval)
4305 SetLastError(WSAEFAULT);
4306 return SOCKET_ERROR;
4308 get_per_thread_data()->opentype = *(const int *)optval;
4309 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
4310 return 0;
4312 #ifdef SO_RCVTIMEO
4313 case WS_SO_RCVTIMEO:
4314 #endif
4315 #ifdef SO_SNDTIMEO
4316 case WS_SO_SNDTIMEO:
4317 #endif
4318 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
4319 if (optval && optlen == sizeof(UINT32)) {
4320 /* WinSock passes milliseconds instead of struct timeval */
4321 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
4322 tval.tv_sec = *(const UINT32*)optval / 1000;
4323 /* min of 500 milliseconds */
4324 if (tval.tv_sec == 0 && tval.tv_usec && tval.tv_usec < 500000)
4325 tval.tv_usec = 500000;
4326 optlen = sizeof(struct timeval);
4327 optval = (char*)&tval;
4328 } else if (optlen == sizeof(struct timeval)) {
4329 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
4330 } else {
4331 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
4332 return 0;
4334 convert_sockopt(&level, &optname);
4335 break;
4336 #endif
4338 default:
4339 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
4340 SetLastError(WSAENOPROTOOPT);
4341 return SOCKET_ERROR;
4343 break; /* case WS_SOL_SOCKET */
4345 #ifdef HAVE_IPX
4346 case NSPROTO_IPX:
4347 switch(optname)
4349 case IPX_PTYPE:
4350 fd = get_sock_fd( s, 0, NULL );
4351 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", *(const int*)optval, fd);
4353 /* We try to set the ipx type on ipx socket level. */
4354 #ifdef SOL_IPX
4355 if(setsockopt(fd, SOL_IPX, IPX_TYPE, optval, optlen) == -1)
4357 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
4358 release_sock_fd( s, fd );
4359 return SOCKET_ERROR;
4361 #else
4363 struct ipx val;
4364 /* Should we retrieve val using a getsockopt call and then
4365 * set the modified one? */
4366 val.ipx_pt = *optval;
4367 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
4369 #endif
4370 release_sock_fd( s, fd );
4371 return 0;
4373 case IPX_FILTERPTYPE:
4374 /* Sets the receive filter packet type, at the moment we don't support it */
4375 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
4376 /* Returning 0 is better for now than returning a SOCKET_ERROR */
4377 return 0;
4379 default:
4380 FIXME("opt_name:%x\n", optname);
4381 return SOCKET_ERROR;
4383 break; /* case NSPROTO_IPX */
4384 #endif
4386 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
4387 case WS_IPPROTO_TCP:
4388 switch(optname)
4390 case WS_TCP_NODELAY:
4391 convert_sockopt(&level, &optname);
4392 break;
4393 default:
4394 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
4395 return SOCKET_ERROR;
4397 break;
4399 case WS_IPPROTO_IP:
4400 switch(optname)
4402 case WS_IP_ADD_MEMBERSHIP:
4403 case WS_IP_DROP_MEMBERSHIP:
4404 #ifdef IP_HDRINCL
4405 case WS_IP_HDRINCL:
4406 #endif
4407 case WS_IP_MULTICAST_IF:
4408 case WS_IP_MULTICAST_LOOP:
4409 case WS_IP_MULTICAST_TTL:
4410 case WS_IP_OPTIONS:
4411 #ifdef IP_PKTINFO
4412 case WS_IP_PKTINFO:
4413 #endif
4414 case WS_IP_TOS:
4415 case WS_IP_TTL:
4416 #ifdef IP_UNICAST_IF
4417 case WS_IP_UNICAST_IF:
4418 #endif
4419 convert_sockopt(&level, &optname);
4420 break;
4421 case WS_IP_DONTFRAGMENT:
4422 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
4423 return 0;
4424 default:
4425 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
4426 return SOCKET_ERROR;
4428 break;
4430 case WS_IPPROTO_IPV6:
4431 switch(optname)
4433 #ifdef IPV6_ADD_MEMBERSHIP
4434 case WS_IPV6_ADD_MEMBERSHIP:
4435 #endif
4436 #ifdef IPV6_DROP_MEMBERSHIP
4437 case WS_IPV6_DROP_MEMBERSHIP:
4438 #endif
4439 case WS_IPV6_MULTICAST_IF:
4440 case WS_IPV6_MULTICAST_HOPS:
4441 case WS_IPV6_MULTICAST_LOOP:
4442 case WS_IPV6_UNICAST_HOPS:
4443 case WS_IPV6_V6ONLY:
4444 #ifdef IPV6_UNICAST_IF
4445 case WS_IPV6_UNICAST_IF:
4446 #endif
4447 convert_sockopt(&level, &optname);
4448 break;
4449 case WS_IPV6_DONTFRAG:
4450 FIXME("IPV6_DONTFRAG is silently ignored!\n");
4451 return 0;
4452 case WS_IPV6_PROTECTION_LEVEL:
4453 FIXME("IPV6_PROTECTION_LEVEL is ignored!\n");
4454 return 0;
4455 default:
4456 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
4457 return SOCKET_ERROR;
4459 break;
4461 default:
4462 WARN("Unknown level: 0x%08x\n", level);
4463 SetLastError(WSAEINVAL);
4464 return SOCKET_ERROR;
4465 } /* end switch(level) */
4467 /* avoid endianness issues if argument is a 16-bit int */
4468 if (optval && optlen < sizeof(int))
4470 woptval= *((const INT16 *) optval);
4471 optval= (char*) &woptval;
4472 optlen=sizeof(int);
4474 fd = get_sock_fd( s, 0, NULL );
4475 if (fd == -1) return SOCKET_ERROR;
4477 if (setsockopt(fd, level, optname, optval, optlen) == 0)
4479 #ifdef __APPLE__
4480 if (level == SOL_SOCKET && optname == SO_REUSEADDR &&
4481 setsockopt(fd, level, SO_REUSEPORT, optval, optlen) != 0)
4483 SetLastError(wsaErrno());
4484 release_sock_fd( s, fd );
4485 return SOCKET_ERROR;
4487 #endif
4488 release_sock_fd( s, fd );
4489 return 0;
4491 TRACE("Setting socket error, %d\n", wsaErrno());
4492 SetLastError(wsaErrno());
4493 release_sock_fd( s, fd );
4495 return SOCKET_ERROR;
4498 /***********************************************************************
4499 * shutdown (WS2_32.22)
4501 int WINAPI WS_shutdown(SOCKET s, int how)
4503 int fd, err = WSAENOTSOCK;
4504 unsigned int options, clear_flags = 0;
4506 fd = get_sock_fd( s, 0, &options );
4507 TRACE("socket %04lx, how %i %x\n", s, how, options );
4509 if (fd == -1)
4510 return SOCKET_ERROR;
4512 switch( how )
4514 case 0: /* drop receives */
4515 clear_flags |= FD_READ;
4516 break;
4517 case 1: /* drop sends */
4518 clear_flags |= FD_WRITE;
4519 break;
4520 case 2: /* drop all */
4521 clear_flags |= FD_READ|FD_WRITE;
4522 /*fall through */
4523 default:
4524 clear_flags |= FD_WINE_LISTENING;
4527 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
4529 switch ( how )
4531 case SD_RECEIVE:
4532 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
4533 break;
4534 case SD_SEND:
4535 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
4536 break;
4537 case SD_BOTH:
4538 default:
4539 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
4540 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
4541 break;
4543 if (err) goto error;
4545 else /* non-overlapped mode */
4547 if ( shutdown( fd, how ) )
4549 err = wsaErrno();
4550 goto error;
4554 release_sock_fd( s, fd );
4555 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
4556 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
4557 return 0;
4559 error:
4560 release_sock_fd( s, fd );
4561 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
4562 WSASetLastError( err );
4563 return SOCKET_ERROR;
4566 /***********************************************************************
4567 * socket (WS2_32.23)
4569 SOCKET WINAPI WS_socket(int af, int type, int protocol)
4571 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
4573 return WSASocketA( af, type, protocol, NULL, 0,
4574 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
4578 /***********************************************************************
4579 * gethostbyaddr (WS2_32.51)
4581 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
4583 struct WS_hostent *retval = NULL;
4584 struct hostent* host;
4586 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4587 char *extrabuf;
4588 int ebufsize=1024;
4589 struct hostent hostentry;
4590 int locerr=ENOBUFS;
4591 host = NULL;
4592 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
4593 while(extrabuf) {
4594 int res = gethostbyaddr_r(addr, len, type,
4595 &hostentry, extrabuf, ebufsize, &host, &locerr);
4596 if( res != ERANGE) break;
4597 ebufsize *=2;
4598 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
4600 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
4601 #else
4602 EnterCriticalSection( &csWSgetXXXbyYYY );
4603 host = gethostbyaddr(addr, len, type);
4604 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
4605 #endif
4606 if( host != NULL ) retval = WS_dup_he(host);
4607 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4608 HeapFree(GetProcessHeap(),0,extrabuf);
4609 #else
4610 LeaveCriticalSection( &csWSgetXXXbyYYY );
4611 #endif
4612 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
4613 return retval;
4616 /***********************************************************************
4617 * WS_get_local_ips (INTERNAL)
4619 * Returns the list of local IP addresses by going through the network
4620 * adapters and using the local routing table to sort the addresses
4621 * from highest routing priority to lowest routing priority. This
4622 * functionality is inferred from the description for obtaining local
4623 * IP addresses given in the Knowledge Base Article Q160215.
4625 * Please note that the returned hostent is only freed when the thread
4626 * closes and is replaced if another hostent is requested.
4628 static struct WS_hostent* WS_get_local_ips( char *hostname )
4630 int last_metric, numroutes = 0, i, j;
4631 DWORD n;
4632 PIP_ADAPTER_INFO adapters = NULL, k;
4633 struct WS_hostent *hostlist = NULL;
4634 PMIB_IPFORWARDTABLE routes = NULL;
4635 struct route *route_addrs = NULL;
4636 DWORD adap_size, route_size;
4638 /* Obtain the size of the adapter list and routing table, also allocate memory */
4639 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
4640 return NULL;
4641 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
4642 return NULL;
4643 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
4644 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
4645 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
4646 if (adapters == NULL || routes == NULL || route_addrs == NULL)
4647 goto cleanup;
4648 /* Obtain the adapter list and the full routing table */
4649 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
4650 goto cleanup;
4651 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
4652 goto cleanup;
4653 /* Store the interface associated with each route */
4654 for (n = 0; n < routes->dwNumEntries; n++)
4656 IF_INDEX ifindex;
4657 DWORD ifmetric, exists = FALSE;
4659 if (routes->table[n].u1.ForwardType != MIB_IPROUTE_TYPE_DIRECT)
4660 continue;
4661 ifindex = routes->table[n].dwForwardIfIndex;
4662 ifmetric = routes->table[n].dwForwardMetric1;
4663 /* Only store the lowest valued metric for an interface */
4664 for (j = 0; j < numroutes; j++)
4666 if (route_addrs[j].interface == ifindex)
4668 if (route_addrs[j].metric > ifmetric)
4669 route_addrs[j].metric = ifmetric;
4670 exists = TRUE;
4673 if (exists)
4674 continue;
4675 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
4676 if (route_addrs == NULL)
4677 goto cleanup; /* Memory allocation error, fail gracefully */
4678 route_addrs[numroutes].interface = ifindex;
4679 route_addrs[numroutes].metric = ifmetric;
4680 /* If no IP is found in the next step (for whatever reason)
4681 * then fall back to the magic loopback address.
4683 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
4684 numroutes++;
4686 if (numroutes == 0)
4687 goto cleanup; /* No routes, fall back to the Magic IP */
4688 /* Find the IP address associated with each found interface */
4689 for (i = 0; i < numroutes; i++)
4691 for (k = adapters; k != NULL; k = k->Next)
4693 char *ip = k->IpAddressList.IpAddress.String;
4695 if (route_addrs[i].interface == k->Index)
4696 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
4699 /* Allocate a hostent and enough memory for all the IPs,
4700 * including the NULL at the end of the list.
4702 hostlist = WS_create_he(hostname, 1, 0, numroutes+1, sizeof(struct in_addr));
4703 if (hostlist == NULL)
4704 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
4705 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
4706 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
4707 hostlist->h_addrtype = AF_INET;
4708 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
4709 /* Reorder the entries when placing them in the host list, Windows expects
4710 * the IP list in order from highest priority to lowest (the critical thing
4711 * is that most applications expect the first IP to be the default route).
4713 last_metric = -1;
4714 for (i = 0; i < numroutes; i++)
4716 struct in_addr addr;
4717 int metric = 0xFFFF;
4719 memcpy(&addr, magic_loopback_addr, 4);
4720 for (j = 0; j < numroutes; j++)
4722 int this_metric = route_addrs[j].metric;
4724 if (this_metric > last_metric && this_metric < metric)
4726 addr = route_addrs[j].addr;
4727 metric = this_metric;
4730 last_metric = metric;
4731 (*(struct in_addr *) hostlist->h_addr_list[i]) = addr;
4734 /* Cleanup all allocated memory except the address list,
4735 * the address list is used by the calling app.
4737 cleanup:
4738 HeapFree(GetProcessHeap(), 0, route_addrs);
4739 HeapFree(GetProcessHeap(), 0, adapters);
4740 HeapFree(GetProcessHeap(), 0, routes);
4741 return hostlist;
4744 /***********************************************************************
4745 * gethostbyname (WS2_32.52)
4747 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
4749 struct WS_hostent *retval = NULL;
4750 struct hostent* host;
4751 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4752 char *extrabuf;
4753 int ebufsize=1024;
4754 struct hostent hostentry;
4755 int locerr = ENOBUFS;
4756 #endif
4757 char hostname[100];
4758 if(!num_startup) {
4759 SetLastError(WSANOTINITIALISED);
4760 return NULL;
4762 if( gethostname( hostname, 100) == -1) {
4763 SetLastError( WSAENOBUFS); /* appropriate ? */
4764 return retval;
4766 if( !name || !name[0]) {
4767 name = hostname;
4769 /* If the hostname of the local machine is requested then return the
4770 * complete list of local IP addresses */
4771 if(strcmp(name, hostname) == 0)
4772 retval = WS_get_local_ips(hostname);
4773 /* If any other hostname was requested (or the routing table lookup failed)
4774 * then return the IP found by the host OS */
4775 if(retval == NULL)
4777 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4778 host = NULL;
4779 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
4780 while(extrabuf) {
4781 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
4782 if( res != ERANGE) break;
4783 ebufsize *=2;
4784 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
4786 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
4787 #else
4788 EnterCriticalSection( &csWSgetXXXbyYYY );
4789 host = gethostbyname(name);
4790 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
4791 #endif
4792 if (host) retval = WS_dup_he(host);
4793 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
4794 HeapFree(GetProcessHeap(),0,extrabuf);
4795 #else
4796 LeaveCriticalSection( &csWSgetXXXbyYYY );
4797 #endif
4799 if (retval && retval->h_addr_list[0][0] == 127 &&
4800 strcmp(name, "localhost") != 0)
4802 /* hostname != "localhost" but has loopback address. replace by our
4803 * special address.*/
4804 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
4806 TRACE( "%s ret %p\n", debugstr_a(name), retval );
4807 return retval;
4811 /***********************************************************************
4812 * getprotobyname (WS2_32.53)
4814 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
4816 struct WS_protoent* retval = NULL;
4817 #ifdef HAVE_GETPROTOBYNAME
4818 struct protoent* proto;
4819 EnterCriticalSection( &csWSgetXXXbyYYY );
4820 if( (proto = getprotobyname(name)) != NULL )
4822 retval = WS_dup_pe(proto);
4824 else {
4825 MESSAGE("protocol %s not found; You might want to add "
4826 "this to /etc/protocols\n", debugstr_a(name) );
4827 SetLastError(WSANO_DATA);
4829 LeaveCriticalSection( &csWSgetXXXbyYYY );
4830 #endif
4831 TRACE( "%s ret %p\n", debugstr_a(name), retval );
4832 return retval;
4836 /***********************************************************************
4837 * getprotobynumber (WS2_32.54)
4839 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
4841 struct WS_protoent* retval = NULL;
4842 #ifdef HAVE_GETPROTOBYNUMBER
4843 struct protoent* proto;
4844 EnterCriticalSection( &csWSgetXXXbyYYY );
4845 if( (proto = getprotobynumber(number)) != NULL )
4847 retval = WS_dup_pe(proto);
4849 else {
4850 MESSAGE("protocol number %d not found; You might want to add "
4851 "this to /etc/protocols\n", number );
4852 SetLastError(WSANO_DATA);
4854 LeaveCriticalSection( &csWSgetXXXbyYYY );
4855 #endif
4856 TRACE("%i ret %p\n", number, retval);
4857 return retval;
4861 /***********************************************************************
4862 * getservbyname (WS2_32.55)
4864 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
4866 struct WS_servent* retval = NULL;
4867 struct servent* serv;
4868 char *name_str;
4869 char *proto_str = NULL;
4871 if (!(name_str = strdup_lower(name))) return NULL;
4873 if (proto && *proto)
4875 if (!(proto_str = strdup_lower(proto)))
4877 HeapFree( GetProcessHeap(), 0, name_str );
4878 return NULL;
4882 EnterCriticalSection( &csWSgetXXXbyYYY );
4883 serv = getservbyname(name_str, proto_str);
4884 if( serv != NULL )
4886 retval = WS_dup_se(serv);
4888 else SetLastError(WSANO_DATA);
4889 LeaveCriticalSection( &csWSgetXXXbyYYY );
4890 HeapFree( GetProcessHeap(), 0, proto_str );
4891 HeapFree( GetProcessHeap(), 0, name_str );
4892 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
4893 return retval;
4896 /***********************************************************************
4897 * freeaddrinfo (WS2_32.@)
4899 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
4901 while (res) {
4902 struct WS_addrinfo *next;
4904 HeapFree(GetProcessHeap(),0,res->ai_canonname);
4905 HeapFree(GetProcessHeap(),0,res->ai_addr);
4906 next = res->ai_next;
4907 HeapFree(GetProcessHeap(),0,res);
4908 res = next;
4912 /* helper functions for getaddrinfo()/getnameinfo() */
4913 static int convert_aiflag_w2u(int winflags) {
4914 unsigned int i;
4915 int unixflags = 0;
4917 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
4918 if (ws_aiflag_map[i][0] & winflags) {
4919 unixflags |= ws_aiflag_map[i][1];
4920 winflags &= ~ws_aiflag_map[i][0];
4922 if (winflags)
4923 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
4924 return unixflags;
4927 static int convert_niflag_w2u(int winflags) {
4928 unsigned int i;
4929 int unixflags = 0;
4931 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
4932 if (ws_niflag_map[i][0] & winflags) {
4933 unixflags |= ws_niflag_map[i][1];
4934 winflags &= ~ws_niflag_map[i][0];
4936 if (winflags)
4937 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
4938 return unixflags;
4941 static int convert_aiflag_u2w(int unixflags) {
4942 unsigned int i;
4943 int winflags = 0;
4945 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
4946 if (ws_aiflag_map[i][1] & unixflags) {
4947 winflags |= ws_aiflag_map[i][0];
4948 unixflags &= ~ws_aiflag_map[i][1];
4950 if (unixflags) /* will warn usually */
4951 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
4952 return winflags;
4955 static int convert_eai_u2w(int unixret) {
4956 int i;
4958 for (i=0;ws_eai_map[i][0];i++)
4959 if (ws_eai_map[i][1] == unixret)
4960 return ws_eai_map[i][0];
4961 return unixret;
4964 static char *get_hostname(void)
4966 char *ret;
4967 DWORD size = 0;
4969 GetComputerNameExA( ComputerNamePhysicalDnsHostname, NULL, &size );
4970 if (GetLastError() != ERROR_MORE_DATA) return NULL;
4971 if (!(ret = HeapAlloc( GetProcessHeap(), 0, size ))) return NULL;
4972 if (!GetComputerNameExA( ComputerNamePhysicalDnsHostname, ret, &size ))
4974 HeapFree( GetProcessHeap(), 0, ret );
4975 return NULL;
4977 return ret;
4980 /***********************************************************************
4981 * getaddrinfo (WS2_32.@)
4983 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
4985 #ifdef HAVE_GETADDRINFO
4986 struct addrinfo *unixaires = NULL;
4987 int result;
4988 struct addrinfo unixhints, *punixhints = NULL;
4989 char *hostname = NULL;
4990 const char *node;
4992 if (!nodename && !servname) return WSAHOST_NOT_FOUND;
4994 if (!nodename)
4995 node = NULL;
4996 else if (!nodename[0])
4998 node = hostname = get_hostname();
4999 if (!node) return WSA_NOT_ENOUGH_MEMORY;
5001 else
5002 node = nodename;
5004 if (hints) {
5005 punixhints = &unixhints;
5007 memset(&unixhints, 0, sizeof(unixhints));
5008 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
5009 if (hints->ai_family == 0) /* wildcard, specific to getaddrinfo() */
5010 punixhints->ai_family = 0;
5011 else
5012 punixhints->ai_family = convert_af_w2u(hints->ai_family);
5013 if (hints->ai_socktype == 0) /* wildcard, specific to getaddrinfo() */
5014 punixhints->ai_socktype = 0;
5015 else
5016 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
5017 if (hints->ai_protocol == 0) /* wildcard, specific to getaddrinfo() */
5018 punixhints->ai_protocol = 0;
5019 else
5020 punixhints->ai_protocol = convert_proto_w2u(hints->ai_protocol);
5023 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
5024 result = getaddrinfo(node, servname, punixhints, &unixaires);
5026 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
5027 HeapFree(GetProcessHeap(), 0, hostname);
5029 if (!result) {
5030 struct addrinfo *xuai = unixaires;
5031 struct WS_addrinfo **xai = res;
5033 *xai = NULL;
5034 while (xuai) {
5035 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
5036 int len;
5038 if (!ai)
5039 goto outofmem;
5041 *xai = ai;xai = &ai->ai_next;
5042 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
5043 ai->ai_family = convert_af_u2w(xuai->ai_family);
5044 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
5045 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
5046 if (xuai->ai_canonname) {
5047 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
5048 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
5049 if (!ai->ai_canonname)
5050 goto outofmem;
5051 strcpy(ai->ai_canonname,xuai->ai_canonname);
5053 len = xuai->ai_addrlen;
5054 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
5055 if (!ai->ai_addr)
5056 goto outofmem;
5057 ai->ai_addrlen = len;
5058 do {
5059 int winlen = ai->ai_addrlen;
5061 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
5062 ai->ai_addrlen = winlen;
5063 break;
5065 len = 2*len;
5066 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
5067 if (!ai->ai_addr)
5068 goto outofmem;
5069 ai->ai_addrlen = len;
5070 } while (1);
5071 xuai = xuai->ai_next;
5073 freeaddrinfo(unixaires);
5074 } else {
5075 result = convert_eai_u2w(result);
5076 *res = NULL;
5078 return result;
5080 outofmem:
5081 if (*res) WS_freeaddrinfo(*res);
5082 if (unixaires) freeaddrinfo(unixaires);
5083 *res = NULL;
5084 return WSA_NOT_ENOUGH_MEMORY;
5085 #else
5086 FIXME("getaddrinfo() failed, not found during buildtime.\n");
5087 return EAI_FAIL;
5088 #endif
5091 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
5093 struct WS_addrinfoW *ret;
5095 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
5096 ret->ai_flags = ai->ai_flags;
5097 ret->ai_family = ai->ai_family;
5098 ret->ai_socktype = ai->ai_socktype;
5099 ret->ai_protocol = ai->ai_protocol;
5100 ret->ai_addrlen = ai->ai_addrlen;
5101 ret->ai_canonname = NULL;
5102 ret->ai_addr = NULL;
5103 ret->ai_next = NULL;
5104 if (ai->ai_canonname)
5106 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
5107 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
5109 HeapFree(GetProcessHeap(), 0, ret);
5110 return NULL;
5112 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
5114 if (ai->ai_addr)
5116 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
5118 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
5119 HeapFree(GetProcessHeap(), 0, ret);
5120 return NULL;
5122 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
5124 return ret;
5127 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
5129 struct WS_addrinfoW *ret, *infoW;
5131 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
5132 while (info->ai_next)
5134 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
5136 FreeAddrInfoW(ret);
5137 return NULL;
5139 infoW = infoW->ai_next;
5140 info = info->ai_next;
5142 return ret;
5145 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
5147 struct WS_addrinfo *ret;
5149 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
5150 ret->ai_flags = ai->ai_flags;
5151 ret->ai_family = ai->ai_family;
5152 ret->ai_socktype = ai->ai_socktype;
5153 ret->ai_protocol = ai->ai_protocol;
5154 ret->ai_addrlen = ai->ai_addrlen;
5155 ret->ai_canonname = NULL;
5156 ret->ai_addr = NULL;
5157 ret->ai_next = NULL;
5158 if (ai->ai_canonname)
5160 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
5161 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
5163 HeapFree(GetProcessHeap(), 0, ret);
5164 return NULL;
5166 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
5168 if (ai->ai_addr)
5170 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
5172 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
5173 HeapFree(GetProcessHeap(), 0, ret);
5174 return NULL;
5176 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
5178 return ret;
5181 /***********************************************************************
5182 * GetAddrInfoW (WS2_32.@)
5184 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
5186 int ret, len;
5187 char *nodenameA = NULL, *servnameA = NULL;
5188 struct WS_addrinfo *resA, *hintsA = NULL;
5190 if (nodename)
5192 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
5193 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
5194 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
5196 if (servname)
5198 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
5199 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
5201 HeapFree(GetProcessHeap(), 0, nodenameA);
5202 return EAI_MEMORY;
5204 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
5207 if (hints) hintsA = addrinfo_WtoA(hints);
5208 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
5209 WS_freeaddrinfo(hintsA);
5211 if (!ret)
5213 *res = addrinfo_list_AtoW(resA);
5214 WS_freeaddrinfo(resA);
5217 HeapFree(GetProcessHeap(), 0, nodenameA);
5218 HeapFree(GetProcessHeap(), 0, servnameA);
5219 return ret;
5222 /***********************************************************************
5223 * FreeAddrInfoW (WS2_32.@)
5225 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
5227 while (ai)
5229 ADDRINFOW *next;
5230 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
5231 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
5232 next = ai->ai_next;
5233 HeapFree(GetProcessHeap(), 0, ai);
5234 ai = next;
5238 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
5239 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
5241 #ifdef HAVE_GETNAMEINFO
5242 int ret;
5243 union generic_unix_sockaddr sa_u;
5244 unsigned int size;
5246 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
5247 serv, servlen, flags);
5249 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
5250 if (!size)
5252 WSASetLastError(WSAEFAULT);
5253 return WSA_NOT_ENOUGH_MEMORY;
5255 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
5256 return convert_eai_u2w(ret);
5257 #else
5258 FIXME("getnameinfo() failed, not found during buildtime.\n");
5259 return EAI_FAIL;
5260 #endif
5263 int WINAPI GetNameInfoW(const SOCKADDR *sa, WS_socklen_t salen, PWCHAR host,
5264 DWORD hostlen, PWCHAR serv, DWORD servlen, INT flags)
5266 int ret;
5267 char *hostA = NULL, *servA = NULL;
5269 if (host && (!(hostA = HeapAlloc(GetProcessHeap(), 0, hostlen)))) return EAI_MEMORY;
5270 if (serv && (!(servA = HeapAlloc(GetProcessHeap(), 0, servlen))))
5272 HeapFree(GetProcessHeap(), 0, hostA);
5273 return EAI_MEMORY;
5276 ret = WS_getnameinfo(sa, salen, hostA, hostlen, servA, servlen, flags);
5277 if (!ret)
5279 if (host) MultiByteToWideChar(CP_ACP, 0, hostA, -1, host, hostlen);
5280 if (serv) MultiByteToWideChar(CP_ACP, 0, servA, -1, serv, servlen);
5283 HeapFree(GetProcessHeap(), 0, hostA);
5284 HeapFree(GetProcessHeap(), 0, servA);
5285 return ret;
5288 /***********************************************************************
5289 * getservbyport (WS2_32.56)
5291 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
5293 struct WS_servent* retval = NULL;
5294 #ifdef HAVE_GETSERVBYPORT
5295 struct servent* serv;
5296 char *proto_str = NULL;
5298 if (proto && *proto)
5300 if (!(proto_str = strdup_lower(proto))) return NULL;
5302 EnterCriticalSection( &csWSgetXXXbyYYY );
5303 if( (serv = getservbyport(port, proto_str)) != NULL ) {
5304 retval = WS_dup_se(serv);
5306 else SetLastError(WSANO_DATA);
5307 LeaveCriticalSection( &csWSgetXXXbyYYY );
5308 HeapFree( GetProcessHeap(), 0, proto_str );
5309 #endif
5310 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
5311 return retval;
5315 /***********************************************************************
5316 * gethostname (WS2_32.57)
5318 int WINAPI WS_gethostname(char *name, int namelen)
5320 TRACE("name %p, len %d\n", name, namelen);
5322 if (gethostname(name, namelen) == 0)
5324 TRACE("<- '%s'\n", name);
5325 return 0;
5327 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
5328 TRACE("<- ERROR !\n");
5329 return SOCKET_ERROR;
5333 /* ------------------------------------- Windows sockets extensions -- *
5335 * ------------------------------------------------------------------- */
5337 /***********************************************************************
5338 * WSAEnumNetworkEvents (WS2_32.36)
5340 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
5342 int ret;
5343 int i;
5344 int errors[FD_MAX_EVENTS];
5346 TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
5348 SERVER_START_REQ( get_socket_event )
5350 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5351 req->service = TRUE;
5352 req->c_event = wine_server_obj_handle( hEvent );
5353 wine_server_set_reply( req, errors, sizeof(errors) );
5354 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
5356 SERVER_END_REQ;
5357 if (!ret)
5359 for (i = 0; i < FD_MAX_EVENTS; i++)
5360 lpEvent->iErrorCode[i] = NtStatusToWSAError(errors[i]);
5361 return 0;
5363 SetLastError(WSAEINVAL);
5364 return SOCKET_ERROR;
5367 /***********************************************************************
5368 * WSAEventSelect (WS2_32.39)
5370 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
5372 int ret;
5374 TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
5376 SERVER_START_REQ( set_socket_event )
5378 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5379 req->mask = lEvent;
5380 req->event = wine_server_obj_handle( hEvent );
5381 req->window = 0;
5382 req->msg = 0;
5383 ret = wine_server_call( req );
5385 SERVER_END_REQ;
5386 if (!ret) return 0;
5387 SetLastError(WSAEINVAL);
5388 return SOCKET_ERROR;
5391 /**********************************************************************
5392 * WSAGetOverlappedResult (WS2_32.40)
5394 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
5395 LPDWORD lpcbTransfer, BOOL fWait,
5396 LPDWORD lpdwFlags )
5398 NTSTATUS status;
5400 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
5401 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
5403 if ( lpOverlapped == NULL )
5405 ERR( "Invalid pointer\n" );
5406 WSASetLastError(WSA_INVALID_PARAMETER);
5407 return FALSE;
5410 status = lpOverlapped->Internal;
5411 if (status == STATUS_PENDING)
5413 if (!fWait)
5415 SetLastError( WSA_IO_INCOMPLETE );
5416 return FALSE;
5419 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
5420 INFINITE ) == WAIT_FAILED)
5421 return FALSE;
5422 status = lpOverlapped->Internal;
5425 if ( lpcbTransfer )
5426 *lpcbTransfer = lpOverlapped->InternalHigh;
5428 if ( lpdwFlags )
5429 *lpdwFlags = lpOverlapped->u.s.Offset;
5431 if (status) SetLastError( RtlNtStatusToDosError(status) );
5432 return !status;
5436 /***********************************************************************
5437 * WSAAsyncSelect (WS2_32.101)
5439 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
5441 int ret;
5443 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
5445 SERVER_START_REQ( set_socket_event )
5447 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5448 req->mask = lEvent;
5449 req->event = 0;
5450 req->window = wine_server_user_handle( hWnd );
5451 req->msg = uMsg;
5452 ret = wine_server_call( req );
5454 SERVER_END_REQ;
5455 if (!ret) return 0;
5456 SetLastError(WSAEINVAL);
5457 return SOCKET_ERROR;
5460 /***********************************************************************
5461 * WSACreateEvent (WS2_32.31)
5464 WSAEVENT WINAPI WSACreateEvent(void)
5466 /* Create a manual-reset event, with initial state: unsignaled */
5467 TRACE("\n");
5469 return CreateEventW(NULL, TRUE, FALSE, NULL);
5472 /***********************************************************************
5473 * WSACloseEvent (WS2_32.29)
5476 BOOL WINAPI WSACloseEvent(WSAEVENT event)
5478 TRACE ("event=%p\n", event);
5480 return CloseHandle(event);
5483 /***********************************************************************
5484 * WSASocketA (WS2_32.78)
5487 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
5488 LPWSAPROTOCOL_INFOA lpProtocolInfo,
5489 GROUP g, DWORD dwFlags)
5491 INT len;
5492 WSAPROTOCOL_INFOW info;
5494 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
5495 af, type, protocol, lpProtocolInfo, g, dwFlags);
5497 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
5499 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
5500 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
5501 info.szProtocol, WSAPROTOCOL_LEN + 1);
5503 if (!len)
5505 WSASetLastError( WSAEINVAL);
5506 return SOCKET_ERROR;
5509 return WSASocketW(af, type, protocol, &info, g, dwFlags);
5512 /***********************************************************************
5513 * WSASocketW (WS2_32.79)
5516 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
5517 LPWSAPROTOCOL_INFOW lpProtocolInfo,
5518 GROUP g, DWORD dwFlags)
5520 SOCKET ret;
5523 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
5524 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
5527 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
5528 af, type, protocol, lpProtocolInfo, g, dwFlags );
5530 /* hack for WSADuplicateSocket */
5531 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
5532 ret = lpProtocolInfo->dwCatalogEntryId;
5533 TRACE("\tgot duplicate %04lx\n", ret);
5534 return ret;
5537 /* convert the socket family and type */
5538 af = convert_af_w2u(af);
5539 type = convert_socktype_w2u(type);
5541 if (lpProtocolInfo)
5543 if (af == FROM_PROTOCOL_INFO)
5544 af = lpProtocolInfo->iAddressFamily;
5545 if (type == FROM_PROTOCOL_INFO)
5546 type = lpProtocolInfo->iSocketType;
5547 if (protocol == FROM_PROTOCOL_INFO)
5548 protocol = lpProtocolInfo->iProtocol;
5551 if ( af == AF_UNSPEC) /* did they not specify the address family? */
5553 if ((protocol == IPPROTO_TCP && type == SOCK_STREAM) ||
5554 (protocol == IPPROTO_UDP && type == SOCK_DGRAM))
5556 af = AF_INET;
5558 else
5560 SetLastError(WSAEPROTOTYPE);
5561 return INVALID_SOCKET;
5565 SERVER_START_REQ( create_socket )
5567 req->family = af;
5568 req->type = type;
5569 req->protocol = protocol;
5570 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
5571 req->attributes = OBJ_INHERIT;
5572 req->flags = dwFlags;
5573 set_error( wine_server_call( req ) );
5574 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
5576 SERVER_END_REQ;
5577 if (ret)
5579 TRACE("\tcreated %04lx\n", ret );
5580 return ret;
5583 if (GetLastError() == WSAEACCES) /* raw socket denied */
5585 if (type == SOCK_RAW)
5586 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
5587 else
5588 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
5589 SetLastError(WSAESOCKTNOSUPPORT);
5592 WARN("\t\tfailed!\n");
5593 return INVALID_SOCKET;
5596 /***********************************************************************
5597 * WSAJoinLeaf (WS2_32.58)
5600 SOCKET WINAPI WSAJoinLeaf(
5601 SOCKET s,
5602 const struct WS_sockaddr *addr,
5603 int addrlen,
5604 LPWSABUF lpCallerData,
5605 LPWSABUF lpCalleeData,
5606 LPQOS lpSQOS,
5607 LPQOS lpGQOS,
5608 DWORD dwFlags)
5610 FIXME("stub.\n");
5611 return INVALID_SOCKET;
5614 /***********************************************************************
5615 * __WSAFDIsSet (WS2_32.151)
5617 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
5619 int i = set->fd_count;
5621 TRACE("(%ld,%p(%i))\n", s, set, i);
5623 while (i--)
5624 if (set->fd_array[i] == s) return 1;
5625 return 0;
5628 /***********************************************************************
5629 * WSAIsBlocking (WS2_32.114)
5631 BOOL WINAPI WSAIsBlocking(void)
5633 /* By default WinSock should set all its sockets to non-blocking mode
5634 * and poll in PeekMessage loop when processing "blocking" ones. This
5635 * function is supposed to tell if the program is in this loop. Our
5636 * blocking calls are truly blocking so we always return FALSE.
5638 * Note: It is allowed to call this function without prior WSAStartup().
5641 TRACE("\n");
5642 return FALSE;
5645 /***********************************************************************
5646 * WSACancelBlockingCall (WS2_32.113)
5648 INT WINAPI WSACancelBlockingCall(void)
5650 TRACE("\n");
5651 return 0;
5654 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
5656 FIXME("How was this called?\n");
5657 return x();
5661 /***********************************************************************
5662 * WSASetBlockingHook (WS2_32.109)
5664 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
5666 FARPROC prev = blocking_hook;
5667 blocking_hook = lpBlockFunc;
5668 TRACE("hook %p\n", lpBlockFunc);
5669 return prev;
5673 /***********************************************************************
5674 * WSAUnhookBlockingHook (WS2_32.110)
5676 INT WINAPI WSAUnhookBlockingHook(void)
5678 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
5679 return 0;
5683 /* ----------------------------------- end of API stuff */
5685 /* ----------------------------------- helper functions -
5687 * TODO: Merge WS_dup_..() stuff into one function that
5688 * would operate with a generic structure containing internal
5689 * pointers (via a template of some kind).
5692 static int list_size(char** l, int item_size)
5694 int i,j = 0;
5695 if(l)
5696 { for(i=0;l[i];i++)
5697 j += (item_size) ? item_size : strlen(l[i]) + 1;
5698 j += (i + 1) * sizeof(char*); }
5699 return j;
5702 static int list_dup(char** l_src, char** l_to, int item_size)
5704 char *p;
5705 int i;
5707 for (i = 0; l_src[i]; i++) ;
5708 p = (char *)(l_to + i + 1);
5709 for (i = 0; l_src[i]; i++)
5711 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
5712 memcpy(p, l_src[i], count);
5713 l_to[i] = p;
5714 p += count;
5716 l_to[i] = NULL;
5717 return p - (char *)l_to;
5720 /* ----- hostent */
5722 /* create a hostent entry
5724 * Creates the entry with enough memory for the name, aliases
5725 * addresses, and the address pointers. Also copies the name
5726 * and sets up all the pointers.
5728 * NOTE: The alias and address lists must be allocated with room
5729 * for the NULL item terminating the list. This is true even if
5730 * the list has no items ("aliases" and "addresses" must be
5731 * at least "1", a truly empty list is invalid).
5733 static struct WS_hostent *WS_create_he(char *name, int aliases, int aliases_size, int addresses, int address_length)
5735 struct WS_hostent *p_to;
5736 char *p;
5737 int size = (sizeof(struct WS_hostent) +
5738 strlen(name) + 1 +
5739 sizeof(char *) * aliases +
5740 aliases_size +
5741 sizeof(char *) * addresses +
5742 address_length * (addresses - 1)), i;
5744 if (!(p_to = check_buffer_he(size))) return NULL;
5745 memset(p_to, 0, size);
5747 /* Use the memory in the same way winsock does.
5748 * First set the pointer for aliases, second set the pointers for addresses.
5749 * Third fill the addresses indexes, fourth jump aliases names size.
5750 * Fifth fill the hostname.
5751 * NOTE: This method is valid for OS version's >= XP.
5753 p = (char *)(p_to + 1);
5754 p_to->h_aliases = (char **)p;
5755 p += sizeof(char *)*aliases;
5757 p_to->h_addr_list = (char **)p;
5758 p += sizeof(char *)*addresses;
5760 for (i = 0, addresses--; i < addresses; i++, p += address_length)
5761 p_to->h_addr_list[i] = p;
5763 /* NOTE: h_aliases must be filled in manually because we don't know each string
5764 * size, leave these pointers NULL (already set to NULL by memset earlier).
5766 p += aliases_size;
5768 p_to->h_name = p;
5769 strcpy(p, name);
5771 return p_to;
5774 /* duplicate hostent entry
5775 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
5776 * Ditto for protoent and servent.
5778 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
5780 int i, addresses = 0, alias_size = 0;
5781 struct WS_hostent *p_to;
5782 char *p;
5784 for( i = 0; p_he->h_aliases[i]; i++) alias_size += strlen(p_he->h_aliases[i]) + 1;
5785 while (p_he->h_addr_list[addresses]) addresses++;
5787 p_to = WS_create_he(p_he->h_name, i + 1, alias_size, addresses + 1, p_he->h_length);
5789 if (!p_to) return NULL;
5790 p_to->h_addrtype = p_he->h_addrtype;
5791 p_to->h_length = p_he->h_length;
5793 for(i = 0, p = p_to->h_addr_list[0]; p_he->h_addr_list[i]; i++, p += p_to->h_length)
5794 memcpy(p, p_he->h_addr_list[i], p_to->h_length);
5796 /* Fill the aliases after the IP data */
5797 for(i = 0; p_he->h_aliases[i]; i++)
5799 p_to->h_aliases[i] = p;
5800 strcpy(p, p_he->h_aliases[i]);
5801 p += strlen(p) + 1;
5804 return p_to;
5807 /* ----- protoent */
5809 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
5811 char *p;
5812 struct WS_protoent *p_to;
5814 int size = (sizeof(*p_pe) +
5815 strlen(p_pe->p_name) + 1 +
5816 list_size(p_pe->p_aliases, 0));
5818 if (!(p_to = check_buffer_pe(size))) return NULL;
5819 p_to->p_proto = p_pe->p_proto;
5821 p = (char *)(p_to + 1);
5822 p_to->p_name = p;
5823 strcpy(p, p_pe->p_name);
5824 p += strlen(p) + 1;
5826 p_to->p_aliases = (char **)p;
5827 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
5828 return p_to;
5831 /* ----- servent */
5833 static struct WS_servent *WS_dup_se(const struct servent* p_se)
5835 char *p;
5836 struct WS_servent *p_to;
5838 int size = (sizeof(*p_se) +
5839 strlen(p_se->s_proto) + 1 +
5840 strlen(p_se->s_name) + 1 +
5841 list_size(p_se->s_aliases, 0));
5843 if (!(p_to = check_buffer_se(size))) return NULL;
5844 p_to->s_port = p_se->s_port;
5846 p = (char *)(p_to + 1);
5847 p_to->s_name = p;
5848 strcpy(p, p_se->s_name);
5849 p += strlen(p) + 1;
5851 p_to->s_proto = p;
5852 strcpy(p, p_se->s_proto);
5853 p += strlen(p) + 1;
5855 p_to->s_aliases = (char **)p;
5856 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
5857 return p_to;
5861 /***********************************************************************
5862 * WSARecv (WS2_32.67)
5864 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5865 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
5866 LPWSAOVERLAPPED lpOverlapped,
5867 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
5869 return WS2_recv_base(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
5870 NULL, NULL, lpOverlapped, lpCompletionRoutine, NULL);
5873 static int WS2_recv_base( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
5874 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags,
5875 struct WS_sockaddr *lpFrom,
5876 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
5877 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
5878 LPWSABUF lpControlBuffer )
5880 unsigned int i, options;
5881 int n, fd, err;
5882 struct ws2_async *wsa;
5883 BOOL is_blocking;
5884 DWORD timeout_start = GetTickCount();
5885 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
5887 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
5888 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
5889 (lpFromlen ? *lpFromlen : -1),
5890 lpOverlapped, lpCompletionRoutine);
5892 fd = get_sock_fd( s, FILE_READ_DATA, &options );
5893 TRACE( "fd=%d, options=%x\n", fd, options );
5895 if (fd == -1) return SOCKET_ERROR;
5897 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
5899 err = WSAEFAULT;
5900 goto error;
5903 wsa->hSocket = SOCKET2HANDLE(s);
5904 wsa->flags = *lpFlags;
5905 wsa->lpFlags = lpFlags;
5906 wsa->addr = lpFrom;
5907 wsa->addrlen.ptr = lpFromlen;
5908 wsa->control = lpControlBuffer;
5909 wsa->n_iovecs = dwBufferCount;
5910 wsa->first_iovec = 0;
5911 for (i = 0; i < dwBufferCount; i++)
5913 /* check buffer first to trigger write watches */
5914 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
5916 err = WSAEFAULT;
5917 goto error;
5919 wsa->iovec[i].iov_base = lpBuffers[i].buf;
5920 wsa->iovec[i].iov_len = lpBuffers[i].len;
5923 for (;;)
5925 n = WS2_recv( fd, wsa );
5926 if (n == -1)
5928 if (errno == EINTR) continue;
5929 if (errno != EAGAIN)
5931 int loc_errno = errno;
5932 err = wsaErrno();
5933 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
5934 goto error;
5937 else if (lpNumberOfBytesRecvd) *lpNumberOfBytesRecvd = n;
5939 if ((lpOverlapped || lpCompletionRoutine) &&
5940 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
5942 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
5944 wsa->user_overlapped = lpOverlapped;
5945 wsa->completion_func = lpCompletionRoutine;
5946 release_sock_fd( s, fd );
5948 if (n == -1)
5950 iosb->u.Status = STATUS_PENDING;
5951 iosb->Information = 0;
5953 SERVER_START_REQ( register_async )
5955 req->type = ASYNC_TYPE_READ;
5956 req->async.handle = wine_server_obj_handle( wsa->hSocket );
5957 req->async.callback = wine_server_client_ptr( WS2_async_recv );
5958 req->async.iosb = wine_server_client_ptr( iosb );
5959 req->async.arg = wine_server_client_ptr( wsa );
5960 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
5961 req->async.cvalue = cvalue;
5962 err = wine_server_call( req );
5964 SERVER_END_REQ;
5966 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
5967 WSASetLastError( NtStatusToWSAError( err ));
5968 return SOCKET_ERROR;
5971 iosb->u.Status = STATUS_SUCCESS;
5972 iosb->Information = n;
5973 if (!wsa->completion_func)
5975 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
5976 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
5977 HeapFree( GetProcessHeap(), 0, wsa );
5979 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
5980 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
5981 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5982 return 0;
5985 if (n != -1) break;
5987 if ((err = _is_blocking( s, &is_blocking )))
5989 err = NtStatusToWSAError( err );
5990 goto error;
5993 if ( is_blocking )
5995 struct pollfd pfd;
5996 int timeout = GET_RCVTIMEO(fd);
5997 if (timeout != -1)
5999 timeout -= GetTickCount() - timeout_start;
6000 if (timeout < 0) timeout = 0;
6003 pfd.fd = fd;
6004 pfd.events = POLLIN;
6005 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
6007 if (!timeout || !poll( &pfd, 1, timeout ))
6009 err = WSAETIMEDOUT;
6010 /* a timeout is not fatal */
6011 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6012 goto error;
6015 else
6017 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6018 err = WSAEWOULDBLOCK;
6019 goto error;
6023 TRACE(" -> %i bytes\n", n);
6024 HeapFree( GetProcessHeap(), 0, wsa );
6025 release_sock_fd( s, fd );
6026 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
6028 return 0;
6030 error:
6031 HeapFree( GetProcessHeap(), 0, wsa );
6032 release_sock_fd( s, fd );
6033 WARN(" -> ERROR %d\n", err);
6034 WSASetLastError( err );
6035 return SOCKET_ERROR;
6038 /***********************************************************************
6039 * WSARecvFrom (WS2_32.69)
6041 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
6042 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
6043 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
6044 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
6047 return WS2_recv_base( s, lpBuffers, dwBufferCount,
6048 lpNumberOfBytesRecvd, lpFlags,
6049 lpFrom, lpFromlen,
6050 lpOverlapped, lpCompletionRoutine, NULL );
6053 /***********************************************************************
6054 * WSCInstallProvider (WS2_32.88)
6056 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
6057 LPCWSTR lpszProviderDllPath,
6058 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
6059 DWORD dwNumberOfEntries,
6060 LPINT lpErrno )
6062 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
6063 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
6064 dwNumberOfEntries, lpErrno);
6065 *lpErrno = 0;
6066 return 0;
6070 /***********************************************************************
6071 * WSCDeinstallProvider (WS2_32.83)
6073 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
6075 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
6076 *lpErrno = 0;
6077 return 0;
6081 /***********************************************************************
6082 * WSAAccept (WS2_32.26)
6084 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
6085 LPCONDITIONPROC lpfnCondition, DWORD_PTR dwCallbackData)
6088 int ret = 0, size = 0;
6089 WSABUF CallerId, CallerData, CalleeId, CalleeData;
6090 /* QOS SQOS, GQOS; */
6091 GROUP g;
6092 SOCKET cs;
6093 SOCKADDR src_addr, dst_addr;
6095 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
6096 s, addr, addrlen, lpfnCondition, dwCallbackData);
6099 size = sizeof(src_addr);
6100 cs = WS_accept(s, &src_addr, &size);
6102 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
6104 if (!lpfnCondition) return cs;
6106 CallerId.buf = (char *)&src_addr;
6107 CallerId.len = sizeof(src_addr);
6109 CallerData.buf = NULL;
6110 CallerData.len = 0;
6112 WS_getsockname(cs, &dst_addr, &size);
6114 CalleeId.buf = (char *)&dst_addr;
6115 CalleeId.len = sizeof(dst_addr);
6118 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
6119 &CalleeId, &CalleeData, &g, dwCallbackData);
6121 switch (ret)
6123 case CF_ACCEPT:
6124 if (addr && addrlen)
6125 memcpy(addr, &src_addr, (*addrlen > size) ? size : *addrlen );
6126 return cs;
6127 case CF_DEFER:
6128 SERVER_START_REQ( set_socket_deferred )
6130 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
6131 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
6132 if ( !wine_server_call_err ( req ) )
6134 SetLastError( WSATRY_AGAIN );
6135 WS_closesocket( cs );
6138 SERVER_END_REQ;
6139 return SOCKET_ERROR;
6140 case CF_REJECT:
6141 WS_closesocket(cs);
6142 SetLastError(WSAECONNREFUSED);
6143 return SOCKET_ERROR;
6144 default:
6145 FIXME("Unknown return type from Condition function\n");
6146 SetLastError(WSAENOTSOCK);
6147 return SOCKET_ERROR;
6151 /***********************************************************************
6152 * WSADuplicateSocketA (WS2_32.32)
6154 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
6156 HANDLE hProcess;
6158 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
6159 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
6160 /* FIXME: WS_getsockopt(s, WS_SOL_SOCKET, SO_PROTOCOL_INFO, lpProtocolInfo, sizeof(*lpProtocolInfo)); */
6161 /* I don't know what the real Windoze does next, this is a hack */
6162 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
6163 * the target use the global duplicate, or we could copy a reference to us to the structure
6164 * and let the target duplicate it from us, but let's do it as simple as possible */
6165 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
6166 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
6167 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
6168 0, FALSE, DUPLICATE_SAME_ACCESS);
6169 CloseHandle(hProcess);
6170 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
6171 return 0;
6174 /***********************************************************************
6175 * WSADuplicateSocketW (WS2_32.33)
6177 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
6179 HANDLE hProcess;
6181 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
6183 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
6184 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
6185 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
6186 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
6187 0, FALSE, DUPLICATE_SAME_ACCESS);
6188 CloseHandle(hProcess);
6189 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
6190 return 0;
6193 /***********************************************************************
6194 * WSAInstallServiceClassA (WS2_32.48)
6196 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
6198 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
6199 WSASetLastError(WSAEACCES);
6200 return SOCKET_ERROR;
6203 /***********************************************************************
6204 * WSAInstallServiceClassW (WS2_32.49)
6206 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
6208 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
6209 WSASetLastError(WSAEACCES);
6210 return SOCKET_ERROR;
6213 /***********************************************************************
6214 * WSARemoveServiceClass (WS2_32.70)
6216 int WINAPI WSARemoveServiceClass(LPGUID info)
6218 FIXME("Request to remove service %p\n",info);
6219 WSASetLastError(WSATYPE_NOT_FOUND);
6220 return SOCKET_ERROR;
6223 /***********************************************************************
6224 * inet_ntop (WS2_32.@)
6226 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
6228 #ifdef HAVE_INET_NTOP
6229 struct WS_in6_addr *in6;
6230 struct WS_in_addr *in;
6231 PCSTR pdst;
6233 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
6234 if (!buffer)
6236 WSASetLastError( STATUS_INVALID_PARAMETER );
6237 return NULL;
6240 switch (family)
6242 case WS_AF_INET:
6244 in = addr;
6245 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
6246 break;
6248 case WS_AF_INET6:
6250 in6 = addr;
6251 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
6252 break;
6254 default:
6255 WSASetLastError( WSAEAFNOSUPPORT );
6256 return NULL;
6259 if (!pdst) WSASetLastError( STATUS_INVALID_PARAMETER );
6260 return pdst;
6261 #else
6262 FIXME( "not supported on this platform\n" );
6263 WSASetLastError( WSAEAFNOSUPPORT );
6264 return NULL;
6265 #endif
6268 /***********************************************************************
6269 * WSAStringToAddressA (WS2_32.80)
6271 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
6272 INT AddressFamily,
6273 LPWSAPROTOCOL_INFOA lpProtocolInfo,
6274 LPSOCKADDR lpAddress,
6275 LPINT lpAddressLength)
6277 INT res=0;
6278 LPSTR workBuffer=NULL,ptrPort;
6280 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
6281 lpProtocolInfo, lpAddress, lpAddressLength );
6283 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
6285 if (!AddressString)
6287 WSASetLastError(WSAEINVAL);
6288 return SOCKET_ERROR;
6291 if (lpProtocolInfo)
6292 FIXME("ProtocolInfo not implemented.\n");
6294 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
6295 strlen(AddressString) + 1);
6296 if (!workBuffer)
6298 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6299 return SOCKET_ERROR;
6302 strcpy(workBuffer, AddressString);
6304 switch(AddressFamily)
6306 case WS_AF_INET:
6308 struct in_addr inetaddr;
6310 /* If lpAddressLength is too small, tell caller the size we need */
6311 if (*lpAddressLength < sizeof(SOCKADDR_IN))
6313 *lpAddressLength = sizeof(SOCKADDR_IN);
6314 res = WSAEFAULT;
6315 break;
6317 *lpAddressLength = sizeof(SOCKADDR_IN);
6318 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
6320 ((LPSOCKADDR_IN)lpAddress)->sin_family = AF_INET;
6322 ptrPort = strchr(workBuffer, ':');
6323 if(ptrPort)
6325 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
6326 *ptrPort = '\0';
6328 else
6330 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
6333 if(inet_aton(workBuffer, &inetaddr) > 0)
6335 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
6336 res = 0;
6338 else
6339 res = WSAEINVAL;
6341 break;
6344 case WS_AF_INET6:
6346 struct in6_addr inetaddr;
6347 /* If lpAddressLength is too small, tell caller the size we need */
6348 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
6350 *lpAddressLength = sizeof(SOCKADDR_IN6);
6351 res = WSAEFAULT;
6352 break;
6354 #ifdef HAVE_INET_PTON
6355 *lpAddressLength = sizeof(SOCKADDR_IN6);
6356 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
6358 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
6360 /* This one is a bit tricky. An IPv6 address contains colons, so the
6361 * check from IPv4 doesn't work like that. However, IPv6 addresses that
6362 * contain a port are written with braces like [fd12:3456:7890::1]:12345
6363 * so what we will do is to look for ']', check if the next char is a
6364 * colon, and if it is, parse the port as in IPv4. */
6366 ptrPort = strchr(workBuffer, ']');
6367 if(ptrPort && *(++ptrPort) == ':')
6369 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort+1));
6370 *ptrPort = '\0';
6372 else
6374 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
6377 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
6379 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
6380 sizeof(struct in6_addr));
6381 res = 0;
6383 else
6384 #endif /* HAVE_INET_PTON */
6385 res = WSAEINVAL;
6387 break;
6389 default:
6390 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
6391 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
6392 res = WSAEINVAL;
6395 HeapFree(GetProcessHeap(), 0, workBuffer);
6397 if (!res) return 0;
6398 WSASetLastError(res);
6399 return SOCKET_ERROR;
6402 /***********************************************************************
6403 * WSAStringToAddressW (WS2_32.81)
6405 * FIXME: Does anybody know if this function allows using Hebrew/Arabic/Chinese... digits?
6406 * If this should be the case, it would be required to map these digits
6407 * to Unicode digits (0-9) using FoldString first.
6409 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
6410 INT AddressFamily,
6411 LPWSAPROTOCOL_INFOW lpProtocolInfo,
6412 LPSOCKADDR lpAddress,
6413 LPINT lpAddressLength)
6415 INT sBuffer,res=0;
6416 LPSTR workBuffer=NULL;
6417 WSAPROTOCOL_INFOA infoA;
6418 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
6420 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
6421 lpAddress, lpAddressLength );
6423 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
6425 /* if ProtocolInfo is available - convert to ANSI variant */
6426 if (lpProtocolInfo)
6428 lpProtoInfoA = &infoA;
6429 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
6431 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
6432 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
6434 WSASetLastError( WSAEINVAL);
6435 return SOCKET_ERROR;
6439 if (AddressString)
6441 /* Translate AddressString to ANSI code page - assumes that only
6442 standard digits 0-9 are used with this API call */
6443 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
6444 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
6446 if (workBuffer)
6448 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
6449 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
6450 lpAddress,lpAddressLength);
6451 HeapFree( GetProcessHeap(), 0, workBuffer );
6452 return res;
6454 else
6455 res = WSA_NOT_ENOUGH_MEMORY;
6457 else
6458 res = WSAEINVAL;
6460 WSASetLastError(res);
6461 return SOCKET_ERROR;
6464 /***********************************************************************
6465 * WSAAddressToStringA (WS2_32.27)
6467 * See WSAAddressToStringW
6469 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
6470 LPWSAPROTOCOL_INFOA info, LPSTR string,
6471 LPDWORD lenstr )
6473 DWORD size;
6474 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
6475 CHAR *p;
6477 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
6479 if (!sockaddr) return SOCKET_ERROR;
6480 if (!string || !lenstr) return SOCKET_ERROR;
6482 switch(sockaddr->sa_family)
6484 case WS_AF_INET:
6485 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
6486 sprintf( buffer, "%u.%u.%u.%u:%u",
6487 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
6488 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
6489 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
6490 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
6491 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
6493 p = strchr( buffer, ':' );
6494 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
6495 break;
6497 case WS_AF_INET6:
6499 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
6501 buffer[0] = 0;
6502 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
6503 if ((sockaddr6->sin6_port))
6504 strcpy(buffer, "[");
6505 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, buffer+strlen(buffer), sizeof(buffer)))
6507 WSASetLastError(WSAEINVAL);
6508 return SOCKET_ERROR;
6510 if ((sockaddr6->sin6_scope_id))
6511 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
6512 if ((sockaddr6->sin6_port))
6513 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
6514 break;
6517 default:
6518 WSASetLastError(WSAEINVAL);
6519 return SOCKET_ERROR;
6522 size = strlen( buffer ) + 1;
6524 if (*lenstr < size)
6526 *lenstr = size;
6527 WSASetLastError(WSAEFAULT);
6528 return SOCKET_ERROR;
6531 *lenstr = size;
6532 strcpy( string, buffer );
6533 return 0;
6536 /***********************************************************************
6537 * WSAAddressToStringW (WS2_32.28)
6539 * Convert a sockaddr address into a readable address string.
6541 * PARAMS
6542 * sockaddr [I] Pointer to a sockaddr structure.
6543 * len [I] Size of the sockaddr structure.
6544 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
6545 * string [I/O] Pointer to a buffer to receive the address string.
6546 * lenstr [I/O] Size of the receive buffer in WCHARs.
6548 * RETURNS
6549 * Success: 0
6550 * Failure: SOCKET_ERROR
6552 * NOTES
6553 * The 'info' parameter is ignored.
6555 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
6556 LPWSAPROTOCOL_INFOW info, LPWSTR string,
6557 LPDWORD lenstr )
6559 INT ret;
6560 DWORD size;
6561 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
6562 CHAR bufAddr[54];
6564 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
6566 size = *lenstr;
6567 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
6569 if (ret) return ret;
6571 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
6573 if (*lenstr < size)
6575 *lenstr = size;
6576 WSASetLastError(WSAEFAULT);
6577 return SOCKET_ERROR;
6580 *lenstr = size;
6581 lstrcpyW( string, buffer );
6582 return 0;
6585 /***********************************************************************
6586 * WSAEnumNameSpaceProvidersA (WS2_32.34)
6588 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
6590 FIXME( "(%p %p) Stub!\n", len, buffer );
6591 return 0;
6594 /***********************************************************************
6595 * WSAEnumNameSpaceProvidersW (WS2_32.35)
6597 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
6599 FIXME( "(%p %p) Stub!\n", len, buffer );
6600 return 0;
6603 /***********************************************************************
6604 * WSAGetQOSByName (WS2_32.41)
6606 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
6608 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
6609 return FALSE;
6612 /***********************************************************************
6613 * WSAGetServiceClassInfoA (WS2_32.42)
6615 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
6616 LPWSASERVICECLASSINFOA info )
6618 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
6619 len, info );
6620 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6621 return SOCKET_ERROR;
6624 /***********************************************************************
6625 * WSAGetServiceClassInfoW (WS2_32.43)
6627 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
6628 LPWSASERVICECLASSINFOW info )
6630 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
6631 len, info );
6632 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6633 return SOCKET_ERROR;
6636 /***********************************************************************
6637 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
6639 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
6641 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
6642 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6643 return SOCKET_ERROR;
6646 /***********************************************************************
6647 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
6649 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
6651 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
6652 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6653 return SOCKET_ERROR;
6656 /***********************************************************************
6657 * WSALookupServiceBeginA (WS2_32.59)
6659 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
6660 DWORD dwControlFlags,
6661 LPHANDLE lphLookup)
6663 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
6664 lphLookup);
6665 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6666 return SOCKET_ERROR;
6669 /***********************************************************************
6670 * WSALookupServiceBeginW (WS2_32.60)
6672 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
6673 DWORD dwControlFlags,
6674 LPHANDLE lphLookup)
6676 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
6677 lphLookup);
6678 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6679 return SOCKET_ERROR;
6682 /***********************************************************************
6683 * WSALookupServiceEnd (WS2_32.61)
6685 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
6687 FIXME("(%p) Stub!\n", lookup );
6688 return 0;
6691 /***********************************************************************
6692 * WSALookupServiceNextA (WS2_32.62)
6694 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
6696 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
6697 WSASetLastError(WSA_E_NO_MORE);
6698 return SOCKET_ERROR;
6701 /***********************************************************************
6702 * WSALookupServiceNextW (WS2_32.63)
6704 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
6706 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
6707 WSASetLastError(WSA_E_NO_MORE);
6708 return SOCKET_ERROR;
6711 /***********************************************************************
6712 * WSANtohl (WS2_32.64)
6714 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
6716 TRACE( "(0x%04lx 0x%08x %p)\n", s, netlong, lphostlong );
6718 if (!lphostlong) return WSAEFAULT;
6720 *lphostlong = ntohl( netlong );
6721 return 0;
6724 /***********************************************************************
6725 * WSANtohs (WS2_32.65)
6727 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
6729 TRACE( "(0x%04lx 0x%08x %p)\n", s, netshort, lphostshort );
6731 if (!lphostshort) return WSAEFAULT;
6733 *lphostshort = ntohs( netshort );
6734 return 0;
6737 /***********************************************************************
6738 * WSAProviderConfigChange (WS2_32.66)
6740 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
6741 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
6743 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
6744 return SOCKET_ERROR;
6747 /***********************************************************************
6748 * WSARecvDisconnect (WS2_32.68)
6750 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
6752 TRACE( "(0x%04lx %p)\n", s, disconnectdata );
6754 return WS_shutdown( s, 0 );
6757 /***********************************************************************
6758 * WSASetServiceA (WS2_32.76)
6760 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
6762 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
6763 return 0;
6766 /***********************************************************************
6767 * WSASetServiceW (WS2_32.77)
6769 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
6771 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
6772 return 0;
6775 /***********************************************************************
6776 * WSCEnableNSProvider (WS2_32.84)
6778 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
6780 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
6781 return 0;
6784 /***********************************************************************
6785 * WSCGetProviderPath (WS2_32.86)
6787 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
6789 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
6791 if (!errcode || !provider || !len) return WSAEFAULT;
6793 *errcode = WSAEINVAL;
6794 return SOCKET_ERROR;
6797 /***********************************************************************
6798 * WSCInstallNameSpace (WS2_32.87)
6800 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
6801 DWORD version, LPGUID provider )
6803 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
6804 namespace, version, debugstr_guid(provider) );
6805 return 0;
6808 /***********************************************************************
6809 * WSCUnInstallNameSpace (WS2_32.89)
6811 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
6813 FIXME("(%p) Stub!\n", lpProviderId);
6814 return NO_ERROR;
6817 /***********************************************************************
6818 * WSCWriteProviderOrder (WS2_32.91)
6820 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
6822 FIXME("(%p 0x%08x) Stub!\n", entry, number);
6823 return 0;
6826 /***********************************************************************
6827 * WSANSPIoctl (WS2_32.91)
6829 INT WINAPI WSANSPIoctl( HANDLE hLookup, DWORD dwControlCode, LPVOID lpvInBuffer,
6830 DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer,
6831 LPDWORD lpcbBytesReturned, LPWSACOMPLETION lpCompletion )
6833 FIXME("(%p, 0x%08x, %p, 0x%08x, %p, 0x%08x, %p, %p) Stub!\n", hLookup, dwControlCode,
6834 lpvInBuffer, cbInBuffer, lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpCompletion);
6835 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
6836 return SOCKET_ERROR;