More spelling fixes.
[wine/multimedia.git] / dlls / ws2_32 / socket.c
blobf82ecc549fcae9146f1e47f326f515ee215e7552
1 /*
2 * based on Windows Sockets 1.1 specs
3 * (ftp.microsoft.com:/Advsys/winsock/spec11/WINSOCK.TXT)
5 * Copyright (C) 1993,1994,1996,1997 John Brezak, Erik Bos, Alex Korobka.
6 * Copyright (C) 2005 Marcus Meissner
7 * Copyright (C) 2006 Kai Blin
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23 * NOTE: If you make any changes to fix a particular app, make sure
24 * they don't break something else like Netscape or telnet and ftp
25 * clients and servers (www.winsite.com got a lot of those).
28 #include "config.h"
29 #include "wine/port.h"
31 #include <stdarg.h>
32 #include <stdio.h>
33 #include <string.h>
34 #include <sys/types.h>
35 #ifdef HAVE_SYS_IPC_H
36 # include <sys/ipc.h>
37 #endif
38 #ifdef HAVE_SYS_IOCTL_H
39 # include <sys/ioctl.h>
40 #endif
41 #ifdef HAVE_SYS_FILIO_H
42 # include <sys/filio.h>
43 #endif
44 #ifdef HAVE_SYS_SOCKIO_H
45 # include <sys/sockio.h>
46 #endif
48 #if defined(__EMX__)
49 # include <sys/so_ioctl.h>
50 #endif
52 #ifdef HAVE_SYS_PARAM_H
53 # include <sys/param.h>
54 #endif
56 #ifdef HAVE_SYS_MSG_H
57 # include <sys/msg.h>
58 #endif
59 #ifdef HAVE_SYS_WAIT_H
60 # include <sys/wait.h>
61 #endif
62 #ifdef HAVE_SYS_UIO_H
63 # include <sys/uio.h>
64 #endif
65 #ifdef HAVE_SYS_SOCKET_H
66 #include <sys/socket.h>
67 #endif
68 #ifdef HAVE_NETINET_IN_H
69 # include <netinet/in.h>
70 #endif
71 #ifdef HAVE_NETINET_TCP_H
72 # include <netinet/tcp.h>
73 #endif
74 #ifdef HAVE_ARPA_INET_H
75 # include <arpa/inet.h>
76 #endif
77 #include <ctype.h>
78 #include <fcntl.h>
79 #include <errno.h>
80 #ifdef HAVE_SYS_ERRNO_H
81 #include <sys/errno.h>
82 #endif
83 #ifdef HAVE_NETDB_H
84 #include <netdb.h>
85 #endif
86 #ifdef HAVE_UNISTD_H
87 # include <unistd.h>
88 #endif
89 #include <stdlib.h>
90 #ifdef HAVE_ARPA_NAMESER_H
91 # include <arpa/nameser.h>
92 #endif
93 #ifdef HAVE_RESOLV_H
94 # include <resolv.h>
95 #endif
96 #ifdef HAVE_NET_IF_H
97 # include <net/if.h>
98 #endif
100 #ifdef HAVE_NETIPX_IPX_H
101 # include <netipx/ipx.h>
102 # define HAVE_IPX
103 #elif defined(HAVE_LINUX_IPX_H)
104 # ifdef HAVE_ASM_TYPES_H
105 # include <asm/types.h>
106 # endif
107 # include <linux/ipx.h>
108 # define HAVE_IPX
109 #endif
111 #ifdef HAVE_POLL_H
112 #include <poll.h>
113 #endif
114 #ifdef HAVE_SYS_POLL_H
115 # include <sys/poll.h>
116 #endif
117 #ifdef HAVE_SYS_TIME_H
118 # include <sys/time.h>
119 #endif
121 #define NONAMELESSUNION
122 #define NONAMELESSSTRUCT
123 #include "ntstatus.h"
124 #define WIN32_NO_STATUS
125 #include "windef.h"
126 #include "winbase.h"
127 #include "wingdi.h"
128 #include "winuser.h"
129 #include "winerror.h"
130 #include "winnls.h"
131 #include "winsock2.h"
132 #include "mswsock.h"
133 #include "ws2tcpip.h"
134 #include "ws2spi.h"
135 #include "wsipx.h"
136 #include "winnt.h"
137 #include "iphlpapi.h"
138 #include "wine/server.h"
139 #include "wine/debug.h"
140 #include "wine/unicode.h"
142 #ifdef HAVE_IPX
143 # include "wsnwlink.h"
144 #endif
147 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
148 # define sipx_network sipx_addr.x_net
149 # define sipx_node sipx_addr.x_host.c_host
150 #endif /* __FreeBSD__ */
152 #ifndef INADDR_NONE
153 #define INADDR_NONE ~0UL
154 #endif
156 WINE_DEFAULT_DEBUG_CHANNEL(winsock);
158 /* critical section to protect some non-reentrant net function */
159 extern CRITICAL_SECTION csWSgetXXXbyYYY;
161 union generic_unix_sockaddr
163 struct sockaddr addr;
164 char data[128]; /* should be big enough for all families */
167 static inline const char *debugstr_sockaddr( const struct WS_sockaddr *a )
169 if (!a) return "(nil)";
170 return wine_dbg_sprintf("{ family %d, address %s, port %d }",
171 ((const struct sockaddr_in *)a)->sin_family,
172 inet_ntoa(((const struct sockaddr_in *)a)->sin_addr),
173 ntohs(((const struct sockaddr_in *)a)->sin_port));
176 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
177 #define SOCKET2HANDLE(s) ((HANDLE)(s))
178 #define HANDLE2SOCKET(h) ((SOCKET)(h))
180 /****************************************************************
181 * Async IO declarations
182 ****************************************************************/
184 typedef struct ws2_async
186 HANDLE hSocket;
187 int type;
188 LPWSAOVERLAPPED user_overlapped;
189 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
190 IO_STATUS_BLOCK local_iosb;
191 struct iovec iovec[WS_MSG_MAXIOVLEN];
192 int n_iovecs;
193 struct WS_sockaddr *addr;
194 union
196 int val; /* for send operations */
197 int *ptr; /* for recv operations */
198 } addrlen;
199 DWORD flags;
200 } ws2_async;
202 /****************************************************************/
204 /* ----------------------------------- internal data */
206 /* ws_... struct conversion flags */
208 typedef struct /* WSAAsyncSelect() control struct */
210 HANDLE service, event, sock;
211 HWND hWnd;
212 UINT uMsg;
213 LONG lEvent;
214 } ws_select_info;
216 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
217 #define WS_MAX_UDP_DATAGRAM 1024
218 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
220 /* hostent's, servent's and protent's are stored in one buffer per thread,
221 * as documented on MSDN for the functions that return any of the buffers */
222 struct per_thread_data
224 int opentype;
225 struct WS_hostent *he_buffer;
226 struct WS_servent *se_buffer;
227 struct WS_protoent *pe_buffer;
228 int he_len;
229 int se_len;
230 int pe_len;
233 static INT num_startup; /* reference counter */
234 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
236 /* function prototypes */
237 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
238 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
239 static struct WS_servent *WS_dup_se(const struct servent* p_se);
241 int WSAIOCTL_GetInterfaceCount(void);
242 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
244 UINT wsaErrno(void);
245 UINT wsaHerrno(int errnr);
247 #define MAP_OPTION(opt) { WS_##opt, opt }
249 static const int ws_sock_map[][2] =
251 MAP_OPTION( SO_DEBUG ),
252 MAP_OPTION( SO_ACCEPTCONN ),
253 MAP_OPTION( SO_REUSEADDR ),
254 MAP_OPTION( SO_KEEPALIVE ),
255 MAP_OPTION( SO_DONTROUTE ),
256 MAP_OPTION( SO_BROADCAST ),
257 MAP_OPTION( SO_LINGER ),
258 MAP_OPTION( SO_OOBINLINE ),
259 MAP_OPTION( SO_SNDBUF ),
260 MAP_OPTION( SO_RCVBUF ),
261 MAP_OPTION( SO_ERROR ),
262 MAP_OPTION( SO_TYPE ),
263 #ifdef SO_RCVTIMEO
264 MAP_OPTION( SO_RCVTIMEO ),
265 #endif
266 #ifdef SO_SNDTIMEO
267 MAP_OPTION( SO_SNDTIMEO ),
268 #endif
271 static const int ws_tcp_map[][2] =
273 #ifdef TCP_NODELAY
274 MAP_OPTION( TCP_NODELAY ),
275 #endif
278 static const int ws_ip_map[][2] =
280 MAP_OPTION( IP_MULTICAST_IF ),
281 MAP_OPTION( IP_MULTICAST_TTL ),
282 MAP_OPTION( IP_MULTICAST_LOOP ),
283 MAP_OPTION( IP_ADD_MEMBERSHIP ),
284 MAP_OPTION( IP_DROP_MEMBERSHIP ),
285 MAP_OPTION( IP_OPTIONS ),
286 #ifdef IP_HDRINCL
287 MAP_OPTION( IP_HDRINCL ),
288 #endif
289 MAP_OPTION( IP_TOS ),
290 MAP_OPTION( IP_TTL ),
293 static const int ws_af_map[][2] =
295 MAP_OPTION( AF_UNSPEC ),
296 MAP_OPTION( AF_INET ),
297 MAP_OPTION( AF_INET6 ),
298 #ifdef HAVE_IPX
299 MAP_OPTION( AF_IPX ),
300 #endif
303 static const int ws_socktype_map[][2] =
305 MAP_OPTION( SOCK_DGRAM ),
306 MAP_OPTION( SOCK_STREAM ),
307 MAP_OPTION( SOCK_RAW ),
310 static const int ws_proto_map[][2] =
312 MAP_OPTION( IPPROTO_IP ),
313 MAP_OPTION( IPPROTO_TCP ),
314 MAP_OPTION( IPPROTO_UDP ),
315 MAP_OPTION( IPPROTO_ICMP ),
316 MAP_OPTION( IPPROTO_IGMP ),
317 MAP_OPTION( IPPROTO_RAW ),
320 static const int ws_aiflag_map[][2] =
322 MAP_OPTION( AI_PASSIVE ),
323 MAP_OPTION( AI_CANONNAME ),
324 MAP_OPTION( AI_NUMERICHOST ),
325 /* Linux/UNIX knows a lot more. But Windows only
326 * has 3 as far as I could see. -Marcus
330 static const int ws_niflag_map[][2] =
332 MAP_OPTION( NI_NOFQDN ),
333 MAP_OPTION( NI_NUMERICHOST ),
334 MAP_OPTION( NI_NAMEREQD ),
335 MAP_OPTION( NI_NUMERICSERV ),
336 MAP_OPTION( NI_DGRAM ),
339 static const int ws_eai_map[][2] =
341 MAP_OPTION( EAI_AGAIN ),
342 MAP_OPTION( EAI_BADFLAGS ),
343 MAP_OPTION( EAI_FAIL ),
344 MAP_OPTION( EAI_FAMILY ),
345 MAP_OPTION( EAI_MEMORY ),
346 /* Note: EAI_NODATA is deprecated, but still
347 * used by Windows and Linux... We map the newer
348 * EAI_NONAME to EAI_NODATA for now until Windows
349 * changes too.
351 #ifdef EAI_NODATA
352 MAP_OPTION( EAI_NODATA ),
353 #endif
354 #ifdef EAI_NONAME
355 { WS_EAI_NODATA, EAI_NONAME },
356 #endif
358 MAP_OPTION( EAI_SERVICE ),
359 MAP_OPTION( EAI_SOCKTYPE ),
360 { 0, 0 }
363 static inline DWORD NtStatusToWSAError( const DWORD status )
365 /* We only need to cover the status codes set by server async request handling */
366 DWORD wserr;
367 switch ( status )
369 case STATUS_SUCCESS: wserr = 0; break;
370 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
371 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
372 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
373 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
374 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
375 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
376 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
377 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
378 default:
379 if ( status >= WSABASEERR && status <= WSABASEERR+1004 )
380 /* It is not an NT status code but a winsock error */
381 wserr = status;
382 else
384 wserr = RtlNtStatusToDosError( status );
385 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
388 return wserr;
391 /* set last error code from NT status without mapping WSA errors */
392 static inline unsigned int set_error( unsigned int err )
394 if (err)
396 err = NtStatusToWSAError( err );
397 SetLastError( err );
399 return err;
402 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
404 int fd;
405 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
406 return -1;
407 return fd;
410 static inline void release_sock_fd( SOCKET s, int fd )
412 wine_server_release_fd( SOCKET2HANDLE(s), fd );
415 static void _enable_event( HANDLE s, unsigned int event,
416 unsigned int sstate, unsigned int cstate )
418 SERVER_START_REQ( enable_socket_event )
420 req->handle = s;
421 req->mask = event;
422 req->sstate = sstate;
423 req->cstate = cstate;
424 wine_server_call( req );
426 SERVER_END_REQ;
429 static int _is_blocking(SOCKET s)
431 int ret;
432 SERVER_START_REQ( get_socket_event )
434 req->handle = SOCKET2HANDLE(s);
435 req->service = FALSE;
436 req->c_event = 0;
437 wine_server_call( req );
438 ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
440 SERVER_END_REQ;
441 return ret;
444 static unsigned int _get_sock_mask(SOCKET s)
446 unsigned int ret;
447 SERVER_START_REQ( get_socket_event )
449 req->handle = SOCKET2HANDLE(s);
450 req->service = FALSE;
451 req->c_event = 0;
452 wine_server_call( req );
453 ret = reply->mask;
455 SERVER_END_REQ;
456 return ret;
459 static void _sync_sock_state(SOCKET s)
461 /* do a dummy wineserver request in order to let
462 the wineserver run through its select loop once */
463 (void)_is_blocking(s);
466 static int _get_sock_error(SOCKET s, unsigned int bit)
468 int events[FD_MAX_EVENTS];
470 SERVER_START_REQ( get_socket_event )
472 req->handle = SOCKET2HANDLE(s);
473 req->service = FALSE;
474 req->c_event = 0;
475 wine_server_set_reply( req, events, sizeof(events) );
476 wine_server_call( req );
478 SERVER_END_REQ;
479 return events[bit];
482 static struct per_thread_data *get_per_thread_data(void)
484 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
485 /* lazy initialization */
486 if (!ptb)
488 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
489 NtCurrentTeb()->WinSockData = ptb;
491 return ptb;
494 static void free_per_thread_data(void)
496 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
498 if (!ptb) return;
500 /* delete scratch buffers */
501 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
502 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
503 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
504 ptb->he_buffer = NULL;
505 ptb->se_buffer = NULL;
506 ptb->pe_buffer = NULL;
508 HeapFree( GetProcessHeap(), 0, ptb );
509 NtCurrentTeb()->WinSockData = NULL;
512 /***********************************************************************
513 * DllMain (WS2_32.init)
515 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
517 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
518 switch (fdwReason) {
519 case DLL_PROCESS_ATTACH:
520 break;
521 case DLL_PROCESS_DETACH:
522 free_per_thread_data();
523 num_startup = 0;
524 break;
525 case DLL_THREAD_DETACH:
526 free_per_thread_data();
527 break;
529 return TRUE;
532 /***********************************************************************
533 * convert_sockopt()
535 * Converts socket flags from Windows format.
536 * Return 1 if converted, 0 if not (error).
538 static int convert_sockopt(INT *level, INT *optname)
540 int i;
541 switch (*level)
543 case WS_SOL_SOCKET:
544 *level = SOL_SOCKET;
545 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
546 if( ws_sock_map[i][0] == *optname )
548 *optname = ws_sock_map[i][1];
549 return 1;
552 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
553 break;
554 case WS_IPPROTO_TCP:
555 *level = IPPROTO_TCP;
556 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
557 if ( ws_tcp_map[i][0] == *optname )
559 *optname = ws_tcp_map[i][1];
560 return 1;
563 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
564 break;
565 case WS_IPPROTO_IP:
566 *level = IPPROTO_IP;
567 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
568 if (ws_ip_map[i][0] == *optname )
570 *optname = ws_ip_map[i][1];
571 return 1;
574 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
575 break;
576 default: FIXME("Unimplemented or unknown socket level\n");
578 return 0;
581 static inline BOOL is_timeout_option( int optname )
583 #ifdef SO_RCVTIMEO
584 if (optname == SO_RCVTIMEO) return TRUE;
585 #endif
586 #ifdef SO_SNDTIMEO
587 if (optname == SO_SNDTIMEO) return TRUE;
588 #endif
589 return FALSE;
592 /* ----------------------------------- Per-thread info (or per-process?) */
594 static char *strdup_lower(const char *str)
596 int i;
597 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
599 if (ret)
601 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
602 ret[i] = 0;
604 else SetLastError(WSAENOBUFS);
605 return ret;
608 static inline int sock_error_p(int s)
610 unsigned int optval, optlen;
612 optlen = sizeof(optval);
613 getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
614 if (optval) WARN("\t[%i] error: %d\n", s, optval);
615 return optval != 0;
618 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
619 * from an fd and return the value converted to milli seconds
620 * or -1 if there is an infinite time out */
621 static inline int get_rcvsnd_timeo( int fd, int optname)
623 struct timeval tv;
624 unsigned int len = sizeof(tv);
625 int ret = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
626 if( ret >= 0)
627 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
628 if( ret <= 0 ) /* tv == {0,0} means infinite time out */
629 return -1;
630 return ret;
633 /* macro wrappers for portability */
634 #ifdef SO_RCVTIMEO
635 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
636 #else
637 #define GET_RCVTIMEO(fd) (-1)
638 #endif
640 #ifdef SO_SNDTIMEO
641 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
642 #else
643 #define GET_SNDTIMEO(fd) (-1)
644 #endif
646 /* utility: given an fd, will block until one of the events occurs */
647 static inline int do_block( int fd, int events, int timeout )
649 struct pollfd pfd;
650 int ret;
652 pfd.fd = fd;
653 pfd.events = events;
655 while ((ret = poll(&pfd, 1, timeout)) < 0)
657 if (errno != EINTR)
658 return -1;
660 if( ret == 0 )
661 return 0;
662 return pfd.revents;
665 static int
666 convert_af_w2u(int windowsaf) {
667 int i;
669 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
670 if (ws_af_map[i][0] == windowsaf)
671 return ws_af_map[i][1];
672 FIXME("unhandled Windows address family %d\n", windowsaf);
673 return -1;
676 static int
677 convert_af_u2w(int unixaf) {
678 int i;
680 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
681 if (ws_af_map[i][1] == unixaf)
682 return ws_af_map[i][0];
683 FIXME("unhandled UNIX address family %d\n", unixaf);
684 return -1;
687 static int
688 convert_proto_w2u(int windowsproto) {
689 int i;
691 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
692 if (ws_proto_map[i][0] == windowsproto)
693 return ws_proto_map[i][1];
694 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
695 return -1;
698 static int
699 convert_proto_u2w(int unixproto) {
700 int i;
702 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
703 if (ws_proto_map[i][1] == unixproto)
704 return ws_proto_map[i][0];
705 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
706 return -1;
709 static int
710 convert_socktype_w2u(int windowssocktype) {
711 int i;
713 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
714 if (ws_socktype_map[i][0] == windowssocktype)
715 return ws_socktype_map[i][1];
716 FIXME("unhandled Windows socket type %d\n", windowssocktype);
717 return -1;
720 static int
721 convert_socktype_u2w(int unixsocktype) {
722 int i;
724 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
725 if (ws_socktype_map[i][1] == unixsocktype)
726 return ws_socktype_map[i][0];
727 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
728 return -1;
731 /* ----------------------------------- API -----
733 * Init / cleanup / error checking.
736 /***********************************************************************
737 * WSAStartup (WS2_32.115)
739 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
741 TRACE("verReq=%x\n", wVersionRequested);
743 if (LOBYTE(wVersionRequested) < 1)
744 return WSAVERNOTSUPPORTED;
746 if (!lpWSAData) return WSAEINVAL;
748 num_startup++;
750 /* that's the whole of the negotiation for now */
751 lpWSAData->wVersion = wVersionRequested;
752 /* return winsock information */
753 lpWSAData->wHighVersion = 0x0202;
754 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
755 strcpy(lpWSAData->szSystemStatus, "Running" );
756 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
757 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
758 /* don't do anything with lpWSAData->lpVendorInfo */
759 /* (some apps don't allocate the space for this field) */
761 TRACE("succeeded\n");
762 return 0;
766 /***********************************************************************
767 * WSACleanup (WS2_32.116)
769 INT WINAPI WSACleanup(void)
771 if (num_startup) {
772 num_startup--;
773 return 0;
775 SetLastError(WSANOTINITIALISED);
776 return SOCKET_ERROR;
780 /***********************************************************************
781 * WSAGetLastError (WINSOCK.111)
782 * WSAGetLastError (WS2_32.111)
784 INT WINAPI WSAGetLastError(void)
786 return GetLastError();
789 /***********************************************************************
790 * WSASetLastError (WS2_32.112)
792 void WINAPI WSASetLastError(INT iError) {
793 SetLastError(iError);
796 static struct WS_hostent *check_buffer_he(int size)
798 struct per_thread_data * ptb = get_per_thread_data();
799 if (ptb->he_buffer)
801 if (ptb->he_len >= size ) return ptb->he_buffer;
802 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
804 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
805 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
806 return ptb->he_buffer;
809 static struct WS_servent *check_buffer_se(int size)
811 struct per_thread_data * ptb = get_per_thread_data();
812 if (ptb->se_buffer)
814 if (ptb->se_len >= size ) return ptb->se_buffer;
815 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
817 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
818 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
819 return ptb->se_buffer;
822 static struct WS_protoent *check_buffer_pe(int size)
824 struct per_thread_data * ptb = get_per_thread_data();
825 if (ptb->pe_buffer)
827 if (ptb->pe_len >= size ) return ptb->pe_buffer;
828 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
830 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
831 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
832 return ptb->pe_buffer;
835 /* ----------------------------------- i/o APIs */
837 #ifdef HAVE_IPX
838 #define SUPPORTED_PF(pf) ((pf)==WS_AF_INET || (pf)== WS_AF_IPX || (pf) == WS_AF_INET6)
839 #else
840 #define SUPPORTED_PF(pf) ((pf)==WS_AF_INET || (pf) == WS_AF_INET6)
841 #endif
844 /**********************************************************************/
846 /* Returns the length of the converted address if successful, 0 if it was too small to
847 * start with.
849 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
850 union generic_unix_sockaddr *uaddr)
852 unsigned int uaddrlen = 0;
854 switch (wsaddr->sa_family)
856 #ifdef HAVE_IPX
857 case WS_AF_IPX:
859 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
860 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
862 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
863 return 0;
865 uaddrlen = sizeof(struct sockaddr_ipx);
866 memset( uaddr, 0, uaddrlen );
867 uipx->sipx_family=AF_IPX;
868 uipx->sipx_port=wsipx->sa_socket;
869 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
870 * in one go
872 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
873 #ifdef IPX_FRAME_NONE
874 uipx->sipx_type=IPX_FRAME_NONE;
875 #endif
876 break;
878 #endif
879 case WS_AF_INET6: {
880 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
881 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
883 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
884 * scope_id, one without. Check:
885 * http://msdn.microsoft.com/library/en-us/winsock/winsock/sockaddr_2.asp
887 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
888 uaddrlen = sizeof(struct sockaddr_in6);
889 memset( uaddr, 0, uaddrlen );
890 uin6->sin6_family = AF_INET6;
891 uin6->sin6_port = win6->sin6_port;
892 uin6->sin6_flowinfo = win6->sin6_flowinfo;
893 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
894 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
895 #endif
896 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
897 break;
899 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
900 return 0;
902 case WS_AF_INET: {
903 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
904 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
906 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
907 return 0;
908 uaddrlen = sizeof(struct sockaddr_in);
909 memset( uaddr, 0, uaddrlen );
910 uin->sin_family = AF_INET;
911 uin->sin_port = win->sin_port;
912 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
913 break;
915 case WS_AF_UNSPEC: {
916 /* Try to determine the needed space by the passed windows sockaddr space */
917 switch (wsaddrlen) {
918 default: /* likely a ipv4 address */
919 case sizeof(struct WS_sockaddr_in):
920 uaddrlen = sizeof(struct sockaddr_in);
921 break;
922 #ifdef HAVE_IPX
923 case sizeof(struct WS_sockaddr_ipx):
924 uaddrlen = sizeof(struct sockaddr_ipx);
925 break;
926 #endif
927 case sizeof(struct WS_sockaddr_in6):
928 case sizeof(struct WS_sockaddr_in6_old):
929 uaddrlen = sizeof(struct sockaddr_in6);
930 break;
932 memset( uaddr, 0, uaddrlen );
933 break;
935 default:
936 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
937 return 0;
939 return uaddrlen;
942 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
944 switch (uaddr->sa_family)
946 #ifdef HAVE_IPX
947 case AF_IPX:
948 FIXME("don't know how to tell if IPX socket is bound, assuming it is!\n");
949 return TRUE;
950 #endif
951 case AF_INET6:
953 static const struct sockaddr_in6 emptyAddr;
954 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
955 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
957 case AF_INET:
959 static const struct sockaddr_in emptyAddr;
960 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
961 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
963 case AF_UNSPEC:
964 return FALSE;
965 default:
966 FIXME("unknown address family %d\n", uaddr->sa_family);
967 return TRUE;
971 /* Returns 0 if successful, -1 if the buffer is too small */
972 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
974 int res;
976 switch(uaddr->sa_family)
978 #ifdef HAVE_IPX
979 case AF_IPX:
981 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
982 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
984 res=-1;
985 switch (*wsaddrlen) /* how much can we copy? */
987 default:
988 res=0; /* enough */
989 *wsaddrlen = sizeof(*wsipx);
990 wsipx->sa_socket=uipx->sipx_port;
991 /* fall through */
992 case 13:
993 case 12:
994 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
995 /* fall through */
996 case 11:
997 case 10:
998 case 9:
999 case 8:
1000 case 7:
1001 case 6:
1002 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1003 /* fall through */
1004 case 5:
1005 case 4:
1006 case 3:
1007 case 2:
1008 wsipx->sa_family=WS_AF_IPX;
1009 /* fall through */
1010 case 1:
1011 case 0:
1012 /* way too small */
1013 break;
1016 break;
1017 #endif
1018 case AF_INET6: {
1019 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1020 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1022 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1023 return -1;
1024 win6old->sin6_family = WS_AF_INET6;
1025 win6old->sin6_port = uin6->sin6_port;
1026 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1027 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1028 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1029 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1030 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1031 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1032 win6->sin6_scope_id = uin6->sin6_scope_id;
1033 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1035 #endif
1036 return 0;
1038 case AF_INET: {
1039 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1040 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1042 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1043 return -1;
1044 win->sin_family = WS_AF_INET;
1045 win->sin_port = uin->sin_port;
1046 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1047 memset(&win->sin_zero, 0, 8); /* Make sure the null padding is null */
1048 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1049 return 0;
1051 case AF_UNSPEC: {
1052 memset(wsaddr,0,*wsaddrlen);
1053 return 0;
1055 default:
1056 FIXME("Unknown address family %d\n", uaddr->sa_family);
1057 return -1;
1059 return res;
1062 /**************************************************************************
1063 * Functions for handling overlapped I/O
1064 **************************************************************************/
1066 /* user APC called upon async completion */
1067 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1069 ws2_async *wsa = arg;
1071 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
1072 iosb->Information, wsa->user_overlapped,
1073 wsa->flags );
1074 HeapFree( GetProcessHeap(), 0, wsa );
1077 /***********************************************************************
1078 * WS2_recv (INTERNAL)
1080 * Workhorse for both synchronous and asynchronous recv() operations.
1082 static int WS2_recv( int fd, struct iovec* iov, int count,
1083 struct WS_sockaddr *lpFrom, LPINT lpFromlen,
1084 LPDWORD lpFlags )
1086 struct msghdr hdr;
1087 union generic_unix_sockaddr unix_sockaddr;
1088 int n;
1090 hdr.msg_name = NULL;
1092 if ( lpFrom )
1094 hdr.msg_namelen = sizeof(unix_sockaddr);
1095 hdr.msg_name = &unix_sockaddr;
1097 else
1098 hdr.msg_namelen = 0;
1100 hdr.msg_iov = iov;
1101 hdr.msg_iovlen = count;
1102 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1103 hdr.msg_accrights = NULL;
1104 hdr.msg_accrightslen = 0;
1105 #else
1106 hdr.msg_control = NULL;
1107 hdr.msg_controllen = 0;
1108 hdr.msg_flags = 0;
1109 #endif
1111 if ( (n = recvmsg(fd, &hdr, *lpFlags)) == -1 )
1112 return -1;
1114 if ( lpFrom &&
1115 ws_sockaddr_u2ws( &unix_sockaddr.addr, lpFrom, lpFromlen ) != 0 )
1117 /* The from buffer was too small, but we read the data
1118 * anyway. Is that really bad?
1122 return n;
1125 /***********************************************************************
1126 * WS2_async_recv (INTERNAL)
1128 * Handler for overlapped recv() operations.
1130 static NTSTATUS WS2_async_recv( void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, ULONG_PTR *total )
1132 ws2_async* wsa = user;
1133 int result = 0, fd;
1135 switch (status)
1137 case STATUS_ALERTED:
1138 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
1139 break;
1141 result = WS2_recv( fd, wsa->iovec, wsa->n_iovecs,
1142 wsa->addr, wsa->addrlen.ptr, &wsa->flags );
1143 wine_server_release_fd( wsa->hSocket, fd );
1144 if (result >= 0)
1146 status = STATUS_SUCCESS;
1147 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1149 else
1151 if (errno == EINTR || errno == EAGAIN)
1153 status = STATUS_PENDING;
1154 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1156 else
1158 result = 0;
1159 status = wsaErrno(); /* FIXME: is this correct ???? */
1162 break;
1164 if (status != STATUS_PENDING)
1166 iosb->u.Status = status;
1167 iosb->Information = *total = result;
1169 return status;
1172 /***********************************************************************
1173 * WS2_send (INTERNAL)
1175 * Workhorse for both synchronous and asynchronous send() operations.
1177 static int WS2_send( int fd, struct iovec* iov, int count,
1178 const struct WS_sockaddr *to, INT tolen, DWORD dwFlags )
1180 struct msghdr hdr;
1181 union generic_unix_sockaddr unix_addr;
1184 hdr.msg_name = NULL;
1185 hdr.msg_namelen = 0;
1187 if ( to )
1189 hdr.msg_name = &unix_addr;
1190 hdr.msg_namelen = ws_sockaddr_ws2u( to, tolen, &unix_addr );
1191 if ( !hdr.msg_namelen )
1193 errno = EFAULT;
1194 return -1;
1197 #if defined(HAVE_IPX) && defined(SOL_IPX)
1198 if(to->sa_family == WS_AF_IPX)
1200 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
1201 int val=0;
1202 unsigned int len=sizeof(int);
1204 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
1205 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
1206 * the packet type and then we can retrieve it using getsockopt. After that we can set the
1207 * ipx type in the sockaddr_opx structure with the stored value.
1209 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
1210 uipx->sipx_type = val;
1212 #endif
1215 hdr.msg_iov = iov;
1216 hdr.msg_iovlen = count;
1217 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1218 hdr.msg_accrights = NULL;
1219 hdr.msg_accrightslen = 0;
1220 #else
1221 hdr.msg_control = NULL;
1222 hdr.msg_controllen = 0;
1223 hdr.msg_flags = 0;
1224 #endif
1226 return sendmsg(fd, &hdr, dwFlags);
1229 /***********************************************************************
1230 * WS2_async_send (INTERNAL)
1232 * Handler for overlapped send() operations.
1234 static NTSTATUS WS2_async_send(void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, ULONG_PTR *total )
1236 ws2_async* wsa = user;
1237 int result = 0, fd;
1239 switch (status)
1241 case STATUS_ALERTED:
1242 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
1243 break;
1245 /* check to see if the data is ready (non-blocking) */
1246 result = WS2_send( fd, wsa->iovec, wsa->n_iovecs, wsa->addr, wsa->addrlen.val, wsa->flags );
1247 wine_server_release_fd( wsa->hSocket, fd );
1249 if (result >= 0)
1251 status = STATUS_SUCCESS;
1252 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1254 else
1256 if (errno == EINTR || errno == EAGAIN)
1258 status = STATUS_PENDING;
1259 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1261 else
1263 /* We set the status to a winsock error code and check for that
1264 later in NtStatusToWSAError () */
1265 status = wsaErrno();
1266 result = 0;
1269 break;
1271 if (status != STATUS_PENDING)
1273 iosb->u.Status = status;
1274 iosb->Information = *total = result;
1276 return status;
1279 /***********************************************************************
1280 * WS2_async_shutdown (INTERNAL)
1282 * Handler for shutdown() operations on overlapped sockets.
1284 static NTSTATUS WS2_async_shutdown( void* user, PIO_STATUS_BLOCK iosb, NTSTATUS status )
1286 ws2_async* wsa = user;
1287 int fd, err = 1;
1289 switch (status)
1291 case STATUS_ALERTED:
1292 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
1293 break;
1295 switch ( wsa->type )
1297 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
1298 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
1300 wine_server_release_fd( wsa->hSocket, fd );
1301 status = err ? wsaErrno() : STATUS_SUCCESS;
1302 break;
1304 iosb->u.Status = status;
1305 return status;
1308 /***********************************************************************
1309 * WS2_register_async_shutdown (INTERNAL)
1311 * Helper function for WS_shutdown() on overlapped sockets.
1313 static int WS2_register_async_shutdown( SOCKET s, int type )
1315 struct ws2_async *wsa;
1316 NTSTATUS status;
1318 TRACE("s %ld type %d\n", s, type);
1320 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
1321 if ( !wsa )
1322 return WSAEFAULT;
1324 wsa->hSocket = SOCKET2HANDLE(s);
1325 wsa->type = type;
1326 wsa->completion_func = NULL;
1328 SERVER_START_REQ( register_async )
1330 req->handle = wsa->hSocket;
1331 req->type = type;
1332 req->async.callback = WS2_async_shutdown;
1333 req->async.iosb = &wsa->local_iosb;
1334 req->async.arg = wsa;
1335 req->async.apc = ws2_async_apc;
1336 req->async.cvalue = 0;
1337 status = wine_server_call( req );
1339 SERVER_END_REQ;
1341 if (status != STATUS_PENDING)
1343 HeapFree( GetProcessHeap(), 0, wsa );
1344 return NtStatusToWSAError( status );
1346 return 0;
1349 /***********************************************************************
1350 * accept (WS2_32.1)
1352 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr,
1353 int *addrlen32)
1355 SOCKET as;
1356 BOOL is_blocking;
1358 TRACE("socket %04lx\n", s );
1359 is_blocking = _is_blocking(s);
1361 do {
1362 if (is_blocking)
1364 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1365 if (fd == -1) return INVALID_SOCKET;
1366 /* block here */
1367 do_block(fd, POLLIN, -1);
1368 _sync_sock_state(s); /* let wineserver notice connection */
1369 release_sock_fd( s, fd );
1370 /* retrieve any error codes from it */
1371 SetLastError(_get_sock_error(s, FD_ACCEPT_BIT));
1372 /* FIXME: care about the error? */
1374 SERVER_START_REQ( accept_socket )
1376 req->lhandle = SOCKET2HANDLE(s);
1377 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
1378 req->attributes = OBJ_INHERIT;
1379 set_error( wine_server_call( req ) );
1380 as = HANDLE2SOCKET( reply->handle );
1382 SERVER_END_REQ;
1383 if (as)
1385 if (addr) WS_getpeername(as, addr, addrlen32);
1386 return as;
1388 } while (is_blocking);
1389 return INVALID_SOCKET;
1392 /***********************************************************************
1393 * bind (WS2_32.2)
1395 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
1397 int fd = get_sock_fd( s, 0, NULL );
1398 int res = SOCKET_ERROR;
1400 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1402 if (fd != -1)
1404 if (!name || (name->sa_family && !SUPPORTED_PF(name->sa_family)))
1406 SetLastError(WSAEAFNOSUPPORT);
1408 else
1410 union generic_unix_sockaddr uaddr;
1411 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1412 if (!uaddrlen)
1414 SetLastError(WSAEFAULT);
1416 else
1418 #ifdef IPV6_V6ONLY
1419 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
1420 if (name->sa_family == WS_AF_INET6 &&
1421 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
1423 int enable = 1;
1424 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
1426 release_sock_fd( s, fd );
1427 SetLastError(WSAEAFNOSUPPORT);
1428 return INVALID_SOCKET;
1431 #endif
1432 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
1434 int loc_errno = errno;
1435 WARN("\tfailure - errno = %i\n", errno);
1436 errno = loc_errno;
1437 switch (errno)
1439 case EBADF:
1440 SetLastError(WSAENOTSOCK);
1441 break;
1442 case EADDRNOTAVAIL:
1443 SetLastError(WSAEINVAL);
1444 break;
1445 default:
1446 SetLastError(wsaErrno());
1447 break;
1450 else
1452 res=0; /* success */
1456 release_sock_fd( s, fd );
1458 return res;
1461 /***********************************************************************
1462 * closesocket (WS2_32.3)
1464 int WINAPI WS_closesocket(SOCKET s)
1466 TRACE("socket %04lx\n", s);
1467 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
1468 return SOCKET_ERROR;
1471 /***********************************************************************
1472 * connect (WS2_32.4)
1474 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
1476 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1478 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1480 if (fd != -1)
1482 union generic_unix_sockaddr uaddr;
1483 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1485 if (!uaddrlen)
1487 SetLastError(WSAEFAULT);
1489 else
1491 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
1492 goto connect_success;
1495 if (errno == EINPROGRESS)
1497 /* tell wineserver that a connection is in progress */
1498 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1499 FD_CONNECT|FD_READ|FD_WRITE,
1500 FD_WINE_CONNECTED|FD_WINE_LISTENING);
1501 if (_is_blocking(s))
1503 int result;
1504 /* block here */
1505 do_block(fd, POLLIN | POLLOUT, -1);
1506 _sync_sock_state(s); /* let wineserver notice connection */
1507 /* retrieve any error codes from it */
1508 result = _get_sock_error(s, FD_CONNECT_BIT);
1509 if (result)
1510 SetLastError(result);
1511 else
1513 goto connect_success;
1516 else
1518 SetLastError(WSAEWOULDBLOCK);
1521 else
1523 SetLastError(wsaErrno());
1525 release_sock_fd( s, fd );
1527 return SOCKET_ERROR;
1529 connect_success:
1530 release_sock_fd( s, fd );
1531 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1532 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
1533 FD_CONNECT|FD_WINE_LISTENING);
1534 return 0;
1537 /***********************************************************************
1538 * WSAConnect (WS2_32.30)
1540 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
1541 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
1542 LPQOS lpSQOS, LPQOS lpGQOS )
1544 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
1545 FIXME("unsupported parameters!\n");
1546 return WS_connect( s, name, namelen );
1550 /***********************************************************************
1551 * getpeername (WS2_32.5)
1553 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
1555 int fd;
1556 int res;
1558 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, *namelen);
1560 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1561 if( (name == NULL) || (namelen == NULL) )
1563 SetLastError( WSAEFAULT );
1564 return SOCKET_ERROR;
1567 fd = get_sock_fd( s, 0, NULL );
1568 res = SOCKET_ERROR;
1570 if (fd != -1)
1572 union generic_unix_sockaddr uaddr;
1573 unsigned int uaddrlen = sizeof(uaddr);
1575 if (getpeername(fd, &uaddr.addr, &uaddrlen) != 0)
1577 SetLastError(wsaErrno());
1579 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
1581 /* The buffer was too small */
1582 SetLastError(WSAEFAULT);
1584 else
1586 res=0;
1588 release_sock_fd( s, fd );
1590 return res;
1593 /***********************************************************************
1594 * getsockname (WS2_32.6)
1596 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
1598 int fd;
1599 int res;
1601 TRACE("socket: %04lx, ptr %p, len %8x\n", s, name, *namelen);
1603 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1604 if( (name == NULL) || (namelen == NULL) )
1606 SetLastError( WSAEFAULT );
1607 return SOCKET_ERROR;
1610 fd = get_sock_fd( s, 0, NULL );
1611 res = SOCKET_ERROR;
1613 if (fd != -1)
1615 union generic_unix_sockaddr uaddr;
1616 unsigned int uaddrlen = sizeof(uaddr);
1618 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
1620 SetLastError(wsaErrno());
1622 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
1624 SetLastError(WSAEINVAL);
1626 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
1628 /* The buffer was too small */
1629 SetLastError(WSAEFAULT);
1631 else
1633 res=0;
1635 release_sock_fd( s, fd );
1637 return res;
1640 /***********************************************************************
1641 * getsockopt (WS2_32.7)
1643 INT WINAPI WS_getsockopt(SOCKET s, INT level,
1644 INT optname, char *optval, INT *optlen)
1646 int fd;
1647 INT ret = 0;
1649 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
1650 s, level, optname, optval, *optlen);
1652 switch(level)
1654 case WS_SOL_SOCKET:
1656 switch(optname)
1658 /* Handle common cases. The special cases are below, sorted
1659 * alphabetically */
1660 case WS_SO_ACCEPTCONN:
1661 case WS_SO_BROADCAST:
1662 case WS_SO_DEBUG:
1663 case WS_SO_ERROR:
1664 case WS_SO_KEEPALIVE:
1665 case WS_SO_OOBINLINE:
1666 case WS_SO_RCVBUF:
1667 case WS_SO_REUSEADDR:
1668 case WS_SO_SNDBUF:
1669 case WS_SO_TYPE:
1670 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1671 return SOCKET_ERROR;
1672 convert_sockopt(&level, &optname);
1673 if (getsockopt(fd,(int) level, optname, optval,
1674 (unsigned int *)optlen) != 0 )
1676 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1677 ret = SOCKET_ERROR;
1679 release_sock_fd( s, fd );
1680 return ret;
1682 case WS_SO_DONTLINGER:
1684 struct linger lingval;
1685 unsigned int len = sizeof(struct linger);
1687 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
1689 SetLastError(WSAEFAULT);
1690 return SOCKET_ERROR;
1692 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1693 return SOCKET_ERROR;
1695 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
1697 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1698 ret = SOCKET_ERROR;
1700 else
1702 *(BOOL *)optval = (lingval.l_onoff) ? FALSE : TRUE;
1703 *optlen = sizeof(BOOL);
1706 release_sock_fd( s, fd );
1707 return ret;
1710 /* As mentioned in setsockopt, Windows ignores this, so we
1711 * always return true here */
1712 case WS_SO_DONTROUTE:
1713 if (!optlen || *optlen < sizeof(BOOL) || !optval)
1715 SetLastError(WSAEFAULT);
1716 return SOCKET_ERROR;
1718 *(BOOL *)optval = TRUE;
1719 *optlen = sizeof(BOOL);
1720 return 0;
1722 case WS_SO_LINGER:
1724 struct linger lingval;
1725 unsigned int len = sizeof(struct linger);
1727 /* struct linger and LINGER have different sizes */
1728 if (!optlen || *optlen < sizeof(LINGER) || !optval)
1730 SetLastError(WSAEFAULT);
1731 return SOCKET_ERROR;
1733 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1734 return SOCKET_ERROR;
1736 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
1738 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1739 ret = SOCKET_ERROR;
1741 else
1743 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
1744 ((LINGER *)optval)->l_linger = lingval.l_linger;
1745 *optlen = sizeof(struct linger);
1748 release_sock_fd( s, fd );
1749 return ret;
1752 case WS_SO_MAX_MSG_SIZE:
1753 if (!optlen || *optlen < sizeof(int) || !optval)
1755 SetLastError(WSAEFAULT);
1756 return SOCKET_ERROR;
1758 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
1759 *(int *)optval = 65507;
1760 *optlen = sizeof(int);
1761 return 0;
1763 /* SO_OPENTYPE does not require a valid socket handle. */
1764 case WS_SO_OPENTYPE:
1765 if (!optlen || *optlen < sizeof(int) || !optval)
1767 SetLastError(WSAEFAULT);
1768 return SOCKET_ERROR;
1770 *(int *)optval = get_per_thread_data()->opentype;
1771 *optlen = sizeof(int);
1772 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
1773 return 0;
1775 #ifdef SO_RCVTIMEO
1776 case WS_SO_RCVTIMEO:
1777 #endif
1778 #ifdef SO_SNDTIMEO
1779 case WS_SO_SNDTIMEO:
1780 #endif
1781 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
1783 struct timeval tv;
1784 unsigned int len = sizeof(struct timeval);
1786 if (!optlen || *optlen < sizeof(int)|| !optval)
1788 SetLastError(WSAEFAULT);
1789 return SOCKET_ERROR;
1791 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1792 return SOCKET_ERROR;
1794 convert_sockopt(&level, &optname);
1795 if (getsockopt(fd,(int) level, optname, &tv, &len) != 0 )
1797 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1798 ret = SOCKET_ERROR;
1800 else
1802 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
1803 *optlen = sizeof(int);
1806 release_sock_fd( s, fd );
1807 return ret;
1809 #endif
1810 default:
1811 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
1812 SetLastError(WSAENOPROTOOPT);
1813 return SOCKET_ERROR;
1814 } /* end switch(optname) */
1815 }/* end case WS_SOL_SOCKET */
1816 #ifdef HAVE_IPX
1817 case NSPROTO_IPX:
1819 struct WS_sockaddr_ipx addr;
1820 IPX_ADDRESS_DATA *data;
1821 int namelen;
1822 switch(optname)
1824 case IPX_PTYPE:
1825 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
1826 #ifdef SOL_IPX
1827 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (unsigned int*)optlen) == -1)
1829 ret = SOCKET_ERROR;
1831 #else
1833 struct ipx val;
1834 socklen_t len=sizeof(struct ipx);
1835 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
1836 ret = SOCKET_ERROR;
1837 else
1838 *optval = (int)val.ipx_pt;
1840 #endif
1841 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
1842 release_sock_fd( s, fd );
1843 return ret;
1845 case IPX_ADDRESS:
1847 * On a Win2000 system with one network card there are usually
1848 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
1849 * Using this call you can then retrieve info about this all.
1850 * In case of Linux it is a bit different. Usually you have
1851 * only "one" device active and further it is not possible to
1852 * query things like the linkspeed.
1854 FIXME("IPX_ADDRESS\n");
1855 namelen = sizeof(struct WS_sockaddr_ipx);
1856 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
1857 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
1859 data = (IPX_ADDRESS_DATA*)optval;
1860 memcpy(data->nodenum,&addr.sa_nodenum,sizeof(data->nodenum));
1861 memcpy(data->netnum,&addr.sa_netnum,sizeof(data->netnum));
1862 data->adapternum = 0;
1863 data->wan = FALSE; /* We are not on a wan for now .. */
1864 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
1865 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
1866 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
1867 * note 1MB = 1000kB in this case */
1868 return 0;
1870 case IPX_MAX_ADAPTER_NUM:
1871 FIXME("IPX_MAX_ADAPTER_NUM\n");
1872 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
1873 return 0;
1875 default:
1876 FIXME("IPX optname:%x\n", optname);
1877 return SOCKET_ERROR;
1878 }/* end switch(optname) */
1879 } /* end case NSPROTO_IPX */
1880 #endif
1881 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
1882 case WS_IPPROTO_TCP:
1883 switch(optname)
1885 case WS_TCP_NODELAY:
1886 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1887 return SOCKET_ERROR;
1888 convert_sockopt(&level, &optname);
1889 if (getsockopt(fd,(int) level, optname, optval,
1890 (unsigned int *)optlen) != 0 )
1892 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1893 ret = SOCKET_ERROR;
1895 release_sock_fd( s, fd );
1896 return ret;
1898 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
1899 return SOCKET_ERROR;
1901 case WS_IPPROTO_IP:
1902 switch(optname)
1904 case WS_IP_ADD_MEMBERSHIP:
1905 case WS_IP_DROP_MEMBERSHIP:
1906 #ifdef IP_HDRINCL
1907 case WS_IP_HDRINCL:
1908 #endif
1909 case WS_IP_MULTICAST_IF:
1910 case WS_IP_MULTICAST_LOOP:
1911 case WS_IP_MULTICAST_TTL:
1912 case WS_IP_OPTIONS:
1913 case WS_IP_TOS:
1914 case WS_IP_TTL:
1915 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1916 return SOCKET_ERROR;
1917 convert_sockopt(&level, &optname);
1918 if (getsockopt(fd,(int) level, optname, optval,
1919 (unsigned int *)optlen) != 0 )
1921 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1922 ret = SOCKET_ERROR;
1924 release_sock_fd( s, fd );
1925 return ret;
1926 case WS_IP_DONTFRAGMENT:
1927 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
1928 *(BOOL*)optval = FALSE;
1929 return 0;
1931 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
1932 return SOCKET_ERROR;
1934 default:
1935 FIXME("Unknown level: 0x%08x\n", level);
1936 return SOCKET_ERROR;
1937 } /* end switch(level) */
1940 /***********************************************************************
1941 * htonl (WINSOCK.8)
1942 * htonl (WS2_32.8)
1944 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
1946 return htonl(hostlong);
1950 /***********************************************************************
1951 * htons (WINSOCK.9)
1952 * htons (WS2_32.9)
1954 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
1956 return htons(hostshort);
1959 /***********************************************************************
1960 * WSAHtonl (WS2_32.46)
1961 * From MSDN description of error codes, this function should also
1962 * check if WinSock has been initialized and the socket is a valid
1963 * socket. But why? This function only translates a host byte order
1964 * u_long into a network byte order u_long...
1966 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
1968 if (lpnetlong)
1970 *lpnetlong = htonl(hostlong);
1971 return 0;
1973 WSASetLastError(WSAEFAULT);
1974 return SOCKET_ERROR;
1977 /***********************************************************************
1978 * WSAHtons (WS2_32.47)
1979 * From MSDN decription of error codes, this function should also
1980 * check if WinSock has been initialized and the socket is a valid
1981 * socket. But why? This function only translates a host byte order
1982 * u_short into a network byte order u_short...
1984 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
1987 if (lpnetshort)
1989 *lpnetshort = htons(hostshort);
1990 return 0;
1992 WSASetLastError(WSAEFAULT);
1993 return SOCKET_ERROR;
1997 /***********************************************************************
1998 * inet_addr (WINSOCK.10)
1999 * inet_addr (WS2_32.11)
2001 WS_u_long WINAPI WS_inet_addr(const char *cp)
2003 if (!cp) return INADDR_NONE;
2004 return inet_addr(cp);
2008 /***********************************************************************
2009 * ntohl (WINSOCK.14)
2010 * ntohl (WS2_32.14)
2012 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
2014 return ntohl(netlong);
2018 /***********************************************************************
2019 * ntohs (WINSOCK.15)
2020 * ntohs (WS2_32.15)
2022 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
2024 return ntohs(netshort);
2028 /***********************************************************************
2029 * inet_ntoa (WS2_32.12)
2031 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
2033 /* use "buffer for dummies" here because some applications have a
2034 * propensity to decode addresses in ws_hostent structure without
2035 * saving them first...
2037 static char dbuffer[16]; /* Yes, 16: 4*3 digits + 3 '.' + 1 '\0' */
2039 char* s = inet_ntoa(*((struct in_addr*)&in));
2040 if( s )
2042 strcpy(dbuffer, s);
2043 return dbuffer;
2045 SetLastError(wsaErrno());
2046 return NULL;
2049 /**********************************************************************
2050 * WSAIoctl (WS2_32.50)
2053 INT WINAPI WSAIoctl(SOCKET s,
2054 DWORD dwIoControlCode,
2055 LPVOID lpvInBuffer,
2056 DWORD cbInBuffer,
2057 LPVOID lpbOutBuffer,
2058 DWORD cbOutBuffer,
2059 LPDWORD lpcbBytesReturned,
2060 LPWSAOVERLAPPED lpOverlapped,
2061 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
2063 TRACE("%ld, 0x%08x, %p, %d, %p, %d, %p, %p, %p\n",
2064 s, dwIoControlCode, lpvInBuffer, cbInBuffer, lpbOutBuffer,
2065 cbOutBuffer, lpcbBytesReturned, lpOverlapped, lpCompletionRoutine);
2067 switch( dwIoControlCode )
2069 case WS_FIONBIO:
2070 if (cbInBuffer != sizeof(WS_u_long)) {
2071 WSASetLastError(WSAEFAULT);
2072 return SOCKET_ERROR;
2074 return WS_ioctlsocket( s, WS_FIONBIO, lpvInBuffer);
2076 case WS_FIONREAD:
2077 if (cbOutBuffer != sizeof(WS_u_long)) {
2078 WSASetLastError(WSAEFAULT);
2079 return SOCKET_ERROR;
2081 return WS_ioctlsocket( s, WS_FIONREAD, lpbOutBuffer);
2083 case WS_SIO_GET_INTERFACE_LIST:
2085 INTERFACE_INFO* intArray = (INTERFACE_INFO*)lpbOutBuffer;
2086 DWORD size, numInt, apiReturn;
2087 int fd;
2089 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
2091 if (!lpbOutBuffer)
2093 WSASetLastError(WSAEFAULT);
2094 return SOCKET_ERROR;
2096 if (!lpcbBytesReturned)
2098 WSASetLastError(WSAEFAULT);
2099 return SOCKET_ERROR;
2102 fd = get_sock_fd( s, 0, NULL );
2103 if (fd == -1) return SOCKET_ERROR;
2105 apiReturn = GetAdaptersInfo(NULL, &size);
2106 if (apiReturn == ERROR_NO_DATA)
2108 numInt = 0;
2110 else if (apiReturn == ERROR_BUFFER_OVERFLOW)
2112 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
2114 if (table)
2116 if (GetAdaptersInfo(table, &size) == NO_ERROR)
2118 PIP_ADAPTER_INFO ptr;
2120 if (size*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > cbOutBuffer)
2122 WARN("Buffer too small = %u, cbOutBuffer = %u\n", size, cbOutBuffer);
2123 HeapFree(GetProcessHeap(),0,table);
2124 release_sock_fd( s, fd );
2125 WSASetLastError(WSAEFAULT);
2126 return SOCKET_ERROR;
2128 for (ptr = table, numInt = 0; ptr;
2129 ptr = ptr->Next, intArray++, numInt++)
2131 unsigned int addr, mask, bcast;
2132 struct ifreq ifInfo;
2134 /* Socket Status Flags */
2135 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
2136 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
2138 ERR("Error obtaining status flags for socket!\n");
2139 HeapFree(GetProcessHeap(),0,table);
2140 release_sock_fd( s, fd );
2141 WSASetLastError(WSAEINVAL);
2142 return SOCKET_ERROR;
2144 else
2146 /* set flags; the values of IFF_* are not the same
2147 under Linux and Windows, therefore must generate
2148 new flags */
2149 intArray->iiFlags = 0;
2150 if (ifInfo.ifr_flags & IFF_BROADCAST)
2151 intArray->iiFlags |= WS_IFF_BROADCAST;
2152 #ifdef IFF_POINTOPOINT
2153 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
2154 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
2155 #endif
2156 if (ifInfo.ifr_flags & IFF_LOOPBACK)
2157 intArray->iiFlags |= WS_IFF_LOOPBACK;
2158 if (ifInfo.ifr_flags & IFF_UP)
2159 intArray->iiFlags |= WS_IFF_UP;
2160 if (ifInfo.ifr_flags & IFF_MULTICAST)
2161 intArray->iiFlags |= WS_IFF_MULTICAST;
2164 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
2165 mask = inet_addr(ptr->IpAddressList.IpMask.String);
2166 bcast = addr | ~mask;
2167 intArray->iiAddress.AddressIn.sin_family = AF_INET;
2168 intArray->iiAddress.AddressIn.sin_port = 0;
2169 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
2170 addr;
2171 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
2172 intArray->iiNetmask.AddressIn.sin_port = 0;
2173 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
2174 mask;
2175 intArray->iiBroadcastAddress.AddressIn.sin_family =
2176 AF_INET;
2177 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
2178 intArray->iiBroadcastAddress.AddressIn.sin_addr.
2179 WS_s_addr = bcast;
2182 else
2184 ERR("Unable to get interface table!\n");
2185 release_sock_fd( s, fd );
2186 HeapFree(GetProcessHeap(),0,table);
2187 WSASetLastError(WSAEINVAL);
2188 return SOCKET_ERROR;
2190 HeapFree(GetProcessHeap(),0,table);
2192 else
2194 release_sock_fd( s, fd );
2195 WSASetLastError(WSAEINVAL);
2196 return SOCKET_ERROR;
2199 else
2201 ERR("Unable to get interface table!\n");
2202 release_sock_fd( s, fd );
2203 WSASetLastError(WSAEINVAL);
2204 return SOCKET_ERROR;
2206 /* Calculate the size of the array being returned */
2207 *lpcbBytesReturned = sizeof(INTERFACE_INFO) * numInt;
2208 release_sock_fd( s, fd );
2209 break;
2212 case WS_SIO_ADDRESS_LIST_CHANGE:
2213 FIXME("-> SIO_ADDRESS_LIST_CHANGE request: stub\n");
2214 /* FIXME: error and return code depend on whether socket was created
2215 * with WSA_FLAG_OVERLAPPED, but there is no easy way to get this */
2216 break;
2218 case WS_SIO_ADDRESS_LIST_QUERY:
2220 DWORD size;
2222 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
2224 if (!lpcbBytesReturned)
2226 WSASetLastError(WSAEFAULT);
2227 return SOCKET_ERROR;
2230 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
2232 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
2233 DWORD need, num;
2235 if (!table || GetAdaptersInfo(table, &size))
2237 HeapFree(GetProcessHeap(), 0, table);
2238 WSASetLastError(WSAEINVAL);
2239 return SOCKET_ERROR;
2242 for (p = table, num = 0; p; p = p->Next)
2243 if (p->IpAddressList.IpAddress.String[0]) num++;
2245 need = sizeof(SOCKET_ADDRESS_LIST) + sizeof(SOCKET_ADDRESS) * (num - 1);
2246 need += sizeof(SOCKADDR) * num;
2247 *lpcbBytesReturned = need;
2249 if (need > cbOutBuffer)
2251 HeapFree(GetProcessHeap(), 0, table);
2252 WSASetLastError(WSAEFAULT);
2253 return SOCKET_ERROR;
2256 if (lpbOutBuffer)
2258 unsigned int i;
2259 SOCKET_ADDRESS *sa;
2260 SOCKET_ADDRESS_LIST *sa_list = (SOCKET_ADDRESS_LIST *)lpbOutBuffer;
2261 SOCKADDR_IN *sockaddr;
2263 sa = sa_list->Address;
2264 sockaddr = (SOCKADDR_IN *)((char *)sa + num * sizeof(SOCKET_ADDRESS));
2265 sa_list->iAddressCount = num;
2267 for (p = table, i = 0; p; p = p->Next)
2269 if (!p->IpAddressList.IpAddress.String[0]) continue;
2271 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
2272 sa[i].iSockaddrLength = sizeof(SOCKADDR);
2274 sockaddr[i].sin_family = AF_INET;
2275 sockaddr[i].sin_port = 0;
2276 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
2277 i++;
2281 HeapFree(GetProcessHeap(), 0, table);
2282 return 0;
2284 else
2286 WARN("unable to get IP address list\n");
2287 WSASetLastError(WSAEINVAL);
2288 return SOCKET_ERROR;
2291 case WS_SIO_FLUSH:
2292 FIXME("SIO_FLUSH: stub.\n");
2293 break;
2295 default:
2296 FIXME("unsupported WS_IOCTL cmd (%08x)\n", dwIoControlCode);
2297 WSASetLastError(WSAEOPNOTSUPP);
2298 return SOCKET_ERROR;
2301 return 0;
2305 /***********************************************************************
2306 * ioctlsocket (WS2_32.10)
2308 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
2310 int fd;
2311 long newcmd = cmd;
2313 TRACE("socket %04lx, cmd %08x, ptr %p\n", s, cmd, argp);
2315 switch( cmd )
2317 case WS_FIONREAD:
2318 newcmd=FIONREAD;
2319 break;
2321 case WS_FIONBIO:
2322 if( _get_sock_mask(s) )
2324 /* AsyncSelect()'ed sockets are always nonblocking */
2325 if (*argp) return 0;
2326 SetLastError(WSAEINVAL);
2327 return SOCKET_ERROR;
2329 fd = get_sock_fd( s, 0, NULL );
2330 if (fd != -1)
2332 int ret;
2333 if (*argp)
2335 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
2336 ret = fcntl( fd, F_SETFL, O_NONBLOCK );
2338 else
2340 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
2341 ret = fcntl( fd, F_SETFL, 0 );
2343 release_sock_fd( s, fd );
2344 if (!ret) return 0;
2345 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2347 return SOCKET_ERROR;
2349 case WS_SIOCATMARK:
2350 newcmd=SIOCATMARK;
2351 break;
2353 case WS_FIOASYNC:
2354 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
2355 SetLastError(WSAEINVAL);
2356 return SOCKET_ERROR;
2358 case SIOCGIFBRDADDR:
2359 case SIOCGIFNETMASK:
2360 case SIOCGIFADDR:
2361 /* These don't need any special handling. They are used by
2362 WsControl, and are here to suppress an unnecessary warning. */
2363 break;
2365 default:
2366 /* Netscape tries hard to use bogus ioctl 0x667e */
2367 /* FIXME: 0x667e above is ('f' << 8) | 126, and is a low word of
2368 * FIONBIO (_IOW('f', 126, u_long)), how that should be handled?
2370 WARN("\tunknown WS_IOCTL cmd (%08x)\n", cmd);
2371 break;
2374 fd = get_sock_fd( s, 0, NULL );
2375 if (fd != -1)
2377 if( ioctl(fd, newcmd, (char*)argp ) == 0 )
2379 release_sock_fd( s, fd );
2380 return 0;
2382 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2383 release_sock_fd( s, fd );
2385 return SOCKET_ERROR;
2388 /***********************************************************************
2389 * listen (WS2_32.13)
2391 int WINAPI WS_listen(SOCKET s, int backlog)
2393 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2395 TRACE("socket %04lx, backlog %d\n", s, backlog);
2396 if (fd != -1)
2398 if (listen(fd, backlog) == 0)
2400 release_sock_fd( s, fd );
2401 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
2402 FD_WINE_LISTENING,
2403 FD_CONNECT|FD_WINE_CONNECTED);
2404 return 0;
2406 SetLastError(wsaErrno());
2407 release_sock_fd( s, fd );
2409 return SOCKET_ERROR;
2412 /***********************************************************************
2413 * recv (WS2_32.16)
2415 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
2417 DWORD n, dwFlags = flags;
2418 WSABUF wsabuf;
2420 wsabuf.len = len;
2421 wsabuf.buf = buf;
2423 if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
2424 return SOCKET_ERROR;
2425 else
2426 return n;
2429 /***********************************************************************
2430 * recvfrom (WS2_32.17)
2432 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
2433 struct WS_sockaddr *from, int *fromlen)
2435 DWORD n, dwFlags = flags;
2436 WSABUF wsabuf;
2438 wsabuf.len = len;
2439 wsabuf.buf = buf;
2441 if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL) == SOCKET_ERROR )
2442 return SOCKET_ERROR;
2443 else
2444 return n;
2447 /* allocate a poll array for the corresponding fd sets */
2448 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
2449 const WS_fd_set *exceptfds, int *count_ptr )
2451 int i, j = 0, count = 0;
2452 struct pollfd *fds;
2454 if (readfds) count += readfds->fd_count;
2455 if (writefds) count += writefds->fd_count;
2456 if (exceptfds) count += exceptfds->fd_count;
2457 *count_ptr = count;
2458 if (!count) return NULL;
2459 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0])))) return NULL;
2460 if (readfds)
2461 for (i = 0; i < readfds->fd_count; i++, j++)
2463 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
2464 fds[j].events = POLLIN;
2465 fds[j].revents = 0;
2467 if (writefds)
2468 for (i = 0; i < writefds->fd_count; i++, j++)
2470 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
2471 fds[j].events = POLLOUT;
2472 fds[j].revents = 0;
2474 if (exceptfds)
2475 for (i = 0; i < exceptfds->fd_count; i++, j++)
2477 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
2478 fds[j].events = POLLHUP;
2479 fds[j].revents = 0;
2481 return fds;
2484 /* release the file descriptor obtained in fd_sets_to_poll */
2485 /* must be called with the original fd_set arrays, before calling get_poll_results */
2486 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
2487 const WS_fd_set *exceptfds, struct pollfd *fds )
2489 int i, j = 0;
2491 if (readfds)
2493 for (i = 0; i < readfds->fd_count; i++, j++)
2494 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
2496 if (writefds)
2498 for (i = 0; i < writefds->fd_count; i++, j++)
2499 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
2501 if (exceptfds)
2503 for (i = 0; i < exceptfds->fd_count; i++, j++)
2504 if (fds[j].fd != -1)
2506 /* make sure we have a real error before releasing the fd */
2507 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
2508 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
2513 /* map the poll results back into the Windows fd sets */
2514 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
2515 const struct pollfd *fds )
2517 int i, j = 0, k, total = 0;
2519 if (readfds)
2521 for (i = k = 0; i < readfds->fd_count; i++, j++)
2522 if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
2523 readfds->fd_count = k;
2524 total += k;
2526 if (writefds)
2528 for (i = k = 0; i < writefds->fd_count; i++, j++)
2529 if (fds[j].revents) writefds->fd_array[k++] = writefds->fd_array[i];
2530 writefds->fd_count = k;
2531 total += k;
2533 if (exceptfds)
2535 for (i = k = 0; i < exceptfds->fd_count; i++, j++)
2536 if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
2537 exceptfds->fd_count = k;
2538 total += k;
2540 return total;
2544 /***********************************************************************
2545 * select (WS2_32.18)
2547 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
2548 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
2549 const struct WS_timeval* ws_timeout)
2551 struct pollfd *pollfds;
2552 int count, ret, timeout = -1;
2554 TRACE("read %p, write %p, excp %p timeout %p\n",
2555 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
2557 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )) && count)
2559 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2560 return SOCKET_ERROR;
2563 if (ws_timeout) timeout = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
2565 ret = poll( pollfds, count, timeout );
2566 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
2568 if (ret == -1) SetLastError(wsaErrno());
2569 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
2570 HeapFree( GetProcessHeap(), 0, pollfds );
2571 return ret;
2574 /* helper to send completion messages for client-only i/o operation case */
2575 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus, ULONG_PTR Information )
2577 NTSTATUS status;
2579 SERVER_START_REQ( add_fd_completion )
2581 req->handle = SOCKET2HANDLE(sock);
2582 req->cvalue = CompletionValue;
2583 req->status = CompletionStatus;
2584 req->information = Information;
2585 status = wine_server_call( req );
2587 SERVER_END_REQ;
2591 /***********************************************************************
2592 * send (WS2_32.19)
2594 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
2596 DWORD n;
2597 WSABUF wsabuf;
2599 wsabuf.len = len;
2600 wsabuf.buf = (char*) buf;
2602 if ( WSASendTo( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
2603 return SOCKET_ERROR;
2604 else
2605 return n;
2608 /***********************************************************************
2609 * WSASend (WS2_32.72)
2611 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2612 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2613 LPWSAOVERLAPPED lpOverlapped,
2614 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2616 return WSASendTo( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
2617 NULL, 0, lpOverlapped, lpCompletionRoutine );
2620 /***********************************************************************
2621 * WSASendDisconnect (WS2_32.73)
2623 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
2625 return WS_shutdown( s, SD_SEND );
2629 /***********************************************************************
2630 * WSASendTo (WS2_32.74)
2632 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2633 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2634 const struct WS_sockaddr *to, int tolen,
2635 LPWSAOVERLAPPED lpOverlapped,
2636 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2638 unsigned int i, options;
2639 int n, fd, err;
2640 struct iovec iovec[WS_MSG_MAXIOVLEN];
2641 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
2643 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
2644 s, lpBuffers, dwBufferCount, dwFlags,
2645 to, tolen, lpOverlapped, lpCompletionRoutine);
2647 if (dwBufferCount > WS_MSG_MAXIOVLEN)
2649 WSASetLastError( WSAEINVAL );
2650 return SOCKET_ERROR;
2653 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
2654 TRACE( "fd=%d, options=%x\n", fd, options );
2656 if ( fd == -1 ) return SOCKET_ERROR;
2658 if ( !lpNumberOfBytesSent )
2660 err = WSAEFAULT;
2661 goto error;
2664 for ( i = 0; i < dwBufferCount; i++ )
2666 iovec[i].iov_base = lpBuffers[i].buf;
2667 iovec[i].iov_len = lpBuffers[i].len;
2670 for (;;)
2672 n = WS2_send( fd, iovec, dwBufferCount, to, tolen, dwFlags );
2673 if (n != -1 || errno != EINTR) break;
2675 if (n == -1 && errno != EAGAIN)
2677 err = wsaErrno();
2678 if (cvalue) WS_AddCompletion( s, cvalue, err, 0 );
2679 goto error;
2682 if ((lpOverlapped || lpCompletionRoutine) &&
2683 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
2685 IO_STATUS_BLOCK *iosb;
2686 struct ws2_async *wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
2688 if ( !wsa )
2690 err = WSAEFAULT;
2691 goto error;
2693 release_sock_fd( s, fd );
2695 wsa->hSocket = SOCKET2HANDLE(s);
2696 wsa->addr = (struct WS_sockaddr *)to;
2697 wsa->addrlen.val = tolen;
2698 wsa->flags = 0;
2699 wsa->user_overlapped = lpOverlapped;
2700 wsa->completion_func = lpCompletionRoutine;
2701 wsa->n_iovecs = dwBufferCount;
2702 memcpy( wsa->iovec, iovec, dwBufferCount * sizeof(*iovec) );
2704 iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
2705 if (n == -1)
2707 iosb->u.Status = STATUS_PENDING;
2708 iosb->Information = 0;
2710 SERVER_START_REQ( register_async )
2712 req->handle = wsa->hSocket;
2713 req->type = ASYNC_TYPE_WRITE;
2714 req->async.callback = WS2_async_send;
2715 req->async.iosb = iosb;
2716 req->async.arg = wsa;
2717 req->async.apc = ws2_async_apc;
2718 req->async.event = lpCompletionRoutine ? 0 : lpOverlapped->hEvent;
2719 req->async.cvalue = cvalue;
2720 err = wine_server_call( req );
2722 SERVER_END_REQ;
2724 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
2725 WSASetLastError( NtStatusToWSAError( err ));
2726 return SOCKET_ERROR;
2729 iosb->u.Status = STATUS_SUCCESS;
2730 iosb->Information = n;
2731 *lpNumberOfBytesSent = n;
2732 if (!wsa->completion_func)
2734 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
2735 SetEvent( lpOverlapped->hEvent );
2736 HeapFree( GetProcessHeap(), 0, wsa );
2738 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
2739 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
2740 return 0;
2743 if ( _is_blocking(s) )
2745 /* On a blocking non-overlapped stream socket,
2746 * sending blocks until the entire buffer is sent. */
2747 DWORD timeout_start = GetTickCount();
2748 unsigned int first_buff = 0;
2750 *lpNumberOfBytesSent = 0;
2752 while (first_buff < dwBufferCount)
2754 struct pollfd pfd;
2755 int timeout = GET_SNDTIMEO(fd);
2757 if (n >= 0)
2759 *lpNumberOfBytesSent += n;
2760 while (first_buff < dwBufferCount && iovec[first_buff].iov_len <= n)
2761 n -= iovec[first_buff++].iov_len;
2762 if (first_buff >= dwBufferCount) break;
2763 iovec[first_buff].iov_base = (char*)iovec[first_buff].iov_base + n;
2764 iovec[first_buff].iov_len -= n;
2767 if (timeout != -1)
2769 timeout -= GetTickCount() - timeout_start;
2770 if (timeout < 0) timeout = 0;
2773 pfd.fd = fd;
2774 pfd.events = POLLOUT;
2776 if (!timeout || !poll( &pfd, 1, timeout ))
2778 err = WSAETIMEDOUT;
2779 goto error; /* msdn says a timeout in send is fatal */
2782 n = WS2_send( fd, iovec + first_buff, dwBufferCount - first_buff, to, tolen, dwFlags );
2783 if (n == -1 && errno != EAGAIN && errno != EINTR)
2785 err = wsaErrno();
2786 goto error;
2790 else /* non-blocking */
2792 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
2793 if (n == -1)
2795 err = WSAEWOULDBLOCK;
2796 goto error;
2798 *lpNumberOfBytesSent = n;
2801 TRACE(" -> %i bytes\n", *lpNumberOfBytesSent);
2803 release_sock_fd( s, fd );
2804 return 0;
2806 error:
2807 release_sock_fd( s, fd );
2808 WARN(" -> ERROR %d\n", err);
2809 WSASetLastError(err);
2810 return SOCKET_ERROR;
2813 /***********************************************************************
2814 * sendto (WS2_32.20)
2816 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
2817 const struct WS_sockaddr *to, int tolen)
2819 DWORD n;
2820 WSABUF wsabuf;
2822 wsabuf.len = len;
2823 wsabuf.buf = (char*) buf;
2825 if ( WSASendTo(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
2826 return SOCKET_ERROR;
2827 else
2828 return n;
2831 /***********************************************************************
2832 * setsockopt (WS2_32.21)
2834 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
2835 const char *optval, int optlen)
2837 int fd;
2838 int woptval;
2839 struct linger linger;
2840 struct timeval tval;
2842 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
2843 s, level, optname, optval, optlen);
2845 /* some broken apps pass the value directly instead of a pointer to it */
2846 if(IS_INTRESOURCE(optval))
2848 SetLastError(WSAEFAULT);
2849 return SOCKET_ERROR;
2852 switch(level)
2854 case WS_SOL_SOCKET:
2855 switch(optname)
2857 /* Some options need some conversion before they can be sent to
2858 * setsockopt. The conversions are done here, then they will fall though
2859 * to the general case. Special options that are not passed to
2860 * setsockopt follow below that.*/
2862 case WS_SO_DONTLINGER:
2863 linger.l_onoff = *((const int*)optval) ? 0: 1;
2864 linger.l_linger = 0;
2865 level = SOL_SOCKET;
2866 optname = SO_LINGER;
2867 optval = (char*)&linger;
2868 optlen = sizeof(struct linger);
2869 break;
2871 case WS_SO_LINGER:
2872 linger.l_onoff = ((LINGER*)optval)->l_onoff;
2873 linger.l_linger = ((LINGER*)optval)->l_linger;
2874 /* FIXME: what is documented behavior if SO_LINGER optval
2875 is null?? */
2876 level = SOL_SOCKET;
2877 optname = SO_LINGER;
2878 optval = (char*)&linger;
2879 optlen = sizeof(struct linger);
2880 break;
2882 case WS_SO_RCVBUF:
2883 if (*(const int*)optval < 2048)
2885 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
2886 return 0;
2888 /* Fall through */
2890 /* The options listed here don't need any special handling. Thanks to
2891 * the conversion happening above, options from there will fall through
2892 * to this, too.*/
2893 case WS_SO_ACCEPTCONN:
2894 case WS_SO_BROADCAST:
2895 case WS_SO_ERROR:
2896 case WS_SO_KEEPALIVE:
2897 case WS_SO_OOBINLINE:
2898 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
2899 * however, using it the BSD way fixes bug 8513 and seems to be what
2900 * most programmers assume, anyway */
2901 case WS_SO_REUSEADDR:
2902 case WS_SO_SNDBUF:
2903 case WS_SO_TYPE:
2904 convert_sockopt(&level, &optname);
2905 break;
2907 /* SO_DEBUG is a privileged operation, ignore it. */
2908 case WS_SO_DEBUG:
2909 TRACE("Ignoring SO_DEBUG\n");
2910 return 0;
2912 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
2913 * socket. According to MSDN, this option is silently ignored.*/
2914 case WS_SO_DONTROUTE:
2915 TRACE("Ignoring SO_DONTROUTE\n");
2916 return 0;
2918 /* Stops two sockets from being bound to the same port. Always happens
2919 * on unix systems, so just drop it. */
2920 case WS_SO_EXCLUSIVEADDRUSE:
2921 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
2922 return 0;
2924 /* SO_OPENTYPE does not require a valid socket handle. */
2925 case WS_SO_OPENTYPE:
2926 if (!optlen || optlen < sizeof(int) || !optval)
2928 SetLastError(WSAEFAULT);
2929 return SOCKET_ERROR;
2931 get_per_thread_data()->opentype = *(const int *)optval;
2932 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
2933 return 0;
2935 #ifdef SO_RCVTIMEO
2936 case WS_SO_RCVTIMEO:
2937 #endif
2938 #ifdef SO_SNDTIMEO
2939 case WS_SO_SNDTIMEO:
2940 #endif
2941 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
2942 if (optval && optlen == sizeof(UINT32)) {
2943 /* WinSock passes milliseconds instead of struct timeval */
2944 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
2945 tval.tv_sec = *(const UINT32*)optval / 1000;
2946 /* min of 500 milliseconds */
2947 if (tval.tv_sec == 0 && tval.tv_usec < 500000)
2948 tval.tv_usec = 500000;
2949 optlen = sizeof(struct timeval);
2950 optval = (char*)&tval;
2951 } else if (optlen == sizeof(struct timeval)) {
2952 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
2953 } else {
2954 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
2955 return 0;
2957 convert_sockopt(&level, &optname);
2958 break;
2959 #endif
2961 default:
2962 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
2963 SetLastError(WSAENOPROTOOPT);
2964 return SOCKET_ERROR;
2966 break; /* case WS_SOL_SOCKET */
2968 #ifdef HAVE_IPX
2969 case NSPROTO_IPX:
2970 switch(optname)
2972 case IPX_PTYPE:
2973 fd = get_sock_fd( s, 0, NULL );
2974 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", *(const int*)optval, fd);
2976 /* We try to set the ipx type on ipx socket level. */
2977 #ifdef SOL_IPX
2978 if(setsockopt(fd, SOL_IPX, IPX_TYPE, optval, optlen) == -1)
2980 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
2981 release_sock_fd( s, fd );
2982 return SOCKET_ERROR;
2984 #else
2986 struct ipx val;
2987 /* Should we retrieve val using a getsockopt call and then
2988 * set the modified one? */
2989 val.ipx_pt = *optval;
2990 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
2992 #endif
2993 release_sock_fd( s, fd );
2994 return 0;
2996 case IPX_FILTERPTYPE:
2997 /* Sets the receive filter packet type, at the moment we don't support it */
2998 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
2999 /* Returning 0 is better for now than returning a SOCKET_ERROR */
3000 return 0;
3002 default:
3003 FIXME("opt_name:%x\n", optname);
3004 return SOCKET_ERROR;
3006 break; /* case NSPROTO_IPX */
3007 #endif
3009 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3010 case WS_IPPROTO_TCP:
3011 switch(optname)
3013 case WS_TCP_NODELAY:
3014 convert_sockopt(&level, &optname);
3015 break;
3016 default:
3017 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
3018 return SOCKET_ERROR;
3020 break;
3022 case WS_IPPROTO_IP:
3023 switch(optname)
3025 case WS_IP_ADD_MEMBERSHIP:
3026 case WS_IP_DROP_MEMBERSHIP:
3027 #ifdef IP_HDRINCL
3028 case WS_IP_HDRINCL:
3029 #endif
3030 case WS_IP_MULTICAST_IF:
3031 case WS_IP_MULTICAST_LOOP:
3032 case WS_IP_MULTICAST_TTL:
3033 case WS_IP_OPTIONS:
3034 case WS_IP_TOS:
3035 case WS_IP_TTL:
3036 convert_sockopt(&level, &optname);
3037 break;
3038 case WS_IP_DONTFRAGMENT:
3039 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
3040 return 0;
3041 default:
3042 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
3043 return SOCKET_ERROR;
3045 break;
3047 default:
3048 FIXME("Unknown level: 0x%08x\n", level);
3049 return SOCKET_ERROR;
3050 } /* end switch(level) */
3052 /* avoid endianness issues if argument is a 16-bit int */
3053 if (optval && optlen < sizeof(int))
3055 woptval= *((const INT16 *) optval);
3056 optval= (char*) &woptval;
3057 optlen=sizeof(int);
3059 fd = get_sock_fd( s, 0, NULL );
3060 if (fd == -1) return SOCKET_ERROR;
3062 if (setsockopt(fd, level, optname, optval, optlen) == 0)
3064 release_sock_fd( s, fd );
3065 return 0;
3067 TRACE("Setting socket error, %d\n", wsaErrno());
3068 SetLastError(wsaErrno());
3069 release_sock_fd( s, fd );
3071 return SOCKET_ERROR;
3074 /***********************************************************************
3075 * shutdown (WS2_32.22)
3077 int WINAPI WS_shutdown(SOCKET s, int how)
3079 int fd, err = WSAENOTSOCK;
3080 unsigned int options, clear_flags = 0;
3082 fd = get_sock_fd( s, 0, &options );
3083 TRACE("socket %04lx, how %i %x\n", s, how, options );
3085 if (fd == -1)
3086 return SOCKET_ERROR;
3088 switch( how )
3090 case 0: /* drop receives */
3091 clear_flags |= FD_READ;
3092 break;
3093 case 1: /* drop sends */
3094 clear_flags |= FD_WRITE;
3095 break;
3096 case 2: /* drop all */
3097 clear_flags |= FD_READ|FD_WRITE;
3098 default:
3099 clear_flags |= FD_WINE_LISTENING;
3102 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
3104 switch ( how )
3106 case SD_RECEIVE:
3107 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3108 break;
3109 case SD_SEND:
3110 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3111 break;
3112 case SD_BOTH:
3113 default:
3114 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3115 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3116 break;
3118 if (err) goto error;
3120 else /* non-overlapped mode */
3122 if ( shutdown( fd, how ) )
3124 err = wsaErrno();
3125 goto error;
3129 release_sock_fd( s, fd );
3130 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3131 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
3132 return 0;
3134 error:
3135 release_sock_fd( s, fd );
3136 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3137 WSASetLastError( err );
3138 return SOCKET_ERROR;
3141 /***********************************************************************
3142 * socket (WS2_32.23)
3144 SOCKET WINAPI WS_socket(int af, int type, int protocol)
3146 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
3148 return WSASocketA( af, type, protocol, NULL, 0,
3149 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
3153 /***********************************************************************
3154 * gethostbyaddr (WS2_32.51)
3156 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
3158 struct WS_hostent *retval = NULL;
3159 struct hostent* host;
3161 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3162 char *extrabuf;
3163 int ebufsize=1024;
3164 struct hostent hostentry;
3165 int locerr=ENOBUFS;
3166 host = NULL;
3167 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3168 while(extrabuf) {
3169 int res = gethostbyaddr_r(addr, len, type,
3170 &hostentry, extrabuf, ebufsize, &host, &locerr);
3171 if( res != ERANGE) break;
3172 ebufsize *=2;
3173 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3175 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3176 #else
3177 EnterCriticalSection( &csWSgetXXXbyYYY );
3178 host = gethostbyaddr(addr, len, type);
3179 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3180 #endif
3181 if( host != NULL ) retval = WS_dup_he(host);
3182 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3183 HeapFree(GetProcessHeap(),0,extrabuf);
3184 #else
3185 LeaveCriticalSection( &csWSgetXXXbyYYY );
3186 #endif
3187 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
3188 return retval;
3191 /***********************************************************************
3192 * gethostbyname (WS2_32.52)
3194 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
3196 struct WS_hostent *retval = NULL;
3197 struct hostent* host;
3198 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3199 char *extrabuf;
3200 int ebufsize=1024;
3201 struct hostent hostentry;
3202 int locerr = ENOBUFS;
3203 #endif
3204 char buf[100];
3205 if( !name || !name[0]) {
3206 name = buf;
3207 if( gethostname( buf, 100) == -1) {
3208 SetLastError( WSAENOBUFS); /* appropriate ? */
3209 return retval;
3212 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3213 host = NULL;
3214 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3215 while(extrabuf) {
3216 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
3217 if( res != ERANGE) break;
3218 ebufsize *=2;
3219 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3221 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3222 #else
3223 EnterCriticalSection( &csWSgetXXXbyYYY );
3224 host = gethostbyname(name);
3225 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3226 #endif
3227 if (host) retval = WS_dup_he(host);
3228 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3229 HeapFree(GetProcessHeap(),0,extrabuf);
3230 #else
3231 LeaveCriticalSection( &csWSgetXXXbyYYY );
3232 #endif
3233 TRACE( "%s ret %p\n", debugstr_a(name), retval );
3234 return retval;
3238 /***********************************************************************
3239 * getprotobyname (WS2_32.53)
3241 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
3243 struct WS_protoent* retval = NULL;
3244 #ifdef HAVE_GETPROTOBYNAME
3245 struct protoent* proto;
3246 EnterCriticalSection( &csWSgetXXXbyYYY );
3247 if( (proto = getprotobyname(name)) != NULL )
3249 retval = WS_dup_pe(proto);
3251 else {
3252 MESSAGE("protocol %s not found; You might want to add "
3253 "this to /etc/protocols\n", debugstr_a(name) );
3254 SetLastError(WSANO_DATA);
3256 LeaveCriticalSection( &csWSgetXXXbyYYY );
3257 #endif
3258 TRACE( "%s ret %p\n", debugstr_a(name), retval );
3259 return retval;
3263 /***********************************************************************
3264 * getprotobynumber (WS2_32.54)
3266 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
3268 struct WS_protoent* retval = NULL;
3269 #ifdef HAVE_GETPROTOBYNUMBER
3270 struct protoent* proto;
3271 EnterCriticalSection( &csWSgetXXXbyYYY );
3272 if( (proto = getprotobynumber(number)) != NULL )
3274 retval = WS_dup_pe(proto);
3276 else {
3277 MESSAGE("protocol number %d not found; You might want to add "
3278 "this to /etc/protocols\n", number );
3279 SetLastError(WSANO_DATA);
3281 LeaveCriticalSection( &csWSgetXXXbyYYY );
3282 #endif
3283 TRACE("%i ret %p\n", number, retval);
3284 return retval;
3288 /***********************************************************************
3289 * getservbyname (WS2_32.55)
3291 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
3293 struct WS_servent* retval = NULL;
3294 struct servent* serv;
3295 char *name_str;
3296 char *proto_str = NULL;
3298 if (!(name_str = strdup_lower(name))) return NULL;
3300 if (proto && *proto)
3302 if (!(proto_str = strdup_lower(proto)))
3304 HeapFree( GetProcessHeap(), 0, name_str );
3305 return NULL;
3309 EnterCriticalSection( &csWSgetXXXbyYYY );
3310 serv = getservbyname(name_str, proto_str);
3311 if( serv != NULL )
3313 retval = WS_dup_se(serv);
3315 else SetLastError(WSANO_DATA);
3316 LeaveCriticalSection( &csWSgetXXXbyYYY );
3317 HeapFree( GetProcessHeap(), 0, proto_str );
3318 HeapFree( GetProcessHeap(), 0, name_str );
3319 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
3320 return retval;
3323 /***********************************************************************
3324 * freeaddrinfo (WS2_32.@)
3326 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
3328 while (res) {
3329 struct WS_addrinfo *next;
3331 HeapFree(GetProcessHeap(),0,res->ai_canonname);
3332 HeapFree(GetProcessHeap(),0,res->ai_addr);
3333 next = res->ai_next;
3334 HeapFree(GetProcessHeap(),0,res);
3335 res = next;
3339 /* helper functions for getaddrinfo()/getnameinfo() */
3340 static int convert_aiflag_w2u(int winflags) {
3341 int i, unixflags = 0;
3343 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
3344 if (ws_aiflag_map[i][0] & winflags) {
3345 unixflags |= ws_aiflag_map[i][1];
3346 winflags &= ~ws_aiflag_map[i][0];
3348 if (winflags)
3349 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
3350 return unixflags;
3353 static int convert_niflag_w2u(int winflags) {
3354 int i, unixflags = 0;
3356 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
3357 if (ws_niflag_map[i][0] & winflags) {
3358 unixflags |= ws_niflag_map[i][1];
3359 winflags &= ~ws_niflag_map[i][0];
3361 if (winflags)
3362 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
3363 return unixflags;
3366 static int convert_aiflag_u2w(int unixflags) {
3367 int i, winflags = 0;
3369 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
3370 if (ws_aiflag_map[i][1] & unixflags) {
3371 winflags |= ws_aiflag_map[i][0];
3372 unixflags &= ~ws_aiflag_map[i][1];
3374 if (unixflags) /* will warn usually */
3375 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
3376 return winflags;
3379 static int convert_eai_u2w(int unixret) {
3380 int i;
3382 for (i=0;ws_eai_map[i][0];i++)
3383 if (ws_eai_map[i][1] == unixret)
3384 return ws_eai_map[i][0];
3385 return unixret;
3388 /***********************************************************************
3389 * getaddrinfo (WS2_32.@)
3391 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
3393 #if HAVE_GETADDRINFO
3394 struct addrinfo *unixaires = NULL;
3395 int result;
3396 struct addrinfo unixhints, *punixhints = NULL;
3397 CHAR *node = NULL, *serv = NULL;
3399 if (nodename)
3400 if (!(node = strdup_lower(nodename))) return WSA_NOT_ENOUGH_MEMORY;
3402 if (servname) {
3403 if (!(serv = strdup_lower(servname))) {
3404 HeapFree(GetProcessHeap(), 0, node);
3405 return WSA_NOT_ENOUGH_MEMORY;
3409 if (hints) {
3410 punixhints = &unixhints;
3412 memset(&unixhints, 0, sizeof(unixhints));
3413 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
3414 if (hints->ai_family == 0) /* wildcard, specific to getaddrinfo() */
3415 punixhints->ai_family = 0;
3416 else
3417 punixhints->ai_family = convert_af_w2u(hints->ai_family);
3418 if (hints->ai_socktype == 0) /* wildcard, specific to getaddrinfo() */
3419 punixhints->ai_socktype = 0;
3420 else
3421 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
3422 if (hints->ai_protocol == 0) /* wildcard, specific to getaddrinfo() */
3423 punixhints->ai_protocol = 0;
3424 else
3425 punixhints->ai_protocol = convert_proto_w2u(hints->ai_protocol);
3428 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
3429 result = getaddrinfo(nodename, servname, punixhints, &unixaires);
3431 TRACE("%s, %s %p -> %p %d\n", nodename, servname, hints, res, result);
3433 HeapFree(GetProcessHeap(), 0, node);
3434 HeapFree(GetProcessHeap(), 0, serv);
3436 if (!result) {
3437 struct addrinfo *xuai = unixaires;
3438 struct WS_addrinfo **xai = res;
3440 *xai = NULL;
3441 while (xuai) {
3442 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
3443 int len;
3445 if (!ai)
3446 goto outofmem;
3448 *xai = ai;xai = &ai->ai_next;
3449 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
3450 ai->ai_family = convert_af_u2w(xuai->ai_family);
3451 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
3452 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
3453 if (xuai->ai_canonname) {
3454 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
3455 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
3456 if (!ai->ai_canonname)
3457 goto outofmem;
3458 strcpy(ai->ai_canonname,xuai->ai_canonname);
3460 len = xuai->ai_addrlen;
3461 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
3462 if (!ai->ai_addr)
3463 goto outofmem;
3464 ai->ai_addrlen = len;
3465 do {
3466 int winlen = ai->ai_addrlen;
3468 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
3469 ai->ai_addrlen = winlen;
3470 break;
3472 len = 2*len;
3473 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
3474 if (!ai->ai_addr)
3475 goto outofmem;
3476 ai->ai_addrlen = len;
3477 } while (1);
3478 xuai = xuai->ai_next;
3480 freeaddrinfo(unixaires);
3481 } else {
3482 result = convert_eai_u2w(result);
3483 *res = NULL;
3485 return result;
3487 outofmem:
3488 if (*res) WS_freeaddrinfo(*res);
3489 if (unixaires) freeaddrinfo(unixaires);
3490 *res = NULL;
3491 return WSA_NOT_ENOUGH_MEMORY;
3492 #else
3493 FIXME("getaddrinfo() failed, not found during buildtime.\n");
3494 return EAI_FAIL;
3495 #endif
3498 /***********************************************************************
3499 * GetAddrInfoW (WS2_32.@)
3501 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
3503 FIXME("empty stub!\n");
3504 return EAI_FAIL;
3507 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
3508 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
3510 #if HAVE_GETNAMEINFO
3511 int ret;
3512 union generic_unix_sockaddr sa_u;
3513 unsigned int size;
3515 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
3516 serv, servlen, flags);
3518 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
3519 if (!size)
3521 WSASetLastError(WSAEFAULT);
3522 return WSA_NOT_ENOUGH_MEMORY;
3524 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
3525 return convert_eai_u2w(ret);
3526 #else
3527 FIXME("getnameinfo() failed, not found during buildtime.\n");
3528 return EAI_FAIL;
3529 #endif
3532 /***********************************************************************
3533 * getservbyport (WS2_32.56)
3535 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
3537 struct WS_servent* retval = NULL;
3538 #ifdef HAVE_GETSERVBYPORT
3539 struct servent* serv;
3540 char *proto_str = NULL;
3542 if (proto && *proto)
3544 if (!(proto_str = strdup_lower(proto))) return NULL;
3546 EnterCriticalSection( &csWSgetXXXbyYYY );
3547 if( (serv = getservbyport(port, proto_str)) != NULL ) {
3548 retval = WS_dup_se(serv);
3550 else SetLastError(WSANO_DATA);
3551 LeaveCriticalSection( &csWSgetXXXbyYYY );
3552 HeapFree( GetProcessHeap(), 0, proto_str );
3553 #endif
3554 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
3555 return retval;
3559 /***********************************************************************
3560 * gethostname (WS2_32.57)
3562 int WINAPI WS_gethostname(char *name, int namelen)
3564 TRACE("name %p, len %d\n", name, namelen);
3566 if (gethostname(name, namelen) == 0)
3568 TRACE("<- '%s'\n", name);
3569 return 0;
3571 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
3572 TRACE("<- ERROR !\n");
3573 return SOCKET_ERROR;
3577 /* ------------------------------------- Windows sockets extensions -- *
3579 * ------------------------------------------------------------------- */
3581 /***********************************************************************
3582 * WSAEnumNetworkEvents (WS2_32.36)
3584 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
3586 int ret;
3588 TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
3590 SERVER_START_REQ( get_socket_event )
3592 req->handle = SOCKET2HANDLE(s);
3593 req->service = TRUE;
3594 req->c_event = hEvent;
3595 wine_server_set_reply( req, lpEvent->iErrorCode, sizeof(lpEvent->iErrorCode) );
3596 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
3598 SERVER_END_REQ;
3599 if (!ret) return 0;
3600 SetLastError(WSAEINVAL);
3601 return SOCKET_ERROR;
3604 /***********************************************************************
3605 * WSAEventSelect (WS2_32.39)
3607 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
3609 int ret;
3611 TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
3613 SERVER_START_REQ( set_socket_event )
3615 req->handle = SOCKET2HANDLE(s);
3616 req->mask = lEvent;
3617 req->event = hEvent;
3618 req->window = 0;
3619 req->msg = 0;
3620 ret = wine_server_call( req );
3622 SERVER_END_REQ;
3623 if (!ret) return 0;
3624 SetLastError(WSAEINVAL);
3625 return SOCKET_ERROR;
3628 /**********************************************************************
3629 * WSAGetOverlappedResult (WS2_32.40)
3631 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
3632 LPDWORD lpcbTransfer, BOOL fWait,
3633 LPDWORD lpdwFlags )
3635 NTSTATUS status;
3637 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
3638 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
3640 if ( lpOverlapped == NULL )
3642 ERR( "Invalid pointer\n" );
3643 WSASetLastError(WSA_INVALID_PARAMETER);
3644 return FALSE;
3647 status = lpOverlapped->Internal;
3648 if (status == STATUS_PENDING)
3650 if (!fWait)
3652 SetLastError( WSA_IO_INCOMPLETE );
3653 return FALSE;
3656 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
3657 INFINITE ) == WAIT_FAILED)
3658 return FALSE;
3659 status = lpOverlapped->Internal;
3662 if ( lpcbTransfer )
3663 *lpcbTransfer = lpOverlapped->InternalHigh;
3665 if ( lpdwFlags )
3666 *lpdwFlags = lpOverlapped->u.s.Offset;
3668 if (status) SetLastError( RtlNtStatusToDosError(status) );
3669 return !status;
3673 /***********************************************************************
3674 * WSAAsyncSelect (WS2_32.101)
3676 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
3678 int ret;
3680 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
3682 SERVER_START_REQ( set_socket_event )
3684 req->handle = SOCKET2HANDLE(s);
3685 req->mask = lEvent;
3686 req->event = 0;
3687 req->window = hWnd;
3688 req->msg = uMsg;
3689 ret = wine_server_call( req );
3691 SERVER_END_REQ;
3692 if (!ret) return 0;
3693 SetLastError(WSAEINVAL);
3694 return SOCKET_ERROR;
3697 /***********************************************************************
3698 * WSACreateEvent (WS2_32.31)
3701 WSAEVENT WINAPI WSACreateEvent(void)
3703 /* Create a manual-reset event, with initial state: unsignaled */
3704 TRACE("\n");
3706 return CreateEventW(NULL, TRUE, FALSE, NULL);
3709 /***********************************************************************
3710 * WSACloseEvent (WS2_32.29)
3713 BOOL WINAPI WSACloseEvent(WSAEVENT event)
3715 TRACE ("event=%p\n", event);
3717 return CloseHandle(event);
3720 /***********************************************************************
3721 * WSASocketA (WS2_32.78)
3724 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
3725 LPWSAPROTOCOL_INFOA lpProtocolInfo,
3726 GROUP g, DWORD dwFlags)
3728 INT len;
3729 WSAPROTOCOL_INFOW info;
3731 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
3732 af, type, protocol, lpProtocolInfo, g, dwFlags);
3734 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
3736 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
3737 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
3738 info.szProtocol, WSAPROTOCOL_LEN + 1);
3740 if (!len)
3742 WSASetLastError( WSAEINVAL);
3743 return SOCKET_ERROR;
3746 return WSASocketW(af, type, protocol, &info, g, dwFlags);
3749 /***********************************************************************
3750 * WSASocketW (WS2_32.79)
3753 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
3754 LPWSAPROTOCOL_INFOW lpProtocolInfo,
3755 GROUP g, DWORD dwFlags)
3757 SOCKET ret;
3760 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
3761 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
3764 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
3765 af, type, protocol, lpProtocolInfo, g, dwFlags );
3767 /* hack for WSADuplicateSocket */
3768 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
3769 ret = lpProtocolInfo->dwCatalogEntryId;
3770 TRACE("\tgot duplicate %04lx\n", ret);
3771 return ret;
3774 /* check and convert the socket family */
3775 af = convert_af_w2u(af);
3776 if (af == -1)
3778 FIXME("Unsupported socket family %d!\n", af);
3779 SetLastError(WSAEAFNOSUPPORT);
3780 return INVALID_SOCKET;
3783 /* check the socket type */
3784 type = convert_socktype_w2u(type);
3785 if (type == -1)
3787 SetLastError(WSAESOCKTNOSUPPORT);
3788 return INVALID_SOCKET;
3791 /* check the protocol type */
3792 if ( protocol < 0 ) /* don't support negative values */
3794 SetLastError(WSAEPROTONOSUPPORT);
3795 return INVALID_SOCKET;
3798 if ( af == AF_UNSPEC) /* did they not specify the address family? */
3799 switch(protocol)
3801 case IPPROTO_TCP:
3802 if (type == SOCK_STREAM) { af = AF_INET; break; }
3803 case IPPROTO_UDP:
3804 if (type == SOCK_DGRAM) { af = AF_INET; break; }
3805 default: SetLastError(WSAEPROTOTYPE); return INVALID_SOCKET;
3808 SERVER_START_REQ( create_socket )
3810 req->family = af;
3811 req->type = type;
3812 req->protocol = protocol;
3813 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
3814 req->attributes = OBJ_INHERIT;
3815 req->flags = dwFlags;
3816 set_error( wine_server_call( req ) );
3817 ret = HANDLE2SOCKET( reply->handle );
3819 SERVER_END_REQ;
3820 if (ret)
3822 TRACE("\tcreated %04lx\n", ret );
3823 return ret;
3826 if (GetLastError() == WSAEACCES) /* raw socket denied */
3828 if (type == SOCK_RAW)
3829 MESSAGE("WARNING: Trying to create a socket of type SOCK_RAW, this"
3830 " will fail unless you have special permissions.\n");
3831 else
3832 MESSAGE("WS_SOCKET: Failed to create socket, this requires"
3833 " special permissions.\n");
3834 SetLastError(WSAESOCKTNOSUPPORT);
3837 WARN("\t\tfailed!\n");
3838 return INVALID_SOCKET;
3841 /***********************************************************************
3842 * WSAJoinLeaf (WS2_32.58)
3845 SOCKET WINAPI WSAJoinLeaf(
3846 SOCKET s,
3847 const struct WS_sockaddr *addr,
3848 int addrlen,
3849 LPWSABUF lpCallerData,
3850 LPWSABUF lpCalleeData,
3851 LPQOS lpSQOS,
3852 LPQOS lpGQOS,
3853 DWORD dwFlags)
3855 FIXME("stub.\n");
3856 return INVALID_SOCKET;
3859 /***********************************************************************
3860 * __WSAFDIsSet (WS2_32.151)
3862 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
3864 int i = set->fd_count;
3866 TRACE("(%ld,%p(%i))\n", s, set, i);
3868 while (i--)
3869 if (set->fd_array[i] == s) return 1;
3870 return 0;
3873 /***********************************************************************
3874 * WSAIsBlocking (WINSOCK.114)
3875 * WSAIsBlocking (WS2_32.114)
3877 BOOL WINAPI WSAIsBlocking(void)
3879 /* By default WinSock should set all its sockets to non-blocking mode
3880 * and poll in PeekMessage loop when processing "blocking" ones. This
3881 * function is supposed to tell if the program is in this loop. Our
3882 * blocking calls are truly blocking so we always return FALSE.
3884 * Note: It is allowed to call this function without prior WSAStartup().
3887 TRACE("\n");
3888 return FALSE;
3891 /***********************************************************************
3892 * WSACancelBlockingCall (WINSOCK.113)
3893 * WSACancelBlockingCall (WS2_32.113)
3895 INT WINAPI WSACancelBlockingCall(void)
3897 TRACE("\n");
3898 return 0;
3901 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
3903 FIXME("How was this called?\n");
3904 return x();
3908 /***********************************************************************
3909 * WSASetBlockingHook (WS2_32.109)
3911 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
3913 FARPROC prev = blocking_hook;
3914 blocking_hook = lpBlockFunc;
3915 TRACE("hook %p\n", lpBlockFunc);
3916 return prev;
3920 /***********************************************************************
3921 * WSAUnhookBlockingHook (WS2_32.110)
3923 INT WINAPI WSAUnhookBlockingHook(void)
3925 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
3926 return 0;
3930 /* ----------------------------------- end of API stuff */
3932 /* ----------------------------------- helper functions -
3934 * TODO: Merge WS_dup_..() stuff into one function that
3935 * would operate with a generic structure containing internal
3936 * pointers (via a template of some kind).
3939 static int list_size(char** l, int item_size)
3941 int i,j = 0;
3942 if(l)
3943 { for(i=0;l[i];i++)
3944 j += (item_size) ? item_size : strlen(l[i]) + 1;
3945 j += (i + 1) * sizeof(char*); }
3946 return j;
3949 static int list_dup(char** l_src, char** l_to, int item_size)
3951 char *p;
3952 int i;
3954 for (i = 0; l_src[i]; i++) ;
3955 p = (char *)(l_to + i + 1);
3956 for (i = 0; l_src[i]; i++)
3958 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
3959 memcpy(p, l_src[i], count);
3960 l_to[i] = p;
3961 p += count;
3963 l_to[i] = NULL;
3964 return p - (char *)l_to;
3967 /* ----- hostent */
3969 /* duplicate hostent entry
3970 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
3971 * Ditto for protoent and servent.
3973 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
3975 char *p;
3976 struct WS_hostent *p_to;
3978 int size = (sizeof(*p_he) +
3979 strlen(p_he->h_name) + 1 +
3980 list_size(p_he->h_aliases, 0) +
3981 list_size(p_he->h_addr_list, p_he->h_length));
3983 if (!(p_to = check_buffer_he(size))) return NULL;
3984 p_to->h_addrtype = p_he->h_addrtype;
3985 p_to->h_length = p_he->h_length;
3987 p = (char *)(p_to + 1);
3988 p_to->h_name = p;
3989 strcpy(p, p_he->h_name);
3990 p += strlen(p) + 1;
3992 p_to->h_aliases = (char **)p;
3993 p += list_dup(p_he->h_aliases, p_to->h_aliases, 0);
3995 p_to->h_addr_list = (char **)p;
3996 list_dup(p_he->h_addr_list, p_to->h_addr_list, p_he->h_length);
3997 return p_to;
4000 /* ----- protoent */
4002 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
4004 char *p;
4005 struct WS_protoent *p_to;
4007 int size = (sizeof(*p_pe) +
4008 strlen(p_pe->p_name) + 1 +
4009 list_size(p_pe->p_aliases, 0));
4011 if (!(p_to = check_buffer_pe(size))) return NULL;
4012 p_to->p_proto = p_pe->p_proto;
4014 p = (char *)(p_to + 1);
4015 p_to->p_name = p;
4016 strcpy(p, p_pe->p_name);
4017 p += strlen(p) + 1;
4019 p_to->p_aliases = (char **)p;
4020 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
4021 return p_to;
4024 /* ----- servent */
4026 static struct WS_servent *WS_dup_se(const struct servent* p_se)
4028 char *p;
4029 struct WS_servent *p_to;
4031 int size = (sizeof(*p_se) +
4032 strlen(p_se->s_proto) + 1 +
4033 strlen(p_se->s_name) + 1 +
4034 list_size(p_se->s_aliases, 0));
4036 if (!(p_to = check_buffer_se(size))) return NULL;
4037 p_to->s_port = p_se->s_port;
4039 p = (char *)(p_to + 1);
4040 p_to->s_name = p;
4041 strcpy(p, p_se->s_name);
4042 p += strlen(p) + 1;
4044 p_to->s_proto = p;
4045 strcpy(p, p_se->s_proto);
4046 p += strlen(p) + 1;
4048 p_to->s_aliases = (char **)p;
4049 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
4050 return p_to;
4053 /* ----------------------------------- error handling */
4055 UINT wsaErrno(void)
4057 int loc_errno = errno;
4058 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
4060 switch(loc_errno)
4062 case EINTR: return WSAEINTR;
4063 case EBADF: return WSAEBADF;
4064 case EPERM:
4065 case EACCES: return WSAEACCES;
4066 case EFAULT: return WSAEFAULT;
4067 case EINVAL: return WSAEINVAL;
4068 case EMFILE: return WSAEMFILE;
4069 case EWOULDBLOCK: return WSAEWOULDBLOCK;
4070 case EINPROGRESS: return WSAEINPROGRESS;
4071 case EALREADY: return WSAEALREADY;
4072 case ENOTSOCK: return WSAENOTSOCK;
4073 case EDESTADDRREQ: return WSAEDESTADDRREQ;
4074 case EMSGSIZE: return WSAEMSGSIZE;
4075 case EPROTOTYPE: return WSAEPROTOTYPE;
4076 case ENOPROTOOPT: return WSAENOPROTOOPT;
4077 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
4078 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
4079 case EOPNOTSUPP: return WSAEOPNOTSUPP;
4080 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
4081 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
4082 case EADDRINUSE: return WSAEADDRINUSE;
4083 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
4084 case ENETDOWN: return WSAENETDOWN;
4085 case ENETUNREACH: return WSAENETUNREACH;
4086 case ENETRESET: return WSAENETRESET;
4087 case ECONNABORTED: return WSAECONNABORTED;
4088 case EPIPE:
4089 case ECONNRESET: return WSAECONNRESET;
4090 case ENOBUFS: return WSAENOBUFS;
4091 case EISCONN: return WSAEISCONN;
4092 case ENOTCONN: return WSAENOTCONN;
4093 case ESHUTDOWN: return WSAESHUTDOWN;
4094 case ETOOMANYREFS: return WSAETOOMANYREFS;
4095 case ETIMEDOUT: return WSAETIMEDOUT;
4096 case ECONNREFUSED: return WSAECONNREFUSED;
4097 case ELOOP: return WSAELOOP;
4098 case ENAMETOOLONG: return WSAENAMETOOLONG;
4099 case EHOSTDOWN: return WSAEHOSTDOWN;
4100 case EHOSTUNREACH: return WSAEHOSTUNREACH;
4101 case ENOTEMPTY: return WSAENOTEMPTY;
4102 #ifdef EPROCLIM
4103 case EPROCLIM: return WSAEPROCLIM;
4104 #endif
4105 #ifdef EUSERS
4106 case EUSERS: return WSAEUSERS;
4107 #endif
4108 #ifdef EDQUOT
4109 case EDQUOT: return WSAEDQUOT;
4110 #endif
4111 #ifdef ESTALE
4112 case ESTALE: return WSAESTALE;
4113 #endif
4114 #ifdef EREMOTE
4115 case EREMOTE: return WSAEREMOTE;
4116 #endif
4118 /* just in case we ever get here and there are no problems */
4119 case 0: return 0;
4120 default:
4121 WARN("Unknown errno %d!\n", loc_errno);
4122 return WSAEOPNOTSUPP;
4126 UINT wsaHerrno(int loc_errno)
4129 WARN("h_errno %d.\n", loc_errno);
4131 switch(loc_errno)
4133 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
4134 case TRY_AGAIN: return WSATRY_AGAIN;
4135 case NO_RECOVERY: return WSANO_RECOVERY;
4136 case NO_DATA: return WSANO_DATA;
4137 case ENOBUFS: return WSAENOBUFS;
4139 case 0: return 0;
4140 default:
4141 WARN("Unknown h_errno %d!\n", loc_errno);
4142 return WSAEOPNOTSUPP;
4147 /***********************************************************************
4148 * WSARecv (WS2_32.67)
4150 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4151 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
4152 LPWSAOVERLAPPED lpOverlapped,
4153 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
4155 return WSARecvFrom(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
4156 NULL, NULL, lpOverlapped, lpCompletionRoutine);
4159 /***********************************************************************
4160 * WSARecvFrom (WS2_32.69)
4162 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4163 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
4164 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
4165 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4168 unsigned int i, options;
4169 int n, fd, err;
4170 DWORD timeout_start = GetTickCount();
4171 struct iovec iovec[WS_MSG_MAXIOVLEN];
4172 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
4174 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
4175 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
4176 (lpFromlen ? *lpFromlen : -1),
4177 lpOverlapped, lpCompletionRoutine);
4179 if (dwBufferCount > WS_MSG_MAXIOVLEN)
4181 WSASetLastError( WSAEINVAL );
4182 return SOCKET_ERROR;
4185 fd = get_sock_fd( s, FILE_READ_DATA, &options );
4186 TRACE( "fd=%d, options=%x\n", fd, options );
4188 if (fd == -1) return SOCKET_ERROR;
4190 for (i = 0; i < dwBufferCount; i++)
4192 iovec[i].iov_base = lpBuffers[i].buf;
4193 iovec[i].iov_len = lpBuffers[i].len;
4196 for (;;)
4198 n = WS2_recv( fd, iovec, dwBufferCount, lpFrom, lpFromlen, lpFlags );
4199 if (n == -1)
4201 if (errno == EINTR) continue;
4202 if (errno != EAGAIN)
4204 err = wsaErrno();
4205 if (cvalue) WS_AddCompletion( s, cvalue, err, 0 );
4206 goto error;
4209 else
4210 *lpNumberOfBytesRecvd = n;
4212 if ((lpOverlapped || lpCompletionRoutine) &&
4213 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
4215 IO_STATUS_BLOCK *iosb;
4216 struct ws2_async *wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
4218 if ( !wsa )
4220 err = WSAEFAULT;
4221 goto error;
4223 release_sock_fd( s, fd );
4225 wsa->hSocket = SOCKET2HANDLE(s);
4226 wsa->flags = *lpFlags;
4227 wsa->addr = lpFrom;
4228 wsa->addrlen.ptr = lpFromlen;
4229 wsa->user_overlapped = lpOverlapped;
4230 wsa->completion_func = lpCompletionRoutine;
4231 wsa->n_iovecs = dwBufferCount;
4232 memcpy( wsa->iovec, iovec, dwBufferCount * sizeof(*iovec) );
4234 iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
4236 if (n == -1)
4238 iosb->u.Status = STATUS_PENDING;
4239 iosb->Information = 0;
4241 SERVER_START_REQ( register_async )
4243 req->handle = wsa->hSocket;
4244 req->type = ASYNC_TYPE_READ;
4245 req->async.callback = WS2_async_recv;
4246 req->async.iosb = iosb;
4247 req->async.arg = wsa;
4248 req->async.apc = ws2_async_apc;
4249 req->async.event = lpCompletionRoutine ? 0 : lpOverlapped->hEvent;
4250 req->async.cvalue = cvalue;
4251 err = wine_server_call( req );
4253 SERVER_END_REQ;
4255 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
4256 WSASetLastError( NtStatusToWSAError( err ));
4257 return SOCKET_ERROR;
4260 iosb->u.Status = STATUS_SUCCESS;
4261 iosb->Information = n;
4262 if (!wsa->completion_func)
4264 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
4265 SetEvent( lpOverlapped->hEvent );
4266 HeapFree( GetProcessHeap(), 0, wsa );
4268 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
4269 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
4270 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4271 return 0;
4274 if (n != -1) break;
4276 if ( _is_blocking(s) )
4278 struct pollfd pfd;
4279 int timeout = GET_RCVTIMEO(fd);
4280 if (timeout != -1)
4282 timeout -= GetTickCount() - timeout_start;
4283 if (timeout < 0) timeout = 0;
4286 pfd.fd = fd;
4287 pfd.events = POLLIN;
4288 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
4290 if (!timeout || !poll( &pfd, 1, timeout ))
4292 err = WSAETIMEDOUT;
4293 /* a timeout is not fatal */
4294 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4295 goto error;
4298 else
4300 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4301 err = WSAEWOULDBLOCK;
4302 goto error;
4306 TRACE(" -> %i bytes\n", n);
4307 release_sock_fd( s, fd );
4308 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4310 return 0;
4312 error:
4313 release_sock_fd( s, fd );
4314 WARN(" -> ERROR %d\n", err);
4315 WSASetLastError( err );
4316 return SOCKET_ERROR;
4319 /***********************************************************************
4320 * WSCInstallProvider (WS2_32.88)
4322 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
4323 LPCWSTR lpszProviderDllPath,
4324 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
4325 DWORD dwNumberOfEntries,
4326 LPINT lpErrno )
4328 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
4329 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
4330 dwNumberOfEntries, lpErrno);
4331 *lpErrno = 0;
4332 return 0;
4336 /***********************************************************************
4337 * WSCDeinstallProvider (WS2_32.83)
4339 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
4341 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
4342 *lpErrno = 0;
4343 return 0;
4347 /***********************************************************************
4348 * WSAAccept (WS2_32.26)
4350 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
4351 LPCONDITIONPROC lpfnCondition, DWORD dwCallbackData)
4354 int ret = 0, size = 0;
4355 WSABUF CallerId, CallerData, CalleeId, CalleeData;
4356 /* QOS SQOS, GQOS; */
4357 GROUP g;
4358 SOCKET cs;
4359 SOCKADDR src_addr, dst_addr;
4361 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %d\n",
4362 s, addr, addrlen, lpfnCondition, dwCallbackData);
4365 size = sizeof(src_addr);
4366 cs = WS_accept(s, &src_addr, &size);
4368 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
4370 CallerId.buf = (char *)&src_addr;
4371 CallerId.len = sizeof(src_addr);
4373 CallerData.buf = NULL;
4374 CallerData.len = (ULONG)NULL;
4376 WS_getsockname(cs, &dst_addr, &size);
4378 CalleeId.buf = (char *)&dst_addr;
4379 CalleeId.len = sizeof(dst_addr);
4382 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
4383 &CalleeId, &CalleeData, &g, dwCallbackData);
4385 switch (ret)
4387 case CF_ACCEPT:
4388 if (addr && addrlen)
4389 addr = memcpy(addr, &src_addr, (*addrlen > size) ? size : *addrlen );
4390 return cs;
4391 case CF_DEFER:
4392 SERVER_START_REQ( set_socket_deferred )
4394 req->handle = SOCKET2HANDLE(s);
4395 req->deferred = SOCKET2HANDLE(cs);
4396 if ( !wine_server_call_err ( req ) )
4398 SetLastError( WSATRY_AGAIN );
4399 WS_closesocket( cs );
4402 SERVER_END_REQ;
4403 return SOCKET_ERROR;
4404 case CF_REJECT:
4405 WS_closesocket(cs);
4406 SetLastError(WSAECONNREFUSED);
4407 return SOCKET_ERROR;
4408 default:
4409 FIXME("Unknown return type from Condition function\n");
4410 SetLastError(WSAENOTSOCK);
4411 return SOCKET_ERROR;
4415 /***********************************************************************
4416 * WSADuplicateSocketA (WS2_32.32)
4418 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
4420 HANDLE hProcess;
4422 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
4423 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
4424 /* FIXME: WS_getsockopt(s, WS_SOL_SOCKET, SO_PROTOCOL_INFO, lpProtocolInfo, sizeof(*lpProtocolInfo)); */
4425 /* I don't know what the real Windoze does next, this is a hack */
4426 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
4427 * the target use the global duplicate, or we could copy a reference to us to the structure
4428 * and let the target duplicate it from us, but let's do it as simple as possible */
4429 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
4430 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
4431 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
4432 0, FALSE, DUPLICATE_SAME_ACCESS);
4433 CloseHandle(hProcess);
4434 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
4435 return 0;
4438 /***********************************************************************
4439 * WSADuplicateSocketW (WS2_32.33)
4441 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
4443 HANDLE hProcess;
4445 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
4447 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
4448 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
4449 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
4450 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
4451 0, FALSE, DUPLICATE_SAME_ACCESS);
4452 CloseHandle(hProcess);
4453 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
4454 return 0;
4457 /***********************************************************************
4458 * WSAInstallServiceClassA (WS2_32.48)
4460 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
4462 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
4463 WSASetLastError(WSAEACCES);
4464 return SOCKET_ERROR;
4467 /***********************************************************************
4468 * WSAInstallServiceClassW (WS2_32.49)
4470 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
4472 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
4473 WSASetLastError(WSAEACCES);
4474 return SOCKET_ERROR;
4477 /***********************************************************************
4478 * WSARemoveServiceClass (WS2_32.70)
4480 int WINAPI WSARemoveServiceClass(LPGUID info)
4482 FIXME("Request to remove service %p\n",info);
4483 WSASetLastError(WSATYPE_NOT_FOUND);
4484 return SOCKET_ERROR;
4487 /***********************************************************************
4488 * WSAStringToAddressA (WS2_32.80)
4490 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
4491 INT AddressFamily,
4492 LPWSAPROTOCOL_INFOA lpProtocolInfo,
4493 LPSOCKADDR lpAddress,
4494 LPINT lpAddressLength)
4496 INT res=0;
4497 LPSTR workBuffer=NULL,ptrPort;
4499 TRACE( "(%s, %x, %p, %p, %p)\n", AddressString, AddressFamily, lpProtocolInfo,
4500 lpAddress, lpAddressLength );
4502 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
4504 if (!AddressString)
4506 WSASetLastError(WSAEINVAL);
4507 return SOCKET_ERROR;
4510 if (lpProtocolInfo)
4511 FIXME("ProtocolInfo not implemented.\n");
4513 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
4514 strlen(AddressString) + 1);
4515 if (!workBuffer)
4517 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4518 return SOCKET_ERROR;
4521 strcpy(workBuffer, AddressString);
4523 switch(AddressFamily)
4525 case WS_AF_INET:
4527 struct in_addr inetaddr;
4529 /* If lpAddressLength is too small, tell caller the size we need */
4530 if (*lpAddressLength < sizeof(SOCKADDR_IN))
4532 *lpAddressLength = sizeof(SOCKADDR_IN);
4533 res = WSAEFAULT;
4534 break;
4536 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
4538 ((LPSOCKADDR_IN)lpAddress)->sin_family = AF_INET;
4540 ptrPort = strchr(workBuffer, ':');
4541 if(ptrPort)
4543 ((LPSOCKADDR_IN)lpAddress)->sin_port = (WS_u_short)atoi(ptrPort+1);
4544 *ptrPort = '\0';
4546 else
4548 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
4551 if(inet_aton(workBuffer, &inetaddr) > 0)
4553 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
4554 res = 0;
4556 else
4557 res = WSAEINVAL;
4559 break;
4562 case WS_AF_INET6:
4564 struct in6_addr inetaddr;
4565 /* If lpAddressLength is too small, tell caller the size we need */
4566 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
4568 *lpAddressLength = sizeof(SOCKADDR_IN6);
4569 res = WSAEFAULT;
4570 break;
4572 #ifdef HAVE_INET_PTON
4573 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
4575 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
4577 /* This one is a bit tricky. An IPv6 address contains colons, so the
4578 * check from IPv4 doesn't work like that. However, IPv6 addresses that
4579 * contain a port are written with braces like [fd12:3456:7890::1]:12345
4580 * so what we will do is to look for ']', check if the next char is a
4581 * colon, and if it is, parse the port as in IPv4. */
4583 ptrPort = strchr(workBuffer, ']');
4584 if(ptrPort && *(++ptrPort) == ':')
4586 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = (WS_u_short)atoi(ptrPort+1);
4587 *ptrPort = '\0';
4589 else
4591 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
4594 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
4596 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
4597 sizeof(struct in6_addr));
4598 res = 0;
4600 else
4601 #endif /* HAVE_INET_PTON */
4602 res = WSAEINVAL;
4604 break;
4606 default:
4607 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
4608 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
4609 res = WSAEINVAL;
4612 HeapFree(GetProcessHeap(), 0, workBuffer);
4614 if (!res) return 0;
4615 WSASetLastError(res);
4616 return SOCKET_ERROR;
4619 /***********************************************************************
4620 * WSAStringToAddressW (WS2_32.81)
4622 * Does anybody know if this functions allows to use hebrew/arabic/chinese... digits?
4623 * If this should be the case, it would be required to map these digits
4624 * to Unicode digits (0-9) using FoldString first.
4626 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
4627 INT AddressFamily,
4628 LPWSAPROTOCOL_INFOW lpProtocolInfo,
4629 LPSOCKADDR lpAddress,
4630 LPINT lpAddressLength)
4632 INT sBuffer,res=0;
4633 LPSTR workBuffer=NULL;
4634 WSAPROTOCOL_INFOA infoA;
4635 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
4637 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
4638 lpAddress, lpAddressLength );
4640 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
4642 /* if ProtocolInfo is available - convert to ANSI variant */
4643 if (lpProtocolInfo)
4645 lpProtoInfoA = &infoA;
4646 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
4648 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
4649 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
4651 WSASetLastError( WSAEINVAL);
4652 return SOCKET_ERROR;
4656 if (AddressString)
4658 /* Translate AddressString to ANSI code page - assumes that only
4659 standard digits 0-9 are used with this API call */
4660 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
4661 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
4663 if (workBuffer)
4665 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
4666 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
4667 lpAddress,lpAddressLength);
4668 HeapFree( GetProcessHeap(), 0, workBuffer );
4669 return res;
4671 else
4672 res = WSA_NOT_ENOUGH_MEMORY;
4674 else
4675 res = WSAEINVAL;
4677 WSASetLastError(res);
4678 return SOCKET_ERROR;
4681 /***********************************************************************
4682 * WSAAddressToStringA (WS2_32.27)
4684 * See WSAAddressToStringW
4686 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
4687 LPWSAPROTOCOL_INFOA info, LPSTR string,
4688 LPDWORD lenstr )
4690 INT size;
4691 CHAR buffer[22]; /* 12 digits + 3 dots + ':' + 5 digits + '\0' */
4692 CHAR *p;
4694 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
4696 if (!sockaddr || len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
4697 if (!string || !lenstr) return SOCKET_ERROR;
4699 /* sin_family is guaranteed to be the first u_short */
4700 if (((SOCKADDR_IN *)sockaddr)->sin_family != AF_INET) return SOCKET_ERROR;
4702 sprintf( buffer, "%u.%u.%u.%u:%u",
4703 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
4704 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
4705 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
4706 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
4707 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
4709 p = strchr( buffer, ':' );
4710 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
4712 size = strlen( buffer );
4714 if (*lenstr < size)
4716 *lenstr = size;
4717 WSASetLastError(WSAEFAULT);
4718 return SOCKET_ERROR;
4721 strcpy( string, buffer );
4722 return 0;
4725 /***********************************************************************
4726 * WSAAddressToStringW (WS2_32.28)
4728 * Convert a sockaddr address into a readable address string.
4730 * PARAMS
4731 * sockaddr [I] Pointer to a sockaddr structure.
4732 * len [I] Size of the sockaddr structure.
4733 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
4734 * string [I/O] Pointer to a buffer to receive the address string.
4735 * lenstr [I/O] Size of the receive buffer in WCHARs.
4737 * RETURNS
4738 * Success: 0
4739 * Failure: SOCKET_ERROR
4741 * NOTES
4742 * The 'info' parameter is ignored.
4744 * BUGS
4745 * Only supports AF_INET addresses.
4747 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
4748 LPWSAPROTOCOL_INFOW info, LPWSTR string,
4749 LPDWORD lenstr )
4751 INT size;
4752 WCHAR buffer[22]; /* 12 digits + 3 dots + ':' + 5 digits + '\0' */
4753 static const WCHAR format[] = { '%','u','.','%','u','.','%','u','.','%','u',':','%','u',0 };
4754 WCHAR *p;
4756 TRACE( "(%p, %x, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
4758 if (!sockaddr || len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
4759 if (!string || !lenstr) return SOCKET_ERROR;
4761 /* sin_family is guaranteed to be the first u_short */
4762 if (((SOCKADDR_IN *)sockaddr)->sin_family != AF_INET) return SOCKET_ERROR;
4764 sprintfW( buffer, format,
4765 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
4766 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
4767 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
4768 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
4769 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
4771 p = strchrW( buffer, ':' );
4772 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
4774 size = lstrlenW( buffer );
4776 if (*lenstr < size)
4778 *lenstr = size;
4779 return SOCKET_ERROR;
4782 lstrcpyW( string, buffer );
4783 return 0;
4786 /***********************************************************************
4787 * WSAEnumNameSpaceProvidersA (WS2_32.34)
4789 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
4791 FIXME( "(%p %p) Stub!\n", len, buffer );
4792 return 0;
4795 /***********************************************************************
4796 * WSAEnumNameSpaceProvidersW (WS2_32.35)
4798 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
4800 FIXME( "(%p %p) Stub!\n", len, buffer );
4801 return 0;
4804 /***********************************************************************
4805 * WSAGetQOSByName (WS2_32.41)
4807 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
4809 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
4810 return FALSE;
4813 /***********************************************************************
4814 * WSAGetServiceClassInfoA (WS2_32.42)
4816 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
4817 LPWSASERVICECLASSINFOA info )
4819 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
4820 len, info );
4821 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4822 return SOCKET_ERROR;
4825 /***********************************************************************
4826 * WSAGetServiceClassInfoW (WS2_32.43)
4828 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
4829 LPWSASERVICECLASSINFOW info )
4831 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
4832 len, info );
4833 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4834 return SOCKET_ERROR;
4837 /***********************************************************************
4838 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
4840 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
4842 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
4843 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4844 return SOCKET_ERROR;
4847 /***********************************************************************
4848 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
4850 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
4852 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
4853 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4854 return SOCKET_ERROR;
4857 /***********************************************************************
4858 * WSALookupServiceBeginA (WS2_32.59)
4860 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
4861 DWORD dwControlFlags,
4862 LPHANDLE lphLookup)
4864 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
4865 lphLookup);
4866 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4867 return SOCKET_ERROR;
4870 /***********************************************************************
4871 * WSALookupServiceBeginW (WS2_32.60)
4873 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
4874 DWORD dwControlFlags,
4875 LPHANDLE lphLookup)
4877 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
4878 lphLookup);
4879 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4880 return SOCKET_ERROR;
4883 /***********************************************************************
4884 * WSALookupServiceBeginW (WS2_32.61)
4886 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
4888 FIXME("(%p) Stub!\n", lookup );
4889 return 0;
4892 /***********************************************************************
4893 * WSALookupServiceNextA (WS2_32.62)
4895 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
4897 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
4898 return 0;
4901 /***********************************************************************
4902 * WSALookupServiceNextW (WS2_32.63)
4904 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
4906 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
4907 return 0;
4910 /***********************************************************************
4911 * WSANtohl (WS2_32.64)
4913 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
4915 TRACE( "(0x%04lx 0x%08x %p)\n", s, netlong, lphostlong );
4917 if (!lphostlong) return WSAEFAULT;
4919 *lphostlong = ntohl( netlong );
4920 return 0;
4923 /***********************************************************************
4924 * WSANtohs (WS2_32.65)
4926 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
4928 TRACE( "(0x%04lx 0x%08x %p)\n", s, netshort, lphostshort );
4930 if (!lphostshort) return WSAEFAULT;
4932 *lphostshort = ntohs( netshort );
4933 return 0;
4936 /***********************************************************************
4937 * WSAProviderConfigChange (WS2_32.66)
4939 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
4940 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
4942 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
4943 return SOCKET_ERROR;
4946 /***********************************************************************
4947 * WSARecvDisconnect (WS2_32.68)
4949 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
4951 TRACE( "(0x%04lx %p)\n", s, disconnectdata );
4953 return WS_shutdown( s, 0 );
4956 /***********************************************************************
4957 * WSASetServiceA (WS2_32.76)
4959 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
4961 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
4962 return 0;
4965 /***********************************************************************
4966 * WSASetServiceW (WS2_32.77)
4968 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
4970 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
4971 return 0;
4974 /***********************************************************************
4975 * WSCEnableNSProvider (WS2_32.84)
4977 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
4979 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
4980 return 0;
4983 /***********************************************************************
4984 * WSCGetProviderPath (WS2_32.86)
4986 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
4988 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
4990 if (!errcode || !provider || !len) return WSAEFAULT;
4992 *errcode = WSAEINVAL;
4993 return SOCKET_ERROR;
4996 /***********************************************************************
4997 * WSCInstallNameSpace (WS2_32.87)
4999 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
5000 DWORD version, LPGUID provider )
5002 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
5003 namespace, version, debugstr_guid(provider) );
5004 return 0;
5007 /***********************************************************************
5008 * WSCUnInstallNameSpace (WS2_32.89)
5010 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
5012 FIXME("(%p) Stub!\n", lpProviderId);
5013 return NO_ERROR;
5016 /***********************************************************************
5017 * WSCWriteProviderOrder (WS2_32.91)
5019 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
5021 FIXME("(%p 0x%08x) Stub!\n", entry, number);
5022 return 0;