d3d8/tests: Fix some pointer cast warnings on 64-bit.
[wine/hramrach.git] / dlls / ws2_32 / socket.c
blob02d8af5302a54b92f8ce8739df3748283342603c
1 /*
2 * based on Windows Sockets 1.1 specs
4 * Copyright (C) 1993,1994,1996,1997 John Brezak, Erik Bos, Alex Korobka.
5 * Copyright (C) 2005 Marcus Meissner
6 * Copyright (C) 2006-2008 Kai Blin
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 * NOTE: If you make any changes to fix a particular app, make sure
23 * they don't break something else like Netscape or telnet and ftp
24 * clients and servers (www.winsite.com got a lot of those).
27 #include "config.h"
28 #include "wine/port.h"
30 #include <stdarg.h>
31 #include <stdio.h>
32 #include <string.h>
33 #include <sys/types.h>
34 #ifdef HAVE_SYS_IPC_H
35 # include <sys/ipc.h>
36 #endif
37 #ifdef HAVE_SYS_IOCTL_H
38 # include <sys/ioctl.h>
39 #endif
40 #ifdef HAVE_SYS_FILIO_H
41 # include <sys/filio.h>
42 #endif
43 #ifdef HAVE_SYS_SOCKIO_H
44 # include <sys/sockio.h>
45 #endif
47 #if defined(__EMX__)
48 # include <sys/so_ioctl.h>
49 #endif
51 #ifdef HAVE_SYS_PARAM_H
52 # include <sys/param.h>
53 #endif
55 #ifdef HAVE_SYS_MSG_H
56 # include <sys/msg.h>
57 #endif
58 #ifdef HAVE_SYS_WAIT_H
59 # include <sys/wait.h>
60 #endif
61 #ifdef HAVE_SYS_UIO_H
62 # include <sys/uio.h>
63 #endif
64 #ifdef HAVE_SYS_SOCKET_H
65 #include <sys/socket.h>
66 #endif
67 #ifdef HAVE_NETINET_IN_H
68 # include <netinet/in.h>
69 #endif
70 #ifdef HAVE_NETINET_TCP_H
71 # include <netinet/tcp.h>
72 #endif
73 #ifdef HAVE_ARPA_INET_H
74 # include <arpa/inet.h>
75 #endif
76 #include <ctype.h>
77 #include <fcntl.h>
78 #include <errno.h>
79 #ifdef HAVE_SYS_ERRNO_H
80 #include <sys/errno.h>
81 #endif
82 #ifdef HAVE_NETDB_H
83 #include <netdb.h>
84 #endif
85 #ifdef HAVE_UNISTD_H
86 # include <unistd.h>
87 #endif
88 #include <stdlib.h>
89 #ifdef HAVE_ARPA_NAMESER_H
90 # include <arpa/nameser.h>
91 #endif
92 #ifdef HAVE_RESOLV_H
93 # include <resolv.h>
94 #endif
95 #ifdef HAVE_NET_IF_H
96 # include <net/if.h>
97 #endif
99 #ifdef HAVE_NETIPX_IPX_H
100 # include <netipx/ipx.h>
101 # define HAVE_IPX
102 #elif defined(HAVE_LINUX_IPX_H)
103 # ifdef HAVE_ASM_TYPES_H
104 # include <asm/types.h>
105 # endif
106 # ifdef HAVE_LINUX_TYPES_H
107 # include <linux/types.h>
108 # endif
109 # include <linux/ipx.h>
110 # define HAVE_IPX
111 #endif
113 #ifdef HAVE_LINUX_IRDA_H
114 # ifdef HAVE_LINUX_TYPES_H
115 # include <linux/types.h>
116 # endif
117 # include <linux/irda.h>
118 # define HAVE_IRDA
119 #endif
121 #ifdef HAVE_POLL_H
122 #include <poll.h>
123 #endif
124 #ifdef HAVE_SYS_POLL_H
125 # include <sys/poll.h>
126 #endif
127 #ifdef HAVE_SYS_TIME_H
128 # include <sys/time.h>
129 #endif
131 #define NONAMELESSUNION
132 #define NONAMELESSSTRUCT
133 #include "ntstatus.h"
134 #define WIN32_NO_STATUS
135 #include "windef.h"
136 #include "winbase.h"
137 #include "wingdi.h"
138 #include "winuser.h"
139 #include "winerror.h"
140 #include "winnls.h"
141 #include "winsock2.h"
142 #include "mswsock.h"
143 #include "ws2tcpip.h"
144 #include "ws2spi.h"
145 #include "wsipx.h"
146 #include "mstcpip.h"
147 #include "af_irda.h"
148 #include "winnt.h"
149 #include "iphlpapi.h"
150 #include "wine/server.h"
151 #include "wine/debug.h"
152 #include "wine/unicode.h"
154 #ifdef HAVE_IPX
155 # include "wsnwlink.h"
156 #endif
159 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
160 # define sipx_network sipx_addr.x_net
161 # define sipx_node sipx_addr.x_host.c_host
162 #endif /* __FreeBSD__ */
164 #ifndef INADDR_NONE
165 #define INADDR_NONE ~0UL
166 #endif
168 WINE_DEFAULT_DEBUG_CHANNEL(winsock);
169 WINE_DECLARE_DEBUG_CHANNEL(winediag);
171 /* critical section to protect some non-reentrant net function */
172 static CRITICAL_SECTION csWSgetXXXbyYYY;
173 static CRITICAL_SECTION_DEBUG critsect_debug =
175 0, 0, &csWSgetXXXbyYYY,
176 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
177 0, 0, { (DWORD_PTR)(__FILE__ ": csWSgetXXXbyYYY") }
179 static CRITICAL_SECTION csWSgetXXXbyYYY = { &critsect_debug, -1, 0, 0, 0, 0 };
181 union generic_unix_sockaddr
183 struct sockaddr addr;
184 char data[128]; /* should be big enough for all families */
187 static inline const char *debugstr_sockaddr( const struct WS_sockaddr *a )
189 if (!a) return "(nil)";
190 switch (a->sa_family)
192 case WS_AF_INET:
193 return wine_dbg_sprintf("{ family AF_INET, address %s, port %d }",
194 inet_ntoa(((const struct sockaddr_in *)a)->sin_addr),
195 ntohs(((const struct sockaddr_in *)a)->sin_port));
196 case WS_AF_INET6:
198 char buf[46];
199 const char *p;
200 struct WS_sockaddr_in6 *sin = (struct WS_sockaddr_in6 *)a;
202 p = WS_inet_ntop( WS_AF_INET6, &sin->sin6_addr, buf, sizeof(buf) );
203 if (!p)
204 p = "(unknown IPv6 address)";
205 return wine_dbg_sprintf("{ family AF_INET6, address %s, port %d }",
206 p, ntohs(sin->sin6_port));
208 case WS_AF_IRDA:
210 DWORD addr;
212 memcpy( &addr, ((const SOCKADDR_IRDA *)a)->irdaDeviceID, sizeof(addr) );
213 addr = ntohl( addr );
214 return wine_dbg_sprintf("{ family AF_IRDA, addr %08x, name %s }",
215 addr,
216 ((const SOCKADDR_IRDA *)a)->irdaServiceName);
218 default:
219 return wine_dbg_sprintf("{ family %d }", a->sa_family);
223 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
224 #define SOCKET2HANDLE(s) ((HANDLE)(s))
225 #define HANDLE2SOCKET(h) ((SOCKET)(h))
227 /****************************************************************
228 * Async IO declarations
229 ****************************************************************/
231 typedef struct ws2_async
233 HANDLE hSocket;
234 int type;
235 LPWSAOVERLAPPED user_overlapped;
236 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion_func;
237 IO_STATUS_BLOCK local_iosb;
238 struct WS_sockaddr *addr;
239 union
241 int val; /* for send operations */
242 int *ptr; /* for recv operations */
243 } addrlen;
244 DWORD flags;
245 unsigned int n_iovecs;
246 unsigned int first_iovec;
247 struct iovec iovec[1];
248 } ws2_async;
250 /****************************************************************/
252 /* ----------------------------------- internal data */
254 /* ws_... struct conversion flags */
256 typedef struct /* WSAAsyncSelect() control struct */
258 HANDLE service, event, sock;
259 HWND hWnd;
260 UINT uMsg;
261 LONG lEvent;
262 } ws_select_info;
264 #define WS_MAX_SOCKETS_PER_PROCESS 128 /* reasonable guess */
265 #define WS_MAX_UDP_DATAGRAM 1024
266 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
268 /* hostent's, servent's and protent's are stored in one buffer per thread,
269 * as documented on MSDN for the functions that return any of the buffers */
270 struct per_thread_data
272 int opentype;
273 struct WS_hostent *he_buffer;
274 struct WS_servent *se_buffer;
275 struct WS_protoent *pe_buffer;
276 int he_len;
277 int se_len;
278 int pe_len;
281 static INT num_startup; /* reference counter */
282 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
284 /* function prototypes */
285 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
286 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
287 static struct WS_servent *WS_dup_se(const struct servent* p_se);
289 int WSAIOCTL_GetInterfaceCount(void);
290 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
292 #define MAP_OPTION(opt) { WS_##opt, opt }
294 static const int ws_sock_map[][2] =
296 MAP_OPTION( SO_DEBUG ),
297 MAP_OPTION( SO_ACCEPTCONN ),
298 MAP_OPTION( SO_REUSEADDR ),
299 MAP_OPTION( SO_KEEPALIVE ),
300 MAP_OPTION( SO_DONTROUTE ),
301 MAP_OPTION( SO_BROADCAST ),
302 MAP_OPTION( SO_LINGER ),
303 MAP_OPTION( SO_OOBINLINE ),
304 MAP_OPTION( SO_SNDBUF ),
305 MAP_OPTION( SO_RCVBUF ),
306 MAP_OPTION( SO_ERROR ),
307 MAP_OPTION( SO_TYPE ),
308 #ifdef SO_RCVTIMEO
309 MAP_OPTION( SO_RCVTIMEO ),
310 #endif
311 #ifdef SO_SNDTIMEO
312 MAP_OPTION( SO_SNDTIMEO ),
313 #endif
316 static const int ws_tcp_map[][2] =
318 #ifdef TCP_NODELAY
319 MAP_OPTION( TCP_NODELAY ),
320 #endif
323 static const int ws_ip_map[][2] =
325 MAP_OPTION( IP_MULTICAST_IF ),
326 MAP_OPTION( IP_MULTICAST_TTL ),
327 MAP_OPTION( IP_MULTICAST_LOOP ),
328 MAP_OPTION( IP_ADD_MEMBERSHIP ),
329 MAP_OPTION( IP_DROP_MEMBERSHIP ),
330 MAP_OPTION( IP_OPTIONS ),
331 #ifdef IP_HDRINCL
332 MAP_OPTION( IP_HDRINCL ),
333 #endif
334 MAP_OPTION( IP_TOS ),
335 MAP_OPTION( IP_TTL ),
338 static const int ws_af_map[][2] =
340 MAP_OPTION( AF_UNSPEC ),
341 MAP_OPTION( AF_INET ),
342 MAP_OPTION( AF_INET6 ),
343 #ifdef HAVE_IPX
344 MAP_OPTION( AF_IPX ),
345 #endif
346 #ifdef AF_IRDA
347 MAP_OPTION( AF_IRDA ),
348 #endif
349 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
352 static const int ws_socktype_map[][2] =
354 MAP_OPTION( SOCK_DGRAM ),
355 MAP_OPTION( SOCK_STREAM ),
356 MAP_OPTION( SOCK_RAW ),
357 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
360 static const int ws_proto_map[][2] =
362 MAP_OPTION( IPPROTO_IP ),
363 MAP_OPTION( IPPROTO_TCP ),
364 MAP_OPTION( IPPROTO_UDP ),
365 MAP_OPTION( IPPROTO_ICMP ),
366 MAP_OPTION( IPPROTO_IGMP ),
367 MAP_OPTION( IPPROTO_RAW ),
368 {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
371 static const int ws_aiflag_map[][2] =
373 MAP_OPTION( AI_PASSIVE ),
374 MAP_OPTION( AI_CANONNAME ),
375 MAP_OPTION( AI_NUMERICHOST ),
376 /* Linux/UNIX knows a lot more. But Windows only
377 * has 3 as far as I could see. -Marcus
381 static const int ws_niflag_map[][2] =
383 MAP_OPTION( NI_NOFQDN ),
384 MAP_OPTION( NI_NUMERICHOST ),
385 MAP_OPTION( NI_NAMEREQD ),
386 MAP_OPTION( NI_NUMERICSERV ),
387 MAP_OPTION( NI_DGRAM ),
390 static const int ws_eai_map[][2] =
392 MAP_OPTION( EAI_AGAIN ),
393 MAP_OPTION( EAI_BADFLAGS ),
394 MAP_OPTION( EAI_FAIL ),
395 MAP_OPTION( EAI_FAMILY ),
396 MAP_OPTION( EAI_MEMORY ),
397 /* Note: EAI_NODATA is deprecated, but still
398 * used by Windows and Linux... We map the newer
399 * EAI_NONAME to EAI_NODATA for now until Windows
400 * changes too.
402 #ifdef EAI_NODATA
403 MAP_OPTION( EAI_NODATA ),
404 #endif
405 #ifdef EAI_NONAME
406 { WS_EAI_NODATA, EAI_NONAME },
407 #endif
409 MAP_OPTION( EAI_SERVICE ),
410 MAP_OPTION( EAI_SOCKTYPE ),
411 { 0, 0 }
414 static const char magic_loopback_addr[] = {127, 12, 34, 56};
416 /* ----------------------------------- error handling */
418 static UINT wsaErrno(void)
420 int loc_errno = errno;
421 WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
423 switch(loc_errno)
425 case EINTR: return WSAEINTR;
426 case EBADF: return WSAEBADF;
427 case EPERM:
428 case EACCES: return WSAEACCES;
429 case EFAULT: return WSAEFAULT;
430 case EINVAL: return WSAEINVAL;
431 case EMFILE: return WSAEMFILE;
432 case EWOULDBLOCK: return WSAEWOULDBLOCK;
433 case EINPROGRESS: return WSAEINPROGRESS;
434 case EALREADY: return WSAEALREADY;
435 case ENOTSOCK: return WSAENOTSOCK;
436 case EDESTADDRREQ: return WSAEDESTADDRREQ;
437 case EMSGSIZE: return WSAEMSGSIZE;
438 case EPROTOTYPE: return WSAEPROTOTYPE;
439 case ENOPROTOOPT: return WSAENOPROTOOPT;
440 case EPROTONOSUPPORT: return WSAEPROTONOSUPPORT;
441 case ESOCKTNOSUPPORT: return WSAESOCKTNOSUPPORT;
442 case EOPNOTSUPP: return WSAEOPNOTSUPP;
443 case EPFNOSUPPORT: return WSAEPFNOSUPPORT;
444 case EAFNOSUPPORT: return WSAEAFNOSUPPORT;
445 case EADDRINUSE: return WSAEADDRINUSE;
446 case EADDRNOTAVAIL: return WSAEADDRNOTAVAIL;
447 case ENETDOWN: return WSAENETDOWN;
448 case ENETUNREACH: return WSAENETUNREACH;
449 case ENETRESET: return WSAENETRESET;
450 case ECONNABORTED: return WSAECONNABORTED;
451 case EPIPE:
452 case ECONNRESET: return WSAECONNRESET;
453 case ENOBUFS: return WSAENOBUFS;
454 case EISCONN: return WSAEISCONN;
455 case ENOTCONN: return WSAENOTCONN;
456 case ESHUTDOWN: return WSAESHUTDOWN;
457 case ETOOMANYREFS: return WSAETOOMANYREFS;
458 case ETIMEDOUT: return WSAETIMEDOUT;
459 case ECONNREFUSED: return WSAECONNREFUSED;
460 case ELOOP: return WSAELOOP;
461 case ENAMETOOLONG: return WSAENAMETOOLONG;
462 case EHOSTDOWN: return WSAEHOSTDOWN;
463 case EHOSTUNREACH: return WSAEHOSTUNREACH;
464 case ENOTEMPTY: return WSAENOTEMPTY;
465 #ifdef EPROCLIM
466 case EPROCLIM: return WSAEPROCLIM;
467 #endif
468 #ifdef EUSERS
469 case EUSERS: return WSAEUSERS;
470 #endif
471 #ifdef EDQUOT
472 case EDQUOT: return WSAEDQUOT;
473 #endif
474 #ifdef ESTALE
475 case ESTALE: return WSAESTALE;
476 #endif
477 #ifdef EREMOTE
478 case EREMOTE: return WSAEREMOTE;
479 #endif
481 /* just in case we ever get here and there are no problems */
482 case 0: return 0;
483 default:
484 WARN("Unknown errno %d!\n", loc_errno);
485 return WSAEOPNOTSUPP;
489 static UINT wsaHerrno(int loc_errno)
492 WARN("h_errno %d.\n", loc_errno);
494 switch(loc_errno)
496 case HOST_NOT_FOUND: return WSAHOST_NOT_FOUND;
497 case TRY_AGAIN: return WSATRY_AGAIN;
498 case NO_RECOVERY: return WSANO_RECOVERY;
499 case NO_DATA: return WSANO_DATA;
500 case ENOBUFS: return WSAENOBUFS;
502 case 0: return 0;
503 default:
504 WARN("Unknown h_errno %d!\n", loc_errno);
505 return WSAEOPNOTSUPP;
509 static inline DWORD NtStatusToWSAError( const DWORD status )
511 /* We only need to cover the status codes set by server async request handling */
512 DWORD wserr;
513 switch ( status )
515 case STATUS_SUCCESS: wserr = 0; break;
516 case STATUS_PENDING: wserr = WSA_IO_PENDING; break;
517 case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK; break;
518 case STATUS_INVALID_HANDLE: wserr = WSAEBADF; break;
519 case STATUS_INVALID_PARAMETER: wserr = WSAEINVAL; break;
520 case STATUS_PIPE_DISCONNECTED: wserr = WSAESHUTDOWN; break;
521 case STATUS_CANCELLED: wserr = WSA_OPERATION_ABORTED; break;
522 case STATUS_TIMEOUT: wserr = WSAETIMEDOUT; break;
523 case STATUS_NO_MEMORY: wserr = WSAEFAULT; break;
524 default:
525 if ( status >= WSABASEERR && status <= WSABASEERR+1004 )
526 /* It is not an NT status code but a winsock error */
527 wserr = status;
528 else
530 wserr = RtlNtStatusToDosError( status );
531 FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
534 return wserr;
537 /* set last error code from NT status without mapping WSA errors */
538 static inline unsigned int set_error( unsigned int err )
540 if (err)
542 err = NtStatusToWSAError( err );
543 SetLastError( err );
545 return err;
548 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
550 int fd;
551 if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
552 return -1;
553 return fd;
556 static inline void release_sock_fd( SOCKET s, int fd )
558 wine_server_release_fd( SOCKET2HANDLE(s), fd );
561 static void _enable_event( HANDLE s, unsigned int event,
562 unsigned int sstate, unsigned int cstate )
564 SERVER_START_REQ( enable_socket_event )
566 req->handle = wine_server_obj_handle( s );
567 req->mask = event;
568 req->sstate = sstate;
569 req->cstate = cstate;
570 wine_server_call( req );
572 SERVER_END_REQ;
575 static int _is_blocking(SOCKET s)
577 int ret;
578 SERVER_START_REQ( get_socket_event )
580 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
581 req->service = FALSE;
582 req->c_event = 0;
583 wine_server_call( req );
584 ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
586 SERVER_END_REQ;
587 return ret;
590 static unsigned int _get_sock_mask(SOCKET s)
592 unsigned int ret;
593 SERVER_START_REQ( get_socket_event )
595 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
596 req->service = FALSE;
597 req->c_event = 0;
598 wine_server_call( req );
599 ret = reply->mask;
601 SERVER_END_REQ;
602 return ret;
605 static void _sync_sock_state(SOCKET s)
607 /* do a dummy wineserver request in order to let
608 the wineserver run through its select loop once */
609 (void)_is_blocking(s);
612 static int _get_sock_error(SOCKET s, unsigned int bit)
614 int events[FD_MAX_EVENTS];
616 SERVER_START_REQ( get_socket_event )
618 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
619 req->service = FALSE;
620 req->c_event = 0;
621 wine_server_set_reply( req, events, sizeof(events) );
622 wine_server_call( req );
624 SERVER_END_REQ;
625 return events[bit];
628 static struct per_thread_data *get_per_thread_data(void)
630 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
631 /* lazy initialization */
632 if (!ptb)
634 ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
635 NtCurrentTeb()->WinSockData = ptb;
637 return ptb;
640 static void free_per_thread_data(void)
642 struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
644 if (!ptb) return;
646 /* delete scratch buffers */
647 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
648 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
649 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
650 ptb->he_buffer = NULL;
651 ptb->se_buffer = NULL;
652 ptb->pe_buffer = NULL;
654 HeapFree( GetProcessHeap(), 0, ptb );
655 NtCurrentTeb()->WinSockData = NULL;
658 /***********************************************************************
659 * DllMain (WS2_32.init)
661 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
663 TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
664 switch (fdwReason) {
665 case DLL_PROCESS_ATTACH:
666 break;
667 case DLL_PROCESS_DETACH:
668 free_per_thread_data();
669 num_startup = 0;
670 break;
671 case DLL_THREAD_DETACH:
672 free_per_thread_data();
673 break;
675 return TRUE;
678 /***********************************************************************
679 * convert_sockopt()
681 * Converts socket flags from Windows format.
682 * Return 1 if converted, 0 if not (error).
684 static int convert_sockopt(INT *level, INT *optname)
686 unsigned int i;
687 switch (*level)
689 case WS_SOL_SOCKET:
690 *level = SOL_SOCKET;
691 for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
692 if( ws_sock_map[i][0] == *optname )
694 *optname = ws_sock_map[i][1];
695 return 1;
698 FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
699 break;
700 case WS_IPPROTO_TCP:
701 *level = IPPROTO_TCP;
702 for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
703 if ( ws_tcp_map[i][0] == *optname )
705 *optname = ws_tcp_map[i][1];
706 return 1;
709 FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
710 break;
711 case WS_IPPROTO_IP:
712 *level = IPPROTO_IP;
713 for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
714 if (ws_ip_map[i][0] == *optname )
716 *optname = ws_ip_map[i][1];
717 return 1;
720 FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
721 break;
722 default: FIXME("Unimplemented or unknown socket level\n");
724 return 0;
727 /* ----------------------------------- Per-thread info (or per-process?) */
729 static char *strdup_lower(const char *str)
731 int i;
732 char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
734 if (ret)
736 for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
737 ret[i] = 0;
739 else SetLastError(WSAENOBUFS);
740 return ret;
743 static inline int sock_error_p(int s)
745 unsigned int optval, optlen;
747 optlen = sizeof(optval);
748 getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
749 if (optval) WARN("\t[%i] error: %d\n", s, optval);
750 return optval != 0;
753 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
754 * from an fd and return the value converted to milli seconds
755 * or -1 if there is an infinite time out */
756 static inline int get_rcvsnd_timeo( int fd, int optname)
758 struct timeval tv;
759 unsigned int len = sizeof(tv);
760 int ret = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
761 if( ret >= 0)
762 ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
763 if( ret <= 0 ) /* tv == {0,0} means infinite time out */
764 return -1;
765 return ret;
768 /* macro wrappers for portability */
769 #ifdef SO_RCVTIMEO
770 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
771 #else
772 #define GET_RCVTIMEO(fd) (-1)
773 #endif
775 #ifdef SO_SNDTIMEO
776 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
777 #else
778 #define GET_SNDTIMEO(fd) (-1)
779 #endif
781 /* utility: given an fd, will block until one of the events occurs */
782 static inline int do_block( int fd, int events, int timeout )
784 struct pollfd pfd;
785 int ret;
787 pfd.fd = fd;
788 pfd.events = events;
790 while ((ret = poll(&pfd, 1, timeout)) < 0)
792 if (errno != EINTR)
793 return -1;
795 if( ret == 0 )
796 return 0;
797 return pfd.revents;
800 static int
801 convert_af_w2u(int windowsaf) {
802 unsigned int i;
804 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
805 if (ws_af_map[i][0] == windowsaf)
806 return ws_af_map[i][1];
807 FIXME("unhandled Windows address family %d\n", windowsaf);
808 return -1;
811 static int
812 convert_af_u2w(int unixaf) {
813 unsigned int i;
815 for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
816 if (ws_af_map[i][1] == unixaf)
817 return ws_af_map[i][0];
818 FIXME("unhandled UNIX address family %d\n", unixaf);
819 return -1;
822 static int
823 convert_proto_w2u(int windowsproto) {
824 unsigned int i;
826 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
827 if (ws_proto_map[i][0] == windowsproto)
828 return ws_proto_map[i][1];
829 FIXME("unhandled Windows socket protocol %d\n", windowsproto);
830 return -1;
833 static int
834 convert_proto_u2w(int unixproto) {
835 unsigned int i;
837 for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
838 if (ws_proto_map[i][1] == unixproto)
839 return ws_proto_map[i][0];
840 FIXME("unhandled UNIX socket protocol %d\n", unixproto);
841 return -1;
844 static int
845 convert_socktype_w2u(int windowssocktype) {
846 unsigned int i;
848 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
849 if (ws_socktype_map[i][0] == windowssocktype)
850 return ws_socktype_map[i][1];
851 FIXME("unhandled Windows socket type %d\n", windowssocktype);
852 return -1;
855 static int
856 convert_socktype_u2w(int unixsocktype) {
857 unsigned int i;
859 for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
860 if (ws_socktype_map[i][1] == unixsocktype)
861 return ws_socktype_map[i][0];
862 FIXME("unhandled UNIX socket type %d\n", unixsocktype);
863 return -1;
866 /* ----------------------------------- API -----
868 * Init / cleanup / error checking.
871 /***********************************************************************
872 * WSAStartup (WS2_32.115)
874 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
876 TRACE("verReq=%x\n", wVersionRequested);
878 if (LOBYTE(wVersionRequested) < 1)
879 return WSAVERNOTSUPPORTED;
881 if (!lpWSAData) return WSAEINVAL;
883 num_startup++;
885 /* that's the whole of the negotiation for now */
886 lpWSAData->wVersion = wVersionRequested;
887 /* return winsock information */
888 lpWSAData->wHighVersion = 0x0202;
889 strcpy(lpWSAData->szDescription, "WinSock 2.0" );
890 strcpy(lpWSAData->szSystemStatus, "Running" );
891 lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
892 lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
893 /* don't do anything with lpWSAData->lpVendorInfo */
894 /* (some apps don't allocate the space for this field) */
896 TRACE("succeeded\n");
897 return 0;
901 /***********************************************************************
902 * WSACleanup (WS2_32.116)
904 INT WINAPI WSACleanup(void)
906 if (num_startup) {
907 num_startup--;
908 return 0;
910 SetLastError(WSANOTINITIALISED);
911 return SOCKET_ERROR;
915 /***********************************************************************
916 * WSAGetLastError (WS2_32.111)
918 INT WINAPI WSAGetLastError(void)
920 return GetLastError();
923 /***********************************************************************
924 * WSASetLastError (WS2_32.112)
926 void WINAPI WSASetLastError(INT iError) {
927 SetLastError(iError);
930 static struct WS_hostent *check_buffer_he(int size)
932 struct per_thread_data * ptb = get_per_thread_data();
933 if (ptb->he_buffer)
935 if (ptb->he_len >= size ) return ptb->he_buffer;
936 HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
938 ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
939 if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
940 return ptb->he_buffer;
943 static struct WS_servent *check_buffer_se(int size)
945 struct per_thread_data * ptb = get_per_thread_data();
946 if (ptb->se_buffer)
948 if (ptb->se_len >= size ) return ptb->se_buffer;
949 HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
951 ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
952 if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
953 return ptb->se_buffer;
956 static struct WS_protoent *check_buffer_pe(int size)
958 struct per_thread_data * ptb = get_per_thread_data();
959 if (ptb->pe_buffer)
961 if (ptb->pe_len >= size ) return ptb->pe_buffer;
962 HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
964 ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
965 if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
966 return ptb->pe_buffer;
969 /* ----------------------------------- i/o APIs */
971 static inline BOOL supported_pf(int pf)
973 switch (pf)
975 case WS_AF_INET:
976 case WS_AF_INET6:
977 return TRUE;
978 #ifdef HAVE_IPX
979 case WS_AF_IPX:
980 return TRUE;
981 #endif
982 #ifdef HAVE_IRDA
983 case WS_AF_IRDA:
984 return TRUE;
985 #endif
986 default:
987 return FALSE;
992 /**********************************************************************/
994 /* Returns the length of the converted address if successful, 0 if it was too small to
995 * start with.
997 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
998 union generic_unix_sockaddr *uaddr)
1000 unsigned int uaddrlen = 0;
1002 switch (wsaddr->sa_family)
1004 #ifdef HAVE_IPX
1005 case WS_AF_IPX:
1007 const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
1008 struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
1010 if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
1011 return 0;
1013 uaddrlen = sizeof(struct sockaddr_ipx);
1014 memset( uaddr, 0, uaddrlen );
1015 uipx->sipx_family=AF_IPX;
1016 uipx->sipx_port=wsipx->sa_socket;
1017 /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
1018 * in one go
1020 memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
1021 #ifdef IPX_FRAME_NONE
1022 uipx->sipx_type=IPX_FRAME_NONE;
1023 #endif
1024 break;
1026 #endif
1027 case WS_AF_INET6: {
1028 struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
1029 const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
1031 /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
1032 * scope_id, one without.
1034 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
1035 uaddrlen = sizeof(struct sockaddr_in6);
1036 memset( uaddr, 0, uaddrlen );
1037 uin6->sin6_family = AF_INET6;
1038 uin6->sin6_port = win6->sin6_port;
1039 uin6->sin6_flowinfo = win6->sin6_flowinfo;
1040 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1041 if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
1042 #endif
1043 memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
1044 break;
1046 FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
1047 return 0;
1049 case WS_AF_INET: {
1050 struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
1051 const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
1053 if (wsaddrlen<sizeof(struct WS_sockaddr_in))
1054 return 0;
1055 uaddrlen = sizeof(struct sockaddr_in);
1056 memset( uaddr, 0, uaddrlen );
1057 uin->sin_family = AF_INET;
1058 uin->sin_port = win->sin_port;
1059 memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
1060 break;
1062 #ifdef HAVE_IRDA
1063 case WS_AF_IRDA: {
1064 struct sockaddr_irda *uin = (struct sockaddr_irda *)uaddr;
1065 const SOCKADDR_IRDA *win = (const SOCKADDR_IRDA *)wsaddr;
1067 if (wsaddrlen < sizeof(SOCKADDR_IRDA))
1068 return 0;
1069 uaddrlen = sizeof(struct sockaddr_irda);
1070 memset( uaddr, 0, uaddrlen );
1071 uin->sir_family = AF_IRDA;
1072 if (!strncmp( win->irdaServiceName, "LSAP-SEL", strlen( "LSAP-SEL" ) ))
1074 unsigned int lsap_sel;
1076 sscanf( win->irdaServiceName, "LSAP-SEL%u", &lsap_sel );
1077 uin->sir_lsap_sel = lsap_sel;
1079 else
1081 uin->sir_lsap_sel = LSAP_ANY;
1082 memcpy( uin->sir_name, win->irdaServiceName, 25 );
1084 memcpy( &uin->sir_addr, win->irdaDeviceID, sizeof(uin->sir_addr) );
1085 break;
1087 #endif
1088 case WS_AF_UNSPEC: {
1089 /* Try to determine the needed space by the passed windows sockaddr space */
1090 switch (wsaddrlen) {
1091 default: /* likely a ipv4 address */
1092 case sizeof(struct WS_sockaddr_in):
1093 uaddrlen = sizeof(struct sockaddr_in);
1094 break;
1095 #ifdef HAVE_IPX
1096 case sizeof(struct WS_sockaddr_ipx):
1097 uaddrlen = sizeof(struct sockaddr_ipx);
1098 break;
1099 #endif
1100 #ifdef HAVE_IRDA
1101 case sizeof(SOCKADDR_IRDA):
1102 uaddrlen = sizeof(struct sockaddr_irda);
1103 break;
1104 #endif
1105 case sizeof(struct WS_sockaddr_in6):
1106 case sizeof(struct WS_sockaddr_in6_old):
1107 uaddrlen = sizeof(struct sockaddr_in6);
1108 break;
1110 memset( uaddr, 0, uaddrlen );
1111 break;
1113 default:
1114 FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
1115 return 0;
1117 return uaddrlen;
1120 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
1122 switch (uaddr->sa_family)
1124 #ifdef HAVE_IPX
1125 case AF_IPX:
1126 FIXME("don't know how to tell if IPX socket is bound, assuming it is!\n");
1127 return TRUE;
1128 #endif
1129 case AF_INET6:
1131 static const struct sockaddr_in6 emptyAddr;
1132 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
1133 return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
1135 case AF_INET:
1137 static const struct sockaddr_in emptyAddr;
1138 const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
1139 return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
1141 case AF_UNSPEC:
1142 return FALSE;
1143 default:
1144 FIXME("unknown address family %d\n", uaddr->sa_family);
1145 return TRUE;
1149 /* Returns 0 if successful, -1 if the buffer is too small */
1150 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
1152 int res;
1154 switch(uaddr->sa_family)
1156 #ifdef HAVE_IPX
1157 case AF_IPX:
1159 const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
1160 struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
1162 res=-1;
1163 switch (*wsaddrlen) /* how much can we copy? */
1165 default:
1166 res=0; /* enough */
1167 *wsaddrlen = sizeof(*wsipx);
1168 wsipx->sa_socket=uipx->sipx_port;
1169 /* fall through */
1170 case 13:
1171 case 12:
1172 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
1173 /* fall through */
1174 case 11:
1175 case 10:
1176 case 9:
1177 case 8:
1178 case 7:
1179 case 6:
1180 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
1181 /* fall through */
1182 case 5:
1183 case 4:
1184 case 3:
1185 case 2:
1186 wsipx->sa_family=WS_AF_IPX;
1187 /* fall through */
1188 case 1:
1189 case 0:
1190 /* way too small */
1191 break;
1194 break;
1195 #endif
1196 #ifdef HAVE_IRDA
1197 case AF_IRDA: {
1198 const struct sockaddr_irda *uin = (const struct sockaddr_irda *)uaddr;
1199 SOCKADDR_IRDA *win = (SOCKADDR_IRDA *)wsaddr;
1201 if (*wsaddrlen < sizeof(SOCKADDR_IRDA))
1202 return -1;
1203 win->irdaAddressFamily = WS_AF_IRDA;
1204 memcpy( win->irdaDeviceID, &uin->sir_addr, sizeof(win->irdaDeviceID) );
1205 if (uin->sir_lsap_sel != LSAP_ANY)
1206 sprintf( win->irdaServiceName, "LSAP-SEL%u", uin->sir_lsap_sel );
1207 else
1208 memcpy( win->irdaServiceName, uin->sir_name,
1209 sizeof(win->irdaServiceName) );
1210 return 0;
1212 #endif
1213 case AF_INET6: {
1214 const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1215 struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1217 if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1218 return -1;
1219 win6old->sin6_family = WS_AF_INET6;
1220 win6old->sin6_port = uin6->sin6_port;
1221 win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1222 memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1223 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1224 if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1225 struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1226 win6->sin6_scope_id = uin6->sin6_scope_id;
1227 *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1229 else
1230 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1231 #else
1232 *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1233 #endif
1234 return 0;
1236 case AF_INET: {
1237 const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1238 struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1240 if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1241 return -1;
1242 win->sin_family = WS_AF_INET;
1243 win->sin_port = uin->sin_port;
1244 memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1245 memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1246 *wsaddrlen = sizeof(struct WS_sockaddr_in);
1247 return 0;
1249 case AF_UNSPEC: {
1250 memset(wsaddr,0,*wsaddrlen);
1251 return 0;
1253 default:
1254 FIXME("Unknown address family %d\n", uaddr->sa_family);
1255 return -1;
1257 return res;
1260 /**************************************************************************
1261 * Functions for handling overlapped I/O
1262 **************************************************************************/
1264 /* user APC called upon async completion */
1265 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1267 ws2_async *wsa = arg;
1269 if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
1270 iosb->Information, wsa->user_overlapped,
1271 wsa->flags );
1272 HeapFree( GetProcessHeap(), 0, wsa );
1275 /***********************************************************************
1276 * WS2_recv (INTERNAL)
1278 * Workhorse for both synchronous and asynchronous recv() operations.
1280 static int WS2_recv( int fd, struct ws2_async *wsa )
1282 struct msghdr hdr;
1283 union generic_unix_sockaddr unix_sockaddr;
1284 int n;
1286 hdr.msg_name = NULL;
1288 if (wsa->addr)
1290 hdr.msg_namelen = sizeof(unix_sockaddr);
1291 hdr.msg_name = &unix_sockaddr;
1293 else
1294 hdr.msg_namelen = 0;
1296 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1297 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1298 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1299 hdr.msg_accrights = NULL;
1300 hdr.msg_accrightslen = 0;
1301 #else
1302 hdr.msg_control = NULL;
1303 hdr.msg_controllen = 0;
1304 hdr.msg_flags = 0;
1305 #endif
1307 if ( (n = recvmsg(fd, &hdr, wsa->flags)) == -1 )
1308 return -1;
1310 /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
1311 * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
1313 * quoting linux 2.6 net/ipv4/tcp.c:
1314 * "According to UNIX98, msg_name/msg_namelen are ignored
1315 * on connected socket. I was just happy when found this 8) --ANK"
1317 * likewise MSDN says that lpFrom and lpFromlen are ignored for
1318 * connection-oriented sockets, so don't try to update lpFrom.
1320 if (wsa->addr && hdr.msg_namelen)
1321 ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
1323 return n;
1326 /***********************************************************************
1327 * WS2_async_recv (INTERNAL)
1329 * Handler for overlapped recv() operations.
1331 static NTSTATUS WS2_async_recv( void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1333 ws2_async* wsa = user;
1334 int result = 0, fd;
1336 switch (status)
1338 case STATUS_ALERTED:
1339 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
1340 break;
1342 result = WS2_recv( fd, wsa );
1343 wine_server_release_fd( wsa->hSocket, fd );
1344 if (result >= 0)
1346 status = STATUS_SUCCESS;
1347 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1349 else
1351 if (errno == EINTR || errno == EAGAIN)
1353 status = STATUS_PENDING;
1354 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1356 else
1358 result = 0;
1359 status = wsaErrno(); /* FIXME: is this correct ???? */
1362 break;
1364 if (status != STATUS_PENDING)
1366 iosb->u.Status = status;
1367 iosb->Information = result;
1368 *apc = ws2_async_apc;
1370 return status;
1373 /***********************************************************************
1374 * WS2_send (INTERNAL)
1376 * Workhorse for both synchronous and asynchronous send() operations.
1378 static int WS2_send( int fd, struct ws2_async *wsa )
1380 struct msghdr hdr;
1381 union generic_unix_sockaddr unix_addr;
1383 hdr.msg_name = NULL;
1384 hdr.msg_namelen = 0;
1386 if (wsa->addr)
1388 hdr.msg_name = &unix_addr;
1389 hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
1390 if ( !hdr.msg_namelen )
1392 errno = EFAULT;
1393 return -1;
1396 #if defined(HAVE_IPX) && defined(SOL_IPX)
1397 if(wsa->addr->sa_family == WS_AF_IPX)
1399 struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
1400 int val=0;
1401 unsigned int len=sizeof(int);
1403 /* The packet type is stored at the ipx socket level; At least the linux kernel seems
1404 * to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
1405 * the packet type and then we can retrieve it using getsockopt. After that we can set the
1406 * ipx type in the sockaddr_opx structure with the stored value.
1408 if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
1409 uipx->sipx_type = val;
1411 #endif
1414 hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1415 hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1416 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1417 hdr.msg_accrights = NULL;
1418 hdr.msg_accrightslen = 0;
1419 #else
1420 hdr.msg_control = NULL;
1421 hdr.msg_controllen = 0;
1422 hdr.msg_flags = 0;
1423 #endif
1425 return sendmsg(fd, &hdr, wsa->flags);
1428 /***********************************************************************
1429 * WS2_async_send (INTERNAL)
1431 * Handler for overlapped send() operations.
1433 static NTSTATUS WS2_async_send(void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, void **apc)
1435 ws2_async* wsa = user;
1436 int result = 0, fd;
1438 switch (status)
1440 case STATUS_ALERTED:
1441 if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
1442 break;
1444 /* check to see if the data is ready (non-blocking) */
1445 result = WS2_send( fd, wsa );
1446 wine_server_release_fd( wsa->hSocket, fd );
1448 if (result >= 0)
1450 int totalLength = 0;
1451 unsigned int i;
1452 status = STATUS_SUCCESS;
1453 for (i = 0; i < wsa->n_iovecs; i++)
1454 totalLength += wsa->iovec[i].iov_len;
1455 if (result < totalLength)
1456 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1458 else
1460 if (errno == EINTR || errno == EAGAIN)
1462 status = STATUS_PENDING;
1463 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1465 else
1467 /* We set the status to a winsock error code and check for that
1468 later in NtStatusToWSAError () */
1469 status = wsaErrno();
1470 result = 0;
1473 break;
1475 if (status != STATUS_PENDING)
1477 iosb->u.Status = status;
1478 iosb->Information = result;
1479 *apc = ws2_async_apc;
1481 return status;
1484 /***********************************************************************
1485 * WS2_async_shutdown (INTERNAL)
1487 * Handler for shutdown() operations on overlapped sockets.
1489 static NTSTATUS WS2_async_shutdown( void* user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc )
1491 ws2_async* wsa = user;
1492 int fd, err = 1;
1494 switch (status)
1496 case STATUS_ALERTED:
1497 if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
1498 break;
1500 switch ( wsa->type )
1502 case ASYNC_TYPE_READ: err = shutdown( fd, 0 ); break;
1503 case ASYNC_TYPE_WRITE: err = shutdown( fd, 1 ); break;
1505 wine_server_release_fd( wsa->hSocket, fd );
1506 status = err ? wsaErrno() : STATUS_SUCCESS;
1507 break;
1509 iosb->u.Status = status;
1510 iosb->Information = 0;
1511 *apc = ws2_async_apc;
1512 return status;
1515 /***********************************************************************
1516 * WS2_register_async_shutdown (INTERNAL)
1518 * Helper function for WS_shutdown() on overlapped sockets.
1520 static int WS2_register_async_shutdown( SOCKET s, int type )
1522 struct ws2_async *wsa;
1523 NTSTATUS status;
1525 TRACE("s %ld type %d\n", s, type);
1527 wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
1528 if ( !wsa )
1529 return WSAEFAULT;
1531 wsa->hSocket = SOCKET2HANDLE(s);
1532 wsa->type = type;
1533 wsa->completion_func = NULL;
1535 SERVER_START_REQ( register_async )
1537 req->type = type;
1538 req->async.handle = wine_server_obj_handle( wsa->hSocket );
1539 req->async.callback = wine_server_client_ptr( WS2_async_shutdown );
1540 req->async.iosb = wine_server_client_ptr( &wsa->local_iosb );
1541 req->async.arg = wine_server_client_ptr( wsa );
1542 req->async.cvalue = 0;
1543 status = wine_server_call( req );
1545 SERVER_END_REQ;
1547 if (status != STATUS_PENDING)
1549 HeapFree( GetProcessHeap(), 0, wsa );
1550 return NtStatusToWSAError( status );
1552 return 0;
1555 /***********************************************************************
1556 * accept (WS2_32.1)
1558 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr,
1559 int *addrlen32)
1561 NTSTATUS status;
1562 SOCKET as;
1563 BOOL is_blocking;
1565 TRACE("socket %04lx\n", s );
1566 is_blocking = _is_blocking(s);
1568 do {
1569 /* try accepting first (if there is a deferred connection) */
1570 SERVER_START_REQ( accept_socket )
1572 req->lhandle = wine_server_obj_handle( SOCKET2HANDLE(s) );
1573 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
1574 req->attributes = OBJ_INHERIT;
1575 status = wine_server_call( req );
1576 as = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
1578 SERVER_END_REQ;
1579 if (!status)
1581 if (addr) WS_getpeername(as, addr, addrlen32);
1582 return as;
1584 if (is_blocking && status == WSAEWOULDBLOCK)
1586 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1587 /* block here */
1588 do_block(fd, POLLIN, -1);
1589 _sync_sock_state(s); /* let wineserver notice connection */
1590 release_sock_fd( s, fd );
1592 } while (is_blocking && status == WSAEWOULDBLOCK);
1594 set_error(status);
1595 return INVALID_SOCKET;
1598 /***********************************************************************
1599 * bind (WS2_32.2)
1601 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
1603 int fd = get_sock_fd( s, 0, NULL );
1604 int res = SOCKET_ERROR;
1606 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1608 if (fd != -1)
1610 if (!name || (name->sa_family && !supported_pf(name->sa_family)))
1612 SetLastError(WSAEAFNOSUPPORT);
1614 else
1616 union generic_unix_sockaddr uaddr;
1617 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1618 if (!uaddrlen)
1620 SetLastError(WSAEFAULT);
1622 else
1624 #ifdef IPV6_V6ONLY
1625 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
1626 if (name->sa_family == WS_AF_INET6 &&
1627 !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
1629 int enable = 1;
1630 if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
1632 release_sock_fd( s, fd );
1633 SetLastError(WSAEAFNOSUPPORT);
1634 return SOCKET_ERROR;
1637 #endif
1638 if (name->sa_family == WS_AF_INET)
1640 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
1641 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
1643 /* Trying to bind to the default host interface, using
1644 * INADDR_ANY instead*/
1645 WARN("Trying to bind to magic IP address, using "
1646 "INADDR_ANY instead.\n");
1647 in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
1650 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
1652 int loc_errno = errno;
1653 WARN("\tfailure - errno = %i\n", errno);
1654 errno = loc_errno;
1655 switch (errno)
1657 case EBADF:
1658 SetLastError(WSAENOTSOCK);
1659 break;
1660 case EADDRNOTAVAIL:
1661 SetLastError(WSAEINVAL);
1662 break;
1663 default:
1664 SetLastError(wsaErrno());
1665 break;
1668 else
1670 res=0; /* success */
1674 release_sock_fd( s, fd );
1676 return res;
1679 /***********************************************************************
1680 * closesocket (WS2_32.3)
1682 int WINAPI WS_closesocket(SOCKET s)
1684 TRACE("socket %04lx\n", s);
1685 if (CloseHandle(SOCKET2HANDLE(s))) return 0;
1686 return SOCKET_ERROR;
1689 /***********************************************************************
1690 * connect (WS2_32.4)
1692 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
1694 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1696 TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1698 if (fd != -1)
1700 union generic_unix_sockaddr uaddr;
1701 unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1703 if (!uaddrlen)
1705 SetLastError(WSAEFAULT);
1707 else
1709 if (name->sa_family == WS_AF_INET)
1711 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
1712 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
1714 /* Trying to connect to magic replace-loopback address,
1715 * assuming we really want to connect to localhost */
1716 TRACE("Trying to connect to magic IP address, using "
1717 "INADDR_LOOPBACK instead.\n");
1718 in4->sin_addr.s_addr = htonl(WS_INADDR_LOOPBACK);
1722 if (connect(fd, &uaddr.addr, uaddrlen) == 0)
1723 goto connect_success;
1726 if (errno == EINPROGRESS)
1728 /* tell wineserver that a connection is in progress */
1729 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1730 FD_CONNECT|FD_READ|FD_WRITE,
1731 FD_WINE_CONNECTED|FD_WINE_LISTENING);
1732 if (_is_blocking(s))
1734 int result;
1735 /* block here */
1736 do_block(fd, POLLIN | POLLOUT, -1);
1737 _sync_sock_state(s); /* let wineserver notice connection */
1738 /* retrieve any error codes from it */
1739 result = _get_sock_error(s, FD_CONNECT_BIT);
1740 if (result)
1741 SetLastError(result);
1742 else
1744 goto connect_success;
1747 else
1749 SetLastError(WSAEWOULDBLOCK);
1752 else
1754 SetLastError(wsaErrno());
1756 release_sock_fd( s, fd );
1758 return SOCKET_ERROR;
1760 connect_success:
1761 release_sock_fd( s, fd );
1762 _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1763 FD_WINE_CONNECTED|FD_READ|FD_WRITE,
1764 FD_CONNECT|FD_WINE_LISTENING);
1765 return 0;
1768 /***********************************************************************
1769 * WSAConnect (WS2_32.30)
1771 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
1772 LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
1773 LPQOS lpSQOS, LPQOS lpGQOS )
1775 if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
1776 FIXME("unsupported parameters!\n");
1777 return WS_connect( s, name, namelen );
1781 /***********************************************************************
1782 * getpeername (WS2_32.5)
1784 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
1786 int fd;
1787 int res;
1789 TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, *namelen);
1791 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1792 if( (name == NULL) || (namelen == NULL) )
1794 SetLastError( WSAEFAULT );
1795 return SOCKET_ERROR;
1798 fd = get_sock_fd( s, 0, NULL );
1799 res = SOCKET_ERROR;
1801 if (fd != -1)
1803 union generic_unix_sockaddr uaddr;
1804 unsigned int uaddrlen = sizeof(uaddr);
1806 if (getpeername(fd, &uaddr.addr, &uaddrlen) != 0)
1808 SetLastError(wsaErrno());
1810 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
1812 /* The buffer was too small */
1813 SetLastError(WSAEFAULT);
1815 else
1817 res=0;
1819 release_sock_fd( s, fd );
1821 return res;
1824 /***********************************************************************
1825 * getsockname (WS2_32.6)
1827 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
1829 int fd;
1830 int res;
1832 TRACE("socket: %04lx, ptr %p, len %8x\n", s, name, *namelen);
1834 /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1835 if( (name == NULL) || (namelen == NULL) )
1837 SetLastError( WSAEFAULT );
1838 return SOCKET_ERROR;
1841 fd = get_sock_fd( s, 0, NULL );
1842 res = SOCKET_ERROR;
1844 if (fd != -1)
1846 union generic_unix_sockaddr uaddr;
1847 unsigned int uaddrlen = sizeof(uaddr);
1849 if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
1851 SetLastError(wsaErrno());
1853 else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
1855 SetLastError(WSAEINVAL);
1857 else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
1859 /* The buffer was too small */
1860 SetLastError(WSAEFAULT);
1862 else
1864 res=0;
1866 release_sock_fd( s, fd );
1868 return res;
1871 /***********************************************************************
1872 * getsockopt (WS2_32.7)
1874 INT WINAPI WS_getsockopt(SOCKET s, INT level,
1875 INT optname, char *optval, INT *optlen)
1877 int fd;
1878 INT ret = 0;
1880 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
1881 s, level, optname, optval, *optlen);
1883 switch(level)
1885 case WS_SOL_SOCKET:
1887 switch(optname)
1889 /* Handle common cases. The special cases are below, sorted
1890 * alphabetically */
1891 case WS_SO_ACCEPTCONN:
1892 case WS_SO_BROADCAST:
1893 case WS_SO_DEBUG:
1894 case WS_SO_ERROR:
1895 case WS_SO_KEEPALIVE:
1896 case WS_SO_OOBINLINE:
1897 case WS_SO_RCVBUF:
1898 case WS_SO_REUSEADDR:
1899 case WS_SO_SNDBUF:
1900 case WS_SO_TYPE:
1901 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1902 return SOCKET_ERROR;
1903 convert_sockopt(&level, &optname);
1904 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
1906 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1907 ret = SOCKET_ERROR;
1909 release_sock_fd( s, fd );
1910 return ret;
1912 case WS_SO_DONTLINGER:
1914 struct linger lingval;
1915 unsigned int len = sizeof(struct linger);
1917 if (!optlen || *optlen < sizeof(BOOL)|| !optval)
1919 SetLastError(WSAEFAULT);
1920 return SOCKET_ERROR;
1922 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1923 return SOCKET_ERROR;
1925 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
1927 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1928 ret = SOCKET_ERROR;
1930 else
1932 *(BOOL *)optval = (lingval.l_onoff) ? FALSE : TRUE;
1933 *optlen = sizeof(BOOL);
1936 release_sock_fd( s, fd );
1937 return ret;
1940 /* As mentioned in setsockopt, Windows ignores this, so we
1941 * always return true here */
1942 case WS_SO_DONTROUTE:
1943 if (!optlen || *optlen < sizeof(BOOL) || !optval)
1945 SetLastError(WSAEFAULT);
1946 return SOCKET_ERROR;
1948 *(BOOL *)optval = TRUE;
1949 *optlen = sizeof(BOOL);
1950 return 0;
1952 case WS_SO_LINGER:
1954 struct linger lingval;
1955 unsigned int len = sizeof(struct linger);
1957 /* struct linger and LINGER have different sizes */
1958 if (!optlen || *optlen < sizeof(LINGER) || !optval)
1960 SetLastError(WSAEFAULT);
1961 return SOCKET_ERROR;
1963 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1964 return SOCKET_ERROR;
1966 if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
1968 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1969 ret = SOCKET_ERROR;
1971 else
1973 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
1974 ((LINGER *)optval)->l_linger = lingval.l_linger;
1975 *optlen = sizeof(struct linger);
1978 release_sock_fd( s, fd );
1979 return ret;
1982 case WS_SO_MAX_MSG_SIZE:
1983 if (!optlen || *optlen < sizeof(int) || !optval)
1985 SetLastError(WSAEFAULT);
1986 return SOCKET_ERROR;
1988 TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
1989 *(int *)optval = 65507;
1990 *optlen = sizeof(int);
1991 return 0;
1993 /* SO_OPENTYPE does not require a valid socket handle. */
1994 case WS_SO_OPENTYPE:
1995 if (!optlen || *optlen < sizeof(int) || !optval)
1997 SetLastError(WSAEFAULT);
1998 return SOCKET_ERROR;
2000 *(int *)optval = get_per_thread_data()->opentype;
2001 *optlen = sizeof(int);
2002 TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
2003 return 0;
2005 #ifdef SO_RCVTIMEO
2006 case WS_SO_RCVTIMEO:
2007 #endif
2008 #ifdef SO_SNDTIMEO
2009 case WS_SO_SNDTIMEO:
2010 #endif
2011 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
2013 struct timeval tv;
2014 unsigned int len = sizeof(struct timeval);
2016 if (!optlen || *optlen < sizeof(int)|| !optval)
2018 SetLastError(WSAEFAULT);
2019 return SOCKET_ERROR;
2021 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2022 return SOCKET_ERROR;
2024 convert_sockopt(&level, &optname);
2025 if (getsockopt(fd, level, optname, &tv, &len) != 0 )
2027 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2028 ret = SOCKET_ERROR;
2030 else
2032 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
2033 *optlen = sizeof(int);
2036 release_sock_fd( s, fd );
2037 return ret;
2039 #endif
2040 default:
2041 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
2042 SetLastError(WSAENOPROTOOPT);
2043 return SOCKET_ERROR;
2044 } /* end switch(optname) */
2045 }/* end case WS_SOL_SOCKET */
2046 #ifdef HAVE_IPX
2047 case NSPROTO_IPX:
2049 struct WS_sockaddr_ipx addr;
2050 IPX_ADDRESS_DATA *data;
2051 int namelen;
2052 switch(optname)
2054 case IPX_PTYPE:
2055 if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
2056 #ifdef SOL_IPX
2057 if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (unsigned int*)optlen) == -1)
2059 ret = SOCKET_ERROR;
2061 #else
2063 struct ipx val;
2064 socklen_t len=sizeof(struct ipx);
2065 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
2066 ret = SOCKET_ERROR;
2067 else
2068 *optval = (int)val.ipx_pt;
2070 #endif
2071 TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
2072 release_sock_fd( s, fd );
2073 return ret;
2075 case IPX_ADDRESS:
2077 * On a Win2000 system with one network card there are usually
2078 * three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
2079 * Using this call you can then retrieve info about this all.
2080 * In case of Linux it is a bit different. Usually you have
2081 * only "one" device active and further it is not possible to
2082 * query things like the linkspeed.
2084 FIXME("IPX_ADDRESS\n");
2085 namelen = sizeof(struct WS_sockaddr_ipx);
2086 memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
2087 WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
2089 data = (IPX_ADDRESS_DATA*)optval;
2090 memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
2091 memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
2092 data->adapternum = 0;
2093 data->wan = FALSE; /* We are not on a wan for now .. */
2094 data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
2095 data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
2096 data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
2097 * note 1MB = 1000kB in this case */
2098 return 0;
2100 case IPX_MAX_ADAPTER_NUM:
2101 FIXME("IPX_MAX_ADAPTER_NUM\n");
2102 *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
2103 return 0;
2105 default:
2106 FIXME("IPX optname:%x\n", optname);
2107 return SOCKET_ERROR;
2108 }/* end switch(optname) */
2109 } /* end case NSPROTO_IPX */
2110 #endif
2112 #ifdef HAVE_IRDA
2113 case WS_SOL_IRLMP:
2114 switch(optname)
2116 case WS_IRLMP_ENUMDEVICES:
2118 static const int MAX_IRDA_DEVICES = 10;
2119 char buf[sizeof(struct irda_device_list) +
2120 (MAX_IRDA_DEVICES - 1) * sizeof(struct irda_device_info)];
2121 int fd, res;
2122 socklen_t len = sizeof(buf);
2124 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2125 return SOCKET_ERROR;
2126 res = getsockopt( fd, SOL_IRLMP, IRLMP_ENUMDEVICES, buf, &len );
2127 if (res < 0)
2129 SetLastError(wsaErrno());
2130 return SOCKET_ERROR;
2132 else
2134 struct irda_device_list *src = (struct irda_device_list *)buf;
2135 DEVICELIST *dst = (DEVICELIST *)optval;
2136 INT needed = sizeof(DEVICELIST), i;
2138 if (src->len > 0)
2139 needed += (src->len - 1) * sizeof(IRDA_DEVICE_INFO);
2140 if (*optlen < needed)
2142 SetLastError(WSAEFAULT);
2143 return SOCKET_ERROR;
2145 *optlen = needed;
2146 TRACE("IRLMP_ENUMDEVICES: %d devices found:\n", src->len);
2147 dst->numDevice = src->len;
2148 for (i = 0; i < src->len; i++)
2150 TRACE("saddr = %08x, daddr = %08x, info = %s, hints = %02x%02x\n",
2151 src->dev[i].saddr, src->dev[i].daddr,
2152 src->dev[i].info, src->dev[i].hints[0],
2153 src->dev[i].hints[1]);
2154 memcpy( dst->Device[i].irdaDeviceID,
2155 &src->dev[i].daddr,
2156 sizeof(dst->Device[i].irdaDeviceID) ) ;
2157 memcpy( dst->Device[i].irdaDeviceName,
2158 &src->dev[i].info,
2159 sizeof(dst->Device[i].irdaDeviceName) ) ;
2160 memcpy( &dst->Device[i].irdaDeviceHints1,
2161 &src->dev[i].hints[0],
2162 sizeof(dst->Device[i].irdaDeviceHints1) ) ;
2163 memcpy( &dst->Device[i].irdaDeviceHints2,
2164 &src->dev[i].hints[1],
2165 sizeof(dst->Device[i].irdaDeviceHints2) ) ;
2166 dst->Device[i].irdaCharSet = src->dev[i].charset;
2168 return 0;
2171 default:
2172 FIXME("IrDA optname:0x%x\n", optname);
2173 return SOCKET_ERROR;
2175 break; /* case WS_SOL_IRLMP */
2176 #endif
2178 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
2179 case WS_IPPROTO_TCP:
2180 switch(optname)
2182 case WS_TCP_NODELAY:
2183 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2184 return SOCKET_ERROR;
2185 convert_sockopt(&level, &optname);
2186 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2188 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2189 ret = SOCKET_ERROR;
2191 release_sock_fd( s, fd );
2192 return ret;
2194 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
2195 return SOCKET_ERROR;
2197 case WS_IPPROTO_IP:
2198 switch(optname)
2200 case WS_IP_ADD_MEMBERSHIP:
2201 case WS_IP_DROP_MEMBERSHIP:
2202 #ifdef IP_HDRINCL
2203 case WS_IP_HDRINCL:
2204 #endif
2205 case WS_IP_MULTICAST_IF:
2206 case WS_IP_MULTICAST_LOOP:
2207 case WS_IP_MULTICAST_TTL:
2208 case WS_IP_OPTIONS:
2209 case WS_IP_TOS:
2210 case WS_IP_TTL:
2211 if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
2212 return SOCKET_ERROR;
2213 convert_sockopt(&level, &optname);
2214 if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
2216 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2217 ret = SOCKET_ERROR;
2219 release_sock_fd( s, fd );
2220 return ret;
2221 case WS_IP_DONTFRAGMENT:
2222 FIXME("WS_IP_DONTFRAGMENT is always false!\n");
2223 *(BOOL*)optval = FALSE;
2224 return 0;
2226 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
2227 return SOCKET_ERROR;
2229 case WS_IPPROTO_IPV6:
2230 FIXME("IPPROTO_IPV6 unimplemented (optname 0x%08x)\n", optname);
2231 return SOCKET_ERROR;
2233 default:
2234 WARN("Unknown level: 0x%08x\n", level);
2235 SetLastError(WSAEINVAL);
2236 return SOCKET_ERROR;
2237 } /* end switch(level) */
2240 /***********************************************************************
2241 * htonl (WS2_32.8)
2243 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
2245 return htonl(hostlong);
2249 /***********************************************************************
2250 * htons (WS2_32.9)
2252 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
2254 return htons(hostshort);
2257 /***********************************************************************
2258 * WSAHtonl (WS2_32.46)
2259 * From MSDN description of error codes, this function should also
2260 * check if WinSock has been initialized and the socket is a valid
2261 * socket. But why? This function only translates a host byte order
2262 * u_long into a network byte order u_long...
2264 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
2266 if (lpnetlong)
2268 *lpnetlong = htonl(hostlong);
2269 return 0;
2271 WSASetLastError(WSAEFAULT);
2272 return SOCKET_ERROR;
2275 /***********************************************************************
2276 * WSAHtons (WS2_32.47)
2277 * From MSDN description of error codes, this function should also
2278 * check if WinSock has been initialized and the socket is a valid
2279 * socket. But why? This function only translates a host byte order
2280 * u_short into a network byte order u_short...
2282 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
2285 if (lpnetshort)
2287 *lpnetshort = htons(hostshort);
2288 return 0;
2290 WSASetLastError(WSAEFAULT);
2291 return SOCKET_ERROR;
2295 /***********************************************************************
2296 * inet_addr (WS2_32.11)
2298 WS_u_long WINAPI WS_inet_addr(const char *cp)
2300 if (!cp) return INADDR_NONE;
2301 return inet_addr(cp);
2305 /***********************************************************************
2306 * ntohl (WS2_32.14)
2308 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
2310 return ntohl(netlong);
2314 /***********************************************************************
2315 * ntohs (WS2_32.15)
2317 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
2319 return ntohs(netshort);
2323 /***********************************************************************
2324 * inet_ntoa (WS2_32.12)
2326 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
2328 /* use "buffer for dummies" here because some applications have a
2329 * propensity to decode addresses in ws_hostent structure without
2330 * saving them first...
2332 static char dbuffer[16]; /* Yes, 16: 4*3 digits + 3 '.' + 1 '\0' */
2334 char* s = inet_ntoa(*((struct in_addr*)&in));
2335 if( s )
2337 strcpy(dbuffer, s);
2338 return dbuffer;
2340 SetLastError(wsaErrno());
2341 return NULL;
2344 /**********************************************************************
2345 * WSAIoctl (WS2_32.50)
2348 INT WINAPI WSAIoctl(SOCKET s,
2349 DWORD dwIoControlCode,
2350 LPVOID lpvInBuffer,
2351 DWORD cbInBuffer,
2352 LPVOID lpbOutBuffer,
2353 DWORD cbOutBuffer,
2354 LPDWORD lpcbBytesReturned,
2355 LPWSAOVERLAPPED lpOverlapped,
2356 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
2358 TRACE("%ld, 0x%08x, %p, %d, %p, %d, %p, %p, %p\n",
2359 s, dwIoControlCode, lpvInBuffer, cbInBuffer, lpbOutBuffer,
2360 cbOutBuffer, lpcbBytesReturned, lpOverlapped, lpCompletionRoutine);
2362 switch( dwIoControlCode )
2364 case WS_FIONBIO:
2365 if (cbInBuffer != sizeof(WS_u_long)) {
2366 WSASetLastError(WSAEFAULT);
2367 return SOCKET_ERROR;
2369 return WS_ioctlsocket( s, WS_FIONBIO, lpvInBuffer);
2371 case WS_FIONREAD:
2372 if (cbOutBuffer != sizeof(WS_u_long)) {
2373 WSASetLastError(WSAEFAULT);
2374 return SOCKET_ERROR;
2376 return WS_ioctlsocket( s, WS_FIONREAD, lpbOutBuffer);
2378 case WS_SIO_GET_INTERFACE_LIST:
2380 INTERFACE_INFO* intArray = (INTERFACE_INFO*)lpbOutBuffer;
2381 DWORD size, numInt, apiReturn;
2382 int fd;
2384 TRACE("-> SIO_GET_INTERFACE_LIST request\n");
2386 if (!lpbOutBuffer)
2388 WSASetLastError(WSAEFAULT);
2389 return SOCKET_ERROR;
2391 if (!lpcbBytesReturned)
2393 WSASetLastError(WSAEFAULT);
2394 return SOCKET_ERROR;
2397 fd = get_sock_fd( s, 0, NULL );
2398 if (fd == -1) return SOCKET_ERROR;
2400 apiReturn = GetAdaptersInfo(NULL, &size);
2401 if (apiReturn == ERROR_NO_DATA)
2403 numInt = 0;
2405 else if (apiReturn == ERROR_BUFFER_OVERFLOW)
2407 PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
2409 if (table)
2411 if (GetAdaptersInfo(table, &size) == NO_ERROR)
2413 PIP_ADAPTER_INFO ptr;
2415 if (size*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > cbOutBuffer)
2417 WARN("Buffer too small = %u, cbOutBuffer = %u\n", size, cbOutBuffer);
2418 HeapFree(GetProcessHeap(),0,table);
2419 release_sock_fd( s, fd );
2420 WSASetLastError(WSAEFAULT);
2421 return SOCKET_ERROR;
2423 for (ptr = table, numInt = 0; ptr;
2424 ptr = ptr->Next, intArray++, numInt++)
2426 unsigned int addr, mask, bcast;
2427 struct ifreq ifInfo;
2429 /* Socket Status Flags */
2430 lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
2431 if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
2433 ERR("Error obtaining status flags for socket!\n");
2434 HeapFree(GetProcessHeap(),0,table);
2435 release_sock_fd( s, fd );
2436 WSASetLastError(WSAEINVAL);
2437 return SOCKET_ERROR;
2439 else
2441 /* set flags; the values of IFF_* are not the same
2442 under Linux and Windows, therefore must generate
2443 new flags */
2444 intArray->iiFlags = 0;
2445 if (ifInfo.ifr_flags & IFF_BROADCAST)
2446 intArray->iiFlags |= WS_IFF_BROADCAST;
2447 #ifdef IFF_POINTOPOINT
2448 if (ifInfo.ifr_flags & IFF_POINTOPOINT)
2449 intArray->iiFlags |= WS_IFF_POINTTOPOINT;
2450 #endif
2451 if (ifInfo.ifr_flags & IFF_LOOPBACK)
2452 intArray->iiFlags |= WS_IFF_LOOPBACK;
2453 if (ifInfo.ifr_flags & IFF_UP)
2454 intArray->iiFlags |= WS_IFF_UP;
2455 if (ifInfo.ifr_flags & IFF_MULTICAST)
2456 intArray->iiFlags |= WS_IFF_MULTICAST;
2459 addr = inet_addr(ptr->IpAddressList.IpAddress.String);
2460 mask = inet_addr(ptr->IpAddressList.IpMask.String);
2461 bcast = addr | ~mask;
2462 intArray->iiAddress.AddressIn.sin_family = AF_INET;
2463 intArray->iiAddress.AddressIn.sin_port = 0;
2464 intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
2465 addr;
2466 intArray->iiNetmask.AddressIn.sin_family = AF_INET;
2467 intArray->iiNetmask.AddressIn.sin_port = 0;
2468 intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
2469 mask;
2470 intArray->iiBroadcastAddress.AddressIn.sin_family =
2471 AF_INET;
2472 intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
2473 intArray->iiBroadcastAddress.AddressIn.sin_addr.
2474 WS_s_addr = bcast;
2477 else
2479 ERR("Unable to get interface table!\n");
2480 release_sock_fd( s, fd );
2481 HeapFree(GetProcessHeap(),0,table);
2482 WSASetLastError(WSAEINVAL);
2483 return SOCKET_ERROR;
2485 HeapFree(GetProcessHeap(),0,table);
2487 else
2489 release_sock_fd( s, fd );
2490 WSASetLastError(WSAEINVAL);
2491 return SOCKET_ERROR;
2494 else
2496 ERR("Unable to get interface table!\n");
2497 release_sock_fd( s, fd );
2498 WSASetLastError(WSAEINVAL);
2499 return SOCKET_ERROR;
2501 /* Calculate the size of the array being returned */
2502 *lpcbBytesReturned = sizeof(INTERFACE_INFO) * numInt;
2503 release_sock_fd( s, fd );
2504 break;
2507 case WS_SIO_ADDRESS_LIST_CHANGE:
2508 FIXME("-> SIO_ADDRESS_LIST_CHANGE request: stub\n");
2509 /* FIXME: error and return code depend on whether socket was created
2510 * with WSA_FLAG_OVERLAPPED, but there is no easy way to get this */
2511 break;
2513 case WS_SIO_ADDRESS_LIST_QUERY:
2515 DWORD size;
2517 TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
2519 if (!lpcbBytesReturned)
2521 WSASetLastError(WSAEFAULT);
2522 return SOCKET_ERROR;
2525 if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
2527 IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
2528 DWORD need, num;
2530 if (!table || GetAdaptersInfo(table, &size))
2532 HeapFree(GetProcessHeap(), 0, table);
2533 WSASetLastError(WSAEINVAL);
2534 return SOCKET_ERROR;
2537 for (p = table, num = 0; p; p = p->Next)
2538 if (p->IpAddressList.IpAddress.String[0]) num++;
2540 need = sizeof(SOCKET_ADDRESS_LIST) + sizeof(SOCKET_ADDRESS) * (num - 1);
2541 need += sizeof(SOCKADDR) * num;
2542 *lpcbBytesReturned = need;
2544 if (need > cbOutBuffer)
2546 HeapFree(GetProcessHeap(), 0, table);
2547 WSASetLastError(WSAEFAULT);
2548 return SOCKET_ERROR;
2551 if (lpbOutBuffer)
2553 unsigned int i;
2554 SOCKET_ADDRESS *sa;
2555 SOCKET_ADDRESS_LIST *sa_list = (SOCKET_ADDRESS_LIST *)lpbOutBuffer;
2556 SOCKADDR_IN *sockaddr;
2558 sa = sa_list->Address;
2559 sockaddr = (SOCKADDR_IN *)((char *)sa + num * sizeof(SOCKET_ADDRESS));
2560 sa_list->iAddressCount = num;
2562 for (p = table, i = 0; p; p = p->Next)
2564 if (!p->IpAddressList.IpAddress.String[0]) continue;
2566 sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
2567 sa[i].iSockaddrLength = sizeof(SOCKADDR);
2569 sockaddr[i].sin_family = AF_INET;
2570 sockaddr[i].sin_port = 0;
2571 sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
2572 i++;
2576 HeapFree(GetProcessHeap(), 0, table);
2577 return 0;
2579 else
2581 WARN("unable to get IP address list\n");
2582 WSASetLastError(WSAEINVAL);
2583 return SOCKET_ERROR;
2586 case WS_SIO_FLUSH:
2587 FIXME("SIO_FLUSH: stub.\n");
2588 break;
2590 case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
2591 FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(lpvInBuffer));
2592 WSASetLastError(WSAEOPNOTSUPP);
2593 return SOCKET_ERROR;
2595 case WS_SIO_KEEPALIVE_VALS:
2597 int fd;
2598 struct tcp_keepalive *k = lpvInBuffer;
2599 int keepalive = k->onoff ? 1 : 0;
2600 int keepidle = k->keepalivetime / 1000;
2601 int keepintvl = k->keepaliveinterval / 1000;
2603 if (!lpvInBuffer)
2605 WSASetLastError(WSAEINVAL);
2606 return SOCKET_ERROR;
2609 TRACE("onoff: %d, keepalivetime: %d, keepaliveinterval: %d\n", keepalive, keepidle, keepintvl);
2611 fd = get_sock_fd(s, 0, NULL);
2612 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive, sizeof(int)) == -1)
2614 release_sock_fd(s, fd);
2615 WSASetLastError(WSAEINVAL);
2616 return SOCKET_ERROR;
2618 #if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL)
2619 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, (void *)&keepidle, sizeof(int)) == -1)
2621 release_sock_fd(s, fd);
2622 WSASetLastError(WSAEINVAL);
2623 return SOCKET_ERROR;
2625 if (setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, (void *)&keepintvl, sizeof(int)) == -1)
2627 release_sock_fd(s, fd);
2628 WSASetLastError(WSAEINVAL);
2629 return SOCKET_ERROR;
2631 #else
2632 FIXME("ignoring keepalive interval and timeout\n");
2633 #endif
2635 release_sock_fd(s, fd);
2636 break;
2638 default:
2639 FIXME("unsupported WS_IOCTL cmd (%08x)\n", dwIoControlCode);
2640 WSASetLastError(WSAEOPNOTSUPP);
2641 return SOCKET_ERROR;
2644 return 0;
2648 /***********************************************************************
2649 * ioctlsocket (WS2_32.10)
2651 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
2653 int fd;
2654 LONG newcmd = cmd;
2656 TRACE("socket %04lx, cmd %08x, ptr %p\n", s, cmd, argp);
2657 /* broken apps like defcon pass the argp value directly instead of a pointer to it */
2658 if(IS_INTRESOURCE(argp))
2660 SetLastError(WSAEFAULT);
2661 return SOCKET_ERROR;
2664 switch( cmd )
2666 case WS_FIONREAD:
2667 newcmd=FIONREAD;
2668 break;
2670 case WS_FIONBIO:
2671 if( _get_sock_mask(s) )
2673 /* AsyncSelect()'ed sockets are always nonblocking */
2674 if (*argp) return 0;
2675 SetLastError(WSAEINVAL);
2676 return SOCKET_ERROR;
2678 if (*argp)
2679 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
2680 else
2681 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
2682 return 0;
2684 case WS_SIOCATMARK:
2685 newcmd=SIOCATMARK;
2686 break;
2688 case WS_FIOASYNC:
2689 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
2690 SetLastError(WSAEINVAL);
2691 return SOCKET_ERROR;
2693 case SIOCGIFBRDADDR:
2694 case SIOCGIFNETMASK:
2695 case SIOCGIFADDR:
2696 /* These don't need any special handling. They are used by
2697 WsControl, and are here to suppress an unnecessary warning. */
2698 break;
2700 default:
2701 /* Netscape tries hard to use bogus ioctl 0x667e */
2702 /* FIXME: 0x667e above is ('f' << 8) | 126, and is a low word of
2703 * FIONBIO (_IOW('f', 126, u_long)), how that should be handled?
2705 WARN("\tunknown WS_IOCTL cmd (%08x)\n", cmd);
2706 break;
2709 fd = get_sock_fd( s, 0, NULL );
2710 if (fd != -1)
2712 if( ioctl(fd, newcmd, (char*)argp ) == 0 )
2714 release_sock_fd( s, fd );
2715 return 0;
2717 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2718 release_sock_fd( s, fd );
2720 return SOCKET_ERROR;
2723 /***********************************************************************
2724 * listen (WS2_32.13)
2726 int WINAPI WS_listen(SOCKET s, int backlog)
2728 int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2730 TRACE("socket %04lx, backlog %d\n", s, backlog);
2731 if (fd != -1)
2733 if (listen(fd, backlog) == 0)
2735 release_sock_fd( s, fd );
2736 _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
2737 FD_WINE_LISTENING,
2738 FD_CONNECT|FD_WINE_CONNECTED);
2739 return 0;
2741 SetLastError(wsaErrno());
2742 release_sock_fd( s, fd );
2744 return SOCKET_ERROR;
2747 /***********************************************************************
2748 * recv (WS2_32.16)
2750 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
2752 DWORD n, dwFlags = flags;
2753 WSABUF wsabuf;
2755 wsabuf.len = len;
2756 wsabuf.buf = buf;
2758 if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
2759 return SOCKET_ERROR;
2760 else
2761 return n;
2764 /***********************************************************************
2765 * recvfrom (WS2_32.17)
2767 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
2768 struct WS_sockaddr *from, int *fromlen)
2770 DWORD n, dwFlags = flags;
2771 WSABUF wsabuf;
2773 wsabuf.len = len;
2774 wsabuf.buf = buf;
2776 if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL) == SOCKET_ERROR )
2777 return SOCKET_ERROR;
2778 else
2779 return n;
2782 /* allocate a poll array for the corresponding fd sets */
2783 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
2784 const WS_fd_set *exceptfds, int *count_ptr )
2786 unsigned int i, j = 0, count = 0;
2787 struct pollfd *fds;
2789 if (readfds) count += readfds->fd_count;
2790 if (writefds) count += writefds->fd_count;
2791 if (exceptfds) count += exceptfds->fd_count;
2792 *count_ptr = count;
2793 if (!count) return NULL;
2794 if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0])))) return NULL;
2795 if (readfds)
2796 for (i = 0; i < readfds->fd_count; i++, j++)
2798 fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
2799 fds[j].events = POLLIN;
2800 fds[j].revents = 0;
2802 if (writefds)
2803 for (i = 0; i < writefds->fd_count; i++, j++)
2805 fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
2806 fds[j].events = POLLOUT;
2807 fds[j].revents = 0;
2809 if (exceptfds)
2810 for (i = 0; i < exceptfds->fd_count; i++, j++)
2812 fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
2813 fds[j].events = POLLHUP;
2814 fds[j].revents = 0;
2816 return fds;
2819 /* release the file descriptor obtained in fd_sets_to_poll */
2820 /* must be called with the original fd_set arrays, before calling get_poll_results */
2821 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
2822 const WS_fd_set *exceptfds, struct pollfd *fds )
2824 unsigned int i, j = 0;
2826 if (readfds)
2828 for (i = 0; i < readfds->fd_count; i++, j++)
2829 if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
2831 if (writefds)
2833 for (i = 0; i < writefds->fd_count; i++, j++)
2834 if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
2836 if (exceptfds)
2838 for (i = 0; i < exceptfds->fd_count; i++, j++)
2839 if (fds[j].fd != -1)
2841 /* make sure we have a real error before releasing the fd */
2842 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
2843 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
2848 /* map the poll results back into the Windows fd sets */
2849 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
2850 const struct pollfd *fds )
2852 unsigned int i, j = 0, k, total = 0;
2854 if (readfds)
2856 for (i = k = 0; i < readfds->fd_count; i++, j++)
2857 if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
2858 readfds->fd_count = k;
2859 total += k;
2861 if (writefds)
2863 for (i = k = 0; i < writefds->fd_count; i++, j++)
2864 if (fds[j].revents) writefds->fd_array[k++] = writefds->fd_array[i];
2865 writefds->fd_count = k;
2866 total += k;
2868 if (exceptfds)
2870 for (i = k = 0; i < exceptfds->fd_count; i++, j++)
2871 if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
2872 exceptfds->fd_count = k;
2873 total += k;
2875 return total;
2879 /***********************************************************************
2880 * select (WS2_32.18)
2882 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
2883 WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
2884 const struct WS_timeval* ws_timeout)
2886 struct pollfd *pollfds;
2887 struct timeval tv1, tv2;
2888 int torig = 0;
2889 int count, ret, timeout = -1;
2891 TRACE("read %p, write %p, excp %p timeout %p\n",
2892 ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
2894 if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )) && count)
2896 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2897 return SOCKET_ERROR;
2900 if (ws_timeout)
2902 torig = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
2903 timeout = torig;
2904 gettimeofday( &tv1, 0 );
2907 while ((ret = poll( pollfds, count, timeout )) < 0)
2909 if (errno == EINTR)
2911 if (!ws_timeout) continue;
2912 gettimeofday( &tv2, 0 );
2914 tv2.tv_sec -= tv1.tv_sec;
2915 tv2.tv_usec -= tv1.tv_usec;
2916 if (tv2.tv_usec < 0)
2918 tv2.tv_usec += 1000000;
2919 tv2.tv_sec -= 1;
2922 timeout = torig - (tv2.tv_sec * 1000) - (tv2.tv_usec + 999) / 1000;
2923 if (timeout <= 0) break;
2924 } else break;
2926 release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
2928 if (ret == -1) SetLastError(wsaErrno());
2929 else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
2930 HeapFree( GetProcessHeap(), 0, pollfds );
2931 return ret;
2934 /* helper to send completion messages for client-only i/o operation case */
2935 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus,
2936 ULONG Information )
2938 NTSTATUS status;
2940 SERVER_START_REQ( add_fd_completion )
2942 req->handle = wine_server_obj_handle( SOCKET2HANDLE(sock) );
2943 req->cvalue = CompletionValue;
2944 req->status = CompletionStatus;
2945 req->information = Information;
2946 status = wine_server_call( req );
2948 SERVER_END_REQ;
2952 /***********************************************************************
2953 * send (WS2_32.19)
2955 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
2957 DWORD n;
2958 WSABUF wsabuf;
2960 wsabuf.len = len;
2961 wsabuf.buf = (char*) buf;
2963 if ( WSASendTo( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
2964 return SOCKET_ERROR;
2965 else
2966 return n;
2969 /***********************************************************************
2970 * WSASend (WS2_32.72)
2972 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2973 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2974 LPWSAOVERLAPPED lpOverlapped,
2975 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2977 return WSASendTo( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
2978 NULL, 0, lpOverlapped, lpCompletionRoutine );
2981 /***********************************************************************
2982 * WSASendDisconnect (WS2_32.73)
2984 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
2986 return WS_shutdown( s, SD_SEND );
2990 /***********************************************************************
2991 * WSASendTo (WS2_32.74)
2993 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2994 LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2995 const struct WS_sockaddr *to, int tolen,
2996 LPWSAOVERLAPPED lpOverlapped,
2997 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2999 unsigned int i, options;
3000 int n, fd, err;
3001 struct ws2_async *wsa;
3002 int totalLength = 0;
3003 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
3005 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
3006 s, lpBuffers, dwBufferCount, dwFlags,
3007 to, tolen, lpOverlapped, lpCompletionRoutine);
3009 fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
3010 TRACE( "fd=%d, options=%x\n", fd, options );
3012 if ( fd == -1 ) return SOCKET_ERROR;
3014 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
3016 err = WSAEFAULT;
3017 goto error;
3020 wsa->hSocket = SOCKET2HANDLE(s);
3021 wsa->addr = (struct WS_sockaddr *)to;
3022 wsa->addrlen.val = tolen;
3023 wsa->flags = dwFlags;
3024 wsa->n_iovecs = dwBufferCount;
3025 wsa->first_iovec = 0;
3026 for ( i = 0; i < dwBufferCount; i++ )
3028 wsa->iovec[i].iov_base = lpBuffers[i].buf;
3029 wsa->iovec[i].iov_len = lpBuffers[i].len;
3030 totalLength += lpBuffers[i].len;
3033 if (!lpNumberOfBytesSent)
3035 err = WSAEFAULT;
3036 goto error;
3039 for (;;)
3041 n = WS2_send( fd, wsa );
3042 if (n != -1 || errno != EINTR) break;
3044 if (n == -1 && errno != EAGAIN)
3046 err = wsaErrno();
3047 if (cvalue) WS_AddCompletion( s, cvalue, err, 0 );
3048 goto error;
3051 if ((lpOverlapped || lpCompletionRoutine) &&
3052 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
3054 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
3056 wsa->user_overlapped = lpOverlapped;
3057 wsa->completion_func = lpCompletionRoutine;
3058 release_sock_fd( s, fd );
3060 if (n == -1)
3062 iosb->u.Status = STATUS_PENDING;
3063 iosb->Information = 0;
3065 SERVER_START_REQ( register_async )
3067 req->type = ASYNC_TYPE_WRITE;
3068 req->async.handle = wine_server_obj_handle( wsa->hSocket );
3069 req->async.callback = wine_server_client_ptr( WS2_async_send );
3070 req->async.iosb = wine_server_client_ptr( iosb );
3071 req->async.arg = wine_server_client_ptr( wsa );
3072 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
3073 req->async.cvalue = cvalue;
3074 err = wine_server_call( req );
3076 SERVER_END_REQ;
3078 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
3079 WSASetLastError( NtStatusToWSAError( err ));
3080 return SOCKET_ERROR;
3083 iosb->u.Status = STATUS_SUCCESS;
3084 iosb->Information = n;
3085 *lpNumberOfBytesSent = n;
3086 if (!wsa->completion_func)
3088 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
3089 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
3090 HeapFree( GetProcessHeap(), 0, wsa );
3092 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
3093 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
3094 WSASetLastError(0);
3095 return 0;
3098 if ( _is_blocking(s) )
3100 /* On a blocking non-overlapped stream socket,
3101 * sending blocks until the entire buffer is sent. */
3102 DWORD timeout_start = GetTickCount();
3104 *lpNumberOfBytesSent = 0;
3106 while (wsa->first_iovec < dwBufferCount)
3108 struct pollfd pfd;
3109 int timeout = GET_SNDTIMEO(fd);
3111 if (n >= 0)
3113 *lpNumberOfBytesSent += n;
3114 while (wsa->first_iovec < dwBufferCount && wsa->iovec[wsa->first_iovec].iov_len <= n)
3115 n -= wsa->iovec[wsa->first_iovec++].iov_len;
3116 if (wsa->first_iovec >= dwBufferCount) break;
3117 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
3118 wsa->iovec[wsa->first_iovec].iov_len -= n;
3121 if (timeout != -1)
3123 timeout -= GetTickCount() - timeout_start;
3124 if (timeout < 0) timeout = 0;
3127 pfd.fd = fd;
3128 pfd.events = POLLOUT;
3130 if (!timeout || !poll( &pfd, 1, timeout ))
3132 err = WSAETIMEDOUT;
3133 goto error; /* msdn says a timeout in send is fatal */
3136 n = WS2_send( fd, wsa );
3137 if (n == -1 && errno != EAGAIN && errno != EINTR)
3139 err = wsaErrno();
3140 goto error;
3144 else /* non-blocking */
3146 if (n < totalLength)
3147 _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
3148 if (n == -1)
3150 err = WSAEWOULDBLOCK;
3151 goto error;
3153 *lpNumberOfBytesSent = n;
3156 TRACE(" -> %i bytes\n", *lpNumberOfBytesSent);
3158 HeapFree( GetProcessHeap(), 0, wsa );
3159 release_sock_fd( s, fd );
3160 WSASetLastError(0);
3161 return 0;
3163 error:
3164 HeapFree( GetProcessHeap(), 0, wsa );
3165 release_sock_fd( s, fd );
3166 WARN(" -> ERROR %d\n", err);
3167 WSASetLastError(err);
3168 return SOCKET_ERROR;
3171 /***********************************************************************
3172 * sendto (WS2_32.20)
3174 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
3175 const struct WS_sockaddr *to, int tolen)
3177 DWORD n;
3178 WSABUF wsabuf;
3180 wsabuf.len = len;
3181 wsabuf.buf = (char*) buf;
3183 if ( WSASendTo(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
3184 return SOCKET_ERROR;
3185 else
3186 return n;
3189 /***********************************************************************
3190 * setsockopt (WS2_32.21)
3192 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
3193 const char *optval, int optlen)
3195 int fd;
3196 int woptval;
3197 struct linger linger;
3198 struct timeval tval;
3200 TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
3201 s, level, optname, optval, optlen);
3203 /* some broken apps pass the value directly instead of a pointer to it */
3204 if(IS_INTRESOURCE(optval))
3206 SetLastError(WSAEFAULT);
3207 return SOCKET_ERROR;
3210 switch(level)
3212 case WS_SOL_SOCKET:
3213 switch(optname)
3215 /* Some options need some conversion before they can be sent to
3216 * setsockopt. The conversions are done here, then they will fall though
3217 * to the general case. Special options that are not passed to
3218 * setsockopt follow below that.*/
3220 case WS_SO_DONTLINGER:
3221 linger.l_onoff = *((const int*)optval) ? 0: 1;
3222 linger.l_linger = 0;
3223 level = SOL_SOCKET;
3224 optname = SO_LINGER;
3225 optval = (char*)&linger;
3226 optlen = sizeof(struct linger);
3227 break;
3229 case WS_SO_LINGER:
3230 linger.l_onoff = ((LINGER*)optval)->l_onoff;
3231 linger.l_linger = ((LINGER*)optval)->l_linger;
3232 /* FIXME: what is documented behavior if SO_LINGER optval
3233 is null?? */
3234 level = SOL_SOCKET;
3235 optname = SO_LINGER;
3236 optval = (char*)&linger;
3237 optlen = sizeof(struct linger);
3238 break;
3240 case WS_SO_RCVBUF:
3241 if (*(const int*)optval < 2048)
3243 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
3244 return 0;
3246 /* Fall through */
3248 /* The options listed here don't need any special handling. Thanks to
3249 * the conversion happening above, options from there will fall through
3250 * to this, too.*/
3251 case WS_SO_ACCEPTCONN:
3252 case WS_SO_BROADCAST:
3253 case WS_SO_ERROR:
3254 case WS_SO_KEEPALIVE:
3255 case WS_SO_OOBINLINE:
3256 /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
3257 * however, using it the BSD way fixes bug 8513 and seems to be what
3258 * most programmers assume, anyway */
3259 case WS_SO_REUSEADDR:
3260 case WS_SO_SNDBUF:
3261 case WS_SO_TYPE:
3262 convert_sockopt(&level, &optname);
3263 break;
3265 /* SO_DEBUG is a privileged operation, ignore it. */
3266 case WS_SO_DEBUG:
3267 TRACE("Ignoring SO_DEBUG\n");
3268 return 0;
3270 /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
3271 * socket. According to MSDN, this option is silently ignored.*/
3272 case WS_SO_DONTROUTE:
3273 TRACE("Ignoring SO_DONTROUTE\n");
3274 return 0;
3276 /* Stops two sockets from being bound to the same port. Always happens
3277 * on unix systems, so just drop it. */
3278 case WS_SO_EXCLUSIVEADDRUSE:
3279 TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
3280 return 0;
3282 /* SO_OPENTYPE does not require a valid socket handle. */
3283 case WS_SO_OPENTYPE:
3284 if (!optlen || optlen < sizeof(int) || !optval)
3286 SetLastError(WSAEFAULT);
3287 return SOCKET_ERROR;
3289 get_per_thread_data()->opentype = *(const int *)optval;
3290 TRACE("setting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
3291 return 0;
3293 #ifdef SO_RCVTIMEO
3294 case WS_SO_RCVTIMEO:
3295 #endif
3296 #ifdef SO_SNDTIMEO
3297 case WS_SO_SNDTIMEO:
3298 #endif
3299 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
3300 if (optval && optlen == sizeof(UINT32)) {
3301 /* WinSock passes milliseconds instead of struct timeval */
3302 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
3303 tval.tv_sec = *(const UINT32*)optval / 1000;
3304 /* min of 500 milliseconds */
3305 if (tval.tv_sec == 0 && tval.tv_usec < 500000)
3306 tval.tv_usec = 500000;
3307 optlen = sizeof(struct timeval);
3308 optval = (char*)&tval;
3309 } else if (optlen == sizeof(struct timeval)) {
3310 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
3311 } else {
3312 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
3313 return 0;
3315 convert_sockopt(&level, &optname);
3316 break;
3317 #endif
3319 default:
3320 TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
3321 SetLastError(WSAENOPROTOOPT);
3322 return SOCKET_ERROR;
3324 break; /* case WS_SOL_SOCKET */
3326 #ifdef HAVE_IPX
3327 case NSPROTO_IPX:
3328 switch(optname)
3330 case IPX_PTYPE:
3331 fd = get_sock_fd( s, 0, NULL );
3332 TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", *(const int*)optval, fd);
3334 /* We try to set the ipx type on ipx socket level. */
3335 #ifdef SOL_IPX
3336 if(setsockopt(fd, SOL_IPX, IPX_TYPE, optval, optlen) == -1)
3338 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
3339 release_sock_fd( s, fd );
3340 return SOCKET_ERROR;
3342 #else
3344 struct ipx val;
3345 /* Should we retrieve val using a getsockopt call and then
3346 * set the modified one? */
3347 val.ipx_pt = *optval;
3348 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
3350 #endif
3351 release_sock_fd( s, fd );
3352 return 0;
3354 case IPX_FILTERPTYPE:
3355 /* Sets the receive filter packet type, at the moment we don't support it */
3356 FIXME("IPX_FILTERPTYPE: %x\n", *optval);
3357 /* Returning 0 is better for now than returning a SOCKET_ERROR */
3358 return 0;
3360 default:
3361 FIXME("opt_name:%x\n", optname);
3362 return SOCKET_ERROR;
3364 break; /* case NSPROTO_IPX */
3365 #endif
3367 /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3368 case WS_IPPROTO_TCP:
3369 switch(optname)
3371 case WS_TCP_NODELAY:
3372 convert_sockopt(&level, &optname);
3373 break;
3374 default:
3375 FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
3376 return SOCKET_ERROR;
3378 break;
3380 case WS_IPPROTO_IP:
3381 switch(optname)
3383 case WS_IP_ADD_MEMBERSHIP:
3384 case WS_IP_DROP_MEMBERSHIP:
3385 #ifdef IP_HDRINCL
3386 case WS_IP_HDRINCL:
3387 #endif
3388 case WS_IP_MULTICAST_IF:
3389 case WS_IP_MULTICAST_LOOP:
3390 case WS_IP_MULTICAST_TTL:
3391 case WS_IP_OPTIONS:
3392 case WS_IP_TOS:
3393 case WS_IP_TTL:
3394 convert_sockopt(&level, &optname);
3395 break;
3396 case WS_IP_DONTFRAGMENT:
3397 FIXME("IP_DONTFRAGMENT is silently ignored!\n");
3398 return 0;
3399 default:
3400 FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
3401 return SOCKET_ERROR;
3403 break;
3405 default:
3406 WARN("Unknown level: 0x%08x\n", level);
3407 SetLastError(WSAEINVAL);
3408 return SOCKET_ERROR;
3409 } /* end switch(level) */
3411 /* avoid endianness issues if argument is a 16-bit int */
3412 if (optval && optlen < sizeof(int))
3414 woptval= *((const INT16 *) optval);
3415 optval= (char*) &woptval;
3416 optlen=sizeof(int);
3418 fd = get_sock_fd( s, 0, NULL );
3419 if (fd == -1) return SOCKET_ERROR;
3421 if (setsockopt(fd, level, optname, optval, optlen) == 0)
3423 release_sock_fd( s, fd );
3424 return 0;
3426 TRACE("Setting socket error, %d\n", wsaErrno());
3427 SetLastError(wsaErrno());
3428 release_sock_fd( s, fd );
3430 return SOCKET_ERROR;
3433 /***********************************************************************
3434 * shutdown (WS2_32.22)
3436 int WINAPI WS_shutdown(SOCKET s, int how)
3438 int fd, err = WSAENOTSOCK;
3439 unsigned int options, clear_flags = 0;
3441 fd = get_sock_fd( s, 0, &options );
3442 TRACE("socket %04lx, how %i %x\n", s, how, options );
3444 if (fd == -1)
3445 return SOCKET_ERROR;
3447 switch( how )
3449 case 0: /* drop receives */
3450 clear_flags |= FD_READ;
3451 break;
3452 case 1: /* drop sends */
3453 clear_flags |= FD_WRITE;
3454 break;
3455 case 2: /* drop all */
3456 clear_flags |= FD_READ|FD_WRITE;
3457 default:
3458 clear_flags |= FD_WINE_LISTENING;
3461 if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
3463 switch ( how )
3465 case SD_RECEIVE:
3466 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3467 break;
3468 case SD_SEND:
3469 err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3470 break;
3471 case SD_BOTH:
3472 default:
3473 err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3474 if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3475 break;
3477 if (err) goto error;
3479 else /* non-overlapped mode */
3481 if ( shutdown( fd, how ) )
3483 err = wsaErrno();
3484 goto error;
3488 release_sock_fd( s, fd );
3489 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3490 if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
3491 return 0;
3493 error:
3494 release_sock_fd( s, fd );
3495 _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3496 WSASetLastError( err );
3497 return SOCKET_ERROR;
3500 /***********************************************************************
3501 * socket (WS2_32.23)
3503 SOCKET WINAPI WS_socket(int af, int type, int protocol)
3505 TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
3507 return WSASocketA( af, type, protocol, NULL, 0,
3508 get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
3512 /***********************************************************************
3513 * gethostbyaddr (WS2_32.51)
3515 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
3517 struct WS_hostent *retval = NULL;
3518 struct hostent* host;
3520 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3521 char *extrabuf;
3522 int ebufsize=1024;
3523 struct hostent hostentry;
3524 int locerr=ENOBUFS;
3525 host = NULL;
3526 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3527 while(extrabuf) {
3528 int res = gethostbyaddr_r(addr, len, type,
3529 &hostentry, extrabuf, ebufsize, &host, &locerr);
3530 if( res != ERANGE) break;
3531 ebufsize *=2;
3532 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3534 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3535 #else
3536 EnterCriticalSection( &csWSgetXXXbyYYY );
3537 host = gethostbyaddr(addr, len, type);
3538 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3539 #endif
3540 if( host != NULL ) retval = WS_dup_he(host);
3541 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3542 HeapFree(GetProcessHeap(),0,extrabuf);
3543 #else
3544 LeaveCriticalSection( &csWSgetXXXbyYYY );
3545 #endif
3546 TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
3547 return retval;
3550 /***********************************************************************
3551 * gethostbyname (WS2_32.52)
3553 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
3555 struct WS_hostent *retval = NULL;
3556 struct hostent* host;
3557 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3558 char *extrabuf;
3559 int ebufsize=1024;
3560 struct hostent hostentry;
3561 int locerr = ENOBUFS;
3562 #endif
3563 char buf[100];
3564 if( !name || !name[0]) {
3565 name = buf;
3566 if( gethostname( buf, 100) == -1) {
3567 SetLastError( WSAENOBUFS); /* appropriate ? */
3568 return retval;
3571 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3572 host = NULL;
3573 extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3574 while(extrabuf) {
3575 int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
3576 if( res != ERANGE) break;
3577 ebufsize *=2;
3578 extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3580 if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3581 #else
3582 EnterCriticalSection( &csWSgetXXXbyYYY );
3583 host = gethostbyname(name);
3584 if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3585 #endif
3586 if (host) retval = WS_dup_he(host);
3587 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3588 HeapFree(GetProcessHeap(),0,extrabuf);
3589 #else
3590 LeaveCriticalSection( &csWSgetXXXbyYYY );
3591 #endif
3592 if (retval && retval->h_addr_list[0][0] == 127 &&
3593 strcmp(name, "localhost") != 0)
3595 /* hostname != "localhost" but has loopback address. replace by our
3596 * special address.*/
3597 memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
3599 TRACE( "%s ret %p\n", debugstr_a(name), retval );
3600 return retval;
3604 /***********************************************************************
3605 * getprotobyname (WS2_32.53)
3607 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
3609 struct WS_protoent* retval = NULL;
3610 #ifdef HAVE_GETPROTOBYNAME
3611 struct protoent* proto;
3612 EnterCriticalSection( &csWSgetXXXbyYYY );
3613 if( (proto = getprotobyname(name)) != NULL )
3615 retval = WS_dup_pe(proto);
3617 else {
3618 MESSAGE("protocol %s not found; You might want to add "
3619 "this to /etc/protocols\n", debugstr_a(name) );
3620 SetLastError(WSANO_DATA);
3622 LeaveCriticalSection( &csWSgetXXXbyYYY );
3623 #endif
3624 TRACE( "%s ret %p\n", debugstr_a(name), retval );
3625 return retval;
3629 /***********************************************************************
3630 * getprotobynumber (WS2_32.54)
3632 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
3634 struct WS_protoent* retval = NULL;
3635 #ifdef HAVE_GETPROTOBYNUMBER
3636 struct protoent* proto;
3637 EnterCriticalSection( &csWSgetXXXbyYYY );
3638 if( (proto = getprotobynumber(number)) != NULL )
3640 retval = WS_dup_pe(proto);
3642 else {
3643 MESSAGE("protocol number %d not found; You might want to add "
3644 "this to /etc/protocols\n", number );
3645 SetLastError(WSANO_DATA);
3647 LeaveCriticalSection( &csWSgetXXXbyYYY );
3648 #endif
3649 TRACE("%i ret %p\n", number, retval);
3650 return retval;
3654 /***********************************************************************
3655 * getservbyname (WS2_32.55)
3657 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
3659 struct WS_servent* retval = NULL;
3660 struct servent* serv;
3661 char *name_str;
3662 char *proto_str = NULL;
3664 if (!(name_str = strdup_lower(name))) return NULL;
3666 if (proto && *proto)
3668 if (!(proto_str = strdup_lower(proto)))
3670 HeapFree( GetProcessHeap(), 0, name_str );
3671 return NULL;
3675 EnterCriticalSection( &csWSgetXXXbyYYY );
3676 serv = getservbyname(name_str, proto_str);
3677 if( serv != NULL )
3679 retval = WS_dup_se(serv);
3681 else SetLastError(WSANO_DATA);
3682 LeaveCriticalSection( &csWSgetXXXbyYYY );
3683 HeapFree( GetProcessHeap(), 0, proto_str );
3684 HeapFree( GetProcessHeap(), 0, name_str );
3685 TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
3686 return retval;
3689 /***********************************************************************
3690 * freeaddrinfo (WS2_32.@)
3692 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
3694 while (res) {
3695 struct WS_addrinfo *next;
3697 HeapFree(GetProcessHeap(),0,res->ai_canonname);
3698 HeapFree(GetProcessHeap(),0,res->ai_addr);
3699 next = res->ai_next;
3700 HeapFree(GetProcessHeap(),0,res);
3701 res = next;
3705 /* helper functions for getaddrinfo()/getnameinfo() */
3706 static int convert_aiflag_w2u(int winflags) {
3707 unsigned int i;
3708 int unixflags = 0;
3710 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
3711 if (ws_aiflag_map[i][0] & winflags) {
3712 unixflags |= ws_aiflag_map[i][1];
3713 winflags &= ~ws_aiflag_map[i][0];
3715 if (winflags)
3716 FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
3717 return unixflags;
3720 static int convert_niflag_w2u(int winflags) {
3721 unsigned int i;
3722 int unixflags = 0;
3724 for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
3725 if (ws_niflag_map[i][0] & winflags) {
3726 unixflags |= ws_niflag_map[i][1];
3727 winflags &= ~ws_niflag_map[i][0];
3729 if (winflags)
3730 FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
3731 return unixflags;
3734 static int convert_aiflag_u2w(int unixflags) {
3735 unsigned int i;
3736 int winflags = 0;
3738 for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
3739 if (ws_aiflag_map[i][1] & unixflags) {
3740 winflags |= ws_aiflag_map[i][0];
3741 unixflags &= ~ws_aiflag_map[i][1];
3743 if (unixflags) /* will warn usually */
3744 WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
3745 return winflags;
3748 static int convert_eai_u2w(int unixret) {
3749 int i;
3751 for (i=0;ws_eai_map[i][0];i++)
3752 if (ws_eai_map[i][1] == unixret)
3753 return ws_eai_map[i][0];
3754 return unixret;
3757 /***********************************************************************
3758 * getaddrinfo (WS2_32.@)
3760 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
3762 #ifdef HAVE_GETADDRINFO
3763 struct addrinfo *unixaires = NULL;
3764 int result;
3765 struct addrinfo unixhints, *punixhints = NULL;
3766 CHAR *node = NULL, *serv = NULL;
3768 if (nodename)
3769 if (!(node = strdup_lower(nodename))) return WSA_NOT_ENOUGH_MEMORY;
3771 if (servname) {
3772 if (!(serv = strdup_lower(servname))) {
3773 HeapFree(GetProcessHeap(), 0, node);
3774 return WSA_NOT_ENOUGH_MEMORY;
3778 if (hints) {
3779 punixhints = &unixhints;
3781 memset(&unixhints, 0, sizeof(unixhints));
3782 punixhints->ai_flags = convert_aiflag_w2u(hints->ai_flags);
3783 if (hints->ai_family == 0) /* wildcard, specific to getaddrinfo() */
3784 punixhints->ai_family = 0;
3785 else
3786 punixhints->ai_family = convert_af_w2u(hints->ai_family);
3787 if (hints->ai_socktype == 0) /* wildcard, specific to getaddrinfo() */
3788 punixhints->ai_socktype = 0;
3789 else
3790 punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
3791 if (hints->ai_protocol == 0) /* wildcard, specific to getaddrinfo() */
3792 punixhints->ai_protocol = 0;
3793 else
3794 punixhints->ai_protocol = convert_proto_w2u(hints->ai_protocol);
3797 /* getaddrinfo(3) is thread safe, no need to wrap in CS */
3798 result = getaddrinfo(nodename, servname, punixhints, &unixaires);
3800 TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
3802 HeapFree(GetProcessHeap(), 0, node);
3803 HeapFree(GetProcessHeap(), 0, serv);
3805 if (!result) {
3806 struct addrinfo *xuai = unixaires;
3807 struct WS_addrinfo **xai = res;
3809 *xai = NULL;
3810 while (xuai) {
3811 struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
3812 int len;
3814 if (!ai)
3815 goto outofmem;
3817 *xai = ai;xai = &ai->ai_next;
3818 ai->ai_flags = convert_aiflag_u2w(xuai->ai_flags);
3819 ai->ai_family = convert_af_u2w(xuai->ai_family);
3820 ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
3821 ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
3822 if (xuai->ai_canonname) {
3823 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
3824 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
3825 if (!ai->ai_canonname)
3826 goto outofmem;
3827 strcpy(ai->ai_canonname,xuai->ai_canonname);
3829 len = xuai->ai_addrlen;
3830 ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
3831 if (!ai->ai_addr)
3832 goto outofmem;
3833 ai->ai_addrlen = len;
3834 do {
3835 int winlen = ai->ai_addrlen;
3837 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
3838 ai->ai_addrlen = winlen;
3839 break;
3841 len = 2*len;
3842 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
3843 if (!ai->ai_addr)
3844 goto outofmem;
3845 ai->ai_addrlen = len;
3846 } while (1);
3847 xuai = xuai->ai_next;
3849 freeaddrinfo(unixaires);
3850 } else {
3851 result = convert_eai_u2w(result);
3852 *res = NULL;
3854 return result;
3856 outofmem:
3857 if (*res) WS_freeaddrinfo(*res);
3858 if (unixaires) freeaddrinfo(unixaires);
3859 *res = NULL;
3860 return WSA_NOT_ENOUGH_MEMORY;
3861 #else
3862 FIXME("getaddrinfo() failed, not found during buildtime.\n");
3863 return EAI_FAIL;
3864 #endif
3867 static struct WS_addrinfoW *addrinfo_AtoW(const struct WS_addrinfo *ai)
3869 struct WS_addrinfoW *ret;
3871 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfoW)))) return NULL;
3872 ret->ai_flags = ai->ai_flags;
3873 ret->ai_family = ai->ai_family;
3874 ret->ai_socktype = ai->ai_socktype;
3875 ret->ai_protocol = ai->ai_protocol;
3876 ret->ai_addrlen = ai->ai_addrlen;
3877 ret->ai_canonname = NULL;
3878 ret->ai_addr = NULL;
3879 ret->ai_next = NULL;
3880 if (ai->ai_canonname)
3882 int len = MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0);
3883 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
3885 HeapFree(GetProcessHeap(), 0, ret);
3886 return NULL;
3888 MultiByteToWideChar(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len);
3890 if (ai->ai_addr)
3892 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
3894 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
3895 HeapFree(GetProcessHeap(), 0, ret);
3896 return NULL;
3898 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
3900 return ret;
3903 static struct WS_addrinfoW *addrinfo_list_AtoW(const struct WS_addrinfo *info)
3905 struct WS_addrinfoW *ret, *infoW;
3907 if (!(ret = infoW = addrinfo_AtoW(info))) return NULL;
3908 while (info->ai_next)
3910 if (!(infoW->ai_next = addrinfo_AtoW(info->ai_next)))
3912 FreeAddrInfoW(ret);
3913 return NULL;
3915 infoW = infoW->ai_next;
3916 info = info->ai_next;
3918 return ret;
3921 static struct WS_addrinfo *addrinfo_WtoA(const struct WS_addrinfoW *ai)
3923 struct WS_addrinfo *ret;
3925 if (!(ret = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_addrinfo)))) return NULL;
3926 ret->ai_flags = ai->ai_flags;
3927 ret->ai_family = ai->ai_family;
3928 ret->ai_socktype = ai->ai_socktype;
3929 ret->ai_protocol = ai->ai_protocol;
3930 ret->ai_addrlen = ai->ai_addrlen;
3931 ret->ai_canonname = NULL;
3932 ret->ai_addr = NULL;
3933 ret->ai_next = NULL;
3934 if (ai->ai_canonname)
3936 int len = WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, NULL, 0, NULL, NULL);
3937 if (!(ret->ai_canonname = HeapAlloc(GetProcessHeap(), 0, len)))
3939 HeapFree(GetProcessHeap(), 0, ret);
3940 return NULL;
3942 WideCharToMultiByte(CP_ACP, 0, ai->ai_canonname, -1, ret->ai_canonname, len, NULL, NULL);
3944 if (ai->ai_addr)
3946 if (!(ret->ai_addr = HeapAlloc(GetProcessHeap(), 0, sizeof(struct WS_sockaddr))))
3948 HeapFree(GetProcessHeap(), 0, ret->ai_canonname);
3949 HeapFree(GetProcessHeap(), 0, ret);
3950 return NULL;
3952 memcpy(ret->ai_addr, ai->ai_addr, sizeof(struct WS_sockaddr));
3954 return ret;
3957 /***********************************************************************
3958 * GetAddrInfoW (WS2_32.@)
3960 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
3962 int ret, len;
3963 char *nodenameA, *servnameA = NULL;
3964 struct WS_addrinfo *resA, *hintsA = NULL;
3966 if (!nodename) return WSAHOST_NOT_FOUND;
3968 len = WideCharToMultiByte(CP_ACP, 0, nodename, -1, NULL, 0, NULL, NULL);
3969 if (!(nodenameA = HeapAlloc(GetProcessHeap(), 0, len))) return EAI_MEMORY;
3970 WideCharToMultiByte(CP_ACP, 0, nodename, -1, nodenameA, len, NULL, NULL);
3972 if (servname)
3974 len = WideCharToMultiByte(CP_ACP, 0, servname, -1, NULL, 0, NULL, NULL);
3975 if (!(servnameA = HeapAlloc(GetProcessHeap(), 0, len)))
3977 HeapFree(GetProcessHeap(), 0, nodenameA);
3978 return EAI_MEMORY;
3980 WideCharToMultiByte(CP_ACP, 0, servname, -1, servnameA, len, NULL, NULL);
3983 if (hints) hintsA = addrinfo_WtoA(hints);
3984 ret = WS_getaddrinfo(nodenameA, servnameA, hintsA, &resA);
3985 WS_freeaddrinfo(hintsA);
3987 if (!ret)
3989 *res = addrinfo_list_AtoW(resA);
3990 WS_freeaddrinfo(resA);
3993 HeapFree(GetProcessHeap(), 0, nodenameA);
3994 HeapFree(GetProcessHeap(), 0, servnameA);
3995 return ret;
3998 /***********************************************************************
3999 * FreeAddrInfoW (WS2_32.@)
4001 void WINAPI FreeAddrInfoW(PADDRINFOW ai)
4003 while (ai)
4005 ADDRINFOW *next;
4006 HeapFree(GetProcessHeap(), 0, ai->ai_canonname);
4007 HeapFree(GetProcessHeap(), 0, ai->ai_addr);
4008 next = ai->ai_next;
4009 HeapFree(GetProcessHeap(), 0, ai);
4010 ai = next;
4014 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
4015 DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
4017 #ifdef HAVE_GETNAMEINFO
4018 int ret;
4019 union generic_unix_sockaddr sa_u;
4020 unsigned int size;
4022 TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
4023 serv, servlen, flags);
4025 size = ws_sockaddr_ws2u(sa, salen, &sa_u);
4026 if (!size)
4028 WSASetLastError(WSAEFAULT);
4029 return WSA_NOT_ENOUGH_MEMORY;
4031 ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
4032 return convert_eai_u2w(ret);
4033 #else
4034 FIXME("getnameinfo() failed, not found during buildtime.\n");
4035 return EAI_FAIL;
4036 #endif
4039 /***********************************************************************
4040 * getservbyport (WS2_32.56)
4042 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
4044 struct WS_servent* retval = NULL;
4045 #ifdef HAVE_GETSERVBYPORT
4046 struct servent* serv;
4047 char *proto_str = NULL;
4049 if (proto && *proto)
4051 if (!(proto_str = strdup_lower(proto))) return NULL;
4053 EnterCriticalSection( &csWSgetXXXbyYYY );
4054 if( (serv = getservbyport(port, proto_str)) != NULL ) {
4055 retval = WS_dup_se(serv);
4057 else SetLastError(WSANO_DATA);
4058 LeaveCriticalSection( &csWSgetXXXbyYYY );
4059 HeapFree( GetProcessHeap(), 0, proto_str );
4060 #endif
4061 TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
4062 return retval;
4066 /***********************************************************************
4067 * gethostname (WS2_32.57)
4069 int WINAPI WS_gethostname(char *name, int namelen)
4071 TRACE("name %p, len %d\n", name, namelen);
4073 if (gethostname(name, namelen) == 0)
4075 TRACE("<- '%s'\n", name);
4076 return 0;
4078 SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
4079 TRACE("<- ERROR !\n");
4080 return SOCKET_ERROR;
4084 /* ------------------------------------- Windows sockets extensions -- *
4086 * ------------------------------------------------------------------- */
4088 /***********************************************************************
4089 * WSAEnumNetworkEvents (WS2_32.36)
4091 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
4093 int ret;
4095 TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
4097 SERVER_START_REQ( get_socket_event )
4099 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
4100 req->service = TRUE;
4101 req->c_event = wine_server_obj_handle( hEvent );
4102 wine_server_set_reply( req, lpEvent->iErrorCode, sizeof(lpEvent->iErrorCode) );
4103 if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
4105 SERVER_END_REQ;
4106 if (!ret) return 0;
4107 SetLastError(WSAEINVAL);
4108 return SOCKET_ERROR;
4111 /***********************************************************************
4112 * WSAEventSelect (WS2_32.39)
4114 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
4116 int ret;
4118 TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
4120 SERVER_START_REQ( set_socket_event )
4122 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
4123 req->mask = lEvent;
4124 req->event = wine_server_obj_handle( hEvent );
4125 req->window = 0;
4126 req->msg = 0;
4127 ret = wine_server_call( req );
4129 SERVER_END_REQ;
4130 if (!ret) return 0;
4131 SetLastError(WSAEINVAL);
4132 return SOCKET_ERROR;
4135 /**********************************************************************
4136 * WSAGetOverlappedResult (WS2_32.40)
4138 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
4139 LPDWORD lpcbTransfer, BOOL fWait,
4140 LPDWORD lpdwFlags )
4142 NTSTATUS status;
4144 TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
4145 s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
4147 if ( lpOverlapped == NULL )
4149 ERR( "Invalid pointer\n" );
4150 WSASetLastError(WSA_INVALID_PARAMETER);
4151 return FALSE;
4154 status = lpOverlapped->Internal;
4155 if (status == STATUS_PENDING)
4157 if (!fWait)
4159 SetLastError( WSA_IO_INCOMPLETE );
4160 return FALSE;
4163 if (WaitForSingleObject( lpOverlapped->hEvent ? lpOverlapped->hEvent : SOCKET2HANDLE(s),
4164 INFINITE ) == WAIT_FAILED)
4165 return FALSE;
4166 status = lpOverlapped->Internal;
4169 if ( lpcbTransfer )
4170 *lpcbTransfer = lpOverlapped->InternalHigh;
4172 if ( lpdwFlags )
4173 *lpdwFlags = lpOverlapped->u.s.Offset;
4175 if (status) SetLastError( RtlNtStatusToDosError(status) );
4176 return !status;
4180 /***********************************************************************
4181 * WSAAsyncSelect (WS2_32.101)
4183 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
4185 int ret;
4187 TRACE("%lx, hWnd %p, uMsg %08x, event %08x\n", s, hWnd, uMsg, lEvent);
4189 SERVER_START_REQ( set_socket_event )
4191 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
4192 req->mask = lEvent;
4193 req->event = 0;
4194 req->window = wine_server_user_handle( hWnd );
4195 req->msg = uMsg;
4196 ret = wine_server_call( req );
4198 SERVER_END_REQ;
4199 if (!ret) return 0;
4200 SetLastError(WSAEINVAL);
4201 return SOCKET_ERROR;
4204 /***********************************************************************
4205 * WSACreateEvent (WS2_32.31)
4208 WSAEVENT WINAPI WSACreateEvent(void)
4210 /* Create a manual-reset event, with initial state: unsignaled */
4211 TRACE("\n");
4213 return CreateEventW(NULL, TRUE, FALSE, NULL);
4216 /***********************************************************************
4217 * WSACloseEvent (WS2_32.29)
4220 BOOL WINAPI WSACloseEvent(WSAEVENT event)
4222 TRACE ("event=%p\n", event);
4224 return CloseHandle(event);
4227 /***********************************************************************
4228 * WSASocketA (WS2_32.78)
4231 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
4232 LPWSAPROTOCOL_INFOA lpProtocolInfo,
4233 GROUP g, DWORD dwFlags)
4235 INT len;
4236 WSAPROTOCOL_INFOW info;
4238 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
4239 af, type, protocol, lpProtocolInfo, g, dwFlags);
4241 if (!lpProtocolInfo) return WSASocketW(af, type, protocol, NULL, g, dwFlags);
4243 memcpy(&info, lpProtocolInfo, FIELD_OFFSET(WSAPROTOCOL_INFOW, szProtocol));
4244 len = MultiByteToWideChar(CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
4245 info.szProtocol, WSAPROTOCOL_LEN + 1);
4247 if (!len)
4249 WSASetLastError( WSAEINVAL);
4250 return SOCKET_ERROR;
4253 return WSASocketW(af, type, protocol, &info, g, dwFlags);
4256 /***********************************************************************
4257 * WSASocketW (WS2_32.79)
4260 SOCKET WINAPI WSASocketW(int af, int type, int protocol,
4261 LPWSAPROTOCOL_INFOW lpProtocolInfo,
4262 GROUP g, DWORD dwFlags)
4264 SOCKET ret;
4267 FIXME: The "advanced" parameters of WSASocketW (lpProtocolInfo,
4268 g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
4271 TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%x\n",
4272 af, type, protocol, lpProtocolInfo, g, dwFlags );
4274 /* hack for WSADuplicateSocket */
4275 if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
4276 ret = lpProtocolInfo->dwCatalogEntryId;
4277 TRACE("\tgot duplicate %04lx\n", ret);
4278 return ret;
4281 /* convert the socket family and type */
4282 af = convert_af_w2u(af);
4283 type = convert_socktype_w2u(type);
4285 if (lpProtocolInfo)
4287 if (af == FROM_PROTOCOL_INFO)
4288 af = lpProtocolInfo->iAddressFamily;
4289 if (type == FROM_PROTOCOL_INFO)
4290 type = lpProtocolInfo->iSocketType;
4291 if (protocol == FROM_PROTOCOL_INFO)
4292 protocol = lpProtocolInfo->iProtocol;
4295 if ( af == AF_UNSPEC) /* did they not specify the address family? */
4296 switch(protocol)
4298 case IPPROTO_TCP:
4299 if (type == SOCK_STREAM) { af = AF_INET; break; }
4300 case IPPROTO_UDP:
4301 if (type == SOCK_DGRAM) { af = AF_INET; break; }
4302 default: SetLastError(WSAEPROTOTYPE); return INVALID_SOCKET;
4305 SERVER_START_REQ( create_socket )
4307 req->family = af;
4308 req->type = type;
4309 req->protocol = protocol;
4310 req->access = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
4311 req->attributes = OBJ_INHERIT;
4312 req->flags = dwFlags;
4313 set_error( wine_server_call( req ) );
4314 ret = HANDLE2SOCKET( wine_server_ptr_handle( reply->handle ));
4316 SERVER_END_REQ;
4317 if (ret)
4319 TRACE("\tcreated %04lx\n", ret );
4320 return ret;
4323 if (GetLastError() == WSAEACCES) /* raw socket denied */
4325 if (type == SOCK_RAW)
4326 ERR_(winediag)("Failed to create a socket of type SOCK_RAW, this requires special permissions.\n");
4327 else
4328 ERR_(winediag)("Failed to create socket, this requires special permissions.\n");
4329 SetLastError(WSAESOCKTNOSUPPORT);
4332 WARN("\t\tfailed!\n");
4333 return INVALID_SOCKET;
4336 /***********************************************************************
4337 * WSAJoinLeaf (WS2_32.58)
4340 SOCKET WINAPI WSAJoinLeaf(
4341 SOCKET s,
4342 const struct WS_sockaddr *addr,
4343 int addrlen,
4344 LPWSABUF lpCallerData,
4345 LPWSABUF lpCalleeData,
4346 LPQOS lpSQOS,
4347 LPQOS lpGQOS,
4348 DWORD dwFlags)
4350 FIXME("stub.\n");
4351 return INVALID_SOCKET;
4354 /***********************************************************************
4355 * __WSAFDIsSet (WS2_32.151)
4357 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
4359 int i = set->fd_count;
4361 TRACE("(%ld,%p(%i))\n", s, set, i);
4363 while (i--)
4364 if (set->fd_array[i] == s) return 1;
4365 return 0;
4368 /***********************************************************************
4369 * WSAIsBlocking (WS2_32.114)
4371 BOOL WINAPI WSAIsBlocking(void)
4373 /* By default WinSock should set all its sockets to non-blocking mode
4374 * and poll in PeekMessage loop when processing "blocking" ones. This
4375 * function is supposed to tell if the program is in this loop. Our
4376 * blocking calls are truly blocking so we always return FALSE.
4378 * Note: It is allowed to call this function without prior WSAStartup().
4381 TRACE("\n");
4382 return FALSE;
4385 /***********************************************************************
4386 * WSACancelBlockingCall (WS2_32.113)
4388 INT WINAPI WSACancelBlockingCall(void)
4390 TRACE("\n");
4391 return 0;
4394 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x )
4396 FIXME("How was this called?\n");
4397 return x();
4401 /***********************************************************************
4402 * WSASetBlockingHook (WS2_32.109)
4404 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
4406 FARPROC prev = blocking_hook;
4407 blocking_hook = lpBlockFunc;
4408 TRACE("hook %p\n", lpBlockFunc);
4409 return prev;
4413 /***********************************************************************
4414 * WSAUnhookBlockingHook (WS2_32.110)
4416 INT WINAPI WSAUnhookBlockingHook(void)
4418 blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
4419 return 0;
4423 /* ----------------------------------- end of API stuff */
4425 /* ----------------------------------- helper functions -
4427 * TODO: Merge WS_dup_..() stuff into one function that
4428 * would operate with a generic structure containing internal
4429 * pointers (via a template of some kind).
4432 static int list_size(char** l, int item_size)
4434 int i,j = 0;
4435 if(l)
4436 { for(i=0;l[i];i++)
4437 j += (item_size) ? item_size : strlen(l[i]) + 1;
4438 j += (i + 1) * sizeof(char*); }
4439 return j;
4442 static int list_dup(char** l_src, char** l_to, int item_size)
4444 char *p;
4445 int i;
4447 for (i = 0; l_src[i]; i++) ;
4448 p = (char *)(l_to + i + 1);
4449 for (i = 0; l_src[i]; i++)
4451 int count = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
4452 memcpy(p, l_src[i], count);
4453 l_to[i] = p;
4454 p += count;
4456 l_to[i] = NULL;
4457 return p - (char *)l_to;
4460 /* ----- hostent */
4462 /* duplicate hostent entry
4463 * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
4464 * Ditto for protoent and servent.
4466 static struct WS_hostent *WS_dup_he(const struct hostent* p_he)
4468 char *p;
4469 struct WS_hostent *p_to;
4471 int size = (sizeof(*p_he) +
4472 strlen(p_he->h_name) + 1 +
4473 list_size(p_he->h_aliases, 0) +
4474 list_size(p_he->h_addr_list, p_he->h_length));
4476 if (!(p_to = check_buffer_he(size))) return NULL;
4477 p_to->h_addrtype = p_he->h_addrtype;
4478 p_to->h_length = p_he->h_length;
4480 p = (char *)(p_to + 1);
4481 p_to->h_name = p;
4482 strcpy(p, p_he->h_name);
4483 p += strlen(p) + 1;
4485 p_to->h_aliases = (char **)p;
4486 p += list_dup(p_he->h_aliases, p_to->h_aliases, 0);
4488 p_to->h_addr_list = (char **)p;
4489 list_dup(p_he->h_addr_list, p_to->h_addr_list, p_he->h_length);
4490 return p_to;
4493 /* ----- protoent */
4495 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe)
4497 char *p;
4498 struct WS_protoent *p_to;
4500 int size = (sizeof(*p_pe) +
4501 strlen(p_pe->p_name) + 1 +
4502 list_size(p_pe->p_aliases, 0));
4504 if (!(p_to = check_buffer_pe(size))) return NULL;
4505 p_to->p_proto = p_pe->p_proto;
4507 p = (char *)(p_to + 1);
4508 p_to->p_name = p;
4509 strcpy(p, p_pe->p_name);
4510 p += strlen(p) + 1;
4512 p_to->p_aliases = (char **)p;
4513 list_dup(p_pe->p_aliases, p_to->p_aliases, 0);
4514 return p_to;
4517 /* ----- servent */
4519 static struct WS_servent *WS_dup_se(const struct servent* p_se)
4521 char *p;
4522 struct WS_servent *p_to;
4524 int size = (sizeof(*p_se) +
4525 strlen(p_se->s_proto) + 1 +
4526 strlen(p_se->s_name) + 1 +
4527 list_size(p_se->s_aliases, 0));
4529 if (!(p_to = check_buffer_se(size))) return NULL;
4530 p_to->s_port = p_se->s_port;
4532 p = (char *)(p_to + 1);
4533 p_to->s_name = p;
4534 strcpy(p, p_se->s_name);
4535 p += strlen(p) + 1;
4537 p_to->s_proto = p;
4538 strcpy(p, p_se->s_proto);
4539 p += strlen(p) + 1;
4541 p_to->s_aliases = (char **)p;
4542 list_dup(p_se->s_aliases, p_to->s_aliases, 0);
4543 return p_to;
4547 /***********************************************************************
4548 * WSARecv (WS2_32.67)
4550 int WINAPI WSARecv(SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4551 LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
4552 LPWSAOVERLAPPED lpOverlapped,
4553 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
4555 return WSARecvFrom(s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
4556 NULL, NULL, lpOverlapped, lpCompletionRoutine);
4559 /***********************************************************************
4560 * WSARecvFrom (WS2_32.69)
4562 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
4563 LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
4564 LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
4565 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
4568 unsigned int i, options;
4569 int n, fd, err;
4570 struct ws2_async *wsa;
4571 DWORD timeout_start = GetTickCount();
4572 ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
4574 TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, from %p, fromlen %d, ovl %p, func %p\n",
4575 s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
4576 (lpFromlen ? *lpFromlen : -1),
4577 lpOverlapped, lpCompletionRoutine);
4579 fd = get_sock_fd( s, FILE_READ_DATA, &options );
4580 TRACE( "fd=%d, options=%x\n", fd, options );
4582 if (fd == -1) return SOCKET_ERROR;
4584 if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
4586 err = WSAEFAULT;
4587 goto error;
4590 wsa->hSocket = SOCKET2HANDLE(s);
4591 wsa->flags = *lpFlags;
4592 wsa->addr = lpFrom;
4593 wsa->addrlen.ptr = lpFromlen;
4594 wsa->n_iovecs = dwBufferCount;
4595 wsa->first_iovec = 0;
4596 for (i = 0; i < dwBufferCount; i++)
4598 /* check buffer first to trigger write watches */
4599 if (IsBadWritePtr( lpBuffers[i].buf, lpBuffers[i].len ))
4601 err = WSAEFAULT;
4602 goto error;
4604 wsa->iovec[i].iov_base = lpBuffers[i].buf;
4605 wsa->iovec[i].iov_len = lpBuffers[i].len;
4608 for (;;)
4610 n = WS2_recv( fd, wsa );
4611 if (n == -1)
4613 if (errno == EINTR) continue;
4614 if (errno != EAGAIN)
4616 err = wsaErrno();
4617 if (cvalue) WS_AddCompletion( s, cvalue, err, 0 );
4618 goto error;
4621 else
4622 *lpNumberOfBytesRecvd = n;
4624 if ((lpOverlapped || lpCompletionRoutine) &&
4625 !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
4627 IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
4629 wsa->user_overlapped = lpOverlapped;
4630 wsa->completion_func = lpCompletionRoutine;
4631 release_sock_fd( s, fd );
4633 if (n == -1)
4635 iosb->u.Status = STATUS_PENDING;
4636 iosb->Information = 0;
4638 SERVER_START_REQ( register_async )
4640 req->type = ASYNC_TYPE_READ;
4641 req->async.handle = wine_server_obj_handle( wsa->hSocket );
4642 req->async.callback = wine_server_client_ptr( WS2_async_recv );
4643 req->async.iosb = wine_server_client_ptr( iosb );
4644 req->async.arg = wine_server_client_ptr( wsa );
4645 req->async.event = wine_server_obj_handle( lpCompletionRoutine ? 0 : lpOverlapped->hEvent );
4646 req->async.cvalue = cvalue;
4647 err = wine_server_call( req );
4649 SERVER_END_REQ;
4651 if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
4652 WSASetLastError( NtStatusToWSAError( err ));
4653 return SOCKET_ERROR;
4656 iosb->u.Status = STATUS_SUCCESS;
4657 iosb->Information = n;
4658 if (!wsa->completion_func)
4660 if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
4661 if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
4662 HeapFree( GetProcessHeap(), 0, wsa );
4664 else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
4665 (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
4666 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4667 return 0;
4670 if (n != -1) break;
4672 if ( _is_blocking(s) )
4674 struct pollfd pfd;
4675 int timeout = GET_RCVTIMEO(fd);
4676 if (timeout != -1)
4678 timeout -= GetTickCount() - timeout_start;
4679 if (timeout < 0) timeout = 0;
4682 pfd.fd = fd;
4683 pfd.events = POLLIN;
4684 if (*lpFlags & WS_MSG_OOB) pfd.events |= POLLPRI;
4686 if (!timeout || !poll( &pfd, 1, timeout ))
4688 err = WSAETIMEDOUT;
4689 /* a timeout is not fatal */
4690 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4691 goto error;
4694 else
4696 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4697 err = WSAEWOULDBLOCK;
4698 goto error;
4702 TRACE(" -> %i bytes\n", n);
4703 HeapFree( GetProcessHeap(), 0, wsa );
4704 release_sock_fd( s, fd );
4705 _enable_event(SOCKET2HANDLE(s), FD_READ, 0, 0);
4707 return 0;
4709 error:
4710 HeapFree( GetProcessHeap(), 0, wsa );
4711 release_sock_fd( s, fd );
4712 WARN(" -> ERROR %d\n", err);
4713 WSASetLastError( err );
4714 return SOCKET_ERROR;
4717 /***********************************************************************
4718 * WSCInstallProvider (WS2_32.88)
4720 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
4721 LPCWSTR lpszProviderDllPath,
4722 const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
4723 DWORD dwNumberOfEntries,
4724 LPINT lpErrno )
4726 FIXME("(%s, %s, %p, %d, %p): stub !\n", debugstr_guid(lpProviderId),
4727 debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
4728 dwNumberOfEntries, lpErrno);
4729 *lpErrno = 0;
4730 return 0;
4734 /***********************************************************************
4735 * WSCDeinstallProvider (WS2_32.83)
4737 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
4739 FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
4740 *lpErrno = 0;
4741 return 0;
4745 /***********************************************************************
4746 * WSAAccept (WS2_32.26)
4748 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
4749 LPCONDITIONPROC lpfnCondition, DWORD dwCallbackData)
4752 int ret = 0, size = 0;
4753 WSABUF CallerId, CallerData, CalleeId, CalleeData;
4754 /* QOS SQOS, GQOS; */
4755 GROUP g;
4756 SOCKET cs;
4757 SOCKADDR src_addr, dst_addr;
4759 TRACE("Socket %04lx, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %d\n",
4760 s, addr, addrlen, lpfnCondition, dwCallbackData);
4763 size = sizeof(src_addr);
4764 cs = WS_accept(s, &src_addr, &size);
4766 if (cs == SOCKET_ERROR) return SOCKET_ERROR;
4768 if (!lpfnCondition) return cs;
4770 CallerId.buf = (char *)&src_addr;
4771 CallerId.len = sizeof(src_addr);
4773 CallerData.buf = NULL;
4774 CallerData.len = 0;
4776 WS_getsockname(cs, &dst_addr, &size);
4778 CalleeId.buf = (char *)&dst_addr;
4779 CalleeId.len = sizeof(dst_addr);
4782 ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
4783 &CalleeId, &CalleeData, &g, dwCallbackData);
4785 switch (ret)
4787 case CF_ACCEPT:
4788 if (addr && addrlen)
4789 addr = memcpy(addr, &src_addr, (*addrlen > size) ? size : *addrlen );
4790 return cs;
4791 case CF_DEFER:
4792 SERVER_START_REQ( set_socket_deferred )
4794 req->handle = wine_server_obj_handle( SOCKET2HANDLE(s) );
4795 req->deferred = wine_server_obj_handle( SOCKET2HANDLE(cs) );
4796 if ( !wine_server_call_err ( req ) )
4798 SetLastError( WSATRY_AGAIN );
4799 WS_closesocket( cs );
4802 SERVER_END_REQ;
4803 return SOCKET_ERROR;
4804 case CF_REJECT:
4805 WS_closesocket(cs);
4806 SetLastError(WSAECONNREFUSED);
4807 return SOCKET_ERROR;
4808 default:
4809 FIXME("Unknown return type from Condition function\n");
4810 SetLastError(WSAENOTSOCK);
4811 return SOCKET_ERROR;
4815 /***********************************************************************
4816 * WSADuplicateSocketA (WS2_32.32)
4818 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
4820 HANDLE hProcess;
4822 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
4823 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
4824 /* FIXME: WS_getsockopt(s, WS_SOL_SOCKET, SO_PROTOCOL_INFO, lpProtocolInfo, sizeof(*lpProtocolInfo)); */
4825 /* I don't know what the real Windoze does next, this is a hack */
4826 /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
4827 * the target use the global duplicate, or we could copy a reference to us to the structure
4828 * and let the target duplicate it from us, but let's do it as simple as possible */
4829 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
4830 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
4831 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
4832 0, FALSE, DUPLICATE_SAME_ACCESS);
4833 CloseHandle(hProcess);
4834 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
4835 return 0;
4838 /***********************************************************************
4839 * WSADuplicateSocketW (WS2_32.33)
4841 int WINAPI WSADuplicateSocketW( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOW lpProtocolInfo )
4843 HANDLE hProcess;
4845 TRACE("(%ld,%x,%p)\n", s, dwProcessId, lpProtocolInfo);
4847 memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
4848 hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
4849 DuplicateHandle(GetCurrentProcess(), SOCKET2HANDLE(s),
4850 hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
4851 0, FALSE, DUPLICATE_SAME_ACCESS);
4852 CloseHandle(hProcess);
4853 lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
4854 return 0;
4857 /***********************************************************************
4858 * WSAInstallServiceClassA (WS2_32.48)
4860 int WINAPI WSAInstallServiceClassA(LPWSASERVICECLASSINFOA info)
4862 FIXME("Request to install service %s\n",debugstr_a(info->lpszServiceClassName));
4863 WSASetLastError(WSAEACCES);
4864 return SOCKET_ERROR;
4867 /***********************************************************************
4868 * WSAInstallServiceClassW (WS2_32.49)
4870 int WINAPI WSAInstallServiceClassW(LPWSASERVICECLASSINFOW info)
4872 FIXME("Request to install service %s\n",debugstr_w(info->lpszServiceClassName));
4873 WSASetLastError(WSAEACCES);
4874 return SOCKET_ERROR;
4877 /***********************************************************************
4878 * WSARemoveServiceClass (WS2_32.70)
4880 int WINAPI WSARemoveServiceClass(LPGUID info)
4882 FIXME("Request to remove service %p\n",info);
4883 WSASetLastError(WSATYPE_NOT_FOUND);
4884 return SOCKET_ERROR;
4887 /***********************************************************************
4888 * inet_ntop (WS2_32.@)
4890 PCSTR WINAPI WS_inet_ntop( INT family, PVOID addr, PSTR buffer, SIZE_T len )
4892 #ifdef HAVE_INET_NTOP
4893 struct WS_in6_addr *in6;
4894 struct WS_in_addr *in;
4895 PCSTR pdst;
4897 TRACE("family %d, addr (%p), buffer (%p), len %ld\n", family, addr, buffer, len);
4898 if (!buffer)
4900 WSASetLastError( STATUS_INVALID_PARAMETER );
4901 return NULL;
4904 switch (family)
4906 case WS_AF_INET:
4908 in = addr;
4909 pdst = inet_ntop( AF_INET, &in->WS_s_addr, buffer, len );
4910 break;
4912 case WS_AF_INET6:
4914 in6 = addr;
4915 pdst = inet_ntop( AF_INET6, in6->WS_s6_addr, buffer, len );
4916 break;
4918 default:
4919 WSASetLastError( WSAEAFNOSUPPORT );
4920 return NULL;
4923 if (!pdst) WSASetLastError( STATUS_INVALID_PARAMETER );
4924 return pdst;
4925 #else
4926 FIXME( "not supported on this platform\n" );
4927 WSASetLastError( WSAEAFNOSUPPORT );
4928 return NULL;
4929 #endif
4932 /***********************************************************************
4933 * WSAStringToAddressA (WS2_32.80)
4935 INT WINAPI WSAStringToAddressA(LPSTR AddressString,
4936 INT AddressFamily,
4937 LPWSAPROTOCOL_INFOA lpProtocolInfo,
4938 LPSOCKADDR lpAddress,
4939 LPINT lpAddressLength)
4941 INT res=0;
4942 LPSTR workBuffer=NULL,ptrPort;
4944 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_a(AddressString), AddressFamily,
4945 lpProtocolInfo, lpAddress, lpAddressLength );
4947 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
4949 if (!AddressString)
4951 WSASetLastError(WSAEINVAL);
4952 return SOCKET_ERROR;
4955 if (lpProtocolInfo)
4956 FIXME("ProtocolInfo not implemented.\n");
4958 workBuffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
4959 strlen(AddressString) + 1);
4960 if (!workBuffer)
4962 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
4963 return SOCKET_ERROR;
4966 strcpy(workBuffer, AddressString);
4968 switch(AddressFamily)
4970 case WS_AF_INET:
4972 struct in_addr inetaddr;
4974 /* If lpAddressLength is too small, tell caller the size we need */
4975 if (*lpAddressLength < sizeof(SOCKADDR_IN))
4977 *lpAddressLength = sizeof(SOCKADDR_IN);
4978 res = WSAEFAULT;
4979 break;
4981 memset(lpAddress, 0, sizeof(SOCKADDR_IN));
4983 ((LPSOCKADDR_IN)lpAddress)->sin_family = AF_INET;
4985 ptrPort = strchr(workBuffer, ':');
4986 if(ptrPort)
4988 ((LPSOCKADDR_IN)lpAddress)->sin_port = htons(atoi(ptrPort+1));
4989 *ptrPort = '\0';
4991 else
4993 ((LPSOCKADDR_IN)lpAddress)->sin_port = 0;
4996 if(inet_aton(workBuffer, &inetaddr) > 0)
4998 ((LPSOCKADDR_IN)lpAddress)->sin_addr.WS_s_addr = inetaddr.s_addr;
4999 res = 0;
5001 else
5002 res = WSAEINVAL;
5004 break;
5007 case WS_AF_INET6:
5009 struct in6_addr inetaddr;
5010 /* If lpAddressLength is too small, tell caller the size we need */
5011 if (*lpAddressLength < sizeof(SOCKADDR_IN6))
5013 *lpAddressLength = sizeof(SOCKADDR_IN6);
5014 res = WSAEFAULT;
5015 break;
5017 #ifdef HAVE_INET_PTON
5018 memset(lpAddress, 0, sizeof(SOCKADDR_IN6));
5020 ((LPSOCKADDR_IN6)lpAddress)->sin6_family = WS_AF_INET6;
5022 /* This one is a bit tricky. An IPv6 address contains colons, so the
5023 * check from IPv4 doesn't work like that. However, IPv6 addresses that
5024 * contain a port are written with braces like [fd12:3456:7890::1]:12345
5025 * so what we will do is to look for ']', check if the next char is a
5026 * colon, and if it is, parse the port as in IPv4. */
5028 ptrPort = strchr(workBuffer, ']');
5029 if(ptrPort && *(++ptrPort) == ':')
5031 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = htons(atoi(ptrPort+1));
5032 *ptrPort = '\0';
5034 else
5036 ((LPSOCKADDR_IN6)lpAddress)->sin6_port = 0;
5039 if(inet_pton(AF_INET6, workBuffer, &inetaddr) > 0)
5041 memcpy(&((LPSOCKADDR_IN6)lpAddress)->sin6_addr, &inetaddr,
5042 sizeof(struct in6_addr));
5043 res = 0;
5045 else
5046 #endif /* HAVE_INET_PTON */
5047 res = WSAEINVAL;
5049 break;
5051 default:
5052 /* According to MSDN, only AF_INET and AF_INET6 are supported. */
5053 TRACE("Unsupported address family specified: %d.\n", AddressFamily);
5054 res = WSAEINVAL;
5057 HeapFree(GetProcessHeap(), 0, workBuffer);
5059 if (!res) return 0;
5060 WSASetLastError(res);
5061 return SOCKET_ERROR;
5064 /***********************************************************************
5065 * WSAStringToAddressW (WS2_32.81)
5067 * Does anybody know if this functions allows to use hebrew/arabic/chinese... digits?
5068 * If this should be the case, it would be required to map these digits
5069 * to Unicode digits (0-9) using FoldString first.
5071 INT WINAPI WSAStringToAddressW(LPWSTR AddressString,
5072 INT AddressFamily,
5073 LPWSAPROTOCOL_INFOW lpProtocolInfo,
5074 LPSOCKADDR lpAddress,
5075 LPINT lpAddressLength)
5077 INT sBuffer,res=0;
5078 LPSTR workBuffer=NULL;
5079 WSAPROTOCOL_INFOA infoA;
5080 LPWSAPROTOCOL_INFOA lpProtoInfoA = NULL;
5082 TRACE( "(%s, %x, %p, %p, %p)\n", debugstr_w(AddressString), AddressFamily, lpProtocolInfo,
5083 lpAddress, lpAddressLength );
5085 if (!lpAddressLength || !lpAddress) return SOCKET_ERROR;
5087 /* if ProtocolInfo is available - convert to ANSI variant */
5088 if (lpProtocolInfo)
5090 lpProtoInfoA = &infoA;
5091 memcpy( lpProtoInfoA, lpProtocolInfo, FIELD_OFFSET( WSAPROTOCOL_INFOA, szProtocol ) );
5093 if (!WideCharToMultiByte( CP_ACP, 0, lpProtocolInfo->szProtocol, -1,
5094 lpProtoInfoA->szProtocol, WSAPROTOCOL_LEN+1, NULL, NULL ))
5096 WSASetLastError( WSAEINVAL);
5097 return SOCKET_ERROR;
5101 if (AddressString)
5103 /* Translate AddressString to ANSI code page - assumes that only
5104 standard digits 0-9 are used with this API call */
5105 sBuffer = WideCharToMultiByte( CP_ACP, 0, AddressString, -1, NULL, 0, NULL, NULL );
5106 workBuffer = HeapAlloc( GetProcessHeap(), 0, sBuffer );
5108 if (workBuffer)
5110 WideCharToMultiByte( CP_ACP, 0, AddressString, -1, workBuffer, sBuffer, NULL, NULL );
5111 res = WSAStringToAddressA(workBuffer,AddressFamily,lpProtoInfoA,
5112 lpAddress,lpAddressLength);
5113 HeapFree( GetProcessHeap(), 0, workBuffer );
5114 return res;
5116 else
5117 res = WSA_NOT_ENOUGH_MEMORY;
5119 else
5120 res = WSAEINVAL;
5122 WSASetLastError(res);
5123 return SOCKET_ERROR;
5126 /***********************************************************************
5127 * WSAAddressToStringA (WS2_32.27)
5129 * See WSAAddressToStringW
5131 INT WINAPI WSAAddressToStringA( LPSOCKADDR sockaddr, DWORD len,
5132 LPWSAPROTOCOL_INFOA info, LPSTR string,
5133 LPDWORD lenstr )
5135 DWORD size;
5136 CHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
5137 CHAR *p;
5139 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
5141 if (!sockaddr) return SOCKET_ERROR;
5142 if (!string || !lenstr) return SOCKET_ERROR;
5144 switch(sockaddr->sa_family)
5146 case WS_AF_INET:
5147 if (len < sizeof(SOCKADDR_IN)) return SOCKET_ERROR;
5148 sprintf( buffer, "%u.%u.%u.%u:%u",
5149 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 24 & 0xff),
5150 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 16 & 0xff),
5151 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) >> 8 & 0xff),
5152 (unsigned int)(ntohl( ((SOCKADDR_IN *)sockaddr)->sin_addr.WS_s_addr ) & 0xff),
5153 ntohs( ((SOCKADDR_IN *)sockaddr)->sin_port ) );
5155 p = strchr( buffer, ':' );
5156 if (!((SOCKADDR_IN *)sockaddr)->sin_port) *p = 0;
5157 break;
5159 case WS_AF_INET6:
5161 struct WS_sockaddr_in6 *sockaddr6 = (LPSOCKADDR_IN6) sockaddr;
5163 buffer[0] = 0;
5164 if (len < sizeof(SOCKADDR_IN6)) return SOCKET_ERROR;
5165 if ((sockaddr6->sin6_port))
5166 strcpy(buffer, "[");
5167 if (!WS_inet_ntop(WS_AF_INET6, &sockaddr6->sin6_addr, buffer+strlen(buffer), sizeof(buffer)))
5169 WSASetLastError(WSAEINVAL);
5170 return SOCKET_ERROR;
5172 if ((sockaddr6->sin6_scope_id))
5173 sprintf(buffer+strlen(buffer), "%%%u", sockaddr6->sin6_scope_id);
5174 if ((sockaddr6->sin6_port))
5175 sprintf(buffer+strlen(buffer), "]:%u", ntohs(sockaddr6->sin6_port));
5176 break;
5179 default:
5180 WSASetLastError(WSAEINVAL);
5181 return SOCKET_ERROR;
5184 size = strlen( buffer ) + 1;
5186 if (*lenstr < size)
5188 *lenstr = size;
5189 WSASetLastError(WSAEFAULT);
5190 return SOCKET_ERROR;
5193 *lenstr = size;
5194 strcpy( string, buffer );
5195 return 0;
5198 /***********************************************************************
5199 * WSAAddressToStringW (WS2_32.28)
5201 * Convert a sockaddr address into a readable address string.
5203 * PARAMS
5204 * sockaddr [I] Pointer to a sockaddr structure.
5205 * len [I] Size of the sockaddr structure.
5206 * info [I] Pointer to a WSAPROTOCOL_INFOW structure (optional).
5207 * string [I/O] Pointer to a buffer to receive the address string.
5208 * lenstr [I/O] Size of the receive buffer in WCHARs.
5210 * RETURNS
5211 * Success: 0
5212 * Failure: SOCKET_ERROR
5214 * NOTES
5215 * The 'info' parameter is ignored.
5217 INT WINAPI WSAAddressToStringW( LPSOCKADDR sockaddr, DWORD len,
5218 LPWSAPROTOCOL_INFOW info, LPWSTR string,
5219 LPDWORD lenstr )
5221 INT ret;
5222 DWORD size;
5223 WCHAR buffer[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
5224 CHAR bufAddr[54];
5226 TRACE( "(%p, %d, %p, %p, %p)\n", sockaddr, len, info, string, lenstr );
5228 size = *lenstr;
5229 ret = WSAAddressToStringA(sockaddr, len, NULL, bufAddr, &size);
5231 if (ret) return ret;
5233 MultiByteToWideChar( CP_ACP, 0, bufAddr, size, buffer, sizeof( buffer )/sizeof(WCHAR));
5235 if (*lenstr < size)
5237 *lenstr = size;
5238 WSASetLastError(WSAEFAULT);
5239 return SOCKET_ERROR;
5242 *lenstr = size;
5243 lstrcpyW( string, buffer );
5244 return 0;
5247 /***********************************************************************
5248 * WSAEnumNameSpaceProvidersA (WS2_32.34)
5250 INT WINAPI WSAEnumNameSpaceProvidersA( LPDWORD len, LPWSANAMESPACE_INFOA buffer )
5252 FIXME( "(%p %p) Stub!\n", len, buffer );
5253 return 0;
5256 /***********************************************************************
5257 * WSAEnumNameSpaceProvidersW (WS2_32.35)
5259 INT WINAPI WSAEnumNameSpaceProvidersW( LPDWORD len, LPWSANAMESPACE_INFOW buffer )
5261 FIXME( "(%p %p) Stub!\n", len, buffer );
5262 return 0;
5265 /***********************************************************************
5266 * WSAGetQOSByName (WS2_32.41)
5268 BOOL WINAPI WSAGetQOSByName( SOCKET s, LPWSABUF lpQOSName, LPQOS lpQOS )
5270 FIXME( "(0x%04lx %p %p) Stub!\n", s, lpQOSName, lpQOS );
5271 return FALSE;
5274 /***********************************************************************
5275 * WSAGetServiceClassInfoA (WS2_32.42)
5277 INT WINAPI WSAGetServiceClassInfoA( LPGUID provider, LPGUID service, LPDWORD len,
5278 LPWSASERVICECLASSINFOA info )
5280 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
5281 len, info );
5282 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5283 return SOCKET_ERROR;
5286 /***********************************************************************
5287 * WSAGetServiceClassInfoW (WS2_32.43)
5289 INT WINAPI WSAGetServiceClassInfoW( LPGUID provider, LPGUID service, LPDWORD len,
5290 LPWSASERVICECLASSINFOW info )
5292 FIXME( "(%s %s %p %p) Stub!\n", debugstr_guid(provider), debugstr_guid(service),
5293 len, info );
5294 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5295 return SOCKET_ERROR;
5298 /***********************************************************************
5299 * WSAGetServiceClassNameByClassIdA (WS2_32.44)
5301 INT WINAPI WSAGetServiceClassNameByClassIdA( LPGUID class, LPSTR service, LPDWORD len )
5303 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
5304 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5305 return SOCKET_ERROR;
5308 /***********************************************************************
5309 * WSAGetServiceClassNameByClassIdW (WS2_32.45)
5311 INT WINAPI WSAGetServiceClassNameByClassIdW( LPGUID class, LPWSTR service, LPDWORD len )
5313 FIXME( "(%s %p %p) Stub!\n", debugstr_guid(class), service, len );
5314 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5315 return SOCKET_ERROR;
5318 /***********************************************************************
5319 * WSALookupServiceBeginA (WS2_32.59)
5321 INT WINAPI WSALookupServiceBeginA( LPWSAQUERYSETA lpqsRestrictions,
5322 DWORD dwControlFlags,
5323 LPHANDLE lphLookup)
5325 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
5326 lphLookup);
5327 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5328 return SOCKET_ERROR;
5331 /***********************************************************************
5332 * WSALookupServiceBeginW (WS2_32.60)
5334 INT WINAPI WSALookupServiceBeginW( LPWSAQUERYSETW lpqsRestrictions,
5335 DWORD dwControlFlags,
5336 LPHANDLE lphLookup)
5338 FIXME("(%p 0x%08x %p) Stub!\n", lpqsRestrictions, dwControlFlags,
5339 lphLookup);
5340 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
5341 return SOCKET_ERROR;
5344 /***********************************************************************
5345 * WSALookupServiceBeginW (WS2_32.61)
5347 INT WINAPI WSALookupServiceEnd( HANDLE lookup )
5349 FIXME("(%p) Stub!\n", lookup );
5350 return 0;
5353 /***********************************************************************
5354 * WSALookupServiceNextA (WS2_32.62)
5356 INT WINAPI WSALookupServiceNextA( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETA results )
5358 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
5359 return 0;
5362 /***********************************************************************
5363 * WSALookupServiceNextW (WS2_32.63)
5365 INT WINAPI WSALookupServiceNextW( HANDLE lookup, DWORD flags, LPDWORD len, LPWSAQUERYSETW results )
5367 FIXME( "(%p 0x%08x %p %p) Stub!\n", lookup, flags, len, results );
5368 return 0;
5371 /***********************************************************************
5372 * WSANtohl (WS2_32.64)
5374 INT WINAPI WSANtohl( SOCKET s, WS_u_long netlong, WS_u_long* lphostlong )
5376 TRACE( "(0x%04lx 0x%08x %p)\n", s, netlong, lphostlong );
5378 if (!lphostlong) return WSAEFAULT;
5380 *lphostlong = ntohl( netlong );
5381 return 0;
5384 /***********************************************************************
5385 * WSANtohs (WS2_32.65)
5387 INT WINAPI WSANtohs( SOCKET s, WS_u_short netshort, WS_u_short* lphostshort )
5389 TRACE( "(0x%04lx 0x%08x %p)\n", s, netshort, lphostshort );
5391 if (!lphostshort) return WSAEFAULT;
5393 *lphostshort = ntohs( netshort );
5394 return 0;
5397 /***********************************************************************
5398 * WSAProviderConfigChange (WS2_32.66)
5400 INT WINAPI WSAProviderConfigChange( LPHANDLE handle, LPWSAOVERLAPPED overlapped,
5401 LPWSAOVERLAPPED_COMPLETION_ROUTINE completion )
5403 FIXME( "(%p %p %p) Stub!\n", handle, overlapped, completion );
5404 return SOCKET_ERROR;
5407 /***********************************************************************
5408 * WSARecvDisconnect (WS2_32.68)
5410 INT WINAPI WSARecvDisconnect( SOCKET s, LPWSABUF disconnectdata )
5412 TRACE( "(0x%04lx %p)\n", s, disconnectdata );
5414 return WS_shutdown( s, 0 );
5417 /***********************************************************************
5418 * WSASetServiceA (WS2_32.76)
5420 INT WINAPI WSASetServiceA( LPWSAQUERYSETA query, WSAESETSERVICEOP operation, DWORD flags )
5422 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
5423 return 0;
5426 /***********************************************************************
5427 * WSASetServiceW (WS2_32.77)
5429 INT WINAPI WSASetServiceW( LPWSAQUERYSETW query, WSAESETSERVICEOP operation, DWORD flags )
5431 FIXME( "(%p 0x%08x 0x%08x) Stub!\n", query, operation, flags );
5432 return 0;
5435 /***********************************************************************
5436 * WSCEnableNSProvider (WS2_32.84)
5438 INT WINAPI WSCEnableNSProvider( LPGUID provider, BOOL enable )
5440 FIXME( "(%s 0x%08x) Stub!\n", debugstr_guid(provider), enable );
5441 return 0;
5444 /***********************************************************************
5445 * WSCGetProviderPath (WS2_32.86)
5447 INT WINAPI WSCGetProviderPath( LPGUID provider, LPWSTR path, LPINT len, LPINT errcode )
5449 FIXME( "(%s %p %p %p) Stub!\n", debugstr_guid(provider), path, len, errcode );
5451 if (!errcode || !provider || !len) return WSAEFAULT;
5453 *errcode = WSAEINVAL;
5454 return SOCKET_ERROR;
5457 /***********************************************************************
5458 * WSCInstallNameSpace (WS2_32.87)
5460 INT WINAPI WSCInstallNameSpace( LPWSTR identifier, LPWSTR path, DWORD namespace,
5461 DWORD version, LPGUID provider )
5463 FIXME( "(%s %s 0x%08x 0x%08x %s) Stub!\n", debugstr_w(identifier), debugstr_w(path),
5464 namespace, version, debugstr_guid(provider) );
5465 return 0;
5468 /***********************************************************************
5469 * WSCUnInstallNameSpace (WS2_32.89)
5471 INT WINAPI WSCUnInstallNameSpace( LPGUID lpProviderId )
5473 FIXME("(%p) Stub!\n", lpProviderId);
5474 return NO_ERROR;
5477 /***********************************************************************
5478 * WSCWriteProviderOrder (WS2_32.91)
5480 INT WINAPI WSCWriteProviderOrder( LPDWORD entry, DWORD number )
5482 FIXME("(%p 0x%08x) Stub!\n", entry, number);
5483 return 0;