~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~ [ freetext search ] ~ [ file search ] ~

Wine Cross Reference
wine/dlls/ws2_32/socket.c

Version: ~ [ wine-1.1.33 ] ~ [ wine-1.1.32 ] ~ [ wine-1.1.31 ] ~ [ wine-1.1.30 ] ~ [ wine-1.1.29 ] ~ [ wine-1.1.28 ] ~ [ wine-1.1.27 ] ~ [ wine-1.1.26 ] ~ [ wine-1.1.25 ] ~ [ wine-1.1.24 ] ~ [ wine-1.1.23 ] ~ [ wine-1.1.22 ] ~ [ wine-1.1.21 ] ~ [ wine-1.1.20 ] ~ [ wine-1.1.19 ] ~ [ wine-1.1.18 ] ~ [ wine-1.1.17 ] ~ [ wine-1.1.16 ] ~ [ wine-1.1.15 ] ~ [ wine-1.1.14 ] ~ [ wine-1.1.13 ] ~ [ wine-1.1.12 ] ~ [ wine-1.1.11 ] ~ [ wine-1.1.10 ] ~ [ wine-1.1.9 ] ~ [ wine-1.1.8 ] ~ [ wine-1.1.7 ] ~ [ wine-1.0.1 ] ~ [ wine-1.1.6 ] ~ [ wine-1.1.5 ] ~ [ wine-1.1.4 ] ~ [ wine-1.1.3 ] ~ [ wine-1.1.2 ] ~ [ wine-1.1.1 ] ~ [ wine-1.1.0 ] ~ [ wine-1.0 ] ~

  1 /*
  2  * based on Windows Sockets 1.1 specs
  3  *
  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
  7  *
  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.
 12  *
 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.
 17  *
 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
 21  *
 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).
 25  */
 26 
 27 #include "config.h"
 28 #include "wine/port.h"
 29 
 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
 46 
 47 #if defined(__EMX__)
 48 # include <sys/so_ioctl.h>
 49 #endif
 50 
 51 #ifdef HAVE_SYS_PARAM_H
 52 # include <sys/param.h>
 53 #endif
 54 
 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
 98 
 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 # include <linux/ipx.h>
