appwiz.cpl: Use the fancy new icon.
[wine/multimedia.git] / dlls / ws2_32 / socket.c
blobe6a6973eb4e6849e7839a85590e6fb471748bd29
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_SYS_ERRNO_H
80 #include <sys/errno.h>
81 #endif
82 #ifdef HAVE_NETDB_H
83 #include <netdb.h>
84 #endif
85 #ifdef HAVE_UNISTD_H
86 # include <unistd.h>
87 #endif
88 #include <stdlib.h>
89 #ifdef HAVE_ARPA_NAMESER_H
90 # include <arpa/nameser.h>
91 #endif
92 #ifdef HAVE_RESOLV_H
93 # include <resolv.h>
94 #endif
95 #ifdef HAVE_NET_IF_H
96 # include <net/if.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 #include "iphlpapi.h"
150 #include "wine/server.h"
151 #include "wine/debug.h"
152 #include "wine/exception.h"
153 #include "wine/unicode.h"
155 #ifdef HAVE_IPX
156 # include "wsnwlink.h"
157 #endif
160 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
161 # define sipx_network sipx_addr.x_net
162 # define sipx_node sipx_addr.x_host.c_host
163 #endif /* __FreeBSD__ */
165 #ifndef INADDR_NONE
166 #define INADDR_NONE ~0UL
167 #endif
169 WINE_DEFAULT_DEBUG_CHANNEL(winsock);
170 WINE_DECLARE_DEBUG_CHANNEL(winediag);
172 /* critical section to protect some non-reentrant net function */
173 static CRITICAL_SECTION csWSgetXXXbyYYY;
174 static CRITICAL_SECTION_DEBUG critsect_debug =
176 0, 0, &csWSgetXXXbyYYY,
177 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
178 0, 0, { (DWORD_PTR)(__FILE__ ": csWSgetXXXbyYYY") }
180 static CRITICAL_SECTION csWSgetXXXbyYYY = { &critsect_debug, -1, 0, 0, 0, 0 };
182 union generic_unix_sockaddr
184 struct sockaddr addr;
185 char data[128]; /* should be big enough for all families */
188 static inline const char *debugstr_sockaddr( const struct WS_sockaddr *a )
190 if (!a) return "(nil)";
191 switch (a->sa_family)
193 case WS_AF_INET:
194 return wine_dbg_sprintf("{ family AF_INET, address %s, port %d }",
195 inet_ntoa(((const struct sockaddr_in *)a)->sin_addr),
196 ntohs(((const struct sockaddr_in *)a)->sin_port));
197 case WS_AF_INET6:
199 char buf[46];
200 const char *p;
201 struct WS_sockaddr_in6 *sin = (struct WS_sockaddr_in6 *)a;
203 p = WS_inet_ntop( WS_AF_INET6, &sin->sin6_addr, buf, sizeof(buf) );
204 if (!p)
205 p = "(unknown IPv6 address)";
206 return wine_dbg_sprintf("{ family AF_INET6, address %s, port %d }",
207 p, ntohs(sin->sin6_port));
209 case WS_AF_IRDA:
211 DWORD addr;
213 memcpy( &addr, ((const SOCKADDR_IRDA *)a)->irdaDeviceID, sizeof(addr) );
214 addr = ntohl( addr );
215 return wine_dbg_sprintf("{ family AF_IRDA, addr %08x, name %s }",
216 addr,
217 ((const SOCKADDR_IRDA *)a)->irdaServiceName);
219 default:
220 return wine_dbg_sprintf("{ family %d }", a->sa_family);
224 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
225 #define SOCKET2HANDLE(s) ((HANDLE)(s))
226 #define HANDLE2SOCKET(h) ((SOCKET)(h))
228 /****************************************************************
229 * Async IO declarations
230 ****************************************************************/
232 typedef struct ws2_async
234 HANDLE hSocket;
235 int type;
236 LPWSAOVERLAPPED user_overlapped;
237 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
238 IO_STATUS_BLOCK local_iosb;
239 struct WS_sockaddr *addr;
240 union
242 int val; /* for send operations */
243 int *ptr; /* for recv operations */
244 } addrlen;
245 DWORD flags;
246 unsigned int n_iovecs;
247 unsigned int first_iovec;
248 struct iovec iovec[1];
249 } ws2_async;
251 /****************************************************************/
253 /* ----------------------------------- internal data */
255 /* ws_... struct conversion flags */
257 typedef struct /* WSAAsyncSelect() control struct */
259 HANDLE service, event, sock;
260 HWND hWnd;
261 UINT uMsg;
262 LONG lEvent;
263 } ws_select_info;
265 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
266 #define WS_MAX_UDP_DATAGRAM 1024
267 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
269 /* hostent's, servent's and protent's are stored in one buffer per thread,
270 * as documented on MSDN for the functions that return any of the buffers */
271 struct per_thread_data
273 int opentype;
274 struct WS_hostent *he_buffer;
275 struct WS_servent *se_buffer;
276 struct WS_protoent *pe_buffer;
277 int he_len;
278 int se_len;
279 int pe_len;
282 /* internal: routing description information */
283 struct route {
284 struct in_addr addr;
285 DWORD interface;
286 DWORD metric;
289 static INT num_startup; /* reference counter */
290 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
292 /* function prototypes */
293 static struct WS_hostent *WS_create_he(char *name, int aliases, int addresses, int fill_addresses);
294 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
295 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
296 static struct WS_servent *WS_dup_se(const struct servent* p_se);
298 int WSAIOCTL_GetInterfaceCount(void);
299 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
301 #define MAP_OPTION(opt) { WS_##opt, opt }
303 static const int ws_sock_map[][2] =
305 MAP_OPTION( SO_DEBUG ),
306 MAP_OPTION( SO_ACCEPTCONN ),
307 MAP_OPTION( SO_REUSEADDR ),
308 MAP_OPTION( SO_KEEPALIVE ),
309 MAP_OPTION( SO_DONTROUTE ),
310 MAP_OPTION( SO_BROADCAST ),
311 MAP_OPTION( SO_LINGER ),
312 MAP_OPTION( SO_OOBINLINE ),
313 MAP_OPTION( SO_SNDBUF ),
314 MAP_OPTION( SO_RCVBUF ),
315 MAP_OPTION( SO_ERROR ),
316 MAP_OPTION( SO_TYPE ),
317 #ifdef SO_RCVTIMEO
318 MAP_OPTION( SO_RCVTIMEO ),
319 #endif
320 #ifdef SO_SNDTIMEO
321 MAP_OPTION( SO_SNDTIMEO ),
322 #endif
325 static const int ws_tcp_map[][2] =
327 #ifdef TCP_NODELAY
328 MAP_OPTION( TCP_NODELAY ),
329 #endif
332 static const int ws_ip_map[][2] =
334 MAP_OPTION( IP_MULTICAST_IF ),
335 MAP_OPTION( IP_MULTICAST_TTL ),
336 MAP_OPTION( IP_MULTICAST_LOOP ),
337 MAP_OPTION( IP_ADD_MEMBERSHIP ),
338 MAP_OPTION( IP_DROP_MEMBERSHIP ),
339 MAP_OPTION( IP_OPTIONS ),
340 #ifdef IP_HDRINCL
341 MAP_OPTION( IP_HDRINCL ),
342 #endif
343 MAP_OPTION( IP_TOS ),
344 MAP_OPTION( IP_TTL ),
347 static const int ws_ipv6_map[][2] =
349 #ifdef IPV6_ADD_MEMBERSHIP
350 MAP_OPTION( IPV6_ADD_MEMBERSHIP ),
351 #endif
352 #ifdef IPV6_DROP_MEMBERSHIP
353 MAP_OPTION( IPV6_DROP_MEMBERSHIP ),
354 #endif
355 MAP_OPTION( IPV6_MULTICAST_IF ),
356 MAP_OPTION( IPV6_MULTICAST_HOPS ),
357 MAP_OPTION( IPV6_MULTICAST_LOOP ),
358 MAP_OPTION( IPV6_UNICAST_HOPS ),
359 MAP_OPTION( IPV6_V6ONLY ),
362 static const int ws_af_map[][2] =
364 MAP_OPTION( AF_UNSPEC ),
365 MAP_OPTION( AF_INET ),
366 MAP_OPTION( AF_INET6 ),
367 #ifdef HAVE_IPX
368 MAP_OPTION( AF_IPX ),
369 #endif
370 #ifdef AF_IRDA
371 MAP_OPTION( AF_IRDA ),
372 #endif
373 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
376 static const int ws_socktype_map[][2] =
378 MAP_OPTION( SOCK_DGRAM ),
379 MAP_OPTION( SOCK_STREAM ),
380 MAP_OPTION( SOCK_RAW ),
381 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
384 static const int ws_proto_map[][2] =
386 MAP_OPTION( IPPROTO_IP ),
387 MAP_OPTION( IPPROTO_TCP ),
388 MAP_OPTION( IPPROTO_UDP ),
389 MAP_OPTION( IPPROTO_ICMP ),
390 MAP_OPTION( IPPROTO_IGMP ),
391 MAP_OPTION( IPPROTO_RAW ),
392 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
395 static const int ws_aiflag_map[][2] =
397 MAP_OPTION( AI_PASSIVE ),
398 MAP_OPTION( AI_CANONNAME ),
399 MAP_OPTION( AI_NUMERICHOST ),
400 /* Linux/UNIX knows a lot more. But Windows only
401 * has 3 as far as I could see. -Marcus
405 static const int ws_niflag_map[][2] =
407 MAP_OPTION( NI_NOFQDN ),
408 MAP_OPTION( NI_NUMERICHOST ),
409 MAP_OPTION( NI_NAMEREQD ),
410 MAP_OPTION( NI_NUMERICSERV ),
411 MAP_OPTION( NI_DGRAM ),
414 static const int ws_eai_map[][2] =
416 MAP_OPTION( EAI_AGAIN ),
417 MAP_OPTION( EAI_BADFLAGS ),
418 MAP_OPTION( EAI_FAIL ),
419 MAP_OPTION( EAI_FAMILY ),
420 MAP_OPTION( EAI_MEMORY ),
421 /* Note: EAI_NODATA is deprecated, but still
422 * used by Windows and Linux... We map the newer
423 * EAI_NONAME to EAI_NODATA for now until Windows
424 * changes too.
426 #ifdef EAI_NODATA
427 MAP_OPTION( EAI_NODATA ),
428 #endif
429 #ifdef EAI_NONAME
430 { WS_EAI_NODATA, EAI_NONAME },
431 #endif
433 MAP_OPTION( EAI_SERVICE ),
434 MAP_OPTION( EAI_SOCKTYPE ),
435 { 0, 0 }
438 static const char magic_loopback_addr[] = {127, 12, 34, 56};
440 /* ----------------------------------- error handling */
442 static NTSTATUS sock_get_ntstatus( int err )
444 switch ( err )
446 case EBADF: return STATUS_INVALID_HANDLE;
447 case EBUSY: return STATUS_DEVICE_BUSY;
448 case EPERM:
449 case EACCES: return STATUS_ACCESS_DENIED;
450 case EFAULT: return STATUS_NO_MEMORY;
451 case EINVAL: return STATUS_INVALID_PARAMETER;
452 case ENFILE:
453 case EMFILE: return STATUS_TOO_MANY_OPENED_FILES;
454 case EWOULDBLOCK: return STATUS_CANT_WAIT;
455 case EINPROGRESS: return STATUS_PENDING;
456 case EALREADY: return STATUS_NETWORK_BUSY;
457 case ENOTSOCK: return STATUS_OBJECT_TYPE_MISMATCH;
458 case EDESTADDRREQ: return STATUS_INVALID_PARAMETER;
459 case EMSGSIZE: return STATUS_BUFFER_OVERFLOW;
460 case EPROTONOSUPPORT:
461 case ESOCKTNOSUPPORT:
462 case EPFNOSUPPORT:
463 case EAFNOSUPPORT:
464 case EPROTOTYPE: return STATUS_NOT_SUPPORTED;
465 case ENOPROTOOPT: return STATUS_INVALID_PARAMETER;
466 case EOPNOTSUPP: return STATUS_NOT_SUPPORTED;
467 case EADDRINUSE: return STATUS_ADDRESS_ALREADY_ASSOCIATED;
468 case EADDRNOTAVAIL: return STATUS_INVALID_PARAMETER;
469 case ECONNREFUSED: return STATUS_CONNECTION_REFUSED;
470 case ESHUTDOWN: return STATUS_PIPE_DISCONNECTED;
471 case ENOTCONN: return STATUS_CONNECTION_DISCONNECTED;
472 case ETIMEDOUT: return STATUS_IO_TIMEOUT;
473 case ENETUNREACH: return STATUS_NETWORK_UNREACHABLE;
474 case ENETDOWN: return STATUS_NETWORK_BUSY;
475 case EPIPE:
476 case ECONNRESET: return STATUS_CONNECTION_RESET;
477 case ECONNABORTED: return STATUS_CONNECTION_ABORTED;
479 case 0: return STATUS_SUCCESS;
480 default:
481 WARN("Unknown errno %d!\n", err);
482 return STATUS_UNSUCCESSFUL;
486 static UINT sock_get_error( int err )
488 switch(err)
490 case EINTR: return WSAEINTR;
491 case EBADF: return WSAEBADF;
492 case EPERM:
493 case EACCES: return WSAEACCES;
494 case EFAULT: return WSAEFAULT;
495 case EINVAL: return WSAEINVAL;
496 case EMFILE: return WSAEMFILE;
497 case EWOULDBLOCK: return WSAEWOULDBLOCK;
498 case EINPROGRESS: return WSAEINPROGRESS;
499 case EALREADY: return WSAEALREADY;
500 case ENOTSOCK: return WSAENOTSOCK;
501 case EDESTADDRREQ: return WSAEDESTADDRREQ;
502 case EMSGSIZE: return WSAEMSGSIZE;
503 case EPROTOTYPE: return WSAEPROTOTYPE;
504 case ENOPROTOOPT: return WSAENOPROTOOPT;
505 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
506 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
507 case EOPNOTSUPP: return WSAEOPNOTSUPP;
508 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
509 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
510 case EADDRINUSE: return WSAEADDRINUSE;
511 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
512 case ENETDOWN: return WSAENETDOWN;
513 case ENETUNREACH: return WSAENETUNREACH;
514 case ENETRESET: return WSAENETRESET;
515 case ECONNABORTED: return WSAECONNABORTED;
516 case EPIPE:
517 case ECONNRESET: return WSAECONNRESET;
518 case ENOBUFS: return WSAENOBUFS;
519 case EISCONN: return WSAEISCONN;
520 case ENOTCONN: return WSAENOTCONN;
521 case ESHUTDOWN: return WSAESHUTDOWN;
522 case ETOOMANYREFS: return WSAETOOMANYREFS;
523 case ETIMEDOUT: return WSAETIMEDOUT;
524 case ECONNREFUSED: return WSAECONNREFUSED;
525 case ELOOP: return WSAELOOP;
526 case ENAMETOOLONG: return WSAENAMETOOLONG;
527 case EHOSTDOWN: return WSAEHOSTDOWN;
528 case EHOSTUNREACH: return WSAEHOSTUNREACH;
529 case ENOTEMPTY: return WSAENOTEMPTY;
530 #ifdef EPROCLIM
531 case EPROCLIM: return WSAEPROCLIM;
532 #endif
533 #ifdef EUSERS
534 case EUSERS: return WSAEUSERS;
535 #endif
536 #ifdef EDQUOT
537 case EDQUOT: return WSAEDQUOT;
538 #endif
539 #ifdef ESTALE
540 case ESTALE: return WSAESTALE;
541 #endif
542 #ifdef EREMOTE
543 case EREMOTE: return WSAEREMOTE;
544 #endif
546 /* just in case we ever get here and there are no problems */
547 case 0: return 0;
548 default:
549 WARN("Unknown errno %d!\n", err);
550 return WSAEOPNOTSUPP;
554 static UINT wsaErrno(void)
556 int loc_errno = errno;
557 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
559 return sock_get_error( loc_errno );
562 /* most ws2 overlapped functions return an ntstatus-based error code */
563 static NTSTATUS wsaErrStatus(void)
565 int loc_errno = errno;
566 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
568 return sock_get_ntstatus(loc_errno);
571 static UINT wsaHerrno(int loc_errno)
573 WARN("h_errno %d.\n", loc_errno);
575 switch(loc_errno)
577 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
578 case TRY_AGAIN: return WSATRY_AGAIN;
579 case NO_RECOVERY: return WSANO_RECOVERY;
580 case NO_DATA: return WSANO_DATA;
581 case ENOBUFS: return WSAENOBUFS;
583 case 0: return 0;
584 default:
585 WARN("Unknown h_errno %d!\n", loc_errno);
586 return WSAEOPNOTSUPP;
590 static inline DWORD NtStatusToWSAError( const DWORD status )
592 /* We only need to cover the status codes set by server async request handling */
593 DWORD wserr;
594 switch ( status )
596 case STATUS_SUCCESS: wserr = 0; break;
597 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
598 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
599 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
600 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
601 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
602 case STATUS_NETWORK_BUSY: wserr = WSAEALREADY; break;
603 case STATUS_NETWORK_UNREACHABLE: wserr = WSAENETUNREACH; break;
604 case STATUS_CONNECTION_REFUSED: wserr = WSAECONNREFUSED; break;
605 case STATUS_CONNECTION_DISCONNECTED: wserr = WSAENOTCONN; break;
606 case STATUS_CONNECTION_RESET: wserr = WSAECONNRESET; break;
607 case STATUS_CONNECTION_ABORTED: wserr = WSAECONNABORTED; break;
608 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
609 case STATUS_ADDRESS_ALREADY_ASSOCIATED: wserr = WSAEADDRINUSE; break;
610 case STATUS_IO_TIMEOUT:
611 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
612 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
613 case STATUS_ACCESS_DENIED: wserr = WSAEACCES; break;
614 case STATUS_TOO_MANY_OPENED_FILES: wserr = WSAEMFILE; break;
615 case STATUS_CANT_WAIT: wserr = WSAEWOULDBLOCK; break;
616 case STATUS_BUFFER_OVERFLOW: wserr = WSAEMSGSIZE; break;
617 case STATUS_NOT_SUPPORTED: wserr = WSAEOPNOTSUPP; break;
619 default:
620 wserr = RtlNtStatusToDosError( status );
621 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
623 return wserr;
626 /* set last error code from NT status without mapping WSA errors */
627 static inline unsigned int set_error( unsigned int err )
629 if (err)
631 err = NtStatusToWSAError( err );
632 SetLastError( err );
634 return err;
637 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
639 int fd;
640 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
641 return -1;
642 return fd;
645 static inline void release_sock_fd( SOCKET s, int fd )
647 wine_server_release_fd( SOCKET2HANDLE(s), fd );
650 static void _enable_event( HANDLE s, unsigned int event,
651 unsigned int sstate, unsigned int cstate )
653 SERVER_START_REQ( enable_socket_event )
655 req->handle = wine_server_obj_handle( s );
656 req->mask = event;
657 req->sstate = sstate;
658 req->cstate = cstate;
659 wine_server_call( req );
661 SERVER_END_REQ;
664 static int _is_blocking(SOCKET s)
666 int ret;
667 SERVER_START_REQ( get_socket_event )
669 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
670 req->service = FALSE;
671 req->c_event = 0;
672 wine_server_call( req );
673 ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
675 SERVER_END_REQ;
676 return ret;
679 static unsigned int _get_sock_mask(SOCKET s)
681 unsigned int ret;
682 SERVER_START_REQ( get_socket_event )
684 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
685 req->service = FALSE;
686 req->c_event = 0;
687 wine_server_call( req );
688 ret = reply->mask;
690 SERVER_END_REQ;
691 return ret;
694 static void _sync_sock_state(SOCKET s)
696 /* do a dummy wineserver request in order to let
697 the wineserver run through its select loop once */
698 (void)_is_blocking(s);
701 static int _get_sock_error(SOCKET s, unsigned int bit)
703 int events[FD_MAX_EVENTS];
705 SERVER_START_REQ( get_socket_event )
707 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
708 req->service = FALSE;
709 req->c_event = 0;
710 wine_server_set_reply( req, events, sizeof(events) );
711 wine_server_call( req );
713 SERVER_END_REQ;
714 return events[bit];
717 static struct per_thread_data *get_per_thread_data(void)
719 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
720 /* lazy initialization */
721 if (!ptb)
723 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
724 NtCurrentTeb()->WinSockData = ptb;
726 return ptb;
729 static void free_per_thread_data(void)
731 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
733 if (!ptb) return;
735 /* delete scratch buffers */
736 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
737 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
738 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
739 ptb->he_buffer = NULL;
740 ptb->se_buffer = NULL;
741 ptb->pe_buffer = NULL;
743 HeapFree( GetProcessHeap(), 0, ptb );
744 NtCurrentTeb()->WinSockData = NULL;
747 /***********************************************************************
748 * DllMain (WS2_32.init)
750 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
752 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
753 switch (fdwReason) {
754 case DLL_PROCESS_ATTACH:
755 break;
756 case DLL_PROCESS_DETACH:
757 free_per_thread_data();
758 num_startup = 0;
759 break;
760 case DLL_THREAD_DETACH:
761 free_per_thread_data();
762 break;
764 return TRUE;
767 /***********************************************************************
768 * convert_sockopt()
770 * Converts socket flags from Windows format.
771 * Return 1 if converted, 0 if not (error).
773 static int convert_sockopt(INT *level, INT *optname)
775 unsigned int i;
776 switch (*level)
778 case WS_SOL_SOCKET:
779 *level = SOL_SOCKET;
780 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
781 if( ws_sock_map[i][0] == *optname )
783 *optname = ws_sock_map[i][1];
784 return 1;
787 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
788 break;
789 case WS_IPPROTO_TCP:
790 *level = IPPROTO_TCP;
791 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
792 if ( ws_tcp_map[i][0] == *optname )
794 *optname = ws_tcp_map[i][1];
795 return 1;
798 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
799 break;
800 case WS_IPPROTO_IP:
801 *level = IPPROTO_IP;
802 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
803 if (ws_ip_map[i][0] == *optname )
805 *optname = ws_ip_map[i][1];
806 return 1;
809 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
810 break;
811 case WS_IPPROTO_IPV6:
812 *level = IPPROTO_IPV6;
813 for(i=0; i<sizeof(ws_ipv6_map)/sizeof(ws_ipv6_map[0]); i++) {
814 if (ws_ipv6_map[i][0] == *optname )
816 *optname = ws_ipv6_map[i][1];
817 return 1;
820 FIXME("Unknown IPPROTO_IPV6 optname 0x%x\n", *optname);
821 break;
822 default: FIXME("Unimplemented or unknown socket level\n");
824 return 0;
827 /* ----------------------------------- Per-thread info (or per-process?) */
829 static char *strdup_lower(const char *str)
831 int i;
832 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
834 if (ret)
836 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
837 ret[i] = 0;
839 else SetLastError(WSAENOBUFS);
840 return ret;
843 static inline int sock_error_p(int s)
845 unsigned int optval, optlen;
847 optlen = sizeof(optval);
848 getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
849 if (optval) WARN("\t[%i] error: %d\n", s, optval);
850 return optval != 0;
853 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
854 * from an fd and return the value converted to milli seconds
855 * or -1 if there is an infinite time out */
856 static inline int get_rcvsnd_timeo( int fd, int optname)
858 struct timeval tv;
859 unsigned int len = sizeof(tv);
860 int ret = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
861 if( ret >= 0)
862 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
863 if( ret <= 0 ) /* tv == {0,0} means infinite time out */
864 return -1;
865 return ret;
868 /* macro wrappers for portability */
869 #ifdef SO_RCVTIMEO
870 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
871 #else
872 #define GET_RCVTIMEO(fd) (-1)
873 #endif
875 #ifdef SO_SNDTIMEO
876 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
877 #else
878 #define GET_SNDTIMEO(fd) (-1)
879 #endif
881 /* utility: given an fd, will block until one of the events occurs */
882 static inline int do_block( int fd, int events, int timeout )
884 struct pollfd pfd;
885 int ret;
887 pfd.fd = fd;
888 pfd.events = events;
890 while ((ret = poll(&pfd, 1, timeout)) < 0)
892 if (errno != EINTR)
893 return -1;
895 if( ret == 0 )
896 return 0;
897 return pfd.revents;
900 static int
901 convert_af_w2u(int windowsaf) {
902 unsigned int i;
904 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
905 if (ws_af_map[i][0] == windowsaf)
906 return ws_af_map[i][1];
907 FIXME("unhandled Windows address family %d\n", windowsaf);
908 return -1;
911 static int
912 convert_af_u2w(int unixaf) {
913 unsigned int i;
915 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
916 if (ws_af_map[i][1] == unixaf)
917 return ws_af_map[i][0];
918 FIXME("unhandled UNIX address family %d\n", unixaf);
919 return -1;
922 static int
923 convert_proto_w2u(int windowsproto) {
924 unsigned int i;
926 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
927 if (ws_proto_map[i][0] == windowsproto)
928 return ws_proto_map[i][1];
929 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
930 return -1;
933 static int
934 convert_proto_u2w(int unixproto) {
935 unsigned int i;
937 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
938 if (ws_proto_map[i][1] == unixproto)
939 return ws_proto_map[i][0];
940 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
941 return -1;
944 static int
945 convert_socktype_w2u(int windowssocktype) {
946 unsigned int i;
948 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
949 if (ws_socktype_map[i][0] == windowssocktype)
950 return ws_socktype_map[i][1];
951 FIXME("unhandled Windows socket type %d\n", windowssocktype);
952 return -1;
955 static int
956 convert_socktype_u2w(int unixsocktype) {
957 unsigned int i;
959 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
960 if (ws_socktype_map[i][1] == unixsocktype)
961 return ws_socktype_map[i][0];
962 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
963 return -1;
966 /* ----------------------------------- API -----
968 * Init / cleanup / error checking.
971 /***********************************************************************
972 * WSAStartup (WS2_32.115)
974 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
976 TRACE("verReq=%x\n", wVersionRequested);
978 if (LOBYTE(wVersionRequested) < 1)
979 return WSAVERNOTSUPPORTED;
981 if (!lpWSAData) return WSAEINVAL;
983 num_startup++;
985 /* that's the whole of the negotiation for now */
986 lpWSAData->wVersion = wVersionRequested;
987 /* return winsock information */
988 lpWSAData->wHighVersion = 0x0202;
989 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
990 strcpy(lpWSAData->szSystemStatus, "Running" );
991 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
992 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
993 /* don't do anything with lpWSAData->lpVendorInfo */
994 /* (some apps don't allocate the space for this field) */
996 TRACE("succeeded\n");
997 return 0;
1001 /***********************************************************************
1002 * WSACleanup (WS2_32.116)
1004 INT WINAPI WSACleanup(void)
1006 if (num_startup) {
1007 num_startup--;
1008 return 0;
1010 SetLastError(WSANOTINITIALISED);
1011 return SOCKET_ERROR;
1015 /***********************************************************************
1016 * WSAGetLastError (WS2_32.111)
1018 INT WINAPI WSAGetLastError(void)
1020 return GetLastError();
1023 /***********************************************************************
1024 * WSASetLastError (WS2_32.112)
1026 void WINAPI WSASetLastError(INT iError) {
1027 SetLastError(iError);
1030 static struct WS_hostent *check_buffer_he(int size)
1032 struct per_thread_data * ptb = get_per_thread_data();
1033 if (ptb->he_buffer)
1035 if (ptb->he_len >= size ) return ptb->he_buffer;
1036 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
1038 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
1039 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
1040 return ptb->he_buffer;
1043 static struct WS_servent *check_buffer_se(int size)
1045 struct per_thread_data * ptb = get_per_thread_data();
1046 if (ptb->se_buffer)
1048 if (ptb->se_len >= size ) return ptb->se_buffer;
1049 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
1051 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
1052 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
1053 return ptb->se_buffer;
1056 static struct WS_protoent *check_buffer_pe(int size)
1058 struct per_thread_data * ptb = get_per_thread_data();
1059 if (ptb->pe_buffer)
1061 if (ptb->pe_len >= size ) return ptb->pe_buffer;
1062 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
1064 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
1065 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
1066 return ptb->pe_buffer;
1069 /* ----------------------------------- i/o APIs */
1071 static inline BOOL supported_pf(int pf)
1073 switch (pf)
1075 case WS_AF_INET:
1076 case WS_AF_INET6:
1077 return TRUE;
1078 #ifdef HAVE_IPX
1079 case WS_AF_IPX:
1080 return TRUE;
1081 #endif
1082 #ifdef HAVE_IRDA
1083 case WS_AF_IRDA:
1084 return TRUE;
1085 #endif
1086 default:
1087 return FALSE;
1092 /**********************************************************************/
1094 /* Returns the length of the converted address if successful, 0 if it was too small to
1095 * start with.
1097 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
1098 union generic_unix_sockaddr *uaddr)
1100 unsigned int uaddrlen = 0;
1102 switch (wsaddr->sa_family)
1104 #ifdef HAVE_IPX
1105 case WS_AF_IPX:
1107 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
1108 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
1110 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
1111 return 0;
1113 uaddrlen = sizeof(struct sockaddr_ipx);
1114 memset( uaddr, 0, uaddrlen );
1115 uipx->sipx_family=AF_IPX;
1116 uipx->sipx_port=wsipx->sa_socket;
1117 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1118 * in one go
1120 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
1121 #ifdef IPX_FRAME_NONE
1122 uipx->sipx_type=IPX_FRAME_NONE;
1123 #endif
1124 break;
1126 #endif
1127 case WS_AF_INET6: {
1128 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
1129 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
1131 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1132 * scope_id, one without.
1134 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
1135 uaddrlen = sizeof(struct sockaddr_in6);
1136 memset( uaddr, 0, uaddrlen );
1137 uin6->sin6_family = AF_INET6;
1138 uin6->sin6_port = win6->sin6_port;
1139 uin6->sin6_flowinfo = win6->sin6_flowinfo;
1140 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1141 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
1142 #endif
1143 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
1144 break;
1146 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
1147 return 0;
1149 case WS_AF_INET: {
1150 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
1151 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
1153 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
1154 return 0;
1155 uaddrlen = sizeof(struct sockaddr_in);
1156 memset( uaddr, 0, uaddrlen );
1157 uin->sin_family = AF_INET;
1158 uin->sin_port = win->sin_port;
1159 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
1160 break;
1162 #ifdef HAVE_IRDA
1163 case WS_AF_IRDA: {
1164 struct sockaddr_irda *uin = (struct sockaddr_irda *)uaddr;
1165 const SOCKADDR_IRDA *win = (const SOCKADDR_IRDA *)wsaddr;
1167 if (wsaddrlen < sizeof(SOCKADDR_IRDA))
1168 return 0;
1169 uaddrlen = sizeof(struct sockaddr_irda);
1170 memset( uaddr, 0, uaddrlen );
1171 uin->sir_family = AF_IRDA;
1172 if (!strncmp( win->irdaServiceName, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1174 unsigned int lsap_sel;
1176 sscanf( win->irdaServiceName, "LSAP-SEL%u", &lsap_sel );
1177 uin->sir_lsap_sel = lsap_sel;
1179 else
1181 uin->sir_lsap_sel = LSAP_ANY;
1182 memcpy( uin->sir_name, win->irdaServiceName, 25 );
1184 memcpy( &uin->sir_addr, win->irdaDeviceID, sizeof(uin->sir_addr) );
1185 break;
1187 #endif
1188 case WS_AF_UNSPEC: {
1189 /* Try to determine the needed space by the passed windows sockaddr space */
1190 switch (wsaddrlen) {
1191 default: /* likely a ipv4 address */
1192 case sizeof(struct WS_sockaddr_in):
1193 uaddrlen = sizeof(struct sockaddr_in);
1194 break;
1195 #ifdef HAVE_IPX
1196 case sizeof(struct WS_sockaddr_ipx):
1197 uaddrlen = sizeof(struct sockaddr_ipx);
1198 break;
1199 #endif
1200 #ifdef HAVE_IRDA
1201 case sizeof(SOCKADDR_IRDA):
1202 uaddrlen = sizeof(struct sockaddr_irda);
1203 break;
1204 #endif
1205 case sizeof(struct WS_sockaddr_in6):
1206 case sizeof(struct WS_sockaddr_in6_old):
1207 uaddrlen = sizeof(struct sockaddr_in6);
1208 break;
1210 memset( uaddr, 0, uaddrlen );
1211 break;
1213 default:
1214 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
1215 return 0;
1217 return uaddrlen;
1220 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
1222 switch (uaddr->sa_family)
1224 #ifdef HAVE_IPX
1225 case AF_IPX:
1226 FIXME("don't know how to tell if IPX socket is bound, assuming it is!\n");
1227 return TRUE;
1228 #endif
1229 case AF_INET6:
1231 static const struct sockaddr_in6 emptyAddr;
1232 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
1233 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
1235 case AF_INET:
1237 static const struct sockaddr_in emptyAddr;
1238 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
1239 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
1241 case AF_UNSPEC:
1242 return FALSE;
1243 default:
1244 FIXME("unknown address family %d\n", uaddr->sa_family);
1245 return TRUE;
1249 /* Returns 0 if successful, -1 if the buffer is too small */
1250 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
1252 int res;
1254 switch(uaddr->sa_family)
1256 #ifdef HAVE_IPX
1257 case AF_IPX:
1259 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
1260 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
1262 res=-1;
1263 switch (*wsaddrlen) /* how much can we copy? */
1265 default:
1266 res=0; /* enough */
1267 *wsaddrlen = sizeof(*wsipx);
1268 wsipx->sa_socket=uipx->sipx_port;
1269 /* fall through */
1270 case 13:
1271 case 12:
1272 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
1273 /* fall through */
1274 case 11:
1275 case 10:
1276 case 9:
1277 case 8:
1278 case 7:
1279 case 6:
1280 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1281 /* fall through */
1282 case 5:
1283 case 4:
1284 case 3:
1285 case 2:
1286 wsipx->sa_family=WS_AF_IPX;
1287 /* fall through */
1288 case 1:
1289 case 0:
1290 /* way too small */
1291 break;
1294 break;
1295 #endif
1296 #ifdef HAVE_IRDA
1297 case AF_IRDA: {
1298 const struct sockaddr_irda *uin = (const struct sockaddr_irda *)uaddr;
1299 SOCKADDR_IRDA *win = (SOCKADDR_IRDA *)wsaddr;
1301 if (*wsaddrlen < sizeof(SOCKADDR_IRDA))
1302 return -1;
1303 win->irdaAddressFamily = WS_AF_IRDA;
1304 memcpy( win->irdaDeviceID, &uin->sir_addr, sizeof(win->irdaDeviceID) );
1305 if (uin->sir_lsap_sel != LSAP_ANY)
1306 sprintf( win->irdaServiceName, "LSAP-SEL%u", uin->sir_lsap_sel );
1307 else
1308 memcpy( win->irdaServiceName, uin->sir_name,
1309 sizeof(win->irdaServiceName) );
1310 return 0;
1312 #endif
1313 case AF_INET6: {
1314 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1315 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1317 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1318 return -1;
1319 win6old->sin6_family = WS_AF_INET6;
1320 win6old->sin6_port = uin6->sin6_port;
1321 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1322 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1323 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1324 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1325 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1326 win6->sin6_scope_id = uin6->sin6_scope_id;
1327 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1329 else
1330 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1331 #else
1332 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1333 #endif
1334 return 0;
1336 case AF_INET: {
1337 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1338 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1340 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1341 return -1;
1342 win->sin_family = WS_AF_INET;
1343 win->sin_port = uin->sin_port;
1344 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1345 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1346 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1347 return 0;
1349 case AF_UNSPEC: {
1350 memset(wsaddr,0,*wsaddrlen);
1351 return 0;
1353 default:
1354 FIXME("Unknown address family %d\n", uaddr->sa_family);
1355 return -1;
1357 return res;
1360 /**************************************************************************
1361 * Functions for handling overlapped I/O
1362 **************************************************************************/
1364 /* user APC called upon async completion */
1365 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1367 ws2_async *wsa = arg;
1369 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
1370 iosb->Information, wsa->user_overlapped,
1371 wsa->flags );
1372 HeapFree( GetProcessHeap(), 0, wsa );
1375 /***********************************************************************
1376 * WS2_recv (INTERNAL)
1378 * Workhorse for both synchronous and asynchronous recv() operations.
1380 static int WS2_recv( int fd, struct ws2_async *wsa )
1382 struct msghdr hdr;
1383 union generic_unix_sockaddr unix_sockaddr;
1384 int n;
1386 hdr.msg_name = NULL;
1388 if (wsa->addr)
1390 hdr.msg_namelen = sizeof(unix_sockaddr);
1391 hdr.msg_name = &unix_sockaddr;
1393 else
1394 hdr.msg_namelen = 0;
1396 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1397 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1398 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1399 hdr.msg_accrights = NULL;
1400 hdr.msg_accrightslen = 0;
1401 #else
1402 hdr.msg_control = NULL;
1403 hdr.msg_controllen = 0;
1404 hdr.msg_flags = 0;
1405 #endif
1407 if ( (n = recvmsg(fd, &hdr, wsa->flags)) == -1 )
1408 return -1;
1410 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
1411 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
1413 * quoting linux 2.6 net/ipv4/tcp.c:
1414 * "According to UNIX98, msg_name/msg_namelen are ignored
1415 * on connected socket. I was just happy when found this 8) --ANK"
1417 * likewise MSDN says that lpFrom and lpFromlen are ignored for
1418 * connection-oriented sockets, so don't try to update lpFrom.
1420 if (wsa->addr && hdr.msg_namelen)
1421 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
1423 return n;
1426 /***********************************************************************
1427 * WS2_async_recv (INTERNAL)
1429 * Handler for overlapped recv() operations.
1431 static NTSTATUS WS2_async_recv( void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1433 ws2_async* wsa = user;
1434 int result = 0, fd;
1436 switch (status)
1438 case STATUS_ALERTED:
1439 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
1440 break;
1442 result = WS2_recv( fd, wsa );
1443 wine_server_release_fd( wsa->hSocket, fd );
1444 if (result >= 0)
1446 status = STATUS_SUCCESS;
1447 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1449 else
1451 if (errno == EINTR || errno == EAGAIN)
1453 status = STATUS_PENDING;
1454 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1456 else
1458 result = 0;
1459 status = wsaErrStatus();
1462 break;
1464 if (status != STATUS_PENDING)
1466 iosb->u.Status = status;
1467 iosb->Information = result;
1468 *apc = ws2_async_apc;
1470 return status;
1473 /***********************************************************************
1474 * WS2_send (INTERNAL)
1476 * Workhorse for both synchronous and asynchronous send() operations.
1478 static int WS2_send( int fd, struct ws2_async *wsa )
1480 struct msghdr hdr;
1481 union generic_unix_sockaddr unix_addr;
1483 hdr.msg_name = NULL;
1484 hdr.msg_namelen = 0;
1486 if (wsa->addr)
1488 hdr.msg_name = &unix_addr;
1489 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
1490 if ( !hdr.msg_namelen )
1492 errno = EFAULT;
1493 return -1;
1496 #if defined(HAVE_IPX) && defined(SOL_IPX)
1497 if(wsa->addr->sa_family == WS_AF_IPX)
1499 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
1500 int val=0;
1501 unsigned int len=sizeof(int);
1503 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
1504 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
1505 * the packet type and then we can retrieve it using getsockopt. After that we can set the
1506 * ipx type in the sockaddr_opx structure with the stored value.
1508 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
1509 uipx->sipx_type = val;
1511 #endif
1514 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1515 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1516 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1517 hdr.msg_accrights = NULL;
1518 hdr.msg_accrightslen = 0;
1519 #else
1520 hdr.msg_control = NULL;
1521 hdr.msg_controllen = 0;
1522 hdr.msg_flags = 0;
1523 #endif
1525 return sendmsg(fd, &hdr, wsa->flags);
1528 /***********************************************************************
1529 * WS2_async_send (INTERNAL)
1531 * Handler for overlapped send() operations.
1533 static NTSTATUS WS2_async_send(void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1535 ws2_async* wsa = user;
1536 int result = 0, fd;
1538 switch (status)
1540 case STATUS_ALERTED:
1541 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
1542 break;
1544 /* check to see if the data is ready (non-blocking) */
1545 result = WS2_send( fd, wsa );
1546 wine_server_release_fd( wsa->hSocket, fd );
1548 if (result >= 0)
1550 int totalLength = 0;
1551 unsigned int i;
1552 status = STATUS_SUCCESS;
1553 for (i = 0; i < wsa->n_iovecs; i++)
1554 totalLength += wsa->iovec[i].iov_len;
1555 if (result < totalLength)
1556 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1558 else
1560 if (errno == EINTR || errno == EAGAIN)
1562 status = STATUS_PENDING;
1563 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1565 else
1567 status = wsaErrStatus();
1568 result = 0;
1571 break;
1573 if (status != STATUS_PENDING)
1575 iosb->u.Status = status;
1576 iosb->Information = result;
1577 *apc = ws2_async_apc;
1579 return status;
1582 /***********************************************************************
1583 * WS2_async_shutdown (INTERNAL)
1585 * Handler for shutdown() operations on overlapped sockets.
1587 static NTSTATUS WS2_async_shutdown( void* user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc )
1589 ws2_async* wsa = user;
1590 int fd, err = 1;
1592 switch (status)
1594 case STATUS_ALERTED:
1595 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
1596 break;
1598 switch ( wsa->type )
1600 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
1601 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
1603 status = err ? wsaErrStatus() : STATUS_SUCCESS;
1604 wine_server_release_fd( wsa->hSocket, fd );
1605 break;
1607 iosb->u.Status = status;
1608 iosb->Information = 0;
1609 *apc = ws2_async_apc;
1610 return status;
1613 /***********************************************************************
1614 * WS2_register_async_shutdown (INTERNAL)
1616 * Helper function for WS_shutdown() on overlapped sockets.
1618 static int WS2_register_async_shutdown( SOCKET s, int type )
1620 struct ws2_async *wsa;
1621 NTSTATUS status;
1623 TRACE("s %ld type %d\n", s, type);
1625 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
1626 if ( !wsa )
1627 return WSAEFAULT;
1629 wsa->hSocket = SOCKET2HANDLE(s);
1630 wsa->type = type;
1631 wsa->completion_func = NULL;
1633 SERVER_START_REQ( register_async )
1635 req->type = type;
1636 req->async.handle = wine_server_obj_handle( wsa->hSocket );
1637 req->async.callback = wine_server_client_ptr( WS2_async_shutdown );
1638 req->async.iosb = wine_server_client_ptr( &wsa->local_iosb );
1639 req->async.arg = wine_server_client_ptr( wsa );
1640 req->async.cvalue = 0;
1641 status = wine_server_call( req );
1643 SERVER_END_REQ;
1645 if (status != STATUS_PENDING)
1647 HeapFree( GetProcessHeap(), 0, wsa );
1648 return NtStatusToWSAError( status );
1650 return 0;
1653 /***********************************************************************
1654 * accept (WS2_32.1)
1656 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr,
1657 int *addrlen32)
1659 NTSTATUS status;
1660 SOCKET as;
1661 BOOL is_blocking;
1663 TRACE("socket %04lx\n", s );
1664 is_blocking = _is_blocking(s);
1666 do {
1667 /* try accepting first (if there is a deferred connection) */
1668 SERVER_START_REQ( accept_socket )
1670 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1671 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
1672 req->attributes = OBJ_INHERIT;
1673 status = wine_server_call( req );
1674 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
1676 SERVER_END_REQ;
1677 if (!status)
1679 if (addr) WS_getpeername(as, addr, addrlen32);
1680 return as;
1682 if (is_blocking && status == STATUS_CANT_WAIT)
1684 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1685 /* block here */
1686 do_block(fd, POLLIN, -1);
1687 _sync_sock_state(s); /* let wineserver notice connection */
1688 release_sock_fd( s, fd );
1690 } while (is_blocking && status == STATUS_CANT_WAIT);
1692 set_error(status);
1693 return INVALID_SOCKET;
1696 /***********************************************************************
1697 * bind (WS2_32.2)
1699 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
1701 int fd = get_sock_fd( s, 0, NULL );
1702 int res = SOCKET_ERROR;
1704 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1706 if (fd != -1)
1708 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
1710 SetLastError(WSAEAFNOSUPPORT);
1712 else
1714 union generic_unix_sockaddr uaddr;
1715 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1716 if (!uaddrlen)
1718 SetLastError(WSAEFAULT);
1720 else
1722 #ifdef IPV6_V6ONLY
1723 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
1724 if (name->sa_family == WS_AF_INET6 &&
1725 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
1727 int enable = 1;
1728 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
1730 release_sock_fd( s, fd );
1731 SetLastError(WSAEAFNOSUPPORT);
1732 return SOCKET_ERROR;
1735 #endif
1736 if (name->sa_family == WS_AF_INET)
1738 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
1739 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
1741 /* Trying to bind to the default host interface, using
1742 * INADDR_ANY instead*/
1743 WARN("Trying to bind to magic IP address, using "
1744 "INADDR_ANY instead.\n");
1745 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
1748 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
1750 int loc_errno = errno;
1751 WARN("\tfailure - errno = %i\n", errno);
1752 errno = loc_errno;
1753 switch (errno)
1755 case EBADF:
1756 SetLastError(WSAENOTSOCK);
1757 break;
1758 case EADDRNOTAVAIL:
1759 SetLastError(WSAEINVAL);
1760 break;
1761 default:
1762 SetLastError(wsaErrno());
1763 break;
1766 else
1768 res=0; /* success */
1772 release_sock_fd( s, fd );
1774 return res;
1777 /***********************************************************************
1778 * closesocket (WS2_32.3)
1780 int WINAPI WS_closesocket(SOCKET s)
1782 TRACE("socket %04lx\n", s);
1783 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
1784 return SOCKET_ERROR;
1787 /***********************************************************************
1788 * connect (WS2_32.4)
1790 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
1792 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1794 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1796 if (fd != -1)
1798 union generic_unix_sockaddr uaddr;
1799 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1801 if (!uaddrlen)
1803 SetLastError(WSAEFAULT);
1805 else
1807 if (name->sa_family == WS_AF_INET)
1809 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
1810 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
1812 /* Trying to connect to magic replace-loopback address,
1813 * assuming we really want to connect to localhost */
1814 TRACE("Trying to connect to magic IP address, using "
1815 "INADDR_LOOPBACK instead.\n");
1816 in4->sin_addr.s_addr = htonl(WS_INADDR_LOOPBACK);
1820 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
1821 goto connect_success;
1824 if (errno == EINPROGRESS)
1826 /* tell wineserver that a connection is in progress */
1827 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1828 FD_CONNECT|FD_READ|FD_WRITE,
1829 FD_WINE_CONNECTED|FD_WINE_LISTENING);
1830 if (_is_blocking(s))
1832 int result;
1833 /* block here */
1834 do_block(fd, POLLIN | POLLOUT, -1);
1835 _sync_sock_state(s); /* let wineserver notice connection */
1836 /* retrieve any error codes from it */
1837 result = _get_sock_error(s, FD_CONNECT_BIT);
1838 if (result)
1839 SetLastError(NtStatusToWSAError(result));
1840 else
1842 goto connect_success;
1845 else
1847 SetLastError(WSAEWOULDBLOCK);
1850 else
1852 SetLastError(wsaErrno());
1854 release_sock_fd( s, fd );
1856 return SOCKET_ERROR;
1858 connect_success:
1859 release_sock_fd( s, fd );
1860 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1861 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
1862 FD_CONNECT|FD_WINE_LISTENING);
1863 return 0;
1866 /***********************************************************************
1867 * WSAConnect (WS2_32.30)
1869 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
1870 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
1871 LPQOS lpSQOS, LPQOS lpGQOS )
1873 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
1874 FIXME("unsupported parameters!\n");
1875 return WS_connect( s, name, namelen );
1879 /***********************************************************************
1880 * getpeername (WS2_32.5)
1882 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
1884 int fd;
1885 int res;
1887 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, namelen?*namelen:0);
1889 fd = get_sock_fd( s, 0, NULL );
1890 res = SOCKET_ERROR;
1892 if (fd != -1)
1894 union generic_unix_sockaddr uaddr;
1895 unsigned int uaddrlen = sizeof(uaddr);
1897 if (getpeername(fd, &uaddr.addr, &uaddrlen) == 0)
1899 if (!name || !namelen)
1900 SetLastError(WSAEFAULT);
1901 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
1902 /* The buffer was too small */
1903 SetLastError(WSAEFAULT);
1904 else
1905 res = 0;
1907 else
1908 SetLastError(wsaErrno());
1909 release_sock_fd( s, fd );
1911 return res;
1914 /***********************************************************************
1915 * getsockname (WS2_32.6)
1917 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
1919 int fd;
1920 int res;
1922 TRACE("socket: %04lx, ptr %p, len %8x\n", s, name, *namelen);
1924 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1925 if( (name == NULL) || (namelen == NULL) )
1927 SetLastError( WSAEFAULT );
1928 return SOCKET_ERROR;
1931 fd = get_sock_fd( s, 0, NULL );
1932 res = SOCKET_ERROR;
1934 if (fd != -1)
1936 union generic_unix_sockaddr uaddr;
1937 unsigned int uaddrlen = sizeof(uaddr);
1939 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
1941 SetLastError(wsaErrno());
1943 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
1945 SetLastError(WSAEINVAL);
1947 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
1949 /* The buffer was too small */
1950 SetLastError(WSAEFAULT);
1952 else
1954 res=0;
1956 release_sock_fd( s, fd );
1958 return res;
1961 /***********************************************************************
1962 * getsockopt (WS2_32.7)
1964 INT WINAPI WS_getsockopt(SOCKET s, INT level,
1965 INT optname, char *optval, INT *optlen)
1967 int fd;
1968 INT ret = 0;
1970 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
1971 s, level, optname, optval, *optlen);
1973 switch(level)
1975 case WS_SOL_SOCKET:
1977 switch(optname)
1979 /* Handle common cases. The special cases are below, sorted
1980 * alphabetically */
1981 case WS_SO_ACCEPTCONN:
1982 case WS_SO_BROADCAST:
1983 case WS_SO_DEBUG:
1984 case WS_SO_ERROR:
1985 case WS_SO_KEEPALIVE:
1986 case WS_SO_OOBINLINE:
1987 case WS_SO_RCVBUF:
1988 case WS_SO_REUSEADDR:
1989 case WS_SO_SNDBUF:
1990 case WS_SO_TYPE:
1991 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1992 return SOCKET_ERROR;
1993 convert_sockopt(&level, &optname);
1994 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
1996 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1997 ret = SOCKET_ERROR;
1999 release_sock_fd( s, fd );
2000 return ret;
2002 case WS_SO_DONTLINGER:
2004 struct linger lingval;
2005 unsigned int len = sizeof(struct linger);
2007 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
2009 SetLastError(WSAEFAULT);
2010 return SOCKET_ERROR;
2012 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2013 return SOCKET_ERROR;
2015 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
2017 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2018 ret = SOCKET_ERROR;
2020 else
2022 *(BOOL *)optval = (lingval.l_onoff) ? FALSE : TRUE;
2023 *optlen = sizeof(BOOL);
2026 release_sock_fd( s, fd );
2027 return ret;
2030 /* As mentioned in setsockopt, Windows ignores this, so we
2031 * always return true here */
2032 case WS_SO_DONTROUTE:
2033 if (!optlen || *optlen < sizeof(BOOL) || !optval)
2035 SetLastError(WSAEFAULT);
2036 return SOCKET_ERROR;
2038 *(BOOL *)optval = TRUE;
2039 *optlen = sizeof(BOOL);
2040 return 0;
2042 case WS_SO_LINGER:
2044 struct linger lingval;
2045 unsigned int len = sizeof(struct linger);
2047 /* struct linger and LINGER have different sizes */
2048 if (!optlen || *optlen < sizeof(LINGER) || !optval)
2050 SetLastError(WSAEFAULT);
2051 return SOCKET_ERROR;
2053 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2054 return SOCKET_ERROR;
2056 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
2058 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2059 ret = SOCKET_ERROR;
2061 else
2063 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
2064 ((LINGER *)optval)->l_linger = lingval.l_linger;
2065 *optlen = sizeof(struct linger);
2068 release_sock_fd( s, fd );
2069 return ret;
2072 case WS_SO_MAX_MSG_SIZE:
2073 if (!optlen || *optlen < sizeof(int) || !optval)
2075 SetLastError(WSAEFAULT);
2076 return SOCKET_ERROR;
2078 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
2079 *(int *)optval = 65507;
2080 *optlen = sizeof(int);
2081 return 0;
2083 /* SO_OPENTYPE does not require a valid socket handle. */
2084 case WS_SO_OPENTYPE:
2085 if (!optlen || *optlen < sizeof(int) || !optval)
2087 SetLastError(WSAEFAULT);
2088 return SOCKET_ERROR;
2090 *(int *)optval = get_per_thread_data()->opentype;
2091 *optlen = sizeof(int);
2092 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
2093 return 0;
2095 #ifdef SO_RCVTIMEO
2096 case WS_SO_RCVTIMEO:
2097 #endif
2098 #ifdef SO_SNDTIMEO
2099 case WS_SO_SNDTIMEO:
2100 #endif
2101 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
2103 struct timeval tv;
2104 unsigned int len = sizeof(struct timeval);
2106 if (!optlen || *optlen < sizeof(int)|| !optval)
2108 SetLastError(WSAEFAULT);
2109 return SOCKET_ERROR;
2111 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2112 return SOCKET_ERROR;
2114 convert_sockopt(&level, &optname);
2115 if (getsockopt(fd, level, optname, &tv, &len) != 0 )
2117 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2118 ret = SOCKET_ERROR;
2120 else
2122 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
2123 *optlen = sizeof(int);
2126 release_sock_fd( s, fd );
2127 return ret;
2129 #endif
2130 default:
2131 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
2132 SetLastError(WSAENOPROTOOPT);
2133 return SOCKET_ERROR;
2134 } /* end switch(optname) */
2135 }/* end case WS_SOL_SOCKET */
2136 #ifdef HAVE_IPX
2137 case NSPROTO_IPX:
2139 struct WS_sockaddr_ipx addr;
2140 IPX_ADDRESS_DATA *data;
2141 int namelen;
2142 switch(optname)
2144 case IPX_PTYPE:
2145 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
2146 #ifdef SOL_IPX
2147 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (unsigned int*)optlen) == -1)
2149 ret = SOCKET_ERROR;
2151 #else
2153 struct ipx val;
2154 socklen_t len=sizeof(struct ipx);
2155 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
2156 ret = SOCKET_ERROR;
2157 else
2158 *optval = (int)val.ipx_pt;
2160 #endif
2161 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
2162 release_sock_fd( s, fd );
2163 return ret;
2165 case IPX_ADDRESS:
2167 * On a Win2000 system with one network card there are usually
2168 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
2169 * Using this call you can then retrieve info about this all.
2170 * In case of Linux it is a bit different. Usually you have
2171 * only "one" device active and further it is not possible to
2172 * query things like the linkspeed.
2174 FIXME("IPX_ADDRESS\n");
2175 namelen = sizeof(struct WS_sockaddr_ipx);
2176 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
2177 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
2179 data = (IPX_ADDRESS_DATA*)optval;
2180 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
2181 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
2182 data->adapternum = 0;
2183 data->wan = FALSE; /* We are not on a wan for now .. */
2184 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
2185 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
2186 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
2187 * note 1MB = 1000kB in this case */
2188 return 0;
2190 case IPX_MAX_ADAPTER_NUM:
2191 FIXME("IPX_MAX_ADAPTER_NUM\n");
2192 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
2193 return 0;
2195 default:
2196 FIXME("IPX optname:%x\n", optname);
2197 return SOCKET_ERROR;
2198 }/* end switch(optname) */
2199 } /* end case NSPROTO_IPX */
2200 #endif
2202 #ifdef HAVE_IRDA
2203 case WS_SOL_IRLMP:
2204 switch(optname)
2206 case WS_IRLMP_ENUMDEVICES:
2208 static const int MAX_IRDA_DEVICES = 10;
2209 char buf[sizeof(struct irda_device_list) +
2210 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
2211 int fd, res;
2212 socklen_t len = sizeof(buf);
2214 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2215 return SOCKET_ERROR;
2216 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
2217 if (res < 0)
2219 SetLastError(wsaErrno());
2220 return SOCKET_ERROR;
2222 else
2224 struct irda_device_list *src = (struct irda_device_list *)buf;
2225 DEVICELIST *dst = (DEVICELIST *)optval;
2226 INT needed = sizeof(DEVICELIST), i;
2228 if (src->len > 0)
2229 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
2230 if (*optlen < needed)
2232 SetLastError(WSAEFAULT);
2233 return SOCKET_ERROR;
2235 *optlen = needed;
2236 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
2237 dst->numDevice = src->len;
2238 for (i = 0; i < src->len; i++)
2240 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
2241 src->dev[i].saddr, src->dev[i].daddr,
2242 src->dev[i].info, src->dev[i].hints[0],
2243 src->dev[i].hints[1]);
2244 memcpy( dst->Device[i].irdaDeviceID,
2245 &src->dev[i].daddr,
2246 sizeof(dst->Device[i].irdaDeviceID) ) ;
2247 memcpy( dst->Device[i].irdaDeviceName,
2248 &src->dev[i].info,
2249 sizeof(dst->Device[i].irdaDeviceName) ) ;
2250 memcpy( &dst->Device[i].irdaDeviceHints1,
2251 &src->dev[i].hints[0],
2252 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
2253 memcpy( &dst->Device[i].irdaDeviceHints2,
2254 &src->dev[i].hints[1],
2255 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
2256 dst->Device[i].irdaCharSet = src->dev[i].charset;
2258 return 0;
2261 default:
2262 FIXME("IrDA optname:0x%x\n", optname);
2263 return SOCKET_ERROR;
2265 break; /* case WS_SOL_IRLMP */
2266 #endif
2268 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
2269 case WS_IPPROTO_TCP:
2270 switch(optname)
2272 case WS_TCP_NODELAY:
2273 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2274 return SOCKET_ERROR;
2275 convert_sockopt(&level, &optname);
2276 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2278 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2279 ret = SOCKET_ERROR;
2281 release_sock_fd( s, fd );
2282 return ret;
2284 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
2285 return SOCKET_ERROR;
2287 case WS_IPPROTO_IP:
2288 switch(optname)
2290 case WS_IP_ADD_MEMBERSHIP:
2291 case WS_IP_DROP_MEMBERSHIP:
2292 #ifdef IP_HDRINCL
2293 case WS_IP_HDRINCL:
2294 #endif
2295 case WS_IP_MULTICAST_IF:
2296 case WS_IP_MULTICAST_LOOP:
2297 case WS_IP_MULTICAST_TTL:
2298 case WS_IP_OPTIONS:
2299 case WS_IP_TOS:
2300 case WS_IP_TTL:
2301 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2302 return SOCKET_ERROR;
2303 convert_sockopt(&level, &optname);
2304 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2306 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2307 ret = SOCKET_ERROR;
2309 release_sock_fd( s, fd );
2310 return ret;
2311 case WS_IP_DONTFRAGMENT:
2312 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
2313 *(BOOL*)optval = FALSE;
2314 return 0;
2316 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
2317 return SOCKET_ERROR;
2319 case WS_IPPROTO_IPV6:
2320 switch(optname)
2322 #ifdef IPV6_ADD_MEMBERSHIP
2323 case WS_IPV6_ADD_MEMBERSHIP:
2324 #endif
2325 #ifdef IPV6_DROP_MEMBERSHIP
2326 case WS_IPV6_DROP_MEMBERSHIP:
2327 #endif
2328 case WS_IPV6_MULTICAST_IF:
2329 case WS_IPV6_MULTICAST_HOPS:
2330 case WS_IPV6_MULTICAST_LOOP:
2331 case WS_IPV6_UNICAST_HOPS:
2332 case WS_IPV6_V6ONLY:
2333 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2334 return SOCKET_ERROR;
2335 convert_sockopt(&level, &optname);
2336 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2338 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2339 ret = SOCKET_ERROR;
2341 release_sock_fd( s, fd );
2342 return ret;
2343 case WS_IPV6_DONTFRAG:
2344 FIXME("WS_IPV6_DONTFRAG is always false!\n");
2345 *(BOOL*)optval = FALSE;
2346 return 0;
2348 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
2349 return SOCKET_ERROR;
2351 default:
2352 WARN("Unknown level: 0x%08x\n", level);
2353 SetLastError(WSAEINVAL);
2354 return SOCKET_ERROR;
2355 } /* end switch(level) */
2358 /***********************************************************************
2359 * htonl (WS2_32.8)
2361 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
2363 return htonl(hostlong);
2367 /***********************************************************************
2368 * htons (WS2_32.9)
2370 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
2372 return htons(hostshort);
2375 /***********************************************************************
2376 * WSAHtonl (WS2_32.46)
2377 * From MSDN description of error codes, this function should also
2378 * check if WinSock has been initialized and the socket is a valid
2379 * socket. But why? This function only translates a host byte order
2380 * u_long into a network byte order u_long...
2382 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
2384 if (lpnetlong)
2386 *lpnetlong = htonl(hostlong);
2387 return 0;
2389 WSASetLastError(WSAEFAULT);
2390 return SOCKET_ERROR;
2393 /***********************************************************************
2394 * WSAHtons (WS2_32.47)
2395 * From MSDN description of error codes, this function should also
2396 * check if WinSock has been initialized and the socket is a valid
2397 * socket. But why? This function only translates a host byte order
2398 * u_short into a network byte order u_short...
2400 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
2403 if (lpnetshort)
2405 *lpnetshort = htons(hostshort);
2406 return 0;
2408 WSASetLastError(WSAEFAULT);
2409 return SOCKET_ERROR;
2413 /***********************************************************************
2414 * inet_addr (WS2_32.11)
2416 WS_u_long WINAPI WS_inet_addr(const char *cp)
2418 if (!cp) return INADDR_NONE;
2419 return inet_addr(cp);
2423 /***********************************************************************
2424 * ntohl (WS2_32.14)
2426 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
2428 return ntohl(netlong);
2432 /***********************************************************************
2433 * ntohs (WS2_32.15)
2435 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
2437 return ntohs(netshort);
2441 /***********************************************************************
2442 * inet_ntoa (WS2_32.12)
2444 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
2446 /* use "buffer for dummies" here because some applications have a
2447 * propensity to decode addresses in ws_hostent structure without
2448 * saving them first...
2450 static char dbuffer[16]; /* Yes, 16: 4*3 digits + 3 '.' + 1 '\0' */
2452 char* s = inet_ntoa(*((struct in_addr*)&in));
2453 if( s )
2455 strcpy(dbuffer, s);
2456 return dbuffer;
2458 SetLastError(wsaErrno());
2459 return NULL;
2462 /**********************************************************************
2463 * WSAIoctl (WS2_32.50)
2466 INT WINAPI WSAIoctl(SOCKET s,
2467 DWORD dwIoControlCode,
2468 LPVOID lpvInBuffer,
2469 DWORD cbInBuffer,
2470 LPVOID lpbOutBuffer,
2471 DWORD cbOutBuffer,
2472 LPDWORD lpcbBytesReturned,
2473 LPWSAOVERLAPPED lpOverlapped,
2474 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
2476 TRACE("%ld, 0x%08x, %p, %d, %p, %d, %p, %p, %p\n",
2477 s, dwIoControlCode, lpvInBuffer, cbInBuffer, lpbOutBuffer,
2478 cbOutBuffer, lpcbBytesReturned, lpOverlapped, lpCompletionRoutine);
2480 switch( dwIoControlCode )
2482 case WS_FIONBIO:
2483 if (cbInBuffer != sizeof(WS_u_long)) {
2484 WSASetLastError(WSAEFAULT);
2485 return SOCKET_ERROR;
2487 return WS_ioctlsocket( s, WS_FIONBIO, lpvInBuffer);
2489 case WS_FIONREAD:
2490 if (cbOutBuffer != sizeof(WS_u_long)) {
2491 WSASetLastError(WSAEFAULT);
2492 return SOCKET_ERROR;
2494 return WS_ioctlsocket( s, WS_FIONREAD, lpbOutBuffer);
2496 case WS_SIO_GET_INTERFACE_LIST:
2498 INTERFACE_INFO* intArray = (INTERFACE_INFO*)lpbOutBuffer;
2499 DWORD size, numInt, apiReturn;
2500 int fd;
2502 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
2504 if (!lpbOutBuffer)
2506 WSASetLastError(WSAEFAULT);
2507 return SOCKET_ERROR;
2509 if (!lpcbBytesReturned)
2511 WSASetLastError(WSAEFAULT);
2512 return SOCKET_ERROR;
2515 fd = get_sock_fd( s, 0, NULL );
2516 if (fd == -1) return SOCKET_ERROR;
2518 apiReturn = GetAdaptersInfo(NULL, &size);
2519 if (apiReturn == ERROR_NO_DATA)
2521 numInt = 0;
2523 else if (apiReturn == ERROR_BUFFER_OVERFLOW)
2525 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
2527 if (table)
2529 if (GetAdaptersInfo(table, &size) == NO_ERROR)
2531 PIP_ADAPTER_INFO ptr;
2533 if (size*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > cbOutBuffer)
2535 WARN("Buffer too small = %u, cbOutBuffer = %u\n", size, cbOutBuffer);
2536 HeapFree(GetProcessHeap(),0,table);
2537 release_sock_fd( s, fd );
2538 WSASetLastError(WSAEFAULT);
2539 return SOCKET_ERROR;
2541 for (ptr = table, numInt = 0; ptr;
2542 ptr = ptr->Next, intArray++, numInt++)
2544 unsigned int addr, mask, bcast;
2545 struct ifreq ifInfo;
2547 /* Socket Status Flags */
2548 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
2549 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
2551 ERR("Error obtaining status flags for socket!\n");
2552 HeapFree(GetProcessHeap(),0,table);
2553 release_sock_fd( s, fd );
2554 WSASetLastError(WSAEINVAL);
2555 return SOCKET_ERROR;
2557 else
2559 /* set flags; the values of IFF_* are not the same
2560 under Linux and Windows, therefore must generate
2561 new flags */
2562 intArray->iiFlags = 0;
2563 if (ifInfo.ifr_flags & IFF_BROADCAST)
2564 intArray->iiFlags |= WS_IFF_BROADCAST;
2565 #ifdef IFF_POINTOPOINT
2566 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
2567 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
2568 #endif
2569 if (ifInfo.ifr_flags & IFF_LOOPBACK)
2570 intArray->iiFlags |= WS_IFF_LOOPBACK;
2571 if (ifInfo.ifr_flags & IFF_UP)
2572 intArray->iiFlags |= WS_IFF_UP;
2573 if (ifInfo.ifr_flags & IFF_MULTICAST)
2574 intArray->iiFlags |= WS_IFF_MULTICAST;
2577 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
2578 mask = inet_addr(ptr->IpAddressList.IpMask.String);
2579 bcast = addr | ~mask;
2580 intArray->iiAddress.AddressIn.sin_family = AF_INET;
2581 intArray->iiAddress.AddressIn.sin_port = 0;
2582 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
2583 addr;
2584 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
2585 intArray->iiNetmask.AddressIn.sin_port = 0;
2586 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
2587 mask;
2588 intArray->iiBroadcastAddress.AddressIn.sin_family =
2589 AF_INET;
2590 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
2591 intArray->iiBroadcastAddress.AddressIn.sin_addr.
2592 WS_s_addr = bcast;
2595 else
2597 ERR("Unable to get interface table!\n");
2598 release_sock_fd( s, fd );
2599 HeapFree(GetProcessHeap(),0,table);
2600 WSASetLastError(WSAEINVAL);
2601 return SOCKET_ERROR;
2603 HeapFree(GetProcessHeap(),0,table);
2605 else
2607 release_sock_fd( s, fd );
2608 WSASetLastError(WSAEINVAL);
2609 return SOCKET_ERROR;
2612 else
2614 ERR("Unable to get interface table!\n");
2615 release_sock_fd( s, fd );
2616 WSASetLastError(WSAEINVAL);
2617 return SOCKET_ERROR;
2619 /* Calculate the size of the array being returned */
2620 *lpcbBytesReturned = sizeof(INTERFACE_INFO) * numInt;
2621 release_sock_fd( s, fd );
2622 break;
2625 case WS_SIO_ADDRESS_LIST_CHANGE:
2626 FIXME("-> SIO_ADDRESS_LIST_CHANGE request: stub\n");
2627 /* FIXME: error and return code depend on whether socket was created
2628 * with WSA_FLAG_OVERLAPPED, but there is no easy way to get this */
2629 break;
2631 case WS_SIO_ADDRESS_LIST_QUERY:
2633 DWORD size;
2635 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
2637 if (!lpcbBytesReturned)
2639 WSASetLastError(WSAEFAULT);
2640 return SOCKET_ERROR;
2643 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
2645 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
2646 DWORD need, num;
2648 if (!table || GetAdaptersInfo(table, &size))
2650 HeapFree(GetProcessHeap(), 0, table);
2651 WSASetLastError(WSAEINVAL);
2652 return SOCKET_ERROR;
2655 for (p = table, num = 0; p; p = p->Next)
2656 if (p->IpAddressList.IpAddress.String[0]) num++;
2658 need = sizeof(SOCKET_ADDRESS_LIST) + sizeof(SOCKET_ADDRESS) * (num - 1);
2659 need += sizeof(SOCKADDR) * num;
2660 *lpcbBytesReturned = need;
2662 if (need > cbOutBuffer)
2664 HeapFree(GetProcessHeap(), 0, table);
2665 WSASetLastError(WSAEFAULT);
2666 return SOCKET_ERROR;
2669 if (lpbOutBuffer)
2671 unsigned int i;
2672 SOCKET_ADDRESS *sa;
2673 SOCKET_ADDRESS_LIST *sa_list = (SOCKET_ADDRESS_LIST *)lpbOutBuffer;
2674 SOCKADDR_IN *sockaddr;
2676 sa = sa_list->Address;
2677 sockaddr = (SOCKADDR_IN *)((char *)sa + num * sizeof(SOCKET_ADDRESS));
2678 sa_list->iAddressCount = num;
2680 for (p = table, i = 0; p; p = p->Next)
2682 if (!p->IpAddressList.IpAddress.String[0]) continue;
2684 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
2685 sa[i].iSockaddrLength = sizeof(SOCKADDR);
2687 sockaddr[i].sin_family = AF_INET;
2688 sockaddr[i].sin_port = 0;
2689 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
2690 i++;
2694 HeapFree(GetProcessHeap(), 0, table);
2695 return 0;
2697 else
2699 WARN("unable to get IP address list\n");
2700 WSASetLastError(WSAEINVAL);
2701 return SOCKET_ERROR;
2704 case WS_SIO_FLUSH:
2705 FIXME("SIO_FLUSH: stub.\n");
2706 break;
2708 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
2709 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(lpvInBuffer));
2710 WSASetLastError(WSAEOPNOTSUPP);
2711 return SOCKET_ERROR;
2713 case WS_SIO_KEEPALIVE_VALS:
2715 int fd;
2716 struct tcp_keepalive *k = lpvInBuffer;
2717 int keepalive = k->onoff ? 1 : 0;
2718 int keepidle = k->keepalivetime / 1000;
2719 int keepintvl = k->keepaliveinterval / 1000;
2721 if (!lpvInBuffer)
2723 WSASetLastError(WSAEINVAL);
2724 return SOCKET_ERROR;
2727 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
2729 fd = get_sock_fd(s, 0, NULL);
2730 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
2732 release_sock_fd(s, fd);
2733 WSASetLastError(WSAEINVAL);
2734 return SOCKET_ERROR;
2736 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
2737 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
2739 release_sock_fd(s, fd);
2740 WSASetLastError(WSAEINVAL);
2741 return SOCKET_ERROR;
2743 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
2745 release_sock_fd(s, fd);
2746 WSASetLastError(WSAEINVAL);
2747 return SOCKET_ERROR;
2749 #else
2750 FIXME("ignoring keepalive interval and timeout\n");
2751 #endif
2753 release_sock_fd(s, fd);
2754 break;
2756 default:
2757 FIXME("unsupported WS_IOCTL cmd (%08x)\n", dwIoControlCode);
2758 WSASetLastError(WSAEOPNOTSUPP);
2759 return SOCKET_ERROR;
2762 return 0;
2766 /***********************************************************************
2767 * ioctlsocket (WS2_32.10)
2769 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
2771 int fd;
2772 LONG newcmd = cmd;
2774 TRACE("socket %04lx, cmd %08x, ptr %p\n", s, cmd, argp);
2775 /* broken apps like defcon pass the argp value directly instead of a pointer to it */
2776 if(IS_INTRESOURCE(argp))
2778 SetLastError(WSAEFAULT);
2779 return SOCKET_ERROR;
2782 switch( cmd )
2784 case WS_FIONREAD:
2785 newcmd=FIONREAD;
2786 break;
2788 case WS_FIONBIO:
2789 if( _get_sock_mask(s) )
2791 /* AsyncSelect()'ed sockets are always nonblocking */
2792 if (*argp) return 0;
2793 SetLastError(WSAEINVAL);
2794 return SOCKET_ERROR;
2796 if (*argp)
2797 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
2798 else
2799 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
2800 return 0;
2802 case WS_SIOCATMARK:
2803 newcmd=SIOCATMARK;
2804 break;
2806 case WS_FIOASYNC:
2807 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
2808 SetLastError(WSAEINVAL);
2809 return SOCKET_ERROR;
2811 case SIOCGIFBRDADDR:
2812 case SIOCGIFNETMASK:
2813 case SIOCGIFADDR:
2814 /* These don't need any special handling. They are used by
2815 WsControl, and are here to suppress an unnecessary warning. */
2816 break;
2818 default:
2819 /* Netscape tries hard to use bogus ioctl 0x667e */
2820 /* FIXME: 0x667e above is ('f' << 8) | 126, and is a low word of
2821 * FIONBIO (_IOW('f', 126, u_long)), how that should be handled?
2823 WARN("\tunknown WS_IOCTL cmd (%08x)\n", cmd);
2824 break;
2827 fd = get_sock_fd( s, 0, NULL );
2828 if (fd != -1)
2830 if( ioctl(fd, newcmd, (char*)argp ) == 0 )
2832 release_sock_fd( s, fd );
2833 return 0;
2835 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2836 release_sock_fd( s, fd );
2838 return SOCKET_ERROR;
2841 /***********************************************************************
2842 * listen (WS2_32.13)
2844 int WINAPI WS_listen(SOCKET s, int backlog)
2846 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2848 TRACE("socket %04lx, backlog %d\n", s, backlog);
2849 if (fd != -1)
2851 if (listen(fd, backlog) == 0)
2853 release_sock_fd( s, fd );
2854 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
2855 FD_WINE_LISTENING,
2856 FD_CONNECT|FD_WINE_CONNECTED);
2857 return 0;
2859 SetLastError(wsaErrno());
2860 release_sock_fd( s, fd );
2862 return SOCKET_ERROR;
2865 /***********************************************************************
2866 * recv (WS2_32.16)
2868 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
2870 DWORD n, dwFlags = flags;
2871 WSABUF wsabuf;
2873 wsabuf.len = len;
2874 wsabuf.buf = buf;
2876 if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
2877 return SOCKET_ERROR;
2878 else
2879 return n;
2882 /***********************************************************************
2883 * recvfrom (WS2_32.17)
2885 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
2886 struct WS_sockaddr *from, int *fromlen)
2888 DWORD n, dwFlags = flags;
2889 WSABUF wsabuf;
2891 wsabuf.len = len;
2892 wsabuf.buf = buf;
2894 if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL) == SOCKET_ERROR )
2895 return SOCKET_ERROR;
2896 else
2897 return n;
2900 /* allocate a poll array for the corresponding fd sets */
2901 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
2902 const WS_fd_set *exceptfds, int *count_ptr )
2904 unsigned int i, j = 0, count = 0;
2905 struct pollfd *fds;
2907 if (readfds) count += readfds->fd_count;
2908 if (writefds) count += writefds->fd_count;
2909 if (exceptfds) count += exceptfds->fd_count;
2910 *count_ptr = count;
2911 if (!count) return NULL;
2912 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0])))) return NULL;
2913 if (readfds)
2914 for (i = 0; i < readfds->fd_count; i++, j++)
2916 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
2917 fds[j].events = POLLIN;
2918 fds[j].revents = 0;
2920 if (writefds)
2921 for (i = 0; i < writefds->fd_count; i++, j++)
2923 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
2924 fds[j].events = POLLOUT;
2925 fds[j].revents = 0;
2927 if (exceptfds)
2928 for (i = 0; i < exceptfds->fd_count; i++, j++)
2930 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
2931 fds[j].events = POLLHUP;
2932 fds[j].revents = 0;
2934 return fds;
2937 /* release the file descriptor obtained in fd_sets_to_poll */
2938 /* must be called with the original fd_set arrays, before calling get_poll_results */
2939 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
2940 const WS_fd_set *exceptfds, struct pollfd *fds )
2942 unsigned int i, j = 0;
2944 if (readfds)
2946 for (i = 0; i < readfds->fd_count; i++, j++)
2947 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
2949 if (writefds)
2951 for (i = 0; i < writefds->fd_count; i++, j++)
2952 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
2954 if (exceptfds)
2956 for (i = 0; i < exceptfds->fd_count; i++, j++)
2957 if (fds[j].fd != -1)
2959 /* make sure we have a real error before releasing the fd */
2960 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
2961 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
2966 /* map the poll results back into the Windows fd sets */
2967 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
2968 const struct pollfd *fds )
2970 unsigned int i, j = 0, k, total = 0;
2972 if (readfds)
2974 for (i = k = 0; i < readfds->fd_count; i++, j++)
2975 if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
2976 readfds->fd_count = k;
2977 total += k;
2979 if (writefds)
2981 for (i = k = 0; i < writefds->fd_count; i++, j++)
2982 if (fds[j].revents) writefds->fd_array[k++] = writefds->fd_array[i];
2983 writefds->fd_count = k;
2984 total += k;
2986 if (exceptfds)
2988 for (i = k = 0; i < exceptfds->fd_count; i++, j++)
2989 if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
2990 exceptfds->fd_count = k;
2991 total += k;
2993 return total;
2997 /***********************************************************************
2998 * select (WS2_32.18)
3000 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
3001 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
3002 const struct WS_timeval* ws_timeout)
3004 struct pollfd *pollfds;
3005 struct timeval tv1, tv2;
3006 int torig = 0;
3007 int count, ret, timeout = -1;
3009 TRACE("read %p, write %p, excp %p timeout %p\n",
3010 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
3012 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )) && count)
3014 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
3015 return SOCKET_ERROR;
3018 if (ws_timeout)
3020 torig = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
3021 timeout = torig;
3022 gettimeofday( &tv1, 0 );
3025 while ((ret = poll( pollfds, count, timeout )) < 0)
3027 if (errno == EINTR)
3029 if (!ws_timeout) continue;
3030 gettimeofday( &tv2, 0 );
3032 tv2.tv_sec -= tv1.tv_sec;
3033 tv2.tv_usec -= tv1.tv_usec;
3034 if (tv2.tv_usec < 0)
3036 tv2.tv_usec += 1000000;
3037 tv2.tv_sec -= 1;
3040 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
3041 if (timeout <= 0) break;
3042 } else break;
3044 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
3046 if (ret == -1) SetLastError(wsaErrno());
3047 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
3048 HeapFree( GetProcessHeap(), 0, pollfds );
3049 return ret;
3052 /* helper to send completion messages for client-only i/o operation case */
3053 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
3054 ULONG Information )
3056 NTSTATUS status;
3058 SERVER_START_REQ( add_fd_completion )
3060 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
3061 req->cvalue = CompletionValue;
3062 req->status = CompletionStatus;
3063 req->information = Information;
3064 status = wine_server_call( req );
3066 SERVER_END_REQ;
3070 /***********************************************************************
3071 * send (WS2_32.19)
3073 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
3075 DWORD n;
3076 WSABUF wsabuf;
3078 wsabuf.len = len;
3079 wsabuf.buf = (char*) buf;
3081 if ( WSASendTo( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
3082 return SOCKET_ERROR;
3083 else
3084 return n;
3087 /***********************************************************************
3088 * WSASend (WS2_32.72)
3090 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3091 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
3092 LPWSAOVERLAPPED lpOverlapped,
3093 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3095 return WSASendTo( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
3096 NULL, 0, lpOverlapped, lpCompletionRoutine );
3099 /***********************************************************************
3100 * WSASendDisconnect (WS2_32.73)
3102 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
3104 return WS_shutdown( s, SD_SEND );
3108 /***********************************************************************
3109 * WSASendTo (WS2_32.74)
3111 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3112 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
3113 const struct WS_sockaddr *to, int tolen,
3114 LPWSAOVERLAPPED lpOverlapped,
3115 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3117 unsigned int i, options;
3118 int n, fd, err;
3119 struct ws2_async *wsa;
3120 int totalLength = 0;
3121 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
3123 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
3124 s, lpBuffers, dwBufferCount, dwFlags,
3125 to, tolen, lpOverlapped, lpCompletionRoutine);
3127 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
3128 TRACE( "fd=%d, options=%x\n", fd, options );
3130 if ( fd == -1 ) return SOCKET_ERROR;
3132 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
3134 err = WSAEFAULT;
3135 goto error;
3138 wsa->hSocket = SOCKET2HANDLE(s);
3139 wsa->addr = (struct WS_sockaddr *)to;
3140 wsa->addrlen.val = tolen;
3141 wsa->flags = dwFlags;
3142 wsa->n_iovecs = dwBufferCount;
3143 wsa->first_iovec = 0;
3144 for ( i = 0; i < dwBufferCount; i++ )
3146 wsa->iovec[i].iov_base = lpBuffers[i].buf;
3147 wsa->iovec[i].iov_len = lpBuffers[i].len;
3148 totalLength += lpBuffers[i].len;
3151 if (!lpNumberOfBytesSent)
3153 err = WSAEFAULT;
3154 goto error;
3157 for (;;)
3159 n = WS2_send( fd, wsa );
3160 if (n != -1 || errno != EINTR) break;
3162 if (n == -1 && errno != EAGAIN)
3164 int loc_errno = errno;
3165 err = wsaErrno();
3166 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
3167 goto error;
3170 if ((lpOverlapped || lpCompletionRoutine) &&
3171 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
3173 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
3175 wsa->user_overlapped = lpOverlapped;
3176 wsa->completion_func = lpCompletionRoutine;
3177 release_sock_fd( s, fd );
3179 if (n == -1)
3181 iosb->u.Status = STATUS_PENDING;
3182 iosb->Information = 0;
3184 SERVER_START_REQ( register_async )
3186 req->type = ASYNC_TYPE_WRITE;
3187 req->async.handle = wine_server_obj_handle( wsa->hSocket );
3188 req->async.callback = wine_server_client_ptr( WS2_async_send );
3189 req->async.iosb = wine_server_client_ptr( iosb );
3190 req->async.arg = wine_server_client_ptr( wsa );
3191 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
3192 req->async.cvalue = cvalue;
3193 err = wine_server_call( req );
3195 SERVER_END_REQ;
3197 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
3198 WSASetLastError( NtStatusToWSAError( err ));
3199 return SOCKET_ERROR;
3202 iosb->u.Status = STATUS_SUCCESS;
3203 iosb->Information = n;
3204 *lpNumberOfBytesSent = n;
3205 if (!wsa->completion_func)
3207 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
3208 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
3209 HeapFree( GetProcessHeap(), 0, wsa );
3211 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
3212 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
3213 WSASetLastError(0);
3214 return 0;
3217 if ( _is_blocking(s) )
3219 /* On a blocking non-overlapped stream socket,
3220 * sending blocks until the entire buffer is sent. */
3221 DWORD timeout_start = GetTickCount();
3223 *lpNumberOfBytesSent = 0;
3225 while (wsa->first_iovec < dwBufferCount)
3227 struct pollfd pfd;
3228 int timeout = GET_SNDTIMEO(fd);
3230 if (n >= 0)
3232 *lpNumberOfBytesSent += n;
3233 while (wsa->first_iovec < dwBufferCount && wsa->iovec[wsa->first_iovec].iov_len <= n)
3234 n -= wsa->iovec[wsa->first_iovec++].iov_len;
3235 if (wsa->first_iovec >= dwBufferCount) break;
3236 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
3237 wsa->iovec[wsa->first_iovec].iov_len -= n;
3240 if (timeout != -1)
3242 timeout -= GetTickCount() - timeout_start;
3243 if (timeout < 0) timeout = 0;
3246 pfd.fd = fd;
3247 pfd.events = POLLOUT;
3249 if (!timeout || !poll( &pfd, 1, timeout ))
3251 err = WSAETIMEDOUT;
3252 goto error; /* msdn says a timeout in send is fatal */
3255 n = WS2_send( fd, wsa );
3256 if (n == -1 && errno != EAGAIN && errno != EINTR)
3258 err = wsaErrno();
3259 goto error;
3263 else /* non-blocking */
3265 if (n < totalLength)
3266 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
3267 if (n == -1)
3269 err = WSAEWOULDBLOCK;
3270 goto error;
3272 *lpNumberOfBytesSent = n;
3275 TRACE(" -> %i bytes\n", *lpNumberOfBytesSent);
3277 HeapFree( GetProcessHeap(), 0, wsa );
3278 release_sock_fd( s, fd );
3279 WSASetLastError(0);
3280 return 0;
3282 error:
3283 HeapFree( GetProcessHeap(), 0, wsa );
3284 release_sock_fd( s, fd );
3285 WARN(" -> ERROR %d\n", err);
3286 WSASetLastError(err);
3287 return SOCKET_ERROR;
3290 /***********************************************************************
3291 * sendto (WS2_32.20)
3293 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
3294 const struct WS_sockaddr *to, int tolen)
3296 DWORD n;
3297 WSABUF wsabuf;
3299 wsabuf.len = len;
3300 wsabuf.buf = (char*) buf;
3302 if ( WSASendTo(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
3303 return SOCKET_ERROR;
3304 else
3305 return n;
3308 /***********************************************************************
3309 * setsockopt (WS2_32.21)
3311 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
3312 const char *optval, int optlen)
3314 int fd;
3315 int woptval;
3316 struct linger linger;
3317 struct timeval tval;
3319 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
3320 s, level, optname, optval, optlen);
3322 /* some broken apps pass the value directly instead of a pointer to it */
3323 if(IS_INTRESOURCE(optval))
3325 SetLastError(WSAEFAULT);
3326 return SOCKET_ERROR;
3329 switch(level)
3331 case WS_SOL_SOCKET:
3332 switch(optname)
3334 /* Some options need some conversion before they can be sent to
3335 * setsockopt. The conversions are done here, then they will fall though
3336 * to the general case. Special options that are not passed to
3337 * setsockopt follow below that.*/
3339 case WS_SO_DONTLINGER:
3340 linger.l_onoff = *((const int*)optval) ? 0: 1;
3341 linger.l_linger = 0;
3342 level = SOL_SOCKET;
3343 optname = SO_LINGER;
3344 optval = (char*)&linger;
3345 optlen = sizeof(struct linger);
3346 break;
3348 case WS_SO_LINGER:
3349 linger.l_onoff = ((LINGER*)optval)->l_onoff;
3350 linger.l_linger = ((LINGER*)optval)->l_linger;
3351 /* FIXME: what is documented behavior if SO_LINGER optval
3352 is null?? */
3353 level = SOL_SOCKET;
3354 optname = SO_LINGER;
3355 optval = (char*)&linger;
3356 optlen = sizeof(struct linger);
3357 break;
3359 case WS_SO_RCVBUF:
3360 if (*(const int*)optval < 2048)
3362 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
3363 return 0;
3365 /* Fall through */
3367 /* The options listed here don't need any special handling. Thanks to
3368 * the conversion happening above, options from there will fall through
3369 * to this, too.*/
3370 case WS_SO_ACCEPTCONN:
3371 case WS_SO_BROADCAST:
3372 case WS_SO_ERROR:
3373 case WS_SO_KEEPALIVE:
3374 case WS_SO_OOBINLINE:
3375 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
3376 * however, using it the BSD way fixes bug 8513 and seems to be what
3377 * most programmers assume, anyway */
3378 case WS_SO_REUSEADDR:
3379 case WS_SO_SNDBUF:
3380 case WS_SO_TYPE:
3381 convert_sockopt(&level, &optname);
3382 break;
3384 /* SO_DEBUG is a privileged operation, ignore it. */
3385 case WS_SO_DEBUG:
3386 TRACE("Ignoring SO_DEBUG\n");
3387 return 0;
3389 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
3390 * socket. According to MSDN, this option is silently ignored.*/
3391 case WS_SO_DONTROUTE:
3392 TRACE("Ignoring SO_DONTROUTE\n");
3393 return 0;
3395 /* Stops two sockets from being bound to the same port. Always happens
3396 * on unix systems, so just drop it. */
3397 case WS_SO_EXCLUSIVEADDRUSE:
3398 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
3399 return 0;
3401 /* SO_OPENTYPE does not require a valid socket handle. */
3402 case WS_SO_OPENTYPE:
3403 if (!optlen || optlen < sizeof(int) || !optval)
3405 SetLastError(WSAEFAULT);
3406 return SOCKET_ERROR;
3408 get_per_thread_data()->opentype = *(const int *)optval;
3409 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((const int*)optval) );
3410 return 0;
3412 #ifdef SO_RCVTIMEO
3413 case WS_SO_RCVTIMEO:
3414 #endif
3415 #ifdef SO_SNDTIMEO
3416 case WS_SO_SNDTIMEO:
3417 #endif
3418 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
3419 if (optval && optlen == sizeof(UINT32)) {
3420 /* WinSock passes milliseconds instead of struct timeval */
3421 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
3422 tval.tv_sec = *(const UINT32*)optval / 1000;
3423 /* min of 500 milliseconds */
3424 if (tval.tv_sec == 0 && tval.tv_usec && tval.tv_usec < 500000)
3425 tval.tv_usec = 500000;
3426 optlen = sizeof(struct timeval);
3427 optval = (char*)&tval;
3428 } else if (optlen == sizeof(struct timeval)) {
3429 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
3430 } else {
3431 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
3432 return 0;
3434 convert_sockopt(&level, &optname);
3435 break;
3436 #endif
3438 default:
3439 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
3440 SetLastError(WSAENOPROTOOPT);
3441 return SOCKET_ERROR;
3443 break; /* case WS_SOL_SOCKET */
3445 #ifdef HAVE_IPX
3446 case NSPROTO_IPX:
3447 switch(optname)
3449 case IPX_PTYPE:
3450 fd = get_sock_fd( s, 0, NULL );
3451 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", *(const int*)optval, fd);
3453 /* We try to set the ipx type on ipx socket level. */
3454 #ifdef SOL_IPX
3455 if(setsockopt(fd, SOL_IPX, IPX_TYPE, optval, optlen) == -1)
3457 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
3458 release_sock_fd( s, fd );
3459 return SOCKET_ERROR;
3461 #else
3463 struct ipx val;
3464 /* Should we retrieve val using a getsockopt call and then
3465 * set the modified one? */
3466 val.ipx_pt = *optval;
3467 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
3469 #endif
3470 release_sock_fd( s, fd );
3471 return 0;
3473 case IPX_FILTERPTYPE:
3474 /* Sets the receive filter packet type, at the moment we don't support it */
3475 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
3476 /* Returning 0 is better for now than returning a SOCKET_ERROR */
3477 return 0;
3479 default:
3480 FIXME("opt_name:%x\n", optname);
3481 return SOCKET_ERROR;
3483 break; /* case NSPROTO_IPX */
3484 #endif
3486 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3487 case WS_IPPROTO_TCP:
3488 switch(optname)
3490 case WS_TCP_NODELAY:
3491 convert_sockopt(&level, &optname);
3492 break;
3493 default:
3494 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
3495 return SOCKET_ERROR;
3497 break;
3499 case WS_IPPROTO_IP:
3500 switch(optname)
3502 case WS_IP_ADD_MEMBERSHIP:
3503 case WS_IP_DROP_MEMBERSHIP:
3504 #ifdef IP_HDRINCL
3505 case WS_IP_HDRINCL:
3506 #endif
3507 case WS_IP_MULTICAST_IF:
3508 case WS_IP_MULTICAST_LOOP:
3509 case WS_IP_MULTICAST_TTL:
3510 case WS_IP_OPTIONS:
3511 case WS_IP_TOS:
3512 case WS_IP_TTL:
3513 convert_sockopt(&level, &optname);
3514 break;
3515 case WS_IP_DONTFRAGMENT:
3516 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
3517 return 0;
3518 default:
3519 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
3520 return SOCKET_ERROR;
3522 break;
3524 case WS_IPPROTO_IPV6:
3525 switch(optname)
3527 #ifdef IPV6_ADD_MEMBERSHIP
3528 case WS_IPV6_ADD_MEMBERSHIP:
3529 #endif
3530 #ifdef IPV6_DROP_MEMBERSHIP
3531 case WS_IPV6_DROP_MEMBERSHIP:
3532 #endif
3533 case WS_IPV6_MULTICAST_IF:
3534 case WS_IPV6_MULTICAST_HOPS:
3535 case WS_IPV6_MULTICAST_LOOP:
3536 case WS_IPV6_UNICAST_HOPS:
3537 case WS_IPV6_V6ONLY:
3538 convert_sockopt(&level, &optname);
3539 break;
3540 case WS_IPV6_DONTFRAG:
3541 FIXME("IPV6_DONTFRAG is silently ignored!\n");
3542 return 0;
3543 default:
3544 FIXME("Unknown IPPROTO_IPV6 optname 0x%08x\n", optname);
3545 return SOCKET_ERROR;
3547 break;
3549 default:
3550 WARN("Unknown level: 0x%08x\n", level);
3551 SetLastError(WSAEINVAL);
3552 return SOCKET_ERROR;
3553 } /* end switch(level) */
3555 /* avoid endianness issues if argument is a 16-bit int */
3556 if (optval && optlen < sizeof(int))
3558 woptval= *((const INT16 *) optval);
3559 optval= (char*) &woptval;
3560 optlen=sizeof(int);
3562 fd = get_sock_fd( s, 0, NULL );
3563 if (fd == -1) return SOCKET_ERROR;
3565 if (setsockopt(fd, level, optname, optval, optlen) == 0)
3567 release_sock_fd( s, fd );
3568 return 0;
3570 TRACE("Setting socket error, %d\n", wsaErrno());
3571 SetLastError(wsaErrno());
3572 release_sock_fd( s, fd );
3574 return SOCKET_ERROR;
3577 /***********************************************************************
3578 * shutdown (WS2_32.22)
3580 int WINAPI WS_shutdown(SOCKET s, int how)
3582 int fd, err = WSAENOTSOCK;
3583 unsigned int options, clear_flags = 0;
3585 fd = get_sock_fd( s, 0, &options );
3586 TRACE("socket %04lx, how %i %x\n", s, how, options );
3588 if (fd == -1)
3589 return SOCKET_ERROR;
3591 switch( how )
3593 case 0: /* drop receives */
3594 clear_flags |= FD_READ;
3595 break;
3596 case 1: /* drop sends */
3597 clear_flags |= FD_WRITE;
3598 break;
3599 case 2: /* drop all */
3600 clear_flags |= FD_READ|FD_WRITE;
3601 default:
3602 clear_flags |= FD_WINE_LISTENING;
3605 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
3607 switch ( how )
3609 case SD_RECEIVE:
3610 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3611 break;
3612 case SD_SEND:
3613 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3614 break;
3615 case SD_BOTH:
3616 default:
3617 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3618 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3619 break;
3621 if (err) goto error;
3623 else /* non-overlapped mode */
3625 if ( shutdown( fd, how ) )
3627 err = wsaErrno();
3628 goto error;
3632 release_sock_fd( s, fd );
3633 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3634 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
3635 return 0;
3637 error:
3638 release_sock_fd( s, fd );
3639 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3640 WSASetLastError( err );
3641 return SOCKET_ERROR;
3644 /***********************************************************************
3645 * socket (WS2_32.23)
3647 SOCKET WINAPI WS_socket(int af, int type, int protocol)
3649 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
3651 return WSASocketA( af, type, protocol, NULL, 0,
3652 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
3656 /***********************************************************************
3657 * gethostbyaddr (WS2_32.51)
3659 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
3661 struct WS_hostent *retval = NULL;
3662 struct hostent* host;
3664 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3665 char *extrabuf;
3666 int ebufsize=1024;
3667 struct hostent hostentry;
3668 int locerr=ENOBUFS;
3669 host = NULL;
3670 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3671 while(extrabuf) {
3672 int res = gethostbyaddr_r(addr, len, type,
3673 &hostentry, extrabuf, ebufsize, &host, &locerr);
3674 if( res != ERANGE) break;
3675 ebufsize *=2;
3676 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3678 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3679 #else
3680 EnterCriticalSection( &csWSgetXXXbyYYY );
3681 host = gethostbyaddr(addr, len, type);
3682 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3683 #endif
3684 if( host != NULL ) retval = WS_dup_he(host);
3685 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3686 HeapFree(GetProcessHeap(),0,extrabuf);
3687 #else
3688 LeaveCriticalSection( &csWSgetXXXbyYYY );
3689 #endif
3690 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
3691 return retval;
3694 /***********************************************************************
3695 * WS_get_local_ips (INTERNAL)
3697 * Returns the list of local IP addresses by going through the network
3698 * adapters and using the local routing table to sort the addresses
3699 * from highest routing priority to lowest routing priority. This
3700 * functionality is inferred from the description for obtaining local
3701 * IP addresses given in the Knowledge Base Article Q160215.
3703 * Please note that the returned hostent is only freed when the thread
3704 * closes and is replaced if another hostent is requested.
3706 static struct WS_hostent* WS_get_local_ips( char *hostname )
3708 int last_metric, numroutes = 0, i, j;
3709 PIP_ADAPTER_INFO adapters = NULL, k;
3710 struct WS_hostent *hostlist = NULL;
3711 PMIB_IPFORWARDTABLE routes = NULL;
3712 struct route *route_addrs = NULL;
3713 DWORD adap_size, route_size;
3715 /* Obtain the size of the adapter list and routing table, also allocate memory */
3716 if (GetAdaptersInfo(NULL, &adap_size) != ERROR_BUFFER_OVERFLOW)
3717 return NULL;
3718 if (GetIpForwardTable(NULL, &route_size, FALSE) != ERROR_INSUFFICIENT_BUFFER)
3719 return NULL;
3720 adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
3721 routes = HeapAlloc(GetProcessHeap(), 0, route_size);
3722 route_addrs = HeapAlloc(GetProcessHeap(), 0, 0); /* HeapReAlloc doesn't work on NULL */
3723 if (adapters == NULL || routes == NULL || route_addrs == NULL)
3724 goto cleanup;
3725 /* Obtain the adapter list and the full routing table */
3726 if (GetAdaptersInfo(adapters, &adap_size) != NO_ERROR)
3727 goto cleanup;
3728 if (GetIpForwardTable(routes, &route_size, FALSE) != NO_ERROR)
3729 goto cleanup;
3730 /* Store the interface associated with each route */
3731 for (i = 0; i < routes->dwNumEntries; i++)
3733 DWORD ifindex, ifmetric, exists = FALSE;
3735 if (routes->table[i].dwForwardType != MIB_IPROUTE_TYPE_DIRECT)
3736 continue;
3737 ifindex = routes->table[i].dwForwardIfIndex;
3738 ifmetric = routes->table[i].dwForwardMetric1;
3739 /* Only store the lowest valued metric for an interface */
3740 for (j = 0; j < numroutes; j++)
3742 if (route_addrs[j].interface == ifindex)
3744 if (route_addrs[j].metric > ifmetric)
3745 route_addrs[j].metric = ifmetric;
3746 exists = TRUE;
3749 if (exists)
3750 continue;
3751 route_addrs = HeapReAlloc(GetProcessHeap(), 0, route_addrs, (numroutes+1)*sizeof(struct route));
3752 if (route_addrs == NULL)
3753 goto cleanup; /* Memory allocation error, fail gracefully */
3754 route_addrs[numroutes].interface = ifindex;
3755 route_addrs[numroutes].metric = ifmetric;
3756 /* If no IP is found in the next step (for whatever reason)
3757 * then fall back to the magic loopback address.
3759 memcpy(&(route_addrs[numroutes].addr.s_addr), magic_loopback_addr, 4);
3760 numroutes++;
3762 if (numroutes == 0)
3763 goto cleanup; /* No routes, fall back to the Magic IP */
3764 /* Find the IP address associated with each found interface */
3765 for (i = 0; i < numroutes; i++)
3767 for (k = adapters; k != NULL; k = k->Next)
3769 char *ip = k->IpAddressList.IpAddress.String;
3771 if (route_addrs[i].interface == k->Index)
3772 route_addrs[i].addr.s_addr = (in_addr_t) inet_addr(ip);
3775 /* Allocate a hostent and enough memory for all the IPs,
3776 * including the NULL at the end of the list.
3778 hostlist = WS_create_he(hostname, 1, numroutes+1, TRUE);
3779 if (hostlist == NULL)
3780 goto cleanup; /* Failed to allocate a hostent for the list of IPs */
3781 hostlist->h_addr_list[numroutes] = NULL; /* NULL-terminate the address list */
3782 hostlist->h_aliases[0] = NULL; /* NULL-terminate the alias list */
3783 hostlist->h_addrtype = AF_INET;
3784 hostlist->h_length = sizeof(struct in_addr); /* = 4 */
3785 /* Reorder the entries when placing them in the host list, Windows expects
3786 * the IP list in order from highest priority to lowest (the critical thing
3787 * is that most applications expect the first IP to be the default route).
3789 last_metric = -1;
3790 for (i = 0; i < numroutes; i++)
3792 struct in_addr addr;
3793 int metric = 0xFFFF;
3795 memcpy(&addr, magic_loopback_addr, 4);
3796 for (j = 0; j < numroutes; j++)
3798 int this_metric = route_addrs[j].metric;
3800 if (this_metric > last_metric && this_metric < metric)
3802 addr = route_addrs[j].addr;
3803 metric = this_metric;
3806 last_metric = metric;
3807 (*(struct in_addr *) hostlist->h_addr_list[i]) = addr;
3810 /* Cleanup all allocated memory except the address list,
3811 * the address list is used by the calling app.
3813 cleanup:
3814 HeapFree(GetProcessHeap(), 0, route_addrs);
3815 HeapFree(GetProcessHeap(), 0, adapters);
3816 HeapFree(GetProcessHeap(), 0, routes);
3817 return hostlist;
3820 /***********************************************************************
3821 * gethostbyname (WS2_32.52)
3823 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
3825 struct WS_hostent *retval = NULL;
3826 struct hostent* host;
3827 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3828 char *extrabuf;
3829 int ebufsize=1024;
3830 struct hostent hostentry;
3831 int locerr = ENOBUFS;
3832 #endif
3833 char hostname[100];
3834 if( gethostname( hostname, 100) == -1) {
3835 SetLastError( WSAENOBUFS); /* appropriate ? */
3836 return retval;
3838 if( !name || !name[0]) {
3839 name = hostname;
3841 /* If the hostname of the local machine is requested then return the
3842 * complete list of local IP addresses */
3843 if(strcmp(name, hostname) == 0)
3844 retval = WS_get_local_ips(hostname);
3845 /* If any other hostname was requested (or the routing table lookup failed)
3846 * then return the IP found by the host OS */
3847 if(retval == NULL)
3849 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3850 host = NULL;
3851 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3852 while(extrabuf) {
3853 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
3854 if( res != ERANGE) break;
3855 ebufsize *=2;
3856 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3858 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3859 #else
3860 EnterCriticalSection( &csWSgetXXXbyYYY );
3861 host = gethostbyname(name);
3862 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3863 #endif
3864 if (host) retval = WS_dup_he(host);
3865 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3866 HeapFree(GetProcessHeap(),0,extrabuf);
3867 #else
3868 LeaveCriticalSection( &csWSgetXXXbyYYY );
3869 #endif
3871 if (retval && retval->h_addr_list[0][0] == 127 &&
3872 strcmp(name, "localhost") != 0)
3874 /* hostname != "localhost" but has loopback address. replace by our
3875 * special address.*/
3876 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
3878 TRACE( "%s ret %p\n", debugstr_a(name), retval );
3879 return retval;
3883 /***********************************************************************
3884 * getprotobyname (WS2_32.53)
3886 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
3888 struct WS_protoent* retval = NULL;
3889 #ifdef HAVE_GETPROTOBYNAME
3890 struct protoent* proto;
3891 EnterCriticalSection( &csWSgetXXXbyYYY );
3892 if( (proto = getprotobyname(name)) != NULL )
3894 retval = WS_dup_pe(proto);
3896 else {
3897 MESSAGE("protocol %s not found; You might want to add "
3898 "this to /etc/protocols\n", debugstr_a(name) );
3899 SetLastError(WSANO_DATA);
3901 LeaveCriticalSection( &csWSgetXXXbyYYY );
3902 #endif
3903 TRACE( "%s ret %p\n", debugstr_a(name), retval );
3904 return retval;
3908 /***********************************************************************
3909 * getprotobynumber (WS2_32.54)
3911 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
3913 struct WS_protoent* retval = NULL;
3914 #ifdef HAVE_GETPROTOBYNUMBER
3915 struct protoent* proto;
3916 EnterCriticalSection( &csWSgetXXXbyYYY );
3917 if( (proto = getprotobynumber(number)) != NULL )
3919 retval = WS_dup_pe(proto);
3921 else {
3922 MESSAGE("protocol number %d not found; You might want to add "
3923 "this to /etc/protocols\n", number );
3924 SetLastError(WSANO_DATA);
3926 LeaveCriticalSection( &csWSgetXXXbyYYY );
3927 #endif
3928 TRACE("%i ret %p\n", number, retval);
3929 return retval;
3933 /***********************************************************************
3934 * getservbyname (WS2_32.55)
3936 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
3938 struct WS_servent* retval = NULL;
3939 struct servent* serv;
3940 char *name_str;
3941 char *proto_str = NULL;
3943 if (!(name_str = strdup_lower(name))) return NULL;
3945 if (proto && *proto)
3947 if (!(proto_str = strdup_lower(proto)))
3949 HeapFree( GetProcessHeap(), 0, name_str );
3950 return NULL;
3954 EnterCriticalSection( &csWSgetXXXbyYYY );
3955 serv = getservbyname(name_str, proto_str);
3956 if( serv != NULL )
3958 retval = WS_dup_se(serv);
3960 else SetLastError(WSANO_DATA);
3961 LeaveCriticalSection( &csWSgetXXXbyYYY );
3962 HeapFree( GetProcessHeap(), 0, proto_str );
3963 HeapFree( GetProcessHeap(), 0, name_str );
3964 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
3965 return retval;
3968 /***********************************************************************
3969 * freeaddrinfo (WS2_32.@)
3971 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
3973 while (res) {
3974 struct WS_addrinfo *next;
3976 HeapFree(GetProcessHeap(),0,res->ai_canonname);
3977 HeapFree(GetProcessHeap(),0,res->ai_addr);
3978 next = res->ai_next;
3979 HeapFree(GetProcessHeap(),0,res);
3980 res = next;
3984 /* helper functions for getaddrinfo()/getnameinfo() */
3985 static int convert_aiflag_w2u(int winflags) {
3986 unsigned int i;
3987 int unixflags = 0;
3989 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
3990 if (ws_aiflag_map[i][0] & winflags) {
3991 unixflags |= ws_aiflag_map[i][1];
3992 winflags &= ~ws_aiflag_map[i][0];
3994 if (winflags)
3995 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
3996 return unixflags;
3999 static int convert_niflag_w2u(int winflags) {
4000 unsigned int i;
4001 int unixflags = 0;
4003 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
4004 if (ws_niflag_map[i][0] & winflags) {
4005 unixflags |= ws_niflag_map[i][1];
4006 winflags &= ~ws_niflag_map[i][0];
4008 if (winflags)
4009 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
4010 return unixflags;
4013 static int convert_aiflag_u2w(int unixflags) {
4014 unsigned int i;
4015 int winflags = 0;
4017 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
4018 if (ws_aiflag_map[i][1] & unixflags) {
4019 winflags |= ws_aiflag_map[i][0];
4020 unixflags &= ~ws_aiflag_map[i][1];
4022 if (unixflags) /* will warn usually */
4023 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
4024 return winflags;
4027 static int convert_eai_u2w(int unixret) {
4028 int i;
4030 for (i=0;ws_eai_map[i][0];i++)
4031 if (ws_eai_map[i][1] == unixret)
4032 return ws_eai_map[i][0];
4033 return unixret;
4036 /***********************************************************************
4037 * getaddrinfo (WS2_32.@)
4039 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
4041 #ifdef HAVE_GETADDRINFO
4042 struct addrinfo *unixaires = NULL;
4043 int result;
4044 struct addrinfo unixhints, *punixhints = NULL;
4045 CHAR *node = NULL, *serv = NULL;
4047 if (nodename)
4048 if (!(node = strdup_lower(nodename))) return WSA_NOT_ENOUGH_MEMORY;
4050 if (servname) {
4051 if (!(serv = strdup_lower(servname))) {
4052 HeapFree(GetProcessHeap(), 0, node);
4053 return WSA_NOT_ENOUGH_MEMORY;
4057 if (hints) {
4058 punixhints = &unixhints;
4060 memset(&unixhints, 0, sizeof(unixhints));
4061 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
4062 if (hints->ai_family == 0) /* wildcard, specific to getaddrinfo() */
4063 punixhints->ai_family = 0;
4064 else
4065 punixhints->ai_family = convert_af_w2u(hints->ai_family);
4066 if (hints->ai_socktype == 0) /* wildcard, specific to getaddrinfo() */
4067 punixhints->ai_socktype = 0;
4068 else
4069 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
4070 if (hints->ai_protocol == 0) /* wildcard, specific to getaddrinfo() */
4071 punixhints->ai_protocol = 0;
4072 else
4073 punixhints->ai_protocol = convert_proto_w2u(hints->ai_protocol);
4076 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
4077 result = getaddrinfo(nodename, servname, punixhints, &unixaires);
4079 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
4081 HeapFree(GetProcessHeap(), 0, node);
4082 HeapFree(GetProcessHeap(), 0, serv);
4084 if (!result) {
4085 struct addrinfo *xuai = unixaires;
4086 struct WS_addrinfo **xai = res;
4088 *xai = NULL;
4089 while (xuai) {
4090 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
4091 int len;
4093 if (!ai)
4094 goto outofmem;
4096 *xai = ai;xai = &ai->ai_next;
4097 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
4098 ai->ai_family = convert_af_u2w(xuai->ai_family);
4099 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
4100 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
4101 if (xuai->ai_canonname) {
4102 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
4103 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
4104 if (!ai->ai_canonname)
4105 goto outofmem;
4106 strcpy(ai->ai_canonname,xuai->ai_canonname);
4108 len = xuai->ai_addrlen;
4109 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
4110 if (!ai->ai_addr)
4111 goto outofmem;
4112 ai->ai_addrlen = len;
4113 do {
4114 int winlen = ai->ai_addrlen;
4116 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
4117 ai->ai_addrlen = winlen;
4118 break;
4120 len = 2*len;
4121 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
4122 if (!ai->ai_addr)
4123 goto outofmem;
4124 ai->ai_addrlen = len;
4125 } while (1);
4126 xuai = xuai->ai_next;
4128 freeaddrinfo(unixaires);
4129 } else {
4130 result = convert_eai_u2w(result);
4131 *res = NULL;
4133 return result;
4135 outofmem:
4136 if (*res) WS_freeaddrinfo(*res);
4137 if (unixaires) freeaddrinfo(unixaires);
4138 *res = NULL;
4139 return WSA_NOT_ENOUGH_MEMORY;
4140 #else
4141 FIXME("getaddrinfo() failed, not found during buildtime.\n");
4142 return EAI_FAIL;
4143 #endif
4146 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
4148 struct WS_addrinfoW *ret;
4150 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
4151 ret->ai_flags = ai->ai_flags;
4152 ret->ai_family = ai->ai_family;
4153 ret->ai_socktype = ai->ai_socktype;
4154 ret->ai_protocol = ai->ai_protocol;
4155 ret->ai_addrlen = ai->ai_addrlen;
4156 ret->ai_canonname = NULL;
4157 ret->ai_addr = NULL;
4158 ret->ai_next = NULL;
4159 if (ai->ai_canonname)
4161 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
4162 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
4164 HeapFree(GetProcessHeap(), 0, ret);
4165 return NULL;
4167 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
4169 if (ai->ai_addr)
4171 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
4173 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
4174 HeapFree(GetProcessHeap(), 0, ret);
4175 return NULL;
4177 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
4179 return ret;
4182 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
4184 struct WS_addrinfoW *ret, *infoW;
4186 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
4187 while (info->ai_next)
4189 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
4191 FreeAddrInfoW(ret);
4192 return NULL;
4194 infoW = infoW->ai_next;
4195 info = info->ai_next;
4197 return ret;
4200 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
4202 struct WS_addrinfo *ret;
4204 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
4205 ret->ai_flags = ai->ai_flags;
4206 ret->ai_family = ai->ai_family;
4207 ret->ai_socktype = ai->ai_socktype;
4208 ret->ai_protocol = ai->ai_protocol;
4209 ret->ai_addrlen = ai->ai_addrlen;
4210 ret->ai_canonname = NULL;
4211 ret->ai_addr = NULL;
4212 ret->ai_next = NULL;
4213 if (ai->ai_canonname)
4215 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
4216 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
4218 HeapFree(GetProcessHeap(), 0, ret);
4219 return NULL;
4221 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
4223 if (ai->ai_addr)
4225 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
4227 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
4228 HeapFree(GetProcessHeap(), 0, ret);
4229 return NULL;
4231 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
4233 return ret;
4236 /***********************************************************************
4237 * GetAddrInfoW (WS2_32.@)
4239 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
4241 int ret, len;
4242 char *nodenameA, *servnameA = NULL;
4243 struct WS_addrinfo *resA, *hintsA = NULL;
4245 if (!nodename) return WSAHOST_NOT_FOUND;
4247 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
4248 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
4249 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
4251 if (servname)
4253 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
4254 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
4256 HeapFree(GetProcessHeap(), 0, nodenameA);
4257 return EAI_MEMORY;
4259 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
4262 if (hints) hintsA = addrinfo_WtoA(hints);
4263 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
4264 WS_freeaddrinfo(hintsA);
4266 if (!ret)
4268 *res = addrinfo_list_AtoW(resA);
4269 WS_freeaddrinfo(resA);
4272 HeapFree(GetProcessHeap(), 0, nodenameA);
4273 HeapFree(GetProcessHeap(), 0, servnameA);
4274 return ret;
4277 /***********************************************************************
4278 * FreeAddrInfoW (WS2_32.@)
4280 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
4282 while (ai)
4284 ADDRINFOW *next;
4285 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
4286 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
4287 next = ai->ai_next;
4288 HeapFree(GetProcessHeap(), 0, ai);
4289 ai = next;
4293 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
4294 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
4296 #ifdef HAVE_GETNAMEINFO
4297 int ret;
4298 union generic_unix_sockaddr sa_u;
4299 unsigned int size;
4301 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
4302 serv, servlen, flags);
4304 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
4305 if (!size)
4307 WSASetLastError(WSAEFAULT);
4308 return WSA_NOT_ENOUGH_MEMORY;
4310 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
4311 return convert_eai_u2w(ret);
4312 #else
4313 FIXME("getnameinfo() failed, not found during buildtime.\n");
4314 return EAI_FAIL;
4315 #endif
4318 /***********************************************************************
4319 * getservbyport (WS2_32.56)
4321 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
4323 struct WS_servent* retval = NULL;
4324 #ifdef HAVE_GETSERVBYPORT
4325 struct servent* serv;
4326 char *proto_str = NULL;
4328 if (proto && *proto)
4330 if (!(proto_str = strdup_lower(proto))) return NULL;
4332 EnterCriticalSection( &csWSgetXXXbyYYY );
4333 if( (serv = getservbyport(port, proto_str)) != NULL ) {
4334 retval = WS_dup_se(serv);
4336 else SetLastError(WSANO_DATA);
4337 LeaveCriticalSection( &csWSgetXXXbyYYY );
4338 HeapFree( GetProcessHeap(), 0, proto_str );
4339 #endif
4340 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
4341 return retval;
4345 /***********************************************************************
4346 * gethostname (WS2_32.57)
4348 int WINAPI WS_gethostname(char *name, int namelen)
4350 TRACE("name %p, len %d\n", name, namelen);
4352 if (gethostname(name, namelen) == 0)
4354 TRACE("<- '%s'\n", name);
4355 return 0;
4357 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
4358 TRACE("<- ERROR !\n");
4359 return SOCKET_ERROR;
4363 /* ------------------------------------- Windows sockets extensions -- *
4365 * ------------------------------------------------------------------- */
4367 /***********************************************************************
4368 * WSAEnumNetworkEvents (WS2_32.36)
4370 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
4372 int ret;
4373 int i;
4374 int errors[FD_MAX_EVENTS];
4376 TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
4378 SERVER_START_REQ( get_socket_event )
4380 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
4381 req->service = TRUE;
4382 req->c_event = wine_server_obj_handle( hEvent );
4383 wine_server_set_reply( req, errors, sizeof(errors) );
4384 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
4386 SERVER_END_REQ;
4387 if (!ret)
4389 for (i = 0; i < FD_MAX_EVENTS; i++)
4390 lpEvent->iErrorCode[i] = NtStatusToWSAError(errors[i]);
4391 return 0;
4393 SetLastError(WSAEINVAL);
4394 return SOCKET_ERROR;
4397 /***********************************************************************
4398 * WSAEventSelect (WS2_32.39)
4400 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
4402 int ret;
4404 TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
4406 SERVER_START_REQ( set_socket_event )
4408 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
4409 req->mask = lEvent;
4410 req->event = wine_server_obj_handle( hEvent );
4411 req->window = 0;
4412 req->msg = 0;
4413 ret = wine_server_call( req );
4415 SERVER_END_REQ;
4416 if (!ret) return 0;
4417 SetLastError(WSAEINVAL);
4418 return SOCKET_ERROR;
4421 /**********************************************************************
4422 * WSAGetOverlappedResult (WS2_32.40)
4424 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
4425 LPDWORD lpcbTransfer, BOOL fWait,
4426 LPDWORD lpdwFlags )
4428 NTSTATUS status;
4430 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
4431 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
4433 if ( lpOverlapped == NULL )
4435 ERR( "Invalid pointer\n" );
4436 WSASetLastError(WSA_INVALID_PARAMETER);
4437 return FALSE;
4440 status = lpOverlapped->Internal;
4441 if (status == STATUS_PENDING)
4443 if (!fWait)
4445 SetLastError( WSA_IO_INCOMPLETE );
4446 return FALSE;
4449 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
4450 INFINITE ) == WAIT_FAILED)
4451 return FALSE;
4452 status = lpOverlapped->Internal;
4455 if ( lpcbTransfer )
4456 *lpcbTransfer = lpOverlapped->InternalHigh;
4458 if ( lpdwFlags )
4459 *lpdwFlags = lpOverlapped->u.s.Offset;
4461 if (status) SetLastError( RtlNtStatusToDosError(status) );
4462 return !status;
4466 /***********************************************************************
4467 * WSAAsyncSelect (WS2_32.101)
4469 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
4471 int ret;
4473 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
4475 SERVER_START_REQ( set_socket_event )
4477 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
4478 req->mask = lEvent;
4479 req->event = 0;
4480 req->window = wine_server_user_handle( hWnd );
4481 req->msg = uMsg;
4482 ret = wine_server_call( req );
4484 SERVER_END_REQ;
4485 if (!ret) return 0;
4486 SetLastError(WSAEINVAL);
4487 return SOCKET_ERROR;
4490 /***********************************************************************
4491 * WSACreateEvent (WS2_32.31)
4494 WSAEVENT WINAPI WSACreateEvent(void)
4496 /* Create a manual-reset event, with initial state: unsignaled */
4497 TRACE("\n");
4499 return CreateEventW(NULL, TRUE, FALSE, NULL);
4502 /***********************************************************************
4503 * WSACloseEvent (WS2_32.29)
4506 BOOL WINAPI WSACloseEvent(WSAEVENT event)
4508 TRACE ("event=%p\n", event);
4510 return CloseHandle(event);
4513 /***********************************************************************
4514 * WSASocketA (WS2_32.78)
4517 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
4518 LPWSAPROTOCOL_INFOA lpProtocolInfo,
4519 GROUP g, DWORD dwFlags)
4521 INT len;
4522 WSAPROTOCOL_INFOW info;
4524 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
4525 af, type, protocol, lpProtocolInfo, g, dwFlags);
4527 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
4529 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
4530 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
4531 info.szProtocol, WSAPROTOCOL_LEN + 1);
4533 if (!len)
4535 WSASetLastError( WSAEINVAL);
4536 return SOCKET_ERROR;
4539 return WSASocketW(af, type, protocol, &info, g, dwFlags);
4542 /***********************************************************************
4543 * WSASocketW (WS2_32.79)
4546 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
4547 LPWSAPROTOCOL_INFOW lpProtocolInfo,
4548 GROUP g, DWORD dwFlags)
4550 SOCKET ret;
4553 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
4554 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
4557 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
4558 af, type, protocol, lpProtocolInfo, g, dwFlags );
4560 /* hack for WSADuplicateSocket */
4561 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
4562 ret = lpProtocolInfo->dwCatalogEntryId;
4563 TRACE("\tgot duplicate %04lx\n", ret);
4564 return ret;
4567 /* convert the socket family and type */
4568 af = convert_af_w2u(af);
4569 type = convert_socktype_w2u(type);
4571 if (lpProtocolInfo)
4573 if (af == FROM_PROTOCOL_INFO)
4574 af = lpProtocolInfo->iAddressFamily;
4575 if (type == FROM_PROTOCOL_INFO)
4576 type = lpProtocolInfo->iSocketType;
4577 if (protocol == FROM_PROTOCOL_INFO)
4578 protocol = lpProtocolInfo->iProtocol;
4581 if ( af == AF_UNSPEC) /* did they not specify the address family? */
4582 switch(protocol)
4584 case IPPROTO_TCP:
4585 if (type == SOCK_STREAM) { af = AF_INET; break; }
4586 case IPPROTO_UDP:
4587 if (type == SOCK_DGRAM) { af = AF_INET; break; }
4588 default: SetLastError(WSAEPROTOTYPE); return INVALID_SOCKET;
4591 SERVER_START_REQ( create_socket )
4593 req->family = af;
4594 req->type = type;
4595 req->protocol = protocol;
4596 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
4597 req->attributes = OBJ_INHERIT;
4598 req->flags = dwFlags;
4599 set_error( wine_server_call( req ) );
4600 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
4602 SERVER_END_REQ;
4603 if (ret)
4605 TRACE("\tcreated %04lx\n", ret );
4606 return ret;
4609 if (GetLastError() == WSAEACCES) /* raw socket denied */
4611 if (type == SOCK_RAW)
4612 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
4613 else
4614 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
4615 SetLastError(WSAESOCKTNOSUPPORT);
4618 WARN("\t\tfailed!\n");
4619 return INVALID_SOCKET;
4622 /***********************************************************************
4623 * WSAJoinLeaf (WS2_32.58)
4626 SOCKET WINAPI WSAJoinLeaf(
4627 SOCKET s,
4628 const struct WS_sockaddr *addr,
4629 int addrlen,
4630 LPWSABUF lpCallerData,
4631 LPWSABUF lpCalleeData,
4632 LPQOS lpSQOS,
4633 LPQOS lpGQOS,
4634 DWORD dwFlags)
4636 FIXME("stub.\n");
4637 return INVALID_SOCKET;
4640 /***********************************************************************
4641 * __WSAFDIsSet (WS2_32.151)
4643 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
4645 int i = set->fd_count;
4647 TRACE("(%ld,%p(%i))\n", s, set, i);
4649 while (i--)
4650 if (set->fd_array[i] == s) return 1;
4651 return 0;
4654 /***********************************************************************
4655 * WSAIsBlocking (WS2_32.114)
4657 BOOL WINAPI WSAIsBlocking(void)
4659 /* By default WinSock should set all its sockets to non-blocking mode
4660 * and poll in PeekMessage loop when processing "blocking" ones. This
4661 * function is supposed to tell if the program is in this loop. Our
4662 * blocking calls are truly blocking so we always return FALSE.
4664 * Note: It is allowed to call this function without prior WSAStartup().
4667 TRACE("\n");
4668 return FALSE;
4671 /***********************************************************************
4672 * WSACancelBlockingCall (WS2_32.113)
4674 INT WINAPI WSACancelBlockingCall(void)
4676 TRACE("\n");
4677 return 0;
4680 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
4682 FIXME("How was this called?\n");
4683 return x();
4687 /***********************************************************************
4688 * WSASetBlockingHook (WS2_32.109)
4690 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
4692 FARPROC prev = blocking_hook;
4693 blocking_hook = lpBlockFunc;
4694 TRACE("hook %p\n", lpBlockFunc);
4695 return prev;
4699 /***********************************************************************
4700 * WSAUnhookBlockingHook (WS2_32.110)
4702 INT WINAPI WSAUnhookBlockingHook(void)
4704 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
4705 return 0;
4709 /* ----------------------------------- end of API stuff */
4711 /* ----------------------------------- helper functions -
4713 * TODO: Merge WS_dup_..() stuff into one function that
4714 * would operate with a generic structure containing internal
4715 * pointers (via a template of some kind).
4718 static int list_size(char** l, int item_size)
4720 int i,j = 0;
4721 if(l)
4722 { for(i=0;l[i];i++)
4723 j += (item_size) ? item_size : strlen(l[i]) + 1;
4724 j += (i + 1) * sizeof(char*); }
4725 return j;
4728 static int list_dup(char** l_src, char** l_to, int item_size)
4730 char *p;
4731 int i;
4733 for (i = 0; l_src[i]; i++) ;
4734 p = (char *)(l_to + i + 1);
4735 for (i = 0; l_src[i]; i++)
4737 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
4738 memcpy(p, l_src[i], count);
4739 l_to[i] = p;
4740 p += count;
4742 l_to[i] = NULL;
4743 return p - (char *)l_to;
4746 /* ----- hostent */
4748 /* create a hostent entry
4750 * Creates the entry with enough memory for the name, aliases
4751 * addresses, and the address pointers. Also copies the name
4752 * and sets up all the pointers. If "fill_addresses" is set then
4753 * sufficient memory for the addresses is also allocated and the
4754 * address pointers are set to this memory.
4756 * NOTE: The alias and address lists must be allocated with room
4757 * for the NULL item terminating the list. This is true even if
4758 * the list has no items ("aliases" and "addresses" must be
4759 * at least "1", a truly empty list is invalid).
4761 static struct WS_hostent *WS_create_he(char *name, int aliases, int addresses, int fill_addresses)
4763 struct WS_hostent *p_to;
4764 char *p;
4766 int size = (sizeof(struct WS_hostent) +
4767 strlen(name) + 1 +
4768 sizeof(char *)*aliases +
4769 sizeof(char *)*addresses);
4771 /* Allocate enough memory for the addresses */
4772 if (fill_addresses)
4773 size += sizeof(struct in_addr)*addresses;
4775 if (!(p_to = check_buffer_he(size))) return NULL;
4776 memset(p_to, 0, size);
4778 p = (char *)(p_to + 1);
4779 p_to->h_name = p;
4780 strcpy(p, name);
4781 p += strlen(p) + 1;
4783 p_to->h_aliases = (char **)p;
4784 p += sizeof(char *)*aliases;
4785 p_to->h_addr_list = (char **)p;
4786 p += sizeof(char *)*addresses;
4787 if (fill_addresses)
4789 int i;
4791 /* NOTE: h_aliases must be filled in manually, leave these
4792 * pointers NULL (already set to NULL by memset earlier).
4795 /* Fill in the list of address pointers */
4796 for (i = 0; i < addresses; i++)
4797 p_to->h_addr_list[i] = (p += sizeof(struct in_addr));
4798 p += sizeof(struct in_addr);
4800 return p_to;
4803 /* duplicate hostent entry
4804 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
4805 * Ditto for protoent and servent.
4807 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
4809 int addresses = list_size(p_he->h_addr_list, p_he->h_length);
4810 int aliases = list_size(p_he->h_aliases, 0);
4811 struct WS_hostent *p_to;
4813 p_to = WS_create_he(p_he->h_name, aliases, addresses, FALSE);
4815 if (!p_to) return NULL;
4816 p_to->h_addrtype = p_he->h_addrtype;
4817 p_to->h_length = p_he->h_length;
4819 list_dup(p_he->h_aliases, p_to->h_aliases, 0);
4820 list_dup(p_he->h_addr_list, p_to->h_addr_list, p_he->h_length);
4821 return p_to;
4824 /* ----- protoent */
4826 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
4828 char *p;
4829 struct WS_protoent *p_to;
4831 int size = (sizeof(*p_pe) +
4832 strlen(p_pe->p_name) + 1 +
4833 list_size(p_pe->p_aliases, 0));
4835 if (!(p_to = check_buffer_pe(size))) return NULL;
4836 p_to->p_proto = p_pe->p_proto;
4838 p = (char *)(p_to + 1);
4839 p_to->p_name = p;
4840 strcpy(p, p_pe->p_name);
4841 p += strlen(p) + 1;
4843 p_to->p_aliases = (char **)p;
4844 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
4845 return p_to;
4848 /* ----- servent */
4850 static struct WS_servent *WS_dup_se(const struct servent* p_se)
4852 char *p;
4853 struct WS_servent *p_to;
4855 int size = (sizeof(*p_se) +
4856 strlen(p_se->s_proto) + 1 +
4857 strlen(p_se->s_name) + 1 +
4858 list_size(p_se->s_aliases, 0));
4860 if (!(p_to = check_buffer_se(size))) return NULL;
4861 p_to->s_port = p_se->s_port;
4863 p = (char *)(p_to + 1);
4864 p_to->s_name = p;
4865 strcpy(p, p_se->s_name);
4866 p += strlen(p) + 1;
4868 p_to->s_proto = p;
4869 strcpy(p, p_se->s_proto);
4870 p += strlen(p) + 1;
4872 p_to->s_aliases = (char **)p;
4873 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
4874 return p_to;
4878 /***********************************************************************
4879 * WSARecv (WS2_32.67)
4881 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4882 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
4883 LPWSAOVERLAPPED lpOverlapped,
4884 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
4886 return WSARecvFrom(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
4887 NULL, NULL, lpOverlapped, lpCompletionRoutine);
4890 /***********************************************************************
4891 * WSARecvFrom (WS2_32.69)
4893 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4894 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
4895 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
4896 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4899 unsigned int i, options;
4900 int n, fd, err;
4901 struct ws2_async *wsa;
4902 DWORD timeout_start = GetTickCount();
4903 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
4905 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
4906 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
4907 (lpFromlen ? *lpFromlen : -1),
4908 lpOverlapped, lpCompletionRoutine);
4910 fd = get_sock_fd( s, FILE_READ_DATA, &options );
4911 TRACE( "fd=%d, options=%x\n", fd, options );
4913 if (fd == -1) return SOCKET_ERROR;
4915 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
4917 err = WSAEFAULT;
4918 goto error;
4921 wsa->hSocket = SOCKET2HANDLE(s);
4922 wsa->flags = *lpFlags;
4923 wsa->addr = lpFrom;
4924 wsa->addrlen.ptr = lpFromlen;
4925 wsa->n_iovecs = dwBufferCount;
4926 wsa->first_iovec = 0;
4927 for (i = 0; i < dwBufferCount; i++)
4929 /* check buffer first to trigger write watches */
4930 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
4932 err = WSAEFAULT;
4933 goto error;
4935 wsa->iovec[i].iov_base = lpBuffers[i].buf;
4936 wsa->iovec[i].iov_len = lpBuffers[i].len;
4939 for (;;)
4941 n = WS2_recv( fd, wsa );
4942 if (n == -1)
4944 if (errno == EINTR) continue;
4945 if (errno != EAGAIN)
4947 int loc_errno = errno;
4948 err = wsaErrno();
4949 if (cvalue) WS_AddCompletion( s, cvalue, sock_get_ntstatus(loc_errno), 0 );
4950 goto error;
4953 else
4954 *lpNumberOfBytesRecvd = n;
4956 if ((lpOverlapped || lpCompletionRoutine) &&
4957 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
4959 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
4961 wsa->user_overlapped = lpOverlapped;
4962 wsa->completion_func = lpCompletionRoutine;
4963 release_sock_fd( s, fd );
4965 if (n == -1)
4967 iosb->u.Status = STATUS_PENDING;
4968 iosb->Information = 0;
4970 SERVER_START_REQ( register_async )
4972 req->type = ASYNC_TYPE_READ;
4973 req->async.handle = wine_server_obj_handle( wsa->hSocket );
4974 req->async.callback = wine_server_client_ptr( WS2_async_recv );
4975 req->async.iosb = wine_server_client_ptr( iosb );
4976 req->async.arg = wine_server_client_ptr( wsa );
4977 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
4978 req->async.cvalue = cvalue;
4979 err = wine_server_call( req );
4981 SERVER_END_REQ;
4983 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
4984 WSASetLastError( NtStatusToWSAError( err ));
4985 return SOCKET_ERROR;
4988 iosb->u.Status = STATUS_SUCCESS;
4989 iosb->Information = n;
4990 if (!wsa->completion_func)
4992 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
4993 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
4994 HeapFree( GetProcessHeap(), 0, wsa );
4996 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
4997 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
4998 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4999 return 0;
5002 if (n != -1) break;
5004 if ( _is_blocking(s) )
5006 struct pollfd pfd;
5007 int timeout = GET_RCVTIMEO(fd);
5008 if (timeout != -1)
5010 timeout -= GetTickCount() - timeout_start;
5011 if (timeout < 0) timeout = 0;
5014 pfd.fd = fd;
5015 pfd.events = POLLIN;
5016 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
5018 if (!timeout || !poll( &pfd, 1, timeout ))
5020 err = WSAETIMEDOUT;
5021 /* a timeout is not fatal */
5022 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5023 goto error;
5026 else
5028 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5029 err = WSAEWOULDBLOCK;
5030 goto error;
5034 TRACE(" -> %i bytes\n", n);
5035 HeapFree( GetProcessHeap(), 0, wsa );
5036 release_sock_fd( s, fd );
5037 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
5039 return 0;
5041 error:
5042 HeapFree( GetProcessHeap(), 0, wsa );
5043 release_sock_fd( s, fd );
5044 WARN(" -> ERROR %d\n", err);
5045 WSASetLastError( err );
5046 return SOCKET_ERROR;
5049 /***********************************************************************
5050 * WSCInstallProvider (WS2_32.88)
5052 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
5053 LPCWSTR lpszProviderDllPath,
5054 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
5055 DWORD dwNumberOfEntries,
5056 LPINT lpErrno )
5058 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
5059 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
5060 dwNumberOfEntries, lpErrno);
5061 *lpErrno = 0;
5062 return 0;
5066 /***********************************************************************
5067 * WSCDeinstallProvider (WS2_32.83)
5069 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
5071 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
5072 *lpErrno = 0;
5073 return 0;
5077 /***********************************************************************
5078 * WSAAccept (WS2_32.26)
5080 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
5081 LPCONDITIONPROC lpfnCondition, DWORD dwCallbackData)
5084 int ret = 0, size = 0;
5085 WSABUF CallerId, CallerData, CalleeId, CalleeData;
5086 /* QOS SQOS, GQOS; */
5087 GROUP g;
5088 SOCKET cs;
5089 SOCKADDR src_addr, dst_addr;
5091 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %d\n",
5092 s, addr, addrlen, lpfnCondition, dwCallbackData);
5095 size = sizeof(src_addr);
5096 cs = WS_accept(s, &src_addr, &size);
5098 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
5100 if (!lpfnCondition) return cs;
5102 CallerId.buf = (char *)&src_addr;
5103 CallerId.len = sizeof(src_addr);
5105 CallerData.buf = NULL;
5106 CallerData.len = 0;
5108 WS_getsockname(cs, &dst_addr, &size);
5110 CalleeId.buf = (char *)&dst_addr;
5111 CalleeId.len = sizeof(dst_addr);
5114 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
5115 &CalleeId, &CalleeData, &g, dwCallbackData);
5117 switch (ret)
5119 case CF_ACCEPT:
5120 if (addr && addrlen)
5121 addr = memcpy(addr, &src_addr, (*addrlen > size) ? size : *addrlen );
5122 return cs;
5123 case CF_DEFER:
5124 SERVER_START_REQ( set_socket_deferred )
5126 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
5127 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
5128 if ( !wine_server_call_err ( req ) )
5130 SetLastError( WSATRY_AGAIN );
5131 WS_closesocket( cs );
5134 SERVER_END_REQ;
5135 return SOCKET_ERROR;
5136 case CF_REJECT:
5137 WS_closesocket(cs);
5138 SetLastError(WSAECONNREFUSED);
5139 return SOCKET_ERROR;
5140 default:
5141 FIXME("Unknown return type from Condition function\n");
5142 SetLastError(WSAENOTSOCK);
5143 return SOCKET_ERROR;
5147 /***********************************************************************
5148 * WSADuplicateSocketA (WS2_32.32)
5150 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
5152 HANDLE hProcess;
5154 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
5155 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
5156 /* FIXME: WS_getsockopt(s, WS_SOL_SOCKET, SO_PROTOCOL_INFO, lpProtocolInfo, sizeof(*lpProtocolInfo)); */
5157 /* I don't know what the real Windoze does next, this is a hack */
5158 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
5159 * the target use the global duplicate, or we could copy a reference to us to the structure
5160 * and let the target duplicate it from us, but let's do it as simple as possible */
5161 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
5162 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
5163 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
5164 0, FALSE, DUPLICATE_SAME_ACCESS);
5165 CloseHandle(hProcess);
5166 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
5167 return 0;
5170 /***********************************************************************
5171 * WSADuplicateSocketW (WS2_32.33)
5173 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
5175 HANDLE hProcess;
5177 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
5179 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
5180 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
5181 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
5182 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
5183 0, FALSE, DUPLICATE_SAME_ACCESS);
5184 CloseHandle(hProcess);
5185 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
5186 return 0;
5189 /***********************************************************************
5190 * WSAInstallServiceClassA (WS2_32.48)
5192 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
5194 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
5195 WSASetLastError(WSAEACCES);
5196 return SOCKET_ERROR;
5199 /***********************************************************************
5200 * WSAInstallServiceClassW (WS2_32.49)
5202 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
5204 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
5205 WSASetLastError(WSAEACCES);
5206 return SOCKET_ERROR;
5209 /***********************************************************************
5210 * WSARemoveServiceClass (WS2_32.70)
5212 int WINAPI WSARemoveServiceClass(LPGUID info)
5214 FIXME("Request to remove service %p\n",info);
5215 WSASetLastError(WSATYPE_NOT_FOUND);
5216 return SOCKET_ERROR;
5219 /***********************************************************************
5220 * inet_ntop (WS2_32.@)
5222 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
5224 #ifdef HAVE_INET_NTOP
5225 struct WS_in6_addr *in6;
5226 struct WS_in_addr *in;
5227 PCSTR pdst;
5229 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
5230 if (!buffer)
5232 WSASetLastError( STATUS_INVALID_PARAMETER );
5233 return NULL;
5236 switch (family)
5238 case WS_AF_INET:
5240 in = addr;
5241 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
5242 break;
5244 case WS_AF_INET6:
5246 in6 = addr;
5247 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
5248 break;
5250 default:
5251 WSASetLastError( WSAEAFNOSUPPORT );
5252 return NULL;
5255 if (!pdst) WSASetLastError( STATUS_INVALID_PARAMETER );
5256 return pdst;
5257 #else
5258 FIXME( "not supported on this platform\n" );
5259 WSASetLastError( WSAEAFNOSUPPORT );
5260 return NULL;
5261 #endif
5264 /***********************************************************************
5265 * WSAStringToAddressA (WS2_32.80)
5267 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
5268 INT AddressFamily,
5269 LPWSAPROTOCOL_INFOA lpProtocolInfo,
5270 LPSOCKADDR lpAddress,
5271 LPINT lpAddressLength)
5273 INT res=0;
5274 LPSTR workBuffer=NULL,ptrPort;
5276 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
5277 lpProtocolInfo, lpAddress, lpAddressLength );
5279 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
5281 if (!AddressString)
5283 WSASetLastError(WSAEINVAL);
5284 return SOCKET_ERROR;
5287 if (lpProtocolInfo)
5288 FIXME("ProtocolInfo not implemented.\n");
5290 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
5291 strlen(AddressString) + 1);
5292 if (!workBuffer)
5294 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5295 return SOCKET_ERROR;
5298 strcpy(workBuffer, AddressString);
5300 switch(AddressFamily)
5302 case WS_AF_INET:
5304 struct in_addr inetaddr;
5306 /* If lpAddressLength is too small, tell caller the size we need */
5307 if (*lpAddressLength < sizeof(SOCKADDR_IN))
5309 *lpAddressLength = sizeof(SOCKADDR_IN);
5310 res = WSAEFAULT;
5311 break;
5313 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
5315 ((LPSOCKADDR_IN)lpAddress)->sin_family = AF_INET;
5317 ptrPort = strchr(workBuffer, ':');
5318 if(ptrPort)
5320 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
5321 *ptrPort = '\0';
5323 else
5325 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
5328 if(inet_aton(workBuffer, &inetaddr) > 0)
5330 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
5331 res = 0;
5333 else
5334 res = WSAEINVAL;
5336 break;
5339 case WS_AF_INET6:
5341 struct in6_addr inetaddr;
5342 /* If lpAddressLength is too small, tell caller the size we need */
5343 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
5345 *lpAddressLength = sizeof(SOCKADDR_IN6);
5346 res = WSAEFAULT;
5347 break;
5349 #ifdef HAVE_INET_PTON
5350 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
5352 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
5354 /* This one is a bit tricky. An IPv6 address contains colons, so the
5355 * check from IPv4 doesn't work like that. However, IPv6 addresses that
5356 * contain a port are written with braces like [fd12:3456:7890::1]:12345
5357 * so what we will do is to look for ']', check if the next char is a
5358 * colon, and if it is, parse the port as in IPv4. */
5360 ptrPort = strchr(workBuffer, ']');
5361 if(ptrPort && *(++ptrPort) == ':')
5363 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort+1));
5364 *ptrPort = '\0';
5366 else
5368 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
5371 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
5373 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
5374 sizeof(struct in6_addr));
5375 res = 0;
5377 else
5378 #endif /* HAVE_INET_PTON */
5379 res = WSAEINVAL;
5381 break;
5383 default:
5384 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
5385 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
5386 res = WSAEINVAL;
5389 HeapFree(GetProcessHeap(), 0, workBuffer);
5391 if (!res) return 0;
5392 WSASetLastError(res);
5393 return SOCKET_ERROR;
5396 /***********************************************************************
5397 * WSAStringToAddressW (WS2_32.81)
5399 * Does anybody know if this functions allows to use hebrew/arabic/chinese... digits?
5400 * If this should be the case, it would be required to map these digits
5401 * to Unicode digits (0-9) using FoldString first.
5403 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
5404 INT AddressFamily,
5405 LPWSAPROTOCOL_INFOW lpProtocolInfo,
5406 LPSOCKADDR lpAddress,
5407 LPINT lpAddressLength)
5409 INT sBuffer,res=0;
5410 LPSTR workBuffer=NULL;
5411 WSAPROTOCOL_INFOA infoA;
5412 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
5414 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
5415 lpAddress, lpAddressLength );
5417 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
5419 /* if ProtocolInfo is available - convert to ANSI variant */
5420 if (lpProtocolInfo)
5422 lpProtoInfoA = &infoA;
5423 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
5425 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
5426 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
5428 WSASetLastError( WSAEINVAL);
5429 return SOCKET_ERROR;
5433 if (AddressString)
5435 /* Translate AddressString to ANSI code page - assumes that only
5436 standard digits 0-9 are used with this API call */
5437 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
5438 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
5440 if (workBuffer)
5442 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
5443 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
5444 lpAddress,lpAddressLength);
5445 HeapFree( GetProcessHeap(), 0, workBuffer );
5446 return res;
5448 else
5449 res = WSA_NOT_ENOUGH_MEMORY;
5451 else
5452 res = WSAEINVAL;
5454 WSASetLastError(res);
5455 return SOCKET_ERROR;
5458 /***********************************************************************
5459 * WSAAddressToStringA (WS2_32.27)
5461 * See WSAAddressToStringW
5463 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
5464 LPWSAPROTOCOL_INFOA info, LPSTR string,
5465 LPDWORD lenstr )
5467 DWORD size;
5468 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
5469 CHAR *p;
5471 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
5473 if (!sockaddr) return SOCKET_ERROR;
5474 if (!string || !lenstr) return SOCKET_ERROR;
5476 switch(sockaddr->sa_family)
5478 case WS_AF_INET:
5479 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
5480 sprintf( buffer, "%u.%u.%u.%u:%u",
5481 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
5482 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
5483 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
5484 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
5485 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
5487 p = strchr( buffer, ':' );
5488 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
5489 break;
5491 case WS_AF_INET6:
5493 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
5495 buffer[0] = 0;
5496 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
5497 if ((sockaddr6->sin6_port))
5498 strcpy(buffer, "[");
5499 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, buffer+strlen(buffer), sizeof(buffer)))
5501 WSASetLastError(WSAEINVAL);
5502 return SOCKET_ERROR;
5504 if ((sockaddr6->sin6_scope_id))
5505 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
5506 if ((sockaddr6->sin6_port))
5507 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
5508 break;
5511 default:
5512 WSASetLastError(WSAEINVAL);
5513 return SOCKET_ERROR;
5516 size = strlen( buffer ) + 1;
5518 if (*lenstr < size)
5520 *lenstr = size;
5521 WSASetLastError(WSAEFAULT);
5522 return SOCKET_ERROR;
5525 *lenstr = size;
5526 strcpy( string, buffer );
5527 return 0;
5530 /***********************************************************************
5531 * WSAAddressToStringW (WS2_32.28)
5533 * Convert a sockaddr address into a readable address string.
5535 * PARAMS
5536 * sockaddr [I] Pointer to a sockaddr structure.
5537 * len [I] Size of the sockaddr structure.
5538 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
5539 * string [I/O] Pointer to a buffer to receive the address string.
5540 * lenstr [I/O] Size of the receive buffer in WCHARs.
5542 * RETURNS
5543 * Success: 0
5544 * Failure: SOCKET_ERROR
5546 * NOTES
5547 * The 'info' parameter is ignored.
5549 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
5550 LPWSAPROTOCOL_INFOW info, LPWSTR string,
5551 LPDWORD lenstr )
5553 INT ret;
5554 DWORD size;
5555 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
5556 CHAR bufAddr[54];
5558 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
5560 size = *lenstr;
5561 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
5563 if (ret) return ret;
5565 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
5567 if (*lenstr < size)
5569 *lenstr = size;
5570 WSASetLastError(WSAEFAULT);
5571 return SOCKET_ERROR;
5574 *lenstr = size;
5575 lstrcpyW( string, buffer );
5576 return 0;
5579 /***********************************************************************
5580 * WSAEnumNameSpaceProvidersA (WS2_32.34)
5582 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
5584 FIXME( "(%p %p) Stub!\n", len, buffer );
5585 return 0;
5588 /***********************************************************************
5589 * WSAEnumNameSpaceProvidersW (WS2_32.35)
5591 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
5593 FIXME( "(%p %p) Stub!\n", len, buffer );
5594 return 0;
5597 /***********************************************************************
5598 * WSAGetQOSByName (WS2_32.41)
5600 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
5602 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
5603 return FALSE;
5606 /***********************************************************************
5607 * WSAGetServiceClassInfoA (WS2_32.42)
5609 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
5610 LPWSASERVICECLASSINFOA info )
5612 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
5613 len, info );
5614 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5615 return SOCKET_ERROR;
5618 /***********************************************************************
5619 * WSAGetServiceClassInfoW (WS2_32.43)
5621 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
5622 LPWSASERVICECLASSINFOW info )
5624 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
5625 len, info );
5626 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5627 return SOCKET_ERROR;
5630 /***********************************************************************
5631 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
5633 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
5635 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
5636 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5637 return SOCKET_ERROR;
5640 /***********************************************************************
5641 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
5643 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
5645 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
5646 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5647 return SOCKET_ERROR;
5650 /***********************************************************************
5651 * WSALookupServiceBeginA (WS2_32.59)
5653 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
5654 DWORD dwControlFlags,
5655 LPHANDLE lphLookup)
5657 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
5658 lphLookup);
5659 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5660 return SOCKET_ERROR;
5663 /***********************************************************************
5664 * WSALookupServiceBeginW (WS2_32.60)
5666 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
5667 DWORD dwControlFlags,
5668 LPHANDLE lphLookup)
5670 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
5671 lphLookup);
5672 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5673 return SOCKET_ERROR;
5676 /***********************************************************************
5677 * WSALookupServiceBeginW (WS2_32.61)
5679 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
5681 FIXME("(%p) Stub!\n", lookup );
5682 return 0;
5685 /***********************************************************************
5686 * WSALookupServiceNextA (WS2_32.62)
5688 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
5690 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
5691 return 0;
5694 /***********************************************************************
5695 * WSALookupServiceNextW (WS2_32.63)
5697 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
5699 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
5700 return 0;
5703 /***********************************************************************
5704 * WSANtohl (WS2_32.64)
5706 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
5708 TRACE( "(0x%04lx 0x%08x %p)\n", s, netlong, lphostlong );
5710 if (!lphostlong) return WSAEFAULT;
5712 *lphostlong = ntohl( netlong );
5713 return 0;
5716 /***********************************************************************
5717 * WSANtohs (WS2_32.65)
5719 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
5721 TRACE( "(0x%04lx 0x%08x %p)\n", s, netshort, lphostshort );
5723 if (!lphostshort) return WSAEFAULT;
5725 *lphostshort = ntohs( netshort );
5726 return 0;
5729 /***********************************************************************
5730 * WSAProviderConfigChange (WS2_32.66)
5732 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
5733 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
5735 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
5736 return SOCKET_ERROR;
5739 /***********************************************************************
5740 * WSARecvDisconnect (WS2_32.68)
5742 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
5744 TRACE( "(0x%04lx %p)\n", s, disconnectdata );
5746 return WS_shutdown( s, 0 );
5749 /***********************************************************************
5750 * WSASetServiceA (WS2_32.76)
5752 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
5754 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
5755 return 0;
5758 /***********************************************************************
5759 * WSASetServiceW (WS2_32.77)
5761 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
5763 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
5764 return 0;
5767 /***********************************************************************
5768 * WSCEnableNSProvider (WS2_32.84)
5770 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
5772 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
5773 return 0;
5776 /***********************************************************************
5777 * WSCGetProviderPath (WS2_32.86)
5779 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
5781 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
5783 if (!errcode || !provider || !len) return WSAEFAULT;
5785 *errcode = WSAEINVAL;
5786 return SOCKET_ERROR;
5789 /***********************************************************************
5790 * WSCInstallNameSpace (WS2_32.87)
5792 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
5793 DWORD version, LPGUID provider )
5795 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
5796 namespace, version, debugstr_guid(provider) );
5797 return 0;
5800 /***********************************************************************
5801 * WSCUnInstallNameSpace (WS2_32.89)
5803 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
5805 FIXME("(%p) Stub!\n", lpProviderId);
5806 return NO_ERROR;
5809 /***********************************************************************
5810 * WSCWriteProviderOrder (WS2_32.91)
5812 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
5814 FIXME("(%p 0x%08x) Stub!\n", entry, number);
5815 return 0;