Added regedit unit test, a couple minor changes to regedit.
[wine] / dlls / winsock / socket.c
1 /*
2  * based on Windows Sockets 1.1 specs
3  * (ftp.microsoft.com:/Advsys/winsock/spec11/WINSOCK.TXT)
4  *
5  * Copyright (C) 1993,1994,1996,1997 John Brezak, Erik Bos, Alex Korobka.
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  *
21  * NOTE: If you make any changes to fix a particular app, make sure
22  * they don't break something else like Netscape or telnet and ftp
23  * clients and servers (www.winsite.com got a lot of those).
24  */
25
26 #include "config.h"
27 #include "wine/port.h"
28
29 #include <stdio.h>
30 #include <string.h>
31 #include <sys/types.h>
32 #ifdef HAVE_SYS_IPC_H
33 # include <sys/ipc.h>
34 #endif
35 #ifdef HAVE_SYS_IOCTL_H
36 # include <sys/ioctl.h>
37 #endif
38 #ifdef HAVE_SYS_FILIO_H
39 # include <sys/filio.h>
40 #endif
41 #ifdef HAVE_SYS_SOCKIO_H
42 # include <sys/sockio.h>
43 #endif
44
45 #if defined(__EMX__)
46 # include <sys/so_ioctl.h>
47 #endif
48
49 #ifdef HAVE_SYS_PARAM_H
50 # include <sys/param.h>
51 #endif
52
53 #ifdef HAVE_SYS_MSG_H
54 # include <sys/msg.h>
55 #endif
56 #ifdef HAVE_SYS_WAIT_H
57 # include <sys/wait.h>
58 #endif
59 #include <sys/uio.h>
60 #ifdef HAVE_SYS_SOCKET_H
61 #include <sys/socket.h>
62 #endif
63 #ifdef HAVE_NETINET_IN_H
64 # include <netinet/in.h>
65 #endif
66 #ifdef HAVE_NETINET_TCP_H
67 # include <netinet/tcp.h>
68 #endif
69 #ifdef HAVE_ARPA_INET_H
70 # include <arpa/inet.h>
71 #endif
72 #include <ctype.h>
73 #include <fcntl.h>
74 #include <errno.h>
75 #ifdef HAVE_SYS_ERRNO_H
76 #include <sys/errno.h>
77 #endif
78 #ifdef HAVE_NETDB_H
79 #include <netdb.h>
80 #endif
81 #include <unistd.h>
82 #include <stdlib.h>
83 #ifdef HAVE_ARPA_NAMESER_H
84 # include <arpa/nameser.h>
85 #endif
86 #ifdef HAVE_RESOLV_H
87 # include <resolv.h>
88 #endif
89 #ifdef HAVE_NET_IF_H
90 # include <net/if.h>
91 #endif
92 #ifdef HAVE_IPX_GNU
93 # include <netipx/ipx.h>
94 # define HAVE_IPX
95 #endif
96 #ifdef HAVE_IPX_LINUX
97 # include <asm/types.h>
98 # include <linux/ipx.h>
99 # define HAVE_IPX
100 #endif
101
102 #ifdef HAVE_SYS_TIME_H
103 # include <sys/time.h>
104 #endif
105
106 #include "wine/winbase16.h"
107 #include "wingdi.h"
108 #include "winuser.h"
109 #include "winerror.h"
110 #include "winsock2.h"
111 #include "ws2tcpip.h"
112 #include "wsipx.h"
113 #include "wine/winsock16.h"
114 #include "winnt.h"
115 #include "wine/server.h"
116 #include "wine/debug.h"
117
118
119 WINE_DEFAULT_DEBUG_CHANNEL(winsock);
120
121 /* critical section to protect some non-rentrant net function */
122 extern CRITICAL_SECTION csWSgetXXXbyYYY;
123
124 #define DEBUG_SOCKADDR 0
125 #define dump_sockaddr(a) \
126         DPRINTF("sockaddr_in: family %d, address %s, port %d\n", \
127                         ((struct sockaddr_in *)a)->sin_family, \
128                         inet_ntoa(((struct sockaddr_in *)a)->sin_addr), \
129                         ntohs(((struct sockaddr_in *)a)->sin_port))
130
131 /****************************************************************
132  * Async IO declarations
133  ****************************************************************/
134 #include "async.h"
135
136 static DWORD ws2_async_get_status (const struct async_private *ovp);
137 static DWORD ws2_async_get_count  (const struct async_private *ovp);
138 static void  ws2_async_set_status (struct async_private *ovp, const DWORD status);
139 static void CALLBACK ws2_async_call_completion (ULONG_PTR data);
140 static void ws2_async_cleanup ( struct async_private *ovp );
141
142 static struct async_ops ws2_async_ops =
143 {
144     ws2_async_get_status,
145     ws2_async_set_status,
146     ws2_async_get_count,
147     ws2_async_call_completion,
148     ws2_async_cleanup
149 };
150
151 static struct async_ops ws2_nocomp_async_ops =
152 {
153     ws2_async_get_status,
154     ws2_async_set_status,
155     ws2_async_get_count,
156     NULL,                     /* call_completion */
157     ws2_async_cleanup
158 };
159
160 typedef struct ws2_async
161 {
162     async_private                       async;
163     LPWSAOVERLAPPED                     overlapped;
164     LPWSAOVERLAPPED                     user_overlapped;
165     LPWSAOVERLAPPED_COMPLETION_ROUTINE  completion_func;
166     struct iovec                        *iovec;
167     int                                 n_iovecs;
168     struct WS_sockaddr            *addr;
169     union {
170         int val;     /* for send operations */
171         int *ptr;    /* for recv operations */
172     }                                   addrlen;
173     DWORD                               flags;
174 } ws2_async;
175
176 /****************************************************************/
177
178 /* ----------------------------------- internal data */
179
180 /* ws_... struct conversion flags */
181
182 #define WS_DUP_LINEAR           0x0001
183 #define WS_DUP_SEGPTR           0x0002          /* internal pointers are SEGPTRs */
184                                                 /* by default, internal pointers are linear */
185 typedef struct          /* WSAAsyncSelect() control struct */
186 {
187   HANDLE      service, event, sock;
188   HWND        hWnd;
189   UINT        uMsg;
190   LONG        lEvent;
191 } ws_select_info;
192
193 #define WS_MAX_SOCKETS_PER_PROCESS      128     /* reasonable guess */
194 #define WS_MAX_UDP_DATAGRAM             1024
195
196 #define PROCFS_NETDEV_FILE   "/proc/net/dev" /* Points to the file in the /proc fs
197                                                 that lists the network devices.
198                                                 Do we need an #ifdef LINUX for this? */
199
200 static void *he_buffer;          /* typecast for Win16/32 ws_hostent */
201 static SEGPTR he_buffer_seg;
202 static void *se_buffer;          /* typecast for Win16/32 ws_servent */
203 static SEGPTR se_buffer_seg;
204 static void *pe_buffer;          /* typecast for Win16/32 ws_protoent */
205 static SEGPTR pe_buffer_seg;
206 static char* local_buffer;
207 static SEGPTR dbuffer_seg;
208 static INT num_startup;          /* reference counter */
209 static FARPROC blocking_hook;
210
211 /* function prototypes */
212 static int WS_dup_he(struct hostent* p_he, int flag);
213 static int WS_dup_pe(struct protoent* p_pe, int flag);
214 static int WS_dup_se(struct servent* p_se, int flag);
215
216 typedef void    WIN_hostent;
217 typedef void    WIN_protoent;
218 typedef void    WIN_servent;
219
220 int WSAIOCTL_GetInterfaceCount(void);
221 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName);
222
223 UINT16 wsaErrno(void);
224 UINT16 wsaHerrno(int errnr);
225
226 static HANDLE   _WSHeap = 0;
227
228 #define WS_ALLOC(size) \
229         HeapAlloc(_WSHeap, HEAP_ZERO_MEMORY, (size) )
230 #define WS_FREE(ptr) \
231         HeapFree(_WSHeap, 0, (ptr) )
232
233 static INT         _ws_sock_ops[] =
234        { WS_SO_DEBUG, WS_SO_REUSEADDR, WS_SO_KEEPALIVE, WS_SO_DONTROUTE,
235          WS_SO_BROADCAST, WS_SO_LINGER, WS_SO_OOBINLINE, WS_SO_SNDBUF,
236          WS_SO_RCVBUF, WS_SO_ERROR, WS_SO_TYPE,
237 #ifdef SO_RCVTIMEO
238          WS_SO_RCVTIMEO,
239 #endif
240 #ifdef SO_SNDTIMEO
241          WS_SO_SNDTIMEO,
242 #endif
243          0 };
244 static int           _px_sock_ops[] =
245        { SO_DEBUG, SO_REUSEADDR, SO_KEEPALIVE, SO_DONTROUTE, SO_BROADCAST,
246          SO_LINGER, SO_OOBINLINE, SO_SNDBUF, SO_RCVBUF, SO_ERROR, SO_TYPE,
247 #ifdef SO_RCVTIMEO
248          SO_RCVTIMEO,
249 #endif
250 #ifdef SO_SNDTIMEO
251          SO_SNDTIMEO,
252 #endif
253         };
254
255 static INT _ws_tcp_ops[] = {
256 #ifdef TCP_NODELAY
257         WS_TCP_NODELAY,
258 #endif
259         0
260 };
261 static int _px_tcp_ops[] = {
262 #ifdef TCP_NODELAY
263         TCP_NODELAY,
264 #endif
265         0
266 };
267
268 static DWORD opentype_tls_index = -1;  /* TLS index for SO_OPENTYPE flag */
269
270 inline static DWORD NtStatusToWSAError ( const DWORD status )
271 {
272     /* We only need to cover the status codes set by server async request handling */
273     DWORD wserr;
274     switch ( status )
275     {
276     case STATUS_SUCCESS:              wserr = 0;                     break;
277     case STATUS_PENDING:              wserr = WSA_IO_PENDING;        break;
278     case STATUS_INVALID_HANDLE:       wserr = WSAENOTSOCK;           break;  /* WSAEBADF ? */
279     case STATUS_INVALID_PARAMETER:    wserr = WSAEINVAL;             break;
280     case STATUS_PIPE_DISCONNECTED:    wserr = WSAESHUTDOWN;          break;
281     case STATUS_CANCELLED:            wserr = WSA_OPERATION_ABORTED; break;
282     case STATUS_TIMEOUT:              wserr = WSAETIMEDOUT;          break;
283     case STATUS_NO_MEMORY:            wserr = WSAEFAULT;             break;
284     default:
285         if ( status >= WSABASEERR && status <= WSABASEERR+1004 )
286             /* It is not a NT status code but a winsock error */
287             wserr = status;
288         else
289         {
290             wserr = RtlNtStatusToDosError( status );
291             FIXME ( "Status code %08lx converted to DOS error code %lx\n", status, wserr );
292         }
293     }
294     return wserr;
295 }
296
297 /* set last error code from NT status without mapping WSA errors */
298 inline static unsigned int set_error( unsigned int err )
299 {
300     if (err)
301     {
302         err = NtStatusToWSAError ( err );
303         SetLastError( err );
304     }
305     return err;
306 }
307
308 static char* check_buffer(int size);
309
310 inline static int _get_sock_fd(SOCKET s)
311 {
312     int fd;
313
314     if (set_error( wine_server_handle_to_fd( s, GENERIC_READ, &fd, NULL, NULL ) )) return -1;
315     return fd;
316 }
317
318 inline static int _get_sock_fd_type( SOCKET s, DWORD access, enum fd_type *type, int *flags )
319 {
320     int fd;
321     if (set_error( wine_server_handle_to_fd( s, access, &fd, type, flags ) )) return -1;
322     if ( ( (access & GENERIC_READ)  && (*flags & FD_FLAG_RECV_SHUTDOWN ) ) ||
323          ( (access & GENERIC_WRITE) && (*flags & FD_FLAG_SEND_SHUTDOWN ) ) )
324     {
325         close (fd);
326         WSASetLastError ( WSAESHUTDOWN );
327         return -1;
328     }
329     return fd;
330 }
331
332 static void _enable_event(SOCKET s, unsigned int event,
333                           unsigned int sstate, unsigned int cstate)
334 {
335     SERVER_START_REQ( enable_socket_event )
336     {
337         req->handle = s;
338         req->mask   = event;
339         req->sstate = sstate;
340         req->cstate = cstate;
341         wine_server_call( req );
342     }
343     SERVER_END_REQ;
344 }
345
346 static int _is_blocking(SOCKET s)
347 {
348     int ret;
349     SERVER_START_REQ( get_socket_event )
350     {
351         req->handle  = s;
352         req->service = FALSE;
353         req->c_event = 0;
354         wine_server_call( req );
355         ret = (reply->state & FD_WINE_NONBLOCKING) == 0;
356     }
357     SERVER_END_REQ;
358     return ret;
359 }
360
361 static unsigned int _get_sock_mask(SOCKET s)
362 {
363     unsigned int ret;
364     SERVER_START_REQ( get_socket_event )
365     {
366         req->handle  = s;
367         req->service = FALSE;
368         req->c_event = 0;
369         wine_server_call( req );
370         ret = reply->mask;
371     }
372     SERVER_END_REQ;
373     return ret;
374 }
375
376 static void _sync_sock_state(SOCKET s)
377 {
378     /* do a dummy wineserver request in order to let
379        the wineserver run through its select loop once */
380     (void)_is_blocking(s);
381 }
382
383 static int _get_sock_error(SOCKET s, unsigned int bit)
384 {
385     int events[FD_MAX_EVENTS];
386
387     SERVER_START_REQ( get_socket_event )
388     {
389         req->handle  = s;
390         req->service = FALSE;
391         req->c_event = 0;
392         wine_server_set_reply( req, events, sizeof(events) );
393         wine_server_call( req );
394     }
395     SERVER_END_REQ;
396     return events[bit];
397 }
398
399 static void WINSOCK_DeleteIData(void)
400 {
401     /* delete scratch buffers */
402
403     UnMapLS( he_buffer_seg );
404     UnMapLS( se_buffer_seg );
405     UnMapLS( pe_buffer_seg );
406     UnMapLS( dbuffer_seg );
407     if (he_buffer) HeapFree( GetProcessHeap(), 0, he_buffer );
408     if (se_buffer) HeapFree( GetProcessHeap(), 0, se_buffer );
409     if (pe_buffer) HeapFree( GetProcessHeap(), 0, pe_buffer );
410     if (local_buffer) HeapFree( GetProcessHeap(), 0, local_buffer );
411     he_buffer = NULL;
412     se_buffer = NULL;
413     pe_buffer = NULL;
414     local_buffer = NULL;
415     he_buffer_seg = 0;
416     se_buffer_seg = 0;
417     pe_buffer_seg = 0;
418     dbuffer_seg = 0;
419     num_startup = 0;
420 }
421
422 /***********************************************************************
423  *              WS_LibMain (WS2_32.init)
424  */
425 BOOL WINAPI WS_LibMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID fImpLoad)
426 {
427     TRACE("0x%x 0x%lx %p\n", hInstDLL, fdwReason, fImpLoad);
428     switch (fdwReason) {
429     case DLL_PROCESS_ATTACH:
430         opentype_tls_index = TlsAlloc();
431         break;
432     case DLL_PROCESS_DETACH:
433         TlsFree( opentype_tls_index );
434         WINSOCK_DeleteIData();
435         break;
436     }
437     return TRUE;
438 }
439
440 /***********************************************************************
441  *          convert_sockopt()
442  *
443  * Converts socket flags from Windows format.
444  * Return 1 if converted, 0 if not (error).
445  */
446 static int convert_sockopt(INT *level, INT *optname)
447 {
448   int i;
449   switch (*level)
450   {
451      case WS_SOL_SOCKET:
452         *level = SOL_SOCKET;
453         for(i=0; _ws_sock_ops[i]; i++)
454             if( _ws_sock_ops[i] == *optname ) break;
455         if( _ws_sock_ops[i] ) {
456             *optname = _px_sock_ops[i];
457             return 1;
458         }
459         FIXME("Unknown SOL_SOCKET optname 0x%x\n", *optname);
460         break;
461      case WS_IPPROTO_TCP:
462         *level = IPPROTO_TCP;
463         for(i=0; _ws_tcp_ops[i]; i++)
464                 if ( _ws_tcp_ops[i] == *optname ) break;
465         if( _ws_tcp_ops[i] ) {
466             *optname = _px_tcp_ops[i];
467             return 1;
468         }
469         FIXME("Unknown IPPROTO_TCP optname 0x%x\n", *optname);
470         break;
471   }
472   return 0;
473 }
474
475 /* ----------------------------------- Per-thread info (or per-process?) */
476
477 static int wsi_strtolo(const char* name, const char* opt)
478 {
479     /* Stuff a lowercase copy of the string into the local buffer */
480
481     int i = strlen(name) + 2;
482     char* p = check_buffer(i + ((opt)?strlen(opt):0));
483
484     if( p )
485     {
486         do *p++ = tolower(*name); while(*name++);
487         i = (p - local_buffer);
488         if( opt ) do *p++ = tolower(*opt); while(*opt++);
489         return i;
490     }
491     return 0;
492 }
493
494 static fd_set* fd_set_import( fd_set* fds, void* wsfds, int* highfd, int lfd[], BOOL b32 )
495 {
496     /* translate Winsock fd set into local fd set */
497
498     if( wsfds )
499     {
500 #define wsfds16 ((ws_fd_set16*)wsfds)
501 #define wsfds32 ((WS_fd_set*)wsfds)
502         int i, count;
503
504         FD_ZERO(fds);
505         count = b32 ? wsfds32->fd_count : wsfds16->fd_count;
506
507         for( i = 0; i < count; i++ )
508         {
509              int s = (b32) ? wsfds32->fd_array[i]
510                            : wsfds16->fd_array[i];
511              int fd = _get_sock_fd(s);
512              if (fd != -1)
513              {
514                     lfd[ i ] = fd;
515                     if( fd > *highfd ) *highfd = fd;
516                     FD_SET(fd, fds);
517              }
518              else lfd[ i ] = -1;
519         }
520 #undef wsfds32
521 #undef wsfds16
522         return fds;
523     }
524     return NULL;
525 }
526
527 inline static int sock_error_p(int s)
528 {
529     unsigned int optval, optlen;
530
531     optlen = sizeof(optval);
532     getsockopt(s, SOL_SOCKET, SO_ERROR, (void *) &optval, &optlen);
533     if (optval) WARN("\t[%i] error: %d\n", s, optval);
534     return optval != 0;
535 }
536
537 static int fd_set_export( fd_set* fds, fd_set* exceptfds, void* wsfds, int lfd[], BOOL b32 )
538 {
539     int num_err = 0;
540
541     /* translate local fd set into Winsock fd set, adding
542      * errors to exceptfds (only if app requested it) */
543
544     if( wsfds )
545     {
546 #define wsfds16 ((ws_fd_set16*)wsfds)
547 #define wsfds32 ((WS_fd_set*)wsfds)
548         int i, j, count = (b32) ? wsfds32->fd_count : wsfds16->fd_count;
549
550         for( i = 0, j = 0; i < count; i++ )
551         {
552             if( lfd[i] >= 0 )
553             {
554                 int fd = lfd[i];
555                 if( FD_ISSET(fd, fds) )
556                 {
557                     if ( exceptfds && sock_error_p(fd) )
558                     {
559                         FD_SET(fd, exceptfds);
560                         num_err++;
561                     }
562                     else if( b32 )
563                              wsfds32->fd_array[j++] = wsfds32->fd_array[i];
564                          else
565                              wsfds16->fd_array[j++] = wsfds16->fd_array[i];
566                 }
567                 close(fd);
568                 lfd[i] = -1;
569             }
570         }
571
572         if( b32 ) wsfds32->fd_count = j;
573         else wsfds16->fd_count = j;
574
575         TRACE("\n");
576 #undef wsfds32
577 #undef wsfds16
578     }
579     return num_err;
580 }
581
582 static void fd_set_unimport( void* wsfds, int lfd[], BOOL b32 )
583 {
584     if ( wsfds )
585     {
586 #define wsfds16 ((ws_fd_set16*)wsfds)
587 #define wsfds32 ((WS_fd_set*)wsfds)
588         int i, count = (b32) ? wsfds32->fd_count : wsfds16->fd_count;
589
590         for( i = 0; i < count; i++ )
591             if ( lfd[i] >= 0 )
592                 close(lfd[i]);
593
594         TRACE("\n");
595 #undef wsfds32
596 #undef wsfds16
597     }
598 }
599
600 static int do_block( int fd, int mask )
601 {
602     fd_set fds[3];
603     int i, r;
604
605     FD_ZERO(&fds[0]);
606     FD_ZERO(&fds[1]);
607     FD_ZERO(&fds[2]);
608     for (i=0; i<3; i++)
609         if (mask & (1<<i))
610             FD_SET(fd, &fds[i]);
611     i = select( fd+1, &fds[0], &fds[1], &fds[2], NULL );
612     if (i <= 0) return -1;
613     r = 0;
614     for (i=0; i<3; i++)
615         if (FD_ISSET(fd, &fds[i]))
616             r |= 1<<i;
617     return r;
618 }
619
620 void* __ws_memalloc( int size )
621 {
622     return WS_ALLOC(size);
623 }
624
625 void __ws_memfree(void* ptr)
626 {
627     WS_FREE(ptr);
628 }
629
630
631 /* ----------------------------------- API -----
632  *
633  * Init / cleanup / error checking.
634  */
635
636 /***********************************************************************
637  *      WSAStartup                      (WINSOCK.115)
638  *
639  * Create socket control struct, attach it to the global list and
640  * update a pointer in the task struct.
641  */
642 INT16 WINAPI WSAStartup16(UINT16 wVersionRequested, LPWSADATA16 lpWSAData)
643 {
644     static const WSADATA16 data =
645     {
646         0x0101, 0x0101,
647         "WINE Sockets 1.1",
648 #ifdef linux
649         "Linux/i386",
650 #elif defined(__NetBSD__)
651         "NetBSD/i386",
652 #elif defined(sunos)
653         "SunOS",
654 #elif defined(__FreeBSD__)
655         "FreeBSD",
656 #elif defined(__OpenBSD__)
657         "OpenBSD/i386",
658 #else
659         "Unknown",
660 #endif
661         WS_MAX_SOCKETS_PER_PROCESS,
662         WS_MAX_UDP_DATAGRAM,
663         0
664     };
665
666     TRACE("verReq=%x\n", wVersionRequested);
667
668     if (LOBYTE(wVersionRequested) < 1 || (LOBYTE(wVersionRequested) == 1 &&
669         HIBYTE(wVersionRequested) < 1)) return WSAVERNOTSUPPORTED;
670
671     if (!lpWSAData) return WSAEINVAL;
672
673     /* initialize socket heap */
674
675     if( !_WSHeap )
676     {
677         _WSHeap = HeapCreate(HEAP_ZERO_MEMORY, 8120, 32768);
678         if( !_WSHeap )
679         {
680             ERR("Fatal: failed to create WinSock heap\n");
681             return 0;
682         }
683     }
684     if( _WSHeap == 0 ) return WSASYSNOTREADY;
685
686     num_startup++;
687
688     /* return winsock information */
689
690     memcpy(lpWSAData, &data, sizeof(data));
691
692     TRACE("succeeded\n");
693     return 0;
694 }
695
696 /***********************************************************************
697  *      WSAStartup              (WS2_32.115)
698  */
699 int WINAPI WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData)
700 {
701     static const WSADATA data =
702     {
703         0x0202, 0x0202,
704         "WINE Sockets 2.0",
705 #ifdef linux
706         "Linux",
707 #elif defined(__NetBSD__)
708         "NetBSD",
709 #elif defined(sunos)
710         "SunOS",
711 #elif defined(__FreeBSD__)
712         "FreeBSD",
713 #elif defined(__OpenBSD__)
714         "OpenBSD",
715 #else
716         "Unknown",
717 #endif
718         WS_MAX_SOCKETS_PER_PROCESS,
719         WS_MAX_UDP_DATAGRAM,
720         NULL
721     };
722
723     TRACE("verReq=%x\n", wVersionRequested);
724
725     if (LOBYTE(wVersionRequested) < 1)
726         return WSAVERNOTSUPPORTED;
727
728     if (!lpWSAData) return WSAEINVAL;
729
730     /* initialize socket heap */
731
732     if( !_WSHeap )
733     {
734         _WSHeap = HeapCreate(HEAP_ZERO_MEMORY, 8120, 32768);
735         if( !_WSHeap )
736         {
737             ERR("Fatal: failed to create WinSock heap\n");
738             return 0;
739         }
740     }
741     if( _WSHeap == 0 ) return WSASYSNOTREADY;
742
743     num_startup++;
744
745     /* return winsock information */
746     memcpy(lpWSAData, &data, sizeof(data));
747
748     /* that's the whole of the negotiation for now */
749     lpWSAData->wVersion = wVersionRequested;
750
751     TRACE("succeeded\n");
752     return 0;
753 }
754
755
756 /***********************************************************************
757  *      WSACleanup                      (WINSOCK.116)
758  *      WSACleanup                      (WS2_32.116)
759  */
760 INT WINAPI WSACleanup(void)
761 {
762     if (num_startup)
763     {
764         if (--num_startup > 0) return 0;
765         WINSOCK_DeleteIData();
766         return 0;
767     }
768     SetLastError(WSANOTINITIALISED);
769     return SOCKET_ERROR;
770 }
771
772
773 /***********************************************************************
774  *      WSAGetLastError         (WINSOCK.111)
775  *      WSAGetLastError         (WS2_32.111)
776  */
777 INT WINAPI WSAGetLastError(void)
778 {
779         return GetLastError();
780 }
781
782 /***********************************************************************
783  *      WSASetLastError         (WS2_32.112)
784  */
785 void WINAPI WSASetLastError(INT iError) {
786     SetLastError(iError);
787 }
788
789 /***********************************************************************
790  *      WSASetLastError         (WINSOCK.112)
791  */
792 void WINAPI WSASetLastError16(INT16 iError)
793 {
794     WSASetLastError(iError);
795 }
796
797 static char* check_buffer(int size)
798 {
799     static int local_buflen;
800
801     if (local_buffer)
802     {
803         if (local_buflen >= size ) return local_buffer;
804         HeapFree( GetProcessHeap(), 0, local_buffer );
805     }
806     local_buffer = HeapAlloc( GetProcessHeap(), 0, (local_buflen = size) );
807     return local_buffer;
808 }
809
810 static struct ws_hostent* check_buffer_he(int size)
811 {
812     static int he_len;
813     if (he_buffer)
814     {
815         if (he_len >= size ) return he_buffer;
816         UnMapLS( he_buffer_seg );
817         HeapFree( GetProcessHeap(), 0, he_buffer );
818     }
819     he_buffer = HeapAlloc( GetProcessHeap(), 0, (he_len = size) );
820     he_buffer_seg = MapLS( he_buffer );
821     return he_buffer;
822 }
823
824 static void* check_buffer_se(int size)
825 {
826     static int se_len;
827     if (se_buffer)
828     {
829         if (se_len >= size ) return se_buffer;
830         UnMapLS( se_buffer_seg );
831         HeapFree( GetProcessHeap(), 0, se_buffer );
832     }
833     se_buffer = HeapAlloc( GetProcessHeap(), 0, (se_len = size) );
834     se_buffer_seg = MapLS( he_buffer );
835     return se_buffer;
836 }
837
838 static struct ws_protoent* check_buffer_pe(int size)
839 {
840     static int pe_len;
841     if (pe_buffer)
842     {
843         if (pe_len >= size ) return pe_buffer;
844         UnMapLS( pe_buffer_seg );
845         HeapFree( GetProcessHeap(), 0, pe_buffer );
846     }
847     pe_buffer = HeapAlloc( GetProcessHeap(), 0, (pe_len = size) );
848     pe_buffer_seg = MapLS( he_buffer );
849     return pe_buffer;
850 }
851
852 /* ----------------------------------- i/o APIs */
853
854 #ifdef HAVE_IPX
855 #define SUPPORTED_PF(pf) ((pf)==WS_AF_INET || (pf)== WS_AF_IPX)
856 #else
857 #define SUPPORTED_PF(pf) ((pf)==WS_AF_INET)
858 #endif
859
860
861 /**********************************************************************/
862
863 /* Returns the converted address if successful, NULL if it was too small to
864  * start with. Note that the returned pointer may be the original pointer
865  * if no conversion is necessary.
866  */
867 static const struct sockaddr* ws_sockaddr_ws2u(const struct WS_sockaddr* wsaddr, int wsaddrlen, int *uaddrlen)
868 {
869     switch (wsaddr->sa_family)
870     {
871 #ifdef HAVE_IPX
872     case WS_AF_IPX:
873         {
874             struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
875             struct sockaddr_ipx* uipx;
876
877             if (wsaddrlen<sizeof(struct WS_sockaddr_ipx))
878                 return NULL;
879
880             *uaddrlen=sizeof(struct sockaddr_ipx);
881             uipx=malloc(*uaddrlen);
882             uipx->sipx_family=AF_IPX;
883             uipx->sipx_port=wsipx->sa_socket;
884             /* copy sa_netnum and sa_nodenum to sipx_network and sipx_node
885              * in one go
886              */
887             memcpy(&uipx->sipx_network,wsipx->sa_netnum,sizeof(uipx->sipx_network)+sizeof(uipx->sipx_node));
888             uipx->sipx_type=IPX_FRAME_NONE;
889             uipx->sipx_zero=0;
890             return (const struct sockaddr*)uipx;
891         }
892 #endif
893
894     default:
895         if (wsaddrlen<sizeof(struct WS_sockaddr))
896             return NULL;
897
898         /* No conversion needed, just return the original address */
899         *uaddrlen=wsaddrlen;
900         return (const struct sockaddr*)wsaddr;
901     }
902     return NULL;
903 }
904
905 /* Allocates a Unix sockaddr structure to receive the data */
906 inline struct sockaddr* ws_sockaddr_alloc(const struct WS_sockaddr* wsaddr, int* wsaddrlen, int* uaddrlen)
907 {
908     if (wsaddr==NULL)
909     {
910       ERR( "WINE shouldn't pass a NULL wsaddr! Attempting to continue\n" );
911
912       /* This is not strictly the right thing to do. Hope it works however */
913       *uaddrlen=0;
914
915       return NULL;
916     }
917
918     if (*wsaddrlen==0)
919         *uaddrlen=0;
920     else
921         *uaddrlen=max(sizeof(struct sockaddr),*wsaddrlen);
922
923     return malloc(*uaddrlen);
924 }
925
926 /* Returns 0 if successful, -1 if the buffer is too small */
927 static int ws_sockaddr_u2ws(const struct sockaddr* uaddr, int uaddrlen, struct WS_sockaddr* wsaddr, int* wsaddrlen)
928 {
929     int res;
930
931     switch(uaddr->sa_family)
932     {
933 #ifdef HAVE_IPX
934     case AF_IPX:
935         {
936             struct sockaddr_ipx* uipx=(struct sockaddr_ipx*)uaddr;
937             struct WS_sockaddr_ipx* wsipx=(struct WS_sockaddr_ipx*)wsaddr;
938
939             res=-1;
940             switch (*wsaddrlen) /* how much can we copy? */
941             {
942             default:
943                 res=0; /* enough */
944                 *wsaddrlen=uaddrlen;
945                 wsipx->sa_socket=uipx->sipx_port;
946                 /* fall through */
947             case 13:
948             case 12:
949                 memcpy(wsipx->sa_nodenum,uipx->sipx_node,sizeof(wsipx->sa_nodenum));
950                 /* fall through */
951             case 11:
952             case 10:
953             case 9:
954             case 8:
955             case 7:
956             case 6:
957                 memcpy(wsipx->sa_netnum,&uipx->sipx_network,sizeof(wsipx->sa_netnum));
958                 /* fall through */
959             case 5:
960             case 4:
961             case 3:
962             case 2:
963                 wsipx->sa_family=WS_AF_IPX;
964                 /* fall through */
965             case 1:
966             case 0:
967                 /* way too small */
968                 break;
969             }
970         }
971         break;
972 #endif
973
974     default:
975         /* No conversion needed */
976         memcpy(wsaddr,uaddr,*wsaddrlen);
977         if (*wsaddrlen<uaddrlen) {
978             res=-1;
979         } else {
980             *wsaddrlen=uaddrlen;
981             res=0;
982         }
983     }
984     return res;
985 }
986
987 /* to be called to free the memory allocated by ws_sockaddr_ws2u or
988  * ws_sockaddr_alloc
989  */
990 inline void ws_sockaddr_free(const struct sockaddr* uaddr, const struct WS_sockaddr* wsaddr)
991 {
992     if (uaddr!=NULL && uaddr!=(const struct sockaddr*)wsaddr)
993         free((void*)uaddr);
994 }
995
996 /**************************************************************************
997  * Functions for handling overlapped I/O
998  **************************************************************************/
999
1000 static DWORD ws2_async_get_status (const struct async_private *ovp)
1001 {
1002     return ((ws2_async*) ovp)->overlapped->Internal;
1003 }
1004
1005 static VOID ws2_async_set_status (struct async_private *ovp, const DWORD status)
1006 {
1007     ((ws2_async*) ovp)->overlapped->Internal = status;
1008 }
1009
1010 static DWORD ws2_async_get_count (const struct async_private *ovp)
1011 {
1012     return ((ws2_async*) ovp)->overlapped->InternalHigh;
1013 }
1014
1015 static void ws2_async_cleanup ( struct async_private *ap )
1016 {
1017     struct ws2_async *as = (struct ws2_async*) ap;
1018
1019     TRACE ( "as: %p uovl %p ovl %p\n", as, as->user_overlapped, as->overlapped );
1020     if ( !as->user_overlapped )
1021     {
1022         if ( as->overlapped->hEvent != INVALID_HANDLE_VALUE )
1023             WSACloseEvent ( as->overlapped->hEvent  );
1024         HeapFree ( GetProcessHeap(), 0, as->overlapped );
1025     }
1026
1027     if ( as->iovec )
1028         HeapFree ( GetProcessHeap(), 0, as->iovec );
1029
1030     HeapFree ( GetProcessHeap(), 0, as );
1031 }
1032
1033 static void CALLBACK ws2_async_call_completion (ULONG_PTR data)
1034 {
1035     ws2_async* as = (ws2_async*) data;
1036
1037     TRACE ("data: %p\n", as);
1038
1039     as->completion_func ( NtStatusToWSAError (as->overlapped->Internal),
1040                           as->overlapped->InternalHigh,
1041                           as->user_overlapped,
1042                           as->flags );
1043     ws2_async_cleanup ( &as->async );
1044 }
1045
1046 /***********************************************************************
1047  *              WS2_make_async          (INTERNAL)
1048  */
1049
1050 static void WS2_async_recv (async_private *as);
1051 static void WS2_async_send (async_private *as);
1052
1053 inline static struct ws2_async*
1054 WS2_make_async (SOCKET s, int fd, int type, struct iovec *iovec, DWORD dwBufferCount,
1055                 LPDWORD lpFlags, struct WS_sockaddr *addr,
1056                 LPINT addrlen, LPWSAOVERLAPPED lpOverlapped,
1057                 LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
1058 {
1059     struct ws2_async *wsa = HeapAlloc ( GetProcessHeap(), 0, sizeof ( ws2_async ) );
1060
1061     TRACE ( "wsa %p\n", wsa );
1062
1063     if (!wsa)
1064         return NULL;
1065
1066     wsa->async.ops = ( lpCompletionRoutine ? &ws2_async_ops : &ws2_nocomp_async_ops );
1067     wsa->async.handle = (HANDLE) s;
1068     wsa->async.fd = fd;
1069     wsa->async.type = type;
1070     switch (type)
1071     {
1072     case ASYNC_TYPE_READ:
1073         wsa->flags = *lpFlags;
1074         wsa->async.func = WS2_async_recv;
1075         wsa->addrlen.ptr = addrlen;
1076         break;
1077     case ASYNC_TYPE_WRITE:
1078         wsa->flags = 0;
1079         wsa->async.func = WS2_async_send;
1080         wsa->addrlen.val = *addrlen;
1081         break;
1082     default:
1083         ERR ("Invalid async type: %d\n", type);
1084     }
1085     wsa->user_overlapped = lpOverlapped;
1086     wsa->completion_func = lpCompletionRoutine;
1087     wsa->iovec = iovec;
1088     wsa->n_iovecs = dwBufferCount;
1089     wsa->addr = addr;
1090
1091     if ( lpOverlapped )
1092     {
1093         wsa->overlapped = lpOverlapped;
1094         wsa->async.event = ( lpCompletionRoutine ? INVALID_HANDLE_VALUE : lpOverlapped->hEvent );
1095     }
1096     else
1097     {
1098         wsa->overlapped = HeapAlloc ( GetProcessHeap(), 0,
1099                                       sizeof (WSAOVERLAPPED) );
1100         if ( !wsa->overlapped )
1101             goto error;
1102         wsa->async.event = wsa->overlapped->hEvent = INVALID_HANDLE_VALUE;
1103     }
1104
1105     wsa->overlapped->InternalHigh = 0;
1106     TRACE ( "wsa %p, ops %p, h %d, ev %d, fd %d, func %p, ov %p, uov %p, cfunc %p\n",
1107             wsa, wsa->async.ops, wsa->async.handle, wsa->async.event, wsa->async.fd, wsa->async.func,
1108             wsa->overlapped, wsa->user_overlapped, wsa->completion_func );
1109
1110     return wsa;
1111
1112 error:
1113     TRACE ("Error\n");
1114     HeapFree ( GetProcessHeap(), 0, wsa );
1115     return NULL;
1116 }
1117
1118 /***********************************************************************
1119  *              WS2_recv                (INTERNAL)
1120  *
1121  * Work horse for both synchronous and asynchronous recv() operations.
1122  */
1123 static int WS2_recv ( int fd, struct iovec* iov, int count,
1124                       struct WS_sockaddr *lpFrom, LPINT lpFromlen,
1125                       LPDWORD lpFlags )
1126 {
1127     struct msghdr hdr;
1128     int n;
1129     TRACE ( "fd %d, iovec %p, count %d addr %p, len %p, flags %lx\n",
1130             fd, iov, count, lpFrom, lpFromlen, *lpFlags);
1131
1132     hdr.msg_name = NULL;
1133
1134     if ( lpFrom )
1135     {
1136 #if DEBUG_SOCKADDR
1137         dump_sockaddr (lpFrom);
1138 #endif
1139
1140         hdr.msg_namelen = *lpFromlen;
1141         hdr.msg_name = ws_sockaddr_alloc ( lpFrom, lpFromlen, &hdr.msg_namelen );
1142         if ( !hdr.msg_name )
1143         {
1144             WSASetLastError ( WSAEFAULT );
1145             n = -1;
1146             goto out;
1147         }
1148     }
1149     else
1150         hdr.msg_namelen = 0;
1151
1152     hdr.msg_iov = iov;
1153     hdr.msg_iovlen = count;
1154 #ifdef HAVE_MSGHDR_ACCRIGHTS
1155     hdr.msg_accrights = NULL;
1156     hdr.msg_accrightslen = 0;
1157 #else
1158     hdr.msg_control = NULL;
1159     hdr.msg_controllen = 0;
1160     hdr.msg_flags = 0;
1161 #endif
1162
1163     if ( (n = recvmsg (fd, &hdr, *lpFlags)) == -1 )
1164     {
1165         TRACE ( "recvmsg error %d\n", errno);
1166         goto out;
1167     }
1168
1169     if ( lpFrom &&
1170          ws_sockaddr_u2ws ( hdr.msg_name, hdr.msg_namelen,
1171                             lpFrom, lpFromlen ) != 0 )
1172     {
1173         /* The from buffer was too small, but we read the data
1174          * anyway. Is that really bad?
1175          */
1176         WSASetLastError ( WSAEFAULT );
1177         WARN ( "Address buffer too small\n" );
1178     }
1179
1180 out:
1181
1182     ws_sockaddr_free ( hdr.msg_name, lpFrom );
1183     TRACE ("-> %d\n", n);
1184     return n;
1185 }
1186
1187 /***********************************************************************
1188  *              WS2_async_recv          (INTERNAL)
1189  *
1190  * Handler for overlapped recv() operations.
1191  */
1192 static void WS2_async_recv ( async_private *as )
1193 {
1194     ws2_async* wsa = (ws2_async*) as;
1195     int result, err;
1196
1197     TRACE ( "async %p\n", wsa );
1198
1199     if ( wsa->overlapped->Internal != STATUS_PENDING )
1200     {
1201         TRACE ( "status: %ld\n", wsa->overlapped->Internal );
1202         return;
1203     }
1204
1205     result = WS2_recv ( wsa->async.fd, wsa->iovec, wsa->n_iovecs,
1206                         wsa->addr, wsa->addrlen.ptr, &wsa->flags );
1207
1208     if (result >= 0)
1209     {
1210         wsa->overlapped->Internal = STATUS_SUCCESS;
1211         wsa->overlapped->InternalHigh = result;
1212         TRACE ( "received %d bytes\n", result );
1213         _enable_event ( (SOCKET) wsa->async.handle, FD_READ, 0, 0 );
1214         return;
1215     }
1216
1217     err = wsaErrno ();
1218     if ( err == WSAEINTR || err == WSAEWOULDBLOCK )  /* errno: EINTR / EAGAIN */
1219     {
1220         wsa->overlapped->Internal = STATUS_PENDING;
1221         _enable_event ( (SOCKET) wsa->async.handle, FD_READ, 0, 0 );
1222         TRACE ( "still pending\n" );
1223     }
1224     else
1225     {
1226         wsa->overlapped->Internal = err;
1227         TRACE ( "Error: %x\n", err );
1228     }
1229 }
1230
1231 /***********************************************************************
1232  *              WS2_send                (INTERNAL)
1233  *
1234  * Work horse for both synchronous and asynchronous send() operations.
1235  */
1236 static int WS2_send ( int fd, struct iovec* iov, int count,
1237                       const struct WS_sockaddr *to, INT tolen, DWORD dwFlags )
1238 {
1239     struct msghdr hdr;
1240     int n = -1;
1241     TRACE ( "fd %d, iovec %p, count %d addr %p, len %d, flags %lx\n",
1242             fd, iov, count, to, tolen, dwFlags);
1243
1244     hdr.msg_name = NULL;
1245
1246     if ( to )
1247     {
1248 #if DEBUG_SOCKADDR
1249         dump_sockaddr (to);
1250 #endif
1251         hdr.msg_name = (struct sockaddr*) ws_sockaddr_ws2u ( to, tolen, &hdr.msg_namelen );
1252         if ( !hdr.msg_name )
1253         {
1254             WSASetLastError ( WSAEFAULT );
1255             goto out;
1256         }
1257     }
1258     else
1259         hdr.msg_namelen = 0;
1260
1261     hdr.msg_iov = iov;
1262     hdr.msg_iovlen = count;
1263 #ifdef HAVE_MSGHDR_ACCRIGHTS
1264     hdr.msg_accrights = NULL;
1265     hdr.msg_accrightslen = 0;
1266 #else
1267     hdr.msg_control = NULL;
1268     hdr.msg_controllen = 0;
1269     hdr.msg_flags = 0;
1270 #endif
1271
1272     n = sendmsg (fd, &hdr, dwFlags);
1273
1274 out:
1275     ws_sockaddr_free ( hdr.msg_name, to );
1276     return n;
1277 }
1278
1279 /***********************************************************************
1280  *              WS2_async_send          (INTERNAL)
1281  *
1282  * Handler for overlapped send() operations.
1283  */
1284 static void WS2_async_send ( async_private *as )
1285 {
1286     ws2_async* wsa = (ws2_async*) as;
1287     int result, err;
1288
1289     TRACE ( "async %p\n", wsa );
1290
1291     if ( wsa->overlapped->Internal != STATUS_PENDING )
1292     {
1293         TRACE ( "status: %ld\n", wsa->overlapped->Internal );
1294         return;
1295     }
1296
1297     result = WS2_send ( wsa->async.fd, wsa->iovec, wsa->n_iovecs,
1298                         wsa->addr, wsa->addrlen.val, wsa->flags );
1299
1300     if (result >= 0)
1301     {
1302         wsa->overlapped->Internal = STATUS_SUCCESS;
1303         wsa->overlapped->InternalHigh = result;
1304         TRACE ( "sent %d bytes\n", result );
1305         _enable_event ( (SOCKET) wsa->async.handle, FD_WRITE, 0, 0 );
1306         return;
1307     }
1308
1309     err = wsaErrno ();
1310     if ( err == WSAEINTR )
1311     {
1312         wsa->overlapped->Internal = STATUS_PENDING;
1313         _enable_event ( (SOCKET) wsa->async.handle, FD_WRITE, 0, 0 );
1314         TRACE ( "still pending\n" );
1315     }
1316     else
1317     {
1318         /* We set the status to a winsock error code and check for that
1319            later in NtStatusToWSAError () */
1320         wsa->overlapped->Internal = err;
1321         TRACE ( "Error: %x\n", err );
1322     }
1323 }
1324
1325 /***********************************************************************
1326  *              WS2_async_shutdown      (INTERNAL)
1327  *
1328  * Handler for shutdown() operations on overlapped sockets.
1329  */
1330 static void WS2_async_shutdown ( async_private *as )
1331 {
1332     ws2_async* wsa = (ws2_async*) as;
1333     int err = 1;
1334
1335     TRACE ( "async %p %d\n", wsa, wsa->async.type );
1336     switch ( wsa->async.type )
1337     {
1338     case ASYNC_TYPE_READ:
1339         err = shutdown ( wsa->async.fd, 0 );
1340         break;
1341     case ASYNC_TYPE_WRITE:
1342         err = shutdown ( wsa->async.fd, 1 );
1343         break;
1344     default:
1345         ERR ("invalid type: %d\n", wsa->async.type );
1346     }
1347
1348     if ( err )
1349         wsa->overlapped->Internal = wsaErrno ();
1350     else
1351         wsa->overlapped->Internal = STATUS_SUCCESS;
1352 }
1353
1354 /***********************************************************************
1355  *  WS2_register_async_shutdown         (INTERNAL)
1356  *
1357  * Helper function for WS_shutdown() on overlapped sockets.
1358  */
1359 static int WS2_register_async_shutdown ( SOCKET s, int fd, int type )
1360 {
1361     struct ws2_async *wsa;
1362     int ret, err = WSAEFAULT;
1363     DWORD dwflags = 0;
1364     int len = 0;
1365     LPWSAOVERLAPPED ovl = HeapAlloc (GetProcessHeap(), 0, sizeof ( WSAOVERLAPPED ));
1366
1367     TRACE ("s %d fd %d type %d\n", s, fd, type);
1368     if (!ovl)
1369         goto out;
1370
1371     ovl->hEvent = WSACreateEvent ();
1372     if ( ovl->hEvent == WSA_INVALID_EVENT  )
1373         goto out_free;
1374
1375     wsa = WS2_make_async ( s, fd, type, NULL, 0,
1376                            &dwflags, NULL, &len, ovl, NULL );
1377     if ( !wsa )
1378         goto out_close;
1379
1380     /* Hack: this will cause ws2_async_cleanup() to free the overlapped structure */
1381     wsa->user_overlapped = NULL;
1382     wsa->async.func = WS2_async_shutdown;
1383     if ( (ret = register_new_async ( &wsa->async )) )
1384     {
1385         err = NtStatusToWSAError ( ret );
1386         ws2_async_cleanup ( &wsa->async );
1387         goto out;
1388     }
1389     return 0;
1390
1391 out_close:
1392     WSACloseEvent ( ovl->hEvent );
1393 out_free:
1394     HeapFree ( GetProcessHeap(), 0, ovl );
1395 out:
1396     return err;
1397 }
1398
1399 /***********************************************************************
1400  *              accept          (WS2_32.1)
1401  */
1402 SOCKET WINAPI WS_accept(SOCKET s, struct WS_sockaddr *addr,
1403                                  int *addrlen32)
1404 {
1405     int fd = _get_sock_fd(s);
1406
1407     TRACE("socket %04x\n", (UINT16)s );
1408     if (fd != -1)
1409     {
1410         SOCKET as;
1411         if (_is_blocking(s))
1412         {
1413             /* block here */
1414             do_block(fd, 5);
1415             _sync_sock_state(s); /* let wineserver notice connection */
1416             /* retrieve any error codes from it */
1417             SetLastError(_get_sock_error(s, FD_ACCEPT_BIT));
1418             /* FIXME: care about the error? */
1419         }
1420         close(fd);
1421         SERVER_START_REQ( accept_socket )
1422         {
1423             req->lhandle = s;
1424             req->access  = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
1425             req->inherit = TRUE;
1426             set_error( wine_server_call( req ) );
1427             as = (SOCKET)reply->handle;
1428         }
1429         SERVER_END_REQ;
1430         if (as)
1431         {
1432             WS_getpeername(as, addr, addrlen32);
1433             return as;
1434         }
1435     }
1436     else
1437     {
1438         SetLastError(WSAENOTSOCK);
1439     }
1440     return INVALID_SOCKET;
1441 }
1442
1443 /***********************************************************************
1444  *              accept          (WINSOCK.1)
1445  */
1446 SOCKET16 WINAPI WINSOCK_accept16(SOCKET16 s, struct WS_sockaddr* addr,
1447                                  INT16* addrlen16 )
1448 {
1449     INT addrlen32 = addrlen16 ? *addrlen16 : 0;
1450     SOCKET retSocket = WS_accept( s, addr, &addrlen32 );
1451     if( addrlen16 ) *addrlen16 = (INT16)addrlen32;
1452     return (SOCKET16)retSocket;
1453 }
1454
1455 /***********************************************************************
1456  *              bind                    (WS2_32.2)
1457  */
1458 int WINAPI WS_bind(SOCKET s, const struct WS_sockaddr* name, int namelen)
1459 {
1460     int fd = _get_sock_fd(s);
1461     int res;
1462
1463     TRACE("socket %04x, ptr %p, length %d\n", s, name, namelen);
1464 #if DEBUG_SOCKADDR
1465     dump_sockaddr(name);
1466 #endif
1467
1468     res=SOCKET_ERROR;
1469     if (fd != -1)
1470     {
1471         if (!name || !SUPPORTED_PF(name->sa_family))
1472         {
1473             SetLastError(WSAEAFNOSUPPORT);
1474         }
1475         else
1476         {
1477             const struct sockaddr* uaddr;
1478             int uaddrlen;
1479
1480             uaddr=ws_sockaddr_ws2u(name,namelen,&uaddrlen);
1481             if (uaddr == NULL)
1482             {
1483                 SetLastError(WSAEFAULT);
1484             }
1485             else
1486             {
1487                 if (bind(fd, uaddr, uaddrlen) < 0)
1488                 {
1489                     int loc_errno = errno;
1490                     WARN("\tfailure - errno = %i\n", errno);
1491                     errno = loc_errno;
1492                     switch (errno)
1493                     {
1494                     case EBADF:
1495                         SetLastError(WSAENOTSOCK);
1496                         break;
1497                     case EADDRNOTAVAIL:
1498                         SetLastError(WSAEINVAL);
1499                         break;
1500                     default:
1501                         SetLastError(wsaErrno());
1502                         break;
1503                     }
1504                 }
1505                 else
1506                 {
1507                     res=0; /* success */
1508                 }
1509                 ws_sockaddr_free(uaddr,name);
1510             }
1511         }
1512         close(fd);
1513     }
1514     else
1515     {
1516         SetLastError(WSAENOTSOCK);
1517     }
1518     return res;
1519 }
1520
1521 /***********************************************************************
1522  *              bind                    (WINSOCK.2)
1523  */
1524 INT16 WINAPI WINSOCK_bind16(SOCKET16 s, struct WS_sockaddr *name, INT16 namelen)
1525 {
1526   return (INT16)WS_bind( s, name, namelen );
1527 }
1528
1529 /***********************************************************************
1530  *              closesocket             (WS2_32.3)
1531  */
1532 int WINAPI WS_closesocket(SOCKET s)
1533 {
1534     TRACE("socket %08x\n", s);
1535     if (CloseHandle(s)) return 0;
1536     return SOCKET_ERROR;
1537 }
1538
1539 /***********************************************************************
1540  *              closesocket           (WINSOCK.3)
1541  */
1542 INT16 WINAPI WINSOCK_closesocket16(SOCKET16 s)
1543 {
1544     return (INT16)WS_closesocket(s);
1545 }
1546
1547 /***********************************************************************
1548  *              connect         (WS2_32.4)
1549  */
1550 int WINAPI WS_connect(SOCKET s, const struct WS_sockaddr* name, int namelen)
1551 {
1552     int fd = _get_sock_fd(s);
1553
1554     TRACE("socket %04x, ptr %p, length %d\n", s, name, namelen);
1555 #if DEBUG_SOCKADDR
1556     dump_sockaddr(name);
1557 #endif
1558
1559     if (fd != -1)
1560     {
1561         const struct sockaddr* uaddr;
1562         int uaddrlen;
1563
1564         uaddr=ws_sockaddr_ws2u(name,namelen,&uaddrlen);
1565         if (uaddr == NULL)
1566         {
1567             SetLastError(WSAEFAULT);
1568         }
1569         else
1570         {
1571             int rc;
1572
1573             rc=connect(fd, uaddr, uaddrlen);
1574             ws_sockaddr_free(uaddr,name);
1575             if (rc == 0)
1576                 goto connect_success;
1577         }
1578
1579         if (errno == EINPROGRESS)
1580         {
1581             /* tell wineserver that a connection is in progress */
1582             _enable_event(s, FD_CONNECT|FD_READ|FD_WRITE,
1583                           FD_CONNECT|FD_READ|FD_WRITE,
1584                           FD_WINE_CONNECTED|FD_WINE_LISTENING);
1585             if (_is_blocking(s))
1586             {
1587                 int result;
1588                 /* block here */
1589                 do_block(fd, 7);
1590                 _sync_sock_state(s); /* let wineserver notice connection */
1591                 /* retrieve any error codes from it */
1592                 result = _get_sock_error(s, FD_CONNECT_BIT);
1593                 if (result)
1594                     SetLastError(result);
1595                 else
1596                 {
1597                     goto connect_success;
1598                 }
1599             }
1600             else
1601             {
1602                 SetLastError(WSAEWOULDBLOCK);
1603             }
1604         }
1605         else
1606         {
1607             SetLastError(wsaErrno());
1608         }
1609         close(fd);
1610     }
1611     else
1612     {
1613         SetLastError(WSAENOTSOCK);
1614     }
1615     return SOCKET_ERROR;
1616
1617 connect_success:
1618     close(fd);
1619     _enable_event(s, FD_CONNECT|FD_READ|FD_WRITE,
1620                   FD_WINE_CONNECTED|FD_READ|FD_WRITE,
1621                   FD_CONNECT|FD_WINE_LISTENING);
1622     return 0;
1623 }
1624
1625 /***********************************************************************
1626  *              connect               (WINSOCK.4)
1627  */
1628 INT16 WINAPI WINSOCK_connect16(SOCKET16 s, struct WS_sockaddr *name, INT16 namelen)
1629 {
1630   return (INT16)WS_connect( s, name, namelen );
1631 }
1632
1633 /***********************************************************************
1634  *              WSAConnect             (WS2_32.30)
1635  */
1636 int WINAPI WSAConnect ( SOCKET s, const struct WS_sockaddr* name, int namelen,
1637                         LPWSABUF lpCallerData, LPWSABUF lpCalleeData,
1638                         LPQOS lpSQOS, LPQOS lpGQOS )
1639 {
1640     if ( lpCallerData || lpCalleeData || lpSQOS || lpGQOS )
1641         FIXME ("unsupported parameters!\n");
1642     return WS_connect ( s, name, namelen );
1643 }
1644
1645
1646 /***********************************************************************
1647  *              getpeername             (WS2_32.5)
1648  */
1649 int WINAPI WS_getpeername(SOCKET s, struct WS_sockaddr *name, int *namelen)
1650 {
1651     int fd;
1652     int res;
1653
1654     TRACE("socket: %04x, ptr %p, len %8x\n", s, name, *namelen);
1655
1656     /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1657     if( (name == NULL) || (namelen == NULL) )
1658     {
1659         SetLastError( WSAEFAULT );
1660         return SOCKET_ERROR;
1661     }
1662
1663     fd = _get_sock_fd(s);
1664     res = SOCKET_ERROR;
1665
1666     if (fd != -1)
1667     {
1668         struct sockaddr* uaddr;
1669         int uaddrlen;
1670
1671         uaddr=ws_sockaddr_alloc(name,namelen,&uaddrlen);
1672         if (getpeername(fd, uaddr, &uaddrlen) != 0)
1673         {
1674             SetLastError(wsaErrno());
1675         }
1676         else if (ws_sockaddr_u2ws(uaddr,uaddrlen,name,namelen) != 0)
1677         {
1678             /* The buffer was too small */
1679             SetLastError(WSAEFAULT);
1680         }
1681         else
1682         {
1683             res=0;
1684         }
1685         ws_sockaddr_free(uaddr,name);
1686         close(fd);
1687     }
1688     else
1689     {
1690         SetLastError(WSAENOTSOCK);
1691     }
1692     return res;
1693 }
1694
1695 /***********************************************************************
1696  *              getpeername             (WINSOCK.5)
1697  */
1698 INT16 WINAPI WINSOCK_getpeername16(SOCKET16 s, struct WS_sockaddr *name,
1699                                    INT16 *namelen16)
1700 {
1701     INT namelen32 = *namelen16;
1702     INT retVal = WS_getpeername( s, name, &namelen32 );
1703
1704 #if DEBUG_SOCKADDR
1705     dump_sockaddr(name);
1706 #endif
1707
1708    *namelen16 = namelen32;
1709     return (INT16)retVal;
1710 }
1711
1712 /***********************************************************************
1713  *              getsockname             (WS2_32.6)
1714  */
1715 int WINAPI WS_getsockname(SOCKET s, struct WS_sockaddr *name, int *namelen)
1716 {
1717     int fd;
1718     int res;
1719
1720     TRACE("socket: %04x, ptr %p, len %8x\n", s, name, *namelen);
1721
1722     /* Check if what we've received is valid. Should we use IsBadReadPtr? */
1723     if( (name == NULL) || (namelen == NULL) )
1724     {
1725         SetLastError( WSAEFAULT );
1726         return SOCKET_ERROR;
1727     }
1728
1729     fd = _get_sock_fd(s);
1730     res = SOCKET_ERROR;
1731
1732     if (fd != -1)
1733     {
1734         struct sockaddr* uaddr;
1735         int uaddrlen;
1736
1737         uaddr=ws_sockaddr_alloc(name,namelen,&uaddrlen);
1738         if (getsockname(fd, uaddr, &uaddrlen) != 0)
1739         {
1740             SetLastError(wsaErrno());
1741         }
1742         else if (ws_sockaddr_u2ws(uaddr,uaddrlen,name,namelen) != 0)
1743         {
1744             /* The buffer was too small */
1745             SetLastError(WSAEFAULT);
1746         }
1747         else
1748         {
1749             res=0;
1750         }
1751         close(fd);
1752     }
1753     else
1754     {
1755         SetLastError(WSAENOTSOCK);
1756     }
1757     return res;
1758 }
1759
1760 /***********************************************************************
1761  *              getsockname             (WINSOCK.6)
1762  */
1763 INT16 WINAPI WINSOCK_getsockname16(SOCKET16 s, struct WS_sockaddr *name,
1764                                    INT16 *namelen16)
1765 {
1766     INT retVal;
1767
1768     if( namelen16 )
1769     {
1770         INT namelen32 = *namelen16;
1771         retVal = WS_getsockname( s, name, &namelen32 );
1772        *namelen16 = namelen32;
1773
1774 #if DEBUG_SOCKADDR
1775     dump_sockaddr(name);
1776 #endif
1777
1778     }
1779     else retVal = SOCKET_ERROR;
1780     return (INT16)retVal;
1781 }
1782
1783
1784 /***********************************************************************
1785  *              getsockopt              (WS2_32.7)
1786  */
1787 INT WINAPI WS_getsockopt(SOCKET s, INT level,
1788                                   INT optname, char *optval, INT *optlen)
1789 {
1790     int fd;
1791
1792     TRACE("socket: %04x, level 0x%x, name 0x%x, ptr %8x, len %d\n", s, level,
1793           (int) optname, (int) optval, (int) *optlen);
1794     /* SO_OPENTYPE does not require a valid socket handle. */
1795     if (level == WS_SOL_SOCKET && optname == WS_SO_OPENTYPE)
1796     {
1797         if (!optlen || *optlen < sizeof(int) || !optval)
1798         {
1799             SetLastError(WSAEFAULT);
1800             return SOCKET_ERROR;
1801         }
1802         *(int *)optval = (int)TlsGetValue( opentype_tls_index );
1803         *optlen = sizeof(int);
1804         TRACE("getting global SO_OPENTYPE = 0x%x\n", *((int*)optval) );
1805         return 0;
1806     }
1807
1808     fd = _get_sock_fd(s);
1809     if (fd != -1)
1810     {
1811         if (!convert_sockopt(&level, &optname)) {
1812             SetLastError(WSAENOPROTOOPT);       /* Unknown option */
1813         } else {
1814             if (getsockopt(fd, (int) level, optname, optval, optlen) == 0 )
1815             {
1816                 close(fd);
1817                 return 0;
1818             }
1819             SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
1820         }
1821         close(fd);
1822     }
1823     return SOCKET_ERROR;
1824 }
1825
1826
1827 /***********************************************************************
1828  *              getsockopt              (WINSOCK.7)
1829  */
1830 INT16 WINAPI WINSOCK_getsockopt16(SOCKET16 s, INT16 level,
1831                                   INT16 optname, char *optval, INT16 *optlen)
1832 {
1833     INT optlen32;
1834     INT *p = &optlen32;
1835     INT retVal;
1836     if( optlen ) optlen32 = *optlen; else p = NULL;
1837     retVal = WS_getsockopt( s, (UINT16)level, optname, optval, p );
1838     if( optlen ) *optlen = optlen32;
1839     return (INT16)retVal;
1840 }
1841
1842
1843 /***********************************************************************
1844  *              htonl                   (WINSOCK.8)
1845  *              htonl                   (WS2_32.8)
1846  */
1847 u_long WINAPI WS_htonl(u_long hostlong)
1848 {
1849     return htonl(hostlong);
1850 }
1851
1852
1853 /***********************************************************************
1854  *              htons                   (WINSOCK.9)
1855  *              htons                   (WS2_32.9)
1856  */
1857 u_short WINAPI WS_htons(u_short hostshort)
1858 {
1859     return htons(hostshort);
1860 }
1861
1862
1863 /***********************************************************************
1864  *              inet_addr               (WINSOCK.10)
1865  *              inet_addr               (WS2_32.11)
1866  */
1867 u_long WINAPI WS_inet_addr(const char *cp)
1868 {
1869     return inet_addr(cp);
1870 }
1871
1872
1873 /***********************************************************************
1874  *              ntohl                   (WINSOCK.14)
1875  *              ntohl                   (WS2_32.14)
1876  */
1877 u_long WINAPI WS_ntohl(u_long netlong)
1878 {
1879     return ntohl(netlong);
1880 }
1881
1882
1883 /***********************************************************************
1884  *              ntohs                   (WINSOCK.15)
1885  *              ntohs                   (WS2_32.15)
1886  */
1887 u_short WINAPI WS_ntohs(u_short netshort)
1888 {
1889     return ntohs(netshort);
1890 }
1891
1892
1893 /***********************************************************************
1894  *              inet_ntoa               (WS2_32.12)
1895  */
1896 char* WINAPI WS_inet_ntoa(struct WS_in_addr in)
1897 {
1898   /* use "buffer for dummies" here because some applications have
1899    * propensity to decode addresses in ws_hostent structure without
1900    * saving them first...
1901    */
1902     static char dbuffer[16]; /* Yes, 16: 4*3 digits + 3 '.' + 1 '\0' */
1903
1904     char* s = inet_ntoa(*((struct in_addr*)&in));
1905     if( s )
1906     {
1907         strcpy(dbuffer, s);
1908         return dbuffer;
1909     }
1910     SetLastError(wsaErrno());
1911     return NULL;
1912 }
1913
1914 /***********************************************************************
1915  *              inet_ntoa               (WINSOCK.11)
1916  */
1917 SEGPTR WINAPI WINSOCK_inet_ntoa16(struct in_addr in)
1918 {
1919     char* retVal;
1920     if (!(retVal = WS_inet_ntoa(*((struct WS_in_addr*)&in)))) return 0;
1921     if (!dbuffer_seg) dbuffer_seg = MapLS( retVal );
1922     return dbuffer_seg;
1923 }
1924
1925
1926 /**********************************************************************
1927  *              WSAIoctl                (WS2_32.50)
1928  *
1929  *
1930  *   FIXME:  Only SIO_GET_INTERFACE_LIST option implemented.
1931  */
1932 INT WINAPI WSAIoctl (SOCKET s,
1933                      DWORD   dwIoControlCode,
1934                      LPVOID  lpvInBuffer,
1935                      DWORD   cbInBuffer,
1936                      LPVOID  lpbOutBuffer,
1937                      DWORD   cbOutBuffer,
1938                      LPDWORD lpcbBytesReturned,
1939                      LPWSAOVERLAPPED lpOverlapped,
1940                      LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
1941 {
1942    int fd = _get_sock_fd(s);
1943
1944    if (fd != -1)
1945    {
1946       switch( dwIoControlCode )
1947       {
1948          case SIO_GET_INTERFACE_LIST:
1949          {
1950             INTERFACE_INFO* intArray = (INTERFACE_INFO*)lpbOutBuffer;
1951             int i, numInt;
1952             struct ifreq ifInfo;
1953             char ifName[512];
1954
1955
1956             TRACE ("-> SIO_GET_INTERFACE_LIST request\n");
1957
1958             numInt = WSAIOCTL_GetInterfaceCount();
1959             if (numInt < 0)
1960             {
1961                ERR ("Unable to open /proc filesystem to determine number of network interfaces!\n");
1962                close(fd);
1963                WSASetLastError(WSAEINVAL);
1964                return (SOCKET_ERROR);
1965             }
1966
1967             for (i=0; i<numInt; i++)
1968             {
1969                if (!WSAIOCTL_GetInterfaceName(i, ifName))
1970                {
1971                   ERR ("Error parsing /proc filesystem!\n");
1972                   close(fd);
1973                   WSASetLastError(WSAEINVAL);
1974                   return (SOCKET_ERROR);
1975                }
1976
1977                ifInfo.ifr_addr.sa_family = AF_INET;
1978
1979                /* IP Address */
1980                strcpy (ifInfo.ifr_name, ifName);
1981                if (ioctl(fd, SIOCGIFADDR, &ifInfo) < 0)
1982                {
1983                   ERR ("Error obtaining IP address\n");
1984                   close(fd);
1985                   WSASetLastError(WSAEINVAL);
1986                   return (SOCKET_ERROR);
1987                }
1988                else
1989                {
1990                   struct WS_sockaddr_in *ipTemp = (struct WS_sockaddr_in *)&ifInfo.ifr_addr;
1991
1992                   intArray->iiAddress.AddressIn.sin_family = AF_INET;
1993                   intArray->iiAddress.AddressIn.sin_port = ipTemp->sin_port;
1994                   intArray->iiAddress.AddressIn.sin_addr.WS_s_addr = ipTemp->sin_addr.S_un.S_addr;
1995                }
1996
1997                /* Broadcast Address */
1998                strcpy (ifInfo.ifr_name, ifName);
1999                if (ioctl(fd, SIOCGIFBRDADDR, &ifInfo) < 0)
2000                {
2001                   ERR ("Error obtaining Broadcast IP address\n");
2002                   close(fd);
2003                   WSASetLastError(WSAEINVAL);
2004                   return (SOCKET_ERROR);
2005                }
2006                else
2007                {
2008                   struct WS_sockaddr_in *ipTemp = (struct WS_sockaddr_in *)&ifInfo.ifr_broadaddr;
2009
2010                   intArray->iiBroadcastAddress.AddressIn.sin_family = AF_INET;
2011                   intArray->iiBroadcastAddress.AddressIn.sin_port = ipTemp->sin_port;
2012                   intArray->iiBroadcastAddress.AddressIn.sin_addr.WS_s_addr = ipTemp->sin_addr.S_un.S_addr;
2013                }
2014
2015                /* Subnet Mask */
2016                strcpy (ifInfo.ifr_name, ifName);
2017                if (ioctl(fd, SIOCGIFNETMASK, &ifInfo) < 0)
2018                {
2019                   ERR ("Error obtaining Subnet IP address\n");
2020                   close(fd);
2021                   WSASetLastError(WSAEINVAL);
2022                   return (SOCKET_ERROR);
2023                }
2024                else
2025                {
2026                   /* Trying to avoid some compile problems across platforms.
2027                      (Linux, FreeBSD, Solaris...) */
2028                   #ifndef ifr_netmask
2029                     #ifndef ifr_addr
2030                        intArray->iiNetmask.AddressIn.sin_family = AF_INET;
2031                        intArray->iiNetmask.AddressIn.sin_port = 0;
2032                        intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr = 0;
2033                        ERR ("Unable to determine Netmask on your platform!\n");
2034                     #else
2035                        struct WS_sockaddr_in *ipTemp = (struct WS_sockaddr_in *)&ifInfo.ifr_addr;
2036
2037                        intArray->iiNetmask.AddressIn.sin_family = AF_INET;
2038                        intArray->iiNetmask.AddressIn.sin_port = ipTemp->sin_port;
2039                        intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr = ipTemp->sin_addr.S_un.S_addr;
2040                     #endif
2041                   #else
2042                      struct WS_sockaddr_in *ipTemp = (struct WS_sockaddr_in *)&ifInfo.ifr_netmask;
2043
2044                      intArray->iiNetmask.AddressIn.sin_family = AF_INET;
2045                      intArray->iiNetmask.AddressIn.sin_port = ipTemp->sin_port;
2046                      intArray->iiNetmask.AddressIn.sin_addr.WS_s_addr = ipTemp->sin_addr.S_un.S_addr;
2047                   #endif
2048                }
2049
2050                /* Socket Status Flags */
2051                strcpy(ifInfo.ifr_name, ifName);
2052                if (ioctl(fd, SIOCGIFFLAGS, &ifInfo) < 0)
2053                {
2054                   ERR ("Error obtaining status flags for socket!\n");
2055                   close(fd);
2056                   WSASetLastError(WSAEINVAL);
2057                   return (SOCKET_ERROR);
2058                }
2059                else
2060                {
2061                   /* FIXME - Is this the right flag to use? */
2062                   intArray->iiFlags = ifInfo.ifr_flags;
2063                }
2064                intArray++; /* Prepare for another interface */
2065             }
2066
2067             /* Calculate the size of the array being returned */
2068             *lpcbBytesReturned = sizeof(INTERFACE_INFO) * numInt;
2069             break;
2070          }
2071
2072          default:
2073          {
2074             WARN("\tunsupported WS_IOCTL cmd (%08lx)\n", dwIoControlCode);
2075             close(fd);
2076             WSASetLastError(WSAEOPNOTSUPP);
2077             return (SOCKET_ERROR);
2078          }
2079       }
2080
2081       /* Function executed with no errors */
2082       close(fd);
2083       return (0);
2084    }
2085    else
2086    {
2087       WSASetLastError(WSAENOTSOCK);
2088       return (SOCKET_ERROR);
2089    }
2090 }
2091
2092
2093 /*
2094   Helper function for WSAIoctl - Get count of the number of interfaces
2095   by parsing /proc filesystem.
2096 */
2097 int WSAIOCTL_GetInterfaceCount(void)
2098 {
2099    FILE *procfs;
2100    char buf[512];  /* Size doesn't matter, something big */
2101    int  intcnt=0;
2102
2103
2104    /* Open /proc filesystem file for network devices */
2105    procfs = fopen(PROCFS_NETDEV_FILE, "r");
2106    if (!procfs)
2107    {
2108       /* If we can't open the file, return an error */
2109       return (-1);
2110    }
2111
2112    /* Omit first two lines, they are only headers */
2113    fgets(buf, sizeof buf, procfs);
2114    fgets(buf, sizeof buf, procfs);
2115
2116    while (fgets(buf, sizeof buf, procfs))
2117    {
2118       /* Each line in the file represents a network interface */
2119       intcnt++;
2120    }
2121
2122    fclose(procfs);
2123    return(intcnt);
2124 }
2125
2126
2127 /*
2128    Helper function for WSAIoctl - Get name of device from interface number
2129    by parsing /proc filesystem.
2130 */
2131 int WSAIOCTL_GetInterfaceName(int intNumber, char *intName)
2132 {
2133    FILE *procfs;
2134    char buf[512]; /* Size doesn't matter, something big */
2135    int  i;
2136
2137    /* Open /proc filesystem file for network devices */
2138    procfs = fopen(PROCFS_NETDEV_FILE, "r");
2139    if (!procfs)
2140    {
2141       /* If we can't open the file, return an error */
2142       return (-1);
2143    }
2144
2145    /* Omit first two lines, they are only headers */
2146    fgets(buf, sizeof(buf), procfs);
2147    fgets(buf, sizeof(buf), procfs);
2148
2149    for (i=0; i<intNumber; i++)
2150    {
2151       /* Skip the lines that don't interest us. */
2152       fgets(buf, sizeof(buf), procfs);
2153    }
2154    fgets(buf, sizeof(buf), procfs); /* This is the line we want */
2155
2156
2157    /* Parse out the line, grabbing only the name of the device
2158       to the intName variable
2159
2160       The Line comes in like this: (we only care about the device name)
2161       lo:   21970 377 0 0 0 0 0 0 21970 377 0 0 0 0 0 0
2162    */
2163    i=0;
2164    while (isspace(buf[i])) /* Skip initial space(s) */
2165    {
2166       i++;
2167    }
2168
2169    while (buf[i])
2170    {
2171       if (isspace(buf[i]))
2172       {
2173          break;
2174       }
2175
2176       if (buf[i] == ':')  /* FIXME: Not sure if this block (alias detection) works properly */
2177       {
2178          /* This interface could be an alias... */
2179          int hold = i;
2180          char *dotname = intName;
2181          *intName++ = buf[i++];
2182
2183          while (isdigit(buf[i]))
2184          {
2185             *intName++ = buf[i++];
2186          }
2187
2188          if (buf[i] != ':')
2189          {
2190             /* ... It wasn't, so back up */
2191             i = hold;
2192             intName = dotname;
2193          }
2194
2195          if (buf[i] == '\0')
2196          {
2197             fclose(procfs);
2198             return(FALSE);
2199          }
2200
2201          i++;
2202          break;
2203       }
2204
2205       *intName++ = buf[i++];
2206    }
2207    *intName++ = '\0';
2208
2209    fclose(procfs);
2210    return(TRUE);
2211  }
2212
2213
2214 /***********************************************************************
2215  *              ioctlsocket             (WS2_32.10)
2216  */
2217 int WINAPI WS_ioctlsocket(SOCKET s, long cmd, u_long *argp)
2218 {
2219   int fd = _get_sock_fd(s);
2220
2221   TRACE("socket %04x, cmd %08lx, ptr %8x\n", s, cmd, (unsigned) argp);
2222   if (fd != -1)
2223   {
2224     long        newcmd  = cmd;
2225
2226     switch( cmd )
2227     {
2228         case WS_FIONREAD:
2229                 newcmd=FIONREAD;
2230                 break;
2231
2232         case WS_FIONBIO:
2233                 newcmd=FIONBIO;
2234                 if( _get_sock_mask(s) )
2235                 {
2236                     /* AsyncSelect()'ed sockets are always nonblocking */
2237                     if (*argp) {
2238                         close(fd);
2239                         return 0;
2240                     }
2241                     SetLastError(WSAEINVAL);
2242                     close(fd);
2243                     return SOCKET_ERROR;
2244                 }
2245                 close(fd);
2246                 if (*argp)
2247                     _enable_event(s, 0, FD_WINE_NONBLOCKING, 0);
2248                 else
2249                     _enable_event(s, 0, 0, FD_WINE_NONBLOCKING);
2250                 return 0;
2251
2252         case WS_SIOCATMARK:
2253                 newcmd=SIOCATMARK;
2254                 break;
2255
2256         case WS__IOW('f',125,u_long):
2257                 WARN("Warning: WS1.1 shouldn't be using async I/O\n");
2258                 SetLastError(WSAEINVAL);
2259                 return SOCKET_ERROR;
2260
2261         case SIOCGIFBRDADDR:
2262         case SIOCGIFNETMASK:
2263         case SIOCGIFADDR:
2264                 /* These don't need any special handling.  They are used by
2265                    WsControl, and are here to suppress an unecessary warning. */
2266                 break;
2267
2268
2269         default:
2270                 /* Netscape tries hard to use bogus ioctl 0x667e */
2271                 WARN("\tunknown WS_IOCTL cmd (%08lx)\n", cmd);
2272     }
2273     if( ioctl(fd, newcmd, (char*)argp ) == 0 )
2274     {
2275         close(fd);
2276         return 0;
2277     }
2278     SetLastError((errno == EBADF) ? WSAENOTSOCK : wsaErrno());
2279     close(fd);
2280   }
2281   return SOCKET_ERROR;
2282 }
2283
2284 /***********************************************************************
2285  *              ioctlsocket           (WINSOCK.12)
2286  */
2287 INT16 WINAPI WINSOCK_ioctlsocket16(SOCKET16 s, LONG cmd, ULONG *argp)
2288 {
2289     return (INT16)WS_ioctlsocket( s, cmd, argp );
2290 }
2291
2292
2293 /***********************************************************************
2294  *              listen          (WS2_32.13)
2295  */
2296 int WINAPI WS_listen(SOCKET s, int backlog)
2297 {
2298     int fd = _get_sock_fd(s);
2299
2300     TRACE("socket %04x, backlog %d\n", s, backlog);
2301     if (fd != -1)
2302     {
2303         if (listen(fd, backlog) == 0)
2304         {
2305             close(fd);
2306             _enable_event(s, FD_ACCEPT,
2307                           FD_WINE_LISTENING,
2308                           FD_CONNECT|FD_WINE_CONNECTED);
2309             return 0;
2310         }
2311         SetLastError(wsaErrno());
2312     }
2313     else SetLastError(WSAENOTSOCK);
2314     return SOCKET_ERROR;
2315 }
2316
2317 /***********************************************************************
2318  *              listen          (WINSOCK.13)
2319  */
2320 INT16 WINAPI WINSOCK_listen16(SOCKET16 s, INT16 backlog)
2321 {
2322     return (INT16)WS_listen( s, backlog );
2323 }
2324
2325
2326 /***********************************************************************
2327  *              recv                    (WS2_32.16)
2328  */
2329 int WINAPI WS_recv(SOCKET s, char *buf, int len, int flags)
2330 {
2331     DWORD n, dwFlags = flags;
2332     WSABUF wsabuf = { len, buf };
2333
2334     if ( WSARecvFrom (s, &wsabuf, 1, &n, &dwFlags, NULL, NULL, NULL, NULL) == SOCKET_ERROR )
2335         return SOCKET_ERROR;
2336     else
2337         return n;
2338 }
2339
2340 /***********************************************************************
2341  *              recv                    (WINSOCK.16)
2342  */
2343 INT16 WINAPI WINSOCK_recv16(SOCKET16 s, char *buf, INT16 len, INT16 flags)
2344 {
2345     return (INT16)WS_recv( s, buf, len, flags );
2346 }
2347
2348
2349 /***********************************************************************
2350  *              recvfrom                (WS2_32.17)
2351  */
2352 int WINAPI WS_recvfrom(SOCKET s, char *buf, INT len, int flags,
2353                                 struct WS_sockaddr *from, int *fromlen)
2354 {
2355     DWORD n, dwFlags = flags;
2356     WSABUF wsabuf = { len, buf };
2357
2358     if ( WSARecvFrom (s, &wsabuf, 1, &n, &dwFlags, from, fromlen, NULL, NULL) == SOCKET_ERROR )
2359         return SOCKET_ERROR;
2360     else
2361         return n;
2362 }
2363
2364 /***********************************************************************
2365  *              recvfrom                (WINSOCK.17)
2366  */
2367 INT16 WINAPI WINSOCK_recvfrom16(SOCKET16 s, char *buf, INT16 len, INT16 flags,
2368                                 struct WS_sockaddr *from, INT16 *fromlen16)
2369 {
2370     INT fromlen32;
2371     INT *p = &fromlen32;
2372     INT retVal;
2373
2374     if( fromlen16 ) fromlen32 = *fromlen16; else p = NULL;
2375     retVal = WS_recvfrom( s, buf, len, flags, from, p );
2376     if( fromlen16 ) *fromlen16 = fromlen32;
2377     return (INT16)retVal;
2378 }
2379
2380 /***********************************************************************
2381  *              __ws_select
2382  */
2383 static int __ws_select(BOOL b32,
2384                        void *ws_readfds, void *ws_writefds, void *ws_exceptfds,
2385                        const struct WS_timeval *ws_timeout)
2386 {
2387     int         highfd = 0;
2388     fd_set      readfds, writefds, exceptfds;
2389     fd_set     *p_read, *p_write, *p_except;
2390     int         readfd[FD_SETSIZE], writefd[FD_SETSIZE], exceptfd[FD_SETSIZE];
2391     struct timeval timeout, *timeoutaddr = NULL;
2392
2393     TRACE("read %p, write %p, excp %p timeout %p\n",
2394           ws_readfds, ws_writefds, ws_exceptfds, ws_timeout);
2395
2396     p_read = fd_set_import(&readfds, ws_readfds, &highfd, readfd, b32);
2397     p_write = fd_set_import(&writefds, ws_writefds, &highfd, writefd, b32);
2398     p_except = fd_set_import(&exceptfds, ws_exceptfds, &highfd, exceptfd, b32);
2399     if (ws_timeout)
2400     {
2401         timeoutaddr = &timeout;
2402         timeout.tv_sec=ws_timeout->tv_sec;
2403         timeout.tv_usec=ws_timeout->tv_usec;
2404     }
2405
2406     if( (highfd = select(highfd + 1, p_read, p_write, p_except, timeoutaddr)) > 0 )
2407     {
2408         fd_set_export(&readfds, p_except, ws_readfds, readfd, b32);
2409         fd_set_export(&writefds, p_except, ws_writefds, writefd, b32);
2410
2411         if (p_except && ws_exceptfds)
2412         {
2413 #define wsfds16 ((ws_fd_set16*)ws_exceptfds)
2414 #define wsfds32 ((WS_fd_set*)ws_exceptfds)
2415             int i, j, count = (b32) ? wsfds32->fd_count : wsfds16->fd_count;
2416
2417             for (i = j = 0; i < count; i++)
2418             {
2419                 int fd = exceptfd[i];
2420                 if( fd >= 0 && FD_ISSET(fd, &exceptfds) )
2421                 {
2422                     if( b32 )
2423                         wsfds32->fd_array[j++] = wsfds32->fd_array[i];
2424                     else
2425                         wsfds16->fd_array[j++] = wsfds16->fd_array[i];
2426                 }
2427                 if( fd >= 0 ) close(fd);
2428                 exceptfd[i] = -1;
2429             }
2430             if( b32 )
2431                 wsfds32->fd_count = j;
2432             else
2433                 wsfds16->fd_count = j;
2434 #undef wsfds32
2435 #undef wsfds16
2436         }
2437         return highfd;
2438     }
2439     fd_set_unimport(ws_readfds, readfd, b32);
2440     fd_set_unimport(ws_writefds, writefd, b32);
2441     fd_set_unimport(ws_exceptfds, exceptfd, b32);
2442     if( ws_readfds ) ((WS_fd_set*)ws_readfds)->fd_count = 0;
2443     if( ws_writefds ) ((WS_fd_set*)ws_writefds)->fd_count = 0;
2444     if( ws_exceptfds ) ((WS_fd_set*)ws_exceptfds)->fd_count = 0;
2445
2446     if( highfd == 0 ) return 0;
2447     SetLastError(wsaErrno());
2448     return SOCKET_ERROR;
2449 }
2450
2451 /***********************************************************************
2452  *              select                  (WINSOCK.18)
2453  */
2454 INT16 WINAPI WINSOCK_select16(INT16 nfds, ws_fd_set16 *ws_readfds,
2455                               ws_fd_set16 *ws_writefds, ws_fd_set16 *ws_exceptfds,
2456                               struct WS_timeval* timeout)
2457 {
2458     return (INT16)__ws_select( FALSE, ws_readfds, ws_writefds, ws_exceptfds, timeout );
2459 }
2460
2461 /***********************************************************************
2462  *              select                  (WS2_32.18)
2463  */
2464 int WINAPI WS_select(int nfds, WS_fd_set *ws_readfds,
2465                      WS_fd_set *ws_writefds, WS_fd_set *ws_exceptfds,
2466                      const struct WS_timeval* timeout)
2467 {
2468     /* struct timeval is the same for both 32- and 16-bit code */
2469     return (INT)__ws_select( TRUE, ws_readfds, ws_writefds, ws_exceptfds, timeout );
2470 }
2471
2472
2473 /***********************************************************************
2474  *              send                    (WS2_32.19)
2475  */
2476 int WINAPI WS_send(SOCKET s, const char *buf, int len, int flags)
2477 {
2478     DWORD n;
2479     WSABUF wsabuf = { len, (char*) buf };
2480
2481     if ( WSASendTo ( s, &wsabuf, 1, &n, flags, NULL, 0, NULL, NULL) == SOCKET_ERROR )
2482         return SOCKET_ERROR;
2483     else
2484         return n;
2485 }
2486
2487 /***********************************************************************
2488  *              WSASend                 (WS2_32.72)
2489  */
2490 INT WINAPI WSASend( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2491                     LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2492                     LPWSAOVERLAPPED lpOverlapped,
2493                     LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2494 {
2495     return WSASendTo ( s, lpBuffers, dwBufferCount, lpNumberOfBytesSent, dwFlags,
2496                        NULL, 0, lpOverlapped, lpCompletionRoutine );
2497 }
2498
2499 /***********************************************************************
2500  *              WSASendTo               (WS2_32.74)
2501  */
2502 INT WINAPI WSASendTo( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
2503                       LPDWORD lpNumberOfBytesSent, DWORD dwFlags,
2504                       const struct WS_sockaddr *to, int tolen,
2505                       LPWSAOVERLAPPED lpOverlapped,
2506                       LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
2507 {
2508     int i, n, fd, err = WSAENOTSOCK, flags, ret;
2509     struct iovec* iovec;
2510     struct ws2_async *wsa;
2511     enum fd_type type;
2512
2513     TRACE ("socket %04x, wsabuf %p, nbufs %ld, flags %ld, to %p, tolen %d, ovl %p, func %p\n",
2514            s, lpBuffers, dwBufferCount, dwFlags,
2515            to, tolen, lpOverlapped, lpCompletionRoutine);
2516
2517     fd = _get_sock_fd_type( s, GENERIC_WRITE, &type, &flags );
2518     TRACE ( "fd=%d, type=%d, flags=%x\n", fd, type, flags );
2519
2520     if ( fd == -1 )
2521     {
2522         err = WSAGetLastError ();
2523         goto error;
2524     }
2525
2526     iovec = HeapAlloc (GetProcessHeap(), 0, dwBufferCount * sizeof (struct iovec) );
2527
2528     if ( !iovec )
2529     {
2530         err = WSAEFAULT;
2531         goto err_close;
2532     }
2533
2534     for ( i = 0; i < dwBufferCount; i++ )
2535     {
2536         iovec[i].iov_base = lpBuffers[i].buf;
2537         iovec[i].iov_len  = lpBuffers[i].len;
2538     }
2539
2540     if ( (lpOverlapped || lpCompletionRoutine) && flags & FD_FLAG_OVERLAPPED )
2541     {
2542         wsa = WS2_make_async ( s, fd, ASYNC_TYPE_WRITE, iovec, dwBufferCount,
2543                                &dwFlags, (struct WS_sockaddr*) to, &tolen,
2544                                lpOverlapped, lpCompletionRoutine );
2545         if ( !wsa )
2546         {
2547             err = WSAEFAULT;
2548             goto err_free;
2549         }
2550
2551         if ( ( ret = register_new_async ( &wsa->async )) )
2552         {
2553             err = NtStatusToWSAError ( ret );
2554
2555             if ( !lpOverlapped )
2556                 HeapFree ( GetProcessHeap(), 0, wsa->overlapped );
2557             HeapFree ( GetProcessHeap(), 0, wsa );
2558             goto err_free;
2559         }
2560
2561         /* Try immediate completion */
2562         if ( lpOverlapped && !NtResetEvent( lpOverlapped->hEvent, NULL ) )
2563         {
2564             if  ( WSAGetOverlappedResult ( (HANDLE) s, lpOverlapped,
2565                                            lpNumberOfBytesSent, FALSE, &dwFlags) )
2566                 return 0;
2567
2568             if ( (err = WSAGetLastError ()) != WSA_IO_INCOMPLETE )
2569                 goto error;
2570         }
2571
2572         WSASetLastError ( WSA_IO_PENDING );
2573         return SOCKET_ERROR;
2574     }
2575
2576     if (_is_blocking(s))
2577     {
2578         /* FIXME: exceptfds? */
2579         do_block(fd, 2);
2580     }
2581
2582     n = WS2_send ( fd, iovec, dwBufferCount, to, tolen, dwFlags );
2583     if ( n == -1 )
2584     {
2585         err = wsaErrno();
2586         if ( err == WSAEWOULDBLOCK )
2587             _enable_event (s, FD_WRITE, 0, 0);
2588         goto err_free;
2589     }
2590
2591     TRACE(" -> %i bytes\n", n);
2592     *lpNumberOfBytesSent = n;
2593
2594     HeapFree ( GetProcessHeap(), 0, iovec );
2595     close ( fd );
2596     return 0;
2597
2598 err_free:
2599     HeapFree ( GetProcessHeap(), 0, iovec );
2600
2601 err_close:
2602     close ( fd );
2603
2604 error:
2605     WARN (" -> ERROR %d\n", err);
2606     WSASetLastError (err);
2607     return SOCKET_ERROR;
2608 }
2609
2610 /***********************************************************************
2611  *              send                    (WINSOCK.19)
2612  */
2613 INT16 WINAPI WINSOCK_send16(SOCKET16 s, char *buf, INT16 len, INT16 flags)
2614 {
2615     return WS_send( s, buf, len, flags );
2616 }
2617
2618 /***********************************************************************
2619  *              sendto          (WS2_32.20)
2620  */
2621 int WINAPI WS_sendto(SOCKET s, const char *buf, int len, int flags,
2622                               const struct WS_sockaddr *to, int tolen)
2623 {
2624     DWORD n;
2625     WSABUF wsabuf = { len, (char*) buf };
2626
2627     if ( WSASendTo (s, &wsabuf, 1, &n, flags, to, tolen, NULL, NULL) == SOCKET_ERROR )
2628         return SOCKET_ERROR;
2629     else
2630         return n;
2631 }
2632
2633 /***********************************************************************
2634  *              sendto          (WINSOCK.20)
2635  */
2636 INT16 WINAPI WINSOCK_sendto16(SOCKET16 s, char *buf, INT16 len, INT16 flags,
2637                               struct WS_sockaddr *to, INT16 tolen)
2638 {
2639     return (INT16)WS_sendto( s, buf, len, flags, to, tolen );
2640 }
2641
2642 /***********************************************************************
2643  *              setsockopt              (WS2_32.21)
2644  */
2645 int WINAPI WS_setsockopt(SOCKET s, int level, int optname,
2646                                   const char *optval, int optlen)
2647 {
2648     int fd;
2649
2650     TRACE("socket: %04x, level 0x%x, name 0x%x, ptr %8x, len %d\n", s, level,
2651           (int) optname, (int) optval, optlen);
2652     /* SO_OPENTYPE does not require a valid socket handle. */
2653     if (level == WS_SOL_SOCKET && optname == WS_SO_OPENTYPE)
2654     {
2655         if (optlen < sizeof(int) || !optval)
2656         {
2657             SetLastError(WSAEFAULT);
2658             return SOCKET_ERROR;
2659         }
2660         TlsSetValue( opentype_tls_index, (LPVOID)*(int *)optval );
2661         TRACE("setting global SO_OPENTYPE to 0x%x\n", *(int *)optval );
2662         return 0;
2663     }
2664
2665     fd = _get_sock_fd(s);
2666     if (fd != -1)
2667     {
2668         struct  linger linger;
2669         int woptval;
2670
2671         /* Is a privileged and useless operation, so we don't. */
2672         if ((optname == WS_SO_DEBUG) && (level == WS_SOL_SOCKET)) {
2673             FIXME("(%d,SOL_SOCKET,SO_DEBUG,%p(%ld)) attempted (is privileged). Ignoring.\n",s,optval,*(DWORD*)optval);
2674             return 0;
2675         }
2676
2677         if(optname == WS_SO_DONTLINGER && level == WS_SOL_SOCKET) {
2678             /* This is unique to WinSock and takes special conversion */
2679             linger.l_onoff      = *((int*)optval) ? 0: 1;
2680             linger.l_linger     = 0;
2681             optname=SO_LINGER;
2682             optval = (char*)&linger;
2683             optlen = sizeof(struct linger);
2684             level = SOL_SOCKET;
2685         }else{
2686             if (!convert_sockopt(&level, &optname)) {
2687                 SetLastError(WSAENOPROTOOPT);
2688                 close(fd);
2689                 return SOCKET_ERROR;
2690             }
2691             if (optname == SO_LINGER && optval) {
2692                 /* yes, uses unsigned short in both win16/win32 */
2693                 linger.l_onoff  = ((UINT16*)optval)[0];
2694                 linger.l_linger = ((UINT16*)optval)[1];
2695                 /* FIXME: what is documented behavior if SO_LINGER optval
2696                    is null?? */
2697                 optval = (char*)&linger;
2698                 optlen = sizeof(struct linger);
2699             } else if (optlen < sizeof(int)){
2700                 woptval= *((INT16 *) optval);
2701                 optval= (char*) &woptval;
2702                 optlen=sizeof(int);
2703             }
2704         }
2705         if(optname == SO_RCVBUF && *(int*)optval < 2048) {
2706             WARN("SO_RCVBF for %d bytes is too small: ignored\n", *(int*)optval );
2707             close( fd);
2708             return 0;
2709         }
2710
2711         if (setsockopt(fd, level, optname, optval, optlen) == 0)
2712         {
2713             close(fd);
2714             return 0;
2715         }
2716         SetLastError(wsaErrno());
2717         close(fd);
2718     }
2719     else SetLastError(WSAENOTSOCK);
2720     return SOCKET_ERROR;
2721 }
2722
2723 /***********************************************************************
2724  *              setsockopt              (WINSOCK.21)
2725  */
2726 INT16 WINAPI WINSOCK_setsockopt16(SOCKET16 s, INT16 level, INT16 optname,
2727                                   char *optval, INT16 optlen)
2728 {
2729     if( !optval ) return SOCKET_ERROR;
2730     return (INT16)WS_setsockopt( s, (UINT16)level, optname, optval, optlen );
2731 }
2732
2733
2734 /***********************************************************************
2735  *              shutdown                (WS2_32.22)
2736  */
2737 int WINAPI WS_shutdown(SOCKET s, int how)
2738 {
2739     int fd, fd0 = -1, fd1 = -1, flags, err = WSAENOTSOCK;
2740     enum fd_type type;
2741     unsigned int clear_flags = 0;
2742
2743     fd = _get_sock_fd_type ( s, 0, &type, &flags );
2744     TRACE("socket %04x, how %i %d %d \n", s, how, type, flags );
2745
2746     if (fd == -1)
2747         return SOCKET_ERROR;
2748
2749     switch( how )
2750     {
2751     case 0: /* drop receives */
2752         clear_flags |= FD_READ;
2753         break;
2754     case 1: /* drop sends */
2755         clear_flags |= FD_WRITE;
2756         break;
2757     case 2: /* drop all */
2758         clear_flags |= FD_READ|FD_WRITE;
2759     default:
2760         clear_flags |= FD_WINE_CONNECTED|FD_WINE_LISTENING;
2761     }
2762
2763     if ( flags & FD_FLAG_OVERLAPPED ) {
2764
2765         switch ( how )
2766         {
2767         case SD_RECEIVE:
2768             fd0 = fd;
2769             break;
2770         case SD_SEND:
2771             fd1 = fd;
2772             break;
2773         case SD_BOTH:
2774         default:
2775             fd0 = fd;
2776             fd1 = _get_sock_fd ( s );
2777         }
2778
2779         if ( fd0 != -1 )
2780         {
2781             err = WS2_register_async_shutdown ( s, fd0, ASYNC_TYPE_READ );
2782             if ( err )
2783             {
2784                 close ( fd0 );
2785                 goto error;
2786             }
2787         }
2788         if ( fd1 != -1 )
2789         {
2790             err = WS2_register_async_shutdown ( s, fd1, ASYNC_TYPE_WRITE );
2791             if ( err )
2792             {
2793                 close ( fd1 );
2794                 goto error;
2795             }
2796         }
2797     }
2798     else /* non-overlapped mode */
2799     {
2800         if ( shutdown( fd, how ) )
2801         {
2802             err = wsaErrno ();
2803             close ( fd );
2804             goto error;
2805         }
2806         close(fd);
2807     }
2808
2809     _enable_event( s, 0, 0, clear_flags );
2810     if ( how > 1) WSAAsyncSelect( s, 0, 0, 0 );
2811     return 0;
2812
2813 error:
2814     _enable_event( s, 0, 0, clear_flags );
2815     WSASetLastError ( err );
2816     return SOCKET_ERROR;
2817 }
2818
2819 /***********************************************************************
2820  *              shutdown                (WINSOCK.22)
2821  */
2822 INT16 WINAPI WINSOCK_shutdown16(SOCKET16 s, INT16 how)
2823 {
2824     return (INT16)WS_shutdown( s, how );
2825 }
2826
2827
2828 /***********************************************************************
2829  *              socket          (WS2_32.23)
2830  */
2831 SOCKET WINAPI WS_socket(int af, int type, int protocol)
2832 {
2833     TRACE("af=%d type=%d protocol=%d\n", af, type, protocol);
2834
2835     return WSASocketA ( af, type, protocol, NULL, 0,
2836                         (TlsGetValue(opentype_tls_index) ? 0 : WSA_FLAG_OVERLAPPED) );
2837 }
2838
2839 /***********************************************************************
2840  *              socket          (WINSOCK.23)
2841  */
2842 SOCKET16 WINAPI WINSOCK_socket16(INT16 af, INT16 type, INT16 protocol)
2843 {
2844     return (SOCKET16)WS_socket( af, type, protocol );
2845 }
2846
2847
2848 /* ----------------------------------- DNS services
2849  *
2850  * IMPORTANT: 16-bit API structures have SEGPTR pointers inside them.
2851  * Also, we have to use wsock32 stubs to convert structures and
2852  * error codes from Unix to WSA, hence there is no direct mapping in
2853  * the relay32/wsock32.spec.
2854  */
2855
2856
2857 /***********************************************************************
2858  *              __ws_gethostbyaddr
2859  */
2860 static WIN_hostent* __ws_gethostbyaddr(const char *addr, int len, int type, int dup_flag)
2861 {
2862     WIN_hostent *retval = NULL;
2863
2864     struct hostent* host;
2865 #if HAVE_LINUX_GETHOSTBYNAME_R_6
2866     char *extrabuf;
2867     int ebufsize=1024;
2868     struct hostent hostentry;
2869     int locerr=ENOBUFS;
2870     host = NULL;
2871     extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
2872     while(extrabuf) {
2873         int res = gethostbyaddr_r(addr, len, type,
2874                                   &hostentry, extrabuf, ebufsize, &host, &locerr);
2875         if( res != ERANGE) break;
2876         ebufsize *=2;
2877         extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
2878     }
2879     if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
2880 #else
2881     EnterCriticalSection( &csWSgetXXXbyYYY );
2882     host = gethostbyaddr(addr, len, type);
2883     if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
2884 #endif
2885     if( host != NULL )
2886     {
2887         if( WS_dup_he(host, dup_flag) )
2888             retval = he_buffer;
2889         else
2890             SetLastError(WSAENOBUFS);
2891     }
2892 #ifdef  HAVE_LINUX_GETHOSTBYNAME_R_6
2893     HeapFree(GetProcessHeap(),0,extrabuf);
2894 #else
2895     LeaveCriticalSection( &csWSgetXXXbyYYY );
2896 #endif
2897     return retval;
2898 }
2899
2900 /***********************************************************************
2901  *              gethostbyaddr           (WINSOCK.51)
2902  */
2903 SEGPTR WINAPI WINSOCK_gethostbyaddr16(const char *addr, INT16 len, INT16 type)
2904 {
2905     TRACE("ptr %p, len %d, type %d\n", addr, len, type);
2906     if (!__ws_gethostbyaddr( addr, len, type, WS_DUP_SEGPTR )) return 0;
2907     return he_buffer_seg;
2908 }
2909
2910 /***********************************************************************
2911  *              gethostbyaddr           (WS2_32.51)
2912  */
2913 struct WS_hostent* WINAPI WS_gethostbyaddr(const char *addr, int len,
2914                                                 int type)
2915 {
2916     TRACE("ptr %08x, len %d, type %d\n",
2917                              (unsigned) addr, len, type);
2918     return __ws_gethostbyaddr(addr, len, type, WS_DUP_LINEAR);
2919 }
2920
2921 /***********************************************************************
2922  *              __ws_gethostbyname
2923  */
2924 static WIN_hostent * __ws_gethostbyname(const char *name, int dup_flag)
2925 {
2926     WIN_hostent *retval = NULL;
2927     struct hostent*     host;
2928 #ifdef  HAVE_LINUX_GETHOSTBYNAME_R_6
2929     char *extrabuf;
2930     int ebufsize=1024;
2931     struct hostent hostentry;
2932     int locerr = ENOBUFS;
2933     host = NULL;
2934     extrabuf=HeapAlloc(GetProcessHeap(),0,ebufsize) ;
2935     while(extrabuf) {
2936         int res = gethostbyname_r(name, &hostentry, extrabuf, ebufsize, &host, &locerr);
2937         if( res != ERANGE) break;
2938         ebufsize *=2;
2939         extrabuf=HeapReAlloc(GetProcessHeap(),0,extrabuf,ebufsize) ;
2940     }
2941     if (!host) SetLastError((locerr < 0) ? wsaErrno() : wsaHerrno(locerr));
2942 #else
2943     EnterCriticalSection( &csWSgetXXXbyYYY );
2944     host = gethostbyname(name);
2945     if (!host) SetLastError((h_errno < 0) ? wsaErrno() : wsaHerrno(h_errno));
2946 #endif
2947     if( host  != NULL )
2948     {
2949         if( WS_dup_he(host, dup_flag) )
2950             retval = he_buffer;
2951         else SetLastError(WSAENOBUFS);
2952     }
2953 #ifdef  HAVE_LINUX_GETHOSTBYNAME_R_6
2954     HeapFree(GetProcessHeap(),0,extrabuf);
2955 #else
2956     LeaveCriticalSection( &csWSgetXXXbyYYY );
2957 #endif
2958     return retval;
2959 }
2960
2961 /***********************************************************************
2962  *              gethostbyname           (WINSOCK.52)
2963  */
2964 SEGPTR WINAPI WINSOCK_gethostbyname16(const char *name)
2965 {
2966     TRACE( "%s\n", debugstr_a(name) );
2967     if (!__ws_gethostbyname( name, WS_DUP_SEGPTR )) return 0;
2968     return he_buffer_seg;
2969 }
2970
2971 /***********************************************************************
2972  *              gethostbyname           (WS2_32.52)
2973  */
2974 struct WS_hostent* WINAPI WS_gethostbyname(const char* name)
2975 {
2976     TRACE( "%s\n", debugstr_a(name) );
2977     return __ws_gethostbyname( name, WS_DUP_LINEAR );
2978 }
2979
2980
2981 /***********************************************************************
2982  *              __ws_getprotobyname
2983  */
2984 static WIN_protoent* __ws_getprotobyname(const char *name, int dup_flag)
2985 {
2986     WIN_protoent* retval = NULL;
2987
2988     struct protoent*     proto;
2989     EnterCriticalSection( &csWSgetXXXbyYYY );
2990     if( (proto = getprotobyname(name)) != NULL )
2991     {
2992         if( WS_dup_pe(proto, dup_flag) )
2993             retval = pe_buffer;
2994         else SetLastError(WSAENOBUFS);
2995     }
2996     else {
2997         MESSAGE("protocol %s not found; You might want to add "
2998                 "this to /etc/protocols\n", debugstr_a(name) );
2999         SetLastError(WSANO_DATA);
3000     }
3001     LeaveCriticalSection( &csWSgetXXXbyYYY );
3002     return retval;
3003 }
3004
3005 /***********************************************************************
3006  *              getprotobyname          (WINSOCK.53)
3007  */
3008 SEGPTR WINAPI WINSOCK_getprotobyname16(const char *name)
3009 {
3010     TRACE( "%s\n", debugstr_a(name) );
3011     if (!__ws_getprotobyname(name, WS_DUP_SEGPTR)) return 0;
3012     return pe_buffer_seg;
3013 }
3014
3015 /***********************************************************************
3016  *              getprotobyname          (WS2_32.53)
3017  */
3018 struct WS_protoent* WINAPI WS_getprotobyname(const char* name)
3019 {
3020     TRACE( "%s\n", debugstr_a(name) );
3021     return __ws_getprotobyname(name, WS_DUP_LINEAR);
3022 }
3023
3024
3025 /***********************************************************************
3026  *              __ws_getprotobynumber
3027  */
3028 static WIN_protoent* __ws_getprotobynumber(int number, int dup_flag)
3029 {
3030     WIN_protoent* retval = NULL;
3031     struct protoent*     proto;
3032     EnterCriticalSection( &csWSgetXXXbyYYY );
3033     if( (proto = getprotobynumber(number)) != NULL )
3034     {
3035         if( WS_dup_pe(proto, dup_flag) )
3036             retval = pe_buffer;
3037         else SetLastError(WSAENOBUFS);
3038     }
3039     else {
3040         MESSAGE("protocol number %d not found; You might want to add "
3041                 "this to /etc/protocols\n", number );
3042         SetLastError(WSANO_DATA);
3043     }
3044     LeaveCriticalSection( &csWSgetXXXbyYYY );
3045     return retval;
3046 }
3047
3048 /***********************************************************************
3049  *              getprotobynumber        (WINSOCK.54)
3050  */
3051 SEGPTR WINAPI WINSOCK_getprotobynumber16(INT16 number)
3052 {
3053     TRACE("%i\n", number);
3054     if (!__ws_getprotobynumber(number, WS_DUP_SEGPTR)) return 0;
3055     return pe_buffer_seg;
3056 }
3057
3058 /***********************************************************************
3059  *              getprotobynumber        (WS2_32.54)
3060  */
3061 struct WS_protoent* WINAPI WS_getprotobynumber(int number)
3062 {
3063     TRACE("%i\n", number);
3064     return __ws_getprotobynumber(number, WS_DUP_LINEAR);
3065 }
3066
3067
3068 /***********************************************************************
3069  *              __ws_getservbyname
3070  */
3071 static WIN_servent* __ws_getservbyname(const char *name, const char *proto, int dup_flag)
3072 {
3073     WIN_servent* retval = NULL;
3074     struct servent*     serv;
3075     int i = wsi_strtolo( name, proto );
3076
3077     if( i ) {
3078         EnterCriticalSection( &csWSgetXXXbyYYY );
3079         serv = getservbyname(local_buffer,
3080                              proto ? (local_buffer + i) : NULL);
3081         if( serv != NULL )
3082         {
3083             if( WS_dup_se(serv, dup_flag) )
3084                 retval = se_buffer;
3085             else SetLastError(WSAENOBUFS);
3086         }
3087         else {
3088             MESSAGE("service %s protocol %s not found; You might want to add "
3089                     "this to /etc/services\n", debugstr_a(local_buffer),
3090                     proto ? debugstr_a(local_buffer+i):"*");
3091             SetLastError(WSANO_DATA);
3092         }
3093         LeaveCriticalSection( &csWSgetXXXbyYYY );
3094     }
3095     else SetLastError(WSAENOBUFS);
3096     return retval;
3097 }
3098
3099 /***********************************************************************
3100  *              getservbyname           (WINSOCK.55)
3101  */
3102 SEGPTR WINAPI WINSOCK_getservbyname16(const char *name, const char *proto)
3103 {
3104     TRACE( "%s, %s\n", debugstr_a(name), debugstr_a(proto) );
3105     if (!__ws_getservbyname(name, proto, WS_DUP_SEGPTR)) return 0;
3106     return se_buffer_seg;
3107 }
3108
3109 /***********************************************************************
3110  *              getservbyname           (WS2_32.55)
3111  */
3112 struct WS_servent* WINAPI WS_getservbyname(const char *name, const char *proto)
3113 {
3114     TRACE( "%s, %s\n", debugstr_a(name), debugstr_a(proto) );
3115     return __ws_getservbyname(name, proto, WS_DUP_LINEAR);
3116 }
3117
3118
3119 /***********************************************************************
3120  *              __ws_getservbyport
3121  */
3122 static WIN_servent* __ws_getservbyport(int port, const char* proto, int dup_flag)
3123 {
3124     WIN_servent* retval = NULL;
3125     struct servent*     serv;
3126     if (!proto || wsi_strtolo( proto, NULL )) {
3127         EnterCriticalSection( &csWSgetXXXbyYYY );
3128         if( (serv = getservbyport(port, (proto) ? local_buffer : NULL)) != NULL ) {
3129             if( WS_dup_se(serv, dup_flag) )
3130                 retval = se_buffer;
3131             else SetLastError(WSAENOBUFS);
3132         }
3133         else {
3134             MESSAGE("service on port %lu protocol %s not found; You might want to add "
3135                     "this to /etc/services\n", (unsigned long)ntohl(port),
3136                     proto ? debugstr_a(local_buffer) : "*");
3137             SetLastError(WSANO_DATA);
3138         }
3139         LeaveCriticalSection( &csWSgetXXXbyYYY );
3140     }
3141     else SetLastError(WSAENOBUFS);
3142     return retval;
3143 }
3144
3145 /***********************************************************************
3146  *              getservbyport           (WINSOCK.56)
3147  */
3148 SEGPTR WINAPI WINSOCK_getservbyport16(INT16 port, const char *proto)
3149 {
3150     TRACE("%d (i.e. port %d), %s\n", (int)port, (int)ntohl(port), debugstr_a(proto));
3151     if (!__ws_getservbyport(port, proto, WS_DUP_SEGPTR)) return 0;
3152     return se_buffer_seg;
3153 }
3154
3155 /***********************************************************************
3156  *              getservbyport           (WS2_32.56)
3157  */
3158 struct WS_servent* WINAPI WS_getservbyport(int port, const char *proto)
3159 {
3160     TRACE("%d (i.e. port %d), %s\n", (int)port, (int)ntohl(port), debugstr_a(proto));
3161     return __ws_getservbyport(port, proto, WS_DUP_LINEAR);
3162 }
3163
3164
3165 /***********************************************************************
3166  *              gethostname           (WS2_32.57)
3167  */
3168 int WINAPI WS_gethostname(char *name, int namelen)
3169 {
3170     TRACE("name %p, len %d\n", name, namelen);
3171
3172     if (gethostname(name, namelen) == 0)
3173     {
3174         TRACE("<- '%s'\n", name);
3175         return 0;
3176     }
3177     SetLastError((errno == EINVAL) ? WSAEFAULT : wsaErrno());
3178     TRACE("<- ERROR !\n");
3179     return SOCKET_ERROR;
3180 }
3181
3182 /***********************************************************************
3183  *              gethostname           (WINSOCK.57)
3184  */
3185 INT16 WINAPI WINSOCK_gethostname16(char *name, INT16 namelen)
3186 {
3187     return (INT16)WS_gethostname(name, namelen);
3188 }
3189
3190
3191 /* ------------------------------------- Windows sockets extensions -- *
3192  *                                                                     *
3193  * ------------------------------------------------------------------- */
3194
3195 /***********************************************************************
3196  *              WSAEnumNetworkEvents (WS2_32.36)
3197  */
3198 int WINAPI WSAEnumNetworkEvents(SOCKET s, WSAEVENT hEvent, LPWSANETWORKEVENTS lpEvent)
3199 {
3200     int ret;
3201
3202     TRACE("%08x, hEvent %08x, lpEvent %08x\n", s, hEvent, (unsigned)lpEvent );
3203
3204     SERVER_START_REQ( get_socket_event )
3205     {
3206         req->handle  = s;
3207         req->service = TRUE;
3208         req->c_event = hEvent;
3209         wine_server_set_reply( req, lpEvent->iErrorCode, sizeof(lpEvent->iErrorCode) );
3210         if (!(ret = wine_server_call(req))) lpEvent->lNetworkEvents = reply->pmask & reply->mask;
3211     }
3212     SERVER_END_REQ;
3213     if (!ret) return 0;
3214     SetLastError(WSAEINVAL);
3215     return SOCKET_ERROR;
3216 }
3217
3218 /***********************************************************************
3219  *              WSAEventSelect (WS2_32.39)
3220  */
3221 int WINAPI WSAEventSelect(SOCKET s, WSAEVENT hEvent, LONG lEvent)
3222 {
3223     int ret;
3224
3225     TRACE("%08x, hEvent %08x, event %08x\n", s, hEvent, (unsigned)lEvent );
3226
3227     SERVER_START_REQ( set_socket_event )
3228     {
3229         req->handle = s;
3230         req->mask   = lEvent;
3231         req->event  = hEvent;
3232         req->window = 0;
3233         req->msg    = 0;
3234         ret = wine_server_call( req );
3235     }
3236     SERVER_END_REQ;
3237     if (!ret) return 0;
3238     SetLastError(WSAEINVAL);
3239     return SOCKET_ERROR;
3240 }
3241
3242 /**********************************************************************
3243  *      WSAGetOverlappedResult (WS2_32.40)
3244  */
3245 BOOL WINAPI WSAGetOverlappedResult ( SOCKET s, LPWSAOVERLAPPED lpOverlapped,
3246                                      LPDWORD lpcbTransfer, BOOL fWait,
3247                                      LPDWORD lpdwFlags )
3248 {
3249     DWORD r;
3250
3251     TRACE ( "socket %d ovl %p trans %p, wait %d flags %p\n",
3252             s, lpOverlapped, lpcbTransfer, fWait, lpdwFlags );
3253
3254     if ( !(lpOverlapped && lpOverlapped->hEvent) )
3255     {
3256         ERR ( "Invalid pointer\n" );
3257         WSASetLastError (WSA_INVALID_PARAMETER);
3258         return FALSE;
3259     }
3260
3261     do {
3262         r = WaitForSingleObjectEx (lpOverlapped->hEvent, fWait ? INFINITE : 0, TRUE);
3263     } while (r == STATUS_USER_APC);
3264
3265     if ( lpcbTransfer )
3266         *lpcbTransfer = lpOverlapped->InternalHigh;
3267
3268     if ( lpdwFlags )
3269         *lpdwFlags = lpOverlapped->Offset;
3270
3271     if ( r == WAIT_OBJECT_0 )
3272         return TRUE;
3273
3274     WSASetLastError ( lpOverlapped->Internal == STATUS_PENDING ?
3275                       WSA_IO_INCOMPLETE : NtStatusToWSAError ( lpOverlapped->Internal ) );
3276     return FALSE;
3277 }
3278
3279
3280 /***********************************************************************
3281  *      WSAAsyncSelect                  (WS2_32.101)
3282  */
3283 INT WINAPI WSAAsyncSelect(SOCKET s, HWND hWnd, UINT uMsg, LONG lEvent)
3284 {
3285     int ret;
3286
3287     TRACE("%x, hWnd %x, uMsg %08x, event %08lx\n", s, hWnd, uMsg, lEvent );
3288
3289     SERVER_START_REQ( set_socket_event )
3290     {
3291         req->handle = s;
3292         req->mask   = lEvent;
3293         req->event  = 0;
3294         req->window = hWnd;
3295         req->msg    = uMsg;
3296         ret = wine_server_call( req );
3297     }
3298     SERVER_END_REQ;
3299     if (!ret) return 0;
3300     SetLastError(WSAEINVAL);
3301     return SOCKET_ERROR;
3302 }
3303
3304 /***********************************************************************
3305  *      WSAAsyncSelect          (WINSOCK.101)
3306  */
3307 INT16 WINAPI WSAAsyncSelect16(SOCKET16 s, HWND16 hWnd, UINT16 wMsg, LONG lEvent)
3308 {
3309     return (INT16)WSAAsyncSelect( s, hWnd, wMsg, lEvent );
3310 }
3311
3312 /***********************************************************************
3313  *              WSARecvEx                       (WINSOCK.1107)
3314  *
3315  * See description for WSARecvEx()
3316  */
3317 INT16     WINAPI WSARecvEx16(SOCKET16 s, char *buf, INT16 len, INT16 *flags)
3318 {
3319   FIXME("(WSARecvEx16) partial packet return value not set \n");
3320
3321   return WINSOCK_recv16(s, buf, len, *flags);
3322 }
3323
3324
3325 /***********************************************************************
3326  *      WSACreateEvent          (WS2_32.31)
3327  *
3328  */
3329 WSAEVENT WINAPI WSACreateEvent(void)
3330 {
3331     /* Create a manual-reset event, with initial state: unsignealed */
3332     TRACE("\n");
3333
3334     return CreateEventA(NULL, TRUE, FALSE, NULL);
3335 }
3336
3337 /***********************************************************************
3338  *      WSACloseEvent          (WS2_32.29)
3339  *
3340  */
3341 BOOL WINAPI WSACloseEvent(WSAEVENT event)
3342 {
3343     TRACE ("event=0x%x\n", event);
3344
3345     return CloseHandle(event);
3346 }
3347
3348 /***********************************************************************
3349  *      WSASocketA          (WS2_32.78)
3350  *
3351  */
3352 SOCKET WINAPI WSASocketA(int af, int type, int protocol,
3353                          LPWSAPROTOCOL_INFOA lpProtocolInfo,
3354                          GROUP g, DWORD dwFlags)
3355 {
3356     SOCKET ret;
3357
3358    /*
3359       FIXME: The "advanced" parameters of WSASocketA (lpProtocolInfo,
3360       g, dwFlags except WSA_FLAG_OVERLAPPED) are ignored.
3361    */
3362
3363    TRACE("af=%d type=%d protocol=%d protocol_info=%p group=%d flags=0x%lx\n",
3364          af, type, protocol, lpProtocolInfo, g, dwFlags );
3365
3366     /* hack for WSADuplicateSocket */
3367     if (lpProtocolInfo && lpProtocolInfo->dwServiceFlags4 == 0xff00ff00) {
3368       ret = lpProtocolInfo->dwCatalogEntryId;
3369       TRACE("\tgot duplicate %04x\n", ret);
3370       return ret;
3371     }
3372
3373     /* check the socket family */
3374     switch(af)
3375     {
3376 #ifdef HAVE_IPX
3377         case WS_AF_IPX: af = AF_IPX;
3378 #endif
3379         case AF_INET:
3380         case AF_UNSPEC:
3381             break;
3382         default:
3383             SetLastError(WSAEAFNOSUPPORT);
3384             return INVALID_SOCKET;
3385     }
3386
3387     /* check the socket type */
3388     switch(type)
3389     {
3390         case WS_SOCK_STREAM:
3391             type=SOCK_STREAM;
3392             break;
3393         case WS_SOCK_DGRAM:
3394             type=SOCK_DGRAM;
3395             break;
3396         case WS_SOCK_RAW:
3397             type=SOCK_RAW;
3398             break;
3399         default:
3400             SetLastError(WSAESOCKTNOSUPPORT);
3401             return INVALID_SOCKET;
3402     }
3403
3404     /* check the protocol type */
3405     if ( protocol < 0 )  /* don't support negative values */
3406     {
3407         SetLastError(WSAEPROTONOSUPPORT);
3408         return INVALID_SOCKET;
3409     }
3410
3411     if ( af == AF_UNSPEC)  /* did they not specify the address family? */
3412         switch(protocol)
3413         {
3414           case IPPROTO_TCP:
3415              if (type == SOCK_STREAM) { af = AF_INET; break; }
3416           case IPPROTO_UDP:
3417              if (type == SOCK_DGRAM)  { af = AF_INET; break; }
3418           default: SetLastError(WSAEPROTOTYPE); return INVALID_SOCKET;
3419         }
3420
3421     SERVER_START_REQ( create_socket )
3422     {
3423         req->family   = af;
3424         req->type     = type;
3425         req->protocol = protocol;
3426         req->access   = GENERIC_READ|GENERIC_WRITE|SYNCHRONIZE;
3427         req->flags    = dwFlags;
3428         req->inherit  = TRUE;
3429         set_error( wine_server_call( req ) );
3430         ret = (SOCKET)reply->handle;
3431     }
3432     SERVER_END_REQ;
3433     if (ret)
3434     {
3435         TRACE("\tcreated %04x\n", ret );
3436         return ret;
3437     }
3438
3439     if (GetLastError() == WSAEACCES) /* raw socket denied */
3440     {
3441         if (type == SOCK_RAW)
3442             MESSAGE("WARNING: Trying to create a socket of type SOCK_RAW, will fail unless running as root\n");
3443         else
3444             MESSAGE("WS_SOCKET: not enough privileges to create socket, try running as root\n");
3445         SetLastError(WSAESOCKTNOSUPPORT);
3446     }
3447
3448     WARN("\t\tfailed!\n");
3449     return INVALID_SOCKET;
3450 }
3451
3452
3453 /***********************************************************************
3454  *      __WSAFDIsSet                    (WINSOCK.151)
3455  */
3456 INT16 WINAPI __WSAFDIsSet16(SOCKET16 s, ws_fd_set16 *set)
3457 {
3458   int i = set->fd_count;
3459
3460   TRACE("(%d,%8lx(%i))\n", s,(unsigned long)set, i);
3461
3462   while (i--)
3463       if (set->fd_array[i] == s) return 1;
3464   return 0;
3465 }
3466
3467 /***********************************************************************
3468  *      __WSAFDIsSet                    (WS2_32.151)
3469  */
3470 int WINAPI __WSAFDIsSet(SOCKET s, WS_fd_set *set)
3471 {
3472   int i = set->fd_count;
3473
3474   TRACE("(%d,%8lx(%i))\n", s,(unsigned long)set, i);
3475
3476   while (i--)
3477       if (set->fd_array[i] == s) return 1;
3478   return 0;
3479 }
3480
3481 /***********************************************************************
3482  *      WSAIsBlocking                   (WINSOCK.114)
3483  *      WSAIsBlocking                   (WS2_32.114)
3484  */
3485 BOOL WINAPI WSAIsBlocking(void)
3486 {
3487   /* By default WinSock should set all its sockets to non-blocking mode
3488    * and poll in PeekMessage loop when processing "blocking" ones. This
3489    * function is supposed to tell if the program is in this loop. Our
3490    * blocking calls are truly blocking so we always return FALSE.
3491    *
3492    * Note: It is allowed to call this function without prior WSAStartup().
3493    */
3494
3495   TRACE("\n");
3496   return FALSE;
3497 }
3498
3499 /***********************************************************************
3500  *      WSACancelBlockingCall           (WINSOCK.113)
3501  *      WSACancelBlockingCall           (WS2_32.113)
3502  */
3503 INT WINAPI WSACancelBlockingCall(void)
3504 {
3505     TRACE("\n");
3506     return 0;
3507 }
3508
3509
3510 /***********************************************************************
3511  *      WSASetBlockingHook              (WINSOCK.109)
3512  */
3513 FARPROC16 WINAPI WSASetBlockingHook16(FARPROC16 lpBlockFunc)
3514 {
3515   FARPROC16 prev = (FARPROC16)blocking_hook;
3516   blocking_hook = (FARPROC)lpBlockFunc;
3517   TRACE("hook %p\n", lpBlockFunc);
3518   return prev;
3519 }
3520
3521
3522 /***********************************************************************
3523  *      WSASetBlockingHook (WS2_32.109)
3524  */
3525 FARPROC WINAPI WSASetBlockingHook(FARPROC lpBlockFunc)
3526 {
3527   FARPROC prev = blocking_hook;
3528   blocking_hook = lpBlockFunc;
3529   TRACE("hook %p\n", lpBlockFunc);
3530   return prev;
3531 }
3532
3533
3534 /***********************************************************************
3535  *      WSAUnhookBlockingHook   (WINSOCK.110)
3536  */
3537 INT16 WINAPI WSAUnhookBlockingHook16(void)
3538 {
3539     blocking_hook = NULL;
3540     return 0;
3541 }
3542
3543
3544 /***********************************************************************
3545  *      WSAUnhookBlockingHook (WS2_32.110)
3546  */
3547 INT WINAPI WSAUnhookBlockingHook(void)
3548 {
3549     blocking_hook = NULL;
3550     return 0;
3551 }
3552
3553
3554 /* ----------------------------------- end of API stuff */
3555
3556 /* ----------------------------------- helper functions -
3557  *
3558  * TODO: Merge WS_dup_..() stuff into one function that
3559  * would operate with a generic structure containing internal
3560  * pointers (via a template of some kind).
3561  */
3562
3563 static int list_size(char** l, int item_size)
3564 {
3565   int i,j = 0;
3566   if(l)
3567   { for(i=0;l[i];i++)
3568         j += (item_size) ? item_size : strlen(l[i]) + 1;
3569     j += (i + 1) * sizeof(char*); }
3570   return j;
3571 }
3572
3573 static int list_dup(char** l_src, char* ref, char* base, int item_size)
3574 {
3575    /* base is either either equal to ref or 0 or SEGPTR */
3576
3577    char*                p = ref;
3578    char**               l_to = (char**)ref;
3579    int                  i,j,k;
3580
3581    for(j=0;l_src[j];j++) ;
3582    p += (j + 1) * sizeof(char*);
3583    for(i=0;i<j;i++)
3584    { l_to[i] = base + (p - ref);
3585      k = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
3586      memcpy(p, l_src[i], k); p += k; }
3587    l_to[i] = NULL;
3588    return (p - ref);
3589 }
3590
3591 /* ----- hostent */
3592
3593 static int hostent_size(struct hostent* p_he)
3594 {
3595   int size = 0;
3596   if( p_he )
3597   { size  = sizeof(struct hostent);
3598     size += strlen(p_he->h_name) + 1;
3599     size += list_size(p_he->h_aliases, 0);
3600     size += list_size(p_he->h_addr_list, p_he->h_length ); }
3601   return size;
3602 }
3603
3604 /* duplicate hostent entry
3605  * and handle all Win16/Win32 dependent things (struct size, ...) *correctly*.
3606  * Dito for protoent and servent.
3607  */
3608 static int WS_dup_he(struct hostent* p_he, int flag)
3609 {
3610     /* Convert hostent structure into ws_hostent so that the data fits
3611      * into local_buffer. Internal pointers can be linear, SEGPTR, or
3612      * relative to local_buffer depending on "flag" value. Returns size
3613      * of the data copied.
3614      */
3615
3616     int size = hostent_size(p_he);
3617     if( size )
3618     {
3619         char *p_name,*p_aliases,*p_addr,*p_base,*p;
3620         char *p_to;
3621         struct ws_hostent16 *p_to16;
3622         struct WS_hostent *p_to32;
3623
3624         check_buffer_he(size);
3625         p_to = he_buffer;
3626         p_to16 = he_buffer;
3627         p_to32 = he_buffer;
3628
3629         p = p_to;
3630         p_base = (flag & WS_DUP_SEGPTR) ? (char*)he_buffer_seg : he_buffer;
3631         p += (flag & WS_DUP_SEGPTR) ?
3632             sizeof(struct ws_hostent16) : sizeof(struct WS_hostent);
3633         p_name = p;
3634         strcpy(p, p_he->h_name); p += strlen(p) + 1;
3635         p_aliases = p;
3636         p += list_dup(p_he->h_aliases, p, p_base + (p - p_to), 0);
3637         p_addr = p;
3638         list_dup(p_he->h_addr_list, p, p_base + (p - p_to), p_he->h_length);
3639
3640         if (flag & WS_DUP_SEGPTR) /* Win16 */
3641         {
3642             p_to16->h_addrtype = (INT16)p_he->h_addrtype;
3643             p_to16->h_length = (INT16)p_he->h_length;
3644             p_to16->h_name = (SEGPTR)(p_base + (p_name - p_to));
3645             p_to16->h_aliases = (SEGPTR)(p_base + (p_aliases - p_to));
3646             p_to16->h_addr_list = (SEGPTR)(p_base + (p_addr - p_to));
3647             size += (sizeof(struct ws_hostent16) - sizeof(struct hostent));
3648         }
3649         else /* Win32 */
3650         {
3651             p_to32->h_addrtype = p_he->h_addrtype;
3652             p_to32->h_length = p_he->h_length;
3653             p_to32->h_name = (p_base + (p_name - p_to));
3654             p_to32->h_aliases = (char **)(p_base + (p_aliases - p_to));
3655             p_to32->h_addr_list = (char **)(p_base + (p_addr - p_to));
3656             size += (sizeof(struct WS_hostent) - sizeof(struct hostent));
3657         }
3658     }
3659     return size;
3660 }
3661
3662 /* ----- protoent */
3663
3664 static int protoent_size(struct protoent* p_pe)
3665 {
3666   int size = 0;
3667   if( p_pe )
3668   { size  = sizeof(struct protoent);
3669     size += strlen(p_pe->p_name) + 1;
3670     size += list_size(p_pe->p_aliases, 0); }
3671   return size;
3672 }
3673
3674 static int WS_dup_pe(struct protoent* p_pe, int flag)
3675 {
3676     int size = protoent_size(p_pe);
3677     if( size )
3678     {
3679         char *p_to;
3680         struct ws_protoent16 *p_to16;
3681         struct WS_protoent *p_to32;
3682         char *p_name,*p_aliases,*p_base,*p;
3683
3684         check_buffer_pe(size);
3685         p_to = pe_buffer;
3686         p_to16 = pe_buffer;
3687         p_to32 = pe_buffer;
3688         p = p_to;
3689         p_base = (flag & WS_DUP_SEGPTR) ? (char*)pe_buffer_seg : pe_buffer;
3690         p += (flag & WS_DUP_SEGPTR) ?
3691             sizeof(struct ws_protoent16) : sizeof(struct WS_protoent);
3692         p_name = p;
3693         strcpy(p, p_pe->p_name); p += strlen(p) + 1;
3694         p_aliases = p;
3695         list_dup(p_pe->p_aliases, p, p_base + (p - p_to), 0);
3696
3697         if (flag & WS_DUP_SEGPTR) /* Win16 */
3698         {
3699             p_to16->p_proto = (INT16)p_pe->p_proto;
3700             p_to16->p_name = (SEGPTR)(p_base) + (p_name - p_to);
3701             p_to16->p_aliases = (SEGPTR)((p_base) + (p_aliases - p_to));
3702             size += (sizeof(struct ws_protoent16) - sizeof(struct protoent));
3703         }
3704         else /* Win32 */
3705         {
3706             p_to32->p_proto = p_pe->p_proto;
3707             p_to32->p_name = (p_base) + (p_name - p_to);
3708             p_to32->p_aliases = (char **)((p_base) + (p_aliases - p_to));
3709             size += (sizeof(struct WS_protoent) - sizeof(struct protoent));
3710         }
3711     }
3712     return size;
3713 }
3714
3715 /* ----- servent */
3716
3717 static int servent_size(struct servent* p_se)
3718 {
3719   int size = 0;
3720   if( p_se )
3721   { size += sizeof(struct servent);
3722     size += strlen(p_se->s_proto) + strlen(p_se->s_name) + 2;
3723     size += list_size(p_se->s_aliases, 0); }
3724   return size;
3725 }
3726
3727 static int WS_dup_se(struct servent* p_se, int flag)
3728 {
3729     int size = servent_size(p_se);
3730     if( size )
3731     {
3732         char *p_name,*p_aliases,*p_proto,*p_base,*p;
3733         char *p_to;
3734         struct ws_servent16 *p_to16;
3735         struct WS_servent *p_to32;
3736
3737         check_buffer_se(size);
3738         p_to = se_buffer;
3739         p_to16 = se_buffer;
3740         p_to32 = se_buffer;
3741         p = p_to;
3742         p_base = (flag & WS_DUP_SEGPTR) ? (char*)se_buffer_seg : se_buffer;
3743         p += (flag & WS_DUP_SEGPTR) ?
3744             sizeof(struct ws_servent16) : sizeof(struct WS_servent);
3745         p_name = p;
3746         strcpy(p, p_se->s_name); p += strlen(p) + 1;
3747         p_proto = p;
3748         strcpy(p, p_se->s_proto); p += strlen(p) + 1;
3749         p_aliases = p;
3750         list_dup(p_se->s_aliases, p, p_base + (p - p_to), 0);
3751
3752         if (flag & WS_DUP_SEGPTR) /* Win16 */
3753         {
3754             p_to16->s_port = (INT16)p_se->s_port;
3755             p_to16->s_name = (SEGPTR)(p_base + (p_name - p_to));
3756             p_to16->s_proto = (SEGPTR)(p_base + (p_proto - p_to));
3757             p_to16->s_aliases = (SEGPTR)(p_base + (p_aliases - p_to));
3758             size += (sizeof(struct ws_servent16) - sizeof(struct servent));
3759         }
3760         else /* Win32 */
3761         {
3762             p_to32->s_port = p_se->s_port;
3763             p_to32->s_name = (p_base + (p_name - p_to));
3764             p_to32->s_proto = (p_base + (p_proto - p_to));
3765             p_to32->s_aliases = (char **)(p_base + (p_aliases - p_to));
3766             size += (sizeof(struct WS_servent) - sizeof(struct servent));
3767         }
3768     }
3769     return size;
3770 }
3771
3772 /* ----------------------------------- error handling */
3773
3774 UINT16 wsaErrno(void)
3775 {
3776     int loc_errno = errno;
3777     WARN("errno %d, (%s).\n", loc_errno, strerror(loc_errno));
3778
3779     switch(loc_errno)
3780     {
3781         case EINTR:             return WSAEINTR;
3782         case EBADF:             return WSAEBADF;
3783         case EPERM:
3784         case EACCES:            return WSAEACCES;
3785         case EFAULT:            return WSAEFAULT;
3786         case EINVAL:            return WSAEINVAL;
3787         case EMFILE:            return WSAEMFILE;
3788         case EWOULDBLOCK:       return WSAEWOULDBLOCK;
3789         case EINPROGRESS:       return WSAEINPROGRESS;
3790         case EALREADY:          return WSAEALREADY;
3791         case ENOTSOCK:          return WSAENOTSOCK;
3792         case EDESTADDRREQ:      return WSAEDESTADDRREQ;
3793         case EMSGSIZE:          return WSAEMSGSIZE;
3794         case EPROTOTYPE:        return WSAEPROTOTYPE;
3795         case ENOPROTOOPT:       return WSAENOPROTOOPT;
3796         case EPROTONOSUPPORT:   return WSAEPROTONOSUPPORT;
3797         case ESOCKTNOSUPPORT:   return WSAESOCKTNOSUPPORT;
3798         case EOPNOTSUPP:        return WSAEOPNOTSUPP;
3799         case EPFNOSUPPORT:      return WSAEPFNOSUPPORT;
3800         case EAFNOSUPPORT:      return WSAEAFNOSUPPORT;
3801         case EADDRINUSE:        return WSAEADDRINUSE;
3802         case EADDRNOTAVAIL:     return WSAEADDRNOTAVAIL;
3803         case ENETDOWN:          return WSAENETDOWN;
3804         case ENETUNREACH:       return WSAENETUNREACH;
3805         case ENETRESET:         return WSAENETRESET;
3806         case ECONNABORTED:      return WSAECONNABORTED;
3807         case EPIPE:
3808         case ECONNRESET:        return WSAECONNRESET;
3809         case ENOBUFS:           return WSAENOBUFS;
3810         case EISCONN:           return WSAEISCONN;
3811         case ENOTCONN:          return WSAENOTCONN;
3812         case ESHUTDOWN:         return WSAESHUTDOWN;
3813         case ETOOMANYREFS:      return WSAETOOMANYREFS;
3814         case ETIMEDOUT:         return WSAETIMEDOUT;
3815         case ECONNREFUSED:      return WSAECONNREFUSED;
3816         case ELOOP:             return WSAELOOP;
3817         case ENAMETOOLONG:      return WSAENAMETOOLONG;
3818         case EHOSTDOWN:         return WSAEHOSTDOWN;
3819         case EHOSTUNREACH:      return WSAEHOSTUNREACH;
3820         case ENOTEMPTY:         return WSAENOTEMPTY;
3821 #ifdef EPROCLIM
3822         case EPROCLIM:          return WSAEPROCLIM;
3823 #endif
3824 #ifdef EUSERS
3825         case EUSERS:            return WSAEUSERS;
3826 #endif
3827 #ifdef EDQUOT
3828         case EDQUOT:            return WSAEDQUOT;
3829 #endif
3830 #ifdef ESTALE
3831         case ESTALE:            return WSAESTALE;
3832 #endif
3833 #ifdef EREMOTE
3834         case EREMOTE:           return WSAEREMOTE;
3835 #endif
3836
3837        /* just in case we ever get here and there are no problems */
3838         case 0:                 return 0;
3839         default:
3840                 WARN("Unknown errno %d!\n", loc_errno);
3841                 return WSAEOPNOTSUPP;
3842     }
3843 }
3844
3845 UINT16 wsaHerrno(int loc_errno)
3846 {
3847
3848     WARN("h_errno %d.\n", loc_errno);
3849
3850     switch(loc_errno)
3851     {
3852         case HOST_NOT_FOUND:    return WSAHOST_NOT_FOUND;
3853         case TRY_AGAIN:         return WSATRY_AGAIN;
3854         case NO_RECOVERY:       return WSANO_RECOVERY;
3855         case NO_DATA:           return WSANO_DATA;
3856         case ENOBUFS:           return WSAENOBUFS;
3857
3858         case 0:                 return 0;
3859         default:
3860                 WARN("Unknown h_errno %d!\n", loc_errno);
3861                 return WSAEOPNOTSUPP;
3862     }
3863 }
3864
3865
3866 /***********************************************************************
3867  *              WSARecv                 (WS2_32.67)
3868  */
3869 int WINAPI WSARecv (SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3870                     LPDWORD NumberOfBytesReceived, LPDWORD lpFlags,
3871                     LPWSAOVERLAPPED lpOverlapped,
3872                     LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
3873 {
3874     return WSARecvFrom (s, lpBuffers, dwBufferCount, NumberOfBytesReceived, lpFlags,
3875                         NULL, NULL, lpOverlapped, lpCompletionRoutine);
3876 }
3877
3878 /***********************************************************************
3879  *              WSARecvFrom             (WS2_32.69)
3880  */
3881 INT WINAPI WSARecvFrom( SOCKET s, LPWSABUF lpBuffers, DWORD dwBufferCount,
3882                         LPDWORD lpNumberOfBytesRecvd, LPDWORD lpFlags, struct WS_sockaddr *lpFrom,
3883                         LPINT lpFromlen, LPWSAOVERLAPPED lpOverlapped,
3884                         LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine )
3885
3886 {
3887     int i, n, fd, err = WSAENOTSOCK, flags, ret;
3888     struct iovec* iovec;
3889     struct ws2_async *wsa;
3890     enum fd_type type;
3891
3892     TRACE("socket %04x, wsabuf %p, nbufs %ld, flags %ld, from %p, fromlen %ld, ovl %p, func %p\n",
3893           s, lpBuffers, dwBufferCount, *lpFlags, lpFrom,
3894           (lpFromlen ? *lpFromlen : -1L),
3895           lpOverlapped, lpCompletionRoutine);
3896
3897     fd = _get_sock_fd_type( s, GENERIC_READ, &type, &flags );
3898     TRACE ( "fd=%d, type=%d, flags=%x\n", fd, type, flags );
3899
3900     if (fd == -1)
3901     {
3902         err = WSAGetLastError ();
3903         goto error;
3904     }
3905
3906     iovec = HeapAlloc ( GetProcessHeap(), 0, dwBufferCount * sizeof (struct iovec) );
3907     if ( !iovec )
3908     {
3909         err = WSAEFAULT;
3910         goto err_close;
3911     }
3912
3913     for (i = 0; i < dwBufferCount; i++)
3914     {
3915         iovec[i].iov_base = lpBuffers[i].buf;
3916         iovec[i].iov_len  = lpBuffers[i].len;
3917     }
3918
3919     if ( (lpOverlapped || lpCompletionRoutine) && flags & FD_FLAG_OVERLAPPED )
3920     {
3921         wsa = WS2_make_async ( s, fd, ASYNC_TYPE_READ, iovec, dwBufferCount,
3922                                lpFlags, lpFrom, lpFromlen,
3923                                lpOverlapped, lpCompletionRoutine );
3924
3925         if ( !wsa )
3926         {
3927             err = WSAEFAULT;
3928             goto err_free;
3929         }
3930
3931         if ( ( ret = register_new_async ( &wsa->async )) )
3932         {
3933             err = NtStatusToWSAError ( ret );
3934
3935             if ( !lpOverlapped )
3936                 HeapFree ( GetProcessHeap(), 0, wsa->overlapped );
3937             HeapFree ( GetProcessHeap(), 0, wsa );
3938             goto err_free;
3939         }
3940
3941         /* Try immediate completion */
3942         if ( lpOverlapped && !NtResetEvent( lpOverlapped->hEvent, NULL ) )
3943         {
3944             if  ( WSAGetOverlappedResult ( (HANDLE) s, lpOverlapped,
3945                                            lpNumberOfBytesRecvd, FALSE, lpFlags) )
3946                 return 0;
3947
3948             if ( (err = WSAGetLastError ()) != WSA_IO_INCOMPLETE )
3949                 goto error;
3950         }
3951
3952         WSASetLastError ( WSA_IO_PENDING );
3953         return SOCKET_ERROR;
3954     }
3955
3956     if ( _is_blocking(s) )
3957     {
3958         /* block here */
3959         /* FIXME: OOB and exceptfds? */
3960         do_block(fd, 1);
3961     }
3962
3963     n = WS2_recv ( fd, iovec, dwBufferCount, lpFrom, lpFromlen, lpFlags );
3964     if ( n == -1 )
3965     {
3966         err = wsaErrno();
3967         goto err_free;
3968     }
3969
3970     TRACE(" -> %i bytes\n", n);
3971     *lpNumberOfBytesRecvd = n;
3972
3973     HeapFree (GetProcessHeap(), 0, iovec);
3974     close(fd);
3975     _enable_event(s, FD_READ, 0, 0);
3976
3977     return 0;
3978
3979 err_free:
3980     HeapFree (GetProcessHeap(), 0, iovec);
3981
3982 err_close:
3983     close (fd);
3984
3985 error:
3986     WARN(" -> ERROR %d\n", err);
3987     WSASetLastError ( err );
3988     return SOCKET_ERROR;
3989 }
3990
3991 /***********************************************************************
3992  *              WSCInstallProvider             (WS2_32.88)
3993  */
3994 INT WINAPI WSCInstallProvider( const LPGUID lpProviderId,
3995                                LPCWSTR lpszProviderDllPath,
3996                                const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
3997                                DWORD dwNumberOfEntries,
3998                                LPINT lpErrno )
3999 {
4000     FIXME("(%s, %s, %p, %ld, %p): stub !\n", debugstr_guid(lpProviderId),
4001           debugstr_w(lpszProviderDllPath), lpProtocolInfoList,
4002           dwNumberOfEntries, lpErrno);
4003     *lpErrno = 0;
4004     return 0;
4005 }
4006
4007
4008 /***********************************************************************
4009  *              WSCDeinstallProvider             (WS2_32.83)
4010  */
4011 INT WINAPI WSCDeinstallProvider(LPGUID lpProviderId, LPINT lpErrno)
4012 {
4013     FIXME("(%s, %p): stub !\n", debugstr_guid(lpProviderId), lpErrno);
4014     *lpErrno = 0;
4015     return 0;
4016 }
4017
4018
4019 /***********************************************************************
4020  *              WSAAccept                        (WS2_32.26)
4021  */
4022 SOCKET WINAPI WSAAccept( SOCKET s, struct WS_sockaddr *addr, LPINT addrlen,
4023                LPCONDITIONPROC lpfnCondition, DWORD dwCallbackData)
4024 {
4025
4026        int ret = 0, size = 0;
4027        WSABUF CallerId, CallerData, CalleeId, CalleeData;
4028        /*        QOS SQOS, GQOS; */
4029        GROUP g;
4030        SOCKET cs;
4031        SOCKADDR src_addr, dst_addr;
4032
4033        TRACE("Socket  %u, sockaddr %p, addrlen %p, fnCondition %p, dwCallbackData %ld\n",
4034                s, addr, addrlen, lpfnCondition, dwCallbackData);
4035
4036
4037        size = sizeof(src_addr);
4038        cs = WS_accept(s, &src_addr, &size);
4039
4040        if (cs == SOCKET_ERROR) return SOCKET_ERROR;
4041
4042        CallerId.buf = (char *)&src_addr;
4043        CallerId.len = sizeof(src_addr);
4044
4045        CallerData.buf = NULL;
4046        CallerData.len = (ULONG)NULL;
4047
4048        WS_getsockname(cs, &dst_addr, &size);
4049
4050        CalleeId.buf = (char *)&dst_addr;
4051        CalleeId.len = sizeof(dst_addr);
4052
4053
4054        ret = (*lpfnCondition)(&CallerId, &CallerData, NULL, NULL,
4055                        &CalleeId, &CalleeData, &g, dwCallbackData);
4056
4057        switch (ret)
4058        {
4059                case CF_ACCEPT:
4060                        if (addr && addrlen)
4061                                addr = memcpy(addr, &src_addr, (*addrlen > size) ?  size : *addrlen );
4062                        return cs;
4063                case CF_DEFER:
4064                        SERVER_START_REQ ( set_socket_deferred )
4065                        {
4066                            req->handle = s;
4067                            req->deferred = cs;
4068                            if ( !wine_server_call_err ( req ) )
4069                            {
4070                                SetLastError ( WSATRY_AGAIN );
4071                                CloseHandle ( cs );
4072                            }
4073                        }
4074                        SERVER_END_REQ;
4075                        return SOCKET_ERROR;
4076                case CF_REJECT:
4077                        WS_closesocket(cs);
4078                        SetLastError(WSAECONNREFUSED);
4079                        return SOCKET_ERROR;
4080                default:
4081                        FIXME("Unknown return type from Condition function\n");
4082                        SetLastError(WSAENOTSOCK);
4083                        return SOCKET_ERROR;
4084                }
4085
4086        SetLastError(WSAENOTSOCK);
4087        return SOCKET_ERROR;
4088 }
4089
4090 /***********************************************************************
4091  *              WSAEnumProtocolsA                        (WS2_32.37)
4092  */
4093 int WINAPI WSAEnumProtocolsA(LPINT lpiProtocols, LPWSAPROTOCOL_INFOA lpProtocolBuffer, LPDWORD lpdwBufferLength)
4094 {
4095     FIXME("(%p,%p,%p): stub\n", lpiProtocols,lpProtocolBuffer, lpdwBufferLength);
4096     return 0;
4097 }
4098
4099 /***********************************************************************
4100  *              WSAEnumProtocolsW                        (WS2_32.38)
4101  */
4102 int WINAPI WSAEnumProtocolsW(LPINT lpiProtocols, LPWSAPROTOCOL_INFOW lpProtocolBuffer, LPDWORD lpdwBufferLength)
4103 {
4104     FIXME("(%p,%p,%p): stub\n", lpiProtocols,lpProtocolBuffer, lpdwBufferLength);
4105     return 0;
4106 }
4107
4108 /***********************************************************************
4109  *              WSADuplicateSocketA                      (WS2_32.32)
4110  */
4111 int WINAPI WSADuplicateSocketA( SOCKET s, DWORD dwProcessId, LPWSAPROTOCOL_INFOA lpProtocolInfo )
4112 {
4113    HANDLE hProcess;
4114
4115    TRACE("(%d,%lx,%p)\n", s, dwProcessId, lpProtocolInfo);
4116    memset(lpProtocolInfo, 0, sizeof(*lpProtocolInfo));
4117    /* FIXME: WS_getsockopt(s, WS_SOL_SOCKET, SO_PROTOCOL_INFO, lpProtocolInfo, sizeof(*lpProtocolInfo)); */
4118    /* I don't know what the real Windoze does next, this is a hack */
4119    /* ...we could duplicate and then use ConvertToGlobalHandle on the duplicate, then let
4120     * the target use the global duplicate, or we could copy a reference to us to the structure
4121     * and let the target duplicate it from us, but let's do it as simple as possible */
4122    hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, dwProcessId);
4123    DuplicateHandle(GetCurrentProcess(), s,
4124                    hProcess, (LPHANDLE)&lpProtocolInfo->dwCatalogEntryId,
4125                    0, FALSE, DUPLICATE_SAME_ACCESS);
4126    CloseHandle(hProcess);
4127    lpProtocolInfo->dwServiceFlags4 = 0xff00ff00; /* magic */
4128    return 0;
4129 }