~ [ 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 
2340     switch( cmd )
2341     {
2342     case WS_FIONREAD:
2343         newcmd=FIONREAD;
2344         break;
2345 
2346     case WS_FIONBIO:
2347         if( _get_sock_mask(s) )
2348         {
2349             /* AsyncSelect()'ed sockets are always nonblocking */
2350             if (*argp) return 0;
2351             SetLastError(WSAEINVAL);
2352             return SOCKET_ERROR;
2353         }
2354         fd = get_sock_fd( s, 0, NULL );
2355         if (fd != -1)
2356         {
2357             int ret;
2358             if (*argp)
2359             {
2360                 _enable_event(SOCKET2HANDLE(s), 0, FD_WINE_NONBLOCKING, 0);
2361                 ret = fcntl( fd, F_SETFL, O_NONBLOCK );
2362             }
2363             else
2364             {
2365                 _enable_event(SOCKET2HANDLE(s), 0, 0, FD_WINE_NONBLOCKING);
2366                 ret = fcntl( fd, F_SETFL, 0 );
2367             }
2368             release_sock_fd( s, fd );
2369             if (!ret) return 0;
2370             SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2371         }
2372         return SOCKET_ERROR;
2373 
2374     case WS_SIOCATMARK:
2375         newcmd=SIOCATMARK;
2376         break;
2377 
2378     case WS_FIOASYNC:
2379         WARN("Warning: WS1.1 shouldn't be using async I/O\n");
2380         SetLastError(WSAEINVAL);
2381         return SOCKET_ERROR;
2382 
2383     case SIOCGIFBRDADDR:
2384     case SIOCGIFNETMASK:
2385     case SIOCGIFADDR:
2386         /* These don't need any special handling.  They are used by
2387            WsControl, and are here to suppress an unnecessary warning. */
2388         break;
2389 
2390     default:
2391         /* Netscape tries hard to use bogus ioctl 0x667e */
2392         /* FIXME: 0x667e above is ('f' << 8) | 126, and is a low word of
2393          * FIONBIO (_IOW('f', 126, u_long)), how that should be handled?
2394          */
2395         WARN("\tunknown WS_IOCTL cmd (%08x)\n", cmd);
2396         break;
2397     }
2398 
2399     fd = get_sock_fd( s, 0, NULL );
2400     if (fd != -1)
2401     {
2402         if( ioctl(fd, newcmd, (char*)argp ) == 0 )
2403         {
2404             release_sock_fd( s, fd );
2405             return 0;
2406         }
2407         SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2408         release_sock_fd( s, fd );
2409     }
2410     return SOCKET_ERROR;
2411 }
2412 
2413 /***********************************************************************
2414  *              listen          (WS2_32.13)
2415  */
2416 int WINAPI WS_listen(SOCKET s, int backlog)
2417 {
2418     int fd = get_sock_fd( s, FILE_READ_DATA, NULL );
2419 
2420     TRACE("socket %04lx, backlog %d\n", s, backlog);
2421     if (fd != -1)
2422     {
2423         if (listen(fd, backlog) == 0)
2424         {
2425             release_sock_fd( s, fd );
2426             _enable_event(SOCKET2HANDLE(s), FD_ACCEPT,
2427                           FD_WINE_LISTENING,
2428                           FD_CONNECT|FD_WINE_CONNECTED);
2429             return 0;
2430         }
2431         SetLastError(wsaErrno());
2432         release_sock_fd( s, fd );
2433     }
2434     return SOCKET_ERROR;
2435 }
2436 
2437 /***********************************************************************
2438  *              recv                    (WS2_32.16)
2439  */
2440 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
2441 {
2442     DWORD n, dwFlags = flags;
2443     WSABUF wsabuf;
2444 
2445     wsabuf.len = len;
2446     wsabuf.buf = buf;
2447 
2448     if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
2449         return SOCKET_ERROR;
2450     else
2451         return n;
2452 }
2453 
2454 /***********************************************************************
2455  *              recvfrom                (WS2_32.17)
2456  */
2457 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
2458                        struct WS_sockaddr *from, int *fromlen)
2459 {
2460     DWORD n, dwFlags = flags;
2461     WSABUF wsabuf;
2462 
2463     wsabuf.len = len;
2464     wsabuf.buf = buf;
2465 
2466     if ( WSARecvFrom(s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL) == SOCKET_ERROR )
2467         return SOCKET_ERROR;
2468     else
2469         return n;
2470 }
2471 
2472 /* allocate a poll array for the corresponding fd sets */
2473 static struct pollfd *fd_sets_to_poll( const WS_fd_set *readfds, const WS_fd_set *writefds,
2474                                        const WS_fd_set *exceptfds, int *count_ptr )
2475 {
2476     int i, j = 0, count = 0;
2477     struct pollfd *fds;
2478 
2479     if (readfds) count += readfds->fd_count;
2480     if (writefds) count += writefds->fd_count;
2481     if (exceptfds) count += exceptfds->fd_count;
2482     *count_ptr = count;
2483     if (!count) return NULL;
2484     if (!(fds = HeapAlloc( GetProcessHeap(), 0, count * sizeof(fds[0])))) return NULL;
2485     if (readfds)
2486         for (i = 0; i < readfds->fd_count; i++, j++)
2487         {
2488             fds[j].fd = get_sock_fd( readfds->fd_array[i], FILE_READ_DATA, NULL );
2489             fds[j].events = POLLIN;
2490             fds[j].revents = 0;
2491         }
2492     if (writefds)
2493         for (i = 0; i < writefds->fd_count; i++, j++)
2494         {
2495             fds[j].fd = get_sock_fd( writefds->fd_array[i], FILE_WRITE_DATA, NULL );
2496             fds[j].events = POLLOUT;
2497             fds[j].revents = 0;
2498         }
2499     if (exceptfds)
2500         for (i = 0; i < exceptfds->fd_count; i++, j++)
2501         {
2502             fds[j].fd = get_sock_fd( exceptfds->fd_array[i], 0, NULL );
2503             fds[j].events = POLLHUP;
2504             fds[j].revents = 0;
2505         }
2506     return fds;
2507 }
2508 
2509 /* release the file descriptor obtained in fd_sets_to_poll */
2510 /* must be called with the original fd_set arrays, before calling get_poll_results */
2511 static void release_poll_fds( const WS_fd_set *readfds, const WS_fd_set *writefds,
2512                               const WS_fd_set *exceptfds, struct pollfd *fds )
2513 {
2514     int i, j = 0;
2515 
2516     if (readfds)
2517     {
2518         for (i = 0; i < readfds->fd_count; i++, j++)
2519             if (fds[j].fd != -1) release_sock_fd( readfds->fd_array[i], fds[j].fd );
2520     }
2521     if (writefds)
2522     {
2523         for (i = 0; i < writefds->fd_count; i++, j++)
2524             if (fds[j].fd != -1) release_sock_fd( writefds->fd_array[i], fds[j].fd );
2525     }
2526     if (exceptfds)
2527     {
2528         for (i = 0; i < exceptfds->fd_count; i++, j++)
2529             if (fds[j].fd != -1)
2530             {
2531                 /* make sure we have a real error before releasing the fd */
2532                 if (!sock_error_p( fds[j].fd )) fds[j].revents = 0;
2533                 release_sock_fd( exceptfds->fd_array[i], fds[j].fd );
2534             }
2535     }
2536 }
2537 
2538 /* map the poll results back into the Windows fd sets */
2539 static int get_poll_results( WS_fd_set *readfds, WS_fd_set *writefds, WS_fd_set *exceptfds,
2540                              const struct pollfd *fds )
2541 {
2542     int i, j = 0, k, total = 0;
2543 
2544     if (readfds)
2545     {
2546         for (i = k = 0; i < readfds->fd_count; i++, j++)
2547             if (fds[j].revents) readfds->fd_array[k++] = readfds->fd_array[i];
2548         readfds->fd_count = k;
2549         total += k;
2550     }
2551     if (writefds)
2552     {
2553         for (i = k = 0; i < writefds->fd_count; i++, j++)
2554             if (fds[j].revents) writefds->fd_array[k++] = writefds->fd_array[i];
2555         writefds->fd_count = k;
2556         total += k;
2557     }
2558     if (exceptfds)
2559     {
2560         for (i = k = 0; i < exceptfds->fd_count; i++, j++)
2561             if (fds[j].revents) exceptfds->fd_array[k++] = exceptfds->fd_array[i];
2562         exceptfds->fd_count = k;
2563         total += k;
2564     }
2565     return total;
2566 }
2567 
2568 
2569 /***********************************************************************
2570  *              select                  (WS2_32.18)
2571  */
2572 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
2573                      WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
2574                      const struct WS_timeval* ws_timeout)
2575 {
2576     struct pollfd *pollfds;
2577     int count, ret, timeout = -1;
2578 
2579     TRACE("read %p, write %p, excp %p timeout %p\n",
2580           ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
2581 
2582     if (!(pollfds = fd_sets_to_poll( ws_readfds, ws_writefds, ws_exceptfds, &count )) && count)
2583     {
2584         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
2585         return SOCKET_ERROR;
2586     }
2587 
2588     if (ws_timeout) timeout = (ws_timeout->tv_sec * 1000) + (ws_timeout->tv_usec + 999) / 1000;
2589 
2590     ret = poll( pollfds, count, timeout );
2591     release_poll_fds( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
2592 
2593     if (ret == -1) SetLastError(wsaErrno());
2594     else ret = get_poll_results( ws_readfds, ws_writefds, ws_exceptfds, pollfds );
2595     HeapFree( GetProcessHeap(), 0, pollfds );
2596     return ret;
2597 }
2598 
2599 /* helper to send completion messages for client-only i/o operation case */
2600 static void WS_AddCompletion( SOCKET sock, ULONG_PTR CompletionValue, NTSTATUS CompletionStatus, ULONG_PTR Information )
2601 {
2602     NTSTATUS status;
2603 
2604     SERVER_START_REQ( add_fd_completion )
2605     {
2606         req->handle      = SOCKET2HANDLE(sock);
2607         req->cvalue      = CompletionValue;
2608         req->status      = CompletionStatus;
2609         req->information = Information;
2610         status = wine_server_call( req );
2611     }
2612     SERVER_END_REQ;
2613 }
2614 
2615 
2616 /***********************************************************************
2617  *              send                    (WS2_32.19)
2618  */
2619 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
2620 {
2621     DWORD n;
2622     WSABUF wsabuf;
2623 
2624     wsabuf.len = len;
2625     wsabuf.buf = (char*) buf;
2626 
2627     if ( WSASendTo( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
2628         return SOCKET_ERROR;
2629     else
2630         return n;
2631 }
2632 
2633 /***********************************************************************
2634  *              WSASend                 (WS2_32.72)
2635  */
2636 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2637                     LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2638                     LPWSAOVERLAPPED lpOverlapped,
2639                     LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2640 {
2641     return WSASendTo( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
2642                       NULL, 0, lpOverlapped, lpCompletionRoutine );
2643 }
2644 
2645 /***********************************************************************
2646  *              WSASendDisconnect       (WS2_32.73)
2647  */
2648 INT WINAPI WSASendDisconnect( SOCKET s, LPWSABUF lpBuffers )
2649 {
2650     return WS_shutdown( s, SD_SEND );
2651 }
2652 
2653 
2654 /***********************************************************************
2655  *              WSASendTo               (WS2_32.74)
2656  */
2657 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2658                       LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2659                       const struct WS_sockaddr *to, int tolen,
2660                       LPWSAOVERLAPPED lpOverlapped,
2661                       LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2662 {
2663     unsigned int i, options;
2664     int n, fd, err;
2665     struct ws2_async *wsa;
2666     int totalLength = 0;
2667     ULONG_PTR cvalue = (lpOverlapped && ((ULONG_PTR)lpOverlapped->hEvent & 1) == 0) ? (ULONG_PTR)lpOverlapped : 0;
2668 
2669     TRACE("socket %04lx, wsabuf %p, nbufs %d, flags %d, to %p, tolen %d, ovl %p, func %p\n",
2670           s, lpBuffers, dwBufferCount, dwFlags,
2671           to, tolen, lpOverlapped, lpCompletionRoutine);
2672 
2673     fd = get_sock_fd( s, FILE_WRITE_DATA, &options );
2674     TRACE( "fd=%d, options=%x\n", fd, options );
2675 
2676     if ( fd == -1 ) return SOCKET_ERROR;
2677 
2678     if (!(wsa = HeapAlloc( GetProcessHeap(), 0, FIELD_OFFSET(struct ws2_async, iovec[dwBufferCount]) )))
2679     {
2680         err = WSAEFAULT;
2681         goto error;
2682     }
2683 
2684     wsa->hSocket     = SOCKET2HANDLE(s);
2685     wsa->addr        = (struct WS_sockaddr *)to;
2686     wsa->addrlen.val = tolen;
2687     wsa->flags       = dwFlags;
2688     wsa->n_iovecs    = dwBufferCount;
2689     wsa->first_iovec = 0;
2690     for ( i = 0; i < dwBufferCount; i++ )
2691     {
2692         wsa->iovec[i].iov_base = lpBuffers[i].buf;
2693         wsa->iovec[i].iov_len  = lpBuffers[i].len;
2694         totalLength += lpBuffers[i].len;
2695     }
2696 
2697     if (!lpNumberOfBytesSent)
2698     {
2699         err = WSAEFAULT;
2700         goto error;
2701     }
2702 
2703     for (;;)
2704     {
2705         n = WS2_send( fd, wsa );
2706         if (n != -1 || errno != EINTR) break;
2707     }
2708     if (n == -1 && errno != EAGAIN)
2709     {
2710         err = wsaErrno();
2711         if (cvalue) WS_AddCompletion( s, cvalue, err, 0 );
2712         goto error;
2713     }
2714 
2715     if ((lpOverlapped || lpCompletionRoutine) &&
2716         !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
2717     {
2718         IO_STATUS_BLOCK *iosb = lpOverlapped ? (IO_STATUS_BLOCK *)lpOverlapped : &wsa->local_iosb;
2719 
2720         wsa->user_overlapped = lpOverlapped;
2721         wsa->completion_func = lpCompletionRoutine;
2722         release_sock_fd( s, fd );
2723 
2724         if (n == -1)
2725         {
2726             iosb->u.Status = STATUS_PENDING;
2727             iosb->Information = 0;
2728 
2729             SERVER_START_REQ( register_async )
2730             {
2731                 req->handle = wsa->hSocket;
2732                 req->type   = ASYNC_TYPE_WRITE;
2733                 req->async.callback = WS2_async_send;
2734                 req->async.iosb     = iosb;
2735                 req->async.arg      = wsa;
2736                 req->async.apc      = ws2_async_apc;
2737                 req->async.event    = lpCompletionRoutine ? 0 : lpOverlapped->hEvent;
2738                 req->async.cvalue   = cvalue;
2739                 err = wine_server_call( req );
2740             }
2741             SERVER_END_REQ;
2742 
2743             if (err != STATUS_PENDING) HeapFree( GetProcessHeap(), 0, wsa );
2744             WSASetLastError( NtStatusToWSAError( err ));
2745             return SOCKET_ERROR;
2746         }
2747 
2748         iosb->u.Status = STATUS_SUCCESS;
2749         iosb->Information = n;
2750         *lpNumberOfBytesSent = n;
2751         if (!wsa->completion_func)
2752         {
2753             if (cvalue) WS_AddCompletion( s, cvalue, STATUS_SUCCESS, n );
2754             SetEvent( lpOverlapped->hEvent );
2755             HeapFree( GetProcessHeap(), 0, wsa );
2756         }
2757         else NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)ws2_async_apc,
2758                                (ULONG_PTR)wsa, (ULONG_PTR)iosb, 0 );
2759         WSASetLastError(0);
2760         return 0;
2761     }
2762 
2763     if ( _is_blocking(s) )
2764     {
2765         /* On a blocking non-overlapped stream socket,
2766          * sending blocks until the entire buffer is sent. */
2767         DWORD timeout_start = GetTickCount();
2768 
2769         *lpNumberOfBytesSent = 0;
2770 
2771         while (wsa->first_iovec < dwBufferCount)
2772         {
2773             struct pollfd pfd;
2774             int timeout = GET_SNDTIMEO(fd);
2775 
2776             if (n >= 0)
2777             {
2778                 *lpNumberOfBytesSent += n;
2779                 while (wsa->first_iovec < dwBufferCount && wsa->iovec[wsa->first_iovec].iov_len <= n)
2780                     n -= wsa->iovec[wsa->first_iovec++].iov_len;
2781                 if (wsa->first_iovec >= dwBufferCount) break;
2782                 wsa->iovec[wsa->first_iovec].iov_base = (char*)wsa->iovec[wsa->first_iovec].iov_base + n;
2783                 wsa->iovec[wsa->first_iovec].iov_len -= n;
2784             }
2785 
2786             if (timeout != -1)
2787             {
2788                 timeout -= GetTickCount() - timeout_start;
2789                 if (timeout < 0) timeout = 0;
2790             }
2791 
2792             pfd.fd = fd;
2793             pfd.events = POLLOUT;
2794 
2795             if (!timeout || !poll( &pfd, 1, timeout ))
2796             {
2797                 err = WSAETIMEDOUT;
2798                 goto error; /* msdn says a timeout in send is fatal */
2799             }
2800 
2801             n = WS2_send( fd, wsa );
2802             if (n == -1 && errno != EAGAIN && errno != EINTR)
2803             {
2804                 err = wsaErrno();
2805                 goto error;
2806             }
2807         }
2808     }
2809     else  /* non-blocking */
2810     {
2811         if (n < totalLength)
2812             _enable_event(SOCKET2HANDLE(s), FD_WRITE, 0, 0);
2813         if (n == -1)
2814         {
2815             err = WSAEWOULDBLOCK;
2816             goto error;
2817         }
2818         *lpNumberOfBytesSent = n;
2819     }
2820 
2821     TRACE(" -> %i bytes\n", *lpNumberOfBytesSent);
2822 
2823     HeapFree( GetProcessHeap(), 0, wsa );
2824     release_sock_fd( s, fd );
2825     WSASetLastError(0);
2826     return 0;
2827 
2828 error:
2829     HeapFree( GetProcessHeap(), 0, wsa );
2830     release_sock_fd( s, fd );
2831     WARN(" -> ERROR %d\n", err);
2832     WSASetLastError(err);
2833     return SOCKET_ERROR;
2834 }
2835 
2836 /***********************************************************************
2837  *              sendto          (WS2_32.20)
2838  */
2839 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
2840                               const struct WS_sockaddr *to, int tolen)
2841 {
2842     DWORD n;
2843     WSABUF wsabuf;
2844 
2845     wsabuf.len = len;
2846     wsabuf.buf = (char*) buf;
2847 
2848     if ( WSASendTo(s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
2849         return SOCKET_ERROR;
2850     else
2851         return n;
2852 }
2853 
2854 /***********************************************************************
2855  *              setsockopt              (WS2_32.21)
2856  */
2857 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
2858                                   const char *optval, int optlen)
2859 {
2860     int fd;
2861     int woptval;
2862     struct linger linger;
2863     struct timeval tval;
2864 
2865     TRACE("socket: %04lx, level 0x%x, name 0x%x, ptr %p, len %d\n",
2866           s, level, optname, optval, optlen);
2867 
2868     /* some broken apps pass the value directly instead of a pointer to it */
2869     if(IS_INTRESOURCE(optval))
2870     {
2871         SetLastError(WSAEFAULT);
2872         return SOCKET_ERROR;
2873     }
2874 
2875     switch(level)
2876     {
2877     case WS_SOL_SOCKET:
2878         switch(optname)
2879         {
2880         /* Some options need some conversion before they can be sent to
2881          * setsockopt. The conversions are done here, then they will fall though
2882          * to the general case. Special options that are not passed to
2883          * setsockopt follow below that.*/
2884 
2885         case WS_SO_DONTLINGER:
2886             linger.l_onoff  = *((const int*)optval) ? 0: 1;
2887             linger.l_linger = 0;
2888             level = SOL_SOCKET;
2889             optname = SO_LINGER;
2890             optval = (char*)&linger;
2891             optlen = sizeof(struct linger);
2892             break;
2893 
2894         case WS_SO_LINGER:
2895             linger.l_onoff  = ((LINGER*)optval)->l_onoff;
2896             linger.l_linger  = ((LINGER*)optval)->l_linger;
2897             /* FIXME: what is documented behavior if SO_LINGER optval
2898                is null?? */
2899             level = SOL_SOCKET;
2900             optname = SO_LINGER;
2901             optval = (char*)&linger;
2902             optlen = sizeof(struct linger);
2903             break;
2904 
2905         case WS_SO_RCVBUF:
2906             if (*(const int*)optval < 2048)
2907             {
2908                 WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(const int*)optval );
2909                 return 0;
2910             }
2911             /* Fall through */
2912 
2913         /* The options listed here don't need any special handling. Thanks to
2914          * the conversion happening above, options from there will fall through
2915          * to this, too.*/
2916         case WS_SO_ACCEPTCONN:
2917         case WS_SO_BROADCAST:
2918         case WS_SO_ERROR:
2919         case WS_SO_KEEPALIVE:
2920         case WS_SO_OOBINLINE:
2921         /* BSD socket SO_REUSEADDR is not 100% compatible to winsock semantics.
2922          * however, using it the BSD way fixes bug 8513 and seems to be what
2923          * most programmers assume, anyway */
2924         case WS_SO_REUSEADDR:
2925         case WS_SO_SNDBUF:
2926         case WS_SO_TYPE:
2927             convert_sockopt(&level, &optname);
2928             break;
2929 
2930         /* SO_DEBUG is a privileged operation, ignore it. */
2931         case WS_SO_DEBUG:
2932             TRACE("Ignoring SO_DEBUG\n");
2933             return 0;
2934 
2935         /* For some reason the game GrandPrixLegends does set SO_DONTROUTE on its
2936          * socket. According to MSDN, this option is silently ignored.*/
2937         case WS_SO_DONTROUTE:
2938             TRACE("Ignoring SO_DONTROUTE\n");
2939             return 0;
2940 
2941         /* Stops two sockets from being bound to the same port. Always happens
2942          * on unix systems, so just drop it. */
2943         case WS_SO_EXCLUSIVEADDRUSE:
2944             TRACE("Ignoring SO_EXCLUSIVEADDRUSE, is always set.\n");
2945             return 0;
2946 
2947         /* SO_OPENTYPE does not require a valid socket handle. */
2948         case WS_SO_OPENTYPE:
2949             if (!optlen || optlen < sizeof(int) || !optval)
2950             {
2951                 SetLastError(WSAEFAULT);
2952                 return SOCKET_ERROR;
2953             }
2954             get_per_thread_data()->opentype = *(const int *)optval;
2955             TRACE("setting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
2956             return 0;
2957 
2958 #ifdef SO_RCVTIMEO
2959         case WS_SO_RCVTIMEO:
2960 #endif
2961 #ifdef SO_SNDTIMEO
2962         case WS_SO_SNDTIMEO:
2963 #endif
2964 #if defined(SO_RCVTIMEO) || defined(SO_SNDTIMEO)
2965             if (optval && optlen == sizeof(UINT32)) {
2966                 /* WinSock passes milliseconds instead of struct timeval */
2967                 tval.tv_usec = (*(const UINT32*)optval % 1000) * 1000;
2968                 tval.tv_sec = *(const UINT32*)optval / 1000;
2969                 /* min of 500 milliseconds */
2970                 if (tval.tv_sec == 0 && tval.tv_usec < 500000)
2971                     tval.tv_usec = 500000;
2972                 optlen = sizeof(struct timeval);
2973                 optval = (char*)&tval;
2974             } else if (optlen == sizeof(struct timeval)) {
2975                 WARN("SO_SND/RCVTIMEO for %d bytes: assuming unixism\n", optlen);
2976             } else {
2977                 WARN("SO_SND/RCVTIMEO for %d bytes is weird: ignored\n", optlen);
2978                 return 0;
2979             }
2980             convert_sockopt(&level, &optname);
2981             break;
2982 #endif
2983 
2984         default:
2985             TRACE("Unknown SOL_SOCKET optname: 0x%08x\n", optname);
2986             SetLastError(WSAENOPROTOOPT);
2987             return SOCKET_ERROR;
2988         }
2989         break; /* case WS_SOL_SOCKET */
2990 
2991 #ifdef HAVE_IPX
2992     case NSPROTO_IPX:
2993         switch(optname)
2994         {
2995         case IPX_PTYPE:
2996             fd = get_sock_fd( s, 0, NULL );
2997             TRACE("trying to set IPX_PTYPE: %d (fd: %d)\n", *(const int*)optval, fd);
2998 
2999             /* We try to set the ipx type on ipx socket level. */
3000 #ifdef SOL_IPX
3001             if(setsockopt(fd, SOL_IPX, IPX_TYPE, optval, optlen) == -1)
3002             {
3003                 ERR("IPX: could not set ipx option type; expect weird behaviour\n");
3004                 release_sock_fd( s, fd );
3005                 return SOCKET_ERROR;
3006             }
3007 #else
3008             {
3009                 struct ipx val;
3010                 /* Should we retrieve val using a getsockopt call and then
3011                  * set the modified one? */
3012                 val.ipx_pt = *optval;
3013                 setsockopt(fd, 0, SO_DEFAULT_HEADERS, &val, sizeof(struct ipx));
3014             }
3015 #endif
3016             release_sock_fd( s, fd );
3017             return 0;
3018 
3019         case IPX_FILTERPTYPE:
3020             /* Sets the receive filter packet type, at the moment we don't support it */
3021             FIXME("IPX_FILTERPTYPE: %x\n", *optval);
3022             /* Returning 0 is better for now than returning a SOCKET_ERROR */
3023             return 0;
3024 
3025         default:
3026             FIXME("opt_name:%x\n", optname);
3027             return SOCKET_ERROR;
3028         }
3029         break; /* case NSPROTO_IPX */
3030 #endif
3031 
3032     /* Levels WS_IPPROTO_TCP and WS_IPPROTO_IP convert directly */
3033     case WS_IPPROTO_TCP:
3034         switch(optname)
3035         {
3036         case WS_TCP_NODELAY:
3037             convert_sockopt(&level, &optname);
3038             break;
3039         default:
3040             FIXME("Unknown IPPROTO_TCP optname 0x%08x\n", optname);
3041             return SOCKET_ERROR;
3042         }
3043         break;
3044 
3045     case WS_IPPROTO_IP:
3046         switch(optname)
3047         {
3048         case WS_IP_ADD_MEMBERSHIP:
3049         case WS_IP_DROP_MEMBERSHIP:
3050 #ifdef IP_HDRINCL
3051         case WS_IP_HDRINCL:
3052 #endif
3053         case WS_IP_MULTICAST_IF:
3054         case WS_IP_MULTICAST_LOOP:
3055         case WS_IP_MULTICAST_TTL:
3056         case WS_IP_OPTIONS:
3057         case WS_IP_TOS:
3058         case WS_IP_TTL:
3059             convert_sockopt(&level, &optname);
3060             break;
3061         case WS_IP_DONTFRAGMENT:
3062             FIXME("IP_DONTFRAGMENT is silently ignored!\n");
3063             return 0;
3064         default:
3065             FIXME("Unknown IPPROTO_IP optname 0x%08x\n", optname);
3066             return SOCKET_ERROR;
3067         }
3068         break;
3069 
3070     default:
3071         FIXME("Unknown level: 0x%08x\n", level);
3072         return SOCKET_ERROR;
3073     } /* end switch(level) */
3074 
3075     /* avoid endianness issues if argument is a 16-bit int */
3076     if (optval && optlen < sizeof(int))
3077     {
3078         woptval= *((const INT16 *) optval);
3079         optval= (char*) &woptval;
3080         optlen=sizeof(int);
3081     }
3082     fd = get_sock_fd( s, 0, NULL );
3083     if (fd == -1) return SOCKET_ERROR;
3084 
3085     if (setsockopt(fd, level, optname, optval, optlen) == 0)
3086     {
3087         release_sock_fd( s, fd );
3088         return 0;
3089     }
3090     TRACE("Setting socket error, %d\n", wsaErrno());
3091     SetLastError(wsaErrno());
3092     release_sock_fd( s, fd );
3093 
3094     return SOCKET_ERROR;
3095 }
3096 
3097 /***********************************************************************
3098  *              shutdown                (WS2_32.22)
3099  */
3100 int WINAPI WS_shutdown(SOCKET s, int how)
3101 {
3102     int fd, err = WSAENOTSOCK;
3103     unsigned int options, clear_flags = 0;
3104 
3105     fd = get_sock_fd( s, 0, &options );
3106     TRACE("socket %04lx, how %i %x\n", s, how, options );
3107 
3108     if (fd == -1)
3109         return SOCKET_ERROR;
3110 
3111     switch( how )
3112     {
3113     case 0: /* drop receives */
3114         clear_flags |= FD_READ;
3115         break;
3116     case 1: /* drop sends */
3117         clear_flags |= FD_WRITE;
3118         break;
3119     case 2: /* drop all */
3120         clear_flags |= FD_READ|FD_WRITE;
3121     default:
3122         clear_flags |= FD_WINE_LISTENING;
3123     }
3124 
3125     if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
3126     {
3127         switch ( how )
3128         {
3129         case SD_RECEIVE:
3130             err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3131             break;
3132         case SD_SEND:
3133             err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3134             break;
3135         case SD_BOTH:
3136         default:
3137             err = WS2_register_async_shutdown( s, ASYNC_TYPE_READ );
3138             if (!err) err = WS2_register_async_shutdown( s, ASYNC_TYPE_WRITE );
3139             break;
3140         }
3141         if (err) goto error;
3142     }
3143     else /* non-overlapped mode */
3144     {
3145         if ( shutdown( fd, how ) )
3146         {
3147             err = wsaErrno();
3148             goto error;
3149         }
3150     }
3151 
3152     release_sock_fd( s, fd );
3153     _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3154     if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
3155     return 0;
3156 
3157 error:
3158     release_sock_fd( s, fd );
3159     _enable_event( SOCKET2HANDLE(s), 0, 0, clear_flags );
3160     WSASetLastError( err );
3161     return SOCKET_ERROR;
3162 }
3163 
3164 /***********************************************************************
3165  *              socket          (WS2_32.23)
3166  */
3167 SOCKET WINAPI WS_socket(int af, int type, int protocol)
3168 {
3169     TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
3170 
3171     return WSASocketA( af, type, protocol, NULL, 0,
3172                        get_per_thread_data()->opentype ? 0 : WSA_FLAG_OVERLAPPED );
3173 }
3174 
3175 
3176 /***********************************************************************
3177  *              gethostbyaddr           (WS2_32.51)
3178  */
3179 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len, int type)
3180 {
3181     struct WS_hostent *retval = NULL;
3182     struct hostent* host;
3183 
3184 #ifdef HAVE_LINUX_GETHOSTBYNAME_R_6
3185     char *extrabuf;
3186     int ebufsize=1024;
3187     struct hostent hostentry;
3188     int locerr=ENOBUFS;
3189     host = NULL;
3190     extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3191     while(extrabuf) {
3192         int res = gethostbyaddr_r(addr, len, type,
3193                                   &hostentry, extrabuf, ebufsize, &host, &locerr);
3194         if( res != ERANGE) break;
3195         ebufsize *=2;
3196         extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3197     }
3198     if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3199 #else
3200     EnterCriticalSection( &csWSgetXXXbyYYY );
3201     host = gethostbyaddr(addr, len, type);
3202     if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3203 #endif
3204     if( host != NULL ) retval = WS_dup_he(host);
3205 #ifdef  HAVE_LINUX_GETHOSTBYNAME_R_6
3206     HeapFree(GetProcessHeap(),0,extrabuf);
3207 #else
3208     LeaveCriticalSection( &csWSgetXXXbyYYY );
3209 #endif
3210     TRACE("ptr %p, len %d, type %d ret %p\n", addr, len, type, retval);
3211     return retval;
3212 }
3213 
3214 /***********************************************************************
3215  *              gethostbyname           (WS2_32.52)
3216  */
3217 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
3218 {
3219     struct WS_hostent *retval = NULL;
3220     struct hostent*     host;
3221 #ifdef  HAVE_LINUX_GETHOSTBYNAME_R_6
3222     char *extrabuf;
3223     int ebufsize=1024;
3224     struct hostent hostentry;
3225     int locerr = ENOBUFS;
3226 #endif
3227     char buf[100];
3228     if( !name || !name[0]) {
3229         name = buf;
3230         if( gethostname( buf, 100) == -1) {
3231             SetLastError( WSAENOBUFS); /* appropriate ? */
3232             return retval;
3233         }
3234     }
3235 #ifdef  HAVE_LINUX_GETHOSTBYNAME_R_6
3236     host = NULL;
3237     extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
3238     while(extrabuf) {
3239         int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
3240         if( res != ERANGE) break;
3241         ebufsize *=2;
3242         extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
3243     }
3244     if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
3245 #else
3246     EnterCriticalSection( &csWSgetXXXbyYYY );
3247     host = gethostbyname(name);
3248     if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
3249 #endif
3250     if (host) retval = WS_dup_he(host);
3251 #ifdef  HAVE_LINUX_GETHOSTBYNAME_R_6
3252     HeapFree(GetProcessHeap(),0,extrabuf);
3253 #else
3254     LeaveCriticalSection( &csWSgetXXXbyYYY );
3255 #endif
3256     if (retval && retval->h_addr_list[0][0] == 127 &&
3257         strcmp(name, "localhost") != 0)
3258     {
3259         /* hostname != "localhost" but has loopback address. replace by our
3260          * special address.*/
3261         memcpy(retval->h_addr_list[0], magic_loopback_addr, 4);
3262     }
3263     TRACE( "%s ret %p\n", debugstr_a(name), retval );
3264     return retval;
3265 }
3266 
3267 
3268 /***********************************************************************
3269  *              getprotobyname          (WS2_32.53)
3270  */
3271 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
3272 {
3273     struct WS_protoent* retval = NULL;
3274 #ifdef HAVE_GETPROTOBYNAME
3275     struct protoent*     proto;
3276     EnterCriticalSection( &csWSgetXXXbyYYY );
3277     if( (proto = getprotobyname(name)) != NULL )
3278     {
3279         retval = WS_dup_pe(proto);
3280     }
3281     else {
3282         MESSAGE("protocol %s not found; You might want to add "
3283                 "this to /etc/protocols\n", debugstr_a(name) );
3284         SetLastError(WSANO_DATA);
3285     }
3286     LeaveCriticalSection( &csWSgetXXXbyYYY );
3287 #endif
3288     TRACE( "%s ret %p\n", debugstr_a(name), retval );
3289     return retval;
3290 }
3291 
3292 
3293 /***********************************************************************
3294  *              getprotobynumber        (WS2_32.54)
3295  */
3296 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
3297 {
3298     struct WS_protoent* retval = NULL;
3299 #ifdef HAVE_GETPROTOBYNUMBER
3300     struct protoent*     proto;
3301     EnterCriticalSection( &csWSgetXXXbyYYY );
3302     if( (proto = getprotobynumber(number)) != NULL )
3303     {
3304         retval = WS_dup_pe(proto);
3305     }
3306     else {
3307         MESSAGE("protocol number %d not found; You might want to add "
3308                 "this to /etc/protocols\n", number );
3309         SetLastError(WSANO_DATA);
3310     }
3311     LeaveCriticalSection( &csWSgetXXXbyYYY );
3312 #endif
3313     TRACE("%i ret %p\n", number, retval);
3314     return retval;
3315 }
3316 
3317 
3318 /***********************************************************************
3319  *              getservbyname           (WS2_32.55)
3320  */
3321 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
3322 {
3323     struct WS_servent* retval = NULL;
3324     struct servent*     serv;
3325     char *name_str;
3326     char *proto_str = NULL;
3327 
3328     if (!(name_str = strdup_lower(name))) return NULL;
3329 
3330     if (proto && *proto)
3331     {
3332         if (!(proto_str = strdup_lower(proto)))
3333         {
3334             HeapFree( GetProcessHeap(), 0, name_str );
3335             return NULL;
3336         }
3337     }
3338 
3339     EnterCriticalSection( &csWSgetXXXbyYYY );
3340     serv = getservbyname(name_str, proto_str);
3341     if( serv != NULL )
3342     {
3343         retval = WS_dup_se(serv);
3344     }
3345     else SetLastError(WSANO_DATA);
3346     LeaveCriticalSection( &csWSgetXXXbyYYY );
3347     HeapFree( GetProcessHeap(), 0, proto_str );
3348     HeapFree( GetProcessHeap(), 0, name_str );
3349     TRACE( "%s, %s ret %p\n", debugstr_a(name), debugstr_a(proto), retval );
3350     return retval;
3351 }
3352 
3353 /***********************************************************************
3354  *              freeaddrinfo            (WS2_32.@)
3355  */
3356 void WINAPI WS_freeaddrinfo(struct WS_addrinfo *res)
3357 {
3358     while (res) {
3359         struct WS_addrinfo *next;
3360 
3361         HeapFree(GetProcessHeap(),0,res->ai_canonname);
3362         HeapFree(GetProcessHeap(),0,res->ai_addr);
3363         next = res->ai_next;
3364         HeapFree(GetProcessHeap(),0,res);
3365         res = next;
3366     }
3367 }
3368 
3369 /* helper functions for getaddrinfo()/getnameinfo() */
3370 static int convert_aiflag_w2u(int winflags) {
3371     int i, unixflags = 0;
3372 
3373     for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
3374         if (ws_aiflag_map[i][0] & winflags) {
3375             unixflags |= ws_aiflag_map[i][1];
3376             winflags &= ~ws_aiflag_map[i][0];
3377         }
3378     if (winflags)
3379         FIXME("Unhandled windows AI_xxx flags %x\n", winflags);
3380     return unixflags;
3381 }
3382 
3383 static int convert_niflag_w2u(int winflags) {
3384     int i, unixflags = 0;
3385 
3386     for (i=0;i<sizeof(ws_niflag_map)/sizeof(ws_niflag_map[0]);i++)
3387         if (ws_niflag_map[i][0] & winflags) {
3388             unixflags |= ws_niflag_map[i][1];
3389             winflags &= ~ws_niflag_map[i][0];
3390         }
3391     if (winflags)
3392         FIXME("Unhandled windows NI_xxx flags %x\n", winflags);
3393     return unixflags;
3394 }
3395 
3396 static int convert_aiflag_u2w(int unixflags) {
3397     int i, winflags = 0;
3398 
3399     for (i=0;i<sizeof(ws_aiflag_map)/sizeof(ws_aiflag_map[0]);i++)
3400         if (ws_aiflag_map[i][1] & unixflags) {
3401             winflags |= ws_aiflag_map[i][0];
3402             unixflags &= ~ws_aiflag_map[i][1];
3403         }
3404     if (unixflags) /* will warn usually */
3405         WARN("Unhandled UNIX AI_xxx flags %x\n", unixflags);
3406     return winflags;
3407 }
3408 
3409 static int convert_eai_u2w(int unixret) {
3410     int i;
3411 
3412     for (i=0;ws_eai_map[i][0];i++)
3413         if (ws_eai_map[i][1] == unixret)
3414             return ws_eai_map[i][0];
3415     return unixret;
3416 }
3417 
3418 /***********************************************************************
3419  *              getaddrinfo             (WS2_32.@)
3420  */
3421 int WINAPI WS_getaddrinfo(LPCSTR nodename, LPCSTR servname, const struct WS_addrinfo *hints, struct WS_addrinfo **res)
3422 {
3423 #ifdef HAVE_GETADDRINFO
3424     struct addrinfo *unixaires = NULL;
3425     int   result;
3426     struct addrinfo unixhints, *punixhints = NULL;
3427     CHAR *node = NULL, *serv = NULL;
3428 
3429     if (nodename)
3430         if (!(node = strdup_lower(nodename))) return WSA_NOT_ENOUGH_MEMORY;
3431 
3432     if (servname) {
3433         if (!(serv = strdup_lower(servname))) {
3434             HeapFree(GetProcessHeap(), 0, node);
3435             return WSA_NOT_ENOUGH_MEMORY;
3436         }
3437     }
3438 
3439     if (hints) {
3440         punixhints = &unixhints;
3441 
3442         memset(&unixhints, 0, sizeof(unixhints));
3443         punixhints->ai_flags    = convert_aiflag_w2u(hints->ai_flags);
3444         if (hints->ai_family == 0) /* wildcard, specific to getaddrinfo() */
3445             punixhints->ai_family = 0;
3446         else
3447             punixhints->ai_family = convert_af_w2u(hints->ai_family);
3448         if (hints->ai_socktype == 0) /* wildcard, specific to getaddrinfo() */
3449             punixhints->ai_socktype = 0;
3450         else
3451             punixhints->ai_socktype = convert_socktype_w2u(hints->ai_socktype);
3452         if (hints->ai_protocol == 0) /* wildcard, specific to getaddrinfo() */
3453             punixhints->ai_protocol = 0;
3454         else
3455             punixhints->ai_protocol = convert_proto_w2u(hints->ai_protocol);
3456     }
3457 
3458     /* getaddrinfo(3) is thread safe, no need to wrap in CS */
3459     result = getaddrinfo(nodename, servname, punixhints, &unixaires);
3460 
3461     TRACE("%s, %s %p -> %p %d\n", nodename, servname, hints, res, result);
3462 
3463     HeapFree(GetProcessHeap(), 0, node);
3464     HeapFree(GetProcessHeap(), 0, serv);
3465 
3466     if (!result) {
3467         struct addrinfo *xuai = unixaires;
3468         struct WS_addrinfo **xai = res;
3469 
3470         *xai = NULL;
3471         while (xuai) {
3472             struct WS_addrinfo *ai = HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY, sizeof(struct WS_addrinfo));
3473             int len;
3474 
3475             if (!ai)
3476                 goto outofmem;
3477 
3478             *xai = ai;xai = &ai->ai_next;
3479             ai->ai_flags    = convert_aiflag_u2w(xuai->ai_flags);
3480             ai->ai_family   = convert_af_u2w(xuai->ai_family);
3481             ai->ai_socktype = convert_socktype_u2w(xuai->ai_socktype);
3482             ai->ai_protocol = convert_proto_u2w(xuai->ai_protocol);
3483             if (xuai->ai_canonname) {
3484                 TRACE("canon name - %s\n",debugstr_a(xuai->ai_canonname));
3485                 ai->ai_canonname = HeapAlloc(GetProcessHeap(),0,strlen(xuai->ai_canonname)+1);
3486                 if (!ai->ai_canonname)
3487                     goto outofmem;
3488                 strcpy(ai->ai_canonname,xuai->ai_canonname);
3489             }
3490             len = xuai->ai_addrlen;
3491             ai->ai_addr = HeapAlloc(GetProcessHeap(),0,len);
3492             if (!ai->ai_addr)
3493                 goto outofmem;
3494             ai->ai_addrlen = len;
3495             do {
3496                 int winlen = ai->ai_addrlen;
3497 
3498                 if (!ws_sockaddr_u2ws(xuai->ai_addr, ai->ai_addr, &winlen)) {
3499                     ai->ai_addrlen = winlen;
3500                     break;
3501                 }
3502                 len = 2*len;
3503                 ai->ai_addr = HeapReAlloc(GetProcessHeap(),0,ai->ai_addr,len);
3504                 if (!ai->ai_addr)
3505                     goto outofmem;
3506                 ai->ai_addrlen = len;
3507             } while (1);
3508             xuai = xuai->ai_next;
3509         }
3510         freeaddrinfo(unixaires);
3511     } else {
3512         result = convert_eai_u2w(result);
3513         *res = NULL;
3514     }
3515     return result;
3516 
3517 outofmem:
3518     if (*res) WS_freeaddrinfo(*res);
3519     if (unixaires) freeaddrinfo(unixaires);
3520     *res = NULL;
3521     return WSA_NOT_ENOUGH_MEMORY;
3522 #else
3523     FIXME("getaddrinfo() failed, not found during buildtime.\n");
3524     return EAI_FAIL;
3525 #endif
3526 }
3527 
3528 /***********************************************************************
3529  *              GetAddrInfoW            (WS2_32.@)
3530  */
3531 int WINAPI GetAddrInfoW(LPCWSTR nodename, LPCWSTR servname, const ADDRINFOW *hints, PADDRINFOW *res)
3532 {
3533     FIXME("empty stub!\n");
3534     return EAI_FAIL;
3535 }
3536 
3537 int WINAPI WS_getnameinfo(const SOCKADDR *sa, WS_socklen_t salen, PCHAR host,
3538                           DWORD hostlen, PCHAR serv, DWORD servlen, INT flags)
3539 {
3540 #ifdef HAVE_GETNAMEINFO
3541     int ret;
3542     union generic_unix_sockaddr sa_u;
3543     unsigned int size;
3544 
3545     TRACE("%s %d %p %d %p %d %d\n", debugstr_sockaddr(sa), salen, host, hostlen,
3546           serv, servlen, flags);
3547 
3548     size = ws_sockaddr_ws2u(sa, salen, &sa_u);
3549     if (!size)
3550     {
3551         WSASetLastError(WSAEFAULT);
3552         return WSA_NOT_ENOUGH_MEMORY;
3553     }
3554     ret = getnameinfo(&sa_u.addr, size, host, hostlen, serv, servlen, convert_niflag_w2u(flags));
3555     return convert_eai_u2w(ret);
3556 #else
3557     FIXME("getnameinfo() failed, not found during buildtime.\n");
3558     return EAI_FAIL;
3559 #endif
3560 }
3561 
3562 /***********************************************************************
3563  *              getservbyport           (WS2_32.56)
3564  */
3565 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
3566 {
3567     struct WS_servent* retval = NULL;
3568 #ifdef HAVE_GETSERVBYPORT
3569     struct servent*     serv;
3570     char *proto_str = NULL;
3571 
3572     if (proto && *proto)
3573     {
3574         if (!(proto_str = strdup_lower(proto))) return NULL;
3575     }
3576     EnterCriticalSection( &csWSgetXXXbyYYY );
3577     if( (serv = getservbyport(port, proto_str)) != NULL ) {
3578         retval = WS_dup_se(serv);
3579     }
3580     else SetLastError(WSANO_DATA);
3581     LeaveCriticalSection( &csWSgetXXXbyYYY );
3582     HeapFree( GetProcessHeap(), 0, proto_str );
3583 #endif
3584     TRACE("%d (i.e. port %d), %s ret %p\n", port, (int)ntohl(port), debugstr_a(proto), retval);
3585     return retval;
3586 }
3587 
3588 
3589 /***********************************************************************
3590  *              gethostname           (WS2_32.57)
3591  */
3592 int WINAPI WS_gethostname(char *name, int namelen)
3593 {
3594     TRACE("name %p, len %d\n", name, namelen);
3595 
3596     if (gethostname(name, namelen) == 0)
3597     {
3598         TRACE("<- '%s'\n", name);
3599         return 0;
3600     }
3601     SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
3602     TRACE("<- ERROR !\n");
3603     return SOCKET_ERROR;
3604 }
3605 
3606 
3607 /* ------------------------------------- Windows sockets extensions -- *
3608  *                                                                     *
3609  * ------------------------------------------------------------------- */
3610 
3611 /***********************************************************************
3612  *              WSAEnumNetworkEvents (WS2_32.36)
3613  */
3614 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
3615 {
3616     int ret;
3617 
3618     TRACE("%08lx, hEvent %p, lpEvent %p\n", s, hEvent, lpEvent );
3619 
3620     SERVER_START_REQ( get_socket_event )
3621     {
3622         req->handle  = SOCKET2HANDLE(s);
3623         req->service = TRUE;
3624         req->c_event = hEvent;
3625         wine_server_set_reply( req, lpEvent->iErrorCode, sizeof(lpEvent->iErrorCode) );
3626         if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
3627     }
3628     SERVER_END_REQ;
3629     if (!ret) return 0;
3630     SetLastError(WSAEINVAL);
3631     return SOCKET_ERROR;
3632 }
3633 
3634 /***********************************************************************
3635  *              WSAEventSelect (WS2_32.39)
3636  */
3637 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
3638 {
3639     int ret;
3640 
3641     TRACE("%08lx, hEvent %p, event %08x\n", s, hEvent, lEvent);
3642 
3643     SERVER_START_REQ( set_socket_event )
3644     {
3645         req->handle = SOCKET2HANDLE(s);
3646         req->mask   = lEvent;
3647         req->event  = hEvent;
3648         req->window = 0;
3649         req->msg    = 0;
3650         ret = wine_server_call( req );
3651     }
3652     SERVER_END_REQ;
3653     if (!ret) return 0;
3654     SetLastError(WSAEINVAL);
3655     return SOCKET_ERROR;
3656 }
3657 
3658 /**********************************************************************
3659  *      WSAGetOverlappedResult (WS2_32.40)
3660  */
3661 BOOL WINAPI WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
3662                                     LPDWORD lpcbTransfer, BOOL fWait,
3663                                     LPDWORD lpdwFlags )
3664 {
3665     NTSTATUS status;
3666 
3667     TRACE( "socket %04lx ovl %p trans %p, wait %d flags %p\n",
3668            s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
3669 
3670     if ( lpOverlapped == NULL )
3671     {
3672