107 # define HAVE_IPX
108 #endif
109 
110 #ifdef HAVE_POLL_H
111 #include <poll.h>
112 #endif
113 #ifdef HAVE_SYS_POLL_H
114 # include <sys/poll.h>
115 #endif
116 #ifdef HAVE_SYS_TIME_H
117 # include <sys/time.h>
118 #endif
119 
120 #define NONAMELESSUNION
121 #define NONAMELESSSTRUCT
122 #include "ntstatus.h"
123 #define WIN32_NO_STATUS
124 #include "windef.h"
125 #include "winbase.h"
126 #include "wingdi.h"
127 #include "winuser.h"
128 #include "winerror.h"
129 #include "winnls.h"
130 #include "winsock2.h"
131 #include "mswsock.h"
132 #include "ws2tcpip.h"
133 #include "ws2spi.h"
134 #include "wsipx.h"
135 #include "winnt.h"
136 #include "iphlpapi.h"
137 #include "wine/server.h"
138 #include "wine/debug.h"
139 #include "wine/unicode.h"
140 
141 #ifdef HAVE_IPX
142 # include "wsnwlink.h"
143 #endif
144 
145 
146 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
147 # define sipx_network    sipx_addr.x_net
148 # define sipx_node       sipx_addr.x_host.c_host
149 #endif  /* __FreeBSD__ */
150 
151 #ifndef INADDR_NONE
152 #define INADDR_NONE ~0UL
153 #endif
154 
155 WINE_DEFAULT_DEBUG_CHANNEL(winsock);
156 
157 /* critical section to protect some non-reentrant net function */
158 extern CRITICAL_SECTION csWSgetXXXbyYYY;
159 
160 union generic_unix_sockaddr
161 {
162     struct sockaddr addr;
163     char data[128];  /* should be big enough for all families */
164 };
165 
166 static inline const char *debugstr_sockaddr( const struct WS_sockaddr *a )
167 {
168     if (!a) return "(nil)";
169     return wine_dbg_sprintf("{ family %d, address %s, port %d }",
170                             ((const struct sockaddr_in *)a)->sin_family,
171                             inet_ntoa(((const struct sockaddr_in *)a)->sin_addr),
172                             ntohs(((const struct sockaddr_in *)a)->sin_port));
173 }
174 
175 /* HANDLE<->SOCKET conversion (SOCKET is UINT_PTR). */
176 #define SOCKET2HANDLE(s) ((HANDLE)(s))
177 #define HANDLE2SOCKET(h) ((SOCKET)(h))
178 
179 /****************************************************************
180  * Async IO declarations
181  ****************************************************************/
182 
183 typedef struct ws2_async
184 {
185     HANDLE                              hSocket;
186     int                                 type;
187     LPWSAOVERLAPPED                     user_overlapped;
188     LPWSAOVERLAPPED_COMPLETION_ROUTINE  completion_func;
189     IO_STATUS_BLOCK                     local_iosb;
190     struct WS_sockaddr                  *addr;
191     union
192     {
193         int val;     /* for send operations */
194         int *ptr;    /* for recv operations */
195     }                                   addrlen;
196     DWORD                               flags;
197     unsigned int                        n_iovecs;
198     unsigned int                        first_iovec;
199     struct iovec                        iovec[1];
200 } ws2_async;
201 
202 /****************************************************************/
203 
204 /* ----------------------------------- internal data */
205 
206 /* ws_... struct conversion flags */
207 
208 typedef struct          /* WSAAsyncSelect() control struct */
209 {
210   HANDLE      service, event, sock;
211   HWND        hWnd;
212   UINT        uMsg;
213   LONG        lEvent;
214 } ws_select_info;
215 
216 #define WS_MAX_SOCKETS_PER_PROCESS      128     /* reasonable guess */
217 #define WS_MAX_UDP_DATAGRAM             1024
218 static INT WINAPI WSA_DefaultBlockingHook( FARPROC x );
219 
220 /* hostent's, servent's and protent's are stored in one buffer per thread,
221  * as documented on MSDN for the functions that return any of the buffers */
222 struct per_thread_data
223 {
224     int opentype;
225     struct WS_hostent *he_buffer;
226     struct WS_servent *se_buffer;
227     struct WS_protoent *pe_buffer;
228     int he_len;
229     int se_len;
230     int pe_len;
231 };
232 
233 static INT num_startup;          /* reference counter */
234 static FARPROC blocking_hook = (FARPROC)WSA_DefaultBlockingHook;
235 
236 /* function prototypes */
237 static struct WS_hostent *WS_dup_he(const struct hostent* p_he);
238 static struct WS_protoent *WS_dup_pe(const struct protoent* p_pe);
239 static struct WS_servent *WS_dup_se(const struct servent* p_se);
240 
241 int WSAIOCTL_GetInterfaceCount(void);
242 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
243 
244 UINT wsaErrno(void);
245 UINT wsaHerrno(int errnr);
246 
247 #define MAP_OPTION(opt) { WS_##opt, opt }
248 
249 static const int ws_sock_map[][2] =
250 {
251     MAP_OPTION( SO_DEBUG ),
252     MAP_OPTION( SO_ACCEPTCONN ),
253     MAP_OPTION( SO_REUSEADDR ),
254     MAP_OPTION( SO_KEEPALIVE ),
255     MAP_OPTION( SO_DONTROUTE ),
256     MAP_OPTION( SO_BROADCAST ),
257     MAP_OPTION( SO_LINGER ),
258     MAP_OPTION( SO_OOBINLINE ),
259     MAP_OPTION( SO_SNDBUF ),
260     MAP_OPTION( SO_RCVBUF ),
261     MAP_OPTION( SO_ERROR ),
262     MAP_OPTION( SO_TYPE ),
263 #ifdef SO_RCVTIMEO
264     MAP_OPTION( SO_RCVTIMEO ),
265 #endif
266 #ifdef SO_SNDTIMEO
267     MAP_OPTION( SO_SNDTIMEO ),
268 #endif
269 };
270 
271 static const int ws_tcp_map[][2] =
272 {
273 #ifdef TCP_NODELAY
274     MAP_OPTION( TCP_NODELAY ),
275 #endif
276 };
277 
278 static const int ws_ip_map[][2] =
279 {
280     MAP_OPTION( IP_MULTICAST_IF ),
281     MAP_OPTION( IP_MULTICAST_TTL ),
282     MAP_OPTION( IP_MULTICAST_LOOP ),
283     MAP_OPTION( IP_ADD_MEMBERSHIP ),
284     MAP_OPTION( IP_DROP_MEMBERSHIP ),
285     MAP_OPTION( IP_OPTIONS ),
286 #ifdef IP_HDRINCL
287     MAP_OPTION( IP_HDRINCL ),
288 #endif
289     MAP_OPTION( IP_TOS ),
290     MAP_OPTION( IP_TTL ),
291 };
292 
293 static const int ws_af_map[][2] =
294 {
295     MAP_OPTION( AF_UNSPEC ),
296     MAP_OPTION( AF_INET ),
297     MAP_OPTION( AF_INET6 ),
298 #ifdef HAVE_IPX
299     MAP_OPTION( AF_IPX ),
300 #endif
301     {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
302 };
303 
304 static const int ws_socktype_map[][2] =
305 {
306     MAP_OPTION( SOCK_DGRAM ),
307     MAP_OPTION( SOCK_STREAM ),
308     MAP_OPTION( SOCK_RAW ),
309     {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
310 };
311 
312 static const int ws_proto_map[][2] =
313 {
314     MAP_OPTION( IPPROTO_IP ),
315     MAP_OPTION( IPPROTO_TCP ),
316     MAP_OPTION( IPPROTO_UDP ),
317     MAP_OPTION( IPPROTO_ICMP ),
318     MAP_OPTION( IPPROTO_IGMP ),
319     MAP_OPTION( IPPROTO_RAW ),
320     {FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO},
321 };
322 
323 static const int ws_aiflag_map[][2] =
324 {
325     MAP_OPTION( AI_PASSIVE ),
326     MAP_OPTION( AI_CANONNAME ),
327     MAP_OPTION( AI_NUMERICHOST ),
328     /* Linux/UNIX knows a lot more. But Windows only
329      * has 3 as far as I could see. -Marcus
330      */
331 };
332 
333 static const int ws_niflag_map[][2] =
334 {
335     MAP_OPTION( NI_NOFQDN ),
336     MAP_OPTION( NI_NUMERICHOST ),
337     MAP_OPTION( NI_NAMEREQD ),
338     MAP_OPTION( NI_NUMERICSERV ),
339     MAP_OPTION( NI_DGRAM ),
340 };
341 
342 static const int ws_eai_map[][2] =
343 {
344     MAP_OPTION( EAI_AGAIN ),
345     MAP_OPTION( EAI_BADFLAGS ),
346     MAP_OPTION( EAI_FAIL ),
347     MAP_OPTION( EAI_FAMILY ),
348     MAP_OPTION( EAI_MEMORY ),
349 /* Note: EAI_NODATA is deprecated, but still 
350  * used by Windows and Linux... We map the newer
351  * EAI_NONAME to EAI_NODATA for now until Windows
352  * changes too.
353  */
354 #ifdef EAI_NODATA
355     MAP_OPTION( EAI_NODATA ),
356 #endif
357 #ifdef EAI_NONAME
358     { WS_EAI_NODATA, EAI_NONAME },
359 #endif
360 
361     MAP_OPTION( EAI_SERVICE ),
362     MAP_OPTION( EAI_SOCKTYPE ),
363     { 0, 0 }
364 };
365 
366 static const char magic_loopback_addr[] = {127, 12, 34, 56};
367 
368 static inline DWORD NtStatusToWSAError( const DWORD status )
369 {
370     /* We only need to cover the status codes set by server async request handling */
371     DWORD wserr;
372     switch ( status )
373     {
374     case STATUS_SUCCESS:              wserr = 0;                     break;
375     case STATUS_PENDING:              wserr = WSA_IO_PENDING;        break;
376     case STATUS_OBJECT_TYPE_MISMATCH: wserr = WSAENOTSOCK;           break;
377     case STATUS_INVALID_HANDLE:       wserr = WSAEBADF;              break;
378     case STATUS_INVALID_PARAMETER:    wserr = WSAEINVAL;             break;
379     case STATUS_PIPE_DISCONNECTED:    wserr = WSAESHUTDOWN;          break;
380     case STATUS_CANCELLED:            wserr = WSA_OPERATION_ABORTED; break;
381     case STATUS_TIMEOUT:              wserr = WSAETIMEDOUT;          break;
382     case STATUS_NO_MEMORY:            wserr = WSAEFAULT;             break;
383     default:
384         if ( status >= WSABASEERR && status <= WSABASEERR+1004 )
385             /* It is not an NT status code but a winsock error */
386             wserr = status;
387         else
388         {
389             wserr = RtlNtStatusToDosError( status );
390             FIXME( "Status code %08x converted to DOS error code %x\n", status, wserr );
391         }
392     }
393     return wserr;
394 }
395 
396 /* set last error code from NT status without mapping WSA errors */
397 static inline unsigned int set_error( unsigned int err )
398 {
399     if (err)
400     {
401         err = NtStatusToWSAError( err );
402         SetLastError( err );
403     }
404     return err;
405 }
406 
407 static inline int get_sock_fd( SOCKET s, DWORD access, unsigned int *options )
408 {
409     int fd;
410     if (set_error( wine_server_handle_to_fd( SOCKET2HANDLE(s), access, &fd, options ) ))
411         return -1;
412     return fd;
413 }
414 
415 static inline void release_sock_fd( SOCKET s, int fd )
416 {
417     wine_server_release_fd( SOCKET2HANDLE(s), fd );
418 }
419 
420 static void _enable_event( HANDLE s, unsigned int event,
421                            unsigned int sstate, unsigned int cstate )
422 {
423     SERVER_START_REQ( enable_socket_event )
424     {
425         req->handle = s;
426         req->mask   = event;
427         req->sstate = sstate;
428         req->cstate = cstate;
429         wine_server_call( req );
430     }
431     SERVER_END_REQ;
432 }
433 
434 static int _is_blocking(SOCKET s)
435 {
436     int ret;
437     SERVER_START_REQ( get_socket_event )
438     {
439         req->handle  = SOCKET2HANDLE(s);
440         req->service = FALSE;
441         req->c_event = 0;
442         wine_server_call( req );
443         ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
444     }
445     SERVER_END_REQ;
446     return ret;
447 }
448 
449 static unsigned int _get_sock_mask(SOCKET s)
450 {
451     unsigned int ret;
452     SERVER_START_REQ( get_socket_event )
453     {
454         req->handle  = SOCKET2HANDLE(s);
455         req->service = FALSE;
456         req->c_event = 0;
457         wine_server_call( req );
458         ret = reply->mask;
459     }
460     SERVER_END_REQ;
461     return ret;
462 }
463 
464 static void _sync_sock_state(SOCKET s)
465 {
466     /* do a dummy wineserver request in order to let
467        the wineserver run through its select loop once */
468     (void)_is_blocking(s);
469 }
470 
471 static int _get_sock_error(SOCKET s, unsigned int bit)
472 {
473     int events[FD_MAX_EVENTS];
474 
475     SERVER_START_REQ( get_socket_event )
476     {
477         req->handle  = SOCKET2HANDLE(s);
478         req->service = FALSE;
479         req->c_event = 0;
480         wine_server_set_reply( req, events, sizeof(events) );
481         wine_server_call( req );
482     }
483     SERVER_END_REQ;
484     return events[bit];
485 }
486 
487 static struct per_thread_data *get_per_thread_data(void)
488 {
489     struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
490     /* lazy initialization */
491     if (!ptb)
492     {
493         ptb = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*ptb) );
494         NtCurrentTeb()->WinSockData = ptb;
495     }
496     return ptb;
497 }
498 
499 static void free_per_thread_data(void)
500 {
501     struct per_thread_data * ptb = NtCurrentTeb()->WinSockData;
502 
503     if (!ptb) return;
504 
505     /* delete scratch buffers */
506     HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
507     HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
508     HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
509     ptb->he_buffer = NULL;
510     ptb->se_buffer = NULL;
511     ptb->pe_buffer = NULL;
512 
513     HeapFree( GetProcessHeap(), 0, ptb );
514     NtCurrentTeb()->WinSockData = NULL;
515 }
516 
517 /***********************************************************************
518  *              DllMain (WS2_32.init)
519  */
520 BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
521 {
522     TRACE("%p 0x%x %p\n", hInstDLL, fdwReason, fImpLoad);
523     switch (fdwReason) {
524     case DLL_PROCESS_ATTACH:
525         break;
526     case DLL_PROCESS_DETACH:
527         free_per_thread_data();
528         num_startup = 0;
529         break;
530     case DLL_THREAD_DETACH:
531         free_per_thread_data();
532         break;
533     }
534     return TRUE;
535 }
536 
537 /***********************************************************************
538  *          convert_sockopt()
539  *
540  * Converts socket flags from Windows format.
541  * Return 1 if converted, 0 if not (error).
542  */
543 static int convert_sockopt(INT *level, INT *optname)
544 {
545   int i;
546   switch (*level)
547   {
548      case WS_SOL_SOCKET:
549         *level = SOL_SOCKET;
550         for(i=0; i<sizeof(ws_sock_map)/sizeof(ws_sock_map[0]); i++) {
551             if( ws_sock_map[i][0] == *optname )
552             {
553                 *optname = ws_sock_map[i][1];
554                 return 1;
555             }
556         }
557         FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
558         break;
559      case WS_IPPROTO_TCP:
560         *level = IPPROTO_TCP;
561         for(i=0; i<sizeof(ws_tcp_map)/sizeof(ws_tcp_map[0]); i++) {
562             if ( ws_tcp_map[i][0] == *optname )
563             {
564                 *optname = ws_tcp_map[i][1];
565                 return 1;
566             }
567         }
568         FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
569         break;
570      case WS_IPPROTO_IP:
571         *level = IPPROTO_IP;
572         for(i=0; i<sizeof(ws_ip_map)/sizeof(ws_ip_map[0]); i++) {
573             if (ws_ip_map[i][0] == *optname )
574             {
575                 *optname = ws_ip_map[i][1];
576                 return 1;
577             }
578         }
579         FIXME("Unknown IPPROTO_IP optname 0x%x\n", *optname);
580         break;
581      default: FIXME("Unimplemented or unknown socket level\n");
582   }
583   return 0;
584 }
585 
586 /* ----------------------------------- Per-thread info (or per-process?) */
587 
588 static char *strdup_lower(const char *str)
589 {
590     int i;
591     char *ret = HeapAlloc( GetProcessHeap(), 0, strlen(str) + 1 );
592 
593     if (ret)
594     {
595         for (i = 0; str[i]; i++) ret[i] = tolower(str[i]);
596         ret[i] = 0;
597     }
598     else SetLastError(WSAENOBUFS);
599     return ret;
600 }
601 
602 static inline int sock_error_p(int s)
603 {
604     unsigned int optval, optlen;
605 
606     optlen = sizeof(optval);
607     getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
608     if (optval) WARN("\t[%i] error: %d\n", s, optval);
609     return optval != 0;
610 }
611 
612 /* Utility: get the SO_RCVTIMEO or SO_SNDTIMEO socket option
613  * from an fd and return the value converted to milli seconds
614  * or -1 if there is an infinite time out */
615 static inline int get_rcvsnd_timeo( int fd, int optname)
616 {
617   struct timeval tv;
618   unsigned int len = sizeof(tv);
619   int ret = getsockopt(fd, SOL_SOCKET, optname, &tv, &len);
620   if( ret >= 0)
621       ret = tv.tv_sec * 1000 + tv.tv_usec / 1000;
622   if( ret <= 0 ) /* tv == {0,0} means infinite time out */
623       return -1;
624   return ret;
625 }
626 
627 /* macro wrappers for portability */
628 #ifdef SO_RCVTIMEO
629 #define GET_RCVTIMEO(fd) get_rcvsnd_timeo( (fd), SO_RCVTIMEO)
630 #else
631 #define GET_RCVTIMEO(fd) (-1)
632 #endif
633 
634 #ifdef SO_SNDTIMEO
635 #define GET_SNDTIMEO(fd) get_rcvsnd_timeo( (fd), SO_SNDTIMEO)
636 #else
637 #define GET_SNDTIMEO(fd) (-1)
638 #endif
639 
640 /* utility: given an fd, will block until one of the events occurs */
641 static inline int do_block( int fd, int events, int timeout )
642 {
643   struct pollfd pfd;
644   int ret;
645 
646   pfd.fd = fd;
647   pfd.events = events;
648 
649   while ((ret = poll(&pfd, 1, timeout)) < 0)
650   {
651       if (errno != EINTR)
652           return -1;
653   }
654   if( ret == 0 )
655       return 0;
656   return pfd.revents;
657 }
658 
659 static int
660 convert_af_w2u(int windowsaf) {
661     int i;
662 
663     for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
664         if (ws_af_map[i][0] == windowsaf)
665             return ws_af_map[i][1];
666     FIXME("unhandled Windows address family %d\n", windowsaf);
667     return -1;
668 }
669 
670 static int
671 convert_af_u2w(int unixaf) {
672     int i;
673 
674     for (i=0;i<sizeof(ws_af_map)/sizeof(ws_af_map[0]);i++)
675         if (ws_af_map[i][1] == unixaf)
676             return ws_af_map[i][0];
677     FIXME("unhandled UNIX address family %d\n", unixaf);
678     return -1;
679 }
680 
681 static int
682 convert_proto_w2u(int windowsproto) {
683     int i;
684 
685     for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
686         if (ws_proto_map[i][0] == windowsproto)
687             return ws_proto_map[i][1];
688     FIXME("unhandled Windows socket protocol %d\n", windowsproto);
689     return -1;
690 }
691 
692 static int
693 convert_proto_u2w(int unixproto) {
694     int i;
695 
696     for (i=0;i<sizeof(ws_proto_map)/sizeof(ws_proto_map[0]);i++)
697         if (ws_proto_map[i][1] == unixproto)
698             return ws_proto_map[i][0];
699     FIXME("unhandled UNIX socket protocol %d\n", unixproto);
700     return -1;
701 }
702 
703 static int
704 convert_socktype_w2u(int windowssocktype) {
705     int i;
706 
707     for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
708         if (ws_socktype_map[i][0] == windowssocktype)
709             return ws_socktype_map[i][1];
710     FIXME("unhandled Windows socket type %d\n", windowssocktype);
711     return -1;
712 }
713 
714 static int
715 convert_socktype_u2w(int unixsocktype) {
716     int i;
717 
718     for (i=0;i<sizeof(ws_socktype_map)/sizeof(ws_socktype_map[0]);i++)
719         if (ws_socktype_map[i][1] == unixsocktype)
720             return ws_socktype_map[i][0];
721     FIXME("unhandled UNIX socket type %d\n", unixsocktype);
722     return -1;
723 }
724 
725 /* ----------------------------------- API -----
726  *
727  * Init / cleanup / error checking.
728  */
729 
730 /***********************************************************************
731  *      WSAStartup              (WS2_32.115)
732  */
733 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
734 {
735     TRACE("verReq=%x\n", wVersionRequested);
736 
737     if (LOBYTE(wVersionRequested) < 1)
738         return WSAVERNOTSUPPORTED;
739 
740     if (!lpWSAData) return WSAEINVAL;
741 
742     num_startup++;
743 
744     /* that's the whole of the negotiation for now */
745     lpWSAData->wVersion = wVersionRequested;
746     /* return winsock information */
747     lpWSAData->wHighVersion = 0x0202;
748     strcpy(lpWSAData->szDescription, "WinSock 2.0" );
749     strcpy(lpWSAData->szSystemStatus, "Running" );
750     lpWSAData->iMaxSockets = WS_MAX_SOCKETS_PER_PROCESS;
751     lpWSAData->iMaxUdpDg = WS_MAX_UDP_DATAGRAM;
752     /* don't do anything with lpWSAData->lpVendorInfo */
753     /* (some apps don't allocate the space for this field) */
754 
755     TRACE("succeeded\n");
756     return 0;
757 }
758 
759 
760 /***********************************************************************
761  *      WSACleanup                      (WS2_32.116)
762  */
763 INT WINAPI WSACleanup(void)
764 {
765     if (num_startup) {
766         num_startup--;
767         return 0;
768     }
769     SetLastError(WSANOTINITIALISED);
770     return SOCKET_ERROR;
771 }
772 
773 
774 /***********************************************************************
775  *      WSAGetLastError         (WINSOCK.111)
776  *      WSAGetLastError         (WS2_32.111)
777  */
778 INT WINAPI WSAGetLastError(void)
779 {
780         return GetLastError();
781 }
782 
783 /***********************************************************************
784  *      WSASetLastError         (WS2_32.112)
785  */
786 void WINAPI WSASetLastError(INT iError) {
787     SetLastError(iError);
788 }
789 
790 static struct WS_hostent *check_buffer_he(int size)
791 {
792     struct per_thread_data * ptb = get_per_thread_data();
793     if (ptb->he_buffer)
794     {
795         if (ptb->he_len >= size ) return ptb->he_buffer;
796         HeapFree( GetProcessHeap(), 0, ptb->he_buffer );
797     }
798     ptb->he_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->he_len = size) );
799     if (!ptb->he_buffer) SetLastError(WSAENOBUFS);
800     return ptb->he_buffer;
801 }
802 
803 static struct WS_servent *check_buffer_se(int size)
804 {
805     struct per_thread_data * ptb = get_per_thread_data();
806     if (ptb->se_buffer)
807     {
808         if (ptb->se_len >= size ) return ptb->se_buffer;
809         HeapFree( GetProcessHeap(), 0, ptb->se_buffer );
810     }
811     ptb->se_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->se_len = size) );
812     if (!ptb->se_buffer) SetLastError(WSAENOBUFS);
813     return ptb->se_buffer;
814 }
815 
816 static struct WS_protoent *check_buffer_pe(int size)
817 {
818     struct per_thread_data * ptb = get_per_thread_data();
819     if (ptb->pe_buffer)
820     {
821         if (ptb->pe_len >= size ) return ptb->pe_buffer;
822         HeapFree( GetProcessHeap(), 0, ptb->pe_buffer );
823     }
824     ptb->pe_buffer = HeapAlloc( GetProcessHeap(), 0, (ptb->pe_len = size) );
825     if (!ptb->pe_buffer) SetLastError(WSAENOBUFS);
826     return ptb->pe_buffer;
827 }
828 
829 /* ----------------------------------- i/o APIs */
830 
831 #ifdef HAVE_IPX
832 #define SUPPORTED_PF(pf) ((pf)==WS_AF_INET || (pf)== WS_AF_IPX || (pf) == WS_AF_INET6)
833 #else
834 #define SUPPORTED_PF(pf) ((pf)==WS_AF_INET || (pf) == WS_AF_INET6)
835 #endif
836 
837 
838 /**********************************************************************/
839 
840 /* Returns the length of the converted address if successful, 0 if it was too small to
841  * start with.
842  */
843 static unsigned int ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen,
844                                      union generic_unix_sockaddr *uaddr)
845 {
846     unsigned int uaddrlen = 0;
847 
848     switch (wsaddr->sa_family)
849     {
850 #ifdef HAVE_IPX
851     case WS_AF_IPX:
852         {
853             const struct WS_sockaddr_ipx* wsipx=(const struct WS_sockaddr_ipx*)wsaddr;
854             struct sockaddr_ipx* uipx = (struct sockaddr_ipx *)uaddr;
855 
856             if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
857                 return 0;
858 
859             uaddrlen = sizeof(struct sockaddr_ipx);
860             memset( uaddr, 0, uaddrlen );
861             uipx->sipx_family=AF_IPX;
862             uipx->sipx_port=wsipx->sa_socket;
863             /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
864              * in one go
865              */
866             memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
867 #ifdef IPX_FRAME_NONE
868             uipx->sipx_type=IPX_FRAME_NONE;
869 #endif
870             break;
871         }
872 #endif
873     case WS_AF_INET6: {
874         struct sockaddr_in6* uin6 = (struct sockaddr_in6 *)uaddr;
875         const struct WS_sockaddr_in6* win6 = (const struct WS_sockaddr_in6*)wsaddr;
876 
877         /* Note: Windows has 2 versions of the sockaddr_in6 struct, one with
878          * scope_id, one without.
879          */
880         if (wsaddrlen >= sizeof(struct WS_sockaddr_in6_old)) {
881             uaddrlen = sizeof(struct sockaddr_in6);
882             memset( uaddr, 0, uaddrlen );
883             uin6->sin6_family   = AF_INET6;
884             uin6->sin6_port     = win6->sin6_port;
885             uin6->sin6_flowinfo = win6->sin6_flowinfo;
886 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
887             if (wsaddrlen >= sizeof(struct WS_sockaddr_in6)) uin6->sin6_scope_id = win6->sin6_scope_id;
888 #endif
889             memcpy(&uin6->sin6_addr,&win6->sin6_addr,16); /* 16 bytes = 128 address bits */
890             break;
891         }
892         FIXME("bad size %d for WS_sockaddr_in6\n",wsaddrlen);
893         return 0;
894     }
895     case WS_AF_INET: {
896         struct sockaddr_in* uin = (struct sockaddr_in *)uaddr;
897         const struct WS_sockaddr_in* win = (const struct WS_sockaddr_in*)wsaddr;
898 
899         if (wsaddrlen<sizeof(struct WS_sockaddr_in))
900             return 0;
901         uaddrlen = sizeof(struct sockaddr_in);
902         memset( uaddr, 0, uaddrlen );
903         uin->sin_family = AF_INET;
904         uin->sin_port   = win->sin_port;
905         memcpy(&uin->sin_addr,&win->sin_addr,4); /* 4 bytes = 32 address bits */
906         break;
907     }
908     case WS_AF_UNSPEC: {
909         /* Try to determine the needed space by the passed windows sockaddr space */
910         switch (wsaddrlen) {
911         default: /* likely a ipv4 address */
912         case sizeof(struct WS_sockaddr_in):
913             uaddrlen = sizeof(struct sockaddr_in);
914             break;
915 #ifdef HAVE_IPX
916         case sizeof(struct WS_sockaddr_ipx):
917             uaddrlen = sizeof(struct sockaddr_ipx);
918             break;
919 #endif
920         case sizeof(struct WS_sockaddr_in6):
921         case sizeof(struct WS_sockaddr_in6_old):
922             uaddrlen = sizeof(struct sockaddr_in6);
923             break;
924         }
925         memset( uaddr, 0, uaddrlen );
926         break;
927     }
928     default:
929         FIXME("Unknown address family %d, return NULL.\n", wsaddr->sa_family);
930         return 0;
931     }
932     return uaddrlen;
933 }
934 
935 static BOOL is_sockaddr_bound(const struct sockaddr *uaddr, int uaddrlen)
936 {
937     switch (uaddr->sa_family)
938     {
939 #ifdef HAVE_IPX
940         case AF_IPX:
941             FIXME("don't know how to tell if IPX socket is bound, assuming it is!\n");
942             return TRUE;
943 #endif
944         case AF_INET6:
945         {
946             static const struct sockaddr_in6 emptyAddr;
947             const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) uaddr;
948             return in6->sin6_port || memcmp(&in6->sin6_addr, &emptyAddr.sin6_addr, sizeof(struct in6_addr));
949         }
950         case AF_INET:
951         {
952             static const struct sockaddr_in emptyAddr;
953             const struct sockaddr_in *in = (const struct sockaddr_in*) uaddr;
954             return in->sin_port || memcmp(&in->sin_addr, &emptyAddr.sin_addr, sizeof(struct in_addr));
955         }
956         case AF_UNSPEC:
957             return FALSE;
958         default:
959             FIXME("unknown address family %d\n", uaddr->sa_family);
960             return TRUE;
961     }
962 }
963 
964 /* Returns 0 if successful, -1 if the buffer is too small */
965 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, struct WS_sockaddr* wsaddr, int* wsaddrlen)
966 {
967     int res;
968 
969     switch(uaddr->sa_family)
970     {
971 #ifdef HAVE_IPX
972     case AF_IPX:
973         {
974             const struct sockaddr_ipx* uipx=(const struct sockaddr_ipx*)uaddr;
975             struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
976 
977             res=-1;
978             switch (*wsaddrlen) /* how much can we copy? */
979             {
980             default:
981                 res=0; /* enough */
982                 *wsaddrlen = sizeof(*wsipx);
983                 wsipx->sa_socket=uipx->sipx_port;
984                 /* fall through */
985             case 13:
986             case 12:
987                 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
988                 /* fall through */
989             case 11:
990             case 10:
991             case 9:
992             case 8:
993             case 7:
994             case 6:
995                 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
996                 /* fall through */
997             case 5:
998             case 4:
999             case 3:
1000             case 2:
1001                 wsipx->sa_family=WS_AF_IPX;
1002                 /* fall through */
1003             case 1:
1004             case 0:
1005                 /* way too small */
1006                 break;
1007             }
1008         }
1009         break;
1010 #endif
1011     case AF_INET6: {
1012         const struct sockaddr_in6* uin6 = (const struct sockaddr_in6*)uaddr;
1013         struct WS_sockaddr_in6_old* win6old = (struct WS_sockaddr_in6_old*)wsaddr;
1014 
1015         if (*wsaddrlen < sizeof(struct WS_sockaddr_in6_old))
1016             return -1;
1017         win6old->sin6_family   = WS_AF_INET6;
1018         win6old->sin6_port     = uin6->sin6_port;
1019         win6old->sin6_flowinfo = uin6->sin6_flowinfo;
1020         memcpy(&win6old->sin6_addr,&uin6->sin6_addr,16); /* 16 bytes = 128 address bits */
1021         *wsaddrlen = sizeof(struct WS_sockaddr_in6_old);
1022 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID
1023         if (*wsaddrlen >= sizeof(struct WS_sockaddr_in6)) {
1024             struct WS_sockaddr_in6* win6 = (struct WS_sockaddr_in6*)wsaddr;
1025             win6->sin6_scope_id = uin6->sin6_scope_id;
1026             *wsaddrlen = sizeof(struct WS_sockaddr_in6);
1027         }
1028 #endif
1029         return 0;
1030     }
1031     case AF_INET: {
1032         const struct sockaddr_in* uin = (const struct sockaddr_in*)uaddr;
1033         struct WS_sockaddr_in* win = (struct WS_sockaddr_in*)wsaddr;
1034 
1035         if (*wsaddrlen < sizeof(struct WS_sockaddr_in))
1036             return -1;
1037         win->sin_family = WS_AF_INET;
1038         win->sin_port   = uin->sin_port;
1039         memcpy(&win->sin_addr,&uin->sin_addr,4); /* 4 bytes = 32 address bits */
1040         memset(win->sin_zero, 0, 8); /* Make sure the null padding is null */
1041         *wsaddrlen = sizeof(struct WS_sockaddr_in);
1042         return 0;
1043     }
1044     case AF_UNSPEC: {
1045         memset(wsaddr,0,*wsaddrlen);
1046         return 0;
1047     }
1048     default:
1049         FIXME("Unknown address family %d\n", uaddr->sa_family);
1050         return -1;
1051     }
1052     return res;
1053 }
1054 
1055 /**************************************************************************
1056  * Functions for handling overlapped I/O
1057  **************************************************************************/
1058 
1059 /* user APC called upon async completion */
1060 static void WINAPI ws2_async_apc( void *arg, IO_STATUS_BLOCK *iosb, ULONG reserved )
1061 {
1062     ws2_async *wsa = arg;
1063 
1064     if (wsa->completion_func) wsa->completion_func( NtStatusToWSAError(iosb->u.Status),
1065                                                     iosb->Information, wsa->user_overlapped,
1066                                                     wsa->flags );
1067     HeapFree( GetProcessHeap(), 0, wsa );
1068 }
1069 
1070 /***********************************************************************
1071  *              WS2_recv                (INTERNAL)
1072  *
1073  * Workhorse for both synchronous and asynchronous recv() operations.
1074  */
1075 static int WS2_recv( int fd, struct ws2_async *wsa )
1076 {
1077     struct msghdr hdr;
1078     union generic_unix_sockaddr unix_sockaddr;
1079     int n;
1080 
1081     hdr.msg_name = NULL;
1082 
1083     if (wsa->addr)
1084     {
1085         hdr.msg_namelen = sizeof(unix_sockaddr);
1086         hdr.msg_name = &unix_sockaddr;
1087     }
1088     else
1089         hdr.msg_namelen = 0;
1090 
1091     hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1092     hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1093 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1094     hdr.msg_accrights = NULL;
1095     hdr.msg_accrightslen = 0;
1096 #else
1097     hdr.msg_control = NULL;
1098     hdr.msg_controllen = 0;
1099     hdr.msg_flags = 0;
1100 #endif
1101 
1102     if ( (n = recvmsg(fd, &hdr, wsa->flags)) == -1 )
1103         return -1;
1104 
1105     /* if this socket is connected and lpFrom is not NULL, Linux doesn't give us
1106      * msg_name and msg_namelen from recvmsg, but it does set msg_namelen to zero.
1107      *
1108      * quoting linux 2.6 net/ipv4/tcp.c:
1109      *  "According to UNIX98, msg_name/msg_namelen are ignored
1110      *  on connected socket. I was just happy when found this 8) --ANK"
1111      *
1112      * likewise MSDN says that lpFrom and lpFromlen are ignored for
1113      * connection-oriented sockets, so don't try to update lpFrom.
1114      */
1115     if (wsa->addr && hdr.msg_namelen)
1116         ws_sockaddr_u2ws( &unix_sockaddr.addr, wsa->addr, wsa->addrlen.ptr );
1117 
1118     return n;
1119 }
1120 
1121 /***********************************************************************
1122  *              WS2_async_recv          (INTERNAL)
1123  *
1124  * Handler for overlapped recv() operations.
1125  */
1126 static NTSTATUS WS2_async_recv( void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, ULONG_PTR *total )
1127 {
1128     ws2_async* wsa = user;
1129     int result = 0, fd;
1130 
1131     switch (status)
1132     {
1133     case STATUS_ALERTED:
1134         if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_READ_DATA, &fd, NULL ) ))
1135             break;
1136 
1137         result = WS2_recv( fd, wsa );
1138         wine_server_release_fd( wsa->hSocket, fd );
1139         if (result >= 0)
1140         {
1141             status = STATUS_SUCCESS;
1142             _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1143         }
1144         else
1145         {
1146             if (errno == EINTR || errno == EAGAIN)
1147             {
1148                 status = STATUS_PENDING;
1149                 _enable_event( wsa->hSocket, FD_READ, 0, 0 );
1150             }
1151             else
1152             {
1153                 result = 0;
1154                 status = wsaErrno(); /* FIXME: is this correct ???? */
1155             }
1156         }
1157         break;
1158     }
1159     if (status != STATUS_PENDING)
1160     {
1161         iosb->u.Status = status;
1162         iosb->Information = *total = result;
1163     }
1164     return status;
1165 }
1166 
1167 /***********************************************************************
1168  *              WS2_send                (INTERNAL)
1169  *
1170  * Workhorse for both synchronous and asynchronous send() operations.
1171  */
1172 static int WS2_send( int fd, struct ws2_async *wsa )
1173 {
1174     struct msghdr hdr;
1175     union generic_unix_sockaddr unix_addr;
1176 
1177     hdr.msg_name = NULL;
1178     hdr.msg_namelen = 0;
1179 
1180     if (wsa->addr)
1181     {
1182         hdr.msg_name = &unix_addr;
1183         hdr.msg_namelen = ws_sockaddr_ws2u( wsa->addr, wsa->addrlen.val, &unix_addr );
1184         if ( !hdr.msg_namelen )
1185         {
1186             errno = EFAULT;
1187             return -1;
1188         }
1189 
1190 #if defined(HAVE_IPX) && defined(SOL_IPX)
1191         if(wsa->addr->sa_family == WS_AF_IPX)
1192         {
1193             struct sockaddr_ipx* uipx = (struct sockaddr_ipx*)hdr.msg_name;
1194             int val=0;
1195             unsigned int len=sizeof(int);
1196 
1197             /* The packet type is stored at the ipx socket level; At least the linux kernel seems
1198              *  to do something with it in case hdr.msg_name is NULL. Nonetheless can we use it to store
1199              *  the packet type and then we can retrieve it using getsockopt. After that we can set the
1200              *  ipx type in the sockaddr_opx structure with the stored value.
1201              */
1202             if(getsockopt(fd, SOL_IPX, IPX_TYPE, &val, &len) != -1)
1203                 uipx->sipx_type = val;
1204         }
1205 #endif
1206     }
1207 
1208     hdr.msg_iov = wsa->iovec + wsa->first_iovec;
1209     hdr.msg_iovlen = wsa->n_iovecs - wsa->first_iovec;
1210 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
1211     hdr.msg_accrights = NULL;
1212     hdr.msg_accrightslen = 0;
1213 #else
1214     hdr.msg_control = NULL;
1215     hdr.msg_controllen = 0;
1216     hdr.msg_flags = 0;
1217 #endif
1218 
1219     return sendmsg(fd, &hdr, wsa->flags);
1220 }
1221 
1222 /***********************************************************************
1223  *              WS2_async_send          (INTERNAL)
1224  *
1225  * Handler for overlapped send() operations.
1226  */
1227 static NTSTATUS WS2_async_send(void* user, IO_STATUS_BLOCK* iosb, NTSTATUS status, ULONG_PTR *total )
1228 {
1229     ws2_async* wsa = user;
1230     int result = 0, fd;
1231 
1232     switch (status)
1233     {
1234     case STATUS_ALERTED:
1235         if ((status = wine_server_handle_to_fd( wsa->hSocket, FILE_WRITE_DATA, &fd, NULL ) ))
1236             break;
1237 
1238         /* check to see if the data is ready (non-blocking) */
1239         result = WS2_send( fd, wsa );
1240         wine_server_release_fd( wsa->hSocket, fd );
1241 
1242         if (result >= 0)
1243         {
1244             int totalLength = 0;
1245             unsigned int i;
1246             status = STATUS_SUCCESS;
1247             for (i = 0; i < wsa->n_iovecs; i++)
1248                 totalLength += wsa->iovec[i].iov_len;
1249             if (result < totalLength)
1250                 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1251         }
1252         else
1253         {
1254             if (errno == EINTR || errno == EAGAIN)
1255             {
1256                 status = STATUS_PENDING;
1257                 _enable_event( wsa->hSocket, FD_WRITE, 0, 0 );
1258             }
1259             else
1260             {
1261                 /* We set the status to a winsock error code and check for that
1262                    later in NtStatusToWSAError () */
1263                 status = wsaErrno();
1264                 result = 0;
1265             }
1266         }
1267         break;
1268     }
1269     if (status != STATUS_PENDING)
1270     {
1271         iosb->u.Status = status;
1272         iosb->Information = *total = result;
1273     }
1274     return status;
1275 }
1276 
1277 /***********************************************************************
1278  *              WS2_async_shutdown      (INTERNAL)
1279  *
1280  * Handler for shutdown() operations on overlapped sockets.
1281  */
1282 static NTSTATUS WS2_async_shutdown( void* user, PIO_STATUS_BLOCK iosb, NTSTATUS status )
1283 {
1284     ws2_async* wsa = user;
1285     int fd, err = 1;
1286 
1287     switch (status)
1288     {
1289     case STATUS_ALERTED:
1290         if ((status = wine_server_handle_to_fd( wsa->hSocket, 0, &fd, NULL ) ))
1291             break;
1292 
1293         switch ( wsa->type )
1294         {
1295         case ASYNC_TYPE_READ:   err = shutdown( fd, 0 );  break;
1296         case ASYNC_TYPE_WRITE:  err = shutdown( fd, 1 );  break;
1297         }
1298         wine_server_release_fd( wsa->hSocket, fd );
1299         status = err ? wsaErrno() : STATUS_SUCCESS;
1300         break;
1301     }
1302     iosb->u.Status = status;
1303     return status;
1304 }
1305 
1306 /***********************************************************************
1307  *  WS2_register_async_shutdown         (INTERNAL)
1308  *
1309  * Helper function for WS_shutdown() on overlapped sockets.
1310  */
1311 static int WS2_register_async_shutdown( SOCKET s, int type )
1312 {
1313     struct ws2_async *wsa;
1314     NTSTATUS status;
1315 
1316     TRACE("s %ld type %d\n", s, type);
1317 
1318     wsa = HeapAlloc( GetProcessHeap(), 0, sizeof(*wsa) );
1319     if ( !wsa )
1320         return WSAEFAULT;
1321 
1322     wsa->hSocket         = SOCKET2HANDLE(s);
1323     wsa->type            = type;
1324     wsa->completion_func = NULL;
1325 
1326     SERVER_START_REQ( register_async )
1327     {
1328         req->handle = wsa->hSocket;
1329         req->type   = type;
1330         req->async.callback = WS2_async_shutdown;
1331         req->async.iosb     = &wsa->local_iosb;
1332         req->async.arg      = wsa;
1333         req->async.apc      = ws2_async_apc;
1334         req->async.cvalue   = 0;
1335         status = wine_server_call( req );
1336     }
1337     SERVER_END_REQ;
1338 
1339     if (status != STATUS_PENDING)
1340     {
1341         HeapFree( GetProcessHeap(), 0, wsa );
1342         return NtStatusToWSAError( status );
1343     }
1344     return 0;
1345 }
1346 
1347 /***********************************************************************
1348  *              accept          (WS2_32.1)
1349  */
1350 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr,
1351                                  int *addrlen32)
1352 {
1353     SOCKET as;
1354     BOOL is_blocking;
1355 
1356     TRACE("socket %04lx\n", s );
1357     is_blocking = _is_blocking(s);
1358 
1359     do {
1360         if (is_blocking)
1361         {
1362             int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1363             if (fd == -1) return INVALID_SOCKET;
1364             /* block here */
1365             do_block(fd, POLLIN, -1);
1366             _sync_sock_state(s); /* let wineserver notice connection */
1367             release_sock_fd( s, fd );
1368             /* retrieve any error codes from it */
1369             SetLastError(_get_sock_error(s, FD_ACCEPT_BIT));
1370             /* FIXME: care about the error? */
1371         }
1372         SERVER_START_REQ( accept_socket )
1373         {
1374             req->lhandle    = SOCKET2HANDLE(s);
1375             req->access     = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
1376             req->attributes = OBJ_INHERIT;
1377             set_error( wine_server_call( req ) );
1378             as = HANDLE2SOCKET( reply->handle );
1379         }
1380         SERVER_END_REQ;
1381         if (as)
1382         {
1383             if (addr) WS_getpeername(as, addr, addrlen32);
1384             return as;
1385         }
1386     } while (is_blocking);
1387     return INVALID_SOCKET;
1388 }
1389 
1390 /***********************************************************************
1391  *              bind                    (WS2_32.2)
1392  */
1393 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
1394 {
1395     int fd = get_sock_fd( s, 0, NULL );
1396     int res = SOCKET_ERROR;
1397 
1398     TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1399 
1400     if (fd != -1)
1401     {
1402         if (!name || (name->sa_family && !SUPPORTED_PF(name->sa_family)))
1403         {
1404             SetLastError(WSAEAFNOSUPPORT);
1405         }
1406         else
1407         {
1408             union generic_unix_sockaddr uaddr;
1409             unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1410             if (!uaddrlen)
1411             {
1412                 SetLastError(WSAEFAULT);
1413             }
1414             else
1415             {
1416 #ifdef IPV6_V6ONLY
1417                 const struct sockaddr_in6 *in6 = (const struct sockaddr_in6*) &uaddr;
1418                 if (name->sa_family == WS_AF_INET6 &&
1419                     !memcmp(&in6->sin6_addr, &in6addr_any, sizeof(struct in6_addr)))
1420                 {
1421                     int enable = 1;
1422                     if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &enable, sizeof(enable)) == -1)
1423                     {
1424                         release_sock_fd( s, fd );
1425                         SetLastError(WSAEAFNOSUPPORT);
1426                         return INVALID_SOCKET;
1427                     }
1428                 }
1429 #endif
1430                 if (name->sa_family == WS_AF_INET)
1431                 {
1432                     struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
1433                     if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
1434                     {
1435                         /* Trying to bind to the default host interface, using
1436                          * INADDR_ANY instead*/
1437                         WARN("Trying to bind to magic IP address, using "
1438                              "INADDR_ANY instead.\n");
1439                         in4->sin_addr.s_addr = htonl(WS_INADDR_ANY);
1440                     }
1441                 }
1442                 if (bind(fd, &uaddr.addr, uaddrlen) < 0)
1443                 {
1444                     int loc_errno = errno;
1445                     WARN("\tfailure - errno = %i\n", errno);
1446                     errno = loc_errno;
1447                     switch (errno)
1448                     {
1449                     case EBADF:
1450                         SetLastError(WSAENOTSOCK);
1451                         break;
1452                     case EADDRNOTAVAIL:
1453                         SetLastError(WSAEINVAL);
1454                         break;
1455                     default:
1456                         SetLastError(wsaErrno());
1457                         break;
1458                     }
1459                 }
1460                 else
1461                 {
1462                     res=0; /* success */
1463                 }
1464             }
1465         }
1466         release_sock_fd( s, fd );
1467     }
1468     return res;
1469 }
1470 
1471 /***********************************************************************
1472  *              closesocket             (WS2_32.3)
1473  */
1474 int WINAPI WS_closesocket(SOCKET s)
1475 {
1476     TRACE("socket %04lx\n", s);
1477     if (CloseHandle(SOCKET2HANDLE(s))) return 0;
1478     return SOCKET_ERROR;
1479 }
1480 
1481 /***********************************************************************
1482  *              connect         (WS2_32.4)
1483  */
1484 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
1485 {
1486     int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
1487 
1488     TRACE("socket %04lx, ptr %p %s, length %d\n", s, name, debugstr_sockaddr(name), namelen);
1489 
1490     if (fd != -1)
1491     {
1492         union generic_unix_sockaddr uaddr;
1493         unsigned int uaddrlen = ws_sockaddr_ws2u(name, namelen, &uaddr);
1494 
1495         if (!uaddrlen)
1496         {
1497             SetLastError(WSAEFAULT);
1498         }
1499         else
1500         {
1501             if (name->sa_family == WS_AF_INET)
1502             {
1503                 struct sockaddr_in *in4 = (struct sockaddr_in*) &uaddr;
1504                 if (memcmp(&in4->sin_addr, magic_loopback_addr, 4) == 0)
1505                 {
1506                     /* Trying to connect to magic replace-loopback address,
1507                      * assuming we really want to connect to localhost */
1508                     TRACE("Trying to connect to magic IP address, using "
1509                          "INADDR_LOOPBACK instead.\n");
1510                     in4->sin_addr.s_addr = htonl(WS_INADDR_LOOPBACK);
1511                 }
1512             }
1513 
1514             if (connect(fd, &uaddr.addr, uaddrlen) == 0)
1515                 goto connect_success;
1516         }
1517 
1518         if (errno == EINPROGRESS)
1519         {
1520             /* tell wineserver that a connection is in progress */
1521             _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1522                           FD_CONNECT|FD_READ|FD_WRITE,
1523                           FD_WINE_CONNECTED|FD_WINE_LISTENING);
1524             if (_is_blocking(s))
1525             {
1526                 int result;
1527                 /* block here */
1528                 do_block(fd, POLLIN | POLLOUT, -1);
1529                 _sync_sock_state(s); /* let wineserver notice connection */
1530                 /* retrieve any error codes from it */
1531                 result = _get_sock_error(s, FD_CONNECT_BIT);
1532                 if (result)
1533                     SetLastError(result);
1534                 else
1535                 {
1536                     goto connect_success;
1537                 }
1538             }
1539             else
1540             {
1541                 SetLastError(WSAEWOULDBLOCK);
1542             }
1543         }
1544         else
1545         {
1546             SetLastError(wsaErrno());
1547         }
1548         release_sock_fd( s, fd );
1549     }
1550     return SOCKET_ERROR;
1551 
1552 connect_success:
1553     release_sock_fd( s, fd );
1554     _enable_event(SOCKET2HANDLE(s), FD_CONNECT|FD_READ|FD_WRITE,
1555                   FD_WINE_CONNECTED|FD_READ|FD_WRITE,
1556                   FD_CONNECT|FD_WINE_LISTENING);
1557     return 0;
1558 }
1559 
1560 /***********************************************************************
1561  *              WSAConnect             (WS2_32.30)
1562  */
1563 int WINAPI WSAConnect( SOCKET s, const struct WS_sockaddr* name, int namelen,
1564                        LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
1565                        LPQOS lpSQOS, LPQOS lpGQOS )
1566 {
1567     if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
1568         FIXME("unsupported parameters!\n");
1569     return WS_connect( s, name, namelen );
1570 }
1571 
1572 
1573 /***********************************************************************
1574  *              getpeername             (WS2_32.5)
1575  */
1576 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
1577 {
1578     int fd;
1579     int res;
1580 
1581     TRACE("socket: %04lx, ptr %p, len %08x\n", s, name, *namelen);
1582 
1583     /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1584     if( (name == NULL) || (namelen == NULL) )
1585     {
1586         SetLastError( WSAEFAULT );
1587         return SOCKET_ERROR;
1588     }
1589 
1590     fd = get_sock_fd( s, 0, NULL );
1591     res = SOCKET_ERROR;
1592 
1593     if (fd != -1)
1594     {
1595         union generic_unix_sockaddr uaddr;
1596         unsigned int uaddrlen = sizeof(uaddr);
1597 
1598         if (getpeername(fd, &uaddr.addr, &uaddrlen) != 0)
1599         {
1600             SetLastError(wsaErrno());
1601         }
1602         else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
1603         {
1604             /* The buffer was too small */
1605             SetLastError(WSAEFAULT);
1606         }
1607         else
1608         {
1609             res=0;
1610         }
1611         release_sock_fd( s, fd );
1612     }
1613     return res;
1614 }
1615 
1616 /***********************************************************************
1617  *              getsockname             (WS2_32.6)
1618  */
1619 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
1620 {
1621     int fd;
1622     int res;
1623 
1624     TRACE("socket: %04lx, ptr %p, len %8x\n", s, name, *namelen);
1625 
1626     /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1627     if( (name == NULL) || (namelen == NULL) )
1628     {
1629         SetLastError( WSAEFAULT );
1630         return SOCKET_ERROR;
1631     }
1632 
1633     fd = get_sock_fd( s, 0, NULL );
1634     res = SOCKET_ERROR;
1635 
1636     if (fd != -1)
1637     {
1638         union generic_unix_sockaddr uaddr;
1639         unsigned int uaddrlen = sizeof(uaddr);
1640 
1641         if (getsockname(fd, &uaddr.addr, &uaddrlen) != 0)
1642         {
1643             SetLastError(wsaErrno());
1644         }
1645         else if (!is_sockaddr_bound(&uaddr.addr, uaddrlen))
1646         {
1647             SetLastError(WSAEINVAL);
1648         }
1649         else if (ws_sockaddr_u2ws(&uaddr.addr, name, namelen) != 0)
1650         {
1651             /* The buffer was too small */
1652             SetLastError(WSAEFAULT);
1653         }
1654         else
1655         {
1656             res=0;
1657         }
1658         release_sock_fd( s, fd );
1659     }
1660     return res;
1661 }
1662 
1663 /***********************************************************************
1664  *              getsockopt              (WS2_32.7)
1665  */
1666 INT WINAPI WS_getsockopt(SOCKET s, INT level,
1667                                   INT optname, char *optval, INT *optlen)
1668 {
1669     int fd;
1670     INT ret = 0;
1671 
1672     TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
1673           s, level, optname, optval, *optlen);
1674 
1675     switch(level)
1676     {
1677     case WS_SOL_SOCKET:
1678     {
1679         switch(optname)
1680         {
1681         /* Handle common cases. The special cases are below, sorted
1682          * alphabetically */
1683         case WS_SO_ACCEPTCONN:
1684         case WS_SO_BROADCAST:
1685         case WS_SO_DEBUG:
1686         case WS_SO_ERROR:
1687         case WS_SO_KEEPALIVE:
1688         case WS_SO_OOBINLINE:
1689         case WS_SO_RCVBUF:
1690         case WS_SO_REUSEADDR:
1691         case WS_SO_SNDBUF:
1692         case WS_SO_TYPE:
1693             if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1694                 return SOCKET_ERROR;
1695             convert_sockopt(&level, &optname);
1696             if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
1697             {
1698                 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1699                 ret = SOCKET_ERROR;
1700             }
1701             release_sock_fd( s, fd );
1702             return ret;
1703 
1704         case WS_SO_DONTLINGER:
1705         {
1706             struct linger lingval;
1707             unsigned int len = sizeof(struct linger);
1708 
1709             if (!optlen || *optlen < sizeof(BOOL)|| !optval)
1710             {
1711                 SetLastError(WSAEFAULT);
1712                 return SOCKET_ERROR;
1713             }
1714             if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1715                 return SOCKET_ERROR;
1716 
1717             if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
1718             {
1719                 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1720                 ret = SOCKET_ERROR;
1721             }
1722             else
1723             {
1724                 *(BOOL *)optval = (lingval.l_onoff) ? FALSE : TRUE;
1725                 *optlen = sizeof(BOOL);
1726             }
1727 
1728             release_sock_fd( s, fd );
1729             return ret;
1730         }
1731 
1732         /* As mentioned in setsockopt, Windows ignores this, so we
1733          * always return true here */
1734         case WS_SO_DONTROUTE:
1735             if (!optlen || *optlen < sizeof(BOOL) || !optval)
1736             {
1737                 SetLastError(WSAEFAULT);
1738                 return SOCKET_ERROR;
1739             }
1740             *(BOOL *)optval = TRUE;
1741             *optlen = sizeof(BOOL);
1742             return 0;
1743 
1744         case WS_SO_LINGER:
1745         {
1746             struct linger lingval;
1747             unsigned int len = sizeof(struct linger);
1748 
1749             /* struct linger and LINGER have different sizes */
1750             if (!optlen || *optlen < sizeof(LINGER) || !optval)
1751             {
1752                 SetLastError(WSAEFAULT);
1753                 return SOCKET_ERROR;
1754             }
1755             if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1756                 return SOCKET_ERROR;
1757 
1758             if (getsockopt(fd, SOL_SOCKET, SO_LINGER, &lingval, &len) != 0 )
1759             {
1760                 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1761                 ret = SOCKET_ERROR;
1762             }
1763             else
1764             {
1765                 ((LINGER *)optval)->l_onoff = lingval.l_onoff;
1766                 ((LINGER *)optval)->l_linger = lingval.l_linger;
1767                 *optlen = sizeof(struct linger);
1768             }
1769 
1770             release_sock_fd( s, fd );
1771             return ret;
1772         }
1773 
1774         case WS_SO_MAX_MSG_SIZE:
1775             if (!optlen || *optlen < sizeof(int) || !optval)
1776             {
1777                 SetLastError(WSAEFAULT);
1778                 return SOCKET_ERROR;
1779             }
1780             TRACE("getting global SO_MAX_MSG_SIZE = 65507\n");
1781             *(int *)optval = 65507;
1782             *optlen = sizeof(int);
1783             return 0;
1784 
1785         /* SO_OPENTYPE does not require a valid socket handle. */
1786         case WS_SO_OPENTYPE:
1787             if (!optlen || *optlen < sizeof(int) || !optval)
1788             {
1789                 SetLastError(WSAEFAULT);
1790                 return SOCKET_ERROR;
1791             }
1792             *(int *)optval = get_per_thread_data()->opentype;
1793             *optlen = sizeof(int);
1794             TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
1795             return 0;
1796 
1797 #ifdef SO_RCVTIMEO
1798         case WS_SO_RCVTIMEO:
1799 #endif
1800 #ifdef SO_SNDTIMEO
1801         case WS_SO_SNDTIMEO:
1802 #endif
1803 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
1804         {
1805             struct timeval tv;
1806             unsigned int len = sizeof(struct timeval);
1807 
1808             if (!optlen || *optlen < sizeof(int)|| !optval)
1809             {
1810                 SetLastError(WSAEFAULT);
1811                 return SOCKET_ERROR;
1812             }
1813             if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1814                 return SOCKET_ERROR;
1815 
1816             convert_sockopt(&level, &optname);
1817             if (getsockopt(fd, level, optname, &tv, &len) != 0 )
1818             {
1819                 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1820                 ret = SOCKET_ERROR;
1821             }
1822             else
1823             {
1824                 *(int *)optval = tv.tv_sec * 1000 + tv.tv_usec / 1000;
1825                 *optlen = sizeof(int);
1826             }
1827 
1828             release_sock_fd( s, fd );
1829             return ret;
1830         }
1831 #endif
1832         default:
1833             TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
1834             SetLastError(WSAENOPROTOOPT);
1835             return SOCKET_ERROR;
1836         } /* end switch(optname) */
1837     }/* end case WS_SOL_SOCKET */
1838 #ifdef HAVE_IPX
1839     case NSPROTO_IPX:
1840     {
1841         struct WS_sockaddr_ipx addr;
1842         IPX_ADDRESS_DATA *data;
1843         int namelen;
1844         switch(optname)
1845         {
1846         case IPX_PTYPE:
1847             if ((fd = get_sock_fd( s, 0, NULL )) == -1) return SOCKET_ERROR;
1848 #ifdef SOL_IPX
1849             if(getsockopt(fd, SOL_IPX, IPX_TYPE, optval, (unsigned int*)optlen) == -1)
1850             {
1851                 ret = SOCKET_ERROR;
1852             }
1853 #else
1854             {
1855                 struct ipx val;
1856                 socklen_t len=sizeof(struct ipx);
1857                 if(getsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, &len) == -1 )
1858                     ret = SOCKET_ERROR;
1859                 else
1860                     *optval = (int)val.ipx_pt;
1861             }
1862 #endif
1863             TRACE("ptype: %d (fd: %d)\n", *(int*)optval, fd);
1864             release_sock_fd( s, fd );
1865             return ret;
1866 
1867         case IPX_ADDRESS:
1868             /*
1869             *  On a Win2000 system with one network card there are usually
1870             *  three ipx devices one with a speed of 28.8kbps, 10Mbps and 100Mbps.
1871             *  Using this call you can then retrieve info about this all.
1872             *  In case of Linux it is a bit different. Usually you have
1873             *  only "one" device active and further it is not possible to
1874             *  query things like the linkspeed.
1875             */
1876             FIXME("IPX_ADDRESS\n");
1877             namelen = sizeof(struct WS_sockaddr_ipx);
1878             memset(&addr, 0, sizeof(struct WS_sockaddr_ipx));
1879             WS_getsockname(s, (struct WS_sockaddr*)&addr, &namelen);
1880 
1881             data = (IPX_ADDRESS_DATA*)optval;
1882                     memcpy(data->nodenum,addr.sa_nodenum,sizeof(data->nodenum));
1883                     memcpy(data->netnum,addr.sa_netnum,sizeof(data->netnum));
1884             data->adapternum = 0;
1885             data->wan = FALSE; /* We are not on a wan for now .. */
1886             data->status = FALSE; /* Since we are not on a wan, the wan link isn't up */
1887             data->maxpkt = 1467; /* This value is the default one, at least on Win2k/WinXP */
1888             data->linkspeed = 100000; /* Set the line speed in 100bit/s to 10 Mbit;
1889                                        * note 1MB = 1000kB in this case */
1890             return 0;
1891 
1892         case IPX_MAX_ADAPTER_NUM:
1893             FIXME("IPX_MAX_ADAPTER_NUM\n");
1894             *(int*)optval = 1; /* As noted under IPX_ADDRESS we have just one card. */
1895             return 0;
1896 
1897         default:
1898             FIXME("IPX optname:%x\n", optname);
1899             return SOCKET_ERROR;
1900         }/* end switch(optname) */
1901     } /* end case NSPROTO_IPX */
1902 #endif
1903     /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
1904     case WS_IPPROTO_TCP:
1905         switch(optname)
1906         {
1907         case WS_TCP_NODELAY:
1908             if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1909                 return SOCKET_ERROR;
1910             convert_sockopt(&level, &optname);
1911             if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
1912             {
1913                 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1914                 ret = SOCKET_ERROR;
1915             }
1916             release_sock_fd( s, fd );
1917             return ret;
1918         }
1919         FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
1920         return SOCKET_ERROR;
1921 
1922     case WS_IPPROTO_IP:
1923         switch(optname)
1924         {
1925         case WS_IP_ADD_MEMBERSHIP:
1926         case WS_IP_DROP_MEMBERSHIP:
1927 #ifdef IP_HDRINCL
1928         case WS_IP_HDRINCL:
1929 #endif
1930         case WS_IP_MULTICAST_IF:
1931         case WS_IP_MULTICAST_LOOP:
1932         case WS_IP_MULTICAST_TTL:
1933         case WS_IP_OPTIONS:
1934         case WS_IP_TOS:
1935         case WS_IP_TTL:
1936             if ( (fd = get_sock_fd( s, 0, NULL )) == -1)
1937                 return SOCKET_ERROR;
1938             convert_sockopt(&level, &optname);
1939             if (getsockopt(fd, level, optname, optval, (unsigned int *)optlen) != 0 )
1940             {
1941                 SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1942                 ret = SOCKET_ERROR;
1943             }
1944             release_sock_fd( s, fd );
1945             return ret;
1946         case WS_IP_DONTFRAGMENT:
1947             FIXME("WS_IP_DONTFRAGMENT is always false!\n");
1948             *(BOOL*)optval = FALSE;
1949             return 0;
1950         }
1951         FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
1952         return SOCKET_ERROR;
1953 
1954     default:
1955         FIXME("Unknown level: 0x%08x\n", level);
1956         return SOCKET_ERROR;
1957     } /* end switch(level) */
1958 }
1959 
1960 /***********************************************************************
1961  *              htonl                   (WINSOCK.8)
1962  *              htonl                   (WS2_32.8)
1963  */
1964 WS_u_long WINAPI WS_htonl(WS_u_long hostlong)
1965 {
1966     return htonl(hostlong);
1967 }
1968 
1969 
1970 /***********************************************************************
1971  *              htons                   (WINSOCK.9)
1972  *              htons                   (WS2_32.9)
1973  */
1974 WS_u_short WINAPI WS_htons(WS_u_short hostshort)
1975 {
1976     return htons(hostshort);
1977 }
1978 
1979 /***********************************************************************
1980  *              WSAHtonl                (WS2_32.46)
1981  *  From MSDN description of error codes, this function should also
1982  *  check if WinSock has been initialized and the socket is a valid
1983  *  socket. But why? This function only translates a host byte order
1984  *  u_long into a network byte order u_long...
1985  */
1986 int WINAPI WSAHtonl(SOCKET s, WS_u_long hostlong, WS_u_long *lpnetlong)
1987 {
1988     if (lpnetlong)
1989     {
1990         *lpnetlong = htonl(hostlong);
1991         return 0;
1992     }
1993     WSASetLastError(WSAEFAULT);
1994     return SOCKET_ERROR;
1995 }
1996 
1997 /***********************************************************************
1998  *              WSAHtons                (WS2_32.47)
1999  *  From MSDN description of error codes, this function should also
2000  *  check if WinSock has been initialized and the socket is a valid
2001  *  socket. But why? This function only translates a host byte order
2002  *  u_short into a network byte order u_short...
2003  */
2004 int WINAPI WSAHtons(SOCKET s, WS_u_short hostshort, WS_u_short *lpnetshort)
2005 {
2006 
2007     if (lpnetshort)
2008     {
2009         *lpnetshort = htons(hostshort);
2010         return 0;
2011     }
2012     WSASetLastError(WSAEFAULT);
2013     return SOCKET_ERROR;
2014 }
2015 
2016 
2017 /***********************************************************************
2018  *              inet_addr               (WINSOCK.10)
2019  *              inet_addr               (WS2_32.11)
2020  */
2021 WS_u_long WINAPI WS_inet_addr(const char *cp)
2022 {
2023     if (!cp) return INADDR_NONE;
2024     return inet_addr(cp);
2025 }
2026 
2027 
2028 /***********************************************************************
2029  *              ntohl                   (WINSOCK.14)
2030  *              ntohl                   (WS2_32.14)
2031  */
2032 WS_u_long WINAPI WS_ntohl(WS_u_long netlong)
2033 {
2034     return ntohl(netlong);
2035 }
2036 
2037 
2038 /***********************************************************************
2039  *              ntohs                   (WINSOCK.15)
2040  *              ntohs                   (WS2_32.15)
2041  */
2042 WS_u_short WINAPI WS_ntohs(WS_u_short netshort)
2043 {
2044     return ntohs(netshort);
2045 }
2046 
2047 
2048 /***********************************************************************
2049  *              inet_ntoa               (WS2_32.12)
2050  */
2051 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
2052 {
2053   /* use "buffer for dummies" here because some applications have a
2054    * propensity to decode addresses in ws_hostent structure without
2055    * saving them first...
2056    */
2057     static char dbuffer[16]; /* Yes, 16: 4*3 digits + 3 '.' + 1 '\0' */
2058 
2059     char* s = inet_ntoa(*((struct in_addr*)&in));
2060     if( s )
2061     {
2062         strcpy(dbuffer, s);
2063         return dbuffer;
2064     }
2065     SetLastError(wsaErrno());
2066     return NULL;
2067 }
2068 
2069 /**********************************************************************
2070  *              WSAIoctl                (WS2_32.50)
2071  *
2072  */
2073 INT WINAPI WSAIoctl(SOCKET s,
2074                     DWORD   dwIoControlCode,
2075                     LPVOID  lpvInBuffer,
2076                     DWORD   cbInBuffer,
2077                     LPVOID  lpbOutBuffer,
2078                     DWORD   cbOutBuffer,
2079                     LPDWORD lpcbBytesReturned,
2080                     LPWSAOVERLAPPED lpOverlapped,
2081                     LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
2082 {
2083    TRACE("%ld, 0x%08x, %p, %d, %p, %d, %p, %p, %p\n",
2084        s, dwIoControlCode, lpvInBuffer, cbInBuffer, lpbOutBuffer,
2085        cbOutBuffer, lpcbBytesReturned, lpOverlapped, lpCompletionRoutine);
2086 
2087    switch( dwIoControlCode )
2088    {
2089    case WS_FIONBIO:
2090         if (cbInBuffer != sizeof(WS_u_long)) {
2091             WSASetLastError(WSAEFAULT);
2092             return SOCKET_ERROR;
2093         }
2094         return WS_ioctlsocket( s, WS_FIONBIO, lpvInBuffer);
2095 
2096    case WS_FIONREAD:
2097         if (cbOutBuffer != sizeof(WS_u_long)) {
2098             WSASetLastError(WSAEFAULT);
2099             return SOCKET_ERROR;
2100         }
2101         return WS_ioctlsocket( s, WS_FIONREAD, lpbOutBuffer);
2102 
2103    case WS_SIO_GET_INTERFACE_LIST:
2104        {
2105            INTERFACE_INFO* intArray = (INTERFACE_INFO*)lpbOutBuffer;
2106            DWORD size, numInt, apiReturn;
2107            int fd;
2108 
2109            TRACE("-> SIO_GET_INTERFACE_LIST request\n");
2110 
2111            if (!lpbOutBuffer)
2112            {
2113                WSASetLastError(WSAEFAULT);
2114                return SOCKET_ERROR;
2115            }
2116            if (!lpcbBytesReturned)
2117            {
2118                WSASetLastError(WSAEFAULT);
2119                return SOCKET_ERROR;
2120            }
2121 
2122            fd = get_sock_fd( s, 0, NULL );
2123            if (fd == -1) return SOCKET_ERROR;
2124 
2125            apiReturn = GetAdaptersInfo(NULL, &size);
2126            if (apiReturn == ERROR_NO_DATA)
2127            {
2128                numInt = 0;
2129            }
2130            else if (apiReturn == ERROR_BUFFER_OVERFLOW)
2131            {
2132                PIP_ADAPTER_INFO table = HeapAlloc(GetProcessHeap(),0,size);
2133 
2134                if (table)
2135                {
2136                   if (GetAdaptersInfo(table, &size) == NO_ERROR)
2137                   {
2138                      PIP_ADAPTER_INFO ptr;
2139 
2140                      if (size*sizeof(INTERFACE_INFO)/sizeof(IP_ADAPTER_INFO) > cbOutBuffer)
2141                      {
2142                         WARN("Buffer too small = %u, cbOutBuffer = %u\n", size, cbOutBuffer);
2143                         HeapFree(GetProcessHeap(),0,table);
2144                         release_sock_fd( s, fd );
2145                         WSASetLastError(WSAEFAULT);
2146                         return SOCKET_ERROR;
2147                      }
2148                      for (ptr = table, numInt = 0; ptr;
2149                       ptr = ptr->Next, intArray++, numInt++)
2150                      {
2151                         unsigned int addr, mask, bcast;
2152                         struct ifreq ifInfo;
2153 
2154                         /* Socket Status Flags */
2155                         lstrcpynA(ifInfo.ifr_name, ptr->AdapterName, IFNAMSIZ);
2156                         if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
2157                         {
2158                            ERR("Error obtaining status flags for socket!\n");
2159                            HeapFree(GetProcessHeap(),0,table);
2160                            release_sock_fd( s, fd );
2161                            WSASetLastError(WSAEINVAL);
2162                            return SOCKET_ERROR;
2163                         }
2164                         else
2165                         {
2166                            /* set flags; the values of IFF_* are not the same
2167                               under Linux and Windows, therefore must generate
2168                               new flags */
2169                            intArray->iiFlags = 0;
2170                            if (ifInfo.ifr_flags & IFF_BROADCAST)
2171                               intArray->iiFlags |= WS_IFF_BROADCAST;
2172 #ifdef IFF_POINTOPOINT
2173                            if (ifInfo.ifr_flags & IFF_POINTOPOINT)
2174                               intArray->iiFlags |= WS_IFF_POINTTOPOINT;
2175 #endif
2176                            if (ifInfo.ifr_flags & IFF_LOOPBACK)
2177                               intArray->iiFlags |= WS_IFF_LOOPBACK;
2178                            if (ifInfo.ifr_flags & IFF_UP)
2179                               intArray->iiFlags |= WS_IFF_UP;
2180                            if (ifInfo.ifr_flags & IFF_MULTICAST)
2181                               intArray->iiFlags |= WS_IFF_MULTICAST;
2182                         }
2183 
2184                         addr = inet_addr(ptr->IpAddressList.IpAddress.String);
2185                         mask = inet_addr(ptr->IpAddressList.IpMask.String);
2186                         bcast = addr | ~mask;
2187                         intArray->iiAddress.AddressIn.sin_family = AF_INET;
2188                         intArray->iiAddress.AddressIn.sin_port = 0;
2189                         intArray->iiAddress.AddressIn.sin_addr.WS_s_addr =
2190                          addr;
2191                         intArray->iiNetmask.AddressIn.sin_family = AF_INET;
2192                         intArray->iiNetmask.AddressIn.sin_port = 0;
2193                         intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr =
2194                          mask;
2195                         intArray->iiBroadcastAddress.AddressIn.sin_family =
2196                          AF_INET;
2197                         intArray->iiBroadcastAddress.AddressIn.sin_port = 0;
2198                         intArray->iiBroadcastAddress.AddressIn.sin_addr.
2199                          WS_s_addr = bcast;
2200                      }
2201                   }
2202                   else
2203                   {
2204                      ERR("Unable to get interface table!\n");
2205                      release_sock_fd( s, fd );
2206                      HeapFree(GetProcessHeap(),0,table);
2207                      WSASetLastError(WSAEINVAL);
2208                      return SOCKET_ERROR;
2209                   }
2210                   HeapFree(GetProcessHeap(),0,table);
2211                }
2212                else
2213                {
2214                   release_sock_fd( s, fd );
2215                   WSASetLastError(WSAEINVAL);
2216                   return SOCKET_ERROR;
2217                }
2218            }
2219            else
2220            {
2221                ERR("Unable to get interface table!\n");
2222                release_sock_fd( s, fd );
2223                WSASetLastError(WSAEINVAL);
2224                return SOCKET_ERROR;
2225            }
2226            /* Calculate the size of the array being returned */
2227            *lpcbBytesReturned = sizeof(INTERFACE_INFO) * numInt;
2228            release_sock_fd( s, fd );
2229            break;
2230        }
2231 
2232    case WS_SIO_ADDRESS_LIST_CHANGE:
2233        FIXME("-> SIO_ADDRESS_LIST_CHANGE request: stub\n");
2234        /* FIXME: error and return code depend on whether socket was created
2235         * with WSA_FLAG_OVERLAPPED, but there is no easy way to get this */
2236        break;
2237 
2238    case WS_SIO_ADDRESS_LIST_QUERY:
2239    {
2240         DWORD size;
2241 
2242         TRACE("-> SIO_ADDRESS_LIST_QUERY request\n");
2243 
2244         if (!lpcbBytesReturned)
2245         {
2246             WSASetLastError(WSAEFAULT);
2247             return SOCKET_ERROR;
2248         }
2249 
2250         if (GetAdaptersInfo(NULL, &size) == ERROR_BUFFER_OVERFLOW)
2251         {
2252             IP_ADAPTER_INFO *p, *table = HeapAlloc(GetProcessHeap(), 0, size);
2253             DWORD need, num;
2254 
2255             if (!table || GetAdaptersInfo(table, &size))
2256             {
2257                 HeapFree(GetProcessHeap(), 0, table);
2258                 WSASetLastError(WSAEINVAL);
2259                 return SOCKET_ERROR;
2260             }
2261 
2262             for (p = table, num = 0; p; p = p->Next)
2263                 if (p->IpAddressList.IpAddress.String[0]) num++;
2264 
2265             need = sizeof(SOCKET_ADDRESS_LIST) + sizeof(SOCKET_ADDRESS) * (num - 1);
2266             need += sizeof(SOCKADDR) * num;
2267             *lpcbBytesReturned = need;
2268 
2269             if (need > cbOutBuffer)
2270             {
2271                 HeapFree(GetProcessHeap(), 0, table);
2272                 WSASetLastError(WSAEFAULT);
2273                 return SOCKET_ERROR;
2274             }
2275 
2276             if (lpbOutBuffer)
2277             {
2278                 unsigned int i;
2279                 SOCKET_ADDRESS *sa;
2280                 SOCKET_ADDRESS_LIST *sa_list = (SOCKET_ADDRESS_LIST *)lpbOutBuffer;
2281                 SOCKADDR_IN *sockaddr;
2282 
2283                 sa = sa_list->Address;
2284                 sockaddr = (SOCKADDR_IN *)((char *)sa + num * sizeof(SOCKET_ADDRESS));
2285                 sa_list->iAddressCount = num;
2286 
2287                 for (p = table, i = 0; p; p = p->Next)
2288                 {
2289                     if (!p->IpAddressList.IpAddress.String[0]) continue;
2290 
2291                     sa[i].lpSockaddr = (SOCKADDR *)&sockaddr[i];
2292                     sa[i].iSockaddrLength = sizeof(SOCKADDR);
2293 
2294                     sockaddr[i].sin_family = AF_INET;
2295                     sockaddr[i].sin_port = 0;
2296                     sockaddr[i].sin_addr.WS_s_addr = inet_addr(p->IpAddressList.IpAddress.String);
2297                     i++;
2298                 }
2299             }
2300 
2301             HeapFree(GetProcessHeap(), 0, table);
2302             return 0;
2303         }
2304         else
2305         {
2306             WARN("unable to get IP address list\n");
2307             WSASetLastError(WSAEINVAL);
2308             return SOCKET_ERROR;
2309         }
2310    }
2311    case WS_SIO_FLUSH:
2312         FIXME("SIO_FLUSH: stub.\n");
2313         break;
2314 
2315    case WS_SIO_GET_EXTENSION_FUNCTION_POINTER:
2316        FIXME("SIO_GET_EXTENSION_FUNCTION_POINTER %s: stub\n", debugstr_guid(lpvInBuffer));
2317        WSASetLastError(WSAEOPNOTSUPP);
2318        return SOCKET_ERROR;
2319 
2320    default:
2321        FIXME("unsupported WS_IOCTL cmd (%08x)\n", dwIoControlCode);
2322        WSASetLastError(WSAEOPNOTSUPP);
2323        return SOCKET_ERROR;
2324    }
2325 
2326    return 0;
2327 }
2328 
2329 
2330 /***********************************************************************
2331  *              ioctlsocket             (WS2_32.10)
2332  */
2333 int WINAPI WS_ioctlsocket(SOCKET s, LONG cmd, WS_u_long *argp)
2334 {
2335     int fd;
2336     long newcmd  = cmd;
2337 
2338     TRACE("socket %04lx, cmd %08x, ptr %p\n", s, cmd, argp);
2339     /* broken apps like defcon pass the argp value directly instead of a pointer to it */
2340     if(IS_INTRESOURCE(argp))
2341     {
2342        SetLastError(WSAEFAULT);
2343        return SOCKET_ERROR;
2344     }
2345 
2346     switch( cmd )
2347     {
2348     case WS_FIONREAD:
2349         newcmd=FIONREAD;
2350         break;
2351 
2352     case WS_FIONBIO:
2353         if( _get_sock_mask(s) )
2354         {
2355             /* AsyncSelect()'ed sockets are always nonblocking */
2356             if (*argp) return 0;
2357             SetLastError(WSAEINVAL);
2358             return SOCKET_ERROR;
2359         }
2360         fd = get_sock_fd( s, 0, NULL );
2361         if (fd != -1)
2362         {
2363             int ret;
2364             if (*argp)
2365             {
2366                 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
2367                 ret = fcntl( fd, F_SETFL, O_NONBLOCK );
2368             }
2369             else
2370             {
2371                 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
2372                 ret = fcntl( fd, F_SETFL, 0 );
2373             }
2374             release_sock_fd( s, fd );
2375             if (!ret) return 0;
2376             SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2377         }
2378         return SOCKET_ERROR;
2379 
2380     case WS_SIOCATMARK:
2381         newcmd=SIOCATMARK;
2382         break;
2383 
2384     case WS_FIOASYNC:
2385         WARN("Warning: WS1.1 shouldn't be using async I/O\n");
2386         SetLastError(WSAEINVAL);
2387         return SOCKET_ERROR;
2388 
2389     case SIOCGIFBRDADDR:
2390     case SIOCGIFNETMASK:
2391     case SIOCGIFADDR:
2392         /* These don't need any special handling.  They are used by
2393            WsControl, and are here to suppress an unnecessary warning. */
2394         break;
2395 
2396     default:
2397         /* Netscape tries hard to use bogus ioctl 0x667e */
2398         /* FIXME: 0x667e above is ('f' << 8) | 126, and is a low word of
2399          * FIONBIO (_IOW('f', 126, u_long)), how that should be handled?
2400          */
2401         WARN("\tunknown WS_IOCTL cmd (%08x)\n", cmd);
2402         break;
2403     }
2404 
2405     fd = get_sock_fd( s, 0, NULL );
2406     if (fd != -1)
2407     {
2408         if( ioctl(fd, newcmd, (char*)argp ) == 0 )
2409         {
2410             release_sock_fd( s, fd );
2411             return 0;
2412         }
2413         SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2414         release_sock_fd( s, fd );
2415     }
2416     return SOCKET_ERROR;
2417 }
2418 
2419 /***********************************************************************
2420  *              listen          (WS2_32.13)
2421  */
2422 int WINAPI WS_listen(SOCKET s, int backlog)
2423 {
2424     int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2425 
2426     TRACE("socket %04lx, backlog %d\n", s, backlog);
2427     if (fd != -1)
2428     {
2429         if (listen(fd, backlog) == 0)
2430         {
2431             release_sock_fd( s, fd );
2432             _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
2433                           FD_WINE_LISTENING,
2434                           FD_CONNECT|FD_WINE_CONNECTED);
2435             return 0;
2436         }
2437         SetLastError(wsaErrno());
2438         release_sock_fd( s, fd );
2439     }
2440     return SOCKET_ERROR;
2441 }
2442 
2443 /***********************************************************************
2444  *              recv                    (WS2_32.16)
2445  */
2446 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
2447 {
2448     DWORD n, dwFlags = flags;
2449     WSABUF wsabuf;
2450 
2451     wsabuf.len = len;
2452     wsabuf.buf = buf;
2453 
2454     if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
2455         return SOCKET_ERROR;
2456     else
2457         return n;
2458 }
2459 
2460 /***********************************************************************
2461  *              recvfrom                (WS2_32.17)
2462  */
2463 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
2464                        struct WS_sockaddr *from, int *fromlen)
2465 {
2466     DWORD n, dwFlags = flags;
2467     WSABUF wsabuf;
2468 
2469     wsabuf.len = len;
2470     wsabuf.buf = buf;
2471 
2472     if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL) == SOCKET_ERROR )
2473         return SOCKET_ERROR;
2474     else
2475         return n;
2476 }
2477 
2478 /* allocate a poll array for the corresponding fd sets */
2479 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
2480                                        const WS_fd_set *exceptfds, int *count_ptr )
2481 {
2482     int i, j = 0, count = 0;
2483     struct pollfd *fds;
2484 
2485     if (readfds) count += readfds->fd_count;
2486     if (writefds) count += writefds->fd_count;
2487     if (exceptfds) count += exceptfds->fd_count;
2488     *count_ptr = count;
2489     if (!count) return NULL;
2490     if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0])))) return NULL;
2491     if (readfds)
2492         for (i = 0; i < readfds->fd_count; i++, j++)
2493         {
2494             fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
2495             fds[j].events = POLLIN;
2496             fds[j].revents = 0;
2497         }
2498     if (writefds)
2499         for (i = 0; i < writefds->fd_count; i++, j++)
2500         {
2501             fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
2502             fds[j].events = POLLOUT;
2503             fds[j].revents = 0;
2504         }
2505     if (exceptfds)
2506         for (i = 0; i < exceptfds->fd_count; i++, j++)
2507         {
2508             fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
2509             fds[j].events = POLLHUP;
2510             fds[j].revents = 0;
2511         }
2512     return fds;
2513 }
2514 
2515 /* release the file descriptor obtained in fd_sets_to_poll */
2516 /* must be called with the original fd_set arrays, before calling get_poll_results */
2517 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
2518                               const WS_fd_set *exceptfds, struct pollfd *fds )
2519 {
2520     int i, j = 0;
2521 
2522     if (readfds)
2523     {
2524         for (i = 0; i < readfds->fd_count; i++, j++)
2525             if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
2526     }
2527     if (writefds)
2528     {
2529         for (i = 0; i < writefds->fd_count; i++, j++)
2530             if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
2531     }
2532     if (exceptfds)
2533     {
2534         for (i = 0; i < exceptfds->fd_count; i++, j++)
2535             if (fds[j].fd != -1)
2536             {
2537                 /* make sure we have a real error before releasing the fd */
2538                 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
2539                 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
2540             }
2541     }
2542 }
2543 
2544 /* map the poll results back into the Windows fd sets */
2545 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
2546                              const struct pollfd *fds )
2547 {
2548     int i, j = 0, k, total = 0;
2549 
2550     if (readfds)
2551     {
2552         for (i = k = 0; i < readfds->fd_count; i++, j++)
2553             if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
2554         readfds->fd_count = k;
2555         total += k;
2556     }
2557     if (writefds)
2558     {
2559         for (i = k = 0; i < writefds->fd_count; i++, j++)
2560             if (fds[j].revents) writefds->fd_array[k++] = writefds->fd_array[i];
2561         writefds->fd_count = k;
2562         total += k;
2563     }
2564     if (exceptfds)
2565     {
2566         for (i = k = 0; i < exceptfds->fd_count; i++, j++)
2567             if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
2568         exceptfds->fd_count = k;
2569         total += k;
2570     }
2571     return total;
2572 }
2573 
2574 
2575 /***********************************************************************
2576  *              select                  (WS2_32.18)
2577  */
2578 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
2579                      WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
2580                      const struct WS_timeval* ws_timeout)
2581 {
2582     struct pollfd *pollfds;
2583     int count, ret, timeout = -1;
2584 
2585     TRACE("read %p, write %p, excp %p timeout %p\n",
2586           ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
2587 
2588     if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )) && count)
2589     {
2590         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2591         return SOCKET_ERROR;
2592     }
2593 
2594     if (ws_timeout) timeout = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
2595 
2596     ret = poll( pollfds, count, timeout );
2597     release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
2598 
2599     if (ret == -1) SetLastError(wsaErrno());
2600     else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
2601     HeapFree( GetProcessHeap(), 0, pollfds );
2602     return ret;
2603 }
2604 
2605 /* helper to send completion messages for client-only i/o operation case */
2606 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus, ULONG_PTR Information )
2607 {
2608     NTSTATUS status;
2609 
2610     SERVER_START_REQ( add_fd_completion )
2611     {
2612         req->handle      = SOCKET2HANDLE(sock);
2613         req->cvalue      = CompletionValue;
2614         req->status      = CompletionStatus;
2615         req->information = Information;
2616         status = wine_server_call( req );
2617     }
2618     SERVER_END_REQ;
2619 }
2620 
2621 
2622 /***********************************************************************
2623  *              send                    (WS2_32.19)
2624  */
2625 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
2626 {
2627     DWORD n;
2628     WSABUF wsabuf;
2629 
2630     wsabuf.len = len;
2631     wsabuf.buf = (char*) buf;
2632 
2633     if ( WSASendTo( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
2634         return SOCKET_ERROR;
2635     else
2636         return n;
2637 }
2638 
2639 /***********************************************************************
2640  *              WSASend                 (WS2_32.72)
2641  */
2642 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2643                     LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2644                     LPWSAOVERLAPPED lpOverlapped,
2645                     LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2646 {
2647     return WSASendTo( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
2648                       NULL, 0, lpOverlapped, lpCompletionRoutine );
2649 }
2650 
2651 /***********************************************************************
2652  *              WSASendDisconnect       (WS2_32.73)
2653  */
2654 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
2655 {
2656     return WS_shutdown( s, SD_SEND );
2657 }
2658 
2659 
2660 /***********************************************************************
2661  *              WSASendTo               (WS2_32.74)
2662  */
2663 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2664                       LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2665                       const struct WS_sockaddr *to, int tolen,
2666                       LPWSAOVERLAPPED lpOverlapped,
2667                       LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2668 {
2669     unsigned int i, options;
2670     int n, fd, err;
2671     struct ws2_async *wsa;
2672     int totalLength = 0;
2673     ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
2674 
2675     TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
2676           s, lpBuffers, dwBufferCount, dwFlags,
2677           to, tolen, lpOverlapped, lpCompletionRoutine);
2678 
2679     fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
2680     TRACE( "fd=%d, options=%x\n", fd, options );
2681 
2682     if ( fd == -1 ) return SOCKET_ERROR;
2683 
2684     if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
2685     {
2686         err = WSAEFAULT;
2687         goto error;
2688     }
2689 
2690     wsa->hSocket     = SOCKET2HANDLE(s);
2691     wsa->addr        = (struct WS_sockaddr *)to;
2692     wsa->addrlen.val = tolen;
2693     wsa->flags       = dwFlags;
2694     wsa->n_iovecs    = dwBufferCount;
2695     wsa->first_iovec = 0;
2696     for ( i = 0; i < dwBufferCount; i++ )
2697     {
2698         wsa->iovec[i].iov_base = lpBuffers[i].buf;
2699         wsa->iovec[i].iov_len  = lpBuffers[i].len;
2700         totalLength += lpBuffers[i].len;
2701     }
2702 
2703     if (!lpNumberOfBytesSent)
2704     {
2705         err = WSAEFAULT;
2706         goto error;
2707     }
2708 
2709     for (;;)
2710     {
2711         n = WS2_send( fd, wsa );
2712         if (n != -1 || errno != EINTR) break;
2713     }
2714     if (n == -1 && errno != EAGAIN)
2715     {
2716         err = wsaErrno();
2717         if (cvalue) WS_AddCompletion( s, cvalue, err, 0 );
2718         goto error;
2719     }
2720 
2721     if ((lpOverlapped || lpCompletionRoutine) &&
2722         !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
2723     {
2724         IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
2725 
2726         wsa->user_overlapped = lpOverlapped;
2727         wsa->completion_func = lpCompletionRoutine;
2728         release_sock_fd( s, fd );
2729 
2730         if (n == -1)
2731         {
2732             iosb->u.Status = STATUS_PENDING;
2733             iosb->Information = 0;
2734 
2735             SERVER_START_REQ( register_async )
2736             {
2737                 req->handle = wsa->hSocket;
2738                 req->type   = ASYNC_TYPE_WRITE;
2739                 req->async.callback = WS2_async_send;
2740                 req->async.iosb     = iosb;
2741                 req->async.arg      = wsa;
2742                 req->async.apc      = ws2_async_apc;
2743                 req->async.event    = lpCompletionRoutine ? 0 : lpOverlapped->hEvent;
2744                 req->async.cvalue   = cvalue;
2745                 err = wine_server_call( req );
2746             }
2747             SERVER_END_REQ;
2748 
2749             if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
2750             WSASetLastError( NtStatusToWSAError( err ));
2751             return SOCKET_ERROR;
2752         }
2753 
2754         iosb->u.Status = STATUS_SUCCESS;
2755         iosb->Information = n;
2756         *lpNumberOfBytesSent = n;
2757         if (!wsa->completion_func)
2758         {
2759             if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
2760             if (lpOverlapped->hEvent) SetEvent( lpOverlapped->hEvent );
2761             HeapFree( GetProcessHeap(), 0, wsa );
2762         }
2763         else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
2764                                (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
2765         WSASetLastError(0);
2766         return 0;
2767     }
2768 
2769     if ( _is_blocking(s) )
2770     {
2771         /* On a blocking non-overlapped stream socket,
2772          * sending blocks until the entire buffer is sent. */
2773         DWORD timeout_start = GetTickCount();
2774 
2775         *lpNumberOfBytesSent = 0;
2776 
2777         while (wsa->first_iovec < dwBufferCount)
2778         {
2779             struct pollfd pfd;
2780             int timeout = GET_SNDTIMEO(fd);
2781 
2782             if (n >= 0)
2783             {
2784                 *lpNumberOfBytesSent += n;
2785                 while (wsa->first_iovec < dwBufferCount && wsa->iovec[wsa->first_iovec].iov_len <= n)
2786                     n -= wsa->iovec[wsa->first_iovec++].iov_len;
2787                 if (wsa->first_iovec >= dwBufferCount) break;
2788                 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
2789                 wsa->iovec[wsa->first_iovec].iov_len -= n;
2790             }
2791 
2792             if (timeout != -1)
2793             {
2794                 timeout -= GetTickCount() - timeout_start;
2795                 if (timeout < 0) timeout = 0;
2796             }
2797 
2798             pfd.fd = fd;
2799             pfd.events = POLLOUT;
2800 
2801             if (!timeout || !poll( &pfd, 1, timeout ))
2802             {
2803                 err = WSAETIMEDOUT;
2804                 goto error; /* msdn says a timeout in send is fatal */
2805             }
2806 
2807             n = WS2_send( fd, wsa );
2808             if (n == -1 && errno != EAGAIN && errno != EINTR)
2809             {
2810                 err = wsaErrno();
2811                 goto error;
2812             }
2813         }
2814     }
2815     else  /* non-blocking */
2816     {
2817         if (n < totalLength)
2818             _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
2819         if (n == -1)
2820         {
2821             err = WSAEWOULDBLOCK;
2822             goto error;
2823         }
2824         *lpNumberOfBytesSent = n;
2825     }
2826 
2827     TRACE(" -> %i bytes\n", *lpNumberOfBytesSent);
2828 
2829     HeapFree( GetProcessHeap(), 0, wsa );
2830     release_sock_fd( s, fd );
2831     WSASetLastError(0);
2832     return 0;
2833 
2834 error:
2835     HeapFree( GetProcessHeap(), 0, wsa );
2836     release_sock_fd( s, fd );
2837     WARN(" -> ERROR %d\n", err);
2838     WSASetLastError(err);
2839     return SOCKET_ERROR;
2840 }
2841 
2842 /***********************************************************************
2843  *              sendto          (WS2_32.20)
2844  */
2845 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
2846                               const struct WS_sockaddr *to, int tolen)
2847 {
2848     DWORD n;
2849     WSABUF wsabuf;
2850 
2851     wsabuf.len = len;
2852     wsabuf.buf = (char*) buf;
2853 
2854     if ( WSASendTo(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
2855         return SOCKET_ERROR;
2856     else
2857         return n;
2858 }
2859 
2860 /***********************************************************************
2861  *              setsockopt              (WS2_32.21)
2862  */
2863 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
2864                                   const char *optval, int optlen)
2865 {
2866     int fd;
2867     int woptval;
2868     struct linger linger;
2869     struct timeval tval;
2870 
2871     TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
2872           s, level, optname, optval, optlen);
2873 
2874     /* some broken apps pass the value directly instead of a pointer to it */
2875     if(IS_INTRESOURCE(optval))
2876     {
2877         SetLastError(WSAEFAULT);
2878         return SOCKET_ERROR;
2879     }
2880 
2881     switch(level)
2882     {
2883     case WS_SOL_SOCKET:
2884         switch(optname)
2885         {
2886         /* Some options need some conversion before they can be sent to
2887          * setsockopt. The conversions are done here, then they will fall though
2888          * to the general case. Special options that are not passed to
2889          * setsockopt follow below that.*/
2890 
2891         case WS_SO_DONTLINGER:
2892             linger.l_onoff  = *((const int*)optval) ? 0: 1;
2893             linger.l_linger = 0;
2894             level = SOL_SOCKET;
2895             optname = SO_LINGER;
2896             optval = (char*)&linger;
2897             optlen = sizeof(struct linger);
2898             break;
2899 
2900         case WS_SO_LINGER:
2901             linger.l_onoff  = ((LINGER*)optval)->l_onoff;
2902             linger.l_linger  = ((LINGER*)optval)->l_linger;
2903             /* FIXME: what is documented behavior if SO_LINGER optval
2904                is null?? */
2905             level = SOL_SOCKET;
2906             optname = SO_LINGER;
2907             optval = (char*)&linger;
2908             optlen = sizeof(struct linger);
2909             break;
2910 
2911         case WS_SO_RCVBUF:
2912             if (*(const int*)optval < 2048)
2913             {
2914                 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
2915                 return 0;
2916             }
2917             /* Fall through */
2918 
2919         /* The options listed here don't need any special handling. Thanks to
2920          * the conversion happening above, options from there will fall through
2921          * to this, too.*/
2922         case WS_SO_ACCEPTCONN:
2923         case WS_SO_BROADCAST:
2924         case WS_SO_ERROR:
2925         case WS_SO_KEEPALIVE:
2926         case WS_SO_OOBINLINE:
2927         /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
2928          * however, using it the BSD way fixes bug 8513 and seems to be what
2929          * most programmers assume, anyway */
2930         case WS_SO_REUSEADDR:
2931         case WS_SO_SNDBUF:
2932         case WS_SO_TYPE:
2933             convert_sockopt(&level, &optname);
2934             break;
2935 
2936         /* SO_DEBUG is a privileged operation, ignore it. */
2937         case WS_SO_DEBUG:
2938             TRACE("Ignoring SO_DEBUG\n");
2939             return 0;
2940 
2941         /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
2942          * socket. According to MSDN, this option is silently ignored.*/
2943         case WS_SO_DONTROUTE:
2944             TRACE("Ignoring SO_DONTROUTE\n");
2945             return 0;
2946 
2947         /* Stops two sockets from being bound to the same port. Always happens
2948          * on unix systems, so just drop it. */
2949         case WS_SO_EXCLUSIVEADDRUSE:
2950             TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
2951             return 0;
2952 
2953         /* SO_OPENTYPE does not require a valid socket handle. */
2954         case WS_SO_OPENTYPE:
2955             if (!optlen || optlen < sizeof(int) || !optval)
2956             {
2957                 SetLastError(WSAEFAULT);
2958                 return SOCKET_ERROR;
2959             }
2960             get_per_thread_data()->opentype = *(const int *)optval;
2961             TRACE("setting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
2962             return 0;
2963 
2964 #ifdef SO_RCVTIMEO
2965         case WS_SO_RCVTIMEO:
2966 #endif
2967 #ifdef SO_SNDTIMEO
2968         case WS_SO_SNDTIMEO:
2969 #endif
2970 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
2971             if (optval && optlen == sizeof(UINT32)) {
2972                 /* WinSock passes milliseconds instead of struct timeval */
2973                 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
2974                 tval.tv_sec = *(const UINT32*)optval / 1000;
2975                 /* min of 500 milliseconds */
2976                 if (tval.tv_sec == 0 && tval.tv_usec < 500000)
2977                     tval.tv_usec = 500000;
2978                 optlen = sizeof(struct timeval);
2979                 optval = (char*)&tval;
2980             } else if (optlen == sizeof(struct timeval)) {
2981                 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
2982             } else {
2983                 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
2984                 return 0;
2985             }
2986             convert_sockopt(&level, &optname);
2987             break;
2988 #endif
2989 
2990         default:
2991             TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
2992             SetLastError(WSAENOPROTOOPT);
2993             return SOCKET_ERROR;
2994         }
2995         break; /* case WS_SOL_SOCKET */
2996 
2997 #ifdef HAVE_IPX
2998     case NSPROTO_IPX:
2999         switch(optname)
3000         {
3001         case IPX_PTYPE:
3002             fd = get_sock_fd( s, 0, NULL );
3003             TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", *(const int*)optval, fd);
3004 
3005             /* We try to set the ipx type on ipx socket level. */
3006 #ifdef SOL_IPX
3007             if(setsockopt(fd, SOL_IPX, IPX_TYPE, optval, optlen) == -1)
3008             {
3009                 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
3010                 release_sock_fd( s, fd );
3011                 return SOCKET_ERROR;
3012             }
3013 #else
3014             {
3015                 struct ipx val;
3016                 /* Should we retrieve val using a getsockopt call and then
3017                  * set the modified one? */
3018                 val.ipx_pt = *optval;
3019                 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
3020             }
3021 #endif
3022             release_sock_fd( s, fd );
3023             return 0;
3024 
3025         case IPX_FILTERPTYPE:
3026             /* Sets the receive filter packet type, at the moment we don't support it */
3027             FIXME("IPX_FILTERPTYPE: %x\n", *optval);
3028             /* Returning 0 is better for now than returning a SOCKET_ERROR */
3029             return 0;
3030 
3031         default:
3032             FIXME("opt_name:%x\n", optname);
3033             return SOCKET_ERROR;
3034         }
3035         break; /* case NSPROTO_IPX */
3036 #endif
3037 
3038     /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3039     case WS_IPPROTO_TCP:
3040         switch(optname)
3041         {
3042         case WS_TCP_NODELAY:
3043             convert_sockopt(&level, &optname);
3044             break;
3045         default:
3046             FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
3047             return SOCKET_ERROR;
3048         }
3049         break;
3050 
3051     case WS_IPPROTO_IP:
3052         switch(optname)
3053         {
3054         case WS_IP_ADD_MEMBERSHIP:
3055         case WS_IP_DROP_MEMBERSHIP:
3056 #ifdef IP_HDRINCL
3057         case WS_IP_HDRINCL:
3058 #endif
3059         case WS_IP_MULTICAST_IF:
3060         case WS_IP_MULTICAST_LOOP:
3061         case WS_IP_MULTICAST_TTL:
3062         case WS_IP_OPTIONS:
3063         case WS_IP_TOS:
3064         case WS_IP_TTL:
3065             convert_sockopt(&level, &optname);
3066             break;
3067         case WS_IP_DONTFRAGMENT:
3068             FIXME("IP_DONTFRAGMENT is silently ignored!\n");
3069             return 0;
3070         default:
3071             FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
3072             return SOCKET_ERROR;
3073         }
3074         break;
3075 
3076     default:
3077         FIXME("Unknown level: 0x%08x\n", level);
3078         return SOCKET_ERROR;
3079     } /* end switch(level) */
3080 
3081     /* avoid endianness issues if argument is a 16-bit int */
3082     if (optval && optlen < sizeof(int))
3083     {
3084         woptval= *((const INT16 *) optval);
3085         optval= (char*) &woptval;
3086         optlen=sizeof(int);
3087     }
3088     fd = get_sock_fd( s, 0, NULL );
3089     if (fd == -1) return SOCKET_ERROR;
3090 
3091     if (setsockopt(fd, level, optname, optval, optlen) == 0)
3092     {
3093         release_sock_fd( s, fd );
3094         return 0;
3095     }
3096     TRACE("Setting socket error, %d\n", wsaErrno());
3097     SetLastError(wsaErrno());
3098     release_sock_fd( s, fd );
3099 
3100     return SOCKET_ERROR;
3101 }
3102 
3103 /***********************************************************************
3104  *              shutdown                (WS2_32.22)
3105  */
3106 int WINAPI WS_shutdown(SOCKET s, int how)
3107 {
3108     int fd, err = WSAENOTSOCK;
3109     unsigned int options, clear_flags = 0;
3110 
3111     fd = get_sock_fd( s, 0, &options );
3112     TRACE("socket %04lx, how %i %x\n", s, how, options );
3113 
3114     if (fd == -1)
3115         return SOCKET_ERROR;
3116 
3117     switch( how )
3118     {
3119     case 0: /* drop receives */
3120         clear_flags |= FD_READ;
3121         break;
3122     case 1: /* drop sends */
3123         clear_flags |= FD_WRITE;
3124         break;
3125     case 2: /* drop all */
3126         clear_flags |= FD_READ|FD_WRITE;
3127     default:
3128         clear_flags |= FD_WINE_LISTENING;
3129     }
3130 
3131     if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
3132     {
3133         switch ( how )
3134         {
3135         case SD_RECEIVE:
3136             err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3137             break;
3138         case SD_SEND:
3139             err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3140             break;
3141         case SD_BOTH:
3142         default:
3143             err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3144             if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3145             break;
3146         }
3147         if (err) goto error;
3148     }
3149     else /* non-overlapped mode */
3150     {
3151         if ( shutdown( fd, how ) )
3152         {
3153             err = wsaErrno();
3154             goto error;
3155         }
3156     }
3157 
3158     release_sock_fd( s, fd );
3159     _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3160     if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
3161     return 0;
3162 
3163 error:
3164     release_sock_fd( s, fd );
3165     _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3166     WSASetLastError( err );
3167     return SOCKET_ERROR;
3168 }
3169 
3170 /***********************************************************************
3171  *              socket          (WS2_32.23)
3172  */
3173 SOCKET WINAPI WS_socket(int af, int type, int protocol)
3174 {
3175     TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
3176 
3177     return WSASocketA( af, type, protocol, NULL, 0,
3178                        get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
3179 }
3180 
3181 
3182 /***********************************************************************
3183  *              gethostbyaddr           (WS2_32.51)
3184  */
3185 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
3186 {
3187     struct WS_hostent *retval = NULL;
3188     struct hostent* host;
3189 
3190 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3191     char *extrabuf;
3192     int ebufsize=1024;
3193     struct hostent hostentry;
3194     int locerr=ENOBUFS;
3195     host = NULL;
3196     extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3197     while(extrabuf) {
3198         int res = gethostbyaddr_r(addr, len, type,
3199                                   &hostentry, extrabuf, ebufsize, &host, &locerr);
3200         if( res != ERANGE) break;
3201         ebufsize *=2;
3202         extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3203     }
3204     if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3205 #else
3206     EnterCriticalSection( &csWSgetXXXbyYYY );
3207     host = gethostbyaddr(addr, len, type);
3208     if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3209 #endif
3210     if( host != NULL ) retval = WS_dup_he(host);
3211 #ifdef  HAVE_LINUX_GETHOSTBYNAME_R_6
3212     HeapFree(GetProcessHeap(),0,extrabuf);
3213 #else
3214     LeaveCriticalSection( &csWSgetXXXbyYYY );
3215 #endif
3216     TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
3217     return retval;
3218 }
3219 
3220 /***********************************************************************
3221  *              gethostbyname           (WS2_32.52)
3222  */
3223 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
3224 {
3225     struct WS_hostent *retval = NULL;
3226     struct hostent*     host;
3227 #ifdef  HAVE_LINUX_GETHOSTBYNAME_R_6
3228     char *extrabuf;
3229     int ebufsize=1024;
3230     struct hostent hostentry;
3231     int locerr = ENOBUFS;
3232 #endif
3233     char buf[100];
3234     if( !name || !name[0]) {
3235         name = buf;
3236         if( gethostname( buf, 100) == -1) {
3237             SetLastError( WSAENOBUFS); /* appropriate ? */
3238             return retval;
3239         }
3240     }
3241 #ifdef  HAVE_LINUX_GETHOSTBYNAME_R_6
3242     host = NULL;
3243     extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3244     while(extrabuf) {
3245         int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
3246         if( res != ERANGE) break;
3247         ebufsize *=2;
3248         extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3249     }
3250     if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3251 #else
3252     EnterCriticalSection( &csWSgetXXXbyYYY );
3253     host = gethostbyname(name);
3254     if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3255 #endif
3256     if (host) retval = WS_dup_he(host);
3257 #ifdef  HAVE_LINUX_GETHOSTBYNAME_R_6
3258     HeapFree(GetProcessHeap(),0,extrabuf);
3259 #else
3260     LeaveCriticalSection( &csWSgetXXXbyYYY );
3261 #endif
3262     if (retval && retval->h_addr_list[0][0] == 127 &&
3263         strcmp(name, "localhost") != 0)
3264     {
3265         /* hostname != "localhost" but has loopback address. replace by our
3266          * special address.*/
3267         memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
3268     }
3269     TRACE( "%s ret %p\n", debugstr_a(name), retval );
3270     return retval;
3271 }
3272 
3273 
3274 /***********************************************************************
3275  *              getprotobyname          (WS2_32.53)
3276  */
3277 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
3278 {
3279     struct WS_protoent* retval = NULL;
3280 #ifdef HAVE_GETPROTOBYNAME
3281     struct protoent*     proto;
3282     EnterCriticalSection( &csWSgetXXXbyYYY );
3283     if( (proto = getprotobyname(name)) != NULL )
3284     {
3285         retval = WS_dup_pe(proto);
3286     }
3287     else {
3288         MESSAGE("protocol %s not found; You might want to add "
3289                 "this to /etc/protocols\n", debugstr_a(name) );
3290         SetLastError(WSANO_DATA);
3291     }
3292     LeaveCriticalSection( &csWSgetXXXbyYYY );
3293 #endif
3294     TRACE( "%s ret %p\n", debugstr_a(name), retval );
3295     return retval;
3296 }
3297 
3298 
3299 /***********************************************************************
3300  *              getprotobynumber        (WS2_32.54)
3301  */
3302 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
3303 {
3304     struct WS_protoent* retval = NULL;
3305 #ifdef HAVE_GETPROTOBYNUMBER
3306     struct protoent*     proto;
3307     EnterCriticalSection( &csWSgetXXXbyYYY );
3308     if( (proto = getprotobynumber(number)) != NULL )
3309     {
3310         retval = WS_dup_pe(proto);
3311     }
3312     else {
3313         MESSAGE("protocol number %d not found; You might want to add "
3314                 "this to /etc/protocols\n", number );
3315         SetLastError(WSANO_DATA);
3316     }
3317     LeaveCriticalSection( &csWSgetXXXbyYYY );
3318 #endif
3319     TRACE("%i ret %p\n", number, retval);
3320     return retval;
3321 }
3322 
3323 
3324 /***********************************************************************
3325  *              getservbyname           (WS2_32.55)
3326  */
3327 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
3328 {
3329     struct WS_servent* retval = NULL;
3330     struct servent*     serv;
3331     char *name_str;
3332     char *proto_str = NULL;
3333 
3334     if (!(name_str = strdup_lower(name))) return NULL;
3335 
3336     if (proto && *proto)
3337     {
3338         if (!(proto_str = strdup_lower(proto)))
3339         {
3340             HeapFree( GetProcessHeap(), 0, name_str );
3341             return NULL;
3342         }
3343     }
3344 
3345     EnterCriticalSection( &csWSgetXXXbyYYY );
3346     serv = getservbyname(name_str, proto_str);
3347     if( serv != NULL )
3348     {
3349         retval = WS_dup_se(serv);
3350     }
3351     else SetLastError(WSANO_DATA);
3352     LeaveCriticalSection( &csWSgetXXXbyYYY );
3353     HeapFree( GetProcessHeap(), 0, proto_str );
3354     HeapFree( GetProcessHeap(), 0, name_str );
3355     TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
3356     return retval;
3357 }
3358 
3359 /***********************************************************************
3360  *              freeaddrinfo            (WS2_32.@)
3361  */
3362 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
3363 {
3364     while (res) {
3365         struct WS_addrinfo *next;
3366 
3367         HeapFree(GetProcessHeap(),0,res->ai_canonname);
3368         HeapFree(GetProcessHeap(),0,res->ai_addr);
3369         next = res->ai_next;
3370         HeapFree(GetProcessHeap(),0,res);
3371         res = next;
3372     }
3373 }
3374 
3375 /* helper functions for getaddrinfo()/getnameinfo() */
3376 static int convert_aiflag_w2u(int winflags) {
3377     int i, unixflags = 0;
3378 
3379     for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
3380         if (ws_aiflag_map[i][0] & winflags) {
3381             unixflags |= ws_aiflag_map[i][1];
3382             winflags &= ~ws_aiflag_map[i][0];
3383         }
3384     if (winflags)
3385         FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
3386     return unixflags;
3387 }
3388 
3389 static int convert_niflag_w2u(int winflags) {
3390     int i, unixflags = 0;
3391 
3392     for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
3393         if (ws_niflag_map[i][0] & winflags) {
3394             unixflags |= ws_niflag_map[i][1];
3395             winflags &= ~ws_niflag_map[i][0];
3396         }
3397     if (winflags)
3398         FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
3399     return unixflags;
3400 }
3401 
3402 static int convert_aiflag_u2w(int unixflags) {
3403     int i, winflags = 0;
3404 
3405     for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
3406         if (ws_aiflag_map[i][1] & unixflags) {
3407             winflags |= ws_aiflag_map[i][0];
3408             unixflags &= ~ws_aiflag_map[i][1];
3409         }
3410     if (unixflags) /* will warn usually */
3411         WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
3412     return winflags;
3413 }
3414 
3415 static int convert_eai_u2w(int unixret) {
3416     int i;
3417 
3418     for (i=0;ws_eai_map[i][0];i++)
3419         if (ws_eai_map[i][1] == unixret)
3420             return ws_eai_map[i][0];
3421     return unixret;
3422 }
3423 
3424 /***********************************************************************
3425  *              getaddrinfo             (WS2_32.@)
3426  */
3427 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
3428 {
3429 #ifdef HAVE_GETADDRINFO
3430     struct addrinfo *unixaires = NULL;
3431     int   result;
3432     struct addrinfo unixhints, *punixhints = NULL;
3433     CHAR *node = NULL, *serv = NULL;
3434 
3435     if (nodename)
3436         if (!(node = strdup_lower(nodename))) return WSA_NOT_ENOUGH_MEMORY;
3437 
3438     if (servname) {
3439         if (!(serv = strdup_lower(servname))) {
3440             HeapFree(GetProcessHeap(), 0, node);
3441             return WSA_NOT_ENOUGH_MEMORY;
3442         }
3443     }
3444 
3445     if (hints) {
3446         punixhints = &unixhints;
3447 
3448         memset(&unixhints, 0, sizeof(unixhints));
3449         punixhints->ai_flags    = convert_aiflag_w2u(hints->ai_flags);
3450         if (hints->ai_family == 0) /* wildcard, specific to getaddrinfo() */
3451             punixhints->ai_family = 0;
3452         else
3453             punixhints->ai_family = convert_af_w2u(hints->ai_family);
3454         if (hints->ai_socktype == 0) /* wildcard, specific to getaddrinfo() */
3455             punixhints->ai_socktype = 0;
3456         else
3457             punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
3458         if (hints->ai_protocol == 0) /* wildcard, specific to getaddrinfo() */
3459             punixhints->ai_protocol = 0;
3460         else
3461             punixhints->ai_protocol = convert_proto_w2u(hints->ai_protocol);
3462     }
3463 
3464     /* getaddrinfo(3) is thread safe, no need to wrap in CS */
3465     result = getaddrinfo(nodename, servname, punixhints, &unixaires);
3466 
3467     TRACE("%s, %s %p -> %p %d\n", debugstr_a(nodename), debugstr_a(servname), hints, res, result);
3468 
3469     HeapFree(GetProcessHeap(), 0, node);
3470     HeapFree(GetProcessHeap(), 0, serv);
3471 
3472     if (!result) {
3473         struct addrinfo *xuai = unixaires;
3474         struct WS_addrinfo **xai = res;
3475 
3476         *xai = NULL;
3477         while (xuai) {
3478             struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
3479             int len;
3480 
3481             if (!ai)
3482                 goto outofmem;
3483 
3484             *xai = ai;xai = &ai->ai_next;
3485             ai->ai_flags    = convert_aiflag_u2w(xuai->ai_flags);
3486             ai->ai_family   = convert_af_u2w(xuai->ai_family);
3487             ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
3488             ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
3489             if (xuai->ai_canonname) {
3490                 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
3491                 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
3492                 if (!ai->ai_canonname)
3493                     goto outofmem;
3494                 strcpy(ai->ai_canonname,xuai->ai_canonname);
3495             }
3496             len = xuai->ai_addrlen;
3497             ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
3498             if (!ai->ai_addr)
3499                 goto outofmem;
3500             ai->ai_addrlen = len;
3501             do {
3502                 int winlen = ai->ai_addrlen;
3503 
3504                 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
3505                     ai->ai_addrlen = winlen;
3506                     break;
3507                 }
3508                 len = 2*len;
3509                 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
3510                 if (!ai->ai_addr)
3511                     goto outofmem;
3512                 ai->ai_addrlen = len;
3513             } while (1);
3514             xuai = xuai->ai_next;
3515         }
3516         freeaddrinfo(unixaires);
3517     } else {
3518         result = convert_eai_u2w(result);
3519         *res = NULL;
3520     }
3521     return result;
3522 
3523 outofmem:
3524     if (*res) WS_freeaddrinfo(*res);
3525     if (unixaires) freeaddrinfo(unixaires);
3526     *res = NULL;
3527     return WSA_NOT_ENOUGH_MEMORY;
3528 #else
3529     FIXME("getaddrinfo() failed, not found during buildtime.\n");
3530     return EAI_FAIL;
3531 #endif
3532 }
3533 
3534 /***********************************************************************
3535  *              GetAddrInfoW            (WS2_32.@)
3536  */
3537 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
3538 {
3539     FIXME("empty stub!\n");
3540     return EAI_FAIL;
3541 }
3542 
3543 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
3544                           DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
3545 {
3546 #ifdef HAVE_GETNAMEINFO
3547     int ret;
3548     union generic_unix_sockaddr sa_u;
3549     unsigned int size;
3550 
3551     TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
3552           serv, servlen, flags);
3553 
3554     size = ws_sockaddr_ws2u(sa, salen, &sa_u);
3555     if (!size)
3556     {
3557         WSASetLastError(WSAEFAULT);
3558         return WSA_NOT_ENOUGH_MEMORY;
3559     }
3560     ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
3561     return convert_eai_u2w(ret);
3562 #else
3563     FIXME("getnameinfo() failed, not found during buildtime.\n");
3564     return EAI_FAIL;
3565 #endif
3566 }
3567 
3568 /***********************************************************************
3569  *              getservbyport           (WS2_32.56)
3570  */
3571 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
3572 {
3573     struct WS_servent* retval = NULL;
3574 #ifdef HAVE_GETSERVBYPORT
3575     struct servent*     serv;
3576     char *proto_str = NULL;
3577 
3578     if (proto && *proto)
3579     {
3580         if (!(proto_str = strdup_lower(proto))) return NULL;
3581     }
3582     EnterCriticalSection( &csWSgetXXXbyYYY );
3583     if( (serv = getservbyport(port, proto_str)) != NULL ) {
3584         retval = WS_dup_se(serv);
3585     }
3586     else SetLastError(WSANO_DATA);
3587     LeaveCriticalSection( &csWSgetXXXbyYYY );
3588     HeapFree( GetProcessHeap(), 0, proto_str );
3589 #endif
3590     TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
3591     return retval;
3592 }
3593 
3594 
3595 /***********************************************************************
3596  *              gethostname           (WS2_32.57)
3597  */
3598 int WINAPI WS_gethostname(char *name, int namelen)
3599 {
3600     TRACE("name %p, len %d\n", name, namelen);
3601 
3602     if (gethostname(name, namelen) == 0)
3603     {
3604         TRACE("<- '%s'\n", name);
3605         return 0;
3606     }
3607     SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
3608     TRACE("<- ERROR !\n");
3609     return SOCKET_ERROR;
3610 }
3611 
3612 
3613 /* ------------------------------------- Windows sockets extensions -- *
3614  *                                                                     *
3615  * ------------------------------------------------------------------- */
3616 
3617 /***********************************************************************
3618  *              WSAEnumNetworkEvents (WS2_32.36)
3619  */
3620 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
3621 {
3622     int ret;
3623 
3624     TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
3625 
3626     SERVER_START_REQ( get_socket_event )
3627     {
3628         req->handle  = SOCKET2HANDLE(s);
3629         req->service = TRUE;
3630         req->c_event = hEvent;
3631         wine_server_set_reply( req, lpEvent->iErrorCode, sizeof(lpEvent->iErrorCode) );
3632         if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
3633     }
3634     SERVER_END_REQ;
3635     if (!ret) return 0;
3636     SetLastError(WSAEINVAL);
3637     return SOCKET_ERROR;
3638 }
3639 
3640 /***********************************************************************
3641  *              WSAEventSelect (WS2_32.39)
3642  */
3643 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
3644 {
3645     int ret;
3646 
3647     TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
3648 
3649     SERVER_START_REQ( set_socket_event )
3650     {
3651         req->handle = SOCKET2HANDLE(s);
3652         req->mask   = lEvent;
3653         req->event  =