1 /*
2  * Unit test suite for winsock functions
3  *
4  * Copyright 2002 Martin Wilck
5  * Copyright 2005 Thomas Kho
6  * Copyright 2008 Jeff Zaroyko
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  */
22 
23 #undef _WIN32_WINNT
24 #define _WIN32_WINNT 0x0600
25 
26 #include <ntstatus.h>
27 #define WIN32_NO_STATUS
28 #include <wine/test.h>
29 #include <winsock2.h>
30 #include <wine/winternl.h>
31 #include <ws2tcpip.h>
32 #include <wsipx.h>
33 #include <wsnwlink.h>
34 #include <mswsock.h>
35 #include <mstcpip.h>
36 #include <iphlpapi.h>
37 #include <stdio.h>
38 
39 
40 // ReactOS: Wine has this in mstcpip.h, but it doesn't belong there
41 #define WSA_CMSG_ALIGN(len)     (((len) + sizeof(SIZE_T) - 1) & ~(sizeof(SIZE_T) - 1))
42 
43 #define MAX_CLIENTS 4      /* Max number of clients */
44 #define FIRST_CHAR 'A'     /* First character in transferred pattern */
45 #define BIND_SLEEP 10      /* seconds to wait between attempts to bind() */
46 #define BIND_TRIES 6       /* Number of bind() attempts */
47 #define TEST_TIMEOUT 30    /* seconds to wait before killing child threads
48                               after server initialization, if something hangs */
49 
50 #define NUM_UDP_PEERS 3    /* Number of UDP sockets to create and test > 1 */
51 
52 #define NUM_THREADS 3      /* Number of threads to run getservbyname */
53 #define NUM_QUERIES 250    /* Number of getservbyname queries per thread */
54 
55 #define SERVERIP "127.0.0.1"   /* IP to bind to */
56 #define SERVERPORT 9374        /* Port number to bind to */
57 
58 #define wsa_ok(op, cond, msg) \
59    do { \
60         int tmp, err = 0; \
61         tmp = op; \
62         if ( !(cond tmp) ) err = WSAGetLastError(); \
63         ok ( cond tmp, msg, GetCurrentThreadId(), err); \
64    } while (0);
65 
66 #define make_keepalive(k, enable, time, interval) \
67    k.onoff = enable; \
68    k.keepalivetime = time; \
69    k.keepaliveinterval = interval;
70 
71 /* Function pointers */
72 static void  (WINAPI *pfreeaddrinfo)(struct addrinfo *);
73 static int   (WINAPI *pgetaddrinfo)(LPCSTR,LPCSTR,const struct addrinfo *,struct addrinfo **);
74 static void  (WINAPI *pFreeAddrInfoW)(PADDRINFOW);
75 static void  (WINAPI *pFreeAddrInfoExW)(ADDRINFOEXW *ai);
76 static int   (WINAPI *pGetAddrInfoW)(LPCWSTR,LPCWSTR,const ADDRINFOW *,PADDRINFOW *);
77 static int   (WINAPI *pGetAddrInfoExW)(const WCHAR *name, const WCHAR *servname, DWORD namespace,
78         GUID *namespace_id, const ADDRINFOEXW *hints, ADDRINFOEXW **result,
79         struct timeval *timeout, OVERLAPPED *overlapped,
80         LPLOOKUPSERVICE_COMPLETION_ROUTINE completion_routine, HANDLE *handle);
81 static int   (WINAPI *pGetAddrInfoExOverlappedResult)(OVERLAPPED *overlapped);
82 static PCSTR (WINAPI *pInetNtop)(INT,LPVOID,LPSTR,ULONG);
83 static PCWSTR(WINAPI *pInetNtopW)(INT,LPVOID,LPWSTR,ULONG);
84 static int   (WINAPI *pInetPtonA)(INT,LPCSTR,LPVOID);
85 static int   (WINAPI *pInetPtonW)(INT,LPWSTR,LPVOID);
86 static int   (WINAPI *pWSALookupServiceBeginW)(LPWSAQUERYSETW,DWORD,LPHANDLE);
87 static int   (WINAPI *pWSALookupServiceEnd)(HANDLE);
88 static int   (WINAPI *pWSALookupServiceNextW)(HANDLE,DWORD,LPDWORD,LPWSAQUERYSETW);
89 static int   (WINAPI *pWSAEnumNameSpaceProvidersA)(LPDWORD,LPWSANAMESPACE_INFOA);
90 static int   (WINAPI *pWSAEnumNameSpaceProvidersW)(LPDWORD,LPWSANAMESPACE_INFOW);
91 static int   (WINAPI *pWSAPoll)(WSAPOLLFD *,ULONG,INT);
92 
93 /* Function pointers from ntdll */
94 static NTSTATUS (WINAPI *pNtSetInformationFile)(HANDLE, PIO_STATUS_BLOCK, PVOID, ULONG, FILE_INFORMATION_CLASS);
95 static NTSTATUS (WINAPI *pNtQueryInformationFile)(HANDLE, PIO_STATUS_BLOCK, PVOID, ULONG, FILE_INFORMATION_CLASS);
96 
97 /* Function pointers from iphlpapi */
98 static DWORD (WINAPI *pGetAdaptersInfo)(PIP_ADAPTER_INFO,PULONG);
99 static DWORD (WINAPI *pGetIpForwardTable)(PMIB_IPFORWARDTABLE,PULONG,BOOL);
100 
101 /**************** Structs and typedefs ***************/
102 
103 typedef struct thread_info
104 {
105     HANDLE thread;
106     DWORD id;
107 } thread_info;
108 
109 /* Information in the server about open client connections */
110 typedef struct sock_info
111 {
112     SOCKET                 s;
113     struct sockaddr_in     addr;
114     struct sockaddr_in     peer;
115     char                  *buf;
116     int                    n_recvd;
117     int                    n_sent;
118 } sock_info;
119 
120 /* Test parameters for both server & client */
121 typedef struct test_params
122 {
123     int          sock_type;
124     int          sock_prot;
125     const char  *inet_addr;
126     short        inet_port;
127     int          chunk_size;
128     int          n_chunks;
129     int          n_clients;
130 } test_params;
131 
132 /* server-specific test parameters */
133 typedef struct server_params
134 {
135     test_params   *general;
136     DWORD          sock_flags;
137     int            buflen;
138 } server_params;
139 
140 /* client-specific test parameters */
141 typedef struct client_params
142 {
143     test_params   *general;
144     DWORD          sock_flags;
145     int            buflen;
146 } client_params;
147 
148 /* This type combines all information for setting up a test scenario */
149 typedef struct test_setup
150 {
151     test_params              general;
152     LPVOID                   srv;
153     server_params            srv_params;
154     LPVOID                   clt;
155     client_params            clt_params;
156 } test_setup;
157 
158 /* Thread local storage for server */
159 typedef struct server_memory
160 {
161     SOCKET                  s;
162     struct sockaddr_in      addr;
163     sock_info               sock[MAX_CLIENTS];
164 } server_memory;
165 
166 /* Thread local storage for client */
167 typedef struct client_memory
168 {
169     SOCKET s;
170     struct sockaddr_in      addr;
171     char                   *send_buf;
172     char                   *recv_buf;
173 } client_memory;
174 
175 /* SelectReadThread thread parameters */
176 typedef struct select_thread_params
177 {
178     SOCKET s;
179     BOOL ReadKilled;
180 } select_thread_params;
181 
182 /* Tests used in both getaddrinfo and GetAddrInfoW */
183 static const struct addr_hint_tests
184 {
185     int family, socktype, protocol;
186     DWORD error;
187 } hinttests[] = {
188     {AF_UNSPEC, SOCK_STREAM, IPPROTO_TCP, 0 },
189     {AF_UNSPEC, SOCK_STREAM, IPPROTO_UDP, 0 },
190     {AF_UNSPEC, SOCK_STREAM, IPPROTO_IPV6,0 },
191     {AF_UNSPEC, SOCK_DGRAM,  IPPROTO_TCP, 0 },
192     {AF_UNSPEC, SOCK_DGRAM,  IPPROTO_UDP, 0 },
193     {AF_UNSPEC, SOCK_DGRAM,  IPPROTO_IPV6,0 },
194     {AF_INET,   SOCK_STREAM, IPPROTO_TCP, 0 },
195     {AF_INET,   SOCK_STREAM, IPPROTO_UDP, 0 },
196     {AF_INET,   SOCK_STREAM, IPPROTO_IPV6,0 },
197     {AF_INET,   SOCK_DGRAM,  IPPROTO_TCP, 0 },
198     {AF_INET,   SOCK_DGRAM,  IPPROTO_UDP, 0 },
199     {AF_INET,   SOCK_DGRAM,  IPPROTO_IPV6,0 },
200     {AF_UNSPEC, 0,           IPPROTO_TCP, 0 },
201     {AF_UNSPEC, 0,           IPPROTO_UDP, 0 },
202     {AF_UNSPEC, 0,           IPPROTO_IPV6,0 },
203     {AF_UNSPEC, SOCK_STREAM, 0,           0 },
204     {AF_UNSPEC, SOCK_DGRAM,  0,           0 },
205     {AF_INET,   0,           IPPROTO_TCP, 0 },
206     {AF_INET,   0,           IPPROTO_UDP, 0 },
207     {AF_INET,   0,           IPPROTO_IPV6,0 },
208     {AF_INET,   SOCK_STREAM, 0,           0 },
209     {AF_INET,   SOCK_DGRAM,  0,           0 },
210     {AF_UNSPEC, 999,         IPPROTO_TCP, WSAESOCKTNOSUPPORT },
211     {AF_UNSPEC, 999,         IPPROTO_UDP, WSAESOCKTNOSUPPORT },
212     {AF_UNSPEC, 999,         IPPROTO_IPV6,WSAESOCKTNOSUPPORT },
213     {AF_INET,   999,         IPPROTO_TCP, WSAESOCKTNOSUPPORT },
214     {AF_INET,   999,         IPPROTO_UDP, WSAESOCKTNOSUPPORT },
215     {AF_INET,   999,         IPPROTO_IPV6,WSAESOCKTNOSUPPORT },
216     {AF_UNSPEC, SOCK_STREAM, 999,         0 },
217     {AF_UNSPEC, SOCK_STREAM, 999,         0 },
218     {AF_INET,   SOCK_DGRAM,  999,         0 },
219     {AF_INET,   SOCK_DGRAM,  999,         0 },
220 };
221 
222 /**************** Static variables ***************/
223 
224 static DWORD      tls;              /* Thread local storage index */
225 static HANDLE     thread[1+MAX_CLIENTS];
226 static DWORD      thread_id[1+MAX_CLIENTS];
227 static HANDLE     server_ready;
228 static HANDLE     client_ready[MAX_CLIENTS];
229 static int        client_id;
230 
231 /**************** General utility functions ***************/
232 
233 static SOCKET setup_server_socket(struct sockaddr_in *addr, int *len);
234 static SOCKET setup_connector_socket(struct sockaddr_in *addr, int len, BOOL nonblock);
235 
236 static int tcp_socketpair(SOCKET *src, SOCKET *dst)
237 {
238     SOCKET server = INVALID_SOCKET;
239     struct sockaddr_in addr;
240     int len;
241     int ret;
242 
243     *src = INVALID_SOCKET;
244     *dst = INVALID_SOCKET;
245 
246     *src = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
247     if (*src == INVALID_SOCKET)
248         goto end;
249 
250     server = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
251     if (server == INVALID_SOCKET)
252         goto end;
253 
254     memset(&addr, 0, sizeof(addr));
255     addr.sin_family = AF_INET;
256     addr.sin_addr.s_addr = inet_addr("127.0.0.1");
257     ret = bind(server, (struct sockaddr*)&addr, sizeof(addr));
258     if (ret != 0)
259         goto end;
260 
261     len = sizeof(addr);
262     ret = getsockname(server, (struct sockaddr*)&addr, &len);
263     if (ret != 0)
264         goto end;
265 
266     ret = listen(server, 1);
267     if (ret != 0)
268         goto end;
269 
270     ret = connect(*src, (struct sockaddr*)&addr, sizeof(addr));
271     if (ret != 0)
272         goto end;
273 
274     len = sizeof(addr);
275     *dst = accept(server, (struct sockaddr*)&addr, &len);
276 
277 end:
278     if (server != INVALID_SOCKET)
279         closesocket(server);
280     if (*src != INVALID_SOCKET && *dst != INVALID_SOCKET)
281         return 0;
282     closesocket(*src);
283     closesocket(*dst);
284     return -1;
285 }
286 
287 static void set_so_opentype ( BOOL overlapped )
288 {
289     int optval = !overlapped, newval, len = sizeof (int);
290 
291     ok ( setsockopt ( INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE,
292                       (LPVOID) &optval, sizeof (optval) ) == 0,
293          "setting SO_OPENTYPE failed\n" );
294     ok ( getsockopt ( INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE,
295                       (LPVOID) &newval, &len ) == 0,
296          "getting SO_OPENTYPE failed\n" );
297     ok ( optval == newval, "failed to set SO_OPENTYPE\n" );
298 }
299 
300 static int set_blocking ( SOCKET s, BOOL blocking )
301 {
302     u_long val = !blocking;
303     return ioctlsocket ( s, FIONBIO, &val );
304 }
305 
306 static void fill_buffer ( char *buf, int chunk_size, int n_chunks )
307 {
308     char c, *p;
309     for ( c = FIRST_CHAR, p = buf; c < FIRST_CHAR + n_chunks; c++, p += chunk_size )
310         memset ( p, c, chunk_size );
311 }
312 
313 static int test_buffer ( char *buf, int chunk_size, int n_chunks )
314 {
315     char c, *p;
316     int i;
317     for ( c = FIRST_CHAR, p = buf; c < FIRST_CHAR + n_chunks; c++, p += chunk_size )
318     {
319         for ( i = 0; i < chunk_size; i++ )
320             if ( p[i] != c ) return i;
321     }
322     return -1;
323 }
324 
325 /*
326  * This routine is called when a client / server does not expect any more data,
327  * but needs to acknowledge the closing of the connection (by reading 0 bytes).
328  */
329 static void read_zero_bytes ( SOCKET s )
330 {
331     char buf[256];
332     int tmp, n = 0;
333     while ( ( tmp = recv ( s, buf, 256, 0 ) ) > 0 )
334         n += tmp;
335     ok ( n <= 0, "garbage data received: %d bytes\n", n );
336 }
337 
338 static int do_synchronous_send ( SOCKET s, char *buf, int buflen, int flags, int sendlen )
339 {
340     char* last = buf + buflen, *p;
341     int n = 1;
342     for ( p = buf; n > 0 && p < last; )
343     {
344         n = send ( s, p, min ( sendlen, last - p ), flags );
345         if (n > 0) p += n;
346     }
347     wsa_ok ( n, 0 <=, "do_synchronous_send (%x): error %d\n" );
348     return p - buf;
349 }
350 
351 static int do_synchronous_recv ( SOCKET s, char *buf, int buflen, int flags, int recvlen )
352 {
353     char* last = buf + buflen, *p;
354     int n = 1;
355     for ( p = buf; n > 0 && p < last; )
356     {
357         n = recv ( s, p, min ( recvlen, last - p ), flags );
358         if (n > 0) p += n;
359     }
360     wsa_ok ( n, 0 <=, "do_synchronous_recv (%x): error %d:\n" );
361     return p - buf;
362 }
363 
364 static int do_synchronous_recvfrom ( SOCKET s, char *buf, int buflen, int flags, struct sockaddr *from, int *fromlen, int recvlen )
365 {
366     char* last = buf + buflen, *p;
367     int n = 1;
368     for ( p = buf; n > 0 && p < last; )
369     {
370         n = recvfrom ( s, p, min ( recvlen, last - p ), flags, from, fromlen );
371         if (n > 0) p += n;
372     }
373     wsa_ok ( n, 0 <=, "do_synchronous_recv (%x): error %d:\n" );
374     return p - buf;
375 }
376 
377 /*
378  *  Call this routine right after thread startup.
379  *  SO_OPENTYPE must by 0, regardless what the server did.
380  */
381 static void check_so_opentype (void)
382 {
383     int tmp = 1, len;
384     len = sizeof (tmp);
385     getsockopt ( INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (LPVOID) &tmp, &len );
386     ok ( tmp == 0, "check_so_opentype: wrong startup value of SO_OPENTYPE: %d\n", tmp );
387 }
388 
389 static void compare_addrinfo (ADDRINFO *a, ADDRINFO *b)
390 {
391     for (; a && b ; a = a->ai_next, b = b->ai_next)
392     {
393         ok(a->ai_flags == b->ai_flags,
394            "Wrong flags %d != %d\n", a->ai_flags, b->ai_flags);
395         ok(a->ai_family == b->ai_family,
396            "Wrong family %d != %d\n", a->ai_family, b->ai_family);
397         ok(a->ai_socktype == b->ai_socktype,
398            "Wrong socktype %d != %d\n", a->ai_socktype, b->ai_socktype);
399         ok(a->ai_protocol == b->ai_protocol,
400            "Wrong protocol %d != %d\n", a->ai_protocol, b->ai_protocol);
401         ok(a->ai_addrlen == b->ai_addrlen,
402            "Wrong addrlen %lu != %lu\n", a->ai_addrlen, b->ai_addrlen);
403         ok(!memcmp(a->ai_addr, b->ai_addr, min(a->ai_addrlen, b->ai_addrlen)),
404            "Wrong address data\n");
405         if (a->ai_canonname && b->ai_canonname)
406         {
407             ok(!strcmp(a->ai_canonname, b->ai_canonname), "Wrong canonical name '%s' != '%s'\n",
408                a->ai_canonname, b->ai_canonname);
409         }
410         else
411             ok(!a->ai_canonname && !b->ai_canonname, "Expected both names absent (%p != %p)\n",
412                a->ai_canonname, b->ai_canonname);
413     }
414     ok(!a && !b, "Expected both addresses null (%p != %p)\n", a, b);
415 }
416 
417 static void compare_addrinfow (ADDRINFOW *a, ADDRINFOW *b)
418 {
419     for (; a && b ; a = a->ai_next, b = b->ai_next)
420     {
421         ok(a->ai_flags == b->ai_flags,
422            "Wrong flags %d != %d\n", a->ai_flags, b->ai_flags);
423         ok(a->ai_family == b->ai_family,
424            "Wrong family %d != %d\n", a->ai_family, b->ai_family);
425         ok(a->ai_socktype == b->ai_socktype,
426            "Wrong socktype %d != %d\n", a->ai_socktype, b->ai_socktype);
427         ok(a->ai_protocol == b->ai_protocol,
428            "Wrong protocol %d != %d\n", a->ai_protocol, b->ai_protocol);
429         ok(a->ai_addrlen == b->ai_addrlen,
430            "Wrong addrlen %lu != %lu\n", a->ai_addrlen, b->ai_addrlen);
431         ok(!memcmp(a->ai_addr, b->ai_addr, min(a->ai_addrlen, b->ai_addrlen)),
432            "Wrong address data\n");
433         if (a->ai_canonname && b->ai_canonname)
434         {
435             ok(!lstrcmpW(a->ai_canonname, b->ai_canonname), "Wrong canonical name '%s' != '%s'\n",
436                wine_dbgstr_w(a->ai_canonname), wine_dbgstr_w(b->ai_canonname));
437         }
438         else
439             ok(!a->ai_canonname && !b->ai_canonname, "Expected both names absent (%p != %p)\n",
440                a->ai_canonname, b->ai_canonname);
441     }
442     ok(!a && !b, "Expected both addresses null (%p != %p)\n", a, b);
443 }
444 
445 /**************** Server utility functions ***************/
446 
447 /*
448  *  Even if we have closed our server socket cleanly,
449  *  the OS may mark the address "in use" for some time -
450  *  this happens with native Linux apps, too.
451  */
452 static void do_bind ( SOCKET s, struct sockaddr* addr, int addrlen )
453 {
454     int err, wsaerr = 0, n_try = BIND_TRIES;
455 
456     while ( ( err = bind ( s, addr, addrlen ) ) != 0 &&
457             ( wsaerr = WSAGetLastError () ) == WSAEADDRINUSE &&
458             n_try-- >= 0)
459     {
460         trace ( "address in use, waiting ...\n" );
461         Sleep ( 1000 * BIND_SLEEP );
462     }
463     ok ( err == 0, "failed to bind: %d\n", wsaerr );
464 }
465 
466 static void server_start ( server_params *par )
467 {
468     int i;
469     test_params *gen = par->general;
470     server_memory *mem = LocalAlloc ( LPTR, sizeof ( server_memory ) );
471 
472     TlsSetValue ( tls, mem );
473     mem->s = WSASocketA ( AF_INET, gen->sock_type, gen->sock_prot,
474                           NULL, 0, par->sock_flags );
475     ok ( mem->s != INVALID_SOCKET, "Server: WSASocket failed\n" );
476 
477     mem->addr.sin_family = AF_INET;
478     mem->addr.sin_addr.s_addr = inet_addr ( gen->inet_addr );
479     mem->addr.sin_port = htons ( gen->inet_port );
480 
481     for (i = 0; i < MAX_CLIENTS; i++)
482     {
483         mem->sock[i].s = INVALID_SOCKET;
484         mem->sock[i].buf = LocalAlloc ( LPTR, gen->n_chunks * gen->chunk_size );
485         mem->sock[i].n_recvd = 0;
486         mem->sock[i].n_sent = 0;
487     }
488 
489     if ( gen->sock_type == SOCK_STREAM )
490         do_bind ( mem->s, (struct sockaddr*) &mem->addr, sizeof (mem->addr) );
491 }
492 
493 static void server_stop (void)
494 {
495     int i;
496     server_memory *mem = TlsGetValue ( tls );
497 
498     for (i = 0; i < MAX_CLIENTS; i++ )
499     {
500         LocalFree ( mem->sock[i].buf );
501         if ( mem->sock[i].s != INVALID_SOCKET )
502             closesocket ( mem->sock[i].s );
503     }
504     ok ( closesocket ( mem->s ) == 0, "closesocket failed\n" );
505     LocalFree ( mem );
506     ExitThread ( GetCurrentThreadId () );
507 }
508 
509 /**************** Client utilitiy functions ***************/
510 
511 static void client_start ( client_params *par )
512 {
513     test_params *gen = par->general;
514     client_memory *mem = LocalAlloc (LPTR, sizeof (client_memory));
515 
516     TlsSetValue ( tls, mem );
517 
518     WaitForSingleObject ( server_ready, INFINITE );
519 
520     mem->s = WSASocketA ( AF_INET, gen->sock_type, gen->sock_prot,
521                           NULL, 0, par->sock_flags );
522 
523     mem->addr.sin_family = AF_INET;
524     mem->addr.sin_addr.s_addr = inet_addr ( gen->inet_addr );
525     mem->addr.sin_port = htons ( gen->inet_port );
526 
527     ok ( mem->s != INVALID_SOCKET, "Client: WSASocket failed\n" );
528 
529     mem->send_buf = LocalAlloc ( LPTR, 2 * gen->n_chunks * gen->chunk_size );
530     mem->recv_buf = mem->send_buf + gen->n_chunks * gen->chunk_size;
531     fill_buffer ( mem->send_buf, gen->chunk_size, gen->n_chunks );
532 
533     SetEvent ( client_ready[client_id] );
534     /* Wait for the other clients to come up */
535     WaitForMultipleObjects ( min ( gen->n_clients, MAX_CLIENTS ), client_ready, TRUE, INFINITE );
536 }
537 
538 static void client_stop (void)
539 {
540     client_memory *mem = TlsGetValue ( tls );
541     wsa_ok ( closesocket ( mem->s ), 0 ==, "closesocket error (%x): %d\n" );
542     LocalFree ( mem->send_buf );
543     LocalFree ( mem );
544     ExitThread(0);
545 }
546 
547 /**************** Servers ***************/
548 
549 /*
550  * simple_server: A very basic server doing synchronous IO.
551  */
552 static VOID WINAPI simple_server ( server_params *par )
553 {
554     test_params *gen = par->general;
555     server_memory *mem;
556     int pos, n_recvd, n_sent, n_expected = gen->n_chunks * gen->chunk_size, tmp, i,
557         id = GetCurrentThreadId();
558 
559     trace ( "simple_server (%x) starting\n", id );
560 
561     set_so_opentype ( FALSE ); /* non-overlapped */
562     server_start ( par );
563     mem = TlsGetValue ( tls );
564 
565     wsa_ok ( set_blocking ( mem->s, TRUE ), 0 ==, "simple_server (%x): failed to set blocking mode: %d\n");
566     wsa_ok ( listen ( mem->s, SOMAXCONN ), 0 ==, "simple_server (%x): listen failed: %d\n");
567 
568     trace ( "simple_server (%x) ready\n", id );
569     SetEvent ( server_ready ); /* notify clients */
570 
571     for ( i = 0; i < min ( gen->n_clients, MAX_CLIENTS ); i++ )
572     {
573         trace ( "simple_server (%x): waiting for client\n", id );
574 
575         /* accept a single connection */
576         tmp = sizeof ( mem->sock[0].peer );
577         mem->sock[0].s = accept ( mem->s, (struct sockaddr*) &mem->sock[0].peer, &tmp );
578         wsa_ok ( mem->sock[0].s, INVALID_SOCKET !=, "simple_server (%x): accept failed: %d\n" );
579 
580         ok ( mem->sock[0].peer.sin_addr.s_addr == inet_addr ( gen->inet_addr ),
581              "simple_server (%x): strange peer address\n", id );
582 
583         /* Receive data & check it */
584         n_recvd = do_synchronous_recv ( mem->sock[0].s, mem->sock[0].buf, n_expected, 0, par->buflen );
585         ok ( n_recvd == n_expected,
586              "simple_server (%x): received less data than expected: %d of %d\n", id, n_recvd, n_expected );
587         pos = test_buffer ( mem->sock[0].buf, gen->chunk_size, gen->n_chunks );
588         ok ( pos == -1, "simple_server (%x): test pattern error: %d\n", id, pos);
589 
590         /* Echo data back */
591         n_sent = do_synchronous_send ( mem->sock[0].s, mem->sock[0].buf, n_expected, 0, par->buflen );
592         ok ( n_sent == n_expected,
593              "simple_server (%x): sent less data than expected: %d of %d\n", id, n_sent, n_expected );
594 
595         /* cleanup */
596         read_zero_bytes ( mem->sock[0].s );
597         wsa_ok ( closesocket ( mem->sock[0].s ),  0 ==, "simple_server (%x): closesocket error: %d\n" );
598         mem->sock[0].s = INVALID_SOCKET;
599     }
600 
601     trace ( "simple_server (%x) exiting\n", id );
602     server_stop ();
603 }
604 
605 /*
606  * oob_server: A very basic server receiving out-of-band data.
607  */
608 static VOID WINAPI oob_server ( server_params *par )
609 {
610     test_params *gen = par->general;
611     server_memory *mem;
612     u_long atmark = 0;
613     int pos, n_sent, n_recvd, n_expected = gen->n_chunks * gen->chunk_size, tmp,
614         id = GetCurrentThreadId();
615 
616     trace ( "oob_server (%x) starting\n", id );
617 
618     set_so_opentype ( FALSE ); /* non-overlapped */
619     server_start ( par );
620     mem = TlsGetValue ( tls );
621 
622     wsa_ok ( set_blocking ( mem->s, TRUE ), 0 ==, "oob_server (%x): failed to set blocking mode: %d\n");
623     wsa_ok ( listen ( mem->s, SOMAXCONN ), 0 ==, "oob_server (%x): listen failed: %d\n");
624 
625     trace ( "oob_server (%x) ready\n", id );
626     SetEvent ( server_ready ); /* notify clients */
627 
628     trace ( "oob_server (%x): waiting for client\n", id );
629 
630     /* accept a single connection */
631     tmp = sizeof ( mem->sock[0].peer );
632     mem->sock[0].s = accept ( mem->s, (struct sockaddr*) &mem->sock[0].peer, &tmp );
633     wsa_ok ( mem->sock[0].s, INVALID_SOCKET !=, "oob_server (%x): accept failed: %d\n" );
634 
635     ok ( mem->sock[0].peer.sin_addr.s_addr == inet_addr ( gen->inet_addr ),
636          "oob_server (%x): strange peer address\n", id );
637 
638     /* check initial atmark state */
639     ioctlsocket ( mem->sock[0].s, SIOCATMARK, &atmark );
640     ok ( atmark == 1, "oob_server (%x): unexpectedly at the OOB mark: %i\n", id, atmark );
641 
642     /* Receive normal data */
643     n_recvd = do_synchronous_recv ( mem->sock[0].s, mem->sock[0].buf, n_expected, 0, par->buflen );
644     ok ( n_recvd == n_expected,
645          "oob_server (%x): received less data than expected: %d of %d\n", id, n_recvd, n_expected );
646     pos = test_buffer ( mem->sock[0].buf, gen->chunk_size, gen->n_chunks );
647     ok ( pos == -1, "oob_server (%x): test pattern error: %d\n", id, pos);
648 
649     /* check atmark state */
650     ioctlsocket ( mem->sock[0].s, SIOCATMARK, &atmark );
651     ok ( atmark == 1, "oob_server (%x): unexpectedly at the OOB mark: %i\n", id, atmark );
652 
653     /* Echo data back */
654     n_sent = do_synchronous_send ( mem->sock[0].s, mem->sock[0].buf, n_expected, 0, par->buflen );
655     ok ( n_sent == n_expected,
656          "oob_server (%x): sent less data than expected: %d of %d\n", id, n_sent, n_expected );
657 
658     /* Receive a part of the out-of-band data and print atmark state */
659     n_recvd = do_synchronous_recv ( mem->sock[0].s, mem->sock[0].buf, 8, 0, par->buflen );
660     ok ( n_recvd == 8,
661          "oob_server (%x): received less data than expected: %d of %d\n", id, n_recvd, 8 );
662     n_expected -= 8;
663 
664     ioctlsocket ( mem->sock[0].s, SIOCATMARK, &atmark );
665     trace( "oob_server (%x): %s the OOB mark: %i\n", id, atmark == 1 ? "not at" : "at", atmark );
666 
667     /* Receive the rest of the out-of-band data and check atmark state */
668     do_synchronous_recv ( mem->sock[0].s, mem->sock[0].buf, n_expected, 0, par->buflen );
669 
670     ioctlsocket ( mem->sock[0].s, SIOCATMARK, &atmark );
671     todo_wine ok ( atmark == 0, "oob_server (%x): not at the OOB mark: %i\n", id, atmark );
672 
673     /* cleanup */
674     wsa_ok ( closesocket ( mem->sock[0].s ),  0 ==, "oob_server (%x): closesocket error: %d\n" );
675     mem->sock[0].s = INVALID_SOCKET;
676 
677     trace ( "oob_server (%x) exiting\n", id );
678     server_stop ();
679 }
680 
681 /*
682  * select_server: A non-blocking server.
683  */
684 static VOID WINAPI select_server ( server_params *par )
685 {
686     test_params *gen = par->general;
687     server_memory *mem;
688     int n_expected = gen->n_chunks * gen->chunk_size, tmp, i,
689         id = GetCurrentThreadId(), n_connections = 0, n_sent, n_recvd,
690         n_set, delta, n_ready;
691     struct timeval timeout = {0,10}; /* wait for 10 milliseconds */
692     fd_set fds_recv, fds_send, fds_openrecv, fds_opensend;
693 
694     trace ( "select_server (%x) starting\n", id );
695 
696     set_so_opentype ( FALSE ); /* non-overlapped */
697     server_start ( par );
698     mem = TlsGetValue ( tls );
699 
700     wsa_ok ( set_blocking ( mem->s, FALSE ), 0 ==, "select_server (%x): failed to set blocking mode: %d\n");
701     wsa_ok ( listen ( mem->s, SOMAXCONN ), 0 ==, "select_server (%x): listen failed: %d\n");
702 
703     trace ( "select_server (%x) ready\n", id );
704     SetEvent ( server_ready ); /* notify clients */
705 
706     FD_ZERO ( &fds_openrecv );
707     FD_ZERO ( &fds_recv );
708     FD_ZERO ( &fds_send );
709     FD_ZERO ( &fds_opensend );
710 
711     FD_SET ( mem->s, &fds_openrecv );
712 
713     while(1)
714     {
715         fds_recv = fds_openrecv;
716         fds_send = fds_opensend;
717 
718         n_set = 0;
719 
720         wsa_ok ( ( n_ready = select ( 0, &fds_recv, &fds_send, NULL, &timeout ) ), SOCKET_ERROR !=,
721             "select_server (%x): select() failed: %d\n" );
722 
723         /* check for incoming requests */
724         if ( FD_ISSET ( mem->s, &fds_recv ) ) {
725             n_set += 1;
726 
727             trace ( "select_server (%x): accepting client connection\n", id );
728 
729             /* accept a single connection */
730             tmp = sizeof ( mem->sock[n_connections].peer );
731             mem->sock[n_connections].s = accept ( mem->s, (struct sockaddr*) &mem->sock[n_connections].peer, &tmp );
732             wsa_ok ( mem->sock[n_connections].s, INVALID_SOCKET !=, "select_server (%x): accept() failed: %d\n" );
733 
734             ok ( mem->sock[n_connections].peer.sin_addr.s_addr == inet_addr ( gen->inet_addr ),
735                 "select_server (%x): strange peer address\n", id );
736 
737             /* add to list of open connections */
738             FD_SET ( mem->sock[n_connections].s, &fds_openrecv );
739             FD_SET ( mem->sock[n_connections].s, &fds_opensend );
740 
741             n_connections++;
742         }
743 
744         /* handle open requests */
745 
746         for ( i = 0; i < n_connections; i++ )
747         {
748             if ( FD_ISSET( mem->sock[i].s, &fds_recv ) ) {
749                 n_set += 1;
750 
751                 if ( mem->sock[i].n_recvd < n_expected ) {
752                     /* Receive data & check it */
753                     n_recvd = recv ( mem->sock[i].s, mem->sock[i].buf + mem->sock[i].n_recvd, min ( n_expected - mem->sock[i].n_recvd, par->buflen ), 0 );
754                     ok ( n_recvd != SOCKET_ERROR, "select_server (%x): error in recv(): %d\n", id, WSAGetLastError() );
755                     mem->sock[i].n_recvd += n_recvd;
756 
757                     if ( mem->sock[i].n_recvd == n_expected ) {
758                         int pos = test_buffer ( mem->sock[i].buf, gen->chunk_size, gen->n_chunks );
759                         ok ( pos == -1, "select_server (%x): test pattern error: %d\n", id, pos );
760                         FD_CLR ( mem->sock[i].s, &fds_openrecv );
761                     }
762 
763                     ok ( mem->sock[i].n_recvd <= n_expected, "select_server (%x): received too many bytes: %d\n", id, mem->sock[i].n_recvd );
764                 }
765             }
766 
767             /* only echo back what we've received */
768             delta = mem->sock[i].n_recvd - mem->sock[i].n_sent;
769 
770             if ( FD_ISSET ( mem->sock[i].s, &fds_send ) ) {
771                 n_set += 1;
772 
773                 if ( ( delta > 0 ) && ( mem->sock[i].n_sent < n_expected ) ) {
774                     /* Echo data back */
775                     n_sent = send ( mem->sock[i].s, mem->sock[i].buf + mem->sock[i].n_sent, min ( delta, par->buflen ), 0 );
776                     ok ( n_sent != SOCKET_ERROR, "select_server (%x): error in send(): %d\n", id, WSAGetLastError() );
777                     mem->sock[i].n_sent += n_sent;
778 
779                     if ( mem->sock[i].n_sent == n_expected ) {
780                         FD_CLR ( mem->sock[i].s, &fds_opensend );
781                     }
782 
783                     ok ( mem->sock[i].n_sent <= n_expected, "select_server (%x): sent too many bytes: %d\n", id, mem->sock[i].n_sent );
784                 }
785             }
786         }
787 
788         /* check that select returned the correct number of ready sockets */
789         ok ( ( n_set == n_ready ), "select_server (%x): select() returns wrong number of ready sockets\n", id );
790 
791         /* check if all clients are done */
792         if ( ( fds_opensend.fd_count == 0 )
793             && ( fds_openrecv.fd_count == 1 ) /* initial socket that accepts clients */
794             && ( n_connections  == min ( gen->n_clients, MAX_CLIENTS ) ) ) {
795             break;
796         }
797     }
798 
799     for ( i = 0; i < min ( gen->n_clients, MAX_CLIENTS ); i++ )
800     {
801         /* cleanup */
802         read_zero_bytes ( mem->sock[i].s );
803         wsa_ok ( closesocket ( mem->sock[i].s ),  0 ==, "select_server (%x): closesocket error: %d\n" );
804         mem->sock[i].s = INVALID_SOCKET;
805     }
806 
807     trace ( "select_server (%x) exiting\n", id );
808     server_stop ();
809 }
810 
811 /**************** Clients ***************/
812 
813 /*
814  * simple_client: A very basic client doing synchronous IO.
815  */
816 static VOID WINAPI simple_client ( client_params *par )
817 {
818     test_params *gen = par->general;
819     client_memory *mem;
820     int pos, n_sent, n_recvd, n_expected = gen->n_chunks * gen->chunk_size, id;
821 
822     id = GetCurrentThreadId();
823     trace ( "simple_client (%x): starting\n", id );
824     /* wait here because we want to call set_so_opentype before creating a socket */
825     WaitForSingleObject ( server_ready, INFINITE );
826     trace ( "simple_client (%x): server ready\n", id );
827 
828     check_so_opentype ();
829     set_so_opentype ( FALSE ); /* non-overlapped */
830     client_start ( par );
831     mem = TlsGetValue ( tls );
832 
833     /* Connect */
834     wsa_ok ( connect ( mem->s, (struct sockaddr*) &mem->addr, sizeof ( mem->addr ) ),
835              0 ==, "simple_client (%x): connect error: %d\n" );
836     ok ( set_blocking ( mem->s, TRUE ) == 0,
837          "simple_client (%x): failed to set blocking mode\n", id );
838     trace ( "simple_client (%x) connected\n", id );
839 
840     /* send data to server */
841     n_sent = do_synchronous_send ( mem->s, mem->send_buf, n_expected, 0, par->buflen );
842     ok ( n_sent == n_expected,
843          "simple_client (%x): sent less data than expected: %d of %d\n", id, n_sent, n_expected );
844 
845     /* shutdown send direction */
846     wsa_ok ( shutdown ( mem->s, SD_SEND ), 0 ==, "simple_client (%x): shutdown failed: %d\n" );
847 
848     /* Receive data echoed back & check it */
849     n_recvd = do_synchronous_recv ( mem->s, mem->recv_buf, n_expected, 0, par->buflen );
850     ok ( n_recvd == n_expected,
851          "simple_client (%x): received less data than expected: %d of %d\n", id, n_recvd, n_expected );
852 
853     /* check data */
854     pos = test_buffer ( mem->recv_buf, gen->chunk_size, gen->n_chunks );
855     ok ( pos == -1, "simple_client (%x): test pattern error: %d\n", id, pos);
856 
857     /* cleanup */
858     read_zero_bytes ( mem->s );
859     trace ( "simple_client (%x) exiting\n", id );
860     client_stop ();
861 }
862 
863 /*
864  * oob_client: A very basic client sending out-of-band data.
865  */
866 static VOID WINAPI oob_client ( client_params *par )
867 {
868     test_params *gen = par->general;
869     client_memory *mem;
870     int pos, n_sent, n_recvd, n_expected = gen->n_chunks * gen->chunk_size, id;
871 
872     id = GetCurrentThreadId();
873     trace ( "oob_client (%x): starting\n", id );
874     /* wait here because we want to call set_so_opentype before creating a socket */
875     WaitForSingleObject ( server_ready, INFINITE );
876     trace ( "oob_client (%x): server ready\n", id );
877 
878     check_so_opentype ();
879     set_so_opentype ( FALSE ); /* non-overlapped */
880     client_start ( par );
881     mem = TlsGetValue ( tls );
882 
883     /* Connect */
884     wsa_ok ( connect ( mem->s, (struct sockaddr*) &mem->addr, sizeof ( mem->addr ) ),
885              0 ==, "oob_client (%x): connect error: %d\n" );
886     ok ( set_blocking ( mem->s, TRUE ) == 0,
887          "oob_client (%x): failed to set blocking mode\n", id );
888     trace ( "oob_client (%x) connected\n", id );
889 
890     /* send data to server */
891     n_sent = do_synchronous_send ( mem->s, mem->send_buf, n_expected, 0, par->buflen );
892     ok ( n_sent == n_expected,
893          "oob_client (%x): sent less data than expected: %d of %d\n", id, n_sent, n_expected );
894 
895     /* Receive data echoed back & check it */
896     n_recvd = do_synchronous_recv ( mem->s, mem->recv_buf, n_expected, 0, par->buflen );
897     ok ( n_recvd == n_expected,
898          "simple_client (%x): received less data than expected: %d of %d\n", id, n_recvd, n_expected );
899     pos = test_buffer ( mem->recv_buf, gen->chunk_size, gen->n_chunks );
900     ok ( pos == -1, "simple_client (%x): test pattern error: %d\n", id, pos);
901 
902     /* send out-of-band data to server */
903     n_sent = do_synchronous_send ( mem->s, mem->send_buf, n_expected, MSG_OOB, par->buflen );
904     ok ( n_sent == n_expected,
905          "oob_client (%x): sent less data than expected: %d of %d\n", id, n_sent, n_expected );
906 
907     /* shutdown send direction */
908     wsa_ok ( shutdown ( mem->s, SD_SEND ), 0 ==, "simple_client (%x): shutdown failed: %d\n" );
909 
910     /* cleanup */
911     read_zero_bytes ( mem->s );
912     trace ( "oob_client (%x) exiting\n", id );
913     client_stop ();
914 }
915 
916 /*
917  * simple_mixed_client: mixing send and recvfrom
918  */
919 static VOID WINAPI simple_mixed_client ( client_params *par )
920 {
921     test_params *gen = par->general;
922     client_memory *mem;
923     int pos, n_sent, n_recvd, n_expected = gen->n_chunks * gen->chunk_size, id;
924     int fromLen = sizeof(mem->addr);
925     struct sockaddr test;
926 
927     id = GetCurrentThreadId();
928     trace ( "simple_client (%x): starting\n", id );
929     /* wait here because we want to call set_so_opentype before creating a socket */
930     WaitForSingleObject ( server_ready, INFINITE );
931     trace ( "simple_client (%x): server ready\n", id );
932 
933     check_so_opentype ();
934     set_so_opentype ( FALSE ); /* non-overlapped */
935     client_start ( par );
936     mem = TlsGetValue ( tls );
937 
938     /* Connect */
939     wsa_ok ( connect ( mem->s, (struct sockaddr*) &mem->addr, sizeof ( mem->addr ) ),
940              0 ==, "simple_client (%x): connect error: %d\n" );
941     ok ( set_blocking ( mem->s, TRUE ) == 0,
942          "simple_client (%x): failed to set blocking mode\n", id );
943     trace ( "simple_client (%x) connected\n", id );
944 
945     /* send data to server */
946     n_sent = do_synchronous_send ( mem->s, mem->send_buf, n_expected, 0, par->buflen );
947     ok ( n_sent == n_expected,
948          "simple_client (%x): sent less data than expected: %d of %d\n", id, n_sent, n_expected );
949 
950     /* shutdown send direction */
951     wsa_ok ( shutdown ( mem->s, SD_SEND ), 0 ==, "simple_client (%x): shutdown failed: %d\n" );
952 
953     /* this shouldn't change, since lpFrom, is not updated on
954        connection oriented sockets - exposed by bug 11640
955     */
956     ((struct sockaddr_in*)&test)->sin_addr.s_addr = inet_addr("0.0.0.0");
957 
958     /* Receive data echoed back & check it */
959     n_recvd = do_synchronous_recvfrom ( mem->s,
960 					mem->recv_buf,
961 					n_expected,
962 					0,
963 					(struct sockaddr *)&test,
964 					&fromLen,
965 					par->buflen );
966     ok ( n_recvd == n_expected,
967          "simple_client (%x): received less data than expected: %d of %d\n", id, n_recvd, n_expected );
968 
969     /* check that lpFrom was not updated */
970     ok(0 ==
971        strcmp(
972 	      inet_ntoa(((struct sockaddr_in*)&test)->sin_addr),
973 	      "0.0.0.0"), "lpFrom shouldn't be updated on connection oriented sockets\n");
974 
975     /* check data */
976     pos = test_buffer ( mem->recv_buf, gen->chunk_size, gen->n_chunks );
977     ok ( pos == -1, "simple_client (%x): test pattern error: %d\n", id, pos);
978 
979     /* cleanup */
980     read_zero_bytes ( mem->s );
981     trace ( "simple_client (%x) exiting\n", id );
982     client_stop ();
983 }
984 
985 /*
986  * event_client: An event-driven client
987  */
988 static void WINAPI event_client ( client_params *par )
989 {
990     test_params *gen = par->general;
991     client_memory *mem;
992     int id = GetCurrentThreadId(), n_expected = gen->n_chunks * gen->chunk_size,
993         tmp, err, n;
994     HANDLE event;
995     WSANETWORKEVENTS wsa_events;
996     char *send_last, *recv_last, *send_p, *recv_p;
997     LONG mask = FD_READ | FD_WRITE | FD_CLOSE;
998 
999     trace ( "event_client (%x): starting\n", id );
1000     client_start ( par );
1001     trace ( "event_client (%x): server ready\n", id );
1002 
1003     mem = TlsGetValue ( tls );
1004 
1005     /* Prepare event notification for connect, makes socket nonblocking */
1006     event = WSACreateEvent ();
1007     WSAEventSelect ( mem->s, event, FD_CONNECT );
1008     tmp = connect ( mem->s, (struct sockaddr*) &mem->addr, sizeof ( mem->addr ) );
1009     if ( tmp != 0 ) {
1010         err = WSAGetLastError ();
1011         ok ( err == WSAEWOULDBLOCK, "event_client (%x): connect error: %d\n", id, err );
1012         tmp = WaitForSingleObject ( event, INFINITE );
1013         ok ( tmp == WAIT_OBJECT_0, "event_client (%x): wait for connect event failed: %d\n", id, tmp );
1014         err = WSAEnumNetworkEvents ( mem->s, event, &wsa_events );
1015         ok ( err == 0, "event_client (%x): WSAEnumNetworkEvents error: %d\n", id, err );
1016         err = wsa_events.iErrorCode[ FD_CONNECT_BIT ];
1017         ok ( err == 0, "event_client (%x): connect error: %d\n", id, err );
1018         if ( err ) goto out;
1019     }
1020 
1021     trace ( "event_client (%x) connected\n", id );
1022 
1023     WSAEventSelect ( mem->s, event, mask );
1024 
1025     recv_p = mem->recv_buf;
1026     recv_last = mem->recv_buf + n_expected;
1027     send_p = mem->send_buf;
1028     send_last = mem->send_buf + n_expected;
1029 
1030     while ( TRUE )
1031     {
1032         err = WaitForSingleObject ( event, INFINITE );
1033         ok ( err == WAIT_OBJECT_0, "event_client (%x): wait failed\n", id );
1034 
1035         err = WSAEnumNetworkEvents ( mem->s, event, &wsa_events );
1036         ok( err == 0, "event_client (%x): WSAEnumNetworkEvents error: %d\n", id, err );
1037 
1038         if ( wsa_events.lNetworkEvents & FD_WRITE )
1039         {
1040             err = wsa_events.iErrorCode[ FD_WRITE_BIT ];
1041             ok ( err == 0, "event_client (%x): FD_WRITE error code: %d\n", id, err );
1042 
1043             if ( err== 0 )
1044                 do
1045                 {
1046                     n = send ( mem->s, send_p, min ( send_last - send_p, par->buflen ), 0 );
1047                     if ( n < 0 )
1048                     {
1049                         err = WSAGetLastError ();
1050                         ok ( err == WSAEWOULDBLOCK, "event_client (%x): send error: %d\n", id, err );
1051                     }
1052                     else
1053                         send_p += n;
1054                 }
1055                 while ( n >= 0 && send_p < send_last );
1056 
1057             if ( send_p == send_last )
1058             {
1059                 trace ( "event_client (%x): all data sent - shutdown\n", id );
1060                 shutdown ( mem->s, SD_SEND );
1061                 mask &= ~FD_WRITE;
1062                 WSAEventSelect ( mem->s, event, mask );
1063             }
1064         }
1065         if ( wsa_events.lNetworkEvents & FD_READ )
1066         {
1067             err = wsa_events.iErrorCode[ FD_READ_BIT ];
1068             ok ( err == 0, "event_client (%x): FD_READ error code: %d\n", id, err );
1069             if ( err != 0 ) break;
1070 
1071             /* First read must succeed */
1072             n = recv ( mem->s, recv_p, min ( recv_last - recv_p, par->buflen ), 0 );
1073             wsa_ok ( n, 0 <=, "event_client (%x): recv error: %d\n" );
1074 
1075             while ( n >= 0 ) {
1076                 recv_p += n;
1077                 if ( recv_p == recv_last )
1078                 {
1079                     mask &= ~FD_READ;
1080                     trace ( "event_client (%x): all data received\n", id );
1081                     WSAEventSelect ( mem->s, event, mask );
1082                     break;
1083                 }
1084                 n = recv ( mem->s, recv_p, min ( recv_last - recv_p, par->buflen ), 0 );
1085                 if ( n < 0 && ( err = WSAGetLastError()) != WSAEWOULDBLOCK )
1086                     ok ( 0, "event_client (%x): read error: %d\n", id, err );
1087 
1088             }
1089         }
1090         if ( wsa_events.lNetworkEvents & FD_CLOSE )
1091         {
1092             trace ( "event_client (%x): close event\n", id );
1093             err = wsa_events.iErrorCode[ FD_CLOSE_BIT ];
1094             ok ( err == 0, "event_client (%x): FD_CLOSE error code: %d\n", id, err );
1095             break;
1096         }
1097     }
1098 
1099     n = send_p - mem->send_buf;
1100     ok ( send_p == send_last,
1101          "simple_client (%x): sent less data than expected: %d of %d\n", id, n, n_expected );
1102     n = recv_p - mem->recv_buf;
1103     ok ( recv_p == recv_last,
1104          "simple_client (%x): received less data than expected: %d of %d\n", id, n, n_expected );
1105     n = test_buffer ( mem->recv_buf, gen->chunk_size, gen->n_chunks );
1106     ok ( n == -1, "event_client (%x): test pattern error: %d\n", id, n);
1107 
1108 out:
1109     WSACloseEvent ( event );
1110     trace ( "event_client (%x) exiting\n", id );
1111     client_stop ();
1112 }
1113 
1114 /* Tests for WSAStartup */
1115 static void test_WithoutWSAStartup(void)
1116 {
1117     DWORD err;
1118 
1119     WSASetLastError(0xdeadbeef);
1120     ok(WSASocketA(0, 0, 0, NULL, 0, 0) == INVALID_SOCKET, "WSASocketA should have failed\n");
1121     err = WSAGetLastError();
1122     ok(err == WSANOTINITIALISED, "Expected 10093, received %d\n", err);
1123 
1124     WSASetLastError(0xdeadbeef);
1125     ok(gethostbyname("localhost") == NULL, "gethostbyname() succeeded unexpectedly\n");
1126     err = WSAGetLastError();
1127     ok(err == WSANOTINITIALISED, "Expected 10093, received %d\n", err);
1128 }
1129 
1130 static void test_WithWSAStartup(void)
1131 {
1132     WSADATA data;
1133     WORD version = MAKEWORD( 2, 2 );
1134     INT res, socks, i, j;
1135     SOCKET sock;
1136     LPVOID ptr;
1137     struct
1138     {
1139         SOCKET src, dst, dup_src, dup_dst;
1140     } pairs[128];
1141     DWORD error;
1142 
1143     res = WSAStartup( version, &data );
1144     ok(res == 0, "WSAStartup() failed unexpectedly: %d\n", res);
1145 
1146     ptr = gethostbyname("localhost");
1147     ok(ptr != NULL, "gethostbyname() failed unexpectedly: %d\n", WSAGetLastError());
1148 
1149     /* Alloc some sockets to check if they are destroyed on WSACleanup */
1150     for (socks = 0; socks < sizeof(pairs) / sizeof(pairs[0]); socks++)
1151     {
1152         WSAPROTOCOL_INFOA info;
1153         if (tcp_socketpair(&pairs[socks].src, &pairs[socks].dst)) break;
1154 
1155         memset(&info, 0, sizeof(info));
1156         ok(!WSADuplicateSocketA(pairs[socks].src, GetCurrentProcessId(), &info),
1157            "WSADuplicateSocketA should have worked\n");
1158         pairs[socks].dup_src = WSASocketA(0, 0, 0, &info, 0, 0);
1159         ok(pairs[socks].dup_src != SOCKET_ERROR, "expected != -1\n");
1160 
1161         memset(&info, 0, sizeof(info));
1162         ok(!WSADuplicateSocketA(pairs[socks].dst, GetCurrentProcessId(), &info),
1163            "WSADuplicateSocketA should have worked\n");
1164         pairs[socks].dup_dst = WSASocketA(0, 0, 0, &info, 0, 0);
1165         ok(pairs[socks].dup_dst != SOCKET_ERROR, "expected != -1\n");
1166     }
1167 
1168     res = send(pairs[0].src, "TEST", 4, 0);
1169     ok(res == 4, "send failed with error %d\n", WSAGetLastError());
1170 
1171     WSACleanup();
1172 
1173     res = WSAStartup( version, &data );
1174     ok(res == 0, "WSAStartup() failed unexpectedly: %d\n", res);
1175 
1176     /* show that sockets are destroyed automatically after WSACleanup */
1177     SetLastError(0xdeadbeef);
1178     res = send(pairs[0].src, "TEST", 4, 0);
1179     error = WSAGetLastError();
1180     ok(res == SOCKET_ERROR, "send should have failed\n");
1181     todo_wine ok(error == WSAENOTSOCK, "expected 10038, got %d\n", error);
1182 
1183     SetLastError(0xdeadbeef);
1184     res = send(pairs[0].dst, "TEST", 4, 0);
1185     error = WSAGetLastError();
1186     ok(res == SOCKET_ERROR, "send should have failed\n");
1187     todo_wine ok(error == WSAENOTSOCK, "expected 10038, got %d\n", error);
1188 
1189     /* Check that all sockets were destroyed */
1190     for (i = 0; i < socks; i++)
1191     {
1192         for (j = 0; j < 4; j++)
1193         {
1194             struct sockaddr_in saddr;
1195             int size = sizeof(saddr);
1196             switch(j)
1197             {
1198                 case 0: sock = pairs[i].src; break;
1199                 case 1: sock = pairs[i].dup_src; break;
1200                 case 2: sock = pairs[i].dst; break;
1201                 case 3: sock = pairs[i].dup_dst; break;
1202             }
1203 
1204             SetLastError(0xdeadbeef);
1205             res = getsockname(sock, (struct sockaddr *)&saddr, &size);
1206             error = WSAGetLastError();
1207             ok(res == SOCKET_ERROR, "Test[%d]: getsockname should have failed\n", i);
1208             todo_wine ok(error == WSAENOTSOCK, "Test[%d]: expected 10038, got %d\n", i, error);
1209         }
1210     }
1211 
1212     /* While wine is not fixed, close all sockets manually */
1213     for (i = 0; i < socks; i++)
1214     {
1215         closesocket(pairs[i].src);
1216         closesocket(pairs[i].dst);
1217         closesocket(pairs[i].dup_src);
1218         closesocket(pairs[i].dup_dst);
1219     }
1220 
1221     res = WSACleanup();
1222     ok(res == 0, "expected 0, got %d\n", res);
1223     WSASetLastError(0xdeadbeef);
1224     res = WSACleanup();
1225     error = WSAGetLastError();
1226     ok ( (res == SOCKET_ERROR && error ==  WSANOTINITIALISED) ||
1227          broken(res == 0),  /* WinME */
1228             "WSACleanup returned %d WSAGetLastError is %d\n", res, error);
1229 }
1230 
1231 /**************** Main program utility functions ***************/
1232 
1233 static void Init (void)
1234 {
1235     WORD ver = MAKEWORD (2, 2);
1236     WSADATA data;
1237     HMODULE hws2_32 = GetModuleHandleA("ws2_32.dll"), hiphlpapi;
1238     HMODULE hntdll = GetModuleHandleA("ntdll.dll");
1239 
1240     pfreeaddrinfo = (void *)GetProcAddress(hws2_32, "freeaddrinfo");
1241     pgetaddrinfo = (void *)GetProcAddress(hws2_32, "getaddrinfo");
1242     pFreeAddrInfoW = (void *)GetProcAddress(hws2_32, "FreeAddrInfoW");
1243     pFreeAddrInfoExW = (void *)GetProcAddress(hws2_32, "FreeAddrInfoExW");
1244     pGetAddrInfoW = (void *)GetProcAddress(hws2_32, "GetAddrInfoW");
1245     pGetAddrInfoExW = (void *)GetProcAddress(hws2_32, "GetAddrInfoExW");
1246     pGetAddrInfoExOverlappedResult = (void *)GetProcAddress(hws2_32, "GetAddrInfoExOverlappedResult");
1247     pInetNtop = (void *)GetProcAddress(hws2_32, "inet_ntop");
1248     pInetNtopW = (void *)GetProcAddress(hws2_32, "InetNtopW");
1249     pInetPtonA = (void *)GetProcAddress(hws2_32, "inet_pton");
1250     pInetPtonW = (void *)GetProcAddress(hws2_32, "InetPtonW");
1251     pWSALookupServiceBeginW = (void *)GetProcAddress(hws2_32, "WSALookupServiceBeginW");
1252     pWSALookupServiceEnd = (void *)GetProcAddress(hws2_32, "WSALookupServiceEnd");
1253     pWSALookupServiceNextW = (void *)GetProcAddress(hws2_32, "WSALookupServiceNextW");
1254     pWSAEnumNameSpaceProvidersA = (void *)GetProcAddress(hws2_32, "WSAEnumNameSpaceProvidersA");
1255     pWSAEnumNameSpaceProvidersW = (void *)GetProcAddress(hws2_32, "WSAEnumNameSpaceProvidersW");
1256     pWSAPoll = (void *)GetProcAddress(hws2_32, "WSAPoll");
1257 
1258     pNtSetInformationFile = (void *)GetProcAddress(hntdll, "NtSetInformationFile");
1259     pNtQueryInformationFile = (void *)GetProcAddress(hntdll, "NtQueryInformationFile");
1260 
1261     hiphlpapi = LoadLibraryA("iphlpapi.dll");
1262     if (hiphlpapi)
1263     {
1264         pGetIpForwardTable = (void *)GetProcAddress(hiphlpapi, "GetIpForwardTable");
1265         pGetAdaptersInfo = (void *)GetProcAddress(hiphlpapi, "GetAdaptersInfo");
1266     }
1267 
1268     ok ( WSAStartup ( ver, &data ) == 0, "WSAStartup failed\n" );
1269     tls = TlsAlloc();
1270 }
1271 
1272 static void Exit (void)
1273 {
1274     INT ret, err;
1275     TlsFree ( tls );
1276     ret = WSACleanup();
1277     err = WSAGetLastError();
1278     ok ( ret == 0, "WSACleanup failed ret = %d GetLastError is %d\n", ret, err);
1279 }
1280 
1281 static void StartServer (LPTHREAD_START_ROUTINE routine,
1282                          test_params *general, server_params *par)
1283 {
1284     par->general = general;
1285     thread[0] = CreateThread ( NULL, 0, routine, par, 0, &thread_id[0] );
1286     ok ( thread[0] != NULL, "Failed to create server thread\n" );
1287 }
1288 
1289 static void StartClients (LPTHREAD_START_ROUTINE routine,
1290                           test_params *general, client_params *par)
1291 {
1292     int i;
1293     par->general = general;
1294     for ( i = 1; i <= min ( general->n_clients, MAX_CLIENTS ); i++ )
1295     {
1296         client_id = i - 1;
1297         thread[i] = CreateThread ( NULL, 0, routine, par, 0, &thread_id[i] );
1298         ok ( thread[i] != NULL, "Failed to create client thread\n" );
1299         /* Make sure the client is up and running */
1300         WaitForSingleObject ( client_ready[client_id], INFINITE );
1301     };
1302 }
1303 
1304 static void do_test( test_setup *test )
1305 {
1306     DWORD i, n = min (test->general.n_clients, MAX_CLIENTS);
1307     DWORD wait;
1308 
1309     server_ready = CreateEventA ( NULL, TRUE, FALSE, NULL );
1310     for (i = 0; i <= n; i++)
1311         client_ready[i] = CreateEventA ( NULL, TRUE, FALSE, NULL );
1312 
1313     StartServer ( test->srv, &test->general, &test->srv_params );
1314     StartClients ( test->clt, &test->general, &test->clt_params );
1315     WaitForSingleObject ( server_ready, INFINITE );
1316 
1317     wait = WaitForMultipleObjects ( 1 + n, thread, TRUE, 1000 * TEST_TIMEOUT );
1318     ok ( wait <= WAIT_OBJECT_0 + n ,
1319          "some threads have not completed: %x\n", wait );
1320 
1321     if ( ! ( wait <= WAIT_OBJECT_0 + n ) )
1322     {
1323         for (i = 0; i <= n; i++)
1324         {
1325             if ( WaitForSingleObject ( thread[i], 0 ) != WAIT_OBJECT_0 )
1326             {
1327                 trace ("terminating thread %08x\n", thread_id[i]);
1328                 TerminateThread ( thread [i], 0 );
1329             }
1330         }
1331     }
1332     CloseHandle ( server_ready );
1333     for (i = 0; i <= n; i++)
1334         CloseHandle ( client_ready[i] );
1335 }
1336 
1337 /********* some tests for getsockopt(setsockopt(X)) == X ***********/
1338 /* optname = SO_LINGER */
1339 static const LINGER linger_testvals[] = {
1340     {0,0},
1341     {0,73},
1342     {1,0},
1343     {5,189}
1344 };
1345 
1346 /* optname = SO_RCVTIMEO, SOSNDTIMEO */
1347 #define SOCKTIMEOUT1 63000 /* 63 seconds. Do not test fractional part because of a
1348                         bug in the linux kernel (fixed in 2.6.8) */
1349 #define SOCKTIMEOUT2 997000 /* 997 seconds */
1350 
1351 static void test_set_getsockopt(void)
1352 {
1353     SOCKET s, s2;
1354     int i, err, lasterr;
1355     int timeout;
1356     LINGER lingval;
1357     int size;
1358     WSAPROTOCOL_INFOA infoA;
1359     WSAPROTOCOL_INFOW infoW;
1360     char providername[WSAPROTOCOL_LEN + 1];
1361     DWORD value;
1362     struct _prottest
1363     {
1364         int family, type, proto;
1365     } prottest[] = {
1366         {AF_INET, SOCK_STREAM, IPPROTO_TCP},
1367         {AF_INET, SOCK_DGRAM, IPPROTO_UDP},
1368         {AF_INET6, SOCK_STREAM, IPPROTO_TCP},
1369         {AF_INET6, SOCK_DGRAM, IPPROTO_UDP}
1370     };
1371     union _csspace
1372     {
1373         CSADDR_INFO cs;
1374         char space[128];
1375     } csinfoA, csinfoB;
1376 
1377     s = socket(AF_INET, SOCK_STREAM, 0);
1378     ok(s!=INVALID_SOCKET, "socket() failed error: %d\n", WSAGetLastError());
1379     if( s == INVALID_SOCKET) return;
1380     /* SO_RCVTIMEO */
1381     timeout = SOCKTIMEOUT1;
1382     size = sizeof(timeout);
1383     err = setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char *) &timeout, size);
1384     if( !err)
1385         err = getsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char *) &timeout, &size);
1386     ok( !err, "get/setsockopt(SO_RCVTIMEO) failed error: %d\n", WSAGetLastError());
1387     ok( timeout == SOCKTIMEOUT1, "getsockopt(SO_RCVTIMEO) returned wrong value %d\n", timeout);
1388 
1389     timeout = 0;
1390     size = sizeof(timeout);
1391     err = setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char *) &timeout, size);
1392     if( !err)
1393         err = getsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (char *) &timeout, &size);
1394     ok( !err, "get/setsockopt(SO_RCVTIMEO) failed error: %d\n", WSAGetLastError());
1395     ok( timeout == 0, "getsockopt(SO_RCVTIMEO) returned wrong value %d\n", timeout);
1396 
1397     /* SO_SNDTIMEO */
1398     timeout = SOCKTIMEOUT2; /* 997 seconds. See remark above */
1399     size = sizeof(timeout);
1400     err = setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, (char *) &timeout, size);
1401     if( !err)
1402         err = getsockopt(s, SOL_SOCKET, SO_SNDTIMEO, (char *) &timeout, &size);
1403     ok( !err, "get/setsockopt(SO_SNDTIMEO) failed error: %d\n", WSAGetLastError());
1404     ok( timeout == SOCKTIMEOUT2, "getsockopt(SO_SNDTIMEO) returned wrong value %d\n", timeout);
1405 
1406     /* SO_SNDBUF */
1407     value = 4096;
1408     size = sizeof(value);
1409     err = setsockopt(s, SOL_SOCKET, SO_SNDBUF, (char *)&value, size);
1410     ok( !err, "setsockopt(SO_SNDBUF) failed error: %u\n", WSAGetLastError() );
1411     value = 0xdeadbeef;
1412     err = getsockopt(s, SOL_SOCKET, SO_SNDBUF, (char *)&value, &size);
1413     ok( !err, "getsockopt(SO_SNDBUF) failed error: %u\n", WSAGetLastError() );
1414     ok( value == 4096, "expected 4096, got %u\n", value );
1415 
1416     /* SO_RCVBUF */
1417     value = 4096;
1418     size = sizeof(value);
1419     err = setsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&value, size);
1420     ok( !err, "setsockopt(SO_RCVBUF) failed error: %u\n", WSAGetLastError() );
1421     value = 0xdeadbeef;
1422     err = getsockopt(s, SOL_SOCKET, SO_RCVBUF, (char *)&value, &size);
1423     ok( !err, "getsockopt(SO_RCVBUF) failed error: %u\n", WSAGetLastError() );
1424     ok( value == 4096, "expected 4096, got %u\n", value );
1425 
1426     /* SO_LINGER */
1427     for( i = 0; i < sizeof(linger_testvals)/sizeof(LINGER);i++) {
1428         size =  sizeof(lingval);
1429         lingval = linger_testvals[i];
1430         err = setsockopt(s, SOL_SOCKET, SO_LINGER, (char *) &lingval, size);
1431         if( !err)
1432             err = getsockopt(s, SOL_SOCKET, SO_LINGER, (char *) &lingval, &size);
1433         ok( !err, "get/setsockopt(SO_LINGER) failed error: %d\n", WSAGetLastError());
1434         ok( !lingval.l_onoff == !linger_testvals[i].l_onoff &&
1435                 (lingval.l_linger == linger_testvals[i].l_linger ||
1436                  (!lingval.l_linger && !linger_testvals[i].l_onoff))
1437                 , "getsockopt(SO_LINGER #%d) returned wrong value %d,%d not %d,%d\n", i,
1438                  lingval.l_onoff, lingval.l_linger,
1439                  linger_testvals[i].l_onoff, linger_testvals[i].l_linger);
1440     }
1441 
1442     size =  sizeof(lingval);
1443     err = setsockopt(s, SOL_SOCKET, SO_LINGER, NULL, size);
1444     ok(err == SOCKET_ERROR && WSAGetLastError() == WSAEFAULT,
1445        "got %d with %d (expected SOCKET_ERROR with WSAEFAULT)\n", err, WSAGetLastError());
1446     err = setsockopt(s, SOL_SOCKET, SO_LINGER, NULL, 0);
1447     ok(err == SOCKET_ERROR && WSAGetLastError() == WSAEFAULT,
1448        "got %d with %d (expected SOCKET_ERROR with WSAEFAULT)\n", err, WSAGetLastError());
1449 
1450     size =  sizeof(BOOL);
1451     err = setsockopt(s, SOL_SOCKET, SO_DONTLINGER, NULL, size);
1452     ok(err == SOCKET_ERROR && WSAGetLastError() == WSAEFAULT,
1453        "got %d with %d (expected SOCKET_ERROR with WSAEFAULT)\n", err, WSAGetLastError());
1454     err = setsockopt(s, SOL_SOCKET, SO_DONTLINGER, NULL, 0);
1455     ok(err == SOCKET_ERROR && WSAGetLastError() == WSAEFAULT,
1456        "got %d with %d (expected SOCKET_ERROR with WSAEFAULT)\n", err, WSAGetLastError());
1457 
1458     /* Test for erroneously passing a value instead of a pointer as optval */
1459     size = sizeof(char);
1460     err = setsockopt(s, SOL_SOCKET, SO_DONTROUTE, (char *)1, size);
1461     ok(err == SOCKET_ERROR, "setsockopt with optval being a value passed "
1462                             "instead of failing.\n");
1463     lasterr = WSAGetLastError();
1464     ok(lasterr == WSAEFAULT, "setsockopt with optval being a value "
1465                              "returned 0x%08x, not WSAEFAULT(0x%08x)\n",
1466                              lasterr, WSAEFAULT);
1467 
1468     /* SO_RCVTIMEO with invalid values for level */
1469     size = sizeof(timeout);
1470     timeout = SOCKTIMEOUT1;
1471     SetLastError(0xdeadbeef);
1472     err = setsockopt(s, 0xffffffff, SO_RCVTIMEO, (char *) &timeout, size);
1473     ok( (err == SOCKET_ERROR) && (WSAGetLastError() == WSAEINVAL),
1474         "got %d with %d (expected SOCKET_ERROR with WSAEINVAL)\n",
1475         err, WSAGetLastError());
1476 
1477     timeout = SOCKTIMEOUT1;
1478     SetLastError(0xdeadbeef);
1479     err = setsockopt(s, 0x00008000, SO_RCVTIMEO, (char *) &timeout, size);
1480     ok( (err == SOCKET_ERROR) && (WSAGetLastError() == WSAEINVAL),
1481         "got %d with %d (expected SOCKET_ERROR with WSAEINVAL)\n",
1482         err, WSAGetLastError());
1483 
1484     /* Test SO_ERROR set/get */
1485     SetLastError(0xdeadbeef);
1486     i = 1234;
1487     err = setsockopt(s, SOL_SOCKET, SO_ERROR, (char *) &i, size);
1488 todo_wine
1489     ok( !err && !WSAGetLastError(),
1490         "got %d with %d (expected 0 with 0)\n",
1491         err, WSAGetLastError());
1492 
1493     SetLastError(0xdeadbeef);
1494     i = 4321;
1495     err = getsockopt(s, SOL_SOCKET, SO_ERROR, (char *) &i, &size);
1496 todo_wine
1497     ok( !err && !WSAGetLastError(),
1498         "got %d with %d (expected 0 with 0)\n",
1499         err, WSAGetLastError());
1500 todo_wine
1501     ok (i == 1234, "got %d (expected 1234)\n", i);
1502 
1503     /* Test invalid optlen */
1504     SetLastError(0xdeadbeef);
1505     size = 1;
1506     err = getsockopt(s, SOL_SOCKET, SO_ERROR, (char *) &i, &size);
1507 todo_wine
1508     ok( (err == SOCKET_ERROR) && (WSAGetLastError() == WSAEFAULT),
1509         "got %d with %d (expected SOCKET_ERROR with WSAEFAULT)\n",
1510         err, WSAGetLastError());
1511 
1512     closesocket(s);
1513     /* Test with the closed socket */
1514     SetLastError(0xdeadbeef);
1515     size = sizeof(i);
1516     i = 1234;
1517     err = getsockopt(s, SOL_SOCKET, SO_ERROR, (char *) &i, &size);
1518 todo_wine
1519     ok( (err == SOCKET_ERROR) && (WSAGetLastError() == WSAENOTSOCK),
1520         "got %d with %d (expected SOCKET_ERROR with WSAENOTSOCK)\n",
1521         err, WSAGetLastError());
1522     ok (i == 1234, "expected 1234, got %d\n", i);
1523 
1524     /* Test WS_IP_MULTICAST_TTL with 8, 16, 24 and 32 bits values */
1525     s = socket(AF_INET, SOCK_DGRAM, 0);
1526     ok(s != INVALID_SOCKET, "Failed to create socket\n");
1527     size = sizeof(i);
1528     i = 0x0000000a;
1529     err = setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, (char *) &i, size);
1530     if (!err)
1531     {
1532         for (i = 0; i < 4; i++)
1533         {
1534             int k, j;
1535             const int tests[] = {0xffffff0a, 0xffff000b, 0xff00000c, 0x0000000d};
1536             err = setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, (char *) &tests[i], i + 1);
1537             ok(!err, "Test [%d] Expected 0, got %d\n", i, err);
1538             err = getsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, (char *) &k, &size);
1539             ok(!err, "Test [%d] Expected 0, got %d\n", i, err);
1540             j = i != 3 ? tests[i] & ((1 << (i + 1) * 8) - 1) : tests[i];
1541             ok(k == j, "Test [%d] Expected 0x%x, got 0x%x\n", i, j, k);
1542         }
1543     }
1544     else
1545         win_skip("IP_MULTICAST_TTL is unsupported\n");
1546     closesocket(s);
1547 
1548     /* test SO_PROTOCOL_INFOA invalid parameters */
1549     ok(getsockopt(INVALID_SOCKET, SOL_SOCKET, SO_PROTOCOL_INFOA, NULL, NULL),
1550        "getsockopt should have failed\n");
1551     err = WSAGetLastError();
1552     ok(err == WSAENOTSOCK, "expected 10038, got %d instead\n", err);
1553     size = sizeof(WSAPROTOCOL_INFOA);
1554     ok(getsockopt(INVALID_SOCKET, SOL_SOCKET, SO_PROTOCOL_INFOA, (char *) &infoA, &size),
1555        "getsockopt should have failed\n");
1556     ok(size == sizeof(WSAPROTOCOL_INFOA), "got size %d\n", size);
1557     err = WSAGetLastError();
1558     ok(err == WSAENOTSOCK, "expected 10038, got %d instead\n", err);
1559     s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
1560     ok(getsockopt(s, SOL_SOCKET, SO_PROTOCOL_INFOA, NULL, NULL),
1561        "getsockopt should have failed\n");
1562     err = WSAGetLastError();
1563     ok(err == WSAEFAULT, "expected 10014, got %d instead\n", err);
1564     ok(getsockopt(s, SOL_SOCKET, SO_PROTOCOL_INFOA, (char *) &infoA, NULL),
1565        "getsockopt should have failed\n");
1566     err = WSAGetLastError();
1567     ok(err == WSAEFAULT, "expected 10014, got %d instead\n", err);
1568     ok(getsockopt(s, SOL_SOCKET, SO_PROTOCOL_INFOA, NULL, &size),
1569        "getsockopt should have failed\n");
1570     err = WSAGetLastError();
1571     ok(err == WSAEFAULT, "expected 10014, got %d instead\n", err);
1572     size = sizeof(WSAPROTOCOL_INFOA) / 2;
1573     ok(getsockopt(s, SOL_SOCKET, SO_PROTOCOL_INFOA, (char *) &infoA, &size),
1574        "getsockopt should have failed\n");
1575     err = WSAGetLastError();
1576     ok(err == WSAEFAULT, "expected 10014, got %d instead\n", err);
1577     ok(size == sizeof(WSAPROTOCOL_INFOA), "got size %d\n", size);
1578     size = sizeof(WSAPROTOCOL_INFOA) * 2;
1579     err = getsockopt(s, SOL_SOCKET, SO_PROTOCOL_INFOA, (char *) &infoA, &size);
1580     ok(!err,"getsockopt failed with %d\n", WSAGetLastError());
1581     ok(size == sizeof(WSAPROTOCOL_INFOA) * 2, "got size %d\n", size);
1582 
1583     closesocket(s);
1584 
1585     /* test SO_PROTOCOL_INFO structure returned for different protocols */
1586     for (i = 0; i < sizeof(prottest) / sizeof(prottest[0]); i++)
1587     {
1588         int k;
1589 
1590         s = socket(prottest[i].family, prottest[i].type, prottest[i].proto);
1591         if (s == INVALID_SOCKET && prottest[i].family == AF_INET6) continue;
1592 
1593         ok(s != INVALID_SOCKET, "Failed to create socket: %d\n",
1594           WSAGetLastError());
1595 
1596         /* compare both A and W version */
1597         infoA.szProtocol[0] = 0;
1598         size = sizeof(WSAPROTOCOL_INFOA);
1599         err = getsockopt(s, SOL_SOCKET, SO_PROTOCOL_INFOA, (char *) &infoA, &size);
1600         ok(!err,"getsockopt failed with %d\n", WSAGetLastError());
1601         ok(size == sizeof(WSAPROTOCOL_INFOA), "got size %d\n", size);
1602 
1603         infoW.szProtocol[0] = 0;
1604         size = sizeof(WSAPROTOCOL_INFOW);
1605         err = getsockopt(s, SOL_SOCKET, SO_PROTOCOL_INFOW, (char *) &infoW, &size);
1606         ok(!err,"getsockopt failed with %d\n", WSAGetLastError());
1607         ok(size == sizeof(WSAPROTOCOL_INFOW), "got size %d\n", size);
1608 
1609         trace("provider name '%s', family %d, type %d, proto %d\n",
1610               infoA.szProtocol, prottest[i].family, prottest[i].type, prottest[i].proto);
1611 
1612         ok(infoA.szProtocol[0] || broken(!infoA.szProtocol[0]) /* NT4 */,
1613            "WSAPROTOCOL_INFOA was not filled\n");
1614         ok(infoW.szProtocol[0] || broken(!infoA.szProtocol[0]) /* NT4 */,
1615            "WSAPROTOCOL_INFOW was not filled\n");
1616 
1617         WideCharToMultiByte(CP_ACP, 0, infoW.szProtocol, -1,
1618                             providername, sizeof(providername), NULL, NULL);
1619         ok(!strcmp(infoA.szProtocol,providername),
1620            "different provider names '%s' != '%s'\n", infoA.szProtocol, providername);
1621 
1622         ok(!memcmp(&infoA, &infoW, FIELD_OFFSET(WSAPROTOCOL_INFOA, szProtocol)),
1623            "SO_PROTOCOL_INFO[A/W] comparison failed\n");
1624 
1625         /* Remove IF when WSAEnumProtocols support IPV6 data */
1626         todo_wine_if (prottest[i].family == AF_INET6)
1627             ok(infoA.iAddressFamily == prottest[i].family, "socket family invalid, expected %d received %d\n",
1628                prottest[i].family, infoA.iAddressFamily);
1629         ok(infoA.iSocketType == prottest[i].type, "socket type invalid, expected %d received %d\n",
1630            prottest[i].type, infoA.iSocketType);
1631         ok(infoA.iProtocol == prottest[i].proto, "socket protocol invalid, expected %d received %d\n",
1632            prottest[i].proto, infoA.iProtocol);
1633 
1634         /* IP_HDRINCL is supported only on SOCK_RAW but passed to SOCK_DGRAM by Impossible Creatures */
1635         size = sizeof(i);
1636         k = 1;
1637         SetLastError(0xdeadbeef);
1638         err = setsockopt(s, IPPROTO_IP, IP_HDRINCL, (char *) &k, size);
1639         if (err == -1) /* >= Vista */
1640         {
1641             todo_wine {
1642             ok(GetLastError() == WSAEINVAL, "Expected 10022, got %d\n", GetLastError());
1643             k = 99;
1644             SetLastError(0xdeadbeef);
1645             err = getsockopt(s, IPPROTO_IP, IP_HDRINCL, (char *) &k, &size);
1646             ok(err == -1, "Expected -1, got %d\n", err);
1647             ok(GetLastError() == WSAEINVAL, "Expected 10022, got %d\n", GetLastError());
1648             ok(k == 99, "Expected 99, got %d\n", k);
1649 
1650             size = sizeof(k);
1651             k = 0;
1652             SetLastError(0xdeadbeef);
1653             err = setsockopt(s, IPPROTO_IP, IP_HDRINCL, (char *) &k, size);
1654             }
1655             ok(err == -1, "Expected -1, got %d\n", err);
1656             todo_wine {
1657             ok(GetLastError() == WSAEINVAL, "Expected 10022, got %d\n", GetLastError());
1658             k = 99;
1659             SetLastError(0xdeadbeef);
1660             err = getsockopt(s, IPPROTO_IP, IP_HDRINCL, (char *) &k, &size);
1661             ok(err == -1, "Expected -1, got %d\n", err);
1662             ok(GetLastError() == WSAEINVAL, "Expected 10022, got %d\n", GetLastError());
1663             ok(k == 99, "Expected 99, got %d\n", k);
1664             }
1665         }
1666         else /* <= 2003 the tests differ between TCP and UDP, UDP silently accepts */
1667         {
1668             SetLastError(0xdeadbeef);
1669             k = 99;
1670             err = getsockopt(s, IPPROTO_IP, IP_HDRINCL, (char *) &k, &size);
1671             if (prottest[i].type == SOCK_DGRAM)
1672             {
1673                 ok(err == 0, "Expected 0, got %d\n", err);
1674                 ok(k == 1, "Expected 1, got %d\n", k);
1675             }
1676             else
1677             {
1678                 /* contratry to what we could expect the function returns error but k is changed */
1679                 ok(err == -1, "Expected -1, got %d\n", err);
1680                 ok(GetLastError() == WSAENOPROTOOPT, "Expected 10042, got %d\n", GetLastError());
1681                 ok(k == 0, "Expected 0, got %d\n", k);
1682             }
1683 
1684             k = 0;
1685             err = setsockopt(s, IPPROTO_IP, IP_HDRINCL, (char *) &k, size);
1686             ok(err == 0, "Expected 0, got %d\n", err);
1687 
1688             k = 99;
1689             err = getsockopt(s, IPPROTO_IP, IP_HDRINCL, (char *) &k, &size);
1690             if (prottest[i].type == SOCK_DGRAM)
1691             {
1692                 ok(err == 0, "Expected 0, got %d\n", err);
1693                 ok(k == 0, "Expected 0, got %d\n", k);
1694             }
1695             else
1696             {
1697                 /* contratry to what we could expect the function returns error but k is changed */
1698                 ok(err == -1, "Expected -1, got %d\n", err);
1699                 ok(GetLastError() == WSAENOPROTOOPT, "Expected 10042, got %d\n", GetLastError());
1700                 ok(k == 0, "Expected 0, got %d\n", k);
1701             }
1702         }
1703 
1704         closesocket(s);
1705     }
1706 
1707     /* Test SO_BSP_STATE - Present only in >= Win 2008 */
1708     s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
1709     ok(s != INVALID_SOCKET, "Failed to create socket\n");
1710     s2 = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
1711     ok(s2 != INVALID_SOCKET, "Failed to create socket\n");
1712 
1713     SetLastError(0xdeadbeef);
1714     size = sizeof(csinfoA);
1715     err = getsockopt(s, SOL_SOCKET, SO_BSP_STATE, (char *) &csinfoA, &size);
1716     if (!err)
1717     {
1718         struct sockaddr_in saddr;
1719         memset(&saddr, 0, sizeof(saddr));
1720         saddr.sin_family = AF_INET;
1721         saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
1722 
1723         /* Socket is not bound, no information provided */
1724         ok(!csinfoA.cs.LocalAddr.iSockaddrLength, "Expected 0, got %d\n", csinfoA.cs.LocalAddr.iSockaddrLength);
1725         ok(csinfoA.cs.LocalAddr.lpSockaddr == NULL, "Expected NULL, got %p\n", csinfoA.cs.LocalAddr.lpSockaddr);
1726         /* Socket is not connected, no information provided */
1727         ok(!csinfoA.cs.RemoteAddr.iSockaddrLength, "Expected 0, got %d\n", csinfoA.cs.LocalAddr.iSockaddrLength);
1728         ok(csinfoA.cs.RemoteAddr.lpSockaddr == NULL, "Expected NULL, got %p\n", csinfoA.cs.LocalAddr.lpSockaddr);
1729 
1730         err = bind(s, (struct sockaddr*)&saddr, sizeof(saddr));
1731         ok(!err, "Expected 0, got %d\n", err);
1732         size = sizeof(csinfoA);
1733         err = getsockopt(s, SOL_SOCKET, SO_BSP_STATE, (char *) &csinfoA, &size);
1734         ok(!err, "Expected 0, got %d\n", err);
1735 
1736         /* Socket is bound */
1737         ok(csinfoA.cs.LocalAddr.iSockaddrLength, "Expected non-zero\n");
1738         ok(csinfoA.cs.LocalAddr.lpSockaddr != NULL, "Expected non-null\n");
1739         /* Socket is not connected, no information provided */
1740         ok(!csinfoA.cs.RemoteAddr.iSockaddrLength, "Expected 0, got %d\n", csinfoA.cs.LocalAddr.iSockaddrLength);
1741         ok(csinfoA.cs.RemoteAddr.lpSockaddr == NULL, "Expected NULL, got %p\n", csinfoA.cs.LocalAddr.lpSockaddr);
1742 
1743         err = bind(s2, (struct sockaddr*)&saddr, sizeof(saddr));
1744         ok(!err, "Expected 0, got %d\n", err);
1745         err = getsockname(s2, (struct sockaddr *)&saddr, &size);
1746         ok(!err, "Expected 0, got %d\n", err);
1747         err = listen(s2, 1);
1748         ok(!err, "Expected 0, got %d\n", err);
1749         err = connect(s, (struct sockaddr*)&saddr, sizeof(saddr));
1750         ok(!err, "Expected 0, got %d\n", err);
1751         size = sizeof(saddr);
1752         err = accept(s2, (struct sockaddr*)&saddr, &size);
1753         ok(err != INVALID_SOCKET, "Failed to accept socket\n");
1754         closesocket(s2);
1755         s2 = err;
1756 
1757         size = sizeof(csinfoA);
1758         err = getsockopt(s, SOL_SOCKET, SO_BSP_STATE, (char *) &csinfoA, &size);
1759         ok(!err, "Expected 0, got %d\n", err);
1760         err = getsockopt(s2, SOL_SOCKET, SO_BSP_STATE, (char *) &csinfoB, &size);
1761         ok(!err, "Expected 0, got %d\n", err);
1762         ok(size == sizeof(csinfoA), "Got %d\n", size);
1763         size = sizeof(saddr);
1764         ok(size == csinfoA.cs.LocalAddr.iSockaddrLength, "Expected %d, got %d\n", size,
1765            csinfoA.cs.LocalAddr.iSockaddrLength);
1766         ok(size == csinfoA.cs.RemoteAddr.iSockaddrLength, "Expected %d, got %d\n", size,
1767            csinfoA.cs.RemoteAddr.iSockaddrLength);
1768         ok(!memcmp(csinfoA.cs.LocalAddr.lpSockaddr, csinfoB.cs.RemoteAddr.lpSockaddr, size),
1769            "Expected matching addresses\n");
1770         ok(!memcmp(csinfoB.cs.LocalAddr.lpSockaddr, csinfoA.cs.RemoteAddr.lpSockaddr, size),
1771            "Expected matching addresses\n");
1772         ok(csinfoA.cs.iSocketType == SOCK_STREAM, "Wrong socket type\n");
1773         ok(csinfoB.cs.iSocketType == SOCK_STREAM, "Wrong socket type\n");
1774         ok(csinfoA.cs.iProtocol == IPPROTO_TCP, "Wrong socket protocol\n");
1775         ok(csinfoB.cs.iProtocol == IPPROTO_TCP, "Wrong socket protocol\n");
1776 
1777         err = getpeername(s, (struct sockaddr *)&saddr, &size);
1778         ok(!err, "Expected 0, got %d\n", err);
1779         ok(!memcmp(&saddr, csinfoA.cs.RemoteAddr.lpSockaddr, size), "Expected matching addresses\n");
1780         ok(!memcmp(&saddr, csinfoB.cs.LocalAddr.lpSockaddr, size), "Expected matching addresses\n");
1781         err = getpeername(s2, (struct sockaddr *)&saddr, &size);
1782         ok(!err, "Expected 0, got %d\n", err);
1783         ok(!memcmp(&saddr, csinfoB.cs.RemoteAddr.lpSockaddr, size), "Expected matching addresses\n");
1784         ok(!memcmp(&saddr, csinfoA.cs.LocalAddr.lpSockaddr, size), "Expected matching addresses\n");
1785         err = getsockname(s, (struct sockaddr *)&saddr, &size);
1786         ok(!err, "Expected 0, got %d\n", err);
1787         ok(!memcmp(&saddr, csinfoA.cs.LocalAddr.lpSockaddr, size), "Expected matching addresses\n");
1788         ok(!memcmp(&saddr, csinfoB.cs.RemoteAddr.lpSockaddr, size), "Expected matching addresses\n");
1789         err = getsockname(s2, (struct sockaddr *)&saddr, &size);
1790         ok(!err, "Expected 0, got %d\n", err);
1791         ok(!memcmp(&saddr, csinfoB.cs.LocalAddr.lpSockaddr, size), "Expected matching addresses\n");
1792         ok(!memcmp(&saddr, csinfoA.cs.RemoteAddr.lpSockaddr, size), "Expected matching addresses\n");
1793 
1794         SetLastError(0xdeadbeef);
1795         size = sizeof(CSADDR_INFO);
1796         err = getsockopt(s, SOL_SOCKET, SO_BSP_STATE, (char *) &csinfoA, &size);
1797         ok(err, "Expected non-zero\n");
1798         ok(size == sizeof(CSADDR_INFO), "Got %d\n", size);
1799         ok(GetLastError() == WSAEFAULT, "Expected 10014, got %d\n", GetLastError());
1800 
1801         /* At least for IPv4 the size is exactly 56 bytes */
1802         size = sizeof(*csinfoA.cs.LocalAddr.lpSockaddr) * 2 + sizeof(csinfoA.cs);
1803         err = getsockopt(s, SOL_SOCKET, SO_BSP_STATE, (char *) &csinfoA, &size);
1804         ok(!err, "Expected 0, got %d\n", err);
1805         size--;
1806         SetLastError(0xdeadbeef);
1807         err = getsockopt(s, SOL_SOCKET, SO_BSP_STATE, (char *) &csinfoA, &size);
1808         ok(err, "Expected non-zero\n");
1809         ok(GetLastError() == WSAEFAULT, "Expected 10014, got %d\n", GetLastError());
1810     }
1811     else
1812         ok(GetLastError() == WSAENOPROTOOPT, "Expected 10042, got %d\n", GetLastError());
1813 
1814     closesocket(s);
1815     closesocket(s2);
1816 
1817     for (i = 0; i < 2; i++)
1818     {
1819         int family, level;
1820 
1821         if (i)
1822         {
1823             family = AF_INET6;
1824             level = IPPROTO_IPV6;
1825         }
1826         else
1827         {
1828             family = AF_INET;
1829             level = IPPROTO_IP;
1830         }
1831 
1832         s = socket(family, SOCK_DGRAM, 0);
1833         if (s == INVALID_SOCKET && i)
1834         {
1835             skip("IPv6 is not supported\n");
1836             break;
1837         }
1838         ok(s != INVALID_SOCKET, "socket failed with error %d\n", GetLastError());
1839 
1840         size = sizeof(value);
1841         value = 0xdead;
1842         err = getsockopt(s, level, IP_DONTFRAGMENT, (char *) &value, &size);
1843         ok(!err, "Expected 0, got %d with error %d\n", err, GetLastError());
1844         ok(value == 0, "Expected 0, got %d\n", value);
1845 
1846         size = sizeof(value);
1847         value = 1;
1848         err = setsockopt(s, level, IP_DONTFRAGMENT, (char *) &value, size);
1849         ok(!err, "Expected 0, got %d with error %d\n", err, GetLastError());
1850 
1851         value = 0xdead;
1852         err = getsockopt(s, level, IP_DONTFRAGMENT, (char *) &value, &size);
1853         ok(!err, "Expected 0, got %d with error %d\n", err, GetLastError());
1854         ok(value == 1, "Expected 1, got %d\n", value);
1855 
1856         size = sizeof(value);
1857         value = 0xdead;
1858         err = setsockopt(s, level, IP_DONTFRAGMENT, (char *) &value, size);
1859         ok(!err, "Expected 0, got %d with error %d\n", err, GetLastError());
1860 
1861         err = getsockopt(s, level, IP_DONTFRAGMENT, (char *) &value, &size);
1862         ok(!err, "Expected 0, got %d with error %d\n", err, GetLastError());
1863         ok(value == 1, "Expected 1, got %d\n", value);
1864 
1865         closesocket(s);
1866     }
1867 }
1868 
1869 static void test_so_reuseaddr(void)
1870 {
1871     struct sockaddr_in saddr;
1872     SOCKET s1,s2;
1873     unsigned int rc,reuse;
1874     int size;
1875     DWORD err;
1876 
1877     saddr.sin_family      = AF_INET;
1878     saddr.sin_port        = htons(SERVERPORT+1);
1879     saddr.sin_addr.s_addr = inet_addr("127.0.0.1");
1880 
1881     s1=socket(AF_INET, SOCK_STREAM, 0);
1882     ok(s1!=INVALID_SOCKET, "socket() failed error: %d\n", WSAGetLastError());
1883     rc = bind(s1, (struct sockaddr*)&saddr, sizeof(saddr));
1884     ok(rc!=SOCKET_ERROR, "bind(s1) failed error: %d\n", WSAGetLastError());
1885 
1886     s2=socket(AF_INET, SOCK_STREAM, 0);
1887     ok(s2!=INVALID_SOCKET, "socket() failed error: %d\n", WSAGetLastError());
1888 
1889     reuse=0x1234;
1890     size=sizeof(reuse);
1891     rc=getsockopt(s2, SOL_SOCKET, SO_REUSEADDR, (char*)&reuse, &size );
1892     ok(rc==0 && reuse==0,"wrong result in getsockopt(SO_REUSEADDR): rc=%d reuse=%d\n",rc,reuse);
1893 
1894     rc = bind(s2, (struct sockaddr*)&saddr, sizeof(saddr));
1895     ok(rc==SOCKET_ERROR, "bind() succeeded\n");
1896 
1897     reuse = 1;
1898     rc = setsockopt(s2, SOL_SOCKET, SO_REUSEADDR, (char*)&reuse, sizeof(reuse));
1899     ok(rc==0, "setsockopt() failed error: %d\n", WSAGetLastError());
1900 
1901     /* On Win2k3 and above, all SO_REUSEADDR seems to do is to allow binding to
1902      * a port immediately after closing another socket on that port, so
1903      * basically following the BSD socket semantics here. */
1904     rc = bind(s2, (struct sockaddr*)&saddr, sizeof(saddr));
1905     if(rc==0)
1906     {
1907         int s3=socket(AF_INET, SOCK_STREAM, 0), s4;
1908         trace("<= Win XP behavior of SO_REUSEADDR\n");
1909 
1910         /* If we could bind again in the same port this is Windows version <= XP.
1911          * Lets test if we can really connect to one of them. */
1912         set_blocking(s1, FALSE);
1913         set_blocking(s2, FALSE);
1914         rc = listen(s1, 1);
1915         ok(!rc, "listen() failed with error: %d\n", WSAGetLastError());
1916         rc = listen(s2, 1);
1917         ok(!rc, "listen() failed with error: %d\n", WSAGetLastError());
1918         rc = connect(s3, (struct sockaddr*)&saddr, sizeof(saddr));
1919         ok(!rc, "connecting to accepting socket failed %d\n", WSAGetLastError());
1920 
1921         /* the delivery of the connection is random so we need to try on both sockets */
1922         size = sizeof(saddr);
1923         s4 = accept(s1, (struct sockaddr*)&saddr, &size);
1924         if(s4 == INVALID_SOCKET)
1925             s4 = accept(s2, (struct sockaddr*)&saddr, &size);
1926         ok(s4 != INVALID_SOCKET, "none of the listening sockets could get the connection\n");
1927 
1928         closesocket(s1);
1929         closesocket(s3);
1930         closesocket(s4);
1931     }
1932     else
1933     {
1934         trace(">= Win 2003 behavior of SO_REUSEADDR\n");
1935         err = WSAGetLastError();
1936         ok(err==WSAEACCES, "expected 10013, got %d\n", err);
1937 
1938         closesocket(s1);
1939         rc = bind(s2, (struct sockaddr*)&saddr, sizeof(saddr));
1940         ok(rc==0, "bind() failed error: %d\n", WSAGetLastError());
1941     }
1942 
1943     closesocket(s2);
1944 }
1945 
1946 #define IP_PKTINFO_LEN (sizeof(WSACMSGHDR) + WSA_CMSG_ALIGN(sizeof(struct in_pktinfo)))
1947 
1948 static void test_ip_pktinfo(void)
1949 {
1950     ULONG addresses[2] = {inet_addr("127.0.0.1"), htonl(INADDR_ANY)};
1951     char recvbuf[10], pktbuf[512], msg[] = "HELLO";
1952     struct sockaddr_in s1addr, s2addr, s3addr;
1953     GUID WSARecvMsg_GUID = WSAID_WSARECVMSG;
1954     LPFN_WSARECVMSG pWSARecvMsg = NULL;
1955     unsigned int rc, yes = 1;
1956     BOOL foundhdr;
1957     DWORD dwBytes, dwSize, dwFlags;
1958     socklen_t addrlen;
1959     WSACMSGHDR *cmsg;
1960     WSAOVERLAPPED ov;
1961     WSABUF iovec[1];
1962     SOCKET s1, s2;
1963     WSAMSG hdr;
1964     int i, err;
1965 
1966     memset(&ov, 0, sizeof(ov));
1967     ov.hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
1968     if (ov.hEvent == INVALID_HANDLE_VALUE)
1969     {
1970         skip("Could not create event object, some tests will be skipped. errno = %d\n", GetLastError());
1971         return;
1972     }
1973 
1974     memset(&hdr, 0x00, sizeof(hdr));
1975     s1addr.sin_family = AF_INET;
1976     s1addr.sin_port   = htons(0);
1977     /* Note: s1addr.sin_addr is set below */
1978     iovec[0].buf      = recvbuf;
1979     iovec[0].len      = sizeof(recvbuf);
1980     hdr.name          = (struct sockaddr*)&s3addr;
1981     hdr.namelen       = sizeof(s3addr);
1982     hdr.lpBuffers     = &iovec[0];
1983     hdr.dwBufferCount = 1;
1984     hdr.Control.buf   = pktbuf;
1985     /* Note: hdr.Control.len is set below */
1986     hdr.dwFlags       = 0;
1987 
1988     for (i=0;i<sizeof(addresses)/sizeof(UINT32);i++)
1989     {
1990         s1addr.sin_addr.s_addr = addresses[i];
1991 
1992         /* Build "server" side socket */
1993         s1=socket(AF_INET, SOCK_DGRAM, 0);
1994         if (s1 == INVALID_SOCKET)
1995         {
1996             skip("socket() failed error, some tests skipped: %d\n", WSAGetLastError());
1997             goto cleanup;
1998         }
1999 
2000         /* Obtain the WSARecvMsg function */
2001         WSAIoctl(s1, SIO_GET_EXTENSION_FUNCTION_POINTER, &WSARecvMsg_GUID, sizeof(WSARecvMsg_GUID),
2002                  &pWSARecvMsg, sizeof(pWSARecvMsg), &dwBytes, NULL, NULL);
2003         if (!pWSARecvMsg)
2004         {
2005             win_skip("WSARecvMsg is unsupported, some tests will be skipped.\n");
2006             closesocket(s1);
2007             goto cleanup;
2008         }
2009 
2010         /* Setup the server side socket */
2011         rc=bind(s1, (struct sockaddr*)&s1addr, sizeof(s1addr));
2012         ok(rc != SOCKET_ERROR, "bind() failed error: %d\n", WSAGetLastError());
2013         rc=setsockopt(s1, IPPROTO_IP, IP_PKTINFO, (const char*)&yes, sizeof(yes));
2014         ok(rc == 0, "failed to set IPPROTO_IP flag IP_PKTINFO!\n");
2015 
2016         /* Build "client" side socket */
2017         addrlen = sizeof(s2addr);
2018         if (getsockname(s1, (struct sockaddr *) &s2addr, &addrlen) != 0)
2019         {
2020             skip("Failed to call getsockname, some tests skipped: %d\n", WSAGetLastError());
2021             closesocket(s1);
2022             goto cleanup;
2023         }
2024         s2addr.sin_addr.s_addr = addresses[0]; /* Always target the local adapter address */
2025         s2=socket(AF_INET, SOCK_DGRAM, 0);
2026         if (s2 == INVALID_SOCKET)
2027         {
2028             skip("socket() failed error, some tests skipped: %d\n", WSAGetLastError());
2029             closesocket(s1);
2030             goto cleanup;
2031         }
2032 
2033         /* Test an empty message header */
2034         rc=pWSARecvMsg(s1, NULL, NULL, NULL, NULL);
2035         err=WSAGetLastError();
2036         ok(rc == SOCKET_ERROR && err == WSAEFAULT, "WSARecvMsg() failed error: %d (ret = %d)\n", err, rc);
2037 
2038         /*
2039          * Send a packet from the client to the server and test for specifying
2040          * a short control header.
2041          */
2042         SetLastError(0xdeadbeef);
2043         rc=sendto(s2, msg, sizeof(msg), 0, (struct sockaddr*)&s2addr, sizeof(s2addr));
2044         ok(rc == sizeof(msg), "sendto() failed error: %d\n", WSAGetLastError());
2045         ok(GetLastError() == ERROR_SUCCESS, "Expected 0, got %d\n", GetLastError());
2046         hdr.Control.len = 1;
2047         rc=pWSARecvMsg(s1, &hdr, &dwSize, NULL, NULL);
2048         err=WSAGetLastError();
2049         ok(rc == SOCKET_ERROR && err == WSAEMSGSIZE && (hdr.dwFlags & MSG_CTRUNC),
2050            "WSARecvMsg() failed error: %d (ret: %d, flags: %d)\n", err, rc, hdr.dwFlags);
2051         hdr.dwFlags = 0; /* Reset flags */
2052 
2053         /* Perform another short control header test, this time with an overlapped receive */
2054         hdr.Control.len = 1;
2055         rc=pWSARecvMsg(s1, &hdr, NULL, &ov, NULL);
2056         err=WSAGetLastError();
2057         ok(rc != 0 && err == WSA_IO_PENDING, "WSARecvMsg() failed error: %d\n", err);
2058         SetLastError(0xdeadbeef);
2059         rc=sendto(s2, msg, sizeof(msg), 0, (struct sockaddr*)&s2addr, sizeof(s2addr));
2060         ok(rc == sizeof(msg), "sendto() failed error: %d\n", WSAGetLastError());
2061         ok(GetLastError() == ERROR_SUCCESS, "Expected 0, got %d\n", GetLastError());
2062         if (WaitForSingleObject(ov.hEvent, 100) != WAIT_OBJECT_0)
2063         {
2064             skip("Server side did not receive packet, some tests skipped.\n");
2065             closesocket(s2);
2066             closesocket(s1);
2067             continue;
2068         }
2069         dwFlags = 0;
2070         WSAGetOverlappedResult(s1, &ov, NULL, FALSE, &dwFlags);
2071         ok(dwFlags == 0,
2072            "WSAGetOverlappedResult() returned unexpected flags %d!\n", dwFlags);
2073         ok(hdr.dwFlags == MSG_CTRUNC,
2074            "WSARecvMsg() overlapped operation set unexpected flags %d.\n", hdr.dwFlags);
2075         hdr.dwFlags = 0; /* Reset flags */
2076 
2077         /*
2078          * Setup an overlapped receive, send a packet, then wait for the packet to be retrieved
2079          * on the server end and check that the returned packet matches what was sent.
2080          */
2081         hdr.Control.len = sizeof(pktbuf);
2082         rc=pWSARecvMsg(s1, &hdr, NULL, &ov, NULL);
2083         err=WSAGetLastError();
2084         ok(rc != 0 && err == WSA_IO_PENDING, "WSARecvMsg() failed error: %d\n", err);
2085         ok(hdr.Control.len == sizeof(pktbuf),
2086            "WSARecvMsg() control length mismatch (%d != sizeof pktbuf).\n", hdr.Control.len);
2087         rc=sendto(s2, msg, sizeof(msg), 0, (struct sockaddr*)&s2addr, sizeof(s2addr));
2088         ok(rc == sizeof(msg), "sendto() failed error: %d\n", WSAGetLastError());
2089         if (WaitForSingleObject(ov.hEvent, 100) != WAIT_OBJECT_0)
2090         {
2091             skip("Server side did not receive packet, some tests skipped.\n");
2092             closesocket(s2);
2093             closesocket(s1);
2094             continue;
2095         }
2096         dwSize = 0;
2097         WSAGetOverlappedResult(s1, &ov, &dwSize, FALSE, NULL);
2098         ok(dwSize == sizeof(msg),
2099            "WSARecvMsg() buffer length does not match transmitted data!\n");
2100         ok(strncmp(iovec[0].buf, msg, sizeof(msg)) == 0,
2101            "WSARecvMsg() buffer does not match transmitted data!\n");
2102         ok(hdr.Control.len == IP_PKTINFO_LEN,
2103            "WSARecvMsg() control length mismatch (%d).\n", hdr.Control.len);
2104 
2105         /* Test for the expected IP_PKTINFO return information. */
2106         foundhdr = FALSE;
2107         for (cmsg = WSA_CMSG_FIRSTHDR(&hdr); cmsg != NULL; cmsg = WSA_CMSG_NXTHDR(&hdr, cmsg))
2108         {
2109             if (cmsg->cmsg_level == IPPROTO_IP && cmsg->cmsg_type == IP_PKTINFO)
2110             {
2111                 struct in_pktinfo *pi = (struct in_pktinfo *)WSA_CMSG_DATA(cmsg);
2112 
2113                 ok(pi->ipi_addr.s_addr == s2addr.sin_addr.s_addr, "destination ip mismatch!\n");
2114                 foundhdr = TRUE;
2115             }
2116         }
2117         ok(foundhdr, "IP_PKTINFO header information was not returned!\n");
2118 
2119         closesocket(s2);
2120         closesocket(s1);
2121     }
2122 
2123 cleanup:
2124     CloseHandle(ov.hEvent);
2125 }
2126 
2127 /************* Array containing the tests to run **********/
2128 
2129 #define STD_STREAM_SOCKET \
2130             SOCK_STREAM, \
2131             0, \
2132             SERVERIP, \
2133             SERVERPORT
2134 
2135 static test_setup tests [] =
2136 {
2137     /* Test 0: synchronous client and server */
2138     {
2139         {
2140             STD_STREAM_SOCKET,
2141             2048,
2142             16,
2143             2
2144         },
2145         simple_server,
2146         {
2147             NULL,
2148             0,
2149             64
2150         },
2151         simple_client,
2152         {
2153             NULL,
2154             0,
2155             128
2156         }
2157     },
2158     /* Test 1: event-driven client, synchronous server */
2159     {
2160         {
2161             STD_STREAM_SOCKET,
2162             2048,
2163             16,
2164             2
2165         },
2166         simple_server,
2167         {
2168             NULL,
2169             0,
2170             64
2171         },
2172         event_client,
2173         {
2174             NULL,
2175             WSA_FLAG_OVERLAPPED,
2176             128
2177         }
2178     },
2179     /* Test 2: synchronous client, non-blocking server via select() */
2180     {
2181         {
2182             STD_STREAM_SOCKET,
2183             2048,
2184             16,
2185             2
2186         },
2187         select_server,
2188         {
2189             NULL,
2190             0,
2191             64
2192         },
2193         simple_client,
2194         {
2195             NULL,
2196             0,
2197             128
2198         }
2199     },
2200     /* Test 3: OOB client, OOB server */
2201     {
2202         {
2203             STD_STREAM_SOCKET,
2204             128,
2205             16,
2206             1
2207         },
2208         oob_server,
2209         {
2210             NULL,
2211             0,
2212             128
2213         },
2214         oob_client,
2215         {
2216             NULL,
2217             0,
2218             128
2219         }
2220     },
2221     /* Test 4: synchronous mixed client and server */
2222     {
2223         {
2224             STD_STREAM_SOCKET,
2225             2048,
2226             16,
2227             2
2228         },
2229         simple_server,
2230         {
2231             NULL,
2232             0,
2233             64
2234         },
2235         simple_mixed_client,
2236         {
2237             NULL,
2238             0,
2239             128
2240         }
2241     }
2242 };
2243 
2244 static void test_UDP(void)
2245 {
2246     /* This function tests UDP sendto() and recvfrom(). UDP is unreliable, so it is
2247        possible that this test fails due to dropped packets. */
2248 
2249     /* peer 0 receives data from all other peers */
2250     struct sock_info peer[NUM_UDP_PEERS];
2251     char buf[16];
2252     int ss, i, n_recv, n_sent;
2253 
2254     memset (buf,0,sizeof(buf));
2255     for ( i = NUM_UDP_PEERS - 1; i >= 0; i-- ) {
2256         ok ( ( peer[i].s = socket ( AF_INET, SOCK_DGRAM, 0 ) ) != INVALID_SOCKET, "UDP: socket failed\n" );
2257 
2258         peer[i].addr.sin_family         = AF_INET;
2259         peer[i].addr.sin_addr.s_addr    = inet_addr ( SERVERIP );
2260 
2261         if ( i == 0 ) {
2262             peer[i].addr.sin_port       = htons ( SERVERPORT );
2263         } else {
2264             peer[i].addr.sin_port       = htons ( 0 );
2265         }
2266 
2267         do_bind ( peer[i].s, (struct sockaddr *) &peer[i].addr, sizeof( peer[i].addr ) );
2268 
2269         /* test getsockname() to get peer's port */
2270         ss = sizeof ( peer[i].addr );
2271         ok ( getsockname ( peer[i].s, (struct sockaddr *) &peer[i].addr, &ss ) != SOCKET_ERROR, "UDP: could not getsockname()\n" );
2272         ok ( peer[i].addr.sin_port != htons ( 0 ), "UDP: bind() did not associate port\n" );
2273     }
2274 
2275     /* test getsockname() */
2276     ok ( peer[0].addr.sin_port == htons ( SERVERPORT ), "UDP: getsockname returned incorrect peer port\n" );
2277 
2278     for ( i = 1; i < NUM_UDP_PEERS; i++ ) {
2279         /* send client's ip */
2280         memcpy( buf, &peer[i].addr.sin_port, sizeof(peer[i].addr.sin_port) );
2281         n_sent = sendto ( peer[i].s, buf, sizeof(buf), 0, (struct sockaddr*) &peer[0].addr, sizeof(peer[0].addr) );
2282         ok ( n_sent == sizeof(buf), "UDP: sendto() sent wrong amount of data or socket error: %d\n", n_sent );
2283     }
2284 
2285     for ( i = 1; i < NUM_UDP_PEERS; i++ ) {
2286         n_recv = recvfrom ( peer[0].s, buf, sizeof(buf), 0,(struct sockaddr *) &peer[0].peer, &ss );
2287         ok ( n_recv == sizeof(buf), "UDP: recvfrom() received wrong amount of data or socket error: %d\n", n_recv );
2288         ok ( memcmp ( &peer[0].peer.sin_port, buf, sizeof(peer[0].addr.sin_port) ) == 0, "UDP: port numbers do not match\n" );
2289     }
2290 }
2291 
2292 static DWORD WINAPI do_getservbyname( void *param )
2293 {
2294     struct {
2295         const char *name;
2296         const char *proto;
2297         int port;
2298     } serv[2] = { {"domain", "udp", 53}, {"telnet", "tcp", 23} };
2299 
2300     HANDLE *starttest = param;
2301     int i, j;
2302     struct servent *pserv[2];
2303 
2304     ok ( WaitForSingleObject ( *starttest, TEST_TIMEOUT * 1000 ) != WAIT_TIMEOUT,
2305          "test_getservbyname: timeout waiting for start signal\n" );
2306 
2307     /* ensure that necessary buffer resizes are completed */
2308     for ( j = 0; j < 2; j++) {
2309         pserv[j] = getservbyname ( serv[j].name, serv[j].proto );
2310     }
2311 
2312     for ( i = 0; i < NUM_QUERIES / 2; i++ ) {
2313         for ( j = 0; j < 2; j++ ) {
2314             pserv[j] = getservbyname ( serv[j].name, serv[j].proto );
2315             ok ( pserv[j] != NULL || broken(pserv[j] == NULL) /* win8, fixed in win81 */,
2316                  "getservbyname could not retrieve information for %s: %d\n", serv[j].name, WSAGetLastError() );
2317             if ( !pserv[j] ) continue;
2318             ok ( pserv[j]->s_port == htons(serv[j].port),
2319                  "getservbyname returned the wrong port for %s: %d\n", serv[j].name, ntohs(pserv[j]->s_port) );
2320             ok ( !strcmp ( pserv[j]->s_proto, serv[j].proto ),
2321                  "getservbyname returned the wrong protocol for %s: %s\n", serv[j].name, pserv[j]->s_proto );
2322             ok ( !strcmp ( pserv[j]->s_name, serv[j].name ),
2323                  "getservbyname returned the wrong name for %s: %s\n", serv[j].name, pserv[j]->s_name );
2324         }
2325 
2326         ok ( pserv[0] == pserv[1] || broken(pserv[0] != pserv[1]) /* win8, fixed in win81 */,
2327              "getservbyname: winsock resized servent buffer when not necessary\n" );
2328     }
2329 
2330     return 0;
2331 }
2332 
2333 static void test_getservbyname(void)
2334 {
2335     int i;
2336     HANDLE starttest, thread[NUM_THREADS];
2337     DWORD thread_id[NUM_THREADS];
2338 
2339     starttest = CreateEventA ( NULL, 1, 0, "test_getservbyname_starttest" );
2340 
2341     /* create threads */
2342     for ( i = 0; i < NUM_THREADS; i++ ) {
2343         thread[i] = CreateThread ( NULL, 0, do_getservbyname, &starttest, 0, &thread_id[i] );
2344     }
2345 
2346     /* signal threads to start */
2347     SetEvent ( starttest );
2348 
2349     for ( i = 0; i < NUM_THREADS; i++) {
2350         WaitForSingleObject ( thread[i], TEST_TIMEOUT * 1000 );
2351     }
2352 }
2353 
2354 static void test_WSASocket(void)
2355 {
2356     SOCKET sock = INVALID_SOCKET;
2357     WSAPROTOCOL_INFOA *pi;
2358     int wsaproviders[] = {IPPROTO_TCP, IPPROTO_IP};
2359     int autoprotocols[] = {IPPROTO_TCP, IPPROTO_UDP};
2360     int items, err, size, socktype, i, j;
2361     UINT pi_size;
2362 
2363     SetLastError(0xdeadbeef);
2364     ok(WSASocketA(0, 0, 0, NULL, 0, 0) == INVALID_SOCKET,
2365        "WSASocketA should have failed\n");
2366     err = WSAGetLastError();
2367     ok(err == WSAEINVAL, "Expected 10022, received %d\n", err);
2368 
2369     sock = WSASocketA(AF_INET, 0, 0, NULL, 0, 0);
2370     ok(sock != INVALID_SOCKET, "WSASocketA should have succeeded\n");
2371     closesocket(sock);
2372 
2373     sock = WSASocketA(AF_INET, SOCK_STREAM, 0, NULL, 0, 0);
2374     ok(sock != INVALID_SOCKET, "WSASocketA should have succeeded\n");
2375     closesocket(sock);
2376 
2377     SetLastError(0xdeadbeef);
2378     ok(WSASocketA(0, SOCK_STREAM, -1, NULL, 0, 0) == INVALID_SOCKET,
2379        "WSASocketA should have failed\n");
2380     err = WSAGetLastError();
2381     ok(err == WSAEPROTONOSUPPORT, "Expected 10043, received %d\n", err);
2382 
2383     SetLastError(0xdeadbeef);
2384     ok(WSASocketA(0, -1, IPPROTO_UDP, NULL, 0, 0) == INVALID_SOCKET,
2385        "WSASocketA should have failed\n");
2386     err = WSAGetLastError();
2387     ok(err == WSAESOCKTNOSUPPORT, "Expected 10044, received %d\n", err);
2388 
2389     SetLastError(0xdeadbeef);
2390     ok(WSASocketA(0, -1, 0, NULL, 0, 0) == INVALID_SOCKET,
2391        "WSASocketA should have failed\n");
2392     err = WSAGetLastError();
2393     ok(err == WSAEINVAL, "Expected 10022, received %d\n", err);
2394 
2395     SetLastError(0xdeadbeef);
2396     ok(WSASocketA(AF_INET, -1, 0, NULL, 0, 0) == INVALID_SOCKET,
2397        "WSASocketA should have failed\n");
2398     err = WSAGetLastError();
2399     ok(err == WSAESOCKTNOSUPPORT, "Expected 10044, received %d\n", err);
2400 
2401     SetLastError(0xdeadbeef);
2402     ok(WSASocketA(AF_INET, 0, -1, NULL, 0, 0) == INVALID_SOCKET,
2403        "WSASocketA should have failed\n");
2404     err = WSAGetLastError();
2405     ok(err == WSAEPROTONOSUPPORT, "Expected 10043, received %d\n", err);
2406 
2407     SetLastError(0xdeadbeef);
2408     ok(WSASocketA(0, -1, -1, NULL, 0, 0) == INVALID_SOCKET,
2409        "WSASocketA should have failed\n");
2410     err = WSAGetLastError();
2411     ok(err == WSAESOCKTNOSUPPORT, "Expected 10044, received %d\n", err);
2412 
2413     SetLastError(0xdeadbeef);
2414     ok(WSASocketA(-1, SOCK_STREAM, IPPROTO_UDP, NULL, 0, 0) == INVALID_SOCKET,
2415        "WSASocketA should have failed\n");
2416     err = WSAGetLastError();
2417     ok(err == WSAEAFNOSUPPORT, "Expected 10047, received %d\n", err);
2418 
2419     sock = WSASocketA(AF_INET, 0, IPPROTO_TCP, NULL, 0, 0);
2420     ok(sock != INVALID_SOCKET, "WSASocketA should have succeeded\n");
2421     closesocket(sock);
2422 
2423     SetLastError(0xdeadbeef);
2424     ok(WSASocketA(0, SOCK_STREAM, 0, NULL, 0, 0) == INVALID_SOCKET,
2425        "WSASocketA should have failed\n");
2426     err = WSAGetLastError();
2427     ok(err == WSAEINVAL, "Expected 10022, received %d\n", err);
2428 
2429     SetLastError(0xdeadbeef);
2430     ok(WSASocketA(0, 0, 0xdead, NULL, 0, 0) == INVALID_SOCKET,
2431        "WSASocketA should have failed\n");
2432     err = WSAGetLastError();
2433     ok(err == WSAEPROTONOSUPPORT, "Expected 10043, received %d\n", err);
2434 
2435     SetLastError(0xdeadbeef);
2436     ok(WSASocketA(AF_INET, 0xdead, 0, NULL, 0, 0) == INVALID_SOCKET,
2437        "WSASocketA should have failed\n");
2438     err = WSAGetLastError();
2439     ok(err == WSAESOCKTNOSUPPORT, "Expected 10044, received %d\n", err);
2440 
2441     SetLastError(0xdeadbeef);
2442     ok(WSASocketA(0, 0xdead, 0, NULL, 0, 0) == INVALID_SOCKET,
2443        "WSASocketA should have failed\n");
2444     err = WSAGetLastError();
2445     ok(err == WSAEINVAL, "Expected 10022, received %d\n", err);
2446 
2447     sock = WSASocketA(0, 0, IPPROTO_TCP, NULL, 0, 0);
2448     ok(sock != INVALID_SOCKET, "WSASocketA should have succeeded\n");
2449     closesocket(sock);
2450 
2451     /* SOCK_STREAM does not support IPPROTO_UDP */
2452     SetLastError(0xdeadbeef);
2453     ok(WSASocketA(AF_INET, SOCK_STREAM, IPPROTO_UDP, NULL, 0, 0) == INVALID_SOCKET,
2454        "WSASocketA should have failed\n");
2455     err = WSAGetLastError();
2456     ok(err == WSAEPROTONOSUPPORT, "Expected 10043, received %d\n", err);
2457 
2458     /* SOCK_DGRAM does not support IPPROTO_TCP */
2459     SetLastError(0xdeadbeef);
2460     ok(WSASocketA(AF_INET, SOCK_DGRAM, IPPROTO_TCP, NULL, 0, 0) == INVALID_SOCKET,
2461        "WSASocketA should have failed\n");
2462     err = WSAGetLastError();
2463     ok(err == WSAEPROTONOSUPPORT, "Expected 10043, received %d\n", err);
2464 
2465     /* Set pi_size explicitly to a value below 2*sizeof(WSAPROTOCOL_INFOA)
2466      * to avoid a crash on win98.
2467      */
2468     pi_size = 0;
2469     items = WSAEnumProtocolsA(wsaproviders, NULL, &pi_size);
2470     ok(items == SOCKET_ERROR, "WSAEnumProtocolsA({6,0}, NULL, 0) returned %d\n",
2471             items);
2472     err = WSAGetLastError();
2473     ok(err == WSAENOBUFS, "WSAEnumProtocolsA error is %d, not WSAENOBUFS(%d)\n",
2474             err, WSAENOBUFS);
2475 
2476     pi = HeapAlloc(GetProcessHeap(), 0, pi_size);
2477     ok(pi != NULL, "Failed to allocate memory\n");
2478     if (pi == NULL) {
2479         skip("Can't continue without memory.\n");
2480         return;
2481     }
2482 
2483     items = WSAEnumProtocolsA(wsaproviders, pi, &pi_size);
2484     ok(items != SOCKET_ERROR, "WSAEnumProtocolsA failed, last error is %d\n",
2485             WSAGetLastError());
2486 
2487     if (items == 0) {
2488         skip("No protocols enumerated.\n");
2489         HeapFree(GetProcessHeap(), 0, pi);
2490         return;
2491     }
2492 
2493     sock = WSASocketA(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
2494                       FROM_PROTOCOL_INFO, &pi[0], 0, 0);
2495     ok(sock != INVALID_SOCKET, "Failed to create socket: %d\n",
2496             WSAGetLastError());
2497     closesocket(sock);
2498 
2499     /* find what parameters are used first: plain parameters or protocol info struct */
2500     pi[0].iProtocol = -1;
2501     pi[0].iSocketType = -1;
2502     pi[0].iAddressFamily = -1;
2503     ok(WSASocketA(0, 0, IPPROTO_UDP, &pi[0], 0, 0) == INVALID_SOCKET,
2504        "WSASocketA should have failed\n");
2505     err = WSAGetLastError();
2506     ok(err == WSAEAFNOSUPPORT, "Expected 10047, received %d\n", err);
2507 
2508     pi[0].iProtocol = 0;
2509     pi[0].iSocketType = 0;
2510     pi[0].iAddressFamily = 0;
2511     sock = WSASocketA(0, 0, IPPROTO_UDP, &pi[0], 0, 0);
2512     if(sock != INVALID_SOCKET)
2513     {
2514       win_skip("must work only in OS <= 2003\n");
2515       closesocket(sock);
2516     }
2517     else
2518     {
2519       err = WSAGetLastError();
2520       ok(err == WSAEAFNOSUPPORT, "Expected 10047, received %d\n", err);
2521     }
2522 
2523     pi[0].iProtocol = IPPROTO_UDP;
2524     pi[0].iSocketType = SOCK_DGRAM;
2525     pi[0].iAddressFamily = AF_INET;
2526     sock = WSASocketA(0, 0, 0, &pi[0], 0, 0);
2527     ok(sock != INVALID_SOCKET, "Failed to create socket: %d\n",
2528             WSAGetLastError());
2529     size = sizeof(socktype);
2530     socktype = 0xdead;
2531     err = getsockopt(sock, SOL_SOCKET, SO_TYPE, (char *) &socktype, &size);
2532     ok(!err,"getsockopt failed with %d\n", WSAGetLastError());
2533     ok(socktype == SOCK_DGRAM, "Wrong socket type, expected %d received %d\n",
2534        SOCK_DGRAM, socktype);
2535     closesocket(sock);
2536 
2537     sock = WSASocketA(AF_INET, SOCK_STREAM, IPPROTO_TCP, &pi[0], 0, 0);
2538     ok(sock != INVALID_SOCKET, "Failed to create socket: %d\n",
2539             WSAGetLastError());
2540     size = sizeof(socktype);
2541     socktype = 0xdead;
2542     err = getsockopt(sock, SOL_SOCKET, SO_TYPE, (char *) &socktype, &size);
2543     ok(!err,"getsockopt failed with %d\n", WSAGetLastError());
2544     ok(socktype == SOCK_STREAM, "Wrong socket type, expected %d received %d\n",
2545        SOCK_STREAM, socktype);
2546     closesocket(sock);
2547 
2548     HeapFree(GetProcessHeap(), 0, pi);
2549 
2550     pi_size = 0;
2551     items = WSAEnumProtocolsA(NULL, NULL, &pi_size);
2552     ok(items == SOCKET_ERROR, "WSAEnumProtocolsA(NULL, NULL, 0) returned %d\n",
2553             items);
2554     err = WSAGetLastError();
2555     ok(err == WSAENOBUFS, "WSAEnumProtocolsA error is %d, not WSAENOBUFS(%d)\n",
2556             err, WSAENOBUFS);
2557 
2558     pi = HeapAlloc(GetProcessHeap(), 0, pi_size);
2559     ok(pi != NULL, "Failed to allocate memory\n");
2560     if (pi == NULL) {
2561         skip("Can't continue without memory.\n");
2562         return;
2563     }
2564 
2565     items = WSAEnumProtocolsA(NULL, pi, &pi_size);
2566     ok(items != SOCKET_ERROR, "WSAEnumProtocolsA failed, last error is %d\n",
2567             WSAGetLastError());
2568 
2569     /* when no protocol and socket type are specified the first entry
2570      * from WSAEnumProtocols that has the flag PFL_MATCHES_PROTOCOL_ZERO
2571      * is returned */
2572     sock = WSASocketA(AF_INET, 0, 0, NULL, 0, 0);
2573     ok(sock != INVALID_SOCKET, "Failed to create socket: %d\n",
2574             WSAGetLastError());
2575 
2576     size = sizeof(socktype);
2577     socktype = 0xdead;
2578     err = getsockopt(sock, SOL_SOCKET, SO_TYPE, (char *) &socktype, &size);
2579     ok(!err, "getsockopt failed with %d\n", WSAGetLastError());
2580     for(i = 0; i < items; i++)
2581     {
2582         if(pi[i].dwProviderFlags & PFL_MATCHES_PROTOCOL_ZERO)
2583         {
2584             ok(socktype == pi[i].iSocketType, "Wrong socket type, expected %d received %d\n",
2585                pi[i].iSocketType, socktype);
2586              break;
2587         }
2588     }
2589     ok(i != items, "Creating a socket without protocol and socket type didn't work\n");
2590     closesocket(sock);
2591 
2592     /* when no socket type is specified the first entry from WSAEnumProtocols
2593      * that matches the protocol is returned */
2594     for (i = 0; i < sizeof(autoprotocols) / sizeof(autoprotocols[0]); i++)
2595     {
2596         sock = WSASocketA(0, 0, autoprotocols[i], NULL, 0, 0);
2597         ok(sock != INVALID_SOCKET, "Failed to create socket for protocol %d, received %d\n",
2598                 autoprotocols[i], WSAGetLastError());
2599 
2600         size = sizeof(socktype);
2601         socktype = 0xdead;
2602         err = getsockopt(sock, SOL_SOCKET, SO_TYPE, (char *) &socktype, &size);
2603         ok(!err, "getsockopt failed with %d\n", WSAGetLastError());
2604 
2605         for (err = 1, j = 0; j < items; j++)
2606         {
2607             if (pi[j].iProtocol == autoprotocols[i])
2608             {
2609                 if (socktype == pi[j].iSocketType)
2610                     err = 0;
2611                 else
2612                     ok(0, "Wrong socket type, expected %d received %d\n",
2613                        pi[j].iSocketType, socktype);
2614                 break;
2615             }
2616         }
2617         ok(!err, "Protocol %d not found in WSAEnumProtocols\n", autoprotocols[i]);
2618 
2619         closesocket(sock);
2620     }
2621 
2622     HeapFree(GetProcessHeap(), 0, pi);
2623 
2624     SetLastError(0xdeadbeef);
2625     /* starting on vista the socket function returns error during the socket
2626        creation and no longer in the socket operations (sendto, readfrom) */
2627     sock = WSASocketA(AF_INET, SOCK_RAW, IPPROTO_ICMP, NULL, 0, 0);
2628     if (sock == INVALID_SOCKET)
2629     {
2630         err = WSAGetLastError();
2631         ok(err == WSAEACCES, "Expected 10013, received %d\n", err);
2632         skip("SOCK_RAW is not supported\n");
2633     }
2634     else
2635     {
2636         trace("SOCK_RAW is supported\n");
2637 
2638         size = sizeof(socktype);
2639         socktype = 0xdead;
2640         err = getsockopt(sock, SOL_SOCKET, SO_TYPE, (char *) &socktype, &size);
2641         ok(!err, "getsockopt failed with %d\n", WSAGetLastError());
2642         ok(socktype == SOCK_RAW, "Wrong socket type, expected %d received %d\n",
2643            SOCK_RAW, socktype);
2644         closesocket(sock);
2645 
2646         todo_wine {
2647         sock = WSASocketA(0, 0, IPPROTO_RAW, NULL, 0, 0);
2648         ok(sock != INVALID_SOCKET, "Failed to create socket: %d\n",
2649            WSAGetLastError());
2650         size = sizeof(socktype);
2651         socktype = 0xdead;
2652         err = getsockopt(sock, SOL_SOCKET, SO_TYPE, (char *) &socktype, &size);
2653         ok(!err, "getsockopt failed with %d\n", WSAGetLastError());
2654         ok(socktype == SOCK_RAW, "Wrong socket type, expected %d received %d\n",
2655            SOCK_RAW, socktype);
2656         closesocket(sock);
2657         }
2658 
2659         sock = WSASocketA(AF_INET, SOCK_RAW, IPPROTO_TCP, NULL, 0, 0);
2660         ok(sock != INVALID_SOCKET, "Failed to create socket: %d\n",
2661            WSAGetLastError());
2662         size = sizeof(socktype);
2663         socktype = 0xdead;
2664         err = getsockopt(sock, SOL_SOCKET, SO_TYPE, (char *) &socktype, &size);
2665         ok(!err, "getsockopt failed with %d\n", WSAGetLastError());
2666         ok(socktype == SOCK_RAW, "Wrong socket type, expected %d received %d\n",
2667            SOCK_RAW, socktype);
2668         closesocket(sock);
2669     }
2670 
2671     /* IPX socket tests */
2672 
2673     SetLastError(0xdeadbeef);
2674     sock = WSASocketA(AF_IPX, SOCK_DGRAM, NSPROTO_IPX, NULL, 0, 0);
2675     if (sock == INVALID_SOCKET)
2676     {
2677         err = WSAGetLastError();
2678         todo_wine_if (err == WSAEPROTONOSUPPORT)
2679         ok(err == WSAEAFNOSUPPORT || broken(err == WSAEPROTONOSUPPORT), "Expected 10047, received %d\n", err);
2680         skip("IPX is not supported\n");
2681     }
2682     else
2683     {
2684         WSAPROTOCOL_INFOA info;
2685         closesocket(sock);
2686 
2687         trace("IPX is supported\n");
2688 
2689         sock = WSASocketA(0, 0, NSPROTO_IPX, NULL, 0, 0);
2690         ok(sock != INVALID_SOCKET, "Failed to create socket: %d\n",
2691                 WSAGetLastError());
2692 
2693         size = sizeof(socktype);
2694         socktype = 0xdead;
2695         err = getsockopt(sock, SOL_SOCKET, SO_TYPE, (char *) &socktype, &size);
2696         ok(!err,"getsockopt failed with %d\n", WSAGetLastError());
2697         ok(socktype == SOCK_DGRAM, "Wrong socket type, expected %d received %d\n",
2698            SOCK_DGRAM, socktype);
2699 
2700         /* check socket family, type and protocol */
2701         size = sizeof(WSAPROTOCOL_INFOA);
2702         err = getsockopt(sock, SOL_SOCKET, SO_PROTOCOL_INFOA, (char *) &info, &size);
2703         ok(!err,"getsockopt failed with %d\n", WSAGetLastError());
2704         ok(info.iProtocol == NSPROTO_IPX, "expected protocol %d, received %d\n",
2705            NSPROTO_IPX, info.iProtocol);
2706         ok(info.iAddressFamily == AF_IPX, "expected family %d, received %d\n",
2707            AF_IPX, info.iProtocol);
2708         ok(info.iSocketType == SOCK_DGRAM, "expected type %d, received %d\n",
2709            SOCK_DGRAM, info.iSocketType);
2710         closesocket(sock);
2711 
2712         /* SOCK_STREAM does not support NSPROTO_IPX */
2713         SetLastError(0xdeadbeef);
2714         ok(WSASocketA(AF_IPX, SOCK_STREAM, NSPROTO_IPX, NULL, 0, 0) == INVALID_SOCKET,
2715            "WSASocketA should have failed\n");
2716         err = WSAGetLastError();
2717         ok(err == WSAEPROTONOSUPPORT, "Expected 10043, received %d\n", err);
2718 
2719         /* test extended IPX support - that is adding any number between 0 and 255
2720          * to the IPX protocol value will make it be used as IPX packet type */
2721         for(i = 0;i <= 255;i += 17)
2722         {
2723           SetLastError(0xdeadbeef);
2724           sock = WSASocketA(0, 0, NSPROTO_IPX + i, NULL, 0, 0);
2725           ok(sock != INVALID_SOCKET, "Failed to create socket: %d\n",
2726                   WSAGetLastError());
2727 
2728           size = sizeof(int);
2729           socktype = -1;
2730           err = getsockopt(sock, NSPROTO_IPX, IPX_PTYPE, (char *) &socktype, &size);
2731           ok(!err, "getsockopt failed with %d\n", WSAGetLastError());
2732           ok(socktype == i, "Wrong IPX packet type, expected %d received %d\n",
2733              i, socktype);
2734 
2735           closesocket(sock);
2736         }
2737     }
2738 }
2739 
2740 static void test_WSADuplicateSocket(void)
2741 {
2742     SOCKET source, dupsock;
2743     WSAPROTOCOL_INFOA info;
2744     DWORD err;
2745     struct sockaddr_in addr;
2746     int socktype, size, addrsize, ret;
2747     char teststr[] = "TEST", buffer[16];
2748 
2749     source = WSASocketA(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, 0);
2750     ok(source != INVALID_SOCKET, "WSASocketA should have succeeded\n");
2751 
2752     /* test invalid parameters */
2753     SetLastError(0xdeadbeef);
2754     ok(WSADuplicateSocketA(0, 0, NULL), "WSADuplicateSocketA should have failed\n");
2755     err = WSAGetLastError();
2756     ok(err == WSAENOTSOCK, "expected 10038, received %d\n", err);
2757 
2758     SetLastError(0xdeadbeef);
2759     ok(WSADuplicateSocketA(source, 0, NULL),
2760        "WSADuplicateSocketA should have failed\n");
2761     err = WSAGetLastError();
2762     ok(err == WSAEINVAL, "expected 10022, received %d\n", err);
2763 
2764     SetLastError(0xdeadbeef);
2765     ok(WSADuplicateSocketA(source, ~0, &info),
2766        "WSADuplicateSocketA should have failed\n");
2767     err = WSAGetLastError();
2768     ok(err == WSAEINVAL, "expected 10022, received %d\n", err);
2769 
2770     SetLastError(0xdeadbeef);
2771     ok(WSADuplicateSocketA(0, GetCurrentProcessId(), &info),
2772        "WSADuplicateSocketA should have failed\n");
2773     err = WSAGetLastError();
2774     ok(err == WSAENOTSOCK, "expected 10038, received %d\n", err);
2775 
2776     SetLastError(0xdeadbeef);
2777     ok(WSADuplicateSocketA(source, GetCurrentProcessId(), NULL),
2778        "WSADuplicateSocketA should have failed\n");
2779     err = WSAGetLastError();
2780     ok(err == WSAEFAULT, "expected 10014, received %d\n", err);
2781 
2782     /* test returned structure */
2783     memset(&info, 0, sizeof(info));
2784     ok(!WSADuplicateSocketA(source, GetCurrentProcessId(), &info),
2785        "WSADuplicateSocketA should have worked\n");
2786 
2787     ok(info.iProtocol == IPPROTO_TCP, "expected protocol %d, received %d\n",
2788        IPPROTO_TCP, info.iProtocol);
2789     ok(info.iAddressFamily == AF_INET, "expected family %d, received %d\n",
2790        AF_INET, info.iProtocol);
2791     ok(info.iSocketType == SOCK_STREAM, "expected type %d, received %d\n",
2792        SOCK_STREAM, info.iSocketType);
2793 
2794     dupsock = WSASocketA(0, 0, 0, &info, 0, 0);
2795     ok(dupsock != INVALID_SOCKET, "WSASocketA should have succeeded\n");
2796 
2797     closesocket(dupsock);
2798     closesocket(source);
2799 
2800     /* create a socket, bind it, duplicate it then send data on source and
2801      * receive in the duplicated socket */
2802     source = WSASocketA(AF_INET, SOCK_DGRAM, IPPROTO_UDP, NULL, 0, 0);
2803     ok(source != INVALID_SOCKET, "WSASocketA should have succeeded\n");
2804 
2805     memset(&info, 0, sizeof(info));
2806     ok(!WSADuplicateSocketA(source, GetCurrentProcessId(), &info),
2807        "WSADuplicateSocketA should have worked\n");
2808 
2809     ok(info.iProtocol == IPPROTO_UDP, "expected protocol %d, received %d\n",
2810        IPPROTO_UDP, info.iProtocol);
2811     ok(info.iAddressFamily == AF_INET, "expected family %d, received %d\n",
2812        AF_INET, info.iProtocol);
2813     ok(info.iSocketType == SOCK_DGRAM, "expected type %d, received %d\n",
2814        SOCK_DGRAM, info.iSocketType);
2815 
2816     memset(&addr, 0, sizeof(addr));
2817     addr.sin_family = AF_INET;
2818     addr.sin_addr.s_addr = inet_addr("127.0.0.1");
2819     ok(!bind(source, (struct sockaddr*)&addr, sizeof(addr)),
2820        "bind should have worked\n");
2821 
2822     /* read address to find out the port number to be used in sendto */
2823     memset(&addr, 0, sizeof(addr));
2824     addrsize = sizeof(addr);
2825     ok(!getsockname(source, (struct sockaddr *) &addr, &addrsize),
2826        "getsockname should have worked\n");
2827     ok(addr.sin_port, "socket port should be != 0\n");
2828 
2829     dupsock = WSASocketA(0, 0, 0, &info, 0, 0);
2830     ok(dupsock != INVALID_SOCKET, "WSASocketA should have succeeded\n");
2831 
2832     size = sizeof(int);
2833     ret = getsockopt(dupsock, SOL_SOCKET, SO_TYPE, (char *) &socktype, &size);
2834     ok(!ret, "getsockopt failed with %d\n", WSAGetLastError());
2835     ok(socktype == SOCK_DGRAM, "Wrong socket type, expected %d received %d\n",
2836        SOCK_DGRAM, socktype);
2837 
2838     set_blocking(source, TRUE);
2839 
2840     /* send data on source socket */
2841     addrsize = sizeof(addr);
2842     size = sendto(source, teststr, sizeof(teststr), 0, (struct sockaddr *) &addr, addrsize);
2843     ok(size == sizeof(teststr), "got %d (err %d)\n", size, WSAGetLastError());
2844 
2845     /* receive on duplicated socket */
2846     addrsize = sizeof(addr);
2847     memset(buffer, 0, sizeof(buffer));
2848     size = recvfrom(dupsock, buffer, sizeof(teststr), 0, (struct sockaddr *) &addr, &addrsize);
2849     ok(size == sizeof(teststr), "got %d (err %d)\n", size, WSAGetLastError());
2850     buffer[sizeof(teststr) - 1] = 0;
2851     ok(!strcmp(buffer, teststr), "expected '%s', received '%s'\n", teststr, buffer);
2852 
2853     closesocket(dupsock);
2854     closesocket(source);
2855 
2856     /* show that the source socket need to be bound before the duplicated
2857      * socket is created */
2858     source = WSASocketA(AF_INET, SOCK_DGRAM, IPPROTO_UDP, NULL, 0, 0);
2859     ok(source != INVALID_SOCKET, "WSASocketA should have succeeded\n");
2860 
2861     memset(&info, 0, sizeof(info));
2862     ok(!WSADuplicateSocketA(source, GetCurrentProcessId(), &info),
2863        "WSADuplicateSocketA should have worked\n");
2864 
2865     dupsock = WSASocketA(0, 0, 0, &info, 0, 0);
2866     ok(dupsock != INVALID_SOCKET, "WSASocketA should have succeeded\n");
2867 
2868     memset(&addr, 0, sizeof(addr));
2869     addr.sin_family = AF_INET;
2870     addr.sin_addr.s_addr = inet_addr("127.0.0.1");
2871     ok(!bind(source, (struct sockaddr*)&addr, sizeof(addr)),
2872        "bind should have worked\n");
2873 
2874     /* read address to find out the port number to be used in sendto */
2875     memset(&addr, 0, sizeof(addr));
2876     addrsize = sizeof(addr);
2877     ok(!getsockname(source, (struct sockaddr *) &addr, &addrsize),
2878        "getsockname should have worked\n");
2879     ok(addr.sin_port, "socket port should be != 0\n");
2880 
2881     set_blocking(source, TRUE);
2882 
2883     addrsize = sizeof(addr);
2884     size = sendto(source, teststr, sizeof(teststr), 0, (struct sockaddr *) &addr, addrsize);
2885     ok(size == sizeof(teststr), "got %d (err %d)\n", size, WSAGetLastError());
2886 
2887     SetLastError(0xdeadbeef);
2888     addrsize = sizeof(addr);
2889     memset(buffer, 0, sizeof(buffer));
2890     todo_wine {
2891     ok(recvfrom(dupsock, buffer, sizeof(teststr), 0, (struct sockaddr *) &addr, &addrsize) == -1,
2892        "recvfrom should have failed\n");
2893     err = WSAGetLastError();
2894     ok(err == WSAEINVAL, "expected 10022, received %d\n", err);
2895     }
2896 
2897     closesocket(dupsock);
2898     closesocket(source);
2899 }
2900 
2901 static void test_WSAEnumNetworkEvents(void)
2902 {
2903     SOCKET s, s2;
2904     int sock_type[] = {SOCK_STREAM, SOCK_DGRAM, SOCK_STREAM}, i, j, k, l;
2905     struct sockaddr_in address;
2906     HANDLE event;
2907     WSANETWORKEVENTS net_events;
2908     /* Windows 2000 Pro without SP installed (testbot) will crash if
2909      * WSAEnumNetworkEvents have a NULL event, so skip this test in <= 2000 */
2910     DWORD ver = GetVersion() & 0xFFFF;
2911     BOOL supports_null = ((ver & 0xFF) << 8 | (ver >> 8)) > 0x0500;
2912 
2913     memset(&address, 0, sizeof(address));
2914     address.sin_addr.s_addr = htonl(INADDR_ANY);
2915     address.sin_family = AF_INET;
2916 
2917     /* This test follows the steps from bugs 10204 and 24946 */
2918     for (l = 0; l < 2; l++)
2919     {
2920         if (l == 1 && !supports_null && broken(1)) continue;
2921 
2922         for (i = 0; i < sizeof(sock_type) / sizeof(sock_type[0]); i++)
2923         {
2924             if (i == 2)
2925                 ok(!tcp_socketpair(&s, &s2), "Test[%d]: creating socket pair failed\n", i);
2926             else
2927             {
2928                 s = socket(AF_INET, sock_type[i], 0);
2929                 ok (s != SOCKET_ERROR, "Test[%d]: failed to create socket\n", i);
2930                 ok (!bind(s, (struct sockaddr*) &address, sizeof(address)), "Test[%d]: bind failed\n", i);
2931             }
2932             event = WSACreateEvent();
2933             ok (event != NULL, "Test[%d]: failed to create event\n", i);
2934             for (j = 0; j < 5; j++) /* Repeat sometimes and the result must be the same */
2935             {
2936                 /* When the TCP socket is not connected NO events will be returned.
2937                  * When connected and no data pending it will get the write event.
2938                  * UDP sockets don't have connections so as soon as they are bound
2939                  * they can read/write data. Since nobody is sendind us data only
2940                  * the write event will be returned and ONLY once.
2941                  */
2942                 ok (!WSAEventSelect(s, event, FD_READ | FD_WRITE), "Test[%d]: WSAEventSelect failed\n", i);
2943                 memset(&net_events, 0xAB, sizeof(net_events));
2944                 ok (!WSAEnumNetworkEvents(s, l == 0 ? event : NULL, &net_events),
2945                     "Test[%d]: WSAEnumNetworkEvents failed\n", i);
2946                 if (i >= 1 && j == 0) /* FD_WRITE is SET on first try for UDP and connected TCP */
2947                 {
2948                     todo_wine_if (i == 0 || net_events.lNetworkEvents == 0)
2949                         ok (net_events.lNetworkEvents == FD_WRITE, "Test[%d]: expected 2, got %d\n",
2950                             i, net_events.lNetworkEvents);
2951                 }
2952                 else
2953                 {
2954                     todo_wine_if (i != 0 && net_events.lNetworkEvents != 0)
2955                         ok (net_events.lNetworkEvents == 0, "Test[%d]: expected 0, got %d\n",
2956                             i, net_events.lNetworkEvents);
2957                 }
2958                 for (k = 0; k < FD_MAX_EVENTS; k++)
2959                 {
2960                     if (i >= 1 && j == 0 && k == 1) /* first UDP and connected TCP test, FD_WRITE bit no error*/
2961                     {
2962                         ok (net_events.iErrorCode[k] == 0x0, "Test[%d][%d]: expected 0x0, got 0x%x\n",
2963                             i, k, net_events.iErrorCode[k]);
2964                     }
2965                     else
2966                     {
2967                         /* Bits that are not set in lNetworkEvents MUST not be changed */
2968                         todo_wine
2969                         ok (net_events.iErrorCode[k] == 0xABABABAB, "Test[%d][%d]: expected 0xABABABAB, got 0x%x\n",
2970                             i, k, net_events.iErrorCode[k]);
2971                     }
2972                 }
2973             }
2974             closesocket(s);
2975             WSACloseEvent(event);
2976             if (i == 2) closesocket(s2);
2977         }
2978     }
2979 }
2980 
2981 static void test_WSAAddressToStringA(void)
2982 {
2983     SOCKET v6 = INVALID_SOCKET;
2984     INT ret;
2985     DWORD len;
2986     int GLE;
2987     SOCKADDR_IN sockaddr;
2988     CHAR address[22]; /* 12 digits + 3 dots + ':' + 5 digits + '\0' */
2989 
2990     CHAR expect1[] = "0.0.0.0";
2991     CHAR expect2[] = "255.255.255.255";
2992     CHAR expect3[] = "0.0.0.0:65535";
2993     CHAR expect4[] = "255.255.255.255:65535";
2994 
2995     SOCKADDR_IN6 sockaddr6;
2996     CHAR address6[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
2997 
2998     CHAR addr6_1[] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01};
2999     CHAR addr6_2[] = {0x20,0xab,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01};
3000     CHAR addr6_3[] = {0x20,0xab,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x20,0x01};
3001 
3002     CHAR expect6_1[] = "::1";
3003     CHAR expect6_2[] = "20ab::1";
3004     CHAR expect6_3[] = "[20ab::2001]:33274";
3005     CHAR expect6_3_nt[] = "20ab::2001@33274";
3006     CHAR expect6_3_w2k[] = "20ab::2001";
3007     CHAR expect6_3_2[] = "[20ab::2001%4660]:33274";
3008     CHAR expect6_3_2_nt[] = "4660/20ab::2001@33274";
3009     CHAR expect6_3_2_w2k[] = "20ab::2001%4660";
3010     CHAR expect6_3_3[] = "20ab::2001%4660";
3011     CHAR expect6_3_3_nt[] = "4660/20ab::2001";
3012 
3013     len = 0;
3014 
3015     sockaddr.sin_family = AF_INET;
3016     sockaddr.sin_port = 0;
3017     sockaddr.sin_addr.s_addr = 0;
3018 
3019     ret = WSAAddressToStringA( (SOCKADDR*)&sockaddr, sizeof(sockaddr), NULL, address, &len );
3020     GLE = WSAGetLastError();
3021     ok( (ret == SOCKET_ERROR && GLE == WSAEFAULT) || (ret == 0),
3022         "WSAAddressToStringA() failed unexpectedly: WSAGetLastError()=%d, ret=%d\n",
3023         GLE, ret );
3024 
3025     len = sizeof(address);
3026 
3027     sockaddr.sin_family = AF_INET;
3028     sockaddr.sin_port = 0;
3029     sockaddr.sin_addr.s_addr = 0;
3030 
3031     ret = WSAAddressToStringA( (SOCKADDR*)&sockaddr, sizeof(sockaddr), NULL, address, &len );
3032     ok( !ret, "WSAAddressToStringA() failed unexpectedly: %d\n", WSAGetLastError() );
3033 
3034     ok( !strcmp( address, expect1 ), "Expected: %s, got: %s\n", expect1, address );
3035     ok( len == sizeof( expect1 ), "Got size %d\n", len);
3036 
3037     len = sizeof(address);
3038 
3039     sockaddr.sin_family = AF_INET;
3040     sockaddr.sin_port = 0;
3041     sockaddr.sin_addr.s_addr = 0xffffffff;
3042 
3043     ret = WSAAddressToStringA( (SOCKADDR*)&sockaddr, sizeof(sockaddr), NULL, address, &len );
3044     ok( !ret, "WSAAddressToStringA() failed unexpectedly: %d\n", WSAGetLastError() );
3045 
3046     ok( !strcmp( address, expect2 ), "Expected: %s, got: %s\n", expect2, address );
3047 
3048     len = sizeof(address);
3049 
3050     sockaddr.sin_family = AF_INET;
3051     sockaddr.sin_port = 0xffff;
3052     sockaddr.sin_addr.s_addr = 0;
3053 
3054     ret = WSAAddressToStringA( (SOCKADDR*)&sockaddr, sizeof(sockaddr), NULL, address, &len );
3055     ok( !ret, "WSAAddressToStringA() failed unexpectedly: %d\n", WSAGetLastError() );
3056 
3057     ok( !strcmp( address, expect3 ), "Expected: %s, got: %s\n", expect3, address );
3058 
3059     len = sizeof(address);
3060 
3061     sockaddr.sin_family = AF_INET;
3062     sockaddr.sin_port = 0xffff;
3063     sockaddr.sin_addr.s_addr = 0xffffffff;
3064 
3065     ret = WSAAddressToStringA( (SOCKADDR*)&sockaddr, sizeof(sockaddr), NULL, address, &len );
3066     ok( !ret, "WSAAddressToStringA() failed unexpectedly: %d\n", WSAGetLastError() );
3067 
3068     ok( !strcmp( address, expect4 ), "Expected: %s, got: %s\n", expect4, address );
3069     ok( len == sizeof( expect4 ), "Got size %d\n", len);
3070 
3071     /*check to see it IPv6 is available */
3072     v6 = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP);
3073     if (v6 == INVALID_SOCKET) {
3074         skip("Could not create IPv6 socket (LastError: %d; %d expected if IPv6 not available).\n",
3075             WSAGetLastError(), WSAEAFNOSUPPORT);
3076         goto end;
3077     }
3078     /* Test a short IPv6 address */
3079     len = sizeof(address6);
3080 
3081     sockaddr6.sin6_family = AF_INET6;
3082     sockaddr6.sin6_port = 0x0000;
3083     sockaddr6.sin6_scope_id = 0;
3084     memcpy (sockaddr6.sin6_addr.s6_addr, addr6_1, sizeof(addr6_1));
3085 
3086     ret = WSAAddressToStringA( (SOCKADDR*)&sockaddr6, sizeof(sockaddr6), NULL, address6, &len );
3087     ok( !ret, "WSAAddressToStringA() failed unexpectedly: %d\n", WSAGetLastError() );
3088     ok( !strcmp( address6, expect6_1 ), "Expected: %s, got: %s\n", expect6_1, address6 );
3089     ok( len == sizeof(expect6_1), "Got size %d\n", len);
3090 
3091     /* Test a longer IPv6 address */
3092     len = sizeof(address6);
3093 
3094     sockaddr6.sin6_family = AF_INET6;
3095     sockaddr6.sin6_port = 0x0000;
3096     sockaddr6.sin6_scope_id = 0;
3097     memcpy (sockaddr6.sin6_addr.s6_addr, addr6_2, sizeof(addr6_2));
3098 
3099     ret = WSAAddressToStringA( (SOCKADDR*)&sockaddr6, sizeof(sockaddr6), NULL, address6, &len );
3100     ok( !ret, "WSAAddressToStringA() failed unexpectedly: %d\n", WSAGetLastError() );
3101     ok( !strcmp( address6, expect6_2 ), "Expected: %s, got: %s\n", expect6_2, address6 );
3102     ok( len == sizeof(expect6_2), "Got size %d\n", len);
3103 
3104     /* Test IPv6 address and port number */
3105     len = sizeof(address6);
3106 
3107     sockaddr6.sin6_family = AF_INET6;
3108     sockaddr6.sin6_port = 0xfa81;
3109     sockaddr6.sin6_scope_id = 0;
3110     memcpy (sockaddr6.sin6_addr.s6_addr, addr6_3, sizeof(addr6_3));
3111 
3112     ret = WSAAddressToStringA( (SOCKADDR*)&sockaddr6, sizeof(sockaddr6), NULL, address6, &len );
3113     ok( !ret, "WSAAddressToStringA() failed unexpectedly: %d\n", WSAGetLastError() );
3114     ok( !strcmp( address6, expect6_3 ) ||
3115         broken( !strcmp( address6, expect6_3_nt ) ) || /* NT4 */
3116         broken( !strcmp( address6, expect6_3_w2k ) ), /* Win2000 */
3117         "Expected: %s, got: %s\n", expect6_3, address6 );
3118     ok( len == sizeof(expect6_3) ||
3119         broken( len == sizeof(expect6_3_nt) ) || /* NT4 */
3120         broken( len == sizeof(expect6_3_w2k) ), /* Win2000 */
3121         "Got size %d\n", len);
3122 
3123     /* Test IPv6 address, port number and scope_id */
3124     len = sizeof(address6);
3125 
3126     sockaddr6.sin6_family = AF_INET6;
3127     sockaddr6.sin6_port = 0xfa81;
3128     sockaddr6.sin6_scope_id = 0x1234;
3129     memcpy (sockaddr6.sin6_addr.s6_addr, addr6_3, sizeof(addr6_3));
3130 
3131     ret = WSAAddressToStringA( (SOCKADDR*)&sockaddr6, sizeof(sockaddr6), NULL, address6, &len );
3132     ok( !ret, "WSAAddressToStringA() failed unexpectedly: %d\n", WSAGetLastError() );
3133     ok( !strcmp( address6, expect6_3_2 ) ||
3134         broken( !strcmp( address6, expect6_3_2_nt ) ) || /* NT4 */
3135         broken( !strcmp( address6, expect6_3_2_w2k ) ), /* Win2000 */
3136         "Expected: %s, got: %s\n", expect6_3_2, address6 );
3137     ok( len == sizeof(expect6_3_2) ||
3138         broken( len == sizeof(expect6_3_2_nt) ) || /* NT4 */
3139         broken( len == sizeof(expect6_3_2_w2k) ), /* Win2000 */
3140         "Got size %d\n", len);
3141 
3142     /* Test IPv6 address and scope_id */
3143     len = sizeof(address6);
3144 
3145     sockaddr6.sin6_family = AF_INET6;
3146     sockaddr6.sin6_port = 0x0000;
3147     sockaddr6.sin6_scope_id = 0x1234;
3148     memcpy (sockaddr6.sin6_addr.s6_addr, addr6_3, sizeof(addr6_3));
3149 
3150     ret = WSAAddressToStringA( (SOCKADDR*)&sockaddr6, sizeof(sockaddr6), NULL, address6, &len );
3151     ok( !ret, "WSAAddressToStringA() failed unexpectedly: %d\n", WSAGetLastError() );
3152     ok( !strcmp( address6, expect6_3_3 ) ||
3153         broken( !strcmp( address6, expect6_3_3_nt ) ), /* NT4 */
3154         "Expected: %s, got: %s\n", expect6_3_3, address6 );
3155     ok( len == sizeof(expect6_3_3) ||
3156         broken( len == sizeof(expect6_3_3_nt) ), /* NT4 */
3157         "Got size %d\n", len);
3158 
3159 end:
3160     if (v6 != INVALID_SOCKET)
3161         closesocket(v6);
3162 }
3163 
3164 static void test_WSAAddressToStringW(void)
3165 {
3166     SOCKET v6 = INVALID_SOCKET;
3167     INT ret;
3168     DWORD len;
3169     int GLE;
3170     SOCKADDR_IN sockaddr;
3171     WCHAR address[22]; /* 12 digits + 3 dots + ':' + 5 digits + '\0' */
3172 
3173     WCHAR expect1[] = { '0','.','0','.','0','.','0', 0 };
3174     WCHAR expect2[] = { '2','5','5','.','2','5','5','.','2','5','5','.','2','5','5', 0 };
3175     WCHAR expect3[] = { '0','.','0','.','0','.','0', ':', '6', '5', '5', '3', '5', 0 };
3176     WCHAR expect4[] = { '2','5','5','.','2','5','5','.','2','5','5','.','2','5','5', ':',
3177                         '6', '5', '5', '3', '5', 0 };
3178 
3179     SOCKADDR_IN6 sockaddr6;
3180     WCHAR address6[54]; /* 32 digits + 7':' + '[' + '%" + 5 digits + ']:' + 5 digits + '\0' */
3181 
3182     CHAR addr6_1[] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01};
3183     CHAR addr6_2[] = {0x20,0xab,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01};
3184     CHAR addr6_3[] = {0x20,0xab,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x20,0x01};
3185 
3186     WCHAR expect6_1[] = {':',':','1',0};
3187     WCHAR expect6_2[] = {'2','0','a','b',':',':','1',0};
3188     WCHAR expect6_3[] = {'[','2','0','a','b',':',':','2','0','0','1',']',':','3','3','2','7','4',0};
3189     WCHAR expect6_3_nt[] = {'2','0','a','b',':',':','2','0','0','1','@','3','3','2','7','4',0};
3190     WCHAR expect6_3_w2k[] = {'2','0','a','b',':',':','2','0','0','1',0};
3191     WCHAR expect6_3_2[] = {'[','2','0','a','b',':',':','2','0','0','1','%','4','6','6','0',']',':','3','3','2','7','4',0};
3192     WCHAR expect6_3_2_nt[] = {'4','6','6','0','/','2','0','a','b',':',':','2','0','0','1','@','3','3','2','7','4',0};
3193     WCHAR expect6_3_2_w2k[] = {'2','0','a','b',':',':','2','0','0','1','%','4','6','6','0',0};
3194     WCHAR expect6_3_3[] = {'2','0','a','b',':',':','2','0','0','1','%','6','5','5','3','4',0};
3195     WCHAR expect6_3_3_nt[] = {'6','5','5','3','4','/','2','0','a','b',':',':','2','0','0','1',0};
3196 
3197     len = 0;
3198 
3199     sockaddr.sin_family = AF_INET;
3200     sockaddr.sin_port = 0;
3201     sockaddr.sin_addr.s_addr = 0;
3202 
3203     ret = WSAAddressToStringW( (SOCKADDR*)&sockaddr, sizeof(sockaddr), NULL, address, &len );
3204     GLE = WSAGetLastError();
3205     ok( (ret == SOCKET_ERROR && GLE == WSAEFAULT) || (ret == 0),
3206         "WSAAddressToStringW() failed unexpectedly: WSAGetLastError()=%d, ret=%d\n",
3207         GLE, ret );
3208 
3209     len = sizeof(address);
3210 
3211     sockaddr.sin_family = AF_INET;
3212     sockaddr.sin_port = 0;
3213     sockaddr.sin_addr.s_addr = 0;
3214 
3215     ret = WSAAddressToStringW( (SOCKADDR*)&sockaddr, sizeof(sockaddr), NULL, address, &len );
3216     ok( !ret, "WSAAddressToStringW() failed unexpectedly: %d\n", WSAGetLastError() );
3217 
3218     ok( !lstrcmpW( address, expect1 ), "Expected different address string\n" );
3219     ok( len == sizeof( expect1 )/sizeof( WCHAR ), "Got size %d\n", len);
3220 
3221     len = sizeof(address);
3222 
3223     sockaddr.sin_family = AF_INET;
3224     sockaddr.sin_port = 0;
3225     sockaddr.sin_addr.s_addr = 0xffffffff;
3226 
3227     ret = WSAAddressToStringW( (SOCKADDR*)&sockaddr, sizeof(sockaddr), NULL, address, &len );
3228     ok( !ret, "WSAAddressToStringW() failed unexpectedly: %d\n", WSAGetLastError() );
3229 
3230     ok( !lstrcmpW( address, expect2 ), "Expected different address string\n" );
3231 
3232     len = sizeof(address);
3233 
3234     sockaddr.sin_family = AF_INET;
3235     sockaddr.sin_port = 0xffff;
3236     sockaddr.sin_addr.s_addr = 0;
3237 
3238     ret = WSAAddressToStringW( (SOCKADDR*)&sockaddr, sizeof(sockaddr), NULL, address, &len );
3239     ok( !ret, "WSAAddressToStringW() failed unexpectedly: %d\n", WSAGetLastError() );
3240 
3241     ok( !lstrcmpW( address, expect3 ), "Expected different address string\n" );
3242 
3243     len = sizeof(address);
3244 
3245     sockaddr.sin_family = AF_INET;
3246     sockaddr.sin_port = 0xffff;
3247     sockaddr.sin_addr.s_addr = 0xffffffff;
3248 
3249     ret = WSAAddressToStringW( (SOCKADDR*)&sockaddr, sizeof(sockaddr), NULL, address, &len );
3250     ok( !ret, "WSAAddressToStringW() failed unexpectedly: %d\n", WSAGetLastError() );
3251 
3252     ok( !lstrcmpW( address, expect4 ), "Expected different address string\n" );
3253     ok( len == sizeof( expect4 )/sizeof( WCHAR ), "Got %d\n", len);
3254 
3255     /*check to see it IPv6 is available */
3256     v6 = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP);
3257     if (v6 == INVALID_SOCKET) {
3258         skip("Could not create IPv6 socket (LastError: %d; %d expected if IPv6 not available).\n",
3259             WSAGetLastError(), WSAEAFNOSUPPORT);
3260         goto end;
3261     }
3262 
3263     /* Test a short IPv6 address */
3264     len = sizeof(address6)/sizeof(WCHAR);
3265 
3266     sockaddr6.sin6_family = AF_INET6;
3267     sockaddr6.sin6_port = 0x0000;
3268     sockaddr6.sin6_scope_id = 0;
3269     memcpy (sockaddr6.sin6_addr.s6_addr, addr6_1, sizeof(addr6_1));
3270 
3271     ret = WSAAddressToStringW( (SOCKADDR*)&sockaddr6, sizeof(sockaddr6), NULL, address6, &len );
3272     ok( !ret, "WSAAddressToStringW() failed unexpectedly: %d\n", WSAGetLastError() );
3273     ok( !lstrcmpW( address6, expect6_1 ), "Wrong string returned\n" );
3274     ok( len == sizeof(expect6_1)/sizeof(WCHAR), "Got %d\n", len);
3275 
3276     /* Test a longer IPv6 address */
3277     len = sizeof(address6)/sizeof(WCHAR);
3278 
3279     sockaddr6.sin6_family = AF_INET6;
3280     sockaddr6.sin6_port = 0x0000;
3281     sockaddr6.sin6_scope_id = 0;
3282     memcpy (sockaddr6.sin6_addr.s6_addr, addr6_2, sizeof(addr6_2));
3283 
3284     ret = WSAAddressToStringW( (SOCKADDR*)&sockaddr6, sizeof(sockaddr6), NULL, address6, &len );
3285     ok( !ret, "WSAAddressToStringW() failed unexpectedly: %d\n", WSAGetLastError() );
3286 
3287     ok( !lstrcmpW( address6, expect6_2 ), "Wrong string returned\n" );
3288     ok( len == sizeof(expect6_2)/sizeof(WCHAR), "Got %d\n", len);
3289 
3290     /* Test IPv6 address and port number */
3291     len = sizeof(address6)/sizeof(WCHAR);
3292 
3293     sockaddr6.sin6_family = AF_INET6;
3294     sockaddr6.sin6_port = 0xfa81;
3295     sockaddr6.sin6_scope_id = 0;
3296     memcpy (sockaddr6.sin6_addr.s6_addr, addr6_3, sizeof(addr6_3));
3297 
3298     ret = WSAAddressToStringW( (SOCKADDR*)&sockaddr6, sizeof(sockaddr6), NULL, address6, &len );
3299     ok( !ret, "WSAAddressToStringW() failed unexpectedly: %d\n", WSAGetLastError() );
3300     ok( !lstrcmpW( address6, expect6_3 ) ||
3301         broken( !lstrcmpW( address6, expect6_3_nt ) ) || /* NT4 */
3302         broken( !lstrcmpW( address6, expect6_3_w2k ) ), /* Win2000 */
3303         "Expected: %s, got: %s\n", wine_dbgstr_w(expect6_3),
3304         wine_dbgstr_w(address6) );
3305     ok( len == sizeof(expect6_3)/sizeof(WCHAR) ||
3306         broken(len == sizeof(expect6_3_nt)/sizeof(WCHAR) ) || /* NT4 */
3307         broken(len == sizeof(expect6_3_w2k)/sizeof(WCHAR) ), /* Win2000 */
3308         "Got %d\n", len);
3309 
3310     /* Test IPv6 address, port number and scope_id */
3311     len = sizeof(address6)/sizeof(WCHAR);
3312 
3313     sockaddr6.sin6_family = AF_INET6;
3314     sockaddr6.sin6_port = 0xfa81;
3315     sockaddr6.sin6_scope_id = 0x1234;
3316     memcpy (sockaddr6.sin6_addr.s6_addr, addr6_3, sizeof(addr6_3));
3317 
3318     ret = WSAAddressToStringW( (SOCKADDR*)&sockaddr6, sizeof(sockaddr6), NULL, address6, &len );
3319     ok( !ret, "WSAAddressToStringW() failed unexpectedly: %d\n", WSAGetLastError() );
3320     ok( !lstrcmpW( address6, expect6_3_2 ) ||
3321         broken( !lstrcmpW( address6, expect6_3_2_nt ) ) || /* NT4 */
3322         broken( !lstrcmpW( address6, expect6_3_2_w2k ) ), /* Win2000 */
3323         "Expected: %s, got: %s\n", wine_dbgstr_w(expect6_3_2),
3324         wine_dbgstr_w(address6) );
3325     ok( len == sizeof(expect6_3_2)/sizeof(WCHAR) ||
3326         broken( len == sizeof(expect6_3_2_nt)/sizeof(WCHAR) ) || /* NT4 */
3327         broken( len == sizeof(expect6_3_2_w2k)/sizeof(WCHAR) ), /* Win2000 */
3328         "Got %d\n", len);
3329 
3330     /* Test IPv6 address and scope_id */
3331     len = sizeof(address6)/sizeof(WCHAR);
3332 
3333     sockaddr6.sin6_family = AF_INET6;
3334     sockaddr6.sin6_port = 0x0000;
3335     sockaddr6.sin6_scope_id = 0xfffe;
3336     memcpy (sockaddr6.sin6_addr.s6_addr, addr6_3, sizeof(addr6_3));
3337 
3338     ret = WSAAddressToStringW( (SOCKADDR*)&sockaddr6, sizeof(sockaddr6), NULL, address6, &len );
3339     ok( !ret, "WSAAddressToStringW() failed unexpectedly: %d\n", WSAGetLastError() );
3340     ok( !lstrcmpW( address6, expect6_3_3 ) ||
3341         broken( !lstrcmpW( address6, expect6_3_3_nt ) ), /* NT4 */
3342         "Expected: %s, got: %s\n", wine_dbgstr_w(expect6_3_3),
3343         wine_dbgstr_w(address6) );
3344     ok( len == sizeof(expect6_3_3)/sizeof(WCHAR) ||
3345         broken( len == sizeof(expect6_3_3_nt)/sizeof(WCHAR) ), /* NT4 */
3346         "Got %d\n", len);
3347 
3348 end:
3349     if (v6 != INVALID_SOCKET)
3350         closesocket(v6);
3351 }
3352 
3353 static void test_WSAStringToAddressA(void)
3354 {
3355     INT ret, len;
3356     SOCKADDR_IN sockaddr;
3357     SOCKADDR_IN6 sockaddr6;
3358     int GLE;
3359 
3360     CHAR address1[] = "0.0.0.0";
3361     CHAR address2[] = "127.127.127.127";
3362     CHAR address3[] = "255.255.255.255";
3363     CHAR address4[] = "127.127.127.127:65535";
3364     CHAR address5[] = "255.255.255.255:65535";
3365     CHAR address6[] = "::1";
3366     CHAR address7[] = "[::1]";
3367     CHAR address8[] = "[::1]:65535";
3368     CHAR address9[] = "2001::1";
3369 
3370     len = 0;
3371     sockaddr.sin_family = AF_INET;
3372 
3373     ret = WSAStringToAddressA( address1, AF_INET, NULL, (SOCKADDR*)&sockaddr, &len );
3374     ok( ret == SOCKET_ERROR, "WSAStringToAddressA() succeeded unexpectedly: %d\n",
3375         WSAGetLastError() );
3376 
3377     len = sizeof(sockaddr);
3378     sockaddr.sin_port = 0;
3379     sockaddr.sin_addr.s_addr = 0;
3380 
3381     ret = WSAStringToAddressA( address1, AF_INET, NULL, (SOCKADDR*)&sockaddr, &len );
3382     ok( !ret && sockaddr.sin_addr.s_addr == 0,
3383         "WSAStringToAddressA() failed unexpectedly: %d\n", WSAGetLastError() );
3384 
3385     len = sizeof(sockaddr);
3386     sockaddr.sin_port = 0;
3387     sockaddr.sin_addr.s_addr = 0;
3388 
3389     ret = WSAStringToAddressA( address2, AF_INET, NULL, (SOCKADDR*)&sockaddr, &len );
3390     ok( !ret && sockaddr.sin_addr.s_addr == 0x7f7f7f7f,
3391         "WSAStringToAddressA() failed unexpectedly: %d\n", WSAGetLastError() );
3392 
3393     len = sizeof(sockaddr);
3394     sockaddr.sin_port = 0;
3395     sockaddr.sin_addr.s_addr = 0;
3396 
3397     ret = WSAStringToAddressA( address3, AF_INET, NULL, (SOCKADDR*)&sockaddr, &len );
3398     GLE = WSAGetLastError();
3399     ok( (ret == 0 && sockaddr.sin_addr.s_addr == 0xffffffff) ||
3400         (ret == SOCKET_ERROR && (GLE == ERROR_INVALID_PARAMETER || GLE == WSAEINVAL)),
3401         "WSAStringToAddressA() failed unexpectedly: %d\n", GLE );
3402 
3403     len = sizeof(sockaddr);
3404     sockaddr.sin_port = 0;
3405     sockaddr.sin_addr.s_addr = 0;
3406 
3407     ret = WSAStringToAddressA( address4, AF_INET, NULL, (SOCKADDR*)&sockaddr, &len );
3408     ok( !ret && sockaddr.sin_addr.s_addr == 0x7f7f7f7f && sockaddr.sin_port == 0xffff,
3409         "WSAStringToAddressA() failed unexpectedly: %d\n", WSAGetLastError() );
3410 
3411     len = sizeof(sockaddr);
3412     sockaddr.sin_port = 0;
3413     sockaddr.sin_addr.s_addr = 0;
3414 
3415     ret = WSAStringToAddressA( address5, AF_INET, NULL, (SOCKADDR*)&sockaddr, &len );
3416     GLE = WSAGetLastError();
3417     ok( (ret == 0 && sockaddr.sin_addr.s_addr == 0xffffffff && sockaddr.sin_port == 0xffff) ||
3418         (ret == SOCKET_ERROR && (GLE == ERROR_INVALID_PARAMETER || GLE == WSAEINVAL)),
3419         "WSAStringToAddressA() failed unexpectedly: %d\n", GLE );
3420 
3421     len = sizeof(sockaddr);
3422 
3423     ret = WSAStringToAddressA( address9, AF_INET, NULL, (SOCKADDR*)&sockaddr, &len );
3424     GLE = WSAGetLastError();
3425     ok( (ret == SOCKET_ERROR && GLE == WSAEINVAL),
3426         "WSAStringToAddressA() should have failed with %d\n", GLE );
3427 
3428     len = sizeof(sockaddr6);
3429     memset(&sockaddr6, 0, len);
3430     sockaddr6.sin6_family = AF_INET6;
3431 
3432     ret = WSAStringToAddressA( address6, AF_INET6, NULL, (SOCKADDR*)&sockaddr6,
3433             &len );
3434     if (ret == SOCKET_ERROR)
3435     {
3436         win_skip("IPv6 not supported\n");
3437         return;
3438     }
3439 
3440     GLE = WSAGetLastError();
3441     ok( ret == 0, "WSAStringToAddressA() failed for IPv6 address: %d\n", GLE);
3442 
3443     len = sizeof(sockaddr6);
3444     memset(&sockaddr6, 0, len);
3445     sockaddr6.sin6_family = AF_INET6;
3446 
3447     ret = WSAStringToAddressA( address7, AF_INET6, NULL, (SOCKADDR*)&sockaddr6,
3448             &len );
3449     GLE = WSAGetLastError();
3450     ok( ret == 0, "WSAStringToAddressA() failed for IPv6 address: %d\n", GLE);
3451 
3452     len = sizeof(sockaddr6);
3453     memset(&sockaddr6, 0, len);
3454     sockaddr6.sin6_family = AF_INET6;
3455 
3456     ret = WSAStringToAddressA( address8, AF_INET6, NULL, (SOCKADDR*)&sockaddr6,
3457             &len );
3458     GLE = WSAGetLastError();
3459     ok( ret == 0 && sockaddr6.sin6_port == 0xffff,
3460         "WSAStringToAddressA() failed for IPv6 address: %d\n", GLE);
3461 
3462     len = sizeof(sockaddr6);
3463 
3464     ret = WSAStringToAddressA( address7 + 1, AF_INET6, NULL, (SOCKADDR*)&sockaddr, &len );
3465     GLE = WSAGetLastError();
3466     ok( (ret == SOCKET_ERROR && GLE == WSAEINVAL),
3467         "WSAStringToAddressW() should have failed with %d\n", GLE );
3468 
3469     len = sizeof(sockaddr6);
3470 
3471     ret = WSAStringToAddressA( address8 + 1, AF_INET6, NULL, (SOCKADDR*)&sockaddr, &len );
3472     GLE = WSAGetLastError();
3473     ok( (ret == SOCKET_ERROR && GLE == WSAEINVAL),
3474         "WSAStringToAddressW() should have failed with %d\n", GLE );
3475 }
3476 
3477 static void test_WSAStringToAddressW(void)
3478 {
3479     INT ret, len;
3480     SOCKADDR_IN sockaddr, *sin;
3481     SOCKADDR_IN6 sockaddr6;
3482     SOCKADDR_STORAGE sockaddr_storage;
3483     int GLE;
3484 
3485     WCHAR address1[] = { '0','.','0','.','0','.','0', 0 };
3486     WCHAR address2[] = { '1','2','7','.','1','2','7','.','1','2','7','.','1','2','7', 0 };
3487     WCHAR address3[] = { '2','5','5','.','2','5','5','.','2','5','5','.','2','5','5', 0 };
3488     WCHAR address4[] = { '1','2','7','.','1','2','7','.','1','2','7','.','1','2','7',
3489                          ':', '6', '5', '5', '3', '5', 0 };
3490     WCHAR address5[] = { '2','5','5','.','2','5','5','.','2','5','5','.','2','5','5', ':',
3491                          '6', '5', '5', '3', '5', 0 };
3492     WCHAR address6[] = {':',':','1','\0'};
3493     WCHAR address7[] = {'[',':',':','1',']','\0'};
3494     WCHAR address8[] = {'[',':',':','1',']',':','6','5','5','3','5','\0'};
3495     WCHAR address9[] = {'2','0','0','1',':',':','1','\0'};
3496 
3497     len = 0;
3498     sockaddr.sin_family = AF_INET;
3499 
3500     ret = WSAStringToAddressW( address1, AF_INET, NULL, (SOCKADDR*)&sockaddr, &len );
3501     ok( ret == SOCKET_ERROR, "WSAStringToAddressW() failed unexpectedly: %d\n",
3502         WSAGetLastError() );
3503 
3504     len = sizeof(sockaddr);
3505     sockaddr.sin_port = 0;
3506     sockaddr.sin_addr.s_addr = 0;
3507 
3508     ret = WSAStringToAddressW( address1, AF_INET, NULL, (SOCKADDR*)&sockaddr, &len );
3509     ok( !ret && sockaddr.sin_addr.s_addr == 0,
3510         "WSAStringToAddressW() failed unexpectedly: %d\n", WSAGetLastError() );
3511 
3512     len = sizeof(sockaddr);
3513     sockaddr.sin_port = 0;
3514     sockaddr.sin_addr.s_addr = 0;
3515 
3516     ret = WSAStringToAddressW( address2, AF_INET, NULL, (SOCKADDR*)&sockaddr, &len );
3517     ok( !ret && sockaddr.sin_addr.s_addr == 0x7f7f7f7f,
3518         "WSAStringToAddressW() failed unexpectedly: %d\n", WSAGetLastError() );
3519 
3520     len = sizeof(sockaddr);
3521     sockaddr.sin_port = 0;
3522     sockaddr.sin_addr.s_addr = 0;
3523 
3524     ret = WSAStringToAddressW( address3, AF_INET, NULL, (SOCKADDR*)&sockaddr, &len );
3525     GLE = WSAGetLastError();
3526     ok( (ret == 0 && sockaddr.sin_addr.s_addr == 0xffffffff) ||
3527         (ret == SOCKET_ERROR && (GLE == ERROR_INVALID_PARAMETER || GLE == WSAEINVAL)),
3528         "WSAStringToAddressW() failed unexpectedly: %d\n", GLE );
3529 
3530     len = sizeof(sockaddr);
3531     sockaddr.sin_port = 0;
3532     sockaddr.sin_addr.s_addr = 0;
3533 
3534     ret = WSAStringToAddressW( address4, AF_INET, NULL, (SOCKADDR*)&sockaddr, &len );
3535     ok( !ret && sockaddr.sin_addr.s_addr == 0x7f7f7f7f && sockaddr.sin_port == 0xffff,
3536         "WSAStringToAddressW() failed unexpectedly: %d\n", WSAGetLastError() );
3537 
3538     len = sizeof(sockaddr);
3539     sockaddr.sin_port = 0;
3540     sockaddr.sin_addr.s_addr = 0;
3541 
3542     ret = WSAStringToAddressW( address5, AF_INET, NULL, (SOCKADDR*)&sockaddr, &len );
3543     ok( (ret == 0 && sockaddr.sin_addr.s_addr == 0xffffffff && sockaddr.sin_port == 0xffff) ||
3544         (ret == SOCKET_ERROR && (GLE == ERROR_INVALID_PARAMETER || GLE == WSAEINVAL)),
3545         "WSAStringToAddressW() failed unexpectedly: %d\n", GLE );
3546 
3547     /* Test with a larger buffer than necessary */
3548     len = sizeof(sockaddr_storage);
3549     sin = (SOCKADDR_IN *)&sockaddr_storage;
3550     sin->sin_port = 0;
3551     sin->sin_addr.s_addr = 0;
3552 
3553     ret = WSAStringToAddressW( address5, AF_INET, NULL, (SOCKADDR*)sin, &len );
3554     ok( (ret == 0 && sin->sin_addr.s_addr == 0xffffffff && sin->sin_port == 0xffff) ||
3555         (ret == SOCKET_ERROR && (GLE == ERROR_INVALID_PARAMETER || GLE == WSAEINVAL)),
3556         "WSAStringToAddressW() failed unexpectedly: %d\n", GLE );
3557     ok( len == sizeof(SOCKADDR_IN) ||
3558         broken(len == sizeof(SOCKADDR_STORAGE)) /* NT4/2k */,
3559         "unexpected length %d\n", len );
3560 
3561     len = sizeof(sockaddr);
3562 
3563     ret = WSAStringToAddressW( address9, AF_INET, NULL, (SOCKADDR*)&sockaddr, &len );
3564     GLE = WSAGetLastError();
3565     ok( (ret == SOCKET_ERROR && GLE == WSAEINVAL),
3566         "WSAStringToAddressW() should have failed with %d\n", GLE );
3567 
3568     len = sizeof(sockaddr6);
3569     memset(&sockaddr6, 0, len);
3570     sockaddr6.sin6_family = AF_INET6;
3571 
3572     ret = WSAStringToAddressW( address6, AF_INET6, NULL, (SOCKADDR*)&sockaddr6,
3573             &len );
3574     if (ret == SOCKET_ERROR)
3575     {
3576         win_skip("IPv6 not supported\n");
3577         return;
3578     }
3579 
3580     GLE = WSAGetLastError();
3581     ok( ret == 0, "WSAStringToAddressW() failed for IPv6 address: %d\n", GLE);
3582 
3583     len = sizeof(sockaddr6);
3584     memset(&sockaddr6, 0, len);
3585     sockaddr6.sin6_family = AF_INET6;
3586 
3587     ret = WSAStringToAddressW( address7, AF_INET6, NULL, (SOCKADDR*)&sockaddr6,
3588             &len );
3589     GLE = WSAGetLastError();
3590     ok( ret == 0, "WSAStringToAddressW() failed for IPv6 address: %d\n", GLE);
3591 
3592     len = sizeof(sockaddr6);
3593     memset(&sockaddr6, 0, len);
3594     sockaddr6.sin6_family = AF_INET6;
3595 
3596     ret = WSAStringToAddressW( address8, AF_INET6, NULL, (SOCKADDR*)&sockaddr6,
3597             &len );
3598     GLE = WSAGetLastError();
3599     ok( ret == 0 && sockaddr6.sin6_port == 0xffff,
3600         "WSAStringToAddressW() failed for IPv6 address: %d\n", GLE);
3601 
3602     len = sizeof(sockaddr6);
3603 
3604     ret = WSAStringToAddressW( address7 + 1, AF_INET6, NULL, (SOCKADDR*)&sockaddr, &len );
3605     GLE = WSAGetLastError();
3606     ok( (ret == SOCKET_ERROR && GLE == WSAEINVAL),
3607         "WSAStringToAddressW() should have failed with %d\n", GLE );
3608 
3609     len = sizeof(sockaddr6);
3610 
3611     ret = WSAStringToAddressW( address8 + 1, AF_INET6, NULL, (SOCKADDR*)&sockaddr, &len );
3612     GLE = WSAGetLastError();
3613     ok( (ret == SOCKET_ERROR && GLE == WSAEINVAL),
3614         "WSAStringToAddressW() should have failed with %d\n", GLE );
3615 }
3616 
3617 static DWORD WINAPI SelectReadThread(void *param)
3618 {
3619     select_thread_params *par = param;
3620     fd_set readfds;
3621     int ret;
3622     struct sockaddr_in addr;
3623     struct timeval select_timeout;
3624 
3625     memset(&readfds, 0, sizeof(readfds));
3626     FD_ZERO(&readfds);
3627     FD_SET(par->s, &readfds);
3628     select_timeout.tv_sec=5;
3629     select_timeout.tv_usec=0;
3630     addr.sin_family = AF_INET;
3631     addr.sin_addr.s_addr = inet_addr(SERVERIP);
3632     addr.sin_port = htons(SERVERPORT);
3633 
3634     do_bind(par->s, (struct sockaddr *)&addr, sizeof(addr));
3635     wsa_ok(listen(par->s, SOMAXCONN ), 0 ==, "SelectReadThread (%x): listen failed: %d\n");
3636 
3637     SetEvent(server_ready);
3638     ret = select(par->s+1, &readfds, NULL, NULL, &select_timeout);
3639     par->ReadKilled = (ret == 1);
3640 
3641     return 0;
3642 }
3643 
3644 static DWORD WINAPI SelectCloseThread(void *param)
3645 {
3646     SOCKET s = *(SOCKET*)param;
3647     Sleep(500);
3648     closesocket(s);
3649     return 0;
3650 }
3651 
3652 static void test_errors(void)
3653 {
3654     SOCKET sock;
3655     SOCKADDR_IN  SockAddr;
3656     int ret, err;
3657 
3658     WSASetLastError(NO_ERROR);
3659     sock = socket(PF_INET, SOCK_STREAM, 0);
3660     ok( (sock != INVALID_SOCKET), "socket failed unexpectedly: %d\n", WSAGetLastError() );
3661     memset(&SockAddr, 0, sizeof(SockAddr));
3662     SockAddr.sin_family = AF_INET;
3663     SockAddr.sin_port = htons(6924);
3664     SockAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
3665 
3666     ret = connect(sock, (PSOCKADDR)&SockAddr, sizeof(SockAddr));
3667     ok( (ret == SOCKET_ERROR), "expected SOCKET_ERROR, got: %d\n", ret );
3668     if (ret == SOCKET_ERROR)
3669     {
3670         err = WSAGetLastError();
3671         ok( (err == WSAECONNREFUSED), "expected WSAECONNREFUSED, got: %d\n", err );
3672     }
3673 
3674     {
3675         TIMEVAL timeval;
3676         fd_set set = {1, {sock}};
3677 
3678         timeval.tv_sec = 0;
3679         timeval.tv_usec = 50000;
3680 
3681         ret = select(1, NULL, &set, NULL, &timeval);
3682         ok( (ret == 0), "expected 0 (timeout), got: %d\n", ret );
3683     }
3684 
3685     ret = closesocket(sock);
3686     ok ( (ret == 0), "closesocket failed unexpectedly: %d\n", WSAGetLastError());
3687 }
3688 
3689 static void test_listen(void)
3690 {
3691     SOCKET fdA, fdB;
3692     int ret, acceptc, olen = sizeof(acceptc);
3693     struct sockaddr_in address;
3694 
3695     memset(&address, 0, sizeof(address));
3696     address.sin_addr.s_addr = inet_addr("127.0.0.1");
3697     address.sin_family = AF_INET;
3698     address.sin_port = htons(SERVERPORT);
3699 
3700     /* invalid socket tests */
3701     SetLastError(0xdeadbeef);
3702     ok ((listen(0, 0) == SOCKET_ERROR), "listen did not fail\n");
3703     ret = WSAGetLastError();
3704     ok (ret == WSAENOTSOCK, "expected 10038, received %d\n", ret);
3705 
3706     SetLastError(0xdeadbeef);
3707     ok ((listen(0xdeadbeef, 0) == SOCKET_ERROR), "listen did not fail\n");
3708     ret = WSAGetLastError();
3709     ok (ret == WSAENOTSOCK, "expected 10038, received %d\n", ret);
3710 
3711     /* tcp tests */
3712     fdA = socket(AF_INET, SOCK_STREAM, 0);
3713     ok ((fdA != INVALID_SOCKET), "socket failed unexpectedly: %d\n", WSAGetLastError() );
3714 
3715     fdB = socket(AF_INET, SOCK_STREAM, 0);
3716     ok ((fdB != INVALID_SOCKET), "socket failed unexpectedly: %d\n", WSAGetLastError() );
3717 
3718     SetLastError(0xdeadbeef);
3719     ok ((listen(fdA, -2) == SOCKET_ERROR), "listen did not fail\n");
3720     ret = WSAGetLastError();
3721     ok (ret == WSAEINVAL, "expected 10022, received %d\n", ret);
3722 
3723     SetLastError(0xdeadbeef);
3724     ok ((listen(fdA, 1) == SOCKET_ERROR), "listen did not fail\n");
3725     ret = WSAGetLastError();
3726     ok (ret == WSAEINVAL, "expected 10022, received %d\n", ret);
3727 
3728     SetLastError(0xdeadbeef);
3729     ok ((listen(fdA, SOMAXCONN) == SOCKET_ERROR), "listen did not fail\n");
3730     ret = WSAGetLastError();
3731     ok (ret == WSAEINVAL, "expected 10022, received %d\n", ret);
3732 
3733     ok (!bind(fdA, (struct sockaddr*) &address, sizeof(address)), "bind failed\n");
3734 
3735     SetLastError(0xdeadbeef);
3736     ok (bind(fdB, (struct sockaddr*) &address, sizeof(address)), "bind should have failed\n");
3737     ok (ret == WSAEINVAL, "expected 10022, received %d\n", ret);
3738 
3739     acceptc = 0xdead;
3740     ret = getsockopt(fdA, SOL_SOCKET, SO_ACCEPTCONN, (char*)&acceptc, &olen);
3741     ok (!ret, "getsockopt failed\n");
3742     ok (acceptc == 0, "SO_ACCEPTCONN should be 0, received %d\n", acceptc);
3743 
3744     ok (!listen(fdA, 0), "listen failed\n");
3745     ok (!listen(fdA, SOMAXCONN), "double listen failed\n");
3746 
3747     acceptc = 0xdead;
3748     ret = getsockopt(fdA, SOL_SOCKET, SO_ACCEPTCONN, (char*)&acceptc, &olen);
3749     ok (!ret, "getsockopt failed\n");
3750     ok (acceptc == 1, "SO_ACCEPTCONN should be 1, received %d\n", acceptc);
3751 
3752     SetLastError(0xdeadbeef);
3753     ok ((listen(fdB, SOMAXCONN) == SOCKET_ERROR), "listen did not fail\n");
3754     ret = WSAGetLastError();
3755     ok (ret == WSAEINVAL, "expected 10022, received %d\n", ret);
3756 
3757     ret = closesocket(fdB);
3758     ok (ret == 0, "closesocket failed unexpectedly: %d\n", ret);
3759 
3760     fdB = socket(AF_INET, SOCK_STREAM, 0);
3761     ok ((fdB != INVALID_SOCKET), "socket failed unexpectedly: %d\n", WSAGetLastError() );
3762 
3763     SetLastError(0xdeadbeef);
3764     ok (bind(fdB, (struct sockaddr*) &address, sizeof(address)), "bind should have failed\n");
3765     ret = WSAGetLastError();
3766     ok (ret == WSAEADDRINUSE, "expected 10048, received %d\n", ret);
3767 
3768     ret = closesocket(fdA);
3769     ok (ret == 0, "closesocket failed unexpectedly: %d\n", ret);
3770     ret = closesocket(fdB);
3771     ok (ret == 0, "closesocket failed unexpectedly: %d\n", ret);
3772 }
3773 
3774 #define FD_ZERO_ALL() { FD_ZERO(&readfds); FD_ZERO(&writefds); FD_ZERO(&exceptfds); }
3775 #define FD_SET_ALL(s) { FD_SET(s, &readfds); FD_SET(s, &writefds); FD_SET(s, &exceptfds); }
3776 static void test_select(void)
3777 {
3778     static char tmp_buf[1024];
3779 
3780     SOCKET fdListen, fdRead, fdWrite;
3781     fd_set readfds, writefds, exceptfds;
3782     unsigned int maxfd;
3783     int ret, len;
3784     char buffer;
3785     struct timeval select_timeout;
3786     struct sockaddr_in address;
3787     select_thread_params thread_params;
3788     HANDLE thread_handle;
3789     DWORD ticks, id;
3790 
3791     fdRead = socket(AF_INET, SOCK_STREAM, 0);
3792     ok( (fdRead != INVALID_SOCKET), "socket failed unexpectedly: %d\n", WSAGetLastError() );
3793     fdWrite = socket(AF_INET, SOCK_STREAM, 0);
3794     ok( (fdWrite != INVALID_SOCKET), "socket failed unexpectedly: %d\n", WSAGetLastError() );
3795 
3796     maxfd = fdRead;
3797     if (fdWrite > maxfd)
3798         maxfd = fdWrite;
3799 
3800     FD_ZERO_ALL();
3801     FD_SET_ALL(fdRead);
3802     FD_SET_ALL(fdWrite);
3803     select_timeout.tv_sec=0;
3804     select_timeout.tv_usec=0;
3805 
3806     ticks = GetTickCount();
3807     ret = select(maxfd+1, &readfds, &writefds, &exceptfds, &select_timeout);
3808     ticks = GetTickCount() - ticks;
3809     ok(ret == 0, "select should not return any socket handles\n");
3810     ok(ticks < 10, "select was blocking for %u ms, expected < 10 ms\n", ticks);
3811     ok(!FD_ISSET(fdRead, &readfds), "FD should not be set\n");
3812     ok(!FD_ISSET(fdWrite, &writefds), "FD should not be set\n");
3813     ok(!FD_ISSET(fdRead, &exceptfds), "FD should not be set\n");
3814     ok(!FD_ISSET(fdWrite, &exceptfds), "FD should not be set\n");
3815 
3816     FD_ZERO_ALL();
3817     FD_SET_ALL(fdRead);
3818     FD_SET_ALL(fdWrite);
3819     select_timeout.tv_sec=0;
3820     select_timeout.tv_usec=500;
3821 
3822     ret = select(maxfd+1, &readfds, &writefds, &exceptfds, &select_timeout);
3823     ok(ret == 0, "select should not return any socket handles\n");
3824     ok(!FD_ISSET(fdRead, &readfds), "FD should not be set\n");
3825     ok(!FD_ISSET(fdWrite, &writefds), "FD should not be set\n");
3826     ok(!FD_ISSET(fdRead, &exceptfds), "FD should not be set\n");
3827     ok(!FD_ISSET(fdWrite, &exceptfds), "FD should not be set\n");
3828 
3829     ok ((listen(fdWrite, SOMAXCONN) == SOCKET_ERROR), "listen did not fail\n");
3830     ret = closesocket(fdWrite);
3831     ok ( (ret == 0), "closesocket failed unexpectedly: %d\n", ret);
3832 
3833     thread_params.s = fdRead;
3834     thread_params.ReadKilled = FALSE;
3835     server_ready = CreateEventA(NULL, TRUE, FALSE, NULL);
3836     thread_handle = CreateThread (NULL, 0, SelectReadThread, &thread_params, 0, &id );
3837     ok ( (thread_handle != NULL), "CreateThread failed unexpectedly: %d\n", GetLastError());
3838 
3839     WaitForSingleObject (server_ready, INFINITE);
3840     Sleep(200);
3841     ret = closesocket(fdRead);
3842     ok ( (ret == 0), "closesocket failed unexpectedly: %d\n", ret);
3843 
3844     WaitForSingleObject (thread_handle, 1000);
3845     ok ( (thread_params.ReadKilled) ||
3846          broken(thread_params.ReadKilled == 0), /*Win98*/
3847             "closesocket did not wakeup select\n");
3848     ret = recv(fdRead, &buffer, 1, MSG_PEEK);
3849     ok( (ret == -1), "peek at closed socket expected -1 got %d\n", ret);
3850 
3851     /* Test selecting invalid handles */
3852     FD_ZERO_ALL();
3853 
3854     SetLastError(0);
3855     ret = select(maxfd+1, 0, 0, 0, &select_timeout);
3856     ok ( (ret == SOCKET_ERROR), "expected SOCKET_ERROR, got %i\n", ret);
3857     ok ( WSAGetLastError() == WSAEINVAL, "expected WSAEINVAL, got %i\n", WSAGetLastError());
3858 
3859     SetLastError(0);
3860     ret = select(maxfd+1, &readfds, &writefds, &exceptfds, &select_timeout);
3861     ok ( (ret == SOCKET_ERROR), "expected SOCKET_ERROR, got %i\n", ret);
3862     ok ( WSAGetLastError() == WSAEINVAL, "expected WSAEINVAL, got %i\n", WSAGetLastError());
3863 
3864     FD_SET(INVALID_SOCKET, &readfds);
3865     SetLastError(0);
3866     ret = select(maxfd+1, &readfds, &writefds, &exceptfds, &select_timeout);
3867     ok ( (ret == SOCKET_ERROR), "expected SOCKET_ERROR, got %i\n", ret);
3868     ok ( WSAGetLastError() == WSAENOTSOCK, "expected WSAENOTSOCK, got %i\n", WSAGetLastError());
3869     ok ( !FD_ISSET(fdRead, &readfds), "FD should not be set\n");
3870 
3871     FD_ZERO(&readfds);
3872     FD_SET(INVALID_SOCKET, &writefds);
3873     SetLastError(0);
3874     ret = select(maxfd+1, &readfds, &writefds, &exceptfds, &select_timeout);
3875     ok ( (ret == SOCKET_ERROR), "expected SOCKET_ERROR, got %i\n", ret);
3876     ok ( WSAGetLastError() == WSAENOTSOCK, "expected WSAENOTSOCK, got %i\n", WSAGetLastError());
3877     ok ( !FD_ISSET(fdRead, &writefds), "FD should not be set\n");
3878 
3879     FD_ZERO(&writefds);
3880     FD_SET(INVALID_SOCKET, &exceptfds);
3881     SetLastError(0);
3882     ret = select(maxfd+1, &readfds, &writefds, &exceptfds, &select_timeout);
3883     ok ( (ret == SOCKET_ERROR), "expected SOCKET_ERROR, got %i\n", ret);
3884     ok ( WSAGetLastError() == WSAENOTSOCK, "expected WSAENOTSOCK, got %i\n", WSAGetLastError());
3885     ok ( !FD_ISSET(fdRead, &exceptfds), "FD should not be set\n");
3886 
3887     ok(!tcp_socketpair(&fdRead, &fdWrite), "creating socket pair failed\n");
3888     maxfd = fdRead;
3889     if(fdWrite > maxfd) maxfd = fdWrite;
3890 
3891     FD_ZERO(&readfds);
3892     FD_SET(fdRead, &readfds);
3893     ret = select(fdRead+1, &readfds, NULL, NULL, &select_timeout);
3894     ok(!ret, "select returned %d\n", ret);
3895 
3896     FD_ZERO(&writefds);
3897     FD_SET(fdWrite, &writefds);
3898     ret = select(fdWrite+1, NULL, &writefds, NULL, &select_timeout);
3899     ok(ret == 1, "select returned %d\n", ret);
3900     ok(FD_ISSET(fdWrite, &writefds), "fdWrite socket is not in the set\n");
3901 
3902     /* tests for overlapping fd_set pointers */
3903     FD_ZERO(&readfds);
3904     FD_SET(fdWrite, &readfds);
3905     ret = select(fdWrite+1, &readfds, &readfds, NULL, &select_timeout);
3906     ok(ret == 1, "select returned %d\n", ret);
3907     ok(FD_ISSET(fdWrite, &readfds), "fdWrite socket is not in the set\n");
3908 
3909     FD_ZERO(&readfds);
3910     FD_SET(fdWrite, &readfds);
3911     FD_SET(fdRead, &readfds);
3912     ret = select(maxfd+1, &readfds, &readfds, NULL, &select_timeout);
3913     ok(ret == 2, "select returned %d\n", ret);
3914     ok(FD_ISSET(fdWrite, &readfds), "fdWrite socket is not in the set\n");
3915     ok(FD_ISSET(fdRead, &readfds), "fdRead socket is not in the set\n");
3916 
3917     ok(send(fdWrite, "test", 4, 0) == 4, "failed to send data\n");
3918     FD_ZERO(&readfds);
3919     FD_SET(fdRead, &readfds);
3920     ret = select(fdRead+1, &readfds, NULL, NULL, &select_timeout);
3921     ok(ret == 1, "select returned %d\n", ret);
3922     ok(FD_ISSET(fdRead, &readfds), "fdRead socket is not in the set\n");
3923 
3924     FD_ZERO(&readfds);
3925     FD_SET(fdWrite, &readfds);
3926     FD_SET(fdRead, &readfds);
3927     ret = select(maxfd+1, &readfds, &readfds, NULL, &select_timeout);
3928     ok(ret == 2, "select returned %d\n", ret);
3929     ok(FD_ISSET(fdWrite, &readfds), "fdWrite socket is not in the set\n");
3930     ok(FD_ISSET(fdRead, &readfds), "fdRead socket is not in the set\n");
3931 
3932 #if ROSTESTS_233_IS_FIXED
3933     while(1) {
3934         FD_ZERO(&writefds);
3935         FD_SET(fdWrite, &writefds);
3936         ret = select(fdWrite+1, NULL, &writefds, NULL, &select_timeout);
3937         if(!ret) break;
3938         ok(send(fdWrite, tmp_buf, sizeof(tmp_buf), 0) > 0, "failed to send data\n");
3939     }
3940 #endif /* ROSTESTS_233_IS_FIXED */
3941 
3942     FD_ZERO(&readfds);
3943     FD_SET(fdWrite, &readfds);
3944     FD_SET(fdRead, &readfds);
3945     ret = select(maxfd+1, &readfds, &readfds, NULL, &select_timeout);
3946     ok(ret == 1, "select returned %d\n", ret);
3947     ok(!FD_ISSET(fdWrite, &readfds), "fdWrite socket is in the set\n");
3948     ok(FD_ISSET(fdRead, &readfds), "fdRead socket is not in the set\n");
3949 
3950     ok(send(fdRead, "test", 4, 0) == 4, "failed to send data\n");
3951     Sleep(100);
3952     FD_ZERO(&readfds);
3953     FD_SET(fdWrite, &readfds);
3954     FD_SET(fdRead, &readfds);
3955     ret = select(maxfd+1, &readfds, &readfds, NULL, &select_timeout);
3956     ok(ret == 2, "select returned %d\n", ret);
3957     ok(FD_ISSET(fdWrite, &readfds), "fdWrite socket is not in the set\n");
3958     ok(FD_ISSET(fdRead, &readfds), "fdRead socket is not in the set\n");
3959 
3960     closesocket(fdRead);
3961     closesocket(fdWrite);
3962 
3963     /* select() works in 3 distinct states:
3964      * - to check if a connection attempt ended with success or error;
3965      * - to check if a pending connection is waiting for acceptance;
3966      * - to check for data to read, availability for write and OOB data
3967      *
3968      * The tests below ensure that all conditions are tested.
3969      */
3970     memset(&address, 0, sizeof(address));
3971     address.sin_addr.s_addr = inet_addr("127.0.0.1");
3972     address.sin_family = AF_INET;
3973     len = sizeof(address);
3974     fdListen = setup_server_socket(&address, &len);
3975     select_timeout.tv_sec = 1;
3976     select_timeout.tv_usec = 250000;
3977 
3978     /* When no events are pending select returns 0 with no error */
3979     FD_ZERO_ALL();
3980     FD_SET_ALL(fdListen);
3981     ret = select(0, &readfds, &writefds, &exceptfds, &select_timeout);
3982     ok(ret == 0, "expected 0, got %d\n", ret);
3983 
3984     /* When a socket is attempting to connect the listening socket receives the read descriptor */
3985     fdWrite = setup_connector_socket(&address, len, TRUE);
3986     FD_ZERO_ALL();
3987     FD_SET_ALL(fdListen);
3988     ret = select(0, &readfds, &writefds, &exceptfds, &select_timeout);
3989     ok(ret == 1, "expected 1, got %d\n", ret);
3990     ok(FD_ISSET(fdListen, &readfds), "fdListen socket is not in the set\n");
3991     len = sizeof(address);
3992     fdRead = accept(fdListen, (struct sockaddr*) &address, &len);
3993     ok(fdRead != INVALID_SOCKET, "expected a valid socket\n");
3994 
3995     /* The connector is signaled through the write descriptor */
3996     FD_ZERO_ALL();
3997     FD_SET_ALL(fdListen);
3998     FD_SET_ALL(fdRead);
3999     FD_SET_ALL(fdWrite);
4000     ret = select(0, &readfds, &writefds, &exceptfds, &select_timeout);
4001     ok(ret == 2, "expected 2, got %d\n", ret);
4002     ok(FD_ISSET(fdWrite, &writefds), "fdWrite socket is not in the set\n");
4003     ok(FD_ISSET(fdRead, &writefds), "fdRead socket is not in the set\n");
4004     len = sizeof(id);
4005     id = 0xdeadbeef;
4006     ret = getsockopt(fdWrite, SOL_SOCKET, SO_ERROR, (char*)&id, &len);
4007     ok(!ret, "getsockopt failed with %d\n", WSAGetLastError());
4008     ok(id == 0, "expected 0, got %d\n", id);
4009 
4010     /* When data is received the receiver gets the read descriptor */
4011     ret = send(fdWrite, "1234", 4, 0);
4012     ok(ret == 4, "expected 4, got %d\n", ret);
4013     FD_ZERO_ALL();
4014     FD_SET_ALL(fdListen);
4015     FD_SET(fdRead, &readfds);
4016     FD_SET(fdRead, &exceptfds);
4017     ret = select(0, &readfds, &writefds, &exceptfds, &select_timeout);
4018     ok(ret == 1, "expected 1, got %d\n", ret);
4019     ok(FD_ISSET(fdRead, &readfds), "fdRead socket is not in the set\n");
4020     ret = recv(fdRead, tmp_buf, sizeof(tmp_buf), 0);
4021     ok(ret == 4, "expected 4, got %d\n", ret);
4022     ok(!strcmp(tmp_buf, "1234"), "data received differs from sent\n");
4023 
4024     /* When OOB data is received the socket is set in the except descriptor */
4025     ret = send(fdWrite, "A", 1, MSG_OOB);
4026     ok(ret == 1, "expected 1, got %d\n", ret);
4027     FD_ZERO_ALL();
4028     FD_SET_ALL(fdListen);
4029     FD_SET(fdRead, &readfds);
4030     FD_SET(fdRead, &exceptfds);
4031     ret = select(0, &readfds, &writefds, &exceptfds, &select_timeout);
4032     ok(ret == 1, "expected 1, got %d\n", ret);
4033     ok(FD_ISSET(fdRead, &exceptfds), "fdRead socket is not in the set\n");
4034     tmp_buf[0] = 0xAF;
4035     ret = recv(fdRead, tmp_buf, sizeof(tmp_buf), MSG_OOB);
4036     ok(ret == 1, "expected 1, got %d\n", ret);
4037     ok(tmp_buf[0] == 'A', "expected 'A', got 0x%02X\n", tmp_buf[0]);
4038 
4039     /* If the socket is OOBINLINED it will not receive the OOB in except fds */
4040     ret = 1;
4041     ret = setsockopt(fdRead, SOL_SOCKET, SO_OOBINLINE, (char*) &ret, sizeof(ret));
4042     ok(ret == 0, "expected 0, got %d\n", ret);
4043     ret = send(fdWrite, "A", 1, MSG_OOB);
4044     ok(ret == 1, "expected 1, got %d\n", ret);
4045     FD_ZERO_ALL();
4046     FD_SET_ALL(fdListen);
4047     FD_SET(fdRead, &readfds);
4048     FD_SET(fdRead, &exceptfds);
4049     ret = select(0, &readfds, &writefds, &exceptfds, &select_timeout);
4050     ok(ret == 1, "expected 1, got %d\n", ret);
4051     ok(FD_ISSET(fdRead, &readfds), "fdRead socket is not in the set\n");
4052     tmp_buf[0] = 0xAF;
4053     SetLastError(0xdeadbeef);
4054     ret = recv(fdRead, tmp_buf, sizeof(tmp_buf), MSG_OOB);
4055     if (ret == SOCKET_ERROR) /* can't recv with MSG_OOB if OOBINLINED */
4056     {
4057         ok(GetLastError() == WSAEINVAL, "expected 10022, got %d\n", GetLastError());
4058         ret = recv(fdRead, tmp_buf, sizeof(tmp_buf), 0);
4059         ok(ret == 1, "expected 1, got %d\n", ret);
4060         ok(tmp_buf[0] == 'A', "expected 'A', got 0x%02X\n", tmp_buf[0]);
4061     }
4062     else ok(broken(ret == 1) /* <= NT4 */, "expected error, got 1\n");
4063 
4064     /* When the connection is closed the socket is set in the read descriptor */
4065     ret = closesocket(fdRead);
4066     ok(ret == 0, "expected 0, got %d\n", ret);
4067     FD_ZERO_ALL();
4068     FD_SET_ALL(fdListen);
4069     FD_SET(fdWrite, &readfds);
4070     ret = select(0, &readfds, &writefds, &exceptfds, &select_timeout);
4071     ok(ret == 1, "expected 1, got %d\n", ret);
4072     ok(FD_ISSET(fdWrite, &readfds), "fdWrite socket is not in the set\n");
4073     ret = recv(fdWrite, tmp_buf, sizeof(tmp_buf), 0);
4074     ok(ret == 0, "expected 0, got %d\n", ret);
4075 
4076     /* When a connection is attempted to a non-listening socket it will get to the except descriptor */
4077     ret = closesocket(fdWrite);
4078     ok(ret == 0, "expected 0, got %d\n", ret);
4079     ret = closesocket(fdListen);
4080     ok(ret == 0, "expected 0, got %d\n", ret);
4081     len = sizeof(address);
4082     fdWrite = setup_connector_socket(&address, len, TRUE);
4083     FD_ZERO_ALL();
4084     FD_SET(fdWrite, &writefds);
4085     FD_SET(fdWrite, &exceptfds);
4086     select_timeout.tv_sec = 2; /* requires more time to realize it will not connect */
4087     ret = select(0, &readfds, &writefds, &exceptfds, &select_timeout);
4088     ok(ret == 1, "expected 1, got %d\n", ret);
4089     len = sizeof(id);
4090     id = 0xdeadbeef;
4091     ret = getsockopt(fdWrite, SOL_SOCKET, SO_ERROR, (char*)&id, &len);
4092     ok(!ret, "getsockopt failed with %d\n", WSAGetLastError());
4093     ok(id == WSAECONNREFUSED, "expected 10061, got %d\n", id);
4094     ok(FD_ISSET(fdWrite, &exceptfds), "fdWrite socket is not in the set\n");
4095     ok(select_timeout.tv_usec == 250000, "select timeout should not have changed\n");
4096     closesocket(fdWrite);
4097 
4098     /* Try select() on a closed socket after connection */
4099     ok(!tcp_socketpair(&fdRead, &fdWrite), "creating socket pair failed\n");
4100     closesocket(fdRead);
4101     FD_ZERO_ALL();
4102     FD_SET_ALL(fdWrite);
4103     FD_SET_ALL(fdRead);
4104     SetLastError(0xdeadbeef);
4105     ret = select(0, &readfds, NULL, &exceptfds, &select_timeout);
4106     ok(ret == SOCKET_ERROR, "expected -1, got %d\n", ret);
4107 todo_wine
4108     ok(GetLastError() == WSAENOTSOCK, "expected 10038, got %d\n", GetLastError());
4109     /* descriptor sets are unchanged */
4110     ok(readfds.fd_count == 2, "expected 2, got %d\n", readfds.fd_count);
4111     ok(exceptfds.fd_count == 2, "expected 2, got %d\n", exceptfds.fd_count);
4112     closesocket(fdWrite);
4113 
4114 #if ROSTESTS_233_IS_FIXED
4115 
4116     /* Close the socket currently being selected in a thread - bug 38399 */
4117     ok(!tcp_socketpair(&fdRead, &fdWrite), "creating socket pair failed\n");
4118     thread_handle = CreateThread(NULL, 0, SelectCloseThread, &fdWrite, 0, &id);
4119     ok(thread_handle != NULL, "CreateThread failed unexpectedly: %d\n", GetLastError());
4120     FD_ZERO_ALL();
4121     FD_SET_ALL(fdWrite);
4122     ret = select(0, &readfds, NULL, &exceptfds, &select_timeout);
4123     ok(ret == 1, "expected 1, got %d\n", ret);
4124     ok(FD_ISSET(fdWrite, &readfds), "fdWrite socket is not in the set\n");
4125     WaitForSingleObject (thread_handle, 1000);
4126     closesocket(fdRead);
4127     /* test again with only the except descriptor */
4128     ok(!tcp_socketpair(&fdRead, &fdWrite), "creating socket pair failed\n");
4129     thread_handle = CreateThread(NULL, 0, SelectCloseThread, &fdWrite, 0, &id);
4130     ok(thread_handle != NULL, "CreateThread failed unexpectedly: %d\n", GetLastError());
4131     FD_ZERO_ALL();
4132     FD_SET(fdWrite, &exceptfds);
4133     SetLastError(0xdeadbeef);
4134     ret = select(0, NULL, NULL, &exceptfds, &select_timeout);
4135 todo_wine
4136     ok(ret == SOCKET_ERROR, "expected -1, got %d\n", ret);
4137 todo_wine
4138     ok(GetLastError() == WSAENOTSOCK, "expected 10038, got %d\n", GetLastError());
4139     WaitForSingleObject (thread_handle, 1000);
4140     closesocket(fdRead);
4141 
4142 #endif /* ROSTESTS_233_IS_FIXED */
4143 
4144     /* test UDP behavior of unbound sockets */
4145     select_timeout.tv_sec = 0;
4146     select_timeout.tv_usec = 250000;
4147     fdWrite = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
4148     ok(fdWrite != INVALID_SOCKET, "socket call failed\n");
4149     FD_ZERO_ALL();
4150     FD_SET_ALL(fdWrite);
4151     ret = select(0, &readfds, &writefds, &exceptfds, &select_timeout);
4152     ok(ret == 1, "expected 1, got %d\n", ret);
4153     ok(FD_ISSET(fdWrite, &writefds), "fdWrite socket is not in the set\n");
4154     closesocket(fdWrite);
4155 }
4156 #undef FD_SET_ALL
4157 #undef FD_ZERO_ALL
4158 
4159 static DWORD WINAPI AcceptKillThread(void *param)
4160 {
4161     select_thread_params *par = param;
4162     struct sockaddr_in address;
4163     int len = sizeof(address);
4164     SOCKET client_socket;
4165 
4166     SetEvent(server_ready);
4167     client_socket = accept(par->s, (struct sockaddr*) &address, &len);
4168     if (client_socket != INVALID_SOCKET)
4169         closesocket(client_socket);
4170     par->ReadKilled = (client_socket == INVALID_SOCKET);
4171     return 0;
4172 }
4173 
4174 
4175 static int CALLBACK AlwaysDeferConditionFunc(LPWSABUF lpCallerId, LPWSABUF lpCallerData, LPQOS pQos,
4176                                              LPQOS lpGQOS, LPWSABUF lpCalleeId, LPWSABUF lpCalleeData,
4177                                              GROUP *g, DWORD_PTR dwCallbackData)
4178 {
4179     return CF_DEFER;
4180 }
4181 
4182 static SOCKET setup_server_socket(struct sockaddr_in *addr, int *len)
4183 {
4184     int ret, val;
4185     SOCKET server_socket;
4186 
4187     server_socket = socket(AF_INET, SOCK_STREAM, 0);
4188     if (server_socket == INVALID_SOCKET)
4189     {
4190         trace("error creating server socket: %d\n", WSAGetLastError());
4191         return INVALID_SOCKET;
4192     }
4193 
4194     val = 1;
4195     ret = setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR, (char *)&val, sizeof(val));
4196     if (ret)
4197     {
4198         trace("error setting SO_REUSEADDR: %d\n", WSAGetLastError());
4199         closesocket(server_socket);
4200         return INVALID_SOCKET;
4201     }
4202 
4203     ret = bind(server_socket, (struct sockaddr *)addr, *len);
4204     if (ret)
4205     {
4206         trace("error binding server socket: %d\n", WSAGetLastError());
4207     }
4208 
4209     ret = getsockname(server_socket, (struct sockaddr *)addr, len);
4210     if (ret)
4211     {
4212         skip("failed to lookup bind address: %d\n", WSAGetLastError());
4213         closesocket(server_socket);
4214         return INVALID_SOCKET;
4215     }
4216 
4217     ret = listen(server_socket, 5);
4218     if (ret)
4219     {
4220         trace("error making server socket listen: %d\n", WSAGetLastError());
4221         closesocket(server_socket);
4222         return INVALID_SOCKET;
4223     }
4224 
4225     return server_socket;
4226 }
4227 
4228 static SOCKET setup_connector_socket(struct sockaddr_in *addr, int len, BOOL nonblock)
4229 {
4230     int ret;
4231     SOCKET connector;
4232 
4233     connector = socket(AF_INET, SOCK_STREAM, 0);
4234     ok(connector != INVALID_SOCKET, "failed to create connector socket %d\n", WSAGetLastError());
4235 
4236     if (nonblock)
4237         set_blocking(connector, !nonblock);
4238 
4239     ret = connect(connector, (struct sockaddr *)addr, len);
4240     if (!nonblock)
4241         ok(!ret, "connecting to accepting socket failed %d\n", WSAGetLastError());
4242     else if (ret == SOCKET_ERROR)
4243     {
4244         DWORD error = WSAGetLastError();
4245         ok(error == WSAEWOULDBLOCK || error == WSAEINPROGRESS,
4246            "expected 10035 or 10036, got %d\n", error);
4247     }
4248 
4249     return connector;
4250 }
4251 
4252 static void test_accept(void)
4253 {
4254     int ret;
4255     SOCKET server_socket, accepted = INVALID_SOCKET, connector;
4256     struct sockaddr_in address;
4257     SOCKADDR_STORAGE ss, ss_empty;
4258     int socklen;
4259     select_thread_params thread_params;
4260     HANDLE thread_handle = NULL;
4261     DWORD id;
4262 
4263     memset(&address, 0, sizeof(address));
4264     address.sin_addr.s_addr = inet_addr("127.0.0.1");
4265     address.sin_family = AF_INET;
4266 
4267     socklen = sizeof(address);
4268     server_socket = setup_server_socket(&address, &socklen);
4269     if (server_socket == INVALID_SOCKET)
4270     {
4271         trace("error creating server socket: %d\n", WSAGetLastError());
4272         return;
4273     }
4274 
4275     connector = setup_connector_socket(&address, socklen, FALSE);
4276     if (connector == INVALID_SOCKET) goto done;
4277 
4278     trace("Blocking accept next\n");
4279 
4280     accepted = WSAAccept(server_socket, NULL, NULL, AlwaysDeferConditionFunc, 0);
4281     ok(accepted == INVALID_SOCKET && WSAGetLastError() == WSATRY_AGAIN, "Failed to defer connection, %d\n", WSAGetLastError());
4282 
4283     accepted = accept(server_socket, NULL, 0);
4284     ok(accepted != INVALID_SOCKET, "Failed to accept deferred connection, error %d\n", WSAGetLastError());
4285 
4286     server_ready = CreateEventA(NULL, TRUE, FALSE, NULL);
4287     if (server_ready == INVALID_HANDLE_VALUE)
4288     {
4289         trace("error creating event: %d\n", GetLastError());
4290         goto done;
4291     }
4292 
4293     thread_params.s = server_socket;
4294     thread_params.ReadKilled = FALSE;
4295     thread_handle = CreateThread(NULL, 0, AcceptKillThread, &thread_params, 0, &id);
4296     if (thread_handle == NULL)
4297     {
4298         trace("error creating thread: %d\n", GetLastError());
4299         goto done;
4300     }
4301 
4302     WaitForSingleObject(server_ready, INFINITE);
4303     Sleep(200);
4304     ret = closesocket(server_socket);
4305     if (ret != 0)
4306     {
4307         trace("closesocket failed: %d\n", WSAGetLastError());
4308         goto done;
4309     }
4310 
4311     WaitForSingleObject(thread_handle, 1000);
4312     ok(thread_params.ReadKilled || broken(!thread_params.ReadKilled) /* Win98/ME, after accept */,
4313        "closesocket did not wakeup accept\n");
4314 
4315     closesocket(accepted);
4316     closesocket(connector);
4317     accepted = connector = INVALID_SOCKET;
4318 
4319     socklen = sizeof(address);
4320     server_socket = setup_server_socket(&address, &socklen);
4321     if (server_socket == INVALID_SOCKET) goto done;
4322 
4323     connector = setup_connector_socket(&address, socklen, FALSE);
4324     if (connector == INVALID_SOCKET) goto done;
4325 
4326     socklen = 0;
4327     accepted = WSAAccept(server_socket, (struct sockaddr *)&ss, &socklen, NULL, 0);
4328     ok(accepted == INVALID_SOCKET && WSAGetLastError() == WSAEFAULT, "got %d\n", WSAGetLastError());
4329     ok(!socklen, "got %d\n", socklen);
4330     closesocket(connector);
4331     connector = INVALID_SOCKET;
4332 
4333     socklen = sizeof(address);
4334     connector = setup_connector_socket(&address, socklen, FALSE);
4335     if (connector == INVALID_SOCKET) goto done;
4336 
4337     accepted = WSAAccept(server_socket, NULL, NULL, NULL, 0);
4338     ok(accepted != INVALID_SOCKET, "Failed to accept connection, %d\n", WSAGetLastError());
4339     closesocket(accepted);
4340     closesocket(connector);
4341     accepted = connector = INVALID_SOCKET;
4342 
4343     socklen = sizeof(address);
4344     connector = setup_connector_socket(&address, socklen, FALSE);
4345     if (connector == INVALID_SOCKET) goto done;
4346 
4347     socklen = sizeof(ss);
4348     memset(&ss, 0, sizeof(ss));
4349     accepted = WSAAccept(server_socket, (struct sockaddr *)&ss, &socklen, NULL, 0);
4350     ok(accepted != INVALID_SOCKET, "Failed to accept connection, %d\n", WSAGetLastError());
4351     ok(socklen != sizeof(ss), "unexpected length\n");
4352     ok(ss.ss_family, "family not set\n");
4353     closesocket(accepted);
4354     closesocket(connector);
4355     accepted = connector = INVALID_SOCKET;
4356 
4357     socklen = sizeof(address);
4358     connector = setup_connector_socket(&address, socklen, FALSE);
4359     if (connector == INVALID_SOCKET) goto done;
4360 
4361     socklen = 0;
4362     accepted = accept(server_socket, (struct sockaddr *)&ss, &socklen);
4363     ok(accepted == INVALID_SOCKET && WSAGetLastError() == WSAEFAULT, "got %d\n", WSAGetLastError());
4364     ok(!socklen, "got %d\n", socklen);
4365     closesocket(connector);
4366     accepted = connector = INVALID_SOCKET;
4367 
4368     socklen = sizeof(address);
4369     connector = setup_connector_socket(&address, socklen, FALSE);
4370     if (connector == INVALID_SOCKET) goto done;
4371 
4372     accepted = accept(server_socket, NULL, NULL);
4373     ok(accepted != INVALID_SOCKET, "Failed to accept connection, %d\n", WSAGetLastError());
4374     closesocket(accepted);
4375     closesocket(connector);
4376     accepted = connector = INVALID_SOCKET;
4377 
4378     socklen = sizeof(address);
4379     connector = setup_connector_socket(&address, socklen, FALSE);
4380     if (connector == INVALID_SOCKET) goto done;
4381 
4382     socklen = sizeof(ss);
4383     memset(&ss, 0, sizeof(ss));
4384     accepted = accept(server_socket, (struct sockaddr *)&ss, &socklen);
4385     ok(accepted != INVALID_SOCKET, "Failed to accept connection, %d\n", WSAGetLastError());
4386     ok(socklen != sizeof(ss), "unexpected length\n");
4387     ok(ss.ss_family, "family not set\n");
4388     closesocket(accepted);
4389     closesocket(connector);
4390     accepted = connector = INVALID_SOCKET;
4391 
4392     socklen = sizeof(address);
4393     connector = setup_connector_socket(&address, socklen, FALSE);
4394     if (connector == INVALID_SOCKET) goto done;
4395 
4396     memset(&ss, 0, sizeof(ss));
4397     memset(&ss_empty, 0, sizeof(ss_empty));
4398     accepted = accept(server_socket, (struct sockaddr *)&ss, NULL);
4399     ok(accepted != INVALID_SOCKET, "Failed to accept connection, %d\n", WSAGetLastError());
4400     ok(!memcmp(&ss, &ss_empty, sizeof(ss)), "structure is different\n");
4401 
4402 done:
4403     if (accepted != INVALID_SOCKET)
4404         closesocket(accepted);
4405     if (connector != INVALID_SOCKET)
4406         closesocket(connector);
4407     if (thread_handle != NULL)
4408         CloseHandle(thread_handle);
4409     if (server_ready != INVALID_HANDLE_VALUE)
4410         CloseHandle(server_ready);
4411     if (server_socket != INVALID_SOCKET)
4412         closesocket(server_socket);
4413 }
4414 
4415 static void test_extendedSocketOptions(void)
4416 {
4417     WSADATA wsa;
4418     SOCKET sock;
4419     struct sockaddr_in sa;
4420     int sa_len = sizeof(struct sockaddr_in);
4421     int optval, optlen = sizeof(int), ret;
4422     BOOL bool_opt_val;
4423     LINGER linger_val;
4424 
4425     if(WSAStartup(MAKEWORD(2,0), &wsa)){
4426         trace("Winsock failed: %d. Aborting test\n", WSAGetLastError());
4427         return;
4428     }
4429 
4430     memset(&sa, 0, sa_len);
4431 
4432     sa.sin_family = AF_INET;
4433     sa.sin_port = htons(0);
4434     sa.sin_addr.s_addr = htonl(INADDR_ANY);
4435 
4436     if((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP)) == INVALID_SOCKET) {
4437         trace("Creating the socket failed: %d\n", WSAGetLastError());
4438         WSACleanup();
4439         return;
4440     }
4441 
4442     if(bind(sock, (struct sockaddr *) &sa, sa_len) < 0){
4443         trace("Failed to bind socket: %d\n", WSAGetLastError());
4444         closesocket(sock);
4445         WSACleanup();
4446         return;
4447     }
4448 
4449     ret = getsockopt(sock, SOL_SOCKET, SO_MAX_MSG_SIZE, (char *)&optval, &optlen);
4450 
4451     ok(ret == 0, "getsockopt failed to query SO_MAX_MSG_SIZE, return value is 0x%08x\n", ret);
4452     ok((optval == 65507) || (optval == 65527),
4453             "SO_MAX_MSG_SIZE reported %d, expected 65507 or 65527\n", optval);
4454 
4455     /* IE 3 use 0xffffffff instead of SOL_SOCKET (0xffff) */
4456     SetLastError(0xdeadbeef);
4457     optval = 0xdeadbeef;
4458     optlen = sizeof(int);
4459     ret = getsockopt(sock, 0xffffffff, SO_MAX_MSG_SIZE, (char *)&optval, &optlen);
4460     ok( (ret == SOCKET_ERROR) && (WSAGetLastError() == WSAEINVAL),
4461         "got %d with %d and optval: 0x%x/%d (expected SOCKET_ERROR with WSAEINVAL)\n",
4462         ret, WSAGetLastError(), optval, optval);
4463 
4464     /* more invalid values for level */
4465     SetLastError(0xdeadbeef);
4466     optval = 0xdeadbeef;
4467     optlen = sizeof(int);
4468     ret = getsockopt(sock, 0x1234ffff, SO_MAX_MSG_SIZE, (char *)&optval, &optlen);
4469     ok( (ret == SOCKET_ERROR) && (WSAGetLastError() == WSAEINVAL),
4470         "got %d with %d and optval: 0x%x/%d (expected SOCKET_ERROR with WSAEINVAL)\n",
4471         ret, WSAGetLastError(), optval, optval);
4472 
4473     SetLastError(0xdeadbeef);
4474     optval = 0xdeadbeef;
4475     optlen = sizeof(int);
4476     ret = getsockopt(sock, 0x8000ffff, SO_MAX_MSG_SIZE, (char *)&optval, &optlen);
4477     ok( (ret == SOCKET_ERROR) && (WSAGetLastError() == WSAEINVAL),
4478         "got %d with %d and optval: 0x%x/%d (expected SOCKET_ERROR with WSAEINVAL)\n",
4479         ret, WSAGetLastError(), optval, optval);
4480 
4481     SetLastError(0xdeadbeef);
4482     optval = 0xdeadbeef;
4483     optlen = sizeof(int);
4484     ret = getsockopt(sock, 0x00008000, SO_MAX_MSG_SIZE, (char *)&optval, &optlen);
4485     ok( (ret == SOCKET_ERROR) && (WSAGetLastError() == WSAEINVAL),
4486         "got %d with %d and optval: 0x%x/%d (expected SOCKET_ERROR with WSAEINVAL)\n",
4487         ret, WSAGetLastError(), optval, optval);
4488 
4489     SetLastError(0xdeadbeef);
4490     optval = 0xdeadbeef;
4491     optlen = sizeof(int);
4492     ret = getsockopt(sock, 0x00000800, SO_MAX_MSG_SIZE, (char *)&optval, &optlen);
4493     ok( (ret == SOCKET_ERROR) && (WSAGetLastError() == WSAEINVAL),
4494         "got %d with %d and optval: 0x%x/%d (expected SOCKET_ERROR with WSAEINVAL)\n",
4495         ret, WSAGetLastError(), optval, optval);
4496 
4497     SetLastError(0xdeadbeef);
4498     optlen = sizeof(LINGER);
4499     ret = getsockopt(sock, SOL_SOCKET, SO_LINGER, (char *)&linger_val, &optlen);
4500     ok( (ret == SOCKET_ERROR) && (WSAGetLastError() == WSAENOPROTOOPT),
4501         "getsockopt should fail for UDP sockets setting last error to WSAENOPROTOOPT, got %d with %d\n",
4502         ret, WSAGetLastError());
4503     closesocket(sock);
4504 
4505     if((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_IP)) == INVALID_SOCKET) {
4506         trace("Creating the socket failed: %d\n", WSAGetLastError());
4507         WSACleanup();
4508         return;
4509     }
4510 
4511     if(bind(sock, (struct sockaddr *) &sa, sa_len) < 0){
4512         trace("Failed to bind socket: %d\n", WSAGetLastError());
4513         closesocket(sock);
4514         WSACleanup();
4515         return;
4516     }
4517 
4518     ret = getsockopt(sock, SOL_SOCKET, SO_LINGER, (char *)&linger_val, &optlen);
4519     ok(ret == 0, "getsockopt failed to query SO_LINGER, return value is 0x%08x\n", ret);
4520 
4521     optlen = sizeof(BOOL);
4522     ret = getsockopt(sock, SOL_SOCKET, SO_DONTLINGER, (char *)&bool_opt_val, &optlen);
4523     ok(ret == 0, "getsockopt failed to query SO_DONTLINGER, return value is 0x%08x\n", ret);
4524     ok((linger_val.l_onoff && !bool_opt_val) || (!linger_val.l_onoff && bool_opt_val),
4525             "Return value of SO_DONTLINGER is %d, but SO_LINGER returned l_onoff == %d.\n",
4526             bool_opt_val, linger_val.l_onoff);
4527 
4528     closesocket(sock);
4529     WSACleanup();
4530 }
4531 
4532 static void test_getsockname(void)
4533 {
4534     WSADATA wsa;
4535     SOCKET sock;
4536     struct sockaddr_in sa_set, sa_get;
4537     int sa_set_len = sizeof(struct sockaddr_in);
4538     int sa_get_len = sa_set_len;
4539     static const unsigned char null_padding[] = {0,0,0,0,0,0,0,0};
4540     int ret;
4541     struct hostent *h;
4542 
4543     if(WSAStartup(MAKEWORD(2,0), &wsa)){
4544         trace("Winsock failed: %d. Aborting test\n", WSAGetLastError());
4545         return;
4546     }
4547 
4548     memset(&sa_set, 0, sa_set_len);
4549 
4550     sa_set.sin_family = AF_INET;
4551     sa_set.sin_port = htons(0);
4552     sa_set.sin_addr.s_addr = htonl(INADDR_ANY);
4553 
4554     if((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_IP)) == INVALID_SOCKET) {
4555         trace("Creating the socket failed: %d\n", WSAGetLastError());
4556         WSACleanup();
4557         return;
4558     }
4559 
4560     sa_get = sa_set;
4561     if (getsockname(sock, (struct sockaddr*) &sa_get, &sa_get_len) == 0)
4562         ok(0, "getsockname on unbound socket should fail\n");
4563     else {
4564         ok(WSAGetLastError() == WSAEINVAL, "getsockname on unbound socket "
4565             "failed with %d, expected %d\n", WSAGetLastError(), WSAEINVAL);
4566         ok(memcmp(&sa_get, &sa_set, sizeof(sa_get)) == 0,
4567             "failed getsockname modified sockaddr when it shouldn't\n");
4568     }
4569 
4570     if(bind(sock, (struct sockaddr *) &sa_set, sa_set_len) < 0){
4571         trace("Failed to bind socket: %d\n", WSAGetLastError());
4572         closesocket(sock);
4573         WSACleanup();
4574         return;
4575     }
4576 
4577     if(getsockname(sock, (struct sockaddr *) &sa_get, &sa_get_len) != 0){
4578         trace("Failed to call getsockname: %d\n", WSAGetLastError());
4579         closesocket(sock);
4580         WSACleanup();
4581         return;
4582     }
4583 
4584     ret = memcmp(sa_get.sin_zero, null_padding, 8);
4585     ok(ret == 0 || broken(ret != 0), /* NT4 */
4586             "getsockname did not zero the sockaddr_in structure\n");
4587 
4588     closesocket(sock);
4589 
4590     h = gethostbyname("");
4591     if (h && h->h_length == 4) /* this test is only meaningful in IPv4 */
4592     {
4593         int i;
4594         for (i = 0; h->h_addr_list[i]; i++)
4595         {
4596             char ipstr[32];
4597             struct in_addr ip;
4598             ip.s_addr = *(ULONG *) h->h_addr_list[i];
4599 
4600             sock = socket(AF_INET, SOCK_DGRAM, 0);
4601             ok(sock != INVALID_SOCKET, "socket failed with %d\n", GetLastError());
4602 
4603             memset(&sa_set, 0, sizeof(sa_set));
4604             sa_set.sin_family = AF_INET;
4605             sa_set.sin_addr.s_addr = ip.s_addr;
4606             /* The same address we bind must be the same address we get */
4607             ret = bind(sock, (struct sockaddr*)&sa_set, sizeof(sa_set));
4608             ok(ret == 0, "bind failed with %d\n", GetLastError());
4609             sa_get_len = sizeof(sa_get);
4610             ret = getsockname(sock, (struct sockaddr*)&sa_get, &sa_get_len);
4611             ok(ret == 0, "getsockname failed with %d\n", GetLastError());
4612             strcpy(ipstr, inet_ntoa(sa_get.sin_addr));
4613             trace("testing bind on interface %s\n", ipstr);
4614             ok(sa_get.sin_addr.s_addr == sa_set.sin_addr.s_addr,
4615                "address does not match: %s != %s\n", ipstr, inet_ntoa(sa_set.sin_addr));
4616 
4617             closesocket(sock);
4618         }
4619     }
4620 
4621     WSACleanup();
4622 }
4623 
4624 static void test_dns(void)
4625 {
4626     struct hostent *h;
4627     union memaddress
4628     {
4629         char *chr;
4630         void *mem;
4631     } addr;
4632     char **ptr;
4633     int acount;
4634 
4635     h = gethostbyname("");
4636     ok(h != NULL, "gethostbyname(\"\") failed with %d\n", h_errno);
4637 
4638     /* Use an address with valid alias names if possible */
4639     h = gethostbyname("source.winehq.org");
4640     if(!h)
4641     {
4642         skip("Can't test the hostent structure because gethostbyname failed\n");
4643         return;
4644     }
4645 
4646     /* The returned struct must be allocated in a very strict way. First we need to
4647      * count how many aliases there are because they must be located right after
4648      * the struct hostent size. Knowing the amount of aliases we know the exact
4649      * location of the first IP returned. Rule valid for >= XP, for older OS's
4650      * it's somewhat the opposite. */
4651     addr.mem = h + 1;
4652     if(h->h_addr_list == addr.mem) /* <= W2K */
4653     {
4654         win_skip("Skipping hostent tests since this OS is unsupported\n");
4655         return;
4656     }
4657 
4658     ok(h->h_aliases == addr.mem,
4659        "hostent->h_aliases should be in %p, it is in %p\n", addr.mem, h->h_aliases);
4660 
4661     for(ptr = h->h_aliases, acount = 1; *ptr; ptr++) acount++;
4662     addr.chr += sizeof(*ptr) * acount;
4663     ok(h->h_addr_list == addr.mem,
4664        "hostent->h_addr_list should be in %p, it is in %p\n", addr.mem, h->h_addr_list);
4665 
4666     for(ptr = h->h_addr_list, acount = 1; *ptr; ptr++) acount++;
4667 
4668     addr.chr += sizeof(*ptr) * acount;
4669     ok(h->h_addr_list[0] == addr.mem,
4670        "hostent->h_addr_list[0] should be in %p, it is in %p\n", addr.mem, h->h_addr_list[0]);
4671 }
4672 
4673 #ifndef __REACTOS__
4674 /* Our winsock headers don't define gethostname because it conflicts with the
4675  * definition in unistd.h. Define it here to get rid of the warning. */
4676 
4677 int WINAPI gethostname(char *name, int namelen);
4678 #endif
4679 
4680 static void test_gethostbyname(void)
4681 {
4682     struct hostent *he;
4683     struct in_addr **addr_list;
4684     char name[256], first_ip[16];
4685     int ret, i, count;
4686     PMIB_IPFORWARDTABLE routes = NULL;
4687     PIP_ADAPTER_INFO adapters = NULL, k;
4688     DWORD adap_size = 0, route_size = 0;
4689     BOOL found_default = FALSE;
4690     BOOL local_ip = FALSE;
4691 
4692     ret = gethostname(name, sizeof(name));
4693     ok(ret == 0, "gethostname() call failed: %d\n", WSAGetLastError());
4694 
4695     he = gethostbyname(name);
4696     ok(he != NULL, "gethostbyname(\"%s\") failed: %d\n", name, WSAGetLastError());
4697 #ifdef __REACTOS__ /* ROSTESTS-233 */
4698     if (he != NULL)
4699     {
4700 #endif
4701         addr_list = (struct in_addr **)he->h_addr_list;
4702         strcpy(first_ip, inet_ntoa(*addr_list[0]));
4703 
4704         trace("List of local IPs:\n");
4705         for(count = 0; addr_list[count] != NULL; count++)
4706         {
4707             char *ip = inet_ntoa(*addr_list[count]);
4708             if (!strcmp(ip, "127.0.0.1"))
4709                 local_ip = TRUE;
4710             trace("%s\n", ip);
4711         }
4712 #ifdef __REACTOS__ /* ROSTESTS-233 */
4713     }
4714 #endif
4715 
4716     if (local_ip)
4717     {
4718         ok (count == 1, "expected 127.0.0.1 to be the only IP returned\n");
4719         skip("Only the loopback address is present, skipping tests\n");
4720         return;
4721     }
4722 
4723     if (!pGetAdaptersInfo || !pGetIpForwardTable)
4724     {
4725         win_skip("GetAdaptersInfo and/or GetIpForwardTable not found, skipping tests\n");
4726         return;
4727     }
4728 
4729     ret = pGetAdaptersInfo(NULL, &adap_size);
4730     ok (ret  == ERROR_BUFFER_OVERFLOW, "GetAdaptersInfo failed with a different error: %d\n", ret);
4731     ret = pGetIpForwardTable(NULL, &route_size, FALSE);
4732     ok (ret == ERROR_INSUFFICIENT_BUFFER, "GetIpForwardTable failed with a different error: %d\n", ret);
4733 
4734     adapters = HeapAlloc(GetProcessHeap(), 0, adap_size);
4735     routes = HeapAlloc(GetProcessHeap(), 0, route_size);
4736 
4737     ret = pGetAdaptersInfo(adapters, &adap_size);
4738     ok (ret  == NO_ERROR, "GetAdaptersInfo failed, error: %d\n", ret);
4739     ret = pGetIpForwardTable(routes, &route_size, FALSE);
4740     ok (ret == NO_ERROR, "GetIpForwardTable failed, error: %d\n", ret);
4741 
4742     /* This test only has meaning if there is more than one IP configured */
4743     if (adapters->Next == NULL && count == 1)
4744     {
4745         skip("Only one IP is present, skipping tests\n");
4746         goto cleanup;
4747     }
4748 
4749     for (i = 0; !found_default && i < routes->dwNumEntries; i++)
4750     {
4751         /* default route (ip 0.0.0.0) ? */
4752         if (routes->table[i].dwForwardDest) continue;
4753 
4754         for (k = adapters; k != NULL; k = k->Next)
4755         {
4756             char *ip;
4757 
4758             if (k->Index != routes->table[i].dwForwardIfIndex) continue;
4759 
4760             /* the first IP returned from gethostbyname must be a default route */
4761             ip = k->IpAddressList.IpAddress.String;
4762             if (!strcmp(first_ip, ip))
4763             {
4764                 found_default = TRUE;
4765                 break;
4766             }
4767         }
4768     }
4769     ok (found_default, "failed to find the first IP from gethostbyname!\n");
4770 
4771 cleanup:
4772     HeapFree(GetProcessHeap(), 0, adapters);
4773     HeapFree(GetProcessHeap(), 0, routes);
4774 }
4775 
4776 static void test_gethostbyname_hack(void)
4777 {
4778     struct hostent *he;
4779     char name[256];
4780     static BYTE loopback[] = {127, 0, 0, 1};
4781     static BYTE magic_loopback[] = {127, 12, 34, 56};
4782     int ret;
4783 
4784     ret = gethostname(name, 256);
4785     ok(ret == 0, "gethostname() call failed: %d\n", WSAGetLastError());
4786 
4787     he = gethostbyname("localhost");
4788     ok(he != NULL, "gethostbyname(\"localhost\") failed: %d\n", h_errno);
4789     if(he)
4790     {
4791         if(he->h_length != 4)
4792         {
4793             skip("h_length is %d, not IPv4, skipping test.\n", he->h_length);
4794             return;
4795         }
4796 
4797         ok(memcmp(he->h_addr_list[0], loopback, he->h_length) == 0,
4798            "gethostbyname(\"localhost\") returned %u.%u.%u.%u\n",
4799            he->h_addr_list[0][0], he->h_addr_list[0][1], he->h_addr_list[0][2],
4800            he->h_addr_list[0][3]);
4801     }
4802 
4803     if(strcmp(name, "localhost") == 0)
4804     {
4805         skip("hostname seems to be \"localhost\", skipping test.\n");
4806         return;
4807     }
4808 
4809     he = gethostbyname(name);
4810     ok(he != NULL, "gethostbyname(\"%s\") failed: %d\n", name, h_errno);
4811     if(he)
4812     {
4813         if(he->h_length != 4)
4814         {
4815             skip("h_length is %d, not IPv4, skipping test.\n", he->h_length);
4816             return;
4817         }
4818 
4819         if (he->h_addr_list[0][0] == 127)
4820         {
4821             ok(memcmp(he->h_addr_list[0], magic_loopback, he->h_length) == 0,
4822                "gethostbyname(\"%s\") returned %u.%u.%u.%u not 127.12.34.56\n",
4823                name, he->h_addr_list[0][0], he->h_addr_list[0][1],
4824                he->h_addr_list[0][2], he->h_addr_list[0][3]);
4825         }
4826     }
4827 
4828     gethostbyname("nonexistent.winehq.org");
4829     /* Don't check for the return value, as some braindead ISPs will kindly
4830      * resolve nonexistent host names to addresses of the ISP's spam pages. */
4831 }
4832 
4833 static void test_gethostname(void)
4834 {
4835     struct hostent *he;
4836     char name[256];
4837     int ret, len;
4838 
4839     WSASetLastError(0xdeadbeef);
4840     ret = gethostname(NULL, 256);
4841     ok(ret == -1, "gethostname() returned %d\n", ret);
4842     ok(WSAGetLastError() == WSAEFAULT, "gethostname with null buffer "
4843             "failed with %d, expected %d\n", WSAGetLastError(), WSAEFAULT);
4844 
4845     ret = gethostname(name, sizeof(name));
4846     ok(ret == 0, "gethostname() call failed: %d\n", WSAGetLastError());
4847     he = gethostbyname(name);
4848     ok(he != NULL, "gethostbyname(\"%s\") failed: %d\n", name, WSAGetLastError());
4849 
4850     len = strlen(name);
4851     WSASetLastError(0xdeadbeef);
4852     strcpy(name, "deadbeef");
4853     ret = gethostname(name, len);
4854     ok(ret == -1, "gethostname() returned %d\n", ret);
4855     ok(!strcmp(name, "deadbeef"), "name changed unexpected!\n");
4856     ok(WSAGetLastError() == WSAEFAULT, "gethostname with insufficient length "
4857             "failed with %d, expected %d\n", WSAGetLastError(), WSAEFAULT);
4858 
4859     len++;
4860     ret = gethostname(name, len);
4861     ok(ret == 0, "gethostname() call failed: %d\n", WSAGetLastError());
4862     he = gethostbyname(name);
4863     ok(he != NULL, "gethostbyname(\"%s\") failed: %d\n", name, WSAGetLastError());
4864 }
4865 
4866 static void test_inet_addr(void)
4867 {
4868     u_long addr;
4869 
4870     addr = inet_addr(NULL);
4871     ok(addr == INADDR_NONE, "inet_addr succeeded unexpectedly\n");
4872 }
4873 
4874 static void test_addr_to_print(void)
4875 {
4876     char dst[16];
4877     char dst6[64];
4878     const char * pdst;
4879     struct in_addr in;
4880     struct in6_addr in6;
4881 
4882     u_long addr0_Num = 0x00000000;
4883     PCSTR addr0_Str = "0.0.0.0";
4884     u_long addr1_Num = 0x20201015;
4885     PCSTR addr1_Str = "21.16.32.32";
4886     u_char addr2_Num[16] = {0,0,0,0,0,0,0,0,0,0,0xff,0xfe,0xcC,0x98,0xbd,0x74};
4887     PCSTR addr2_Str = "::fffe:cc98:bd74";
4888     u_char addr3_Num[16] = {0x20,0x30,0xa4,0xb1};
4889     PCSTR addr3_Str = "2030:a4b1::";
4890     u_char addr4_Num[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0xcC,0x98,0xbd,0x74};
4891     PCSTR addr4_Str = "::204.152.189.116";
4892 
4893     /* Test IPv4 addresses */
4894     in.s_addr = addr0_Num;
4895 
4896     pdst = inet_ntoa(*((struct in_addr*)&in.s_addr));
4897     ok(pdst != NULL, "inet_ntoa failed %s\n", dst);
4898     ok(!strcmp(pdst, addr0_Str),"Address %s != %s\n", pdst, addr0_Str);
4899 
4900     /* Test that inet_ntoa and inet_ntop return the same value */
4901     in.S_un.S_addr = addr1_Num;
4902     pdst = inet_ntoa(*((struct in_addr*)&in.s_addr));
4903     ok(pdst != NULL, "inet_ntoa failed %s\n", dst);
4904     ok(!strcmp(pdst, addr1_Str),"Address %s != %s\n", pdst, addr1_Str);
4905 
4906     /* InetNtop became available in Vista and Win2008 */
4907     if (!pInetNtop)
4908     {
4909         win_skip("InetNtop not present, not executing tests\n");
4910         return;
4911     }
4912 
4913     /* Second part of test */
4914     pdst = pInetNtop(AF_INET,(void*)&in.s_addr, dst, sizeof(dst));
4915     ok(pdst != NULL, "InetNtop failed %s\n", dst);
4916     ok(!strcmp(pdst, addr1_Str),"Address %s != %s\n", pdst, addr1_Str);
4917 
4918     /* Test invalid parm conditions */
4919     pdst = pInetNtop(1, (void*)&in.s_addr, dst, sizeof(dst));
4920     ok(pdst == NULL, "The pointer should not be returned (%p)\n", pdst);
4921     ok(WSAGetLastError() == WSAEAFNOSUPPORT, "Should be WSAEAFNOSUPPORT\n");
4922 
4923     /* Test Null destination */
4924     pdst = NULL;
4925     pdst = pInetNtop(AF_INET, (void*)&in.s_addr, NULL, sizeof(dst));
4926     ok(pdst == NULL, "The pointer should not be returned (%p)\n", pdst);
4927     ok(WSAGetLastError() == STATUS_INVALID_PARAMETER || WSAGetLastError() == WSAEINVAL /* Win7 */,
4928        "Should be STATUS_INVALID_PARAMETER or WSAEINVAL not 0x%x\n", WSAGetLastError());
4929 
4930     /* Test zero length passed */
4931     WSASetLastError(0);
4932     pdst = NULL;
4933     pdst = pInetNtop(AF_INET, (void*)&in.s_addr, dst, 0);
4934     ok(pdst == NULL, "The pointer should not be returned (%p)\n", pdst);
4935     ok(WSAGetLastError() == STATUS_INVALID_PARAMETER || WSAGetLastError() == WSAEINVAL /* Win7 */,
4936        "Should be STATUS_INVALID_PARAMETER or WSAEINVAL not 0x%x\n", WSAGetLastError());
4937 
4938     /* Test length one shorter than the address length */
4939     WSASetLastError(0);
4940     pdst = NULL;
4941     pdst = pInetNtop(AF_INET, (void*)&in.s_addr, dst, 6);
4942     ok(pdst == NULL, "The pointer should not be returned (%p)\n", pdst);
4943     ok(WSAGetLastError() == STATUS_INVALID_PARAMETER || WSAGetLastError() == WSAEINVAL /* Win7 */,
4944        "Should be STATUS_INVALID_PARAMETER or WSAEINVAL not 0x%x\n", WSAGetLastError());
4945 
4946     /* Test longer length is ok */
4947     WSASetLastError(0);
4948     pdst = NULL;
4949     pdst = pInetNtop(AF_INET, (void*)&in.s_addr, dst, sizeof(dst)+1);
4950     ok(pdst != NULL, "The pointer should  be returned (%p)\n", pdst);
4951     ok(!strcmp(pdst, addr1_Str),"Address %s != %s\n", pdst, addr1_Str);
4952 
4953     /* Test the IPv6 addresses */
4954 
4955     /* Test an zero prefixed IPV6 address */
4956     memcpy(in6.u.Byte, addr2_Num, sizeof(addr2_Num));
4957     pdst = pInetNtop(AF_INET6,(void*)&in6.s6_addr, dst6, sizeof(dst6));
4958     ok(pdst != NULL, "InetNtop failed %s\n", dst6);
4959     ok(!strcmp(pdst, addr2_Str),"Address %s != %s\n", pdst, addr2_Str);
4960 
4961     /* Test an zero suffixed IPV6 address */
4962     memcpy(in6.s6_addr, addr3_Num, sizeof(addr3_Num));
4963     pdst = pInetNtop(AF_INET6,(void*)&in6.s6_addr, dst6, sizeof(dst6));
4964     ok(pdst != NULL, "InetNtop failed %s\n", dst6);
4965     ok(!strcmp(pdst, addr3_Str),"Address %s != %s\n", pdst, addr3_Str);
4966 
4967     /* Test the IPv6 address contains the IPv4 address in IPv4 notation */
4968     memcpy(in6.s6_addr, addr4_Num, sizeof(addr4_Num));
4969     pdst = pInetNtop(AF_INET6, (void*)&in6.s6_addr, dst6, sizeof(dst6));
4970     ok(pdst != NULL, "InetNtop failed %s\n", dst6);
4971     ok(!strcmp(pdst, addr4_Str),"Address %s != %s\n", pdst, addr4_Str);
4972 
4973     /* Test invalid parm conditions */
4974     memcpy(in6.u.Byte, addr2_Num, sizeof(addr2_Num));
4975 
4976     /* Test Null destination */
4977     pdst = NULL;
4978     pdst = pInetNtop(AF_INET6, (void*)&in6.s6_addr, NULL, sizeof(dst6));
4979     ok(pdst == NULL, "The pointer should not be returned (%p)\n", pdst);
4980     ok(WSAGetLastError() == STATUS_INVALID_PARAMETER || WSAGetLastError() == WSAEINVAL /* Win7 */,
4981        "Should be STATUS_INVALID_PARAMETER or WSAEINVAL not 0x%x\n", WSAGetLastError());
4982 
4983     /* Test zero length passed */
4984     WSASetLastError(0);
4985     pdst = NULL;
4986     pdst = pInetNtop(AF_INET6, (void*)&in6.s6_addr, dst6, 0);
4987     ok(pdst == NULL, "The pointer should not be returned (%p)\n", pdst);
4988     ok(WSAGetLastError() == STATUS_INVALID_PARAMETER || WSAGetLastError() == WSAEINVAL /* Win7 */,
4989        "Should be STATUS_INVALID_PARAMETER or WSAEINVAL not 0x%x\n", WSAGetLastError());
4990 
4991     /* Test length one shorter than the address length */
4992     WSASetLastError(0);
4993     pdst = NULL;
4994     pdst = pInetNtop(AF_INET6, (void*)&in6.s6_addr, dst6, 16);
4995     ok(pdst == NULL, "The pointer should not be returned (%p)\n", pdst);
4996     ok(WSAGetLastError() == STATUS_INVALID_PARAMETER || WSAGetLastError() == WSAEINVAL /* Win7 */,
4997        "Should be STATUS_INVALID_PARAMETER or WSAEINVAL not 0x%x\n", WSAGetLastError());
4998 
4999     /* Test longer length is ok */
5000     WSASetLastError(0);
5001     pdst = NULL;
5002     pdst = pInetNtop(AF_INET6, (void*)&in6.s6_addr, dst6, 18);
5003     ok(pdst != NULL, "The pointer should be returned (%p)\n", pdst);
5004 }
5005 static void test_inet_pton(void)
5006 {
5007     struct TEST_DATA
5008     {
5009         int family, ret;
5010         DWORD err;
5011         const char *printable, *collapsed, *raw_data;
5012     } tests[] = {
5013         {AF_UNSPEC, -1, WSAEFAULT,    /* Test 0 */
5014         NULL, NULL, NULL},
5015         {AF_INET, -1, WSAEFAULT,
5016         NULL, NULL, NULL},
5017         {AF_INET6, -1, WSAEFAULT,
5018         NULL, NULL, NULL},
5019         {AF_UNSPEC, -1, WSAEAFNOSUPPORT,
5020         "127.0.0.1", NULL, NULL},
5021         {AF_INET, 1, 0,
5022         "127.0.0.1", "127.0.0.1",
5023         "\x7f\x00\x00\x01"},
5024         {AF_INET6, 0, 0,
5025         "127.0.0.1", "127.0.0.1", NULL},
5026         {AF_INET, 0, 0,
5027         "::1/128", NULL, NULL},
5028         {AF_INET6, 0, 0,
5029         "::1/128", NULL, NULL},
5030         {AF_UNSPEC, -1, WSAEAFNOSUPPORT,
5031         "broken", NULL, NULL},
5032         {AF_INET, 0, 0,
5033         "broken", NULL, NULL},
5034         {AF_INET6, 0, 0,              /* Test 10 */
5035         "broken", NULL, NULL},
5036         {AF_UNSPEC, -1, WSAEAFNOSUPPORT,
5037         "177.32.45.20", NULL, NULL},
5038         {AF_INET, 1, 0,
5039         "177.32.45.20", "177.32.45.20",
5040         "\xb1\x20\x2d\x14"},
5041         {AF_INET6, 0, 0,
5042         "177.32.45.20", NULL, NULL},
5043         {AF_INET, 0, 0,
5044         "2607:f0d0:1002:51::4", NULL, NULL},
5045         {AF_INET6, 1, 0,
5046         "2607:f0d0:1002:51::4", "2607:f0d0:1002:51::4",
5047         "\x26\x07\xf0\xd0\x10\x02\x00\x51\x00\x00\x00\x00\x00\x00\x00\x04"},
5048         {AF_INET, 0, 0,
5049         "::177.32.45.20", NULL, NULL},
5050         {AF_INET6, 1, 0,
5051         "::177.32.45.20", "::177.32.45.20",
5052         "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xb1\x20\x2d\x14"},
5053         {AF_INET, 0, 0,
5054         "fe80::0202:b3ff:fe1e:8329", NULL, NULL},
5055         {AF_INET6, 1, 0,
5056         "fe80::0202:b3ff:fe1e:8329", "fe80::202:b3ff:fe1e:8329",
5057         "\xfe\x80\x00\x00\x00\x00\x00\x00\x02\x02\xb3\xff\xfe\x1e\x83\x29"},
5058         {AF_INET6, 1, 0,              /* Test 20 */
5059         "fe80::202:b3ff:fe1e:8329", "fe80::202:b3ff:fe1e:8329",
5060         "\xfe\x80\x00\x00\x00\x00\x00\x00\x02\x02\xb3\xff\xfe\x1e\x83\x29"},
5061         {AF_INET, 0, 0,
5062         "a", NULL, NULL},
5063         {AF_INET, 0, 0,
5064         "a.b", NULL, NULL},
5065         {AF_INET, 0, 0,
5066         "a.b.c",  NULL, NULL},
5067         {AF_INET, 0, 0,
5068         "a.b.c.d", NULL, NULL},
5069         {AF_INET6, 1, 0,
5070         "2001:cdba:0000:0000:0000:0000:3257:9652", "2001:cdba::3257:9652",
5071         "\x20\x01\xcd\xba\x00\x00\x00\x00\x00\x00\x00\x00\x32\x57\x96\x52"},
5072         {AF_INET6, 1, 0,
5073         "2001:cdba::3257:9652", "2001:cdba::3257:9652",
5074         "\x20\x01\xcd\xba\x00\x00\x00\x00\x00\x00\x00\x00\x32\x57\x96\x52"},
5075         {AF_INET6, 1, 0,
5076         "2001:cdba:0:0:0:0:3257:9652", "2001:cdba::3257:9652",
5077         "\x20\x01\xcd\xba\x00\x00\x00\x00\x00\x00\x00\x00\x32\x57\x96\x52"}
5078     };
5079     int i, ret;
5080     DWORD err;
5081     char buffer[64],str[64];
5082     WCHAR printableW[64], collapsedW[64];
5083     const char *ptr;
5084     const WCHAR *ptrW;
5085 
5086     /* InetNtop and InetPton became available in Vista and Win2008 */
5087     if (!pInetNtop || !pInetNtopW || !pInetPtonA || !pInetPtonW)
5088     {
5089         win_skip("InetNtop and/or InetPton not present, not executing tests\n");
5090         return;
5091     }
5092 
5093     for (i = 0; i < sizeof(tests) / sizeof(tests[0]); i++)
5094     {
5095         WSASetLastError(0xdeadbeef);
5096         ret = pInetPtonA(tests[i].family, tests[i].printable, buffer);
5097         ok (ret == tests[i].ret, "Test [%d]: Expected %d, got %d\n", i, tests[i].ret, ret);
5098         if (tests[i].ret == -1)
5099         {
5100             err = WSAGetLastError();
5101             ok (tests[i].err == err, "Test [%d]: Expected 0x%x, got 0x%x\n", i, tests[i].err, err);
5102         }
5103         if (tests[i].ret != 1) continue;
5104         ok (memcmp(buffer, tests[i].raw_data,
5105             tests[i].family == AF_INET ? sizeof(struct in_addr) : sizeof(struct in6_addr)) == 0,
5106             "Test [%d]: Expected binary data differs\n", i);
5107 
5108         /* Test the result from Pton with Ntop */
5109         strcpy (str, "deadbeef");
5110         ptr = pInetNtop(tests[i].family, buffer, str, sizeof(str));
5111         ok (ptr != NULL, "Test [%d]: Failed with NULL\n", i);
5112         ok (ptr == str, "Test [%d]: Pointers differ (%p != %p)\n", i, ptr, str);
5113         if (!ptr) continue;
5114         ok (strcmp(ptr, tests[i].collapsed) == 0, "Test [%d]: Expected '%s', got '%s'\n",
5115             i, tests[i].collapsed, ptr);
5116     }
5117 
5118     for (i = 0; i < sizeof(tests) / sizeof(tests[0]); i++)
5119     {
5120         if (tests[i].printable)
5121             MultiByteToWideChar(CP_ACP, 0, tests[i].printable, -1, printableW,
5122                                 sizeof(printableW) / sizeof(printableW[0]));
5123         WSASetLastError(0xdeadbeef);
5124         ret = pInetPtonW(tests[i].family, tests[i].printable ? printableW : NULL, buffer);
5125         ok(ret == tests[i].ret, "Test [%d]: Expected %d, got %d\n", i, tests[i].ret, ret);
5126         if (tests[i].ret == -1)
5127         {
5128             err = WSAGetLastError();
5129             ok(tests[i].err == err, "Test [%d]: Expected 0x%x, got 0x%x\n", i, tests[i].err, err);
5130         }
5131         if (tests[i].ret != 1) continue;
5132         ok(memcmp(buffer, tests[i].raw_data,
5133            tests[i].family == AF_INET ? sizeof(struct in_addr) : sizeof(struct in6_addr)) == 0,
5134            "Test [%d]: Expected binary data differs\n", i);
5135 
5136         /* Test the result from Pton with Ntop */
5137         printableW[0] = 0xdead;
5138         ptrW = pInetNtopW(tests[i].family, buffer, printableW, sizeof(printableW) / sizeof(printableW[0]));
5139         ok (ptrW != NULL, "Test [%d]: Failed with NULL\n", i);
5140         ok (ptrW == printableW, "Test [%d]: Pointers differ (%p != %p)\n", i, ptrW, printableW);
5141         if (!ptrW) continue;
5142 
5143         MultiByteToWideChar(CP_ACP, 0, tests[i].collapsed, -1, collapsedW,
5144                             sizeof(collapsedW) / sizeof(collapsedW[0]));
5145         ok (lstrcmpW(ptrW, collapsedW) == 0, "Test [%d]: Expected '%s', got '%s'\n",
5146             i, tests[i].collapsed, wine_dbgstr_w(ptrW));
5147     }
5148 }
5149 
5150 static void test_ioctlsocket(void)
5151 {
5152     SOCKET sock, src, dst;
5153     struct tcp_keepalive kalive;
5154     int ret, optval;
5155     static const LONG cmds[] = {FIONBIO, FIONREAD, SIOCATMARK};
5156     UINT i, bytes_rec;
5157     char data;
5158     WSABUF bufs;
5159     u_long arg = 0;
5160 
5161     sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
5162     ok(sock != INVALID_SOCKET, "Creating the socket failed: %d\n", WSAGetLastError());
5163     if(sock == INVALID_SOCKET)
5164     {
5165         skip("Can't continue without a socket.\n");
5166         return;
5167     }
5168 
5169     for(i = 0; i < sizeof(cmds)/sizeof(cmds[0]); i++)
5170     {
5171         /* broken apps like defcon pass the argp value directly instead of a pointer to it */
5172         ret = ioctlsocket(sock, cmds[i], (u_long *)1);
5173         ok(ret == SOCKET_ERROR, "ioctlsocket succeeded unexpectedly\n");
5174         ret = WSAGetLastError();
5175         ok(ret == WSAEFAULT, "expected WSAEFAULT, got %d instead\n", ret);
5176     }
5177 
5178     /* A fresh and not connected socket has no urgent data, this test shows
5179      * that normal(not urgent) data returns a non-zero value for SIOCATMARK. */
5180 
5181     ret = ioctlsocket(sock, SIOCATMARK, &arg);
5182     ok(ret != SOCKET_ERROR, "ioctlsocket failed unexpectedly\n");
5183     ok(arg, "SIOCATMARK expected a non-zero value\n");
5184 
5185     /* when SO_OOBINLINE is set SIOCATMARK must always return TRUE */
5186     optval = 1;
5187     ret = setsockopt(sock, SOL_SOCKET, SO_OOBINLINE, (void *)&optval, sizeof(optval));
5188     ok(ret != SOCKET_ERROR, "setsockopt failed unexpectedly\n");
5189     arg = 0;
5190     ret = ioctlsocket(sock, SIOCATMARK, &arg);
5191     ok(ret != SOCKET_ERROR, "ioctlsocket failed unexpectedly\n");
5192     ok(arg, "SIOCATMARK expected a non-zero value\n");
5193 
5194     /* disable SO_OOBINLINE and get the same old behavior */
5195     optval = 0;
5196     ret = setsockopt(sock, SOL_SOCKET, SO_OOBINLINE, (void *)&optval, sizeof(optval));
5197     ok(ret != SOCKET_ERROR, "setsockopt failed unexpectedly\n");
5198     arg = 0;
5199     ret = ioctlsocket(sock, SIOCATMARK, &arg);
5200     ok(ret != SOCKET_ERROR, "ioctlsocket failed unexpectedly\n");
5201     ok(arg, "SIOCATMARK expected a non-zero value\n");
5202 
5203     ret = WSAIoctl(sock, SIO_KEEPALIVE_VALS, &arg, 0, NULL, 0, &arg, NULL, NULL);
5204     ok(ret == SOCKET_ERROR, "WSAIoctl succeeded unexpectedly\n");
5205     ret = WSAGetLastError();
5206     ok(ret == WSAEFAULT || broken(ret == WSAEINVAL), "expected WSAEFAULT, got %d instead\n", ret);
5207 
5208     ret = WSAIoctl(sock, SIO_KEEPALIVE_VALS, NULL, sizeof(struct tcp_keepalive), NULL, 0, &arg, NULL, NULL);
5209     ok(ret == SOCKET_ERROR, "WSAIoctl succeeded unexpectedly\n");
5210     ret = WSAGetLastError();
5211     ok(ret == WSAEFAULT || broken(ret == WSAEINVAL), "expected WSAEFAULT, got %d instead\n", ret);
5212 
5213     /* broken used to catch W95, W98, NT4 */
5214     make_keepalive(kalive, 0, 0, 0);
5215     ret = WSAIoctl(sock, SIO_KEEPALIVE_VALS, &kalive, sizeof(struct tcp_keepalive), NULL, 0, &arg, NULL, NULL);
5216     ok(ret == 0 || broken(ret == SOCKET_ERROR), "WSAIoctl failed unexpectedly\n");
5217 
5218     make_keepalive(kalive, 1, 0, 0);
5219     ret = WSAIoctl(sock, SIO_KEEPALIVE_VALS, &kalive, sizeof(struct tcp_keepalive), NULL, 0, &arg, NULL, NULL);
5220     ok(ret == 0 || broken(ret == SOCKET_ERROR), "WSAIoctl failed unexpectedly\n");
5221 
5222     make_keepalive(kalive, 1, 1000, 1000);
5223     ret = WSAIoctl(sock, SIO_KEEPALIVE_VALS, &kalive, sizeof(struct tcp_keepalive), NULL, 0, &arg, NULL, NULL);
5224     ok(ret == 0 || broken(ret == SOCKET_ERROR), "WSAIoctl failed unexpectedly\n");
5225 
5226     make_keepalive(kalive, 1, 10000, 10000);
5227     ret = WSAIoctl(sock, SIO_KEEPALIVE_VALS, &kalive, sizeof(struct tcp_keepalive), NULL, 0, &arg, NULL, NULL);
5228     ok(ret == 0 || broken(ret == SOCKET_ERROR), "WSAIoctl failed unexpectedly\n");
5229 
5230     make_keepalive(kalive, 1, 100, 100);
5231     ret = WSAIoctl(sock, SIO_KEEPALIVE_VALS, &kalive, sizeof(struct tcp_keepalive), NULL, 0, &arg, NULL, NULL);
5232     ok(ret == 0 || broken(ret == SOCKET_ERROR), "WSAIoctl failed unexpectedly\n");
5233 
5234     make_keepalive(kalive, 0, 100, 100);
5235     ret = WSAIoctl(sock, SIO_KEEPALIVE_VALS, &kalive, sizeof(struct tcp_keepalive), NULL, 0, &arg, NULL, NULL);
5236     ok(ret == 0 || broken(ret == SOCKET_ERROR), "WSAIoctl failed unexpectedly\n");
5237 
5238     closesocket(sock);
5239 
5240     if (tcp_socketpair(&src, &dst) != 0)
5241     {
5242         ok(0, "creating socket pair failed, skipping test\n");
5243         return;
5244     }
5245 
5246     /* test FIONREAD on TCP sockets */
5247     optval = 0xdeadbeef;
5248     ret = WSAIoctl(dst, FIONREAD, NULL, 0, &optval, sizeof(optval), &arg, NULL, NULL);
5249     ok(ret == 0, "WSAIoctl failed unexpectedly with error %d\n", WSAGetLastError());
5250     ok(optval == 0, "FIONREAD should have returned 0 bytes, got %d instead\n", optval);
5251 
5252     optval = 0xdeadbeef;
5253     ok(send(src, "TEST", 4, 0) == 4, "failed to send test data\n");
5254     Sleep(100);
5255     ret = WSAIoctl(dst, FIONREAD, NULL, 0, &optval, sizeof(optval), &arg, NULL, NULL);
5256     ok(ret == 0, "WSAIoctl failed unexpectedly with error %d\n", WSAGetLastError());
5257     ok(optval == 4, "FIONREAD should have returned 4 bytes, got %d instead\n", optval);
5258 
5259     /* trying to read from an OOB inlined socket with MSG_OOB results in WSAEINVAL */
5260     set_blocking(dst, FALSE);
5261     i = MSG_OOB;
5262     SetLastError(0xdeadbeef);
5263     ret = recv(dst, &data, 1, i);
5264     ok(ret == SOCKET_ERROR, "expected -1, got %d\n", ret);
5265     ret = GetLastError();
5266     ok(ret == WSAEWOULDBLOCK, "expected 10035, got %d\n", ret);
5267     bufs.len = sizeof(char);
5268     bufs.buf = &data;
5269     ret = WSARecv(dst, &bufs, 1, &bytes_rec, &i, NULL, NULL);
5270     ok(ret == SOCKET_ERROR, "expected -1, got %d\n", ret);
5271     ret = GetLastError();
5272     ok(ret == WSAEWOULDBLOCK, "expected 10035, got %d\n", ret);
5273     optval = 1;
5274     ret = setsockopt(dst, SOL_SOCKET, SO_OOBINLINE, (void *)&optval, sizeof(optval));
5275     ok(ret != SOCKET_ERROR, "setsockopt failed unexpectedly\n");
5276     i = MSG_OOB;
5277     SetLastError(0xdeadbeef);
5278     ret = recv(dst, &data, 1, i);
5279     if (ret == SOCKET_ERROR)
5280     {
5281         ret = GetLastError();
5282         ok(ret == WSAEINVAL, "expected 10022, got %d\n", ret);
5283         bufs.len = sizeof(char);
5284         bufs.buf = &data;
5285         ret = WSARecv(dst, &bufs, 1, &bytes_rec, &i, NULL, NULL);
5286         ok(ret == SOCKET_ERROR, "expected -1, got %d\n", ret);
5287         ret = GetLastError();
5288         ok(ret == WSAEINVAL, "expected 10022, got %d\n", ret);
5289     }
5290     else ok(broken(ret == 1) /* <= NT4 */, "expected error, got 1\n");
5291 
5292     closesocket(dst);
5293     optval = 0xdeadbeef;
5294     ret = WSAIoctl(dst, FIONREAD, NULL, 0, &optval, sizeof(optval), &arg, NULL, NULL);
5295     ok(ret == SOCKET_ERROR, "WSAIoctl succeeded unexpectedly\n");
5296     ok(optval == 0xdeadbeef, "FIONREAD should not have changed last error, got %d instead\n", optval);
5297     closesocket(src);
5298 }
5299 
5300 static BOOL drain_pause = FALSE;
5301 static DWORD WINAPI drain_socket_thread(LPVOID arg)
5302 {
5303     char buffer[1024];
5304     SOCKET sock = *(SOCKET*)arg;
5305     int ret;
5306 
5307     while ((ret = recv(sock, buffer, sizeof(buffer), 0)) != 0)
5308     {
5309         if (ret < 0)
5310         {
5311             if (WSAGetLastError() == WSAEWOULDBLOCK)
5312             {
5313                 fd_set readset;
5314                 FD_ZERO(&readset);
5315                 FD_SET(sock, &readset);
5316                 select(sock+1, &readset, NULL, NULL, NULL);
5317                 while (drain_pause)
5318                     Sleep(100);
5319             }
5320             else
5321                 break;
5322         }
5323     }
5324     return 0;
5325 }
5326 
5327 static void test_send(void)
5328 {
5329     SOCKET src = INVALID_SOCKET;
5330     SOCKET dst = INVALID_SOCKET;
5331     HANDLE hThread = NULL;
5332     const int buflen = 1024*1024;
5333     char *buffer = NULL;
5334     int ret, i, zero = 0;
5335     WSABUF buf;
5336     OVERLAPPED ov;
5337     BOOL bret;
5338     DWORD id, bytes_sent, dwRet;
5339     DWORD expected_time, connect_time;
5340     socklen_t optlen;
5341 
5342     memset(&ov, 0, sizeof(ov));
5343 
5344     if (tcp_socketpair(&src, &dst) != 0)
5345     {
5346         ok(0, "creating socket pair failed, skipping test\n");
5347         return;
5348     }
5349     expected_time = GetTickCount();
5350 
5351     set_blocking(dst, FALSE);
5352     /* force disable buffering so we can get a pending overlapped request */
5353     ret = setsockopt(dst, SOL_SOCKET, SO_SNDBUF, (char *) &zero, sizeof(zero));
5354     ok(!ret, "setsockopt SO_SNDBUF failed: %d - %d\n", ret, GetLastError());
5355 
5356     hThread = CreateThread(NULL, 0, drain_socket_thread, &dst, 0, &id);
5357     if (hThread == NULL)
5358     {
5359         ok(0, "CreateThread failed, error %d\n", GetLastError());
5360         goto end;
5361     }
5362 
5363     buffer = HeapAlloc(GetProcessHeap(), 0, buflen);
5364     if (buffer == NULL)
5365     {
5366         ok(0, "HeapAlloc failed, error %d\n", GetLastError());
5367         goto end;
5368     }
5369 
5370     /* fill the buffer with some nonsense */
5371     for (i = 0; i < buflen; ++i)
5372     {
5373         buffer[i] = (char) i;
5374     }
5375 
5376     ret = send(src, buffer, buflen, 0);
5377     if (ret >= 0)
5378         ok(ret == buflen, "send should have sent %d bytes, but it only sent %d\n", buflen, ret);
5379     else
5380         ok(0, "send failed, error %d\n", WSAGetLastError());
5381 
5382     buf.buf = buffer;
5383     buf.len = buflen;
5384 
5385     ov.hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
5386     ok(ov.hEvent != NULL, "could not create event object, errno = %d\n", GetLastError());
5387     if (!ov.hEvent)
5388         goto end;
5389 
5390     bytes_sent = 0;
5391     WSASetLastError(12345);
5392     ret = WSASend(dst, &buf, 1, &bytes_sent, 0, &ov, NULL);
5393     ok((ret == SOCKET_ERROR && WSAGetLastError() == ERROR_IO_PENDING) || broken(bytes_sent == buflen),
5394        "Failed to start overlapped send %d - %d - %d/%d\n", ret, WSAGetLastError(), bytes_sent, buflen);
5395 
5396     /* don't check for completion yet, we may need to drain the buffer while still sending */
5397     set_blocking(src, FALSE);
5398     for (i = 0; i < buflen; ++i)
5399     {
5400         int j = 0;
5401 
5402         ret = recv(src, buffer, 1, 0);
5403         while (ret == SOCKET_ERROR && GetLastError() == WSAEWOULDBLOCK && j < 100)
5404         {
5405             j++;
5406             Sleep(50);
5407             ret = recv(src, buffer, 1, 0);
5408         }
5409 
5410         ok(ret == 1, "Failed to receive data %d - %d (got %d/%d)\n", ret, GetLastError(), i, buflen);
5411         if (ret != 1)
5412             break;
5413 
5414         ok(buffer[0] == (char) i, "Received bad data at position %d\n", i);
5415     }
5416 
5417     dwRet = WaitForSingleObject(ov.hEvent, 1000);
5418     ok(dwRet == WAIT_OBJECT_0, "Failed to wait for recv message: %d - %d\n", dwRet, GetLastError());
5419     if (dwRet == WAIT_OBJECT_0)
5420     {
5421         bret = GetOverlappedResult((HANDLE)dst, &ov, &bytes_sent, FALSE);
5422         ok((bret && bytes_sent == buflen) || broken(!bret && GetLastError() == ERROR_IO_INCOMPLETE) /* win9x */,
5423            "Got %d instead of %d (%d - %d)\n", bytes_sent, buflen, bret, GetLastError());
5424     }
5425 
5426     WSASetLastError(12345);
5427     ret = WSASend(INVALID_SOCKET, &buf, 1, NULL, 0, &ov, NULL);
5428     ok(ret == SOCKET_ERROR && WSAGetLastError() == WSAENOTSOCK,
5429        "WSASend failed %d - %d\n", ret, WSAGetLastError());
5430 
5431     WSASetLastError(12345);
5432     ret = WSASend(dst, &buf, 1, NULL, 0, &ov, NULL);
5433     ok(ret == SOCKET_ERROR && WSAGetLastError() == ERROR_IO_PENDING,
5434        "Failed to start overlapped send %d - %d\n", ret, WSAGetLastError());
5435 
5436     expected_time = (GetTickCount() - expected_time) / 1000;
5437 
5438     connect_time = 0xdeadbeef;
5439     optlen = sizeof(connect_time);
5440     ret = getsockopt(dst, SOL_SOCKET, SO_CONNECT_TIME, (char *)&connect_time, &optlen);
5441     ok(!ret, "getsockopt failed %d\n", WSAGetLastError());
5442     ok(connect_time >= expected_time && connect_time <= expected_time + 1,
5443        "unexpected connect time %u, expected %u\n", connect_time, expected_time);
5444 
5445     connect_time = 0xdeadbeef;
5446     optlen = sizeof(connect_time);
5447     ret = getsockopt(src, SOL_SOCKET, SO_CONNECT_TIME, (char *)&connect_time, &optlen);
5448     ok(!ret, "getsockopt failed %d\n", WSAGetLastError());
5449     ok(connect_time >= expected_time && connect_time <= expected_time + 1,
5450        "unexpected connect time %u, expected %u\n", connect_time, expected_time);
5451 
5452 end:
5453     if (src != INVALID_SOCKET)
5454         closesocket(src);
5455     if (dst != INVALID_SOCKET)
5456         closesocket(dst);
5457     if (hThread != NULL)
5458     {
5459         dwRet = WaitForSingleObject(hThread, 500);
5460         ok(dwRet == WAIT_OBJECT_0, "failed to wait for thread termination: %d\n", GetLastError());
5461         CloseHandle(hThread);
5462     }
5463     if (ov.hEvent)
5464         CloseHandle(ov.hEvent);
5465     HeapFree(GetProcessHeap(), 0, buffer);
5466 }
5467 
5468 typedef struct async_message
5469 {
5470     SOCKET socket;
5471     LPARAM lparam;
5472     struct async_message *next;
5473 } async_message;
5474 
5475 static struct async_message *messages_received;
5476 
5477 #define WM_SOCKET (WM_USER+100)
5478 static LRESULT CALLBACK ws2_test_WndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
5479 {
5480     struct async_message *message;
5481 
5482     switch (msg)
5483     {
5484     case WM_SOCKET:
5485         message = HeapAlloc(GetProcessHeap(), 0, sizeof(*message));
5486         message->socket = (SOCKET) wparam;
5487         message->lparam = lparam;
5488         message->next = NULL;
5489 
5490         if (messages_received)
5491         {
5492             struct async_message *last = messages_received;
5493             while (last->next) last = last->next;
5494             last->next = message;
5495         }
5496         else
5497             messages_received = message;
5498         return 0;
5499     }
5500 
5501     return DefWindowProcA(hwnd, msg, wparam, lparam);
5502 }
5503 
5504 static void get_event_details(int event, int *bit, char *name)
5505 {
5506     switch (event)
5507     {
5508         case FD_ACCEPT:
5509             if (bit) *bit = FD_ACCEPT_BIT;
5510             if (name) strcpy(name, "FD_ACCEPT");
5511             break;
5512         case FD_CONNECT:
5513             if (bit) *bit = FD_CONNECT_BIT;
5514             if (name) strcpy(name, "FD_CONNECT");
5515             break;
5516         case FD_READ:
5517             if (bit) *bit = FD_READ_BIT;
5518             if (name) strcpy(name, "FD_READ");
5519             break;
5520         case FD_OOB:
5521             if (bit) *bit = FD_OOB_BIT;
5522             if (name) strcpy(name, "FD_OOB");
5523             break;
5524         case FD_WRITE:
5525             if (bit) *bit = FD_WRITE_BIT;
5526             if (name) strcpy(name, "FD_WRITE");
5527             break;
5528         case FD_CLOSE:
5529             if (bit) *bit = FD_CLOSE_BIT;
5530             if (name) strcpy(name, "FD_CLOSE");
5531             break;
5532         default:
5533             if (bit) *bit = -1;
5534             if (name) sprintf(name, "bad%x", event);
5535     }
5536 }
5537 
5538 static const char *dbgstr_event_seq(const LPARAM *seq)
5539 {
5540     static char message[1024];
5541     char name[12];
5542     int len = 1;
5543 
5544     message[0] = '[';
5545     message[1] = 0;
5546     while (*seq)
5547     {
5548         get_event_details(WSAGETSELECTEVENT(*seq), NULL, name);
5549         len += sprintf(message + len, "%s(%d) ", name, WSAGETSELECTERROR(*seq));
5550         seq++;
5551     }
5552     if (len > 1) len--;
5553     strcpy( message + len, "]" );
5554     return message;
5555 }
5556 
5557 static char *dbgstr_event_seq_result(SOCKET s, WSANETWORKEVENTS *netEvents)
5558 {
5559     static char message[1024];
5560     struct async_message *curr = messages_received;
5561     int index, error, bit = 0;
5562     char name[12];
5563     int len = 1;
5564 
5565     message[0] = '[';
5566     message[1] = 0;
5567     while (1)
5568     {
5569         if (netEvents)
5570         {
5571             if (bit >= FD_MAX_EVENTS) break;
5572             if ( !(netEvents->lNetworkEvents & (1 << bit)) )
5573             {
5574                 bit++;
5575                 continue;
5576             }
5577             get_event_details(1 << bit, &index, name);
5578             error = netEvents->iErrorCode[index];
5579             bit++;
5580         }
5581         else
5582         {
5583             if (!curr) break;
5584             if (curr->socket != s)
5585             {
5586                 curr = curr->next;
5587                 continue;
5588             }
5589             get_event_details(WSAGETSELECTEVENT(curr->lparam), NULL, name);
5590             error = WSAGETSELECTERROR(curr->lparam);
5591             curr = curr->next;
5592         }
5593 
5594         len += sprintf(message + len, "%s(%d) ", name, error);
5595     }
5596     if (len > 1) len--;
5597     strcpy( message + len, "]" );
5598     return message;
5599 }
5600 
5601 static void flush_events(SOCKET s, HANDLE hEvent)
5602 {
5603     WSANETWORKEVENTS netEvents;
5604     struct async_message *prev = NULL, *curr = messages_received;
5605     int ret;
5606     DWORD dwRet;
5607 
5608     if (hEvent != INVALID_HANDLE_VALUE)
5609     {
5610         dwRet = WaitForSingleObject(hEvent, 100);
5611         if (dwRet == WAIT_OBJECT_0)
5612         {
5613             ret = WSAEnumNetworkEvents(s, hEvent, &netEvents);
5614             if (ret)
5615                 ok(0, "WSAEnumNetworkEvents failed, error %d\n", ret);
5616         }
5617     }
5618     else
5619     {
5620         while (curr)
5621         {
5622             if (curr->socket == s)
5623             {
5624                 if (prev) prev->next = curr->next;
5625                 else messages_received = curr->next;
5626 
5627                 HeapFree(GetProcessHeap(), 0, curr);
5628 
5629                 if (prev) curr = prev->next;
5630                 else curr = messages_received;
5631             }
5632             else
5633             {
5634                 prev = curr;
5635                 curr = curr->next;
5636             }
5637         }
5638     }
5639 }
5640 
5641 static int match_event_sequence(SOCKET s, WSANETWORKEVENTS *netEvents, const LPARAM *seq)
5642 {
5643     int event, index, error, events;
5644     struct async_message *curr;
5645 
5646     if (netEvents)
5647     {
5648         events = netEvents->lNetworkEvents;
5649         while (*seq)
5650         {
5651             event = WSAGETSELECTEVENT(*seq);
5652             error = WSAGETSELECTERROR(*seq);
5653             get_event_details(event, &index, NULL);
5654 
5655             if (!(events & event) && index != -1)
5656                 return 0;
5657             if (events & event && index != -1)
5658             {
5659                 if (netEvents->iErrorCode[index] != error)
5660                     return 0;
5661             }
5662             events &= ~event;
5663             seq++;
5664         }
5665         if (events)
5666             return 0;
5667     }
5668     else
5669     {
5670         curr = messages_received;
5671         while (curr)
5672         {
5673             if (curr->socket == s)
5674             {
5675                 if (!*seq) return 0;
5676                 if (*seq != curr->lparam) return 0;
5677                 seq++;
5678             }
5679             curr = curr->next;
5680         }
5681         if (*seq)
5682             return 0;
5683     }
5684     return 1;
5685 }
5686 
5687 /* checks for a sequence of events, (order only checked if window is used) */
5688 static void ok_event_sequence(SOCKET s, HANDLE hEvent, const LPARAM *seq, const LPARAM **broken_seqs, int completelyBroken)
5689 {
5690     MSG msg;
5691     WSANETWORKEVENTS events, *netEvents = NULL;
5692     int ret;
5693     DWORD dwRet;
5694 
5695     if (hEvent != INVALID_HANDLE_VALUE)
5696     {
5697         netEvents = &events;
5698 
5699         dwRet = WaitForSingleObject(hEvent, 200);
5700         if (dwRet == WAIT_OBJECT_0)
5701         {
5702             ret = WSAEnumNetworkEvents(s, hEvent, netEvents);
5703             if (ret)
5704             {
5705                 winetest_ok(0, "WSAEnumNetworkEvents failed, error %d\n", ret);
5706                 return;
5707             }
5708         }
5709         else
5710             memset(netEvents, 0, sizeof(*netEvents));
5711     }
5712     else
5713     {
5714         Sleep(200);
5715         /* Run the message loop a little */
5716         while (PeekMessageA( &msg, 0, 0, 0, PM_REMOVE ))
5717         {
5718             DispatchMessageA(&msg);
5719         }
5720     }
5721 
5722     if (match_event_sequence(s, netEvents, seq))
5723     {
5724         winetest_ok(1, "Sequence matches expected: %s\n", dbgstr_event_seq(seq));
5725         flush_events(s, hEvent);
5726         return;
5727     }
5728 
5729     if (broken_seqs)
5730     {
5731         for (; *broken_seqs; broken_seqs++)
5732         {
5733             if (match_event_sequence(s, netEvents, *broken_seqs))
5734             {
5735                 winetest_ok(broken(1), "Sequence matches broken: %s, expected %s\n", dbgstr_event_seq_result(s, netEvents), dbgstr_event_seq(seq));
5736                 flush_events(s, hEvent);
5737                 return;
5738             }
5739         }
5740     }
5741 
5742     winetest_ok(broken(completelyBroken), "Expected event sequence %s, got %s\n", dbgstr_event_seq(seq),
5743                 dbgstr_event_seq_result(s, netEvents));
5744     flush_events(s, hEvent);
5745 }
5746 
5747 #define ok_event_seq (winetest_set_location(__FILE__, __LINE__), 0) ? (void)0 : ok_event_sequence
5748 
5749 static void test_events(int useMessages)
5750 {
5751     SOCKET server = INVALID_SOCKET;
5752     SOCKET src = INVALID_SOCKET, src2 = INVALID_SOCKET;
5753     SOCKET dst = INVALID_SOCKET, dst2 = INVALID_SOCKET;
5754     struct sockaddr_in addr;
5755     HANDLE hThread = NULL;
5756     HANDLE hEvent = INVALID_HANDLE_VALUE, hEvent2 = INVALID_HANDLE_VALUE;
5757     WNDCLASSEXA wndclass;
5758     HWND hWnd = NULL;
5759     char *buffer = NULL;
5760     int bufferSize = 1024*1024;
5761     WSABUF bufs;
5762     OVERLAPPED ov, ov2;
5763     DWORD flags = 0;
5764     DWORD bytesReturned;
5765     DWORD id;
5766     int len;
5767     int ret;
5768     DWORD dwRet;
5769     BOOL bret;
5770     static char szClassName[] = "wstestclass";
5771     const LPARAM *broken_seq[3];
5772     static const LPARAM empty_seq[] = { 0 };
5773     static const LPARAM close_seq[] = { WSAMAKESELECTREPLY(FD_CLOSE, 0), 0 };
5774     static const LPARAM write_seq[] = { WSAMAKESELECTREPLY(FD_WRITE, 0), 0 };
5775     static const LPARAM read_seq[] = { WSAMAKESELECTREPLY(FD_READ, 0), 0 };
5776     static const LPARAM oob_seq[] = { WSAMAKESELECTREPLY(FD_OOB, 0), 0 };
5777     static const LPARAM connect_seq[] = { WSAMAKESELECTREPLY(FD_CONNECT, 0),
5778                                           WSAMAKESELECTREPLY(FD_WRITE, 0), 0 };
5779     static const LPARAM read_read_seq[] = { WSAMAKESELECTREPLY(FD_READ, 0),
5780                                             WSAMAKESELECTREPLY(FD_READ, 0), 0 };
5781     static const LPARAM read_write_seq[] = { WSAMAKESELECTREPLY(FD_READ, 0),
5782                                              WSAMAKESELECTREPLY(FD_WRITE, 0), 0 };
5783     static const LPARAM read_close_seq[] = { WSAMAKESELECTREPLY(FD_READ, 0),
5784                                              WSAMAKESELECTREPLY(FD_CLOSE, 0), 0 };
5785 
5786     memset(&ov, 0, sizeof(ov));
5787     memset(&ov2, 0, sizeof(ov2));
5788 
5789     /* don't use socketpair, we want connection event */
5790     src = socket(AF_INET, SOCK_STREAM, 0);
5791     if (src == INVALID_SOCKET)
5792     {
5793         ok(0, "creating socket pair failed (%d), skipping test\n", GetLastError());
5794         goto end;
5795     }
5796 
5797     ret = set_blocking(src, TRUE);
5798     ok(!ret, "set_blocking failed, error %d\n", WSAGetLastError());
5799 
5800     src2 = socket(AF_INET, SOCK_STREAM, 0);
5801     if (src2 == INVALID_SOCKET)
5802     {
5803         ok(0, "creating socket pair failed (%d), skipping test\n", GetLastError());
5804         goto end;
5805     }
5806 
5807     ret = set_blocking(src2, TRUE);
5808     ok(!ret, "set_blocking failed, error %d\n", WSAGetLastError());
5809 
5810     len = sizeof(BOOL);
5811     if (getsockopt(src, SOL_SOCKET, SO_OOBINLINE, (void *)&bret, &len) == SOCKET_ERROR)
5812     {
5813         ok(0, "failed to get oobinline status, %d\n", GetLastError());
5814         goto end;
5815     }
5816     ok(bret == FALSE, "OOB not inline\n");
5817 
5818     if (useMessages)
5819     {
5820         trace("Event test using messages\n");
5821 
5822         wndclass.cbSize         = sizeof(wndclass);
5823         wndclass.style          = CS_HREDRAW | CS_VREDRAW;
5824         wndclass.lpfnWndProc    = ws2_test_WndProc;
5825         wndclass.cbClsExtra     = 0;
5826         wndclass.cbWndExtra     = 0;
5827         wndclass.hInstance      = GetModuleHandleA(NULL);
5828         wndclass.hIcon          = LoadIconA(NULL, (LPCSTR)IDI_APPLICATION);
5829         wndclass.hIconSm        = LoadIconA(NULL, (LPCSTR)IDI_APPLICATION);
5830         wndclass.hCursor        = LoadCursorA(NULL, (LPCSTR)IDC_ARROW);
5831         wndclass.hbrBackground  = (HBRUSH)(COLOR_WINDOW + 1);
5832         wndclass.lpszClassName  = szClassName;
5833         wndclass.lpszMenuName   = NULL;
5834         RegisterClassExA(&wndclass);
5835 
5836         hWnd = CreateWindowA(szClassName, "WS2Test", WS_OVERLAPPEDWINDOW,
5837                             0, 0, 500, 500, NULL, NULL, GetModuleHandleA(NULL), NULL);
5838         if (!hWnd)
5839         {
5840             ok(0, "failed to create window: %d\n", GetLastError());
5841             return;
5842         }
5843 
5844         ret = WSAAsyncSelect(src, hWnd, WM_SOCKET, FD_CONNECT | FD_READ | FD_OOB | FD_WRITE | FD_CLOSE);
5845         if (ret)
5846         {
5847             ok(0, "WSAAsyncSelect failed, error %d\n", ret);
5848             goto end;
5849         }
5850 
5851         ok(set_blocking(src, TRUE) == SOCKET_ERROR, "set_blocking should failed!\n");
5852         ok(WSAGetLastError() == WSAEINVAL, "expect WSAEINVAL, returned %x\n", WSAGetLastError());
5853 
5854         ret = WSAAsyncSelect(src2, hWnd, WM_SOCKET, FD_CONNECT | FD_READ | FD_OOB | FD_WRITE | FD_CLOSE);
5855         if (ret)
5856         {
5857             ok(0, "WSAAsyncSelect failed, error %d\n", ret);
5858             goto end;
5859         }
5860 
5861         ok(set_blocking(src2, TRUE) == SOCKET_ERROR, "set_blocking should failed!\n");
5862         ok(WSAGetLastError() == WSAEINVAL, "expect WSAEINVAL, returned %x\n", WSAGetLastError());
5863     }
5864     else
5865     {
5866         trace("Event test using events\n");
5867 
5868         hEvent = WSACreateEvent();
5869         if (hEvent == INVALID_HANDLE_VALUE)
5870         {
5871             ok(0, "WSACreateEvent failed, error %d\n", GetLastError());
5872             goto end;
5873         }
5874 
5875         hEvent2 = WSACreateEvent();
5876         if (hEvent2 == INVALID_HANDLE_VALUE)
5877         {
5878             ok(0, "WSACreateEvent failed, error %d\n", GetLastError());
5879             goto end;
5880         }
5881 
5882         ret = WSAEventSelect(src, hEvent, FD_CONNECT | FD_READ | FD_OOB | FD_WRITE | FD_CLOSE);
5883         if (ret)
5884         {
5885             ok(0, "WSAEventSelect failed, error %d\n", ret);
5886             goto end;
5887         }
5888 
5889         ok(set_blocking(src, TRUE) == SOCKET_ERROR, "set_blocking should failed!\n");
5890         ok(WSAGetLastError() == WSAEINVAL, "expect WSAEINVAL, returned %x\n", WSAGetLastError());
5891 
5892         ret = WSAEventSelect(src2, hEvent2, FD_CONNECT | FD_READ | FD_OOB | FD_WRITE | FD_CLOSE);
5893         if (ret)
5894         {
5895             ok(0, "WSAEventSelect failed, error %d\n", ret);
5896             goto end;
5897         }
5898 
5899         ok(set_blocking(src2, TRUE) == SOCKET_ERROR, "set_blocking should failed!\n");
5900         ok(WSAGetLastError() == WSAEINVAL, "expect WSAEINVAL, returned %x\n", WSAGetLastError());
5901     }
5902 
5903     server = socket(AF_INET, SOCK_STREAM, 0);
5904     if (server == INVALID_SOCKET)
5905     {
5906         ok(0, "creating socket pair failed (%d), skipping test\n", GetLastError());
5907         goto end;
5908     }
5909 
5910     memset(&addr, 0, sizeof(addr));
5911     addr.sin_family = AF_INET;
5912     addr.sin_addr.s_addr = inet_addr("127.0.0.1");
5913     ret = bind(server, (struct sockaddr*)&addr, sizeof(addr));
5914     if (ret != 0)
5915     {
5916         ok(0, "creating socket pair failed (%d), skipping test\n", GetLastError());
5917         goto end;
5918     }
5919 
5920     len = sizeof(addr);
5921     ret = getsockname(server, (struct sockaddr*)&addr, &len);
5922     if (ret != 0)
5923     {
5924         ok(0, "creating socket pair failed (%d), skipping test\n", GetLastError());
5925         goto end;
5926     }
5927 
5928     ret = listen(server, 2);
5929     if (ret != 0)
5930     {
5931         ok(0, "creating socket pair failed (%d), skipping test\n", GetLastError());
5932         goto end;
5933     }
5934 
5935     SetLastError(0xdeadbeef);
5936     ret = connect(src, NULL, 0);
5937     ok(ret == SOCKET_ERROR, "expected -1, got %d\n", ret);
5938     ok(GetLastError() == WSAEFAULT, "expected 10014, got %d\n", GetLastError());
5939 
5940     ret = connect(src, (struct sockaddr*)&addr, sizeof(addr));
5941     if (ret == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK)
5942     {
5943         ok(0, "creating socket pair failed (%d), skipping test\n", GetLastError());
5944         goto end;
5945     }
5946 
5947     ret = connect(src2, (struct sockaddr*)&addr, sizeof(addr));
5948     if (ret == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK)
5949     {
5950         ok(0, "creating socket pair failed (%d), skipping test\n", GetLastError());
5951         goto end;
5952     }
5953 
5954     len = sizeof(addr);
5955     dst = accept(server, (struct sockaddr*)&addr, &len);
5956     if (dst == INVALID_SOCKET)
5957     {
5958         ok(0, "creating socket pair failed (%d), skipping test\n", GetLastError());
5959         goto end;
5960     }
5961 
5962     len = sizeof(addr);
5963     dst2 = accept(server, (struct sockaddr*)&addr, &len);
5964     if (dst2 == INVALID_SOCKET)
5965     {
5966         ok(0, "creating socket pair failed (%d), skipping test\n", GetLastError());
5967         goto end;
5968     }
5969 
5970     closesocket(server);
5971     server = INVALID_SOCKET;
5972 
5973     /* On Windows it seems when a non-blocking socket sends to a
5974        blocking socket on the same host, the send() is BLOCKING,
5975        so make both sockets non-blocking. src is already non-blocking
5976        from the async select */
5977 
5978     if (set_blocking(dst, FALSE))
5979     {
5980         ok(0, "ioctlsocket failed, error %d\n", WSAGetLastError());
5981         goto end;
5982     }
5983 
5984     buffer = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, bufferSize);
5985     if (buffer == NULL)
5986     {
5987         ok(0, "could not allocate memory for test\n");
5988         goto end;
5989     }
5990 
5991     ov.hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
5992     if (ov.hEvent == NULL)
5993     {
5994         ok(0, "could not create event object, errno = %d\n", GetLastError());
5995         goto end;
5996     }
5997 
5998     ov2.hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
5999     if (ov2.hEvent == NULL)
6000     {
6001         ok(0, "could not create event object, errno = %d\n", GetLastError());
6002         goto end;
6003     }
6004 
6005     /* FD_WRITE should be set initially, and allow us to send at least 1 byte */
6006     ok_event_seq(src, hEvent, connect_seq, NULL, 1);
6007     ok_event_seq(src2, hEvent2, connect_seq, NULL, 1);
6008     /* broken on all windows - FD_CONNECT error is garbage */
6009 
6010     /* Test simple send/recv */
6011     SetLastError(0xdeadbeef);
6012     ret = send(dst, buffer, 100, 0);
6013     ok(ret == 100, "Failed to send buffer %d err %d\n", ret, GetLastError());
6014     ok(GetLastError() == ERROR_SUCCESS, "Expected 0, got %d\n", GetLastError());
6015     ok_event_seq(src, hEvent, read_seq, NULL, 0);
6016 
6017     SetLastError(0xdeadbeef);
6018     ret = recv(src, buffer, 1, MSG_PEEK);
6019     ok(ret == 1, "Failed to peek at recv buffer %d err %d\n", ret, GetLastError());
6020     ok(GetLastError() == ERROR_SUCCESS, "Expected 0, got %d\n", GetLastError());
6021     ok_event_seq(src, hEvent, read_seq, NULL, 0);
6022 
6023     SetLastError(0xdeadbeef);
6024     ret = recv(src, buffer, 50, 0);
6025     ok(ret == 50, "Failed to recv buffer %d err %d\n", ret, GetLastError());
6026     ok(GetLastError() == ERROR_SUCCESS, "Expected 0, got %d\n", GetLastError());
6027     ok_event_seq(src, hEvent, read_seq, NULL, 0);
6028 
6029     ret = recv(src, buffer, 50, 0);
6030     ok(ret == 50, "Failed to recv buffer %d err %d\n", ret, GetLastError());
6031     ok_event_seq(src, hEvent, empty_seq, NULL, 0);
6032 
6033     /* fun fact - events are re-enabled even on failure, but only for messages */
6034     ret = send(dst, "1", 1, 0);
6035     ok(ret == 1, "Failed to send buffer %d err %d\n", ret, GetLastError());
6036     ok_event_seq(src, hEvent, read_seq, NULL, 0);
6037 
6038     ret = recv(src, buffer, -1, 0);
6039     ok(ret == SOCKET_ERROR && (GetLastError() == WSAEFAULT || GetLastError() == WSAENOBUFS),
6040        "Failed to recv buffer %d err %d\n", ret, GetLastError());
6041     if (useMessages)
6042     {
6043         broken_seq[0] = empty_seq; /* win9x */
6044         broken_seq[1] = NULL;
6045         todo_wine ok_event_seq(src, hEvent, read_seq, broken_seq, 0);
6046     }
6047     else
6048         ok_event_seq(src, hEvent, empty_seq, NULL, 0);
6049 
6050     SetLastError(0xdeadbeef);
6051     ret = recv(src, buffer, 1, 0);
6052     ok(ret == 1, "Failed to recv buffer %d err %d\n", ret, GetLastError());
6053     ok(GetLastError() == ERROR_SUCCESS, "Expected 0, got %d\n", GetLastError());
6054     ok_event_seq(src, hEvent, empty_seq, NULL, 0);
6055 
6056     /* Interaction with overlapped */
6057     bufs.len = sizeof(char);
6058     bufs.buf = buffer;
6059     ret = WSARecv(src, &bufs, 1, &bytesReturned, &flags, &ov, NULL);
6060     ok(ret == SOCKET_ERROR && GetLastError() == ERROR_IO_PENDING,
6061        "WSARecv failed - %d error %d\n", ret, GetLastError());
6062 
6063     bufs.len = sizeof(char);
6064     bufs.buf = buffer+1;
6065     ret = WSARecv(src, &bufs, 1, &bytesReturned, &flags, &ov2, NULL);
6066     ok(ret == SOCKET_ERROR && GetLastError() == ERROR_IO_PENDING,
6067        "WSARecv failed - %d error %d\n", ret, GetLastError());
6068 
6069     ret = send(dst, "12", 2, 0);
6070     ok(ret == 2, "Failed to send buffer %d err %d\n", ret, GetLastError());
6071     broken_seq[0] = read_read_seq; /* win9x */
6072     broken_seq[1] = NULL;
6073     ok_event_seq(src, hEvent, empty_seq, broken_seq, 0);
6074 
6075     dwRet = WaitForSingleObject(ov.hEvent, 100);
6076     ok(dwRet == WAIT_OBJECT_0, "Failed to wait for recv message: %d - %d\n", dwRet, GetLastError());
6077     if (dwRet == WAIT_OBJECT_0)
6078     {
6079         bret = GetOverlappedResult((HANDLE)src, &ov, &bytesReturned, FALSE);
6080         ok((bret && bytesReturned == 1) || broken(!bret && GetLastError() == ERROR_IO_INCOMPLETE) /* win9x */,
6081            "Got %d instead of 1 (%d - %d)\n", bytesReturned, bret, GetLastError());
6082         ok(buffer[0] == '1', "Got %c instead of 1\n", buffer[0]);
6083     }
6084 
6085     dwRet = WaitForSingleObject(ov2.hEvent, 100);
6086     ok(dwRet == WAIT_OBJECT_0, "Failed to wait for recv message: %d - %d\n", dwRet, GetLastError());
6087     if (dwRet == WAIT_OBJECT_0)
6088     {
6089         bret = GetOverlappedResult((HANDLE)src, &ov2, &bytesReturned, FALSE);
6090         ok((bret && bytesReturned == 1) || broken(!bret && GetLastError() == ERROR_IO_INCOMPLETE) /* win9x */,
6091            "Got %d instead of 1 (%d - %d)\n", bytesReturned, bret, GetLastError());
6092         ok(buffer[1] == '2', "Got %c instead of 2\n", buffer[1]);
6093     }
6094 
6095     SetLastError(0xdeadbeef);
6096     ret = send(dst, "1", 1, 0);
6097     ok(ret == 1, "Failed to send buffer %d err %d\n", ret, GetLastError());
6098     ok(GetLastError() == ERROR_SUCCESS, "Expected 0, got %d\n", GetLastError());
6099     ok_event_seq(src, hEvent, read_seq, NULL, 0);
6100 
6101     ret = recv(src, buffer, 1, 0);
6102     ok(ret == 1, "Failed to empty buffer: %d - %d\n", ret, GetLastError());
6103     ok_event_seq(src, hEvent, empty_seq, NULL, 0);
6104 
6105     /* Notifications are delivered as soon as possible, blocked only on
6106      * async requests on the same type */
6107     bufs.len = sizeof(char);
6108     bufs.buf = buffer;
6109     ret = WSARecv(src, &bufs, 1, &bytesReturned, &flags, &ov, NULL);
6110     ok(ret == SOCKET_ERROR && GetLastError() == ERROR_IO_PENDING,
6111        "WSARecv failed - %d error %d\n", ret, GetLastError());
6112 
6113     if (0) {
6114     ret = send(dst, "1", 1, MSG_OOB);
6115     ok(ret == 1, "Failed to send buffer %d err %d\n", ret, GetLastError());
6116     ok_event_seq(src, hEvent, oob_seq, NULL, 0);
6117     }
6118 
6119     dwRet = WaitForSingleObject(ov.hEvent, 100);
6120     ok(dwRet == WAIT_TIMEOUT, "OOB message activated read?: %d - %d\n", dwRet, GetLastError());
6121 
6122     ret = send(dst, "2", 1, 0);
6123     ok(ret == 1, "Failed to send buffer %d err %d\n", ret, GetLastError());
6124     broken_seq[0] = read_seq;  /* win98 */
6125     broken_seq[1] = NULL;
6126     ok_event_seq(src, hEvent, empty_seq, broken_seq, 0);
6127 
6128     dwRet = WaitForSingleObject(ov.hEvent, 100);
6129     ok(dwRet == WAIT_OBJECT_0 || broken(dwRet == WAIT_TIMEOUT),
6130        "Failed to wait for recv message: %d - %d\n", dwRet, GetLastError());
6131     if (dwRet == WAIT_OBJECT_0)
6132     {
6133         bret = GetOverlappedResult((HANDLE)src, &ov, &bytesReturned, FALSE);
6134         ok((bret && bytesReturned == 1) || broken(!bret && GetLastError() == ERROR_IO_INCOMPLETE) /* win9x */,
6135            "Got %d instead of 1 (%d - %d)\n", bytesReturned, bret, GetLastError());
6136         ok(buffer[0] == '2', "Got %c instead of 2\n", buffer[0]);
6137     }
6138     else if (dwRet == WAIT_TIMEOUT)
6139     {
6140         /* this happens on win98. We get an FD_READ later on the next test */
6141         CancelIo((HANDLE) src);
6142     }
6143 
6144     if (0) {
6145     ret = recv(src, buffer, 1, MSG_OOB);
6146     todo_wine ok(ret == 1, "Failed to empty buffer: %d - %d\n", ret, GetLastError());
6147     /* We get OOB notification, but no data on wine */
6148     ok_event_seq(src, hEvent, empty_seq, NULL, 0);
6149     }
6150 
6151     /* Flood the send queue */
6152     hThread = CreateThread(NULL, 0, drain_socket_thread, &dst, 0, &id);
6153     if (hThread == NULL)
6154     {
6155         ok(0, "CreateThread failed, error %d\n", GetLastError());
6156         goto end;
6157     }
6158 
6159     /* Now FD_WRITE should not be set, because the socket send buffer isn't full yet */
6160     ok_event_seq(src, hEvent, empty_seq, NULL, 0);
6161 
6162     /* Now if we send a ton of data and the 'server' does not drain it fast
6163      * enough (set drain_pause to be sure), the socket send buffer will only
6164      * take some of it, and we will get a short write. This will trigger
6165      * another FD_WRITE event as soon as data is sent and more space becomes
6166      * available, but not any earlier. */
6167     drain_pause = TRUE;
6168     do
6169     {
6170         ret = send(src, buffer, bufferSize, 0);
6171     } while (ret == bufferSize);
6172     drain_pause = FALSE;
6173     if (ret >= 0 || WSAGetLastError() == WSAEWOULDBLOCK)
6174     {
6175         Sleep(400); /* win9x */
6176         broken_seq[0] = read_write_seq;
6177         broken_seq[1] = NULL;
6178         ok_event_seq(src, hEvent, write_seq, broken_seq, 0);
6179     }
6180     else
6181     {
6182         ok(0, "sending a lot of data failed with error %d\n", WSAGetLastError());
6183     }
6184 
6185     /* Test how FD_CLOSE is handled */
6186     ret = send(dst, "12", 2, 0);
6187     ok(ret == 2, "Failed to send buffer %d err %d\n", ret, GetLastError());
6188 
6189     /* Wait a little and let the send complete */
6190     Sleep(100);
6191     closesocket(dst);
6192     dst = INVALID_SOCKET;
6193     Sleep(100);
6194 
6195     /* We can never implement this in wine, best we can hope for is
6196        sending FD_CLOSE after the reads complete */
6197     broken_seq[0] = read_seq;  /* win9x */
6198     broken_seq[1] = NULL;
6199     todo_wine ok_event_seq(src, hEvent, read_close_seq, broken_seq, 0);
6200 
6201     ret = recv(src, buffer, 1, 0);
6202     ok(ret == 1, "Failed to empty buffer: %d - %d\n", ret, GetLastError());
6203     ok_event_seq(src, hEvent, read_seq, NULL, 0);
6204 
6205     ret = recv(src, buffer, 1, 0);
6206     ok(ret == 1, "Failed to empty buffer: %d - %d\n", ret, GetLastError());
6207     /* want it? it's here, but you can't have it */
6208     broken_seq[0] = close_seq;  /* win9x */
6209     broken_seq[1] = NULL;
6210     todo_wine ok_event_seq(src, hEvent, empty_seq, /* wine sends FD_CLOSE here */
6211                            broken_seq, 0);
6212 
6213     /* Test how FD_CLOSE is handled */
6214     ret = send(dst2, "12", 2, 0);
6215     ok(ret == 2, "Failed to send buffer %d err %d\n", ret, GetLastError());
6216 
6217     Sleep(200);
6218     shutdown(dst2, SD_SEND);
6219     Sleep(200);
6220 
6221     /* Some of the below are technically todo_wine, but our event sequence is still valid, so to prevent
6222        regressions, don't mark them as todo_wine, and mark windows as broken */
6223     broken_seq[0] = read_close_seq;
6224     broken_seq[1] = close_seq;
6225     broken_seq[2] = NULL;
6226     ok_event_seq(src2, hEvent2, read_seq, broken_seq, 0);
6227 
6228     ret = recv(src2, buffer, 1, 0);
6229     ok(ret == 1 || broken(!ret), "Failed to empty buffer: %d - %d\n", ret, GetLastError());
6230     broken_seq[0] = close_seq;  /* win98 */
6231     broken_seq[1] = NULL;
6232     ok_event_seq(src2, hEvent2, read_seq, broken_seq, 0);
6233 
6234     ret = recv(src2, buffer, 1, 0);
6235     ok(ret == 1 || broken(!ret), "Failed to empty buffer: %d - %d\n", ret, GetLastError());
6236     broken_seq[0] = empty_seq;
6237     broken_seq[1] = NULL;
6238     ok_event_seq(src2, hEvent2, close_seq, broken_seq, 0);
6239 
6240     ret = send(src2, "1", 1, 0);
6241     ok(ret == 1, "Sending to half-closed socket failed %d err %d\n", ret, GetLastError());
6242     ok_event_seq(src2, hEvent2, empty_seq, NULL, 0);
6243 
6244     ret = send(src2, "1", 1, 0);
6245     ok(ret == 1, "Sending to half-closed socket failed %d err %d\n", ret, GetLastError());
6246     ok_event_seq(src2, hEvent2, empty_seq, NULL, 0);
6247 
6248     if (useMessages)
6249     {
6250         ret = WSAAsyncSelect(src, hWnd, WM_SOCKET, 0);
6251         if (ret)
6252         {
6253             ok(0, "WSAAsyncSelect failed, error %d\n", ret);
6254             goto end;
6255         }
6256 
6257         ret = set_blocking(src, TRUE);
6258         ok(!ret, "set_blocking failed, error %d\n", WSAGetLastError());
6259 
6260         ret = WSAAsyncSelect(src2, hWnd, WM_SOCKET, 0);
6261         if (ret)
6262         {
6263             ok(0, "WSAAsyncSelect failed, error %d\n", ret);
6264             goto end;
6265         }
6266 
6267         ret = set_blocking(src2, TRUE);
6268         ok(!ret, "set_blocking failed, error %d\n", WSAGetLastError());
6269     }
6270     else
6271     {
6272         ret = WSAEventSelect(src, hEvent2, 0);
6273         if (ret)
6274         {
6275             ok(0, "WSAAsyncSelect failed, error %d\n", ret);
6276             goto end;
6277         }
6278 
6279         ret = set_blocking(src, TRUE);
6280         ok(!ret, "set_blocking failed, error %d\n", WSAGetLastError());
6281 
6282         ret = WSAEventSelect(src2, hEvent2, 0);
6283         if (ret)
6284         {
6285             ok(0, "WSAAsyncSelect failed, error %d\n", ret);
6286             goto end;
6287         }
6288 
6289         ret = set_blocking(src2, TRUE);
6290         ok(!ret, "set_blocking failed, error %d\n", WSAGetLastError());
6291     }
6292 
6293 end:
6294     if (src != INVALID_SOCKET)
6295     {
6296         flush_events(src, hEvent);
6297         closesocket(src);
6298     }
6299     if (src2 != INVALID_SOCKET)
6300     {
6301         flush_events(src2, hEvent2);
6302         closesocket(src2);
6303     }
6304     HeapFree(GetProcessHeap(), 0, buffer);
6305     if (server != INVALID_SOCKET)
6306         closesocket(server);
6307     if (dst != INVALID_SOCKET)
6308         closesocket(dst);
6309     if (dst2 != INVALID_SOCKET)
6310         closesocket(dst2);
6311     if (hThread != NULL)
6312         CloseHandle(hThread);
6313     if (hWnd != NULL)
6314         DestroyWindow(hWnd);
6315     if (hEvent != NULL)
6316         CloseHandle(hEvent);
6317     if (hEvent2 != NULL)
6318         CloseHandle(hEvent2);
6319     if (ov.hEvent != NULL)
6320         CloseHandle(ov.hEvent);
6321     if (ov2.hEvent != NULL)
6322         CloseHandle(ov2.hEvent);
6323 }
6324 
6325 static void test_ipv6only(void)
6326 {
6327     SOCKET v4 = INVALID_SOCKET, v6;
6328     struct sockaddr_in sin4;
6329     struct sockaddr_in6 sin6;
6330     int ret, enabled, len = sizeof(enabled);
6331 
6332     memset(&sin4, 0, sizeof(sin4));
6333     sin4.sin_family = AF_INET;
6334     sin4.sin_port = htons(SERVERPORT);
6335 
6336     memset(&sin6, 0, sizeof(sin6));
6337     sin6.sin6_family = AF_INET6;
6338     sin6.sin6_port = htons(SERVERPORT);
6339 
6340     v6 = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP);
6341     if (v6 == INVALID_SOCKET)
6342     {
6343         skip("Could not create IPv6 socket (LastError: %d)\n", WSAGetLastError());
6344         goto end;
6345     }
6346 
6347     enabled = 2;
6348     ret = getsockopt(v6, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&enabled, &len);
6349     ok(!ret, "getsockopt(IPV6_ONLY) failed (LastError: %d)\n", WSAGetLastError());
6350     ok(enabled == 1, "expected 1, got %d\n", enabled);
6351 
6352     ret = bind(v6, (struct sockaddr*)&sin6, sizeof(sin6));
6353     if (ret)
6354     {
6355         skip("Could not bind IPv6 address (LastError: %d)\n", WSAGetLastError());
6356         goto end;
6357     }
6358 
6359     v4 = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
6360     ok(v4 != INVALID_SOCKET, "Could not create IPv4 socket (LastError: %d)\n", WSAGetLastError());
6361 
6362 todo_wine {
6363     enabled = 2;
6364     ret = getsockopt(v4, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&enabled, &len);
6365     ok(!ret, "getsockopt(IPV6_ONLY) failed (LastError: %d)\n", WSAGetLastError());
6366     ok(enabled == 1, "expected 1, got %d\n", enabled);
6367 }
6368 
6369     enabled = 0;
6370     len = sizeof(enabled);
6371     ret = setsockopt(v4, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&enabled, len);
6372     ok(!ret, "setsockopt(IPV6_ONLY) failed (LastError: %d)\n", WSAGetLastError());
6373 
6374 todo_wine {
6375     enabled = 2;
6376     ret = getsockopt(v4, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&enabled, &len);
6377     ok(!ret, "getsockopt(IPV6_ONLY) failed (LastError: %d)\n", WSAGetLastError());
6378     ok(!enabled, "expected 0, got %d\n", enabled);
6379 }
6380 
6381     enabled = 1;
6382     len = sizeof(enabled);
6383     ret = setsockopt(v4, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&enabled, len);
6384     ok(!ret, "setsockopt(IPV6_ONLY) failed (LastError: %d)\n", WSAGetLastError());
6385 
6386     /* bind on IPv4 socket should succeed - IPV6_V6ONLY is enabled by default */
6387     ret = bind(v4, (struct sockaddr*)&sin4, sizeof(sin4));
6388     ok(!ret, "Could not bind IPv4 address (LastError: %d)\n", WSAGetLastError());
6389 
6390 todo_wine {
6391     enabled = 2;
6392     ret = getsockopt(v4, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&enabled, &len);
6393     ok(!ret, "getsockopt(IPV6_ONLY) failed (LastError: %d)\n", WSAGetLastError());
6394     ok(enabled == 1, "expected 1, got %d\n", enabled);
6395 }
6396 
6397     enabled = 0;
6398     len = sizeof(enabled);
6399     ret = setsockopt(v4, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&enabled, len);
6400     ok(ret, "setsockopt(IPV6_ONLY) succeeded (LastError: %d)\n", WSAGetLastError());
6401 
6402 todo_wine {
6403     enabled = 0;
6404     ret = getsockopt(v4, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&enabled, &len);
6405     ok(!ret, "getsockopt(IPV6_ONLY) failed (LastError: %d)\n", WSAGetLastError());
6406     ok(enabled == 1, "expected 1, got %d\n", enabled);
6407 }
6408 
6409     enabled = 1;
6410     len = sizeof(enabled);
6411     ret = setsockopt(v4, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&enabled, len);
6412     ok(ret, "setsockopt(IPV6_ONLY) succeeded (LastError: %d)\n", WSAGetLastError());
6413 
6414     closesocket(v4);
6415     closesocket(v6);
6416 
6417     /* Test again, this time disabling IPV6_V6ONLY. */
6418     sin4.sin_port = htons(SERVERPORT+2);
6419     sin6.sin6_port = htons(SERVERPORT+2);
6420 
6421     v6 = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP);
6422     ok(v6 != INVALID_SOCKET, "Could not create IPv6 socket (LastError: %d; %d expected if IPv6 not available).\n",
6423         WSAGetLastError(), WSAEAFNOSUPPORT);
6424 
6425     enabled = 0;
6426     ret = setsockopt(v6, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&enabled, len);
6427     ok(!ret, "Could not disable IPV6_V6ONLY (LastError: %d).\n", WSAGetLastError());
6428 
6429     enabled = 2;
6430     ret = getsockopt(v6, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&enabled, &len);
6431     ok(!ret, "getsockopt(IPV6_ONLY) failed (LastError: %d)\n", WSAGetLastError());
6432     ok(!enabled, "expected 0, got %d\n", enabled);
6433 
6434     /*
6435         Observaition:
6436         On Windows, bind on both IPv4 and IPv6 with IPV6_V6ONLY disabled succeeds by default.
6437         Application must set SO_EXCLUSIVEADDRUSE on first socket to disallow another successful bind.
6438         In general, a standard application should not use SO_REUSEADDR.
6439         Setting both SO_EXCLUSIVEADDRUSE and SO_REUSEADDR on the same socket is not possible in
6440         either order, the later setsockopt call always fails.
6441     */
6442     enabled = 1;
6443     ret = setsockopt(v6, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (char*)&enabled, len);
6444     ok(!ret, "Could not set SO_EXCLUSIVEADDRUSE on IPv6 socket (LastError: %d)\n", WSAGetLastError());
6445 
6446     ret = bind(v6, (struct sockaddr*)&sin6, sizeof(sin6));
6447     ok(!ret, "Could not bind IPv6 address (LastError: %d)\n", WSAGetLastError());
6448 
6449     enabled = 2;
6450     len = sizeof(enabled);
6451     getsockopt(v6, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&enabled, &len);
6452     ok(!ret, "getsockopt(IPV6_ONLY) failed (LastError: %d)\n", WSAGetLastError());
6453     ok(!enabled, "IPV6_V6ONLY is enabled after bind\n");
6454 
6455     v4 = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
6456     ok(v4 != INVALID_SOCKET, "Could not create IPv4 socket (LastError: %d)\n", WSAGetLastError());
6457 
6458     enabled = 1;
6459     ret = setsockopt(v4, SOL_SOCKET, SO_REUSEADDR, (char*)&enabled, len);
6460     ok(!ret, "Could not set SO_REUSEADDR on IPv4 socket (LastError: %d)\n", WSAGetLastError());
6461 
6462     WSASetLastError(0xdeadbeef);
6463     ret = bind(v4, (struct sockaddr*)&sin4, sizeof(sin4));
6464     ok(ret, "bind succeeded unexpectedly for the IPv4 socket\n");
6465     ok(WSAGetLastError() == WSAEACCES, "Expected 10013, got %d\n", WSAGetLastError());
6466 
6467 end:
6468     if (v4 != INVALID_SOCKET)
6469         closesocket(v4);
6470     if (v6 != INVALID_SOCKET)
6471         closesocket(v6);
6472 }
6473 
6474 static void test_WSASendMsg(void)
6475 {
6476     SOCKET sock, dst;
6477     struct sockaddr_in sendaddr, sockaddr;
6478     GUID WSASendMsg_GUID = WSAID_WSASENDMSG;
6479     LPFN_WSASENDMSG pWSASendMsg = NULL;
6480     char teststr[12] = "hello world", buffer[32];
6481     WSABUF iovec[2];
6482     WSAMSG msg;
6483     DWORD bytesSent, err;
6484     int ret, addrlen;
6485 
6486     /* FIXME: Missing OVERLAPPED and OVERLAPPED COMPLETION ROUTINE tests */
6487 
6488     sock = socket(AF_INET, SOCK_DGRAM, 0);
6489     ok(sock != INVALID_SOCKET, "socket() failed\n");
6490 
6491     /* Obtain the WSASendMsg function */
6492     WSAIoctl(sock, SIO_GET_EXTENSION_FUNCTION_POINTER, &WSASendMsg_GUID, sizeof(WSASendMsg_GUID),
6493              &pWSASendMsg, sizeof(pWSASendMsg), &err, NULL, NULL);
6494     if (!pWSASendMsg)
6495     {
6496         closesocket(sock);
6497         win_skip("WSASendMsg is unsupported, some tests will be skipped.\n");
6498         return;
6499     }
6500 
6501     /* fake address for now */
6502     sendaddr.sin_family = AF_INET;
6503     sendaddr.sin_port = htons(139);
6504     sendaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
6505 
6506     memset(&msg, 0, sizeof(msg));
6507     iovec[0].buf      = teststr;
6508     iovec[0].len      = sizeof(teststr);
6509     iovec[1].buf      = teststr;
6510     iovec[1].len      = sizeof(teststr) / 2;
6511     msg.name          = (struct sockaddr *) &sendaddr;
6512     msg.namelen       = sizeof(sendaddr);
6513     msg.lpBuffers     = iovec;
6514     msg.dwBufferCount = 1; /* send only one buffer for now */
6515 
6516     WSASetLastError(0xdeadbeef);
6517     ret = pWSASendMsg(INVALID_SOCKET, &msg, 0, NULL, NULL, NULL);
6518     ok(ret == SOCKET_ERROR, "WSASendMsg should have failed\n");
6519     err = WSAGetLastError();
6520     ok(err == WSAENOTSOCK, "expected 10038, got %d instead\n", err);
6521 
6522     WSASetLastError(0xdeadbeef);
6523     ret = pWSASendMsg(sock, NULL, 0, NULL, NULL, NULL);
6524     ok(ret == SOCKET_ERROR, "WSASendMsg should have failed\n");
6525     err = WSAGetLastError();
6526     ok(err == WSAEFAULT, "expected 10014, got %d instead\n", err);
6527 
6528     WSASetLastError(0xdeadbeef);
6529     ret = pWSASendMsg(sock, NULL, 0, &bytesSent, NULL, NULL);
6530     ok(ret == SOCKET_ERROR, "WSASendMsg should have failed\n");
6531     err = WSAGetLastError();
6532     ok(err == WSAEFAULT, "expected 10014, got %d instead\n", err);
6533 
6534     WSASetLastError(0xdeadbeef);
6535     ret = pWSASendMsg(sock, &msg, 0, NULL, NULL, NULL);
6536     ok(ret == SOCKET_ERROR, "WSASendMsg should have failed\n");
6537     err = WSAGetLastError();
6538     ok(err == WSAEFAULT, "expected 10014, got %d instead\n", err);
6539 
6540     closesocket(sock);
6541 
6542     sock = socket(AF_INET, SOCK_DGRAM, 0);
6543     ok(sock != INVALID_SOCKET, "socket() failed\n");
6544 
6545     dst = socket(AF_INET, SOCK_DGRAM, 0);
6546     ok(dst != INVALID_SOCKET, "socket() failed\n");
6547 
6548     memset(&sockaddr, 0, sizeof(sockaddr));
6549     sockaddr.sin_family = AF_INET;
6550     sockaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
6551     ok(!bind(dst, (struct sockaddr*)&sockaddr, sizeof(sockaddr)),
6552        "bind should have worked\n");
6553 
6554     /* read address to find out the port number to be used in send */
6555     memset(&sendaddr, 0, sizeof(sendaddr));
6556     addrlen = sizeof(sendaddr);
6557     ok(!getsockname(dst, (struct sockaddr *) &sendaddr, &addrlen),
6558        "getsockname should have worked\n");
6559     ok(sendaddr.sin_port, "socket port should be != 0\n");
6560 
6561     /* ensure the sending socket is not bound */
6562     WSASetLastError(0xdeadbeef);
6563     addrlen = sizeof(sockaddr);
6564     ret = getsockname(sock, (struct sockaddr*)&sockaddr, &addrlen);
6565     ok(ret == SOCKET_ERROR, "getsockname should have failed\n");
6566     err = WSAGetLastError();
6567     ok(err == WSAEINVAL, "expected 10022, got %d instead\n", err);
6568 
6569     set_blocking(sock, TRUE);
6570 
6571     bytesSent = 0;
6572     SetLastError(0xdeadbeef);
6573     ret = pWSASendMsg(sock, &msg, 0, &bytesSent, NULL, NULL);
6574     ok(!ret, "WSASendMsg should have worked\n");
6575     ok(GetLastError() == 0 || broken(GetLastError() == 0xdeadbeef) /* Win <= 2008 */,
6576        "Expected 0, got %d\n", GetLastError());
6577     ok(bytesSent == iovec[0].len, "incorret bytes sent, expected %d, sent %d\n",
6578        iovec[0].len, bytesSent);
6579 
6580     /* receive data */
6581     addrlen = sizeof(sockaddr);
6582     memset(buffer, 0, sizeof(buffer));
6583     SetLastError(0xdeadbeef);
6584     ret = recvfrom(dst, buffer, sizeof(buffer), 0, (struct sockaddr *) &sockaddr, &addrlen);
6585     ok(ret == bytesSent, "got %d, expected %d\n",
6586        ret, bytesSent);
6587     ok(GetLastError() == ERROR_SUCCESS, "Expected 0, got %d\n", GetLastError());
6588 
6589     /* A successful call to WSASendMsg must have bound the socket */
6590     addrlen = sizeof(sockaddr);
6591     sockaddr.sin_port = 0;
6592     sockaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
6593     ret = getsockname(sock, (struct sockaddr*)&sockaddr, &addrlen);
6594     ok(!ret, "getsockname should have worked\n");
6595     ok(sockaddr.sin_addr.s_addr == htonl(INADDR_ANY), "expected 0.0.0.0, got %s\n",
6596        inet_ntoa(sockaddr.sin_addr));
6597     ok(sockaddr.sin_port, "sin_port should be != 0\n");
6598 
6599     msg.dwBufferCount = 2; /* send both buffers */
6600 
6601     bytesSent = 0;
6602     SetLastError(0xdeadbeef);
6603     ret = pWSASendMsg(sock, &msg, 0, &bytesSent, NULL, NULL);
6604     ok(!ret, "WSASendMsg should have worked\n");
6605     ok(bytesSent == iovec[0].len + iovec[1].len, "incorret bytes sent, expected %d, sent %d\n",
6606        iovec[0].len + iovec[1].len, bytesSent);
6607     ok(GetLastError() == 0 || broken(GetLastError() == 0xdeadbeef) /* Win <= 2008 */,
6608        "Expected 0, got %d\n", GetLastError());
6609 
6610     /* receive data */
6611     addrlen = sizeof(sockaddr);
6612     memset(buffer, 0, sizeof(buffer));
6613     SetLastError(0xdeadbeef);
6614     ret = recvfrom(dst, buffer, sizeof(buffer), 0, (struct sockaddr *) &sockaddr, &addrlen);
6615     ok(ret == bytesSent, "got %d, expected %d\n",
6616        ret, bytesSent);
6617     ok(GetLastError() == ERROR_SUCCESS, "Expected 0, got %d\n", GetLastError());
6618 
6619     closesocket(sock);
6620     closesocket(dst);
6621 
6622     /* a bad call to WSASendMsg will also bind the socket */
6623     addrlen = sizeof(sockaddr);
6624     sockaddr.sin_port = 0;
6625     sockaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
6626     sock = socket(AF_INET, SOCK_DGRAM, 0);
6627     ok(sock != INVALID_SOCKET, "socket() failed\n");
6628     ok(pWSASendMsg(sock, &msg, 0, NULL, NULL, NULL) == SOCKET_ERROR, "WSASendMsg should have failed\n");
6629 todo_wine {
6630     ok(!getsockname(sock, (struct sockaddr*)&sockaddr, &addrlen), "getsockname should have worked\n");
6631     ok(sockaddr.sin_addr.s_addr == htonl(INADDR_ANY), "expected 0.0.0.0, got %s\n",
6632        inet_ntoa(sockaddr.sin_addr));
6633     ok(sockaddr.sin_port, "sin_port should be > 0\n");
6634 }
6635     closesocket(sock);
6636 
6637     /* a bad call without msg parameter will not trigger the auto-bind */
6638     sock = socket(AF_INET, SOCK_DGRAM, 0);
6639     ok(sock != INVALID_SOCKET, "socket() failed\n");
6640     ok(pWSASendMsg(sock, NULL, 0, NULL, NULL, NULL) == SOCKET_ERROR, "WSASendMsg should have failed\n");
6641     ok(getsockname(sock, (struct sockaddr*)&sockaddr, &addrlen), "getsockname should have failed\n");
6642     err = WSAGetLastError();
6643     ok(err == WSAEINVAL, "expected 10022, got %d instead\n", err);
6644     closesocket(sock);
6645 
6646     /* SOCK_STREAM sockets are not supported */
6647     bytesSent = 0;
6648     sock = socket(AF_INET, SOCK_STREAM, 0);
6649     ok(sock != INVALID_SOCKET, "socket() failed\n");
6650     SetLastError(0xdeadbeef);
6651     ret = pWSASendMsg(sock, &msg, 0, &bytesSent, NULL, NULL);
6652     ok(ret == SOCKET_ERROR, "WSASendMsg should have failed\n");
6653     err = WSAGetLastError();
6654 todo_wine
6655     ok(err == WSAEINVAL, "expected 10014, got %d instead\n", err);
6656     closesocket(sock);
6657 }
6658 
6659 static void test_WSASendTo(void)
6660 {
6661     SOCKET s;
6662     struct sockaddr_in addr;
6663     char buf[12] = "hello world";
6664     WSABUF data_buf;
6665     DWORD bytesSent;
6666     int ret;
6667 
6668     addr.sin_family = AF_INET;
6669     addr.sin_port = htons(139);
6670     addr.sin_addr.s_addr = inet_addr("127.0.0.1");
6671     data_buf.len = sizeof(buf);
6672     data_buf.buf = buf;
6673 
6674     if( (s = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET) {
6675         ok(0, "socket() failed error: %d\n", WSAGetLastError());
6676         return;
6677     }
6678 
6679     WSASetLastError(12345);
6680     ret = WSASendTo(INVALID_SOCKET, &data_buf, 1, NULL, 0, (struct sockaddr*)&addr, sizeof(addr), NULL, NULL);
6681     ok(ret == SOCKET_ERROR && WSAGetLastError() == WSAENOTSOCK,
6682        "WSASendTo() failed: %d/%d\n", ret, WSAGetLastError());
6683 
6684     WSASetLastError(12345);
6685     ret = WSASendTo(s, &data_buf, 1, NULL, 0, (struct sockaddr*)&addr, sizeof(addr), NULL, NULL);
6686     ok(ret == SOCKET_ERROR && WSAGetLastError() == WSAEFAULT,
6687        "WSASendTo() failed: %d/%d\n", ret, WSAGetLastError());
6688 
6689     WSASetLastError(12345);
6690     if(WSASendTo(s, &data_buf, 1, &bytesSent, 0, (struct sockaddr*)&addr, sizeof(addr), NULL, NULL)) {
6691         ok(0, "WSASendTo() failed error: %d\n", WSAGetLastError());
6692         return;
6693     }
6694     ok(!WSAGetLastError(), "WSAGetLastError() should return zero after "
6695             "a successful call to WSASendTo()\n");
6696 }
6697 
6698 static DWORD WINAPI recv_thread(LPVOID arg)
6699 {
6700     SOCKET sock = *(SOCKET *)arg;
6701     char buffer[32];
6702     WSABUF wsa;
6703     WSAOVERLAPPED ov;
6704     DWORD flags = 0;
6705 
6706     wsa.buf = buffer;
6707     wsa.len = sizeof(buffer);
6708     ov.hEvent = WSACreateEvent();
6709     WSARecv(sock, &wsa, 1, NULL, &flags, &ov, NULL);
6710 
6711     WaitForSingleObject(ov.hEvent, 1000);
6712     WSACloseEvent(ov.hEvent);
6713     return 0;
6714 }
6715 
6716 static int completion_called;
6717 
6718 static void WINAPI io_completion(DWORD error, DWORD transferred, WSAOVERLAPPED *overlapped, DWORD flags)
6719 {
6720     completion_called++;
6721 }
6722 
6723 static void test_WSARecv(void)
6724 {
6725     SOCKET src, dest, server = INVALID_SOCKET;
6726     char buf[20];
6727     WSABUF bufs[2];
6728     WSAOVERLAPPED ov;
6729     DWORD bytesReturned, flags, id;
6730     struct linger ling;
6731     struct sockaddr_in addr;
6732     int iret, len;
6733     DWORD dwret;
6734     BOOL bret;
6735     HANDLE thread, event = NULL, io_port;
6736 
6737     tcp_socketpair(&src, &dest);
6738     if (src == INVALID_SOCKET || dest == INVALID_SOCKET)
6739     {
6740         skip("failed to create sockets\n");
6741         goto end;
6742     }
6743 
6744     memset(&ov, 0, sizeof(ov));
6745     flags = 0;
6746     bufs[0].len = 2;
6747     bufs[0].buf = buf;
6748 
6749     /* Send 4 bytes and receive in two calls of 2 */
6750     SetLastError(0xdeadbeef);
6751     iret = send(src, "test", 4, 0);
6752     ok(iret == 4, "Expected 4, got %d\n", iret);
6753     ok(GetLastError() == ERROR_SUCCESS, "Expected 0, got %d\n", GetLastError());
6754     SetLastError(0xdeadbeef);
6755     bytesReturned = 0xdeadbeef;
6756     iret = WSARecv(dest, bufs, 1, &bytesReturned, &flags, NULL, NULL);
6757     ok(!iret, "Expected 0, got %d\n", iret);
6758     ok(bytesReturned == 2, "Expected 2, got %d\n", bytesReturned);
6759     ok(GetLastError() == ERROR_SUCCESS, "Expected 0, got %d\n", GetLastError());
6760     SetLastError(0xdeadbeef);
6761     bytesReturned = 0xdeadbeef;
6762     iret = WSARecv(dest, bufs, 1, &bytesReturned, &flags, NULL, NULL);
6763     ok(!iret, "Expected 0, got %d\n", iret);
6764     ok(bytesReturned == 2, "Expected 2, got %d\n", bytesReturned);
6765     ok(GetLastError() == ERROR_SUCCESS, "Expected 0, got %d\n", GetLastError());
6766 
6767     bufs[0].len = 4;
6768     SetLastError(0xdeadbeef);
6769     iret = send(src, "test", 4, 0);
6770     ok(iret == 4, "Expected 4, got %d\n", iret);
6771     ok(GetLastError() == ERROR_SUCCESS, "Expected 0, got %d\n", GetLastError());
6772     SetLastError(0xdeadbeef);
6773     bytesReturned = 0xdeadbeef;
6774     iret = WSARecv(dest, bufs, 1, &bytesReturned, &flags, NULL, NULL);
6775     ok(!iret, "Expected 0, got %d\n", iret);
6776     ok(bytesReturned == 4, "Expected 4, got %d\n", bytesReturned);
6777     ok(GetLastError() == ERROR_SUCCESS, "Expected 0, got %d\n", GetLastError());
6778 
6779     /* Test 2 buffers */
6780     bufs[0].len = 4;
6781     bufs[1].len = 5;
6782     bufs[1].buf = buf + 10;
6783     SetLastError(0xdeadbeef);
6784     iret = send(src, "deadbeefs", 9, 0);
6785     ok(iret == 9, "Expected 9, got %d\n", iret);
6786     ok(GetLastError() == ERROR_SUCCESS, "Expected 0, got %d\n", GetLastError());
6787     SetLastError(0xdeadbeef);
6788     bytesReturned = 0xdeadbeef;
6789     iret = WSARecv(dest, bufs, 2, &bytesReturned, &flags, NULL, NULL);
6790     ok(!iret, "Expected 0, got %d\n", iret);
6791     ok(bytesReturned == 9, "Expected 9, got %d\n", bytesReturned);
6792     bufs[0].buf[4] = '\0';
6793     bufs[1].buf[5] = '\0';
6794     ok(!strcmp(bufs[0].buf, "dead"), "buf[0] doesn't match: %s != dead\n", bufs[0].buf);
6795     ok(!strcmp(bufs[1].buf, "beefs"), "buf[1] doesn't match: %s != beefs\n", bufs[1].buf);
6796     ok(GetLastError() == ERROR_SUCCESS, "Expected 0, got %d\n", GetLastError());
6797 
6798     bufs[0].len = sizeof(buf);
6799     ov.hEvent = event = CreateEventA(NULL, FALSE, FALSE, NULL);
6800     ok(ov.hEvent != NULL, "could not create event object, errno = %d\n", GetLastError());
6801     if (!event)
6802         goto end;
6803 
6804     ling.l_onoff = 1;
6805     ling.l_linger = 0;
6806     iret = setsockopt (src, SOL_SOCKET, SO_LINGER, (char *) &ling, sizeof(ling));
6807     ok(!iret, "Failed to set linger %d\n", GetLastError());
6808 
6809     iret = WSARecv(dest, bufs, 1, NULL, &flags, &ov, NULL);
6810     ok(iret == SOCKET_ERROR && GetLastError() == ERROR_IO_PENDING, "WSARecv failed - %d error %d\n", iret, GetLastError());
6811 
6812     iret = WSARecv(dest, bufs, 1, &bytesReturned, &flags, &ov, NULL);
6813     ok(iret == SOCKET_ERROR && GetLastError() == ERROR_IO_PENDING, "WSARecv failed - %d error %d\n", iret, GetLastError());
6814 
6815     closesocket(src);
6816     src = INVALID_SOCKET;
6817 
6818     dwret = WaitForSingleObject(ov.hEvent, 1000);
6819     ok(dwret == WAIT_OBJECT_0, "Waiting for disconnect event failed with %d + errno %d\n", dwret, GetLastError());
6820 
6821     bret = GetOverlappedResult((HANDLE)dest, &ov, &bytesReturned, FALSE);
6822     todo_wine ok(!bret && (GetLastError() == ERROR_NETNAME_DELETED || broken(GetLastError() == ERROR_IO_INCOMPLETE) /* win9x */),
6823         "Did not get disconnect event: %d, error %d\n", bret, GetLastError());
6824     ok(bytesReturned == 0, "Bytes received is %d\n", bytesReturned);
6825     closesocket(dest);
6826     dest = INVALID_SOCKET;
6827 
6828     src = WSASocketW(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, 0);
6829     ok(src != INVALID_SOCKET, "failed to create socket %d\n", WSAGetLastError());
6830     if (src == INVALID_SOCKET) goto end;
6831 
6832     server = WSASocketW(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
6833     ok(server != INVALID_SOCKET, "failed to create socket %d\n", WSAGetLastError());
6834     if (server == INVALID_SOCKET) goto end;
6835 
6836     memset(&addr, 0, sizeof(addr));
6837     addr.sin_family = AF_INET;
6838     addr.sin_addr.s_addr = inet_addr("127.0.0.1");
6839     iret = bind(server, (struct sockaddr *)&addr, sizeof(addr));
6840     if (iret) goto end;
6841 
6842     len = sizeof(addr);
6843     iret = getsockname(server, (struct sockaddr *)&addr, &len);
6844     if (iret) goto end;
6845 
6846     iret = listen(server, 1);
6847     if (iret) goto end;
6848 
6849     iret = connect(src, (struct sockaddr *)&addr, sizeof(addr));
6850     if (iret) goto end;
6851 
6852     len = sizeof(addr);
6853     dest = accept(server, (struct sockaddr *)&addr, &len);
6854     ok(dest != INVALID_SOCKET, "failed to create socket %d\n", WSAGetLastError());
6855     if (dest == INVALID_SOCKET) goto end;
6856 
6857     send(src, "test message", sizeof("test message"), 0);
6858     thread = CreateThread(NULL, 0, recv_thread, &dest, 0, &id);
6859     WaitForSingleObject(thread, 3000);
6860     CloseHandle(thread);
6861 
6862     memset(&ov, 0, sizeof(ov));
6863     ov.hEvent = event;
6864     ResetEvent(event);
6865     iret = WSARecv(dest, bufs, 1, NULL, &flags, &ov, io_completion);
6866     ok(iret == SOCKET_ERROR && GetLastError() == ERROR_IO_PENDING, "WSARecv failed - %d error %d\n", iret, GetLastError());
6867     send(src, "test message", sizeof("test message"), 0);
6868 
6869     completion_called = 0;
6870     dwret = SleepEx(1000, TRUE);
6871     ok(dwret == WAIT_IO_COMPLETION, "got %u\n", dwret);
6872     ok(completion_called == 1, "completion not called\n");
6873 
6874     dwret = WaitForSingleObject(event, 1);
6875     ok(dwret == WAIT_TIMEOUT, "got %u\n", dwret);
6876 
6877     io_port = CreateIoCompletionPort( (HANDLE)dest, NULL, 0, 0 );
6878     ok(io_port != NULL, "failed to create completion port %u\n", GetLastError());
6879 
6880     /* Using completion function on socket associated with completion port is not allowed. */
6881     memset(&ov, 0, sizeof(ov));
6882     completion_called = 0;
6883     iret = WSARecv(dest, bufs, 1, NULL, &flags, &ov, io_completion);
6884     ok(iret == SOCKET_ERROR && GetLastError() == WSAEINVAL, "WSARecv failed - %d error %d\n", iret, GetLastError());
6885     ok(!completion_called, "completion called\n");
6886 
6887     CloseHandle(io_port);
6888 
6889 end:
6890     if (server != INVALID_SOCKET)
6891         closesocket(server);
6892     if (dest != INVALID_SOCKET)
6893         closesocket(dest);
6894     if (src != INVALID_SOCKET)
6895         closesocket(src);
6896     if (event)
6897         WSACloseEvent(event);
6898 }
6899 
6900 #define POLL_CLEAR() ix = 0
6901 #define POLL_SET(s, ev) {fds[ix].fd = s; fds[ix++].events = ev;}
6902 #define POLL_ISSET(s, rev) poll_isset(fds, ix, s, rev)
6903 static BOOL poll_isset(WSAPOLLFD *fds, int max, SOCKET s, int rev)
6904 {
6905     int k;
6906     for (k = 0; k < max; k++)
6907         if (fds[k].fd == s && (fds[k].revents == rev)) return TRUE;
6908     return FALSE;
6909 }
6910 
6911 static void test_WSAPoll(void)
6912 {
6913     int ix, ret, err, poll_timeout;
6914     SOCKET fdListen, fdRead, fdWrite;
6915     struct sockaddr_in address;
6916     socklen_t len;
6917     static char tmp_buf[1024];
6918     WSAPOLLFD fds[16];
6919     HANDLE thread_handle;
6920     DWORD id;
6921 
6922     if (!pWSAPoll) /* >= Vista */
6923     {
6924         skip("WSAPoll is unsupported, some tests will be skipped.\n");
6925         return;
6926     }
6927 
6928     /* Invalid parameters test */
6929     SetLastError(0xdeadbeef);
6930     ret = pWSAPoll(NULL, 0, 0);
6931     err = GetLastError();
6932     ok(ret == SOCKET_ERROR, "expected -1, got %d\n", ret);
6933     ok(err == WSAEINVAL, "expected 10022, got %d\n", err);
6934     SetLastError(0xdeadbeef);
6935     ret = pWSAPoll(NULL, 1, 0);
6936     err = GetLastError();
6937     ok(ret == SOCKET_ERROR, "expected -1, got %d\n", ret);
6938     ok(err == WSAEFAULT, "expected 10014, got %d\n", err);
6939     SetLastError(0xdeadbeef);
6940     ret = pWSAPoll(NULL, 0, 1);
6941     err = GetLastError();
6942     ok(ret == SOCKET_ERROR, "expected -1, got %d\n", ret);
6943     ok(err == WSAEINVAL, "expected 10022, got %d\n", err);
6944     SetLastError(0xdeadbeef);
6945     ret = pWSAPoll(NULL, 1, 1);
6946     err = GetLastError();
6947     ok(ret == SOCKET_ERROR, "expected -1, got %d\n", ret);
6948     ok(err == WSAEFAULT, "expected 10014, got %d\n", err);
6949 
6950     /* WSAPoll() tries to mime the unix poll() call. The following tests do:
6951      * - check if a connection attempt ended with success or error;
6952      * - check if a pending connection is waiting for acceptance;
6953      * - check for data to read, availability for write and OOB data
6954      */
6955     memset(&address, 0, sizeof(address));
6956     address.sin_addr.s_addr = inet_addr("127.0.0.1");
6957     address.sin_family = AF_INET;
6958     len = sizeof(address);
6959     fdListen = setup_server_socket(&address, &len);
6960     poll_timeout = 100;
6961 
6962     /* When no events are pending poll returns 0 with no error */
6963     POLL_CLEAR();
6964     POLL_SET(fdListen, POLLIN);
6965     ret = pWSAPoll(fds, ix, poll_timeout);
6966     ok(ret == 0, "expected 0, got %d\n", ret);
6967 
6968     /* Test listening socket connection attempt notifications */
6969     fdWrite = setup_connector_socket(&address, len, TRUE);
6970     POLL_CLEAR();
6971     POLL_SET(fdListen, POLLIN | POLLOUT);
6972     ret = pWSAPoll(fds, ix, poll_timeout);
6973     ok(ret == 1, "expected 1, got %d\n", ret);
6974     ok(POLL_ISSET(fdListen, POLLRDNORM), "fdListen socket events incorrect\n");
6975     len = sizeof(address);
6976     fdRead = accept(fdListen, (struct sockaddr*) &address, &len);
6977     ok(fdRead != INVALID_SOCKET, "expected a valid socket\n");
6978 
6979     /* Test client side connection attempt notifications */
6980     POLL_CLEAR();
6981     POLL_SET(fdListen, POLLIN | POLLOUT);
6982     POLL_SET(fdRead, POLLIN | POLLOUT);
6983     POLL_SET(fdWrite, POLLIN | POLLOUT);
6984     ret = pWSAPoll(fds, ix, poll_timeout);
6985     ok(ret == 2, "expected 2, got %d\n", ret);
6986     ok(POLL_ISSET(fdWrite, POLLWRNORM), "fdWrite socket events incorrect\n");
6987     ok(POLL_ISSET(fdRead, POLLWRNORM), "fdRead socket events incorrect\n");
6988     len = sizeof(id);
6989     id = 0xdeadbeef;
6990     err = getsockopt(fdWrite, SOL_SOCKET, SO_ERROR, (char*)&id, &len);
6991     ok(!err, "getsockopt failed with %d\n", WSAGetLastError());
6992     ok(id == 0, "expected 0, got %d\n", id);
6993 
6994     /* Test data receiving notifications */
6995     ret = send(fdWrite, "1234", 4, 0);
6996     ok(ret == 4, "expected 4, got %d\n", ret);
6997     POLL_CLEAR();
6998     POLL_SET(fdListen, POLLIN | POLLOUT);
6999     POLL_SET(fdRead, POLLIN);
7000     ret = pWSAPoll(fds, ix, poll_timeout);
7001     ok(ret == 1, "expected 1, got %d\n", ret);
7002     ok(POLL_ISSET(fdRead, POLLRDNORM), "fdRead socket events incorrect\n");
7003     ret = recv(fdRead, tmp_buf, sizeof(tmp_buf), 0);
7004     ok(ret == 4, "expected 4, got %d\n", ret);
7005     ok(!strcmp(tmp_buf, "1234"), "data received differs from sent\n");
7006 
7007     /* Test OOB data notifications */
7008     ret = send(fdWrite, "A", 1, MSG_OOB);
7009     ok(ret == 1, "expected 1, got %d\n", ret);
7010     POLL_CLEAR();
7011     POLL_SET(fdListen, POLLIN | POLLOUT);
7012     POLL_SET(fdRead, POLLIN);
7013     ret = pWSAPoll(fds, ix, poll_timeout);
7014     ok(ret == 1, "expected 1, got %d\n", ret);
7015     ok(POLL_ISSET(fdRead, POLLRDBAND), "fdRead socket events incorrect\n");
7016     tmp_buf[0] = 0xAF;
7017     ret = recv(fdRead, tmp_buf, sizeof(tmp_buf), MSG_OOB);
7018     ok(ret == 1, "expected 1, got %d\n", ret);
7019     ok(tmp_buf[0] == 'A', "expected 'A', got 0x%02X\n", tmp_buf[0]);
7020 
7021     /* If the socket is OOBINLINED the notification is like normal data */
7022     ret = 1;
7023     ret = setsockopt(fdRead, SOL_SOCKET, SO_OOBINLINE, (char*) &ret, sizeof(ret));
7024     ok(ret == 0, "expected 0, got %d\n", ret);
7025     ret = send(fdWrite, "A", 1, MSG_OOB);
7026     ok(ret == 1, "expected 1, got %d\n", ret);
7027     POLL_CLEAR();
7028     POLL_SET(fdListen, POLLIN | POLLOUT);
7029     POLL_SET(fdRead, POLLIN | POLLOUT);
7030     ret = pWSAPoll(fds, ix, poll_timeout);
7031     ok(ret == 1, "expected 1, got %d\n", ret);
7032     tmp_buf[0] = 0xAF;
7033     SetLastError(0xdeadbeef);
7034     ret = recv(fdRead, tmp_buf, sizeof(tmp_buf), MSG_OOB);
7035     ok(ret == SOCKET_ERROR, "expected -1, got %d\n", ret);
7036     ok(GetLastError() == WSAEINVAL, "expected 10022, got %d\n", GetLastError());
7037     ret = recv(fdRead, tmp_buf, sizeof(tmp_buf), 0);
7038     ok(ret == 1, "expected 1, got %d\n", ret);
7039     ok(tmp_buf[0] == 'A', "expected 'A', got 0x%02X\n", tmp_buf[0]);
7040 
7041     /* Test connection closed notifications */
7042     ret = closesocket(fdRead);
7043     ok(ret == 0, "expected 0, got %d\n", ret);
7044     POLL_CLEAR();
7045     POLL_SET(fdListen, POLLIN | POLLOUT);
7046     POLL_SET(fdWrite, POLLIN);
7047     ret = pWSAPoll(fds, ix, poll_timeout);
7048     ok(ret == 1, "expected 1, got %d\n", ret);
7049     ok(POLL_ISSET(fdWrite, POLLHUP), "fdWrite socket events incorrect\n");
7050     ret = recv(fdWrite, tmp_buf, sizeof(tmp_buf), 0);
7051     ok(ret == 0, "expected 0, got %d\n", ret);
7052 
7053     /* When a connection is attempted to a non-listening socket due to a bug
7054      * in the MS code it will never be notified. This is a long standing issue
7055      * that will never be fixed for compatibility reasons so we have to deal
7056      * with it manually. */
7057     ret = closesocket(fdWrite);
7058     ok(ret == 0, "expected 0, got %d\n", ret);
7059     ret = closesocket(fdListen);
7060     ok(ret == 0, "expected 0, got %d\n", ret);
7061     len = sizeof(address);
7062     fdWrite = setup_connector_socket(&address, len, TRUE);
7063     POLL_CLEAR();
7064     POLL_SET(fdWrite, POLLIN | POLLOUT);
7065     poll_timeout = 2000;
7066     ret = pWSAPoll(fds, ix, poll_timeout);
7067 todo_wine
7068     ok(ret == 0, "expected 0, got %d\n", ret);
7069     len = sizeof(id);
7070     id = 0xdeadbeef;
7071     err = getsockopt(fdWrite, SOL_SOCKET, SO_ERROR, (char*)&id, &len);
7072     ok(!err, "getsockopt failed with %d\n", WSAGetLastError());
7073     ok(id == WSAECONNREFUSED, "expected 10061, got %d\n", id);
7074     closesocket(fdWrite);
7075 
7076     /* Try poll() on a closed socket after connection */
7077     ok(!tcp_socketpair(&fdRead, &fdWrite), "creating socket pair failed\n");
7078     closesocket(fdRead);
7079     POLL_CLEAR();
7080     POLL_SET(fdWrite, POLLIN | POLLOUT);
7081     POLL_SET(fdRead, POLLIN | POLLOUT);
7082     ret = pWSAPoll(fds, ix, poll_timeout);
7083     ok(ret == 1, "expected 1, got %d\n", ret);
7084     ok(POLL_ISSET(fdRead, POLLNVAL), "fdRead socket events incorrect\n");
7085     POLL_CLEAR();
7086     POLL_SET(fdWrite, POLLIN | POLLOUT);
7087     ret = pWSAPoll(fds, ix, poll_timeout);
7088     ok(ret == 1, "expected 1, got %d\n", ret);
7089 todo_wine
7090     ok(POLL_ISSET(fdWrite, POLLWRNORM | POLLHUP) || broken(POLL_ISSET(fdWrite, POLLWRNORM)) /* <= 2008 */,
7091        "fdWrite socket events incorrect\n");
7092     closesocket(fdWrite);
7093 
7094     /* Close the socket currently being polled in a thread */
7095     ok(!tcp_socketpair(&fdRead, &fdWrite), "creating socket pair failed\n");
7096     thread_handle = CreateThread(NULL, 0, SelectCloseThread, &fdWrite, 0, &id);
7097     ok(thread_handle != NULL, "CreateThread failed unexpectedly: %d\n", GetLastError());
7098     POLL_CLEAR();
7099     POLL_SET(fdWrite, POLLIN | POLLOUT);
7100     ret = pWSAPoll(fds, ix, poll_timeout);
7101     ok(ret == 1, "expected 1, got %d\n", ret);
7102     ok(POLL_ISSET(fdWrite, POLLWRNORM), "fdWrite socket events incorrect\n");
7103     WaitForSingleObject (thread_handle, 1000);
7104     closesocket(fdRead);
7105     /* test again with less flags - behavior changes */
7106     ok(!tcp_socketpair(&fdRead, &fdWrite), "creating socket pair failed\n");
7107     thread_handle = CreateThread(NULL, 0, SelectCloseThread, &fdWrite, 0, &id);
7108     ok(thread_handle != NULL, "CreateThread failed unexpectedly: %d\n", GetLastError());
7109     POLL_CLEAR();
7110     POLL_SET(fdWrite, POLLIN);
7111     ret = pWSAPoll(fds, ix, poll_timeout);
7112     ok(ret == 1, "expected 1, got %d\n", ret);
7113     ok(POLL_ISSET(fdWrite, POLLNVAL), "fdWrite socket events incorrect\n");
7114     WaitForSingleObject (thread_handle, 1000);
7115     closesocket(fdRead);
7116 }
7117 #undef POLL_SET
7118 #undef POLL_ISSET
7119 #undef POLL_CLEAR
7120 
7121 static void test_GetAddrInfoW(void)
7122 {
7123     static const WCHAR port[] = {'8','0',0};
7124     static const WCHAR empty[] = {0};
7125     static const WCHAR localhost[] = {'l','o','c','a','l','h','o','s','t',0};
7126     static const WCHAR nxdomain[] =
7127         {'n','x','d','o','m','a','i','n','.','c','o','d','e','w','e','a','v','e','r','s','.','c','o','m',0};
7128     static const WCHAR zero[] = {'0',0};
7129     int i, ret;
7130     ADDRINFOW *result, *result2, *p, hint;
7131     WCHAR name[256];
7132     DWORD size = sizeof(name)/sizeof(WCHAR);
7133     /* te su to.winehq.org written in katakana */
7134     static const WCHAR idn_domain[] =
7135         {0x30C6,0x30B9,0x30C8,'.','w','i','n','e','h','q','.','o','r','g',0};
7136     static const WCHAR idn_punycode[] =
7137         {'x','n','-','-','z','c','k','z','a','h','.','w','i','n','e','h','q','.','o','r','g',0};
7138 
7139     if (!pGetAddrInfoW || !pFreeAddrInfoW)
7140     {
7141         win_skip("GetAddrInfoW and/or FreeAddrInfoW not present\n");
7142         return;
7143     }
7144     memset(&hint, 0, sizeof(ADDRINFOW));
7145     name[0] = 0;
7146     GetComputerNameExW( ComputerNamePhysicalDnsHostname, name, &size );
7147 
7148     result = (ADDRINFOW *)0xdeadbeef;
7149     WSASetLastError(0xdeadbeef);
7150     ret = pGetAddrInfoW(NULL, NULL, NULL, &result);
7151     ok(ret == WSAHOST_NOT_FOUND, "got %d expected WSAHOST_NOT_FOUND\n", ret);
7152     ok(WSAGetLastError() == WSAHOST_NOT_FOUND, "expected 11001, got %d\n", WSAGetLastError());
7153     ok(result == NULL, "got %p\n", result);
7154 
7155     result = NULL;
7156     WSASetLastError(0xdeadbeef);
7157     ret = pGetAddrInfoW(empty, NULL, NULL, &result);
7158     ok(!ret, "GetAddrInfoW failed with %d\n", WSAGetLastError());
7159     ok(result != NULL, "GetAddrInfoW failed\n");
7160     ok(WSAGetLastError() == 0, "expected 0, got %d\n", WSAGetLastError());
7161     pFreeAddrInfoW(result);
7162 
7163     result = NULL;
7164     ret = pGetAddrInfoW(NULL, zero, NULL, &result);
7165     ok(!ret, "GetAddrInfoW failed with %d\n", WSAGetLastError());
7166     ok(result != NULL, "GetAddrInfoW failed\n");
7167 
7168     result2 = NULL;
7169     ret = pGetAddrInfoW(NULL, empty, NULL, &result2);
7170     ok(!ret, "GetAddrInfoW failed with %d\n", WSAGetLastError());
7171     ok(result2 != NULL, "GetAddrInfoW failed\n");
7172     compare_addrinfow(result, result2);
7173     pFreeAddrInfoW(result);
7174     pFreeAddrInfoW(result2);
7175 
7176     result = NULL;
7177     ret = pGetAddrInfoW(empty, zero, NULL, &result);
7178     ok(!ret, "GetAddrInfoW failed with %d\n", WSAGetLastError());
7179     ok(WSAGetLastError() == 0, "expected 0, got %d\n", WSAGetLastError());
7180     ok(result != NULL, "GetAddrInfoW failed\n");
7181 
7182     result2 = NULL;
7183     ret = pGetAddrInfoW(empty, empty, NULL, &result2);
7184     ok(!ret, "GetAddrInfoW failed with %d\n", WSAGetLastError());
7185     ok(result2 != NULL, "GetAddrInfoW failed\n");
7186     compare_addrinfow(result, result2);
7187     pFreeAddrInfoW(result);
7188     pFreeAddrInfoW(result2);
7189 
7190     result = NULL;
7191     ret = pGetAddrInfoW(localhost, NULL, NULL, &result);
7192     ok(!ret, "GetAddrInfoW failed with %d\n", WSAGetLastError());
7193     pFreeAddrInfoW(result);
7194 
7195     result = NULL;
7196     ret = pGetAddrInfoW(localhost, empty, NULL, &result);
7197     ok(!ret, "GetAddrInfoW failed with %d\n", WSAGetLastError());
7198     pFreeAddrInfoW(result);
7199 
7200     result = NULL;
7201     ret = pGetAddrInfoW(localhost, zero, NULL, &result);
7202     ok(!ret, "GetAddrInfoW failed with %d\n", WSAGetLastError());
7203     pFreeAddrInfoW(result);
7204 
7205     result = NULL;
7206     ret = pGetAddrInfoW(localhost, port, NULL, &result);
7207     ok(!ret, "GetAddrInfoW failed with %d\n", WSAGetLastError());
7208     pFreeAddrInfoW(result);
7209 
7210     result = NULL;
7211     ret = pGetAddrInfoW(localhost, NULL, &hint, &result);
7212     ok(!ret, "GetAddrInfoW failed with %d\n", WSAGetLastError());
7213     pFreeAddrInfoW(result);
7214 
7215     result = NULL;
7216     SetLastError(0xdeadbeef);
7217     ret = pGetAddrInfoW(localhost, port, &hint, &result);
7218     ok(!ret, "GetAddrInfoW failed with %d\n", WSAGetLastError());
7219     ok(WSAGetLastError() == 0, "expected 0, got %d\n", WSAGetLastError());
7220     pFreeAddrInfoW(result);
7221 
7222     /* try to get information from the computer name, result is the same
7223      * as if requesting with an empty host name. */
7224     ret = pGetAddrInfoW(name, NULL, NULL, &result);
7225     ok(!ret, "GetAddrInfoW failed with %d\n", WSAGetLastError());
7226     ok(result != NULL, "GetAddrInfoW failed\n");
7227 
7228     ret = pGetAddrInfoW(empty, NULL, NULL, &result2);
7229     ok(!ret, "GetAddrInfoW failed with %d\n", WSAGetLastError());
7230     ok(result2 != NULL, "GetAddrInfoW failed\n");
7231     compare_addrinfow(result, result2);
7232     pFreeAddrInfoW(result);
7233     pFreeAddrInfoW(result2);
7234 
7235     ret = pGetAddrInfoW(name, empty, NULL, &result);
7236     ok(!ret, "GetAddrInfoW failed with %d\n", WSAGetLastError());
7237     ok(result != NULL, "GetAddrInfoW failed\n");
7238 
7239     ret = pGetAddrInfoW(empty, empty, NULL, &result2);
7240     ok(!ret, "GetAddrInfoW failed with %d\n", WSAGetLastError());
7241     ok(result2 != NULL, "GetAddrInfoW failed\n");
7242     compare_addrinfow(result, result2);
7243     pFreeAddrInfoW(result);
7244     pFreeAddrInfoW(result2);
7245 
7246     result = (ADDRINFOW *)0xdeadbeef;
7247     WSASetLastError(0xdeadbeef);
7248     ret = pGetAddrInfoW(NULL, NULL, NULL, &result);
7249     if(ret == 0)
7250     {
7251         skip("nxdomain returned success. Broken ISP redirects?\n");
7252         return;
7253     }
7254     ok(ret == WSAHOST_NOT_FOUND, "got %d expected WSAHOST_NOT_FOUND\n", ret);
7255     ok(WSAGetLastError() == WSAHOST_NOT_FOUND, "expected 11001, got %d\n", WSAGetLastError());
7256     ok(result == NULL, "got %p\n", result);
7257 
7258     result = (ADDRINFOW *)0xdeadbeef;
7259     WSASetLastError(0xdeadbeef);
7260     ret = pGetAddrInfoW(nxdomain, NULL, NULL, &result);
7261     if(ret == 0)
7262     {
7263         skip("nxdomain returned success. Broken ISP redirects?\n");
7264         return;
7265     }
7266     ok(ret == WSAHOST_NOT_FOUND, "got %d expected WSAHOST_NOT_FOUND\n", ret);
7267     ok(WSAGetLastError() == WSAHOST_NOT_FOUND, "expected 11001, got %d\n", WSAGetLastError());
7268     ok(result == NULL, "got %p\n", result);
7269 
7270     for (i = 0;i < (sizeof(hinttests) / sizeof(hinttests[0]));i++)
7271     {
7272         hint.ai_family = hinttests[i].family;
7273         hint.ai_socktype = hinttests[i].socktype;
7274         hint.ai_protocol = hinttests[i].protocol;
7275 
7276         result = NULL;
7277         SetLastError(0xdeadbeef);
7278         ret = pGetAddrInfoW(localhost, NULL, &hint, &result);
7279         if (!ret)
7280         {
7281             if (hinttests[i].error)
7282                 ok(0, "test %d: GetAddrInfoW succeeded unexpectedly\n", i);
7283             else
7284             {
7285                 p = result;
7286                 do
7287                 {
7288                     /* when AF_UNSPEC is used the return will be either AF_INET or AF_INET6 */
7289                     if (hinttests[i].family == AF_UNSPEC)
7290                         ok(p->ai_family == AF_INET || p->ai_family == AF_INET6,
7291                            "test %d: expected AF_INET or AF_INET6, got %d\n",
7292                            i, p->ai_family);
7293                     else
7294                         ok(p->ai_family == hinttests[i].family,
7295                            "test %d: expected family %d, got %d\n",
7296                            i, hinttests[i].family, p->ai_family);
7297 
7298                     ok(p->ai_socktype == hinttests[i].socktype,
7299                        "test %d: expected type %d, got %d\n",
7300                        i, hinttests[i].socktype, p->ai_socktype);
7301                     ok(p->ai_protocol == hinttests[i].protocol,
7302                        "test %d: expected protocol %d, got %d\n",
7303                        i, hinttests[i].protocol, p->ai_protocol);
7304                     p = p->ai_next;
7305                 }
7306                 while (p);
7307             }
7308             pFreeAddrInfoW(result);
7309         }
7310         else
7311         {
7312             DWORD err = WSAGetLastError();
7313             if (hinttests[i].error)
7314                 ok(hinttests[i].error == err, "test %d: GetAddrInfoW failed with error %d, expected %d\n",
7315                    i, err, hinttests[i].error);
7316             else
7317                 ok(0, "test %d: GetAddrInfoW failed with %d (err %d)\n", i, ret, err);
7318         }
7319     }
7320 
7321     /* Test IDN resolution (Internationalized Domain Names) present since Windows 8 */
7322     trace("Testing punycode IDN %s\n", wine_dbgstr_w(idn_punycode));
7323     result = NULL;
7324     ret = pGetAddrInfoW(idn_punycode, NULL, NULL, &result);
7325     ok(!ret, "got %d expected success\n", ret);
7326     ok(result != NULL, "got %p\n", result);
7327     pFreeAddrInfoW(result);
7328 
7329     hint.ai_family = AF_INET;
7330     hint.ai_socktype = 0;
7331     hint.ai_protocol = 0;
7332     hint.ai_flags = 0;
7333 
7334     result = NULL;
7335     ret = pGetAddrInfoW(idn_punycode, NULL, &hint, &result);
7336     ok(!ret, "got %d expected success\n", ret);
7337     ok(result != NULL, "got %p\n", result);
7338 
7339     trace("Testing unicode IDN %s\n", wine_dbgstr_w(idn_domain));
7340     result2 = NULL;
7341     ret = pGetAddrInfoW(idn_domain, NULL, NULL, &result2);
7342     if (ret == WSAHOST_NOT_FOUND && broken(1))
7343     {
7344         pFreeAddrInfoW(result);
7345         win_skip("IDN resolution not supported in Win <= 7\n");
7346         return;
7347     }
7348 
7349     ok(!ret, "got %d expected success\n", ret);
7350     ok(result2 != NULL, "got %p\n", result2);
7351     pFreeAddrInfoW(result2);
7352 
7353     hint.ai_family = AF_INET;
7354     hint.ai_socktype = 0;
7355     hint.ai_protocol = 0;
7356     hint.ai_flags = 0;
7357 
7358     result2 = NULL;
7359     ret = pGetAddrInfoW(idn_domain, NULL, &hint, &result2);
7360     ok(!ret, "got %d expected success\n", ret);
7361     ok(result2 != NULL, "got %p\n", result2);
7362 
7363     /* ensure manually resolved punycode and unicode hosts result in same data */
7364     compare_addrinfow(result, result2);
7365 
7366     pFreeAddrInfoW(result);
7367     pFreeAddrInfoW(result2);
7368 
7369     hint.ai_family = AF_INET;
7370     hint.ai_socktype = 0;
7371     hint.ai_protocol = 0;
7372     hint.ai_flags = 0;
7373 
7374     result2 = NULL;
7375     ret = pGetAddrInfoW(idn_domain, NULL, &hint, &result2);
7376     ok(!ret, "got %d expected success\n", ret);
7377     ok(result2 != NULL, "got %p\n", result2);
7378     pFreeAddrInfoW(result2);
7379 
7380     /* Disable IDN resolution and test again*/
7381     hint.ai_family = AF_INET;
7382     hint.ai_socktype = 0;
7383     hint.ai_protocol = 0;
7384     hint.ai_flags = AI_DISABLE_IDN_ENCODING;
7385 
7386     SetLastError(0xdeadbeef);
7387     result2 = NULL;
7388     ret = pGetAddrInfoW(idn_domain, NULL, &hint, &result2);
7389     ok(ret == WSAHOST_NOT_FOUND, "got %d expected WSAHOST_NOT_FOUND\n", ret);
7390     ok(WSAGetLastError() == WSAHOST_NOT_FOUND, "expected 11001, got %d\n", WSAGetLastError());
7391     ok(result2 == NULL, "got %p\n", result2);
7392 }
7393 
7394 static void test_GetAddrInfoExW(void)
7395 {
7396     static const WCHAR empty[] = {0};
7397     static const WCHAR localhost[] = {'l','o','c','a','l','h','o','s','t',0};
7398     static const WCHAR winehq[] = {'t','e','s','t','.','w','i','n','e','h','q','.','o','r','g',0};
7399     ADDRINFOEXW *result;
7400     OVERLAPPED overlapped;
7401     HANDLE event;
7402     int ret;
7403 
7404     if (!pGetAddrInfoExW || !pGetAddrInfoExOverlappedResult)
7405     {
7406         win_skip("GetAddrInfoExW and/or GetAddrInfoExOverlappedResult not present\n");
7407         return;
7408     }
7409 
7410     event = WSACreateEvent();
7411 
7412     result = (ADDRINFOEXW *)0xdeadbeef;
7413     WSASetLastError(0xdeadbeef);
7414     ret = pGetAddrInfoExW(NULL, NULL, NS_DNS, NULL, NULL, &result, NULL, NULL, NULL, NULL);
7415     ok(ret == WSAHOST_NOT_FOUND, "got %d expected WSAHOST_NOT_FOUND\n", ret);
7416     ok(WSAGetLastError() == WSAHOST_NOT_FOUND, "expected 11001, got %d\n", WSAGetLastError());
7417     ok(result == NULL, "got %p\n", result);
7418 
7419     result = NULL;
7420     WSASetLastError(0xdeadbeef);
7421     ret = pGetAddrInfoExW(empty, NULL, NS_DNS, NULL, NULL, &result, NULL, NULL, NULL, NULL);
7422     ok(!ret, "GetAddrInfoExW failed with %d\n", WSAGetLastError());
7423     ok(result != NULL, "GetAddrInfoW failed\n");
7424     ok(WSAGetLastError() == 0, "expected 0, got %d\n", WSAGetLastError());
7425     pFreeAddrInfoExW(result);
7426 
7427     result = NULL;
7428     ret = pGetAddrInfoExW(localhost, NULL, NS_DNS, NULL, NULL, &result, NULL, NULL, NULL, NULL);
7429     ok(!ret, "GetAddrInfoExW failed with %d\n", WSAGetLastError());
7430     pFreeAddrInfoExW(result);
7431 
7432     result = (void*)0xdeadbeef;
7433     memset(&overlapped, 0xcc, sizeof(overlapped));
7434     overlapped.hEvent = event;
7435     ResetEvent(event);
7436     ret = pGetAddrInfoExW(localhost, NULL, NS_DNS, NULL, NULL, &result, NULL, &overlapped, NULL, NULL);
7437     ok(ret == ERROR_IO_PENDING, "GetAddrInfoExW failed with %d\n", WSAGetLastError());
7438     ok(!result, "result != NULL\n");
7439     ok(WaitForSingleObject(event, 1000) == WAIT_OBJECT_0, "wait failed\n");
7440     ret = pGetAddrInfoExOverlappedResult(&overlapped);
7441     ok(!ret, "overlapped result is %d\n", ret);
7442     pFreeAddrInfoExW(result);
7443 
7444     result = (void*)0xdeadbeef;
7445     memset(&overlapped, 0xcc, sizeof(overlapped));
7446     ResetEvent(event);
7447     overlapped.hEvent = event;
7448     WSASetLastError(0xdeadbeef);
7449     ret = pGetAddrInfoExW(winehq, NULL, NS_DNS, NULL, NULL, &result, NULL, &overlapped, NULL, NULL);
7450     ok(ret == ERROR_IO_PENDING, "GetAddrInfoExW failed with %d\n", WSAGetLastError());
7451     ok(WSAGetLastError() == ERROR_IO_PENDING, "expected 11001, got %d\n", WSAGetLastError());
7452     ret = overlapped.Internal;
7453     ok(ret == WSAEINPROGRESS || ret == ERROR_SUCCESS, "overlapped.Internal = %u\n", ret);
7454     ok(WaitForSingleObject(event, 1000) == WAIT_OBJECT_0, "wait failed\n");
7455     ret = pGetAddrInfoExOverlappedResult(&overlapped);
7456     ok(!ret, "overlapped result is %d\n", ret);
7457     ok(overlapped.hEvent == event, "hEvent changed %p\n", overlapped.hEvent);
7458     ok(overlapped.Internal == ERROR_SUCCESS, "overlapped.Internal = %lx\n", overlapped.Internal);
7459     ok(overlapped.Pointer == &result, "overlapped.Pointer != &result\n");
7460     ok(result != NULL, "result == NULL\n");
7461     ok(!result->ai_blob, "ai_blob != NULL\n");
7462     ok(!result->ai_bloblen, "ai_bloblen != 0\n");
7463     ok(!result->ai_provider, "ai_provider = %s\n", wine_dbgstr_guid(result->ai_provider));
7464     pFreeAddrInfoExW(result);
7465 
7466     result = (void*)0xdeadbeef;
7467     memset(&overlapped, 0xcc, sizeof(overlapped));
7468     ResetEvent(event);
7469     overlapped.hEvent = event;
7470     ret = pGetAddrInfoExW(NULL, NULL, NS_DNS, NULL, NULL, &result, NULL, &overlapped, NULL, NULL);
7471     todo_wine
7472     ok(ret == WSAHOST_NOT_FOUND, "got %d expected WSAHOST_NOT_FOUND\n", ret);
7473     todo_wine
7474     ok(WSAGetLastError() == WSAHOST_NOT_FOUND, "expected 11001, got %d\n", WSAGetLastError());
7475     ok(result == NULL, "got %p\n", result);
7476     ret = WaitForSingleObject(event, 0);
7477     todo_wine_if(ret != WAIT_TIMEOUT) /* Remove when abowe todo_wines are fixed */
7478     ok(ret == WAIT_TIMEOUT, "wait failed\n");
7479 
7480     WSACloseEvent(event);
7481 }
7482 
7483 static void verify_ipv6_addrinfo(ADDRINFOA *result, const char *expectedIp)
7484 {
7485     SOCKADDR_IN6 *sockaddr6;
7486     char ipBuffer[256];
7487     const char *ret;
7488 
7489     ok(result->ai_family == AF_INET6, "ai_family == %d\n", result->ai_family);
7490     ok(result->ai_addrlen >= sizeof(struct sockaddr_in6), "ai_addrlen == %d\n", (int)result->ai_addrlen);
7491     ok(result->ai_addr != NULL, "ai_addr == NULL\n");
7492 
7493     if (result->ai_addr != NULL)
7494     {
7495         sockaddr6 = (SOCKADDR_IN6 *)result->ai_addr;
7496         ok(sockaddr6->sin6_family == AF_INET6, "ai_addr->sin6_family == %d\n", sockaddr6->sin6_family);
7497         ok(sockaddr6->sin6_port == 0, "ai_addr->sin6_port == %d\n", sockaddr6->sin6_port);
7498 
7499         ZeroMemory(ipBuffer, sizeof(ipBuffer));
7500         ret = pInetNtop(AF_INET6, &sockaddr6->sin6_addr, ipBuffer, sizeof(ipBuffer));
7501         ok(ret != NULL, "inet_ntop failed (%d)\n", WSAGetLastError());
7502         ok(strcmp(ipBuffer, expectedIp) == 0, "ai_addr->sin6_addr == '%s' (expected '%s')\n", ipBuffer, expectedIp);
7503     }
7504 }
7505 
7506 static void test_getaddrinfo(void)
7507 {
7508     int i, ret;
7509     ADDRINFOA *result, *result2, *p, hint;
7510     SOCKADDR_IN *sockaddr;
7511     CHAR name[256], *ip;
7512     DWORD size = sizeof(name);
7513 
7514     if (!pgetaddrinfo || !pfreeaddrinfo)
7515     {
7516         win_skip("getaddrinfo and/or freeaddrinfo not present\n");
7517         return;
7518     }
7519     memset(&hint, 0, sizeof(ADDRINFOA));
7520     GetComputerNameExA( ComputerNamePhysicalDnsHostname, name, &size );
7521 
7522     result = (ADDRINFOA *)0xdeadbeef;
7523     WSASetLastError(0xdeadbeef);
7524     ret = pgetaddrinfo(NULL, NULL, NULL, &result);
7525     ok(ret == WSAHOST_NOT_FOUND, "got %d expected WSAHOST_NOT_FOUND\n", ret);
7526     ok(WSAGetLastError() == WSAHOST_NOT_FOUND, "expected 11001, got %d\n", WSAGetLastError());
7527     ok(result == NULL, "got %p\n", result);
7528 
7529     result = NULL;
7530     WSASetLastError(0xdeadbeef);
7531     ret = pgetaddrinfo("", NULL, NULL, &result);
7532     ok(!ret, "getaddrinfo failed with %d\n", WSAGetLastError());
7533     ok(result != NULL, "getaddrinfo failed\n");
7534     ok(WSAGetLastError() == 0, "expected 0, got %d\n", WSAGetLastError());
7535     pfreeaddrinfo(result);
7536 
7537     result = NULL;
7538     ret = pgetaddrinfo(NULL, "0", NULL, &result);
7539     ok(!ret, "getaddrinfo failed with %d\n", WSAGetLastError());
7540     ok(result != NULL, "getaddrinfo failed\n");
7541 
7542     result2 = NULL;
7543     ret = pgetaddrinfo(NULL, "", NULL, &result2);
7544     ok(!ret, "getaddrinfo failed with %d\n", WSAGetLastError());
7545     ok(result2 != NULL, "getaddrinfo failed\n");
7546     compare_addrinfo(result, result2);
7547     pfreeaddrinfo(result);
7548     pfreeaddrinfo(result2);
7549 
7550     result = NULL;
7551     WSASetLastError(0xdeadbeef);
7552     ret = pgetaddrinfo("", "0", NULL, &result);
7553     ok(!ret, "getaddrinfo failed with %d\n", WSAGetLastError());
7554     ok(WSAGetLastError() == 0, "expected 0, got %d\n", WSAGetLastError());
7555     ok(result != NULL, "getaddrinfo failed\n");
7556 
7557     result2 = NULL;
7558     ret = pgetaddrinfo("", "", NULL, &result2);
7559     ok(!ret, "getaddrinfo failed with %d\n", WSAGetLastError());
7560     ok(result2 != NULL, "getaddrinfo failed\n");
7561     compare_addrinfo(result, result2);
7562     pfreeaddrinfo(result);
7563     pfreeaddrinfo(result2);
7564 
7565     result = NULL;
7566     ret = pgetaddrinfo("localhost", NULL, NULL, &result);
7567     ok(!ret, "getaddrinfo failed with %d\n", WSAGetLastError());
7568     pfreeaddrinfo(result);
7569 
7570     result = NULL;
7571     ret = pgetaddrinfo("localhost", "", NULL, &result);
7572     ok(!ret, "getaddrinfo failed with %d\n", WSAGetLastError());
7573     pfreeaddrinfo(result);
7574 
7575     result = NULL;
7576     ret = pgetaddrinfo("localhost", "0", NULL, &result);
7577     ok(!ret, "getaddrinfo failed with %d\n", WSAGetLastError());
7578     pfreeaddrinfo(result);
7579 
7580     result = NULL;
7581     ret = pgetaddrinfo("localhost", "80", NULL, &result);
7582     ok(!ret, "getaddrinfo failed with %d\n", WSAGetLastError());
7583     pfreeaddrinfo(result);
7584 
7585     result = NULL;
7586     ret = pgetaddrinfo("localhost", NULL, &hint, &result);
7587     ok(!ret, "getaddrinfo failed with %d\n", WSAGetLastError());
7588     pfreeaddrinfo(result);
7589 
7590     result = NULL;
7591     WSASetLastError(0xdeadbeef);
7592     ret = pgetaddrinfo("localhost", "80", &hint, &result);
7593     ok(!ret, "getaddrinfo failed with %d\n", WSAGetLastError());
7594     ok(WSAGetLastError() == 0, "expected 0, got %d\n", WSAGetLastError());
7595     pfreeaddrinfo(result);
7596 
7597     hint.ai_flags = AI_NUMERICHOST;
7598     result = (void*)0xdeadbeef;
7599     ret = pgetaddrinfo("localhost", "80", &hint, &result);
7600     ok(ret == WSAHOST_NOT_FOUND, "getaddrinfo failed with %d\n", WSAGetLastError());
7601     ok(WSAGetLastError() == WSAHOST_NOT_FOUND, "expected WSAHOST_NOT_FOUND, got %d\n", WSAGetLastError());
7602     ok(!result, "result = %p\n", result);
7603     hint.ai_flags = 0;
7604 
7605     /* try to get information from the computer name, result is the same
7606      * as if requesting with an empty host name. */
7607     ret = pgetaddrinfo(name, NULL, NULL, &result);
7608     ok(!ret, "getaddrinfo failed with %d\n", WSAGetLastError());
7609     ok(result != NULL, "getaddrinfo failed\n");
7610 
7611     ret = pgetaddrinfo("", NULL, NULL, &result2);
7612     ok(!ret, "getaddrinfo failed with %d\n", WSAGetLastError());
7613     ok(result2 != NULL, "getaddrinfo failed\n");
7614     compare_addrinfo(result, result2);
7615     pfreeaddrinfo(result);
7616     pfreeaddrinfo(result2);
7617 
7618     ret = pgetaddrinfo(name, "", NULL, &result);
7619     ok(!ret, "getaddrinfo failed with %d\n", WSAGetLastError());
7620     ok(result != NULL, "getaddrinfo failed\n");
7621 
7622     ret = pgetaddrinfo("", "", NULL, &result2);
7623     ok(!ret, "getaddrinfo failed with %d\n", WSAGetLastError());
7624     ok(result2 != NULL, "getaddrinfo failed\n");
7625     compare_addrinfo(result, result2);
7626     pfreeaddrinfo(result);
7627     pfreeaddrinfo(result2);
7628 
7629     result = (ADDRINFOA *)0xdeadbeef;
7630     WSASetLastError(0xdeadbeef);
7631     ret = pgetaddrinfo("nxdomain.codeweavers.com", NULL, NULL, &result);
7632     if(ret == 0)
7633     {
7634         skip("nxdomain returned success. Broken ISP redirects?\n");
7635         return;
7636     }
7637     ok(ret == WSAHOST_NOT_FOUND, "got %d expected WSAHOST_NOT_FOUND\n", ret);
7638     ok(WSAGetLastError() == WSAHOST_NOT_FOUND, "expected 11001, got %d\n", WSAGetLastError());
7639     ok(result == NULL, "got %p\n", result);
7640 
7641     /* Test IPv4 address conversion */
7642     result = NULL;
7643     ret = pgetaddrinfo("192.168.1.253", NULL, NULL, &result);
7644     ok(!ret, "getaddrinfo failed with %d\n", ret);
7645     ok(result->ai_family == AF_INET, "ai_family == %d\n", result->ai_family);
7646     ok(result->ai_addrlen >= sizeof(struct sockaddr_in), "ai_addrlen == %d\n", (int)result->ai_addrlen);
7647     ok(result->ai_addr != NULL, "ai_addr == NULL\n");
7648     sockaddr = (SOCKADDR_IN *)result->ai_addr;
7649     ok(sockaddr->sin_family == AF_INET, "ai_addr->sin_family == %d\n", sockaddr->sin_family);
7650     ok(sockaddr->sin_port == 0, "ai_addr->sin_port == %d\n", sockaddr->sin_port);
7651 
7652     ip = inet_ntoa(sockaddr->sin_addr);
7653     ok(strcmp(ip, "192.168.1.253") == 0, "sockaddr->ai_addr == '%s'\n", ip);
7654     pfreeaddrinfo(result);
7655 
7656     /* Test IPv4 address conversion with port */
7657     result = NULL;
7658     hint.ai_flags = AI_NUMERICHOST;
7659     ret = pgetaddrinfo("192.168.1.253:1024", NULL, &hint, &result);
7660     hint.ai_flags = 0;
7661     ok(ret == WSAHOST_NOT_FOUND, "getaddrinfo returned unexpected result: %d\n", ret);
7662     ok(result == NULL, "expected NULL, got %p\n", result);
7663 
7664     /* Test IPv6 address conversion */
7665     result = NULL;
7666     SetLastError(0xdeadbeef);
7667     ret = pgetaddrinfo("2a00:2039:dead:beef:cafe::6666", NULL, NULL, &result);
7668 
7669     if (result != NULL)
7670     {
7671         ok(!ret, "getaddrinfo failed with %d\n", ret);
7672         verify_ipv6_addrinfo(result, "2a00:2039:dead:beef:cafe::6666");
7673         pfreeaddrinfo(result);
7674 
7675         /* Test IPv6 address conversion with brackets */
7676         result = NULL;
7677         ret = pgetaddrinfo("[beef::cafe]", NULL, NULL, &result);
7678         ok(!ret, "getaddrinfo failed with %d\n", ret);
7679         verify_ipv6_addrinfo(result, "beef::cafe");
7680         pfreeaddrinfo(result);
7681 
7682         /* Test IPv6 address conversion with brackets and hints */
7683         memset(&hint, 0, sizeof(ADDRINFOA));
7684         hint.ai_flags = AI_NUMERICHOST;
7685         hint.ai_family = AF_INET6;
7686         result = NULL;
7687         ret = pgetaddrinfo("[beef::cafe]", NULL, &hint, &result);
7688         ok(!ret, "getaddrinfo failed with %d\n", ret);
7689         verify_ipv6_addrinfo(result, "beef::cafe");
7690         pfreeaddrinfo(result);
7691 
7692         memset(&hint, 0, sizeof(ADDRINFOA));
7693         hint.ai_flags = AI_NUMERICHOST;
7694         hint.ai_family = AF_INET;
7695         result = NULL;
7696         ret = pgetaddrinfo("[beef::cafe]", NULL, &hint, &result);
7697         ok(ret == WSAHOST_NOT_FOUND, "getaddrinfo failed with %d\n", ret);
7698 
7699         /* Test IPv6 address conversion with brackets and port */
7700         result = NULL;
7701         ret = pgetaddrinfo("[beef::cafe]:10239", NULL, NULL, &result);
7702         ok(!ret, "getaddrinfo failed with %d\n", ret);
7703         verify_ipv6_addrinfo(result, "beef::cafe");
7704         pfreeaddrinfo(result);
7705 
7706         /* Test IPv6 address conversion with unmatched brackets */
7707         result = NULL;
7708         hint.ai_flags = AI_NUMERICHOST;
7709         ret = pgetaddrinfo("[beef::cafe", NULL, &hint, &result);
7710         ok(ret == WSAHOST_NOT_FOUND, "getaddrinfo failed with %d\n", ret);
7711 
7712         ret = pgetaddrinfo("beef::cafe]", NULL, &hint, &result);
7713         ok(ret == WSAHOST_NOT_FOUND, "getaddrinfo failed with %d\n", ret);
7714     }
7715     else
7716     {
7717         ok(ret == WSAHOST_NOT_FOUND, "getaddrinfo failed with %d\n", ret);
7718         win_skip("getaddrinfo does not support IPV6\n");
7719     }
7720 
7721     hint.ai_flags = 0;
7722 
7723     for (i = 0;i < (sizeof(hinttests) / sizeof(hinttests[0]));i++)
7724     {
7725         hint.ai_family = hinttests[i].family;
7726         hint.ai_socktype = hinttests[i].socktype;
7727         hint.ai_protocol = hinttests[i].protocol;
7728 
7729         result = NULL;
7730         SetLastError(0xdeadbeef);
7731         ret = pgetaddrinfo("localhost", NULL, &hint, &result);
7732         if(!ret)
7733         {
7734             if (hinttests[i].error)
7735                 ok(0, "test %d: getaddrinfo succeeded unexpectedly\n", i);
7736             else
7737             {
7738                 p = result;
7739                 do
7740                 {
7741                     /* when AF_UNSPEC is used the return will be either AF_INET or AF_INET6 */
7742                     if (hinttests[i].family == AF_UNSPEC)
7743                         ok(p->ai_family == AF_INET || p->ai_family == AF_INET6,
7744                            "test %d: expected AF_INET or AF_INET6, got %d\n",
7745                            i, p->ai_family);
7746                     else
7747                         ok(p->ai_family == hinttests[i].family,
7748                            "test %d: expected family %d, got %d\n",
7749                            i, hinttests[i].family, p->ai_family);
7750 
7751                     ok(p->ai_socktype == hinttests[i].socktype,
7752                        "test %d: expected type %d, got %d\n",
7753                        i, hinttests[i].socktype, p->ai_socktype);
7754                     ok(p->ai_protocol == hinttests[i].protocol,
7755                        "test %d: expected protocol %d, got %d\n",
7756                        i, hinttests[i].protocol, p->ai_protocol);
7757                     p = p->ai_next;
7758                 }
7759                 while (p);
7760             }
7761             pfreeaddrinfo(result);
7762         }
7763         else
7764         {
7765             DWORD err = WSAGetLastError();
7766             if (hinttests[i].error)
7767                 ok(hinttests[i].error == err, "test %d: getaddrinfo failed with error %d, expected %d\n",
7768                    i, err, hinttests[i].error);
7769             else
7770                 ok(0, "test %d: getaddrinfo failed with %d (err %d)\n", i, ret, err);
7771         }
7772     }
7773 }
7774 
7775 static void test_ConnectEx(void)
7776 {
7777     SOCKET listener = INVALID_SOCKET;
7778     SOCKET acceptor = INVALID_SOCKET;
7779     SOCKET connector = INVALID_SOCKET;
7780     struct sockaddr_in address, conaddress;
7781     int addrlen;
7782     OVERLAPPED overlapped;
7783     LPFN_CONNECTEX pConnectEx;
7784     GUID connectExGuid = WSAID_CONNECTEX;
7785     DWORD bytesReturned;
7786     char buffer[1024];
7787     BOOL bret;
7788     DWORD dwret;
7789     int iret;
7790 
7791     memset(&overlapped, 0, sizeof(overlapped));
7792 
7793     listener = socket(AF_INET, SOCK_STREAM, 0);
7794     if (listener == INVALID_SOCKET) {
7795         skip("could not create listener socket, error %d\n", WSAGetLastError());
7796         goto end;
7797     }
7798 
7799     connector = socket(AF_INET, SOCK_STREAM, 0);
7800     if (connector == INVALID_SOCKET) {
7801         skip("could not create connector socket, error %d\n", WSAGetLastError());
7802         goto end;
7803     }
7804 
7805     memset(&address, 0, sizeof(address));
7806     address.sin_family = AF_INET;
7807     address.sin_addr.s_addr = inet_addr("127.0.0.1");
7808     iret = bind(listener, (struct sockaddr*)&address, sizeof(address));
7809     if (iret != 0) {
7810         skip("failed to bind, error %d\n", WSAGetLastError());
7811         goto end;
7812     }
7813 
7814     addrlen = sizeof(address);
7815     iret = getsockname(listener, (struct sockaddr*)&address, &addrlen);
7816     if (iret != 0) {
7817         skip("failed to lookup bind address, error %d\n", WSAGetLastError());
7818         goto end;
7819     }
7820 
7821     if (set_blocking(listener, TRUE)) {
7822         skip("couldn't make socket non-blocking, error %d\n", WSAGetLastError());
7823         goto end;
7824     }
7825 
7826     bytesReturned = 0xdeadbeef;
7827     iret = WSAIoctl(connector, SIO_GET_EXTENSION_FUNCTION_POINTER, &connectExGuid, sizeof(connectExGuid),
7828         &pConnectEx, sizeof(pConnectEx), &bytesReturned, NULL, NULL);
7829     if (iret) {
7830         win_skip("WSAIoctl failed to get ConnectEx with ret %d + errno %d\n", iret, WSAGetLastError());
7831         goto end;
7832     }
7833 
7834     ok(bytesReturned == sizeof(pConnectEx), "expected sizeof(pConnectEx), got %u\n", bytesReturned);
7835 
7836     bret = pConnectEx(INVALID_SOCKET, (struct sockaddr*)&address, addrlen, NULL, 0, &bytesReturned, &overlapped);
7837     ok(bret == FALSE && WSAGetLastError() == WSAENOTSOCK, "ConnectEx on invalid socket "
7838         "returned %d + errno %d\n", bret, WSAGetLastError());
7839 
7840     bret = pConnectEx(connector, (struct sockaddr*)&address, addrlen, NULL, 0, &bytesReturned, &overlapped);
7841     ok(bret == FALSE && WSAGetLastError() == WSAEINVAL, "ConnectEx on a unbound socket "
7842         "returned %d + errno %d\n", bret, WSAGetLastError());
7843     if (bret == TRUE || WSAGetLastError() != WSAEINVAL)
7844     {
7845         acceptor = accept(listener, NULL, NULL);
7846         if (acceptor != INVALID_SOCKET) {
7847             closesocket(acceptor);
7848             acceptor = INVALID_SOCKET;
7849         }
7850 
7851         closesocket(connector);
7852         connector = socket(AF_INET, SOCK_STREAM, 0);
7853         if (connector == INVALID_SOCKET) {
7854             skip("could not create connector socket, error %d\n", WSAGetLastError());
7855             goto end;
7856         }
7857     }
7858 
7859     /* ConnectEx needs a bound socket */
7860     memset(&conaddress, 0, sizeof(conaddress));
7861     conaddress.sin_family = AF_INET;
7862     conaddress.sin_addr.s_addr = inet_addr("127.0.0.1");
7863     iret = bind(connector, (struct sockaddr*)&conaddress, sizeof(conaddress));
7864     if (iret != 0) {
7865         skip("failed to bind, error %d\n", WSAGetLastError());
7866         goto end;
7867     }
7868 
7869     bret = pConnectEx(connector, (struct sockaddr*)&address, addrlen, NULL, 0, &bytesReturned, NULL);
7870     ok(bret == FALSE && WSAGetLastError() == ERROR_INVALID_PARAMETER, "ConnectEx on a NULL overlapped "
7871         "returned %d + errno %d\n", bret, WSAGetLastError());
7872 
7873     overlapped.hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
7874     if (overlapped.hEvent == NULL) {
7875         skip("could not create event object, errno = %d\n", GetLastError());
7876         goto end;
7877     }
7878 
7879     iret = listen(listener, 1);
7880     if (iret != 0) {
7881         skip("listening failed, errno = %d\n", WSAGetLastError());
7882         goto end;
7883     }
7884 
7885     bret = pConnectEx(connector, (struct sockaddr*)&address, addrlen, NULL, 0, &bytesReturned, &overlapped);
7886     ok(bret == FALSE && WSAGetLastError() == ERROR_IO_PENDING, "ConnectEx failed: "
7887         "returned %d + errno %d\n", bret, WSAGetLastError());
7888     dwret = WaitForSingleObject(overlapped.hEvent, 15000);
7889     ok(dwret == WAIT_OBJECT_0, "Waiting for connect event failed with %d + errno %d\n", dwret, GetLastError());
7890 
7891     bret = GetOverlappedResult((HANDLE)connector, &overlapped, &bytesReturned, FALSE);
7892     ok(bret, "Connecting failed, error %d\n", GetLastError());
7893     ok(bytesReturned == 0, "Bytes sent is %d\n", bytesReturned);
7894 
7895     closesocket(connector);
7896     connector = socket(AF_INET, SOCK_STREAM, 0);
7897     if (connector == INVALID_SOCKET) {
7898         skip("could not create connector socket, error %d\n", WSAGetLastError());
7899         goto end;
7900     }
7901     /* ConnectEx needs a bound socket */
7902     memset(&conaddress, 0, sizeof(conaddress));
7903     conaddress.sin_family = AF_INET;
7904     conaddress.sin_addr.s_addr = inet_addr("127.0.0.1");
7905     iret = bind(connector, (struct sockaddr*)&conaddress, sizeof(conaddress));
7906     if (iret != 0) {
7907         skip("failed to bind, error %d\n", WSAGetLastError());
7908         goto end;
7909     }
7910 
7911     acceptor = accept(listener, NULL, NULL);
7912     if (acceptor != INVALID_SOCKET) {
7913         closesocket(acceptor);
7914     }
7915 
7916     buffer[0] = '1';
7917     buffer[1] = '2';
7918     buffer[2] = '3';
7919     bret = pConnectEx(connector, (struct sockaddr*)&address, addrlen, buffer, 3, &bytesReturned, &overlapped);
7920     ok(bret == FALSE && WSAGetLastError() == ERROR_IO_PENDING, "ConnectEx failed: "
7921         "returned %d + errno %d\n", bret, WSAGetLastError());
7922     dwret = WaitForSingleObject(overlapped.hEvent, 15000);
7923     ok(dwret == WAIT_OBJECT_0, "Waiting for connect event failed with %d + errno %d\n", dwret, GetLastError());
7924 
7925     bret = GetOverlappedResult((HANDLE)connector, &overlapped, &bytesReturned, FALSE);
7926     ok(bret, "Connecting failed, error %d\n", GetLastError());
7927     ok(bytesReturned == 3, "Bytes sent is %d\n", bytesReturned);
7928 
7929     acceptor = accept(listener, NULL, NULL);
7930     ok(acceptor != INVALID_SOCKET, "could not accept socket error %d\n", WSAGetLastError());
7931 
7932     bytesReturned = recv(acceptor, buffer, 3, 0);
7933     buffer[4] = 0;
7934     ok(bytesReturned == 3, "Didn't get all sent data, got only %d\n", bytesReturned);
7935     ok(buffer[0] == '1' && buffer[1] == '2' && buffer[2] == '3',
7936        "Failed to get the right data, expected '123', got '%s'\n", buffer);
7937 
7938     closesocket(connector);
7939     connector = socket(AF_INET, SOCK_STREAM, 0);
7940     if (connector == INVALID_SOCKET) {
7941         skip("could not create connector socket, error %d\n", WSAGetLastError());
7942         goto end;
7943     }
7944     /* ConnectEx needs a bound socket */
7945     memset(&conaddress, 0, sizeof(conaddress));
7946     conaddress.sin_family = AF_INET;
7947     conaddress.sin_addr.s_addr = inet_addr("127.0.0.1");
7948     iret = bind(connector, (struct sockaddr*)&conaddress, sizeof(conaddress));
7949     if (iret != 0) {
7950         skip("failed to bind, error %d\n", WSAGetLastError());
7951         goto end;
7952     }
7953 
7954     if (acceptor != INVALID_SOCKET) {
7955         closesocket(acceptor);
7956         acceptor = INVALID_SOCKET;
7957     }
7958 
7959     /* Connect with error */
7960     closesocket(listener);
7961     listener = INVALID_SOCKET;
7962 
7963     address.sin_port = htons(1);
7964 
7965     bret = pConnectEx(connector, (struct sockaddr*)&address, addrlen, NULL, 0, &bytesReturned, &overlapped);
7966     ok(bret == FALSE && GetLastError() == ERROR_IO_PENDING, "ConnectEx to bad destination failed: "
7967         "returned %d + errno %d\n", bret, GetLastError());
7968     dwret = WaitForSingleObject(overlapped.hEvent, 15000);
7969     ok(dwret == WAIT_OBJECT_0, "Waiting for connect event failed with %d + errno %d\n", dwret, GetLastError());
7970 
7971     bret = GetOverlappedResult((HANDLE)connector, &overlapped, &bytesReturned, FALSE);
7972     ok(bret == FALSE && GetLastError() == ERROR_CONNECTION_REFUSED,
7973        "Connecting to a disconnected host returned error %d - %d\n", bret, WSAGetLastError());
7974 
7975 end:
7976     if (overlapped.hEvent)
7977         WSACloseEvent(overlapped.hEvent);
7978     if (listener != INVALID_SOCKET)
7979         closesocket(listener);
7980     if (acceptor != INVALID_SOCKET)
7981         closesocket(acceptor);
7982     if (connector != INVALID_SOCKET)
7983         closesocket(connector);
7984 }
7985 
7986 static void test_AcceptEx(void)
7987 {
7988     SOCKET listener = INVALID_SOCKET;
7989     SOCKET acceptor = INVALID_SOCKET;
7990     SOCKET connector = INVALID_SOCKET;
7991     SOCKET connector2 = INVALID_SOCKET;
7992     struct sockaddr_in bindAddress, peerAddress, *readBindAddress, *readRemoteAddress;
7993     int socklen, optlen;
7994     GUID acceptExGuid = WSAID_ACCEPTEX, getAcceptExGuid = WSAID_GETACCEPTEXSOCKADDRS;
7995     LPFN_ACCEPTEX pAcceptEx = NULL;
7996     LPFN_GETACCEPTEXSOCKADDRS pGetAcceptExSockaddrs = NULL;
7997     fd_set fds_accept, fds_send;
7998     struct timeval timeout = {0,10}; /* wait for 10 milliseconds */
7999     int got, conn1, i;
8000     DWORD bytesReturned, connect_time;
8001     char buffer[1024], ipbuffer[32];
8002     OVERLAPPED overlapped;
8003     int iret, localSize = sizeof(struct sockaddr_in), remoteSize = localSize;
8004     BOOL bret;
8005     DWORD dwret;
8006 
8007     memset(&overlapped, 0, sizeof(overlapped));
8008 
8009     listener = socket(AF_INET, SOCK_STREAM, 0);
8010     if (listener == INVALID_SOCKET) {
8011         skip("could not create listener socket, error %d\n", WSAGetLastError());
8012         goto end;
8013     }
8014 
8015     acceptor = socket(AF_INET, SOCK_STREAM, 0);
8016     if (acceptor == INVALID_SOCKET) {
8017         skip("could not create acceptor socket, error %d\n", WSAGetLastError());
8018         goto end;
8019     }
8020 
8021     connector = socket(AF_INET, SOCK_STREAM, 0);
8022     if (connector == INVALID_SOCKET) {
8023         skip("could not create connector socket, error %d\n", WSAGetLastError());
8024         goto end;
8025     }
8026 
8027     memset(&bindAddress, 0, sizeof(bindAddress));
8028     bindAddress.sin_family = AF_INET;
8029     bindAddress.sin_addr.s_addr = inet_addr("127.0.0.1");
8030     iret = bind(listener, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
8031     if (iret != 0) {
8032         skip("failed to bind, error %d\n", WSAGetLastError());
8033         goto end;
8034     }
8035 
8036     socklen = sizeof(bindAddress);
8037     iret = getsockname(listener, (struct sockaddr*)&bindAddress, &socklen);
8038     if (iret != 0) {
8039         skip("failed to lookup bind address, error %d\n", WSAGetLastError());
8040         goto end;
8041     }
8042 
8043     if (set_blocking(listener, FALSE)) {
8044         skip("couldn't make socket non-blocking, error %d\n", WSAGetLastError());
8045         goto end;
8046     }
8047 
8048     iret = WSAIoctl(listener, SIO_GET_EXTENSION_FUNCTION_POINTER, &acceptExGuid, sizeof(acceptExGuid),
8049         &pAcceptEx, sizeof(pAcceptEx), &bytesReturned, NULL, NULL);
8050     if (iret) {
8051         skip("WSAIoctl failed to get AcceptEx with ret %d + errno %d\n", iret, WSAGetLastError());
8052         goto end;
8053     }
8054 
8055     iret = WSAIoctl(listener, SIO_GET_EXTENSION_FUNCTION_POINTER, &getAcceptExGuid, sizeof(getAcceptExGuid),
8056         &pGetAcceptExSockaddrs, sizeof(pGetAcceptExSockaddrs), &bytesReturned, NULL, NULL);
8057     if (iret) {
8058         skip("WSAIoctl failed to get GetAcceptExSockaddrs with ret %d + errno %d\n", iret, WSAGetLastError());
8059         goto end;
8060     }
8061 
8062     bret = pAcceptEx(INVALID_SOCKET, acceptor, buffer, sizeof(buffer) - 2*(sizeof(struct sockaddr_in) + 16),
8063         sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
8064         &bytesReturned, &overlapped);
8065     ok(bret == FALSE && WSAGetLastError() == WSAENOTSOCK, "AcceptEx on invalid listening socket "
8066         "returned %d + errno %d\n", bret, WSAGetLastError());
8067 
8068     bret = pAcceptEx(listener, acceptor, buffer, sizeof(buffer) - 2*(sizeof(struct sockaddr_in) + 16),
8069         sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
8070         &bytesReturned, &overlapped);
8071 todo_wine
8072     ok(bret == FALSE && WSAGetLastError() == WSAEINVAL, "AcceptEx on a non-listening socket "
8073         "returned %d + errno %d\n", bret, WSAGetLastError());
8074 
8075     iret = listen(listener, 5);
8076     if (iret != 0) {
8077         skip("listening failed, errno = %d\n", WSAGetLastError());
8078         goto end;
8079     }
8080 
8081     bret = pAcceptEx(listener, INVALID_SOCKET, buffer, sizeof(buffer) - 2*(sizeof(struct sockaddr_in) + 16),
8082         sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
8083         &bytesReturned, &overlapped);
8084     ok(bret == FALSE && WSAGetLastError() == WSAENOTSOCK, "AcceptEx on invalid accepting socket "
8085         "returned %d + errno %d\n", bret, WSAGetLastError());
8086 
8087     bret = pAcceptEx(listener, acceptor, NULL, sizeof(buffer) - 2*(sizeof(struct sockaddr_in) + 16),
8088         sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
8089         &bytesReturned, &overlapped);
8090     ok(bret == FALSE &&
8091         (WSAGetLastError() == WSAEINVAL ||
8092          broken(WSAGetLastError() == WSAEFAULT)), /* NT4 */
8093         "AcceptEx on NULL buffer returned %d + errno %d\n", bret, WSAGetLastError());
8094 
8095     bret = pAcceptEx(listener, acceptor, buffer, 0, 0, sizeof(struct sockaddr_in) + 16,
8096         &bytesReturned, &overlapped);
8097     ok(bret == FALSE && (WSAGetLastError() == ERROR_IO_PENDING || broken(WSAGetLastError() == WSAEINVAL)) /* NT4 */,
8098         "AcceptEx on too small local address size returned %d + errno %d\n",
8099         bret, WSAGetLastError());
8100     bret = CancelIo((HANDLE) listener);
8101     ok(bret, "Failed to cancel pending accept socket\n");
8102 
8103     bret = pAcceptEx(listener, acceptor, buffer, 0, sizeof(struct sockaddr_in) + 15,
8104         sizeof(struct sockaddr_in) + 16, &bytesReturned, &overlapped);
8105     ok(bret == FALSE && WSAGetLastError() == ERROR_IO_PENDING, "AcceptEx on too small local address "
8106         "size returned %d + errno %d\n",
8107         bret, WSAGetLastError());
8108     bret = CancelIo((HANDLE) listener);
8109     ok(bret, "Failed to cancel pending accept socket\n");
8110 
8111     bret = pAcceptEx(listener, acceptor, buffer, 0, sizeof(struct sockaddr_in) + 16, 0,
8112         &bytesReturned, &overlapped);
8113     ok(bret == FALSE && (WSAGetLastError() == WSAEFAULT || broken(WSAGetLastError() == WSAEINVAL)) /* NT4 */,
8114         "AcceptEx on too small remote address size returned %d + errno %d\n", bret, WSAGetLastError());
8115 
8116     bret = pAcceptEx(listener, acceptor, buffer, 0, sizeof(struct sockaddr_in) + 16,
8117         sizeof(struct sockaddr_in) + 15, &bytesReturned, &overlapped);
8118     ok(bret == FALSE && (WSAGetLastError() == ERROR_IO_PENDING || broken(WSAGetLastError() == WSAEINVAL)) /* NT4 */,
8119         "AcceptEx on too small remote address size returned %d + errno %d\n", bret, WSAGetLastError());
8120     bret = CancelIo((HANDLE) listener);
8121     ok(bret, "Failed to cancel pending accept socket\n");
8122 
8123     bret = pAcceptEx(listener, acceptor, buffer, 0,
8124         sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
8125         &bytesReturned, NULL);
8126     ok(bret == FALSE && WSAGetLastError() == ERROR_INVALID_PARAMETER, "AcceptEx on a NULL overlapped "
8127         "returned %d + errno %d\n", bret, WSAGetLastError());
8128 
8129     bret = pAcceptEx(listener, acceptor, buffer, 0, 0, 0, &bytesReturned, NULL);
8130     ok(bret == FALSE && WSAGetLastError() == ERROR_INVALID_PARAMETER, "AcceptEx on a NULL overlapped "
8131         "returned %d + errno %d\n", bret, WSAGetLastError());
8132 
8133     overlapped.hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
8134     if (overlapped.hEvent == NULL) {
8135         skip("could not create event object, errno = %d\n", GetLastError());
8136         goto end;
8137     }
8138 
8139     bret = pAcceptEx(listener, acceptor, buffer, 0,
8140         sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
8141         &bytesReturned, &overlapped);
8142     ok(bret == FALSE && WSAGetLastError() == ERROR_IO_PENDING, "AcceptEx returned %d + errno %d\n", bret, WSAGetLastError());
8143 
8144     bret = pAcceptEx(listener, acceptor, buffer, 0,
8145         sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
8146         &bytesReturned, &overlapped);
8147     todo_wine ok((bret == FALSE && WSAGetLastError() == WSAEINVAL) || broken(bret == FALSE && WSAGetLastError() == ERROR_IO_PENDING) /* NT4 */,
8148        "AcceptEx on already pending socket returned %d + errno %d\n", bret, WSAGetLastError());
8149     if (bret == FALSE && WSAGetLastError() == ERROR_IO_PENDING) {
8150         /* We need to cancel this call, otherwise things fail */
8151         bret = CancelIo((HANDLE) listener);
8152         ok(bret, "Failed to cancel failed test. Bailing...\n");
8153         if (!bret) return;
8154         WaitForSingleObject(overlapped.hEvent, 0);
8155 
8156         bret = pAcceptEx(listener, acceptor, buffer, 0,
8157             sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
8158             &bytesReturned, &overlapped);
8159         ok(bret == FALSE && WSAGetLastError() == ERROR_IO_PENDING, "AcceptEx returned %d + errno %d\n", bret, WSAGetLastError());
8160     }
8161 
8162     iret = connect(acceptor,  (struct sockaddr*)&bindAddress, sizeof(bindAddress));
8163     todo_wine ok((iret == SOCKET_ERROR && WSAGetLastError() == WSAEINVAL) || broken(!iret) /* NT4 */,
8164        "connecting to acceptex acceptor succeeded? return %d + errno %d\n", iret, WSAGetLastError());
8165     if (!iret || (iret == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)) {
8166         /* We need to cancel this call, otherwise things fail */
8167         closesocket(acceptor);
8168         acceptor = socket(AF_INET, SOCK_STREAM, 0);
8169         if (acceptor == INVALID_SOCKET) {
8170             skip("could not create acceptor socket, error %d\n", WSAGetLastError());
8171             goto end;
8172         }
8173 
8174         bret = CancelIo((HANDLE) listener);
8175         ok(bret, "Failed to cancel failed test. Bailing...\n");
8176         if (!bret) return;
8177 
8178         bret = pAcceptEx(listener, acceptor, buffer, 0,
8179             sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
8180             &bytesReturned, &overlapped);
8181         ok(bret == FALSE && WSAGetLastError() == ERROR_IO_PENDING, "AcceptEx returned %d + errno %d\n", bret, WSAGetLastError());
8182     }
8183 
8184     iret = connect(connector, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
8185     ok(iret == 0, "connecting to accepting socket failed, error %d\n", WSAGetLastError());
8186 
8187     dwret = WaitForSingleObject(overlapped.hEvent, INFINITE);
8188     ok(dwret == WAIT_OBJECT_0, "Waiting for accept event failed with %d + errno %d\n", dwret, GetLastError());
8189 
8190     bret = GetOverlappedResult((HANDLE)listener, &overlapped, &bytesReturned, FALSE);
8191     ok(bret, "GetOverlappedResult failed, error %d\n", GetLastError());
8192     ok(bytesReturned == 0, "bytesReturned isn't supposed to be %d\n", bytesReturned);
8193 
8194     closesocket(connector);
8195     connector = INVALID_SOCKET;
8196     closesocket(acceptor);
8197 
8198     /* Test short reads */
8199 
8200     acceptor = socket(AF_INET, SOCK_STREAM, 0);
8201     if (acceptor == INVALID_SOCKET) {
8202         skip("could not create acceptor socket, error %d\n", WSAGetLastError());
8203         goto end;
8204     }
8205     connector = socket(AF_INET, SOCK_STREAM, 0);
8206     if (connector == INVALID_SOCKET) {
8207         skip("could not create connector socket, error %d\n", WSAGetLastError());
8208         goto end;
8209     }
8210     bret = pAcceptEx(listener, acceptor, buffer, 2,
8211         sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
8212         &bytesReturned, &overlapped);
8213     ok(bret == FALSE && WSAGetLastError() == ERROR_IO_PENDING, "AcceptEx returned %d + errno %d\n", bret, WSAGetLastError());
8214 
8215     connect_time = 0xdeadbeef;
8216     optlen = sizeof(connect_time);
8217     iret = getsockopt(connector, SOL_SOCKET, SO_CONNECT_TIME, (char *)&connect_time, &optlen);
8218     ok(!iret, "getsockopt failed %d\n", WSAGetLastError());
8219     ok(connect_time == ~0u, "unexpected connect time %u\n", connect_time);
8220 
8221     /* AcceptEx() still won't complete until we send data */
8222     iret = connect(connector, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
8223     ok(iret == 0, "connecting to accepting socket failed, error %d\n", WSAGetLastError());
8224 
8225     connect_time = 0xdeadbeef;
8226     optlen = sizeof(connect_time);
8227     iret = getsockopt(connector, SOL_SOCKET, SO_CONNECT_TIME, (char *)&connect_time, &optlen);
8228     ok(!iret, "getsockopt failed %d\n", WSAGetLastError());
8229     ok(connect_time < 0xdeadbeef, "unexpected connect time %u\n", connect_time);
8230 
8231     dwret = WaitForSingleObject(overlapped.hEvent, 0);
8232     ok(dwret == WAIT_TIMEOUT, "Waiting for accept event timeout failed with %d + errno %d\n", dwret, GetLastError());
8233 
8234     iret = getsockname( connector, (struct sockaddr *)&peerAddress, &remoteSize);
8235     ok( !iret, "getsockname failed.\n");
8236 
8237     /* AcceptEx() could complete any time now */
8238     iret = send(connector, buffer, 1, 0);
8239     ok(iret == 1, "could not send 1 byte: send %d errno %d\n", iret, WSAGetLastError());
8240 
8241     dwret = WaitForSingleObject(overlapped.hEvent, 1000);
8242     ok(dwret == WAIT_OBJECT_0, "Waiting for accept event failed with %d + errno %d\n", dwret, GetLastError());
8243 
8244     /* Check if the buffer from AcceptEx is decoded correctly */
8245     pGetAcceptExSockaddrs(buffer, 2, sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
8246                           (struct sockaddr **)&readBindAddress, &localSize,
8247                           (struct sockaddr **)&readRemoteAddress, &remoteSize);
8248     strcpy( ipbuffer, inet_ntoa(readBindAddress->sin_addr));
8249     ok( readBindAddress->sin_addr.s_addr == bindAddress.sin_addr.s_addr,
8250             "Local socket address is different %s != %s\n",
8251             ipbuffer, inet_ntoa(bindAddress.sin_addr));
8252     ok( readBindAddress->sin_port == bindAddress.sin_port,
8253             "Local socket port is different: %d != %d\n",
8254             readBindAddress->sin_port, bindAddress.sin_port);
8255     strcpy( ipbuffer, inet_ntoa(readRemoteAddress->sin_addr));
8256     ok( readRemoteAddress->sin_addr.s_addr == peerAddress.sin_addr.s_addr,
8257             "Remote socket address is different %s != %s\n",
8258             ipbuffer, inet_ntoa(peerAddress.sin_addr));
8259     ok( readRemoteAddress->sin_port == peerAddress.sin_port,
8260             "Remote socket port is different: %d != %d\n",
8261             readRemoteAddress->sin_port, peerAddress.sin_port);
8262 
8263     bret = GetOverlappedResult((HANDLE)listener, &overlapped, &bytesReturned, FALSE);
8264     ok(bret, "GetOverlappedResult failed, error %d\n", GetLastError());
8265     ok(bytesReturned == 1, "bytesReturned isn't supposed to be %d\n", bytesReturned);
8266 
8267     closesocket(connector);
8268     connector = INVALID_SOCKET;
8269     closesocket(acceptor);
8270 
8271     /* Test CF_DEFER & AcceptEx interaction */
8272 
8273     acceptor = socket(AF_INET, SOCK_STREAM, 0);
8274     if (acceptor == INVALID_SOCKET) {
8275         skip("could not create acceptor socket, error %d\n", WSAGetLastError());
8276         goto end;
8277     }
8278     connector = socket(AF_INET, SOCK_STREAM, 0);
8279     if (connector == INVALID_SOCKET) {
8280         skip("could not create connector socket, error %d\n", WSAGetLastError());
8281         goto end;
8282     }
8283     connector2 = socket(AF_INET, SOCK_STREAM, 0);
8284     if (connector == INVALID_SOCKET) {
8285         skip("could not create connector socket, error %d\n", WSAGetLastError());
8286         goto end;
8287     }
8288 
8289     if (set_blocking(connector, FALSE)) {
8290         skip("couldn't make socket non-blocking, error %d\n", WSAGetLastError());
8291         goto end;
8292     }
8293 
8294     if (set_blocking(connector2, FALSE)) {
8295         skip("couldn't make socket non-blocking, error %d\n", WSAGetLastError());
8296         goto end;
8297     }
8298 
8299     /* Connect socket #1 */
8300     iret = connect(connector, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
8301     ok(iret == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK, "connecting to accepting socket failed, error %d\n", WSAGetLastError());
8302 
8303     FD_ZERO ( &fds_accept );
8304     FD_ZERO ( &fds_send );
8305 
8306     FD_SET ( listener, &fds_accept );
8307     FD_SET ( connector, &fds_send );
8308 
8309     buffer[0] = '0';
8310     got = 0;
8311     conn1 = 0;
8312 
8313     for (i = 0; i < 4000; ++i)
8314     {
8315         fd_set fds_openaccept = fds_accept, fds_opensend = fds_send;
8316 
8317         wsa_ok ( ( select ( 0, &fds_openaccept, &fds_opensend, NULL, &timeout ) ), SOCKET_ERROR !=,
8318             "acceptex test(%d): could not select on socket, errno %d\n" );
8319 
8320         /* check for incoming requests */
8321         if ( FD_ISSET ( listener, &fds_openaccept ) ) {
8322             got++;
8323             if (got == 1) {
8324                 SOCKET tmp = WSAAccept(listener, NULL, NULL, (LPCONDITIONPROC) AlwaysDeferConditionFunc, 0);
8325                 ok(tmp == INVALID_SOCKET && WSAGetLastError() == WSATRY_AGAIN, "Failed to defer connection, %d\n", WSAGetLastError());
8326                 bret = pAcceptEx(listener, acceptor, buffer, 0,
8327                                     sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
8328                                     &bytesReturned, &overlapped);
8329                 ok(bret == FALSE && WSAGetLastError() == ERROR_IO_PENDING, "AcceptEx returned %d + errno %d\n", bret, WSAGetLastError());
8330             }
8331             else if (got == 2) {
8332                 /* this should be socket #2 */
8333                 SOCKET tmp = accept(listener, NULL, NULL);
8334                 ok(tmp != INVALID_SOCKET, "accept failed %d\n", WSAGetLastError());
8335                 closesocket(tmp);
8336             }
8337             else {
8338                 ok(FALSE, "Got more than 2 connections?\n");
8339             }
8340         }
8341         if ( conn1 && FD_ISSET ( connector2, &fds_opensend ) ) {
8342             /* Send data on second socket, and stop */
8343             send(connector2, "2", 1, 0);
8344             FD_CLR ( connector2, &fds_send );
8345 
8346             break;
8347         }
8348         if ( FD_ISSET ( connector, &fds_opensend ) ) {
8349             /* Once #1 is connected, allow #2 to connect */
8350             conn1 = 1;
8351 
8352             send(connector, "1", 1, 0);
8353             FD_CLR ( connector, &fds_send );
8354 
8355             iret = connect(connector2, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
8356             ok(iret == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK, "connecting to accepting socket failed, error %d\n", WSAGetLastError());
8357             FD_SET ( connector2, &fds_send );
8358         }
8359     }
8360 
8361     ok (got == 2 || broken(got == 1) /* NT4 */,
8362             "Did not get both connections, got %d\n", got);
8363 
8364     dwret = WaitForSingleObject(overlapped.hEvent, 0);
8365     ok(dwret == WAIT_OBJECT_0, "Waiting for accept event failed with %d + errno %d\n", dwret, GetLastError());
8366 
8367     bret = GetOverlappedResult((HANDLE)listener, &overlapped, &bytesReturned, FALSE);
8368     ok(bret, "GetOverlappedResult failed, error %d\n", GetLastError());
8369     ok(bytesReturned == 0, "bytesReturned isn't supposed to be %d\n", bytesReturned);
8370 
8371     set_blocking(acceptor, TRUE);
8372     iret = recv( acceptor, buffer, 2, 0);
8373     ok(iret == 1, "Failed to get data, %d, errno: %d\n", iret, WSAGetLastError());
8374 
8375     ok(buffer[0] == '1', "The wrong first client was accepted by acceptex: %c != 1\n", buffer[0]);
8376 
8377     closesocket(connector);
8378     connector = INVALID_SOCKET;
8379     closesocket(acceptor);
8380 
8381     /* clean up in case of failures */
8382     while ((acceptor = accept(listener, NULL, NULL)) != INVALID_SOCKET)
8383         closesocket(acceptor);
8384 
8385     /* Disconnect during receive? */
8386 
8387     acceptor = socket(AF_INET, SOCK_STREAM, 0);
8388     if (acceptor == INVALID_SOCKET) {
8389         skip("could not create acceptor socket, error %d\n", WSAGetLastError());
8390         goto end;
8391     }
8392     connector = socket(AF_INET, SOCK_STREAM, 0);
8393     if (connector == INVALID_SOCKET) {
8394         skip("could not create connector socket, error %d\n", WSAGetLastError());
8395         goto end;
8396     }
8397     bret = pAcceptEx(listener, acceptor, buffer, sizeof(buffer) - 2*(sizeof(struct sockaddr_in) + 16),
8398         sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
8399         &bytesReturned, &overlapped);
8400     ok(bret == FALSE && WSAGetLastError() == ERROR_IO_PENDING, "AcceptEx returned %d + errno %d\n", bret, WSAGetLastError());
8401 
8402     iret = connect(connector, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
8403     ok(iret == 0, "connecting to accepting socket failed, error %d\n", WSAGetLastError());
8404 
8405     closesocket(connector);
8406     connector = INVALID_SOCKET;
8407 
8408     dwret = WaitForSingleObject(overlapped.hEvent, 1000);
8409     ok(dwret == WAIT_OBJECT_0, "Waiting for accept event failed with %d + errno %d\n", dwret, GetLastError());
8410 
8411     bret = GetOverlappedResult((HANDLE)listener, &overlapped, &bytesReturned, FALSE);
8412     ok(bret, "GetOverlappedResult failed, error %d\n", GetLastError());
8413     ok(bytesReturned == 0, "bytesReturned isn't supposed to be %d\n", bytesReturned);
8414 
8415     closesocket(acceptor);
8416 
8417     /* Test closing with pending requests */
8418 
8419     acceptor = socket(AF_INET, SOCK_STREAM, 0);
8420     if (acceptor == INVALID_SOCKET) {
8421         skip("could not create acceptor socket, error %d\n", WSAGetLastError());
8422         goto end;
8423     }
8424     bret = pAcceptEx(listener, acceptor, buffer, sizeof(buffer) - 2*(sizeof(struct sockaddr_in) + 16),
8425         sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
8426         &bytesReturned, &overlapped);
8427     ok(bret == FALSE && WSAGetLastError() == ERROR_IO_PENDING, "AcceptEx returned %d + errno %d\n", bret, WSAGetLastError());
8428 
8429     closesocket(acceptor);
8430 
8431     dwret = WaitForSingleObject(overlapped.hEvent, 1000);
8432     todo_wine ok(dwret == WAIT_OBJECT_0 || broken(dwret == WAIT_TIMEOUT) /* NT4/2000 */,
8433        "Waiting for accept event failed with %d + errno %d\n", dwret, GetLastError());
8434 
8435     if (dwret != WAIT_TIMEOUT) {
8436         bret = GetOverlappedResult((HANDLE)listener, &overlapped, &bytesReturned, FALSE);
8437         ok(!bret && GetLastError() == ERROR_OPERATION_ABORTED, "GetOverlappedResult failed, error %d\n", GetLastError());
8438     }
8439     else {
8440         bret = CancelIo((HANDLE) listener);
8441         ok(bret, "Failed to cancel failed test. Bailing...\n");
8442         if (!bret) return;
8443         WaitForSingleObject(overlapped.hEvent, 0);
8444     }
8445 
8446     acceptor = socket(AF_INET, SOCK_STREAM, 0);
8447     if (acceptor == INVALID_SOCKET) {
8448         skip("could not create acceptor socket, error %d\n", WSAGetLastError());
8449         goto end;
8450     }
8451     bret = pAcceptEx(listener, acceptor, buffer, sizeof(buffer) - 2*(sizeof(struct sockaddr_in) + 16),
8452         sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
8453         &bytesReturned, &overlapped);
8454     ok(bret == FALSE && WSAGetLastError() == ERROR_IO_PENDING, "AcceptEx returned %d + errno %d\n", bret, WSAGetLastError());
8455 
8456     CancelIo((HANDLE) acceptor);
8457 
8458     dwret = WaitForSingleObject(overlapped.hEvent, 1000);
8459     ok(dwret == WAIT_TIMEOUT, "Waiting for timeout failed with %d + errno %d\n", dwret, GetLastError());
8460 
8461     closesocket(acceptor);
8462 
8463     acceptor = socket(AF_INET, SOCK_STREAM, 0);
8464     if (acceptor == INVALID_SOCKET) {
8465         skip("could not create acceptor socket, error %d\n", WSAGetLastError());
8466         goto end;
8467     }
8468     bret = pAcceptEx(listener, acceptor, buffer, sizeof(buffer) - 2*(sizeof(struct sockaddr_in) + 16),
8469         sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
8470         &bytesReturned, &overlapped);
8471     ok(bret == FALSE && WSAGetLastError() == ERROR_IO_PENDING, "AcceptEx returned %d + errno %d\n", bret, WSAGetLastError());
8472 
8473     closesocket(listener);
8474     listener = INVALID_SOCKET;
8475 
8476     dwret = WaitForSingleObject(overlapped.hEvent, 1000);
8477     ok(dwret == WAIT_OBJECT_0, "Waiting for accept event failed with %d + errno %d\n", dwret, GetLastError());
8478 
8479     bret = GetOverlappedResult((HANDLE)listener, &overlapped, &bytesReturned, FALSE);
8480     ok(!bret && GetLastError() == ERROR_OPERATION_ABORTED, "GetOverlappedResult failed, error %d\n", GetLastError());
8481 
8482 end:
8483     if (overlapped.hEvent)
8484         WSACloseEvent(overlapped.hEvent);
8485     if (listener != INVALID_SOCKET)
8486         closesocket(listener);
8487     if (acceptor != INVALID_SOCKET)
8488         closesocket(acceptor);
8489     if (connector != INVALID_SOCKET)
8490         closesocket(connector);
8491     if (connector2 != INVALID_SOCKET)
8492         closesocket(connector2);
8493 }
8494 
8495 static void test_DisconnectEx(void)
8496 {
8497     SOCKET listener, acceptor, connector;
8498     LPFN_DISCONNECTEX pDisconnectEx;
8499     GUID disconnectExGuid = WSAID_DISCONNECTEX;
8500     struct sockaddr_in address;
8501     DWORD num_bytes, flags;
8502     OVERLAPPED overlapped;
8503     int addrlen, iret;
8504     BOOL bret;
8505 
8506     connector = socket(AF_INET, SOCK_STREAM, 0);
8507     ok(connector != INVALID_SOCKET, "failed to create connector socket, error %d\n", WSAGetLastError());
8508 
8509     iret = WSAIoctl(connector, SIO_GET_EXTENSION_FUNCTION_POINTER, &disconnectExGuid, sizeof(disconnectExGuid),
8510                     &pDisconnectEx, sizeof(pDisconnectEx), &num_bytes, NULL, NULL);
8511     if (iret)
8512     {
8513         win_skip("WSAIoctl failed to get DisconnectEx, error %d\n", WSAGetLastError());
8514         closesocket(connector);
8515         return;
8516     }
8517 
8518     listener = socket(AF_INET, SOCK_STREAM, 0);
8519     ok(listener != INVALID_SOCKET, "failed to create listener socket, error %d\n", WSAGetLastError());
8520 
8521     memset(&address, 0, sizeof(address));
8522     address.sin_family = AF_INET;
8523     address.sin_addr.s_addr = inet_addr("127.0.0.1");
8524     iret = bind(listener, (struct sockaddr *)&address, sizeof(address));
8525     ok(iret == 0, "failed to bind, error %d\n", WSAGetLastError());
8526 
8527     addrlen = sizeof(address);
8528     iret = getsockname(listener, (struct sockaddr *)&address, &addrlen);
8529     ok(iret == 0, "failed to lookup bind address, error %d\n", WSAGetLastError());
8530 
8531     iret = listen(listener, 1);
8532     ok(iret == 0, "failed to listen, error %d\n", WSAGetLastError());
8533 
8534     set_blocking(listener, TRUE);
8535 
8536     memset(&overlapped, 0, sizeof(overlapped));
8537     bret = pDisconnectEx(INVALID_SOCKET, &overlapped, 0, 0);
8538     ok(bret == FALSE, "DisconnectEx unexpectedly succeeded\n");
8539     ok(WSAGetLastError() == WSAENOTSOCK, "expected WSAENOTSOCK, got %d\n", WSAGetLastError());
8540 
8541     memset(&overlapped, 0, sizeof(overlapped));
8542     bret = pDisconnectEx(connector, &overlapped, 0, 0);
8543     ok(bret == FALSE, "DisconnectEx unexpectedly succeeded\n");
8544     todo_wine ok(WSAGetLastError() == WSAENOTCONN, "expected WSAENOTCONN, got %d\n", WSAGetLastError());
8545 
8546     iret = connect(connector, (struct sockaddr *)&address, addrlen);
8547     ok(iret == 0, "failed to connect, error %d\n", WSAGetLastError());
8548 
8549     acceptor = accept(listener, NULL, NULL);
8550     ok(acceptor != INVALID_SOCKET, "could not accept socket, error %d\n", WSAGetLastError());
8551 
8552     memset(&overlapped, 0, sizeof(overlapped));
8553     overlapped.hEvent = WSACreateEvent();
8554     ok(overlapped.hEvent != WSA_INVALID_EVENT, "WSACreateEvent failed, error %d\n", WSAGetLastError());
8555     bret = pDisconnectEx(connector, &overlapped, 0, 0);
8556     if (bret)
8557         ok(overlapped.Internal == STATUS_PENDING, "expected STATUS_PENDING, got %08lx\n", overlapped.Internal);
8558     else if (WSAGetLastError() == ERROR_IO_PENDING)
8559         bret = WSAGetOverlappedResult(connector, &overlapped, &num_bytes, TRUE, &flags);
8560     ok(bret, "DisconnectEx failed, error %d\n", WSAGetLastError());
8561     WSACloseEvent(overlapped.hEvent);
8562 
8563     iret = connect(connector, (struct sockaddr *)&address, sizeof(address));
8564     ok(iret != 0, "connect unexpectedly succeeded\n");
8565     ok(WSAGetLastError() == WSAEISCONN, "expected WSAEISCONN, got %d\n", WSAGetLastError());
8566 
8567     closesocket(acceptor);
8568     closesocket(connector);
8569 
8570     connector = socket(AF_INET, SOCK_STREAM, 0);
8571     ok(connector != INVALID_SOCKET, "failed to create connector socket, error %d\n", WSAGetLastError());
8572 
8573     iret = connect(connector, (struct sockaddr *)&address, addrlen);
8574     ok(iret == 0, "failed to connect, error %d\n", WSAGetLastError());
8575 
8576     acceptor = accept(listener, NULL, NULL);
8577     ok(acceptor != INVALID_SOCKET, "could not accept socket, error %d\n", WSAGetLastError());
8578 
8579     bret = pDisconnectEx(connector, NULL, 0, 0);
8580     ok(bret, "DisconnectEx failed, error %d\n", WSAGetLastError());
8581 
8582     iret = connect(connector, (struct sockaddr *)&address, sizeof(address));
8583     ok(iret != 0, "connect unexpectedly succeeded\n");
8584     ok(WSAGetLastError() == WSAEISCONN, "expected WSAEISCONN, got %d\n", WSAGetLastError());
8585 
8586     closesocket(acceptor);
8587     closesocket(connector);
8588     closesocket(listener);
8589 }
8590 
8591 #define compare_file(h,s,o) compare_file2(h,s,o,__FILE__,__LINE__)
8592 
8593 static void compare_file2(HANDLE handle, SOCKET sock, int offset, const char *file, int line)
8594 {
8595     char buf1[256], buf2[256];
8596     BOOL success;
8597     int i = 0;
8598 
8599     SetFilePointer(handle, offset, NULL, FILE_BEGIN);
8600     while (1)
8601     {
8602         DWORD n1 = 0, n2 = 0;
8603 
8604         success = ReadFile(handle, buf1, sizeof(buf1), &n1, NULL);
8605         ok_(file,line)(success, "Failed to read from file.\n");
8606         if (success && n1 == 0)
8607             break;
8608         else if(!success)
8609             return;
8610         n2 = recv(sock, buf2, n1, 0);
8611         ok_(file,line)(n1 == n2, "Block %d size mismatch (%d != %d)\n", i, n1, n2);
8612         ok_(file,line)(memcmp(buf1, buf2, n2) == 0, "Block %d failed\n", i);
8613         i++;
8614     }
8615 }
8616 
8617 static void test_TransmitFile(void)
8618 {
8619     DWORD num_bytes, err, file_size, total_sent;
8620     GUID transmitFileGuid = WSAID_TRANSMITFILE;
8621     LPFN_TRANSMITFILE pTransmitFile = NULL;
8622     HANDLE file = INVALID_HANDLE_VALUE;
8623     char header_msg[] = "hello world";
8624     char footer_msg[] = "goodbye!!!";
8625     char system_ini_path[MAX_PATH];
8626     struct sockaddr_in bindAddress;
8627     TRANSMIT_FILE_BUFFERS buffers;
8628     SOCKET client, server, dest;
8629     WSAOVERLAPPED ov;
8630     char buf[256];
8631     int iret, len;
8632     BOOL bret;
8633 
8634     memset( &ov, 0, sizeof(ov) );
8635 
8636     /* Setup sockets for testing TransmitFile */
8637     client = socket(AF_INET, SOCK_STREAM, 0);
8638     server = socket(AF_INET, SOCK_STREAM, 0);
8639     if (client == INVALID_SOCKET || server == INVALID_SOCKET)
8640     {
8641         skip("could not create acceptor socket, error %d\n", WSAGetLastError());
8642         goto cleanup;
8643     }
8644     iret = WSAIoctl(client, SIO_GET_EXTENSION_FUNCTION_POINTER, &transmitFileGuid, sizeof(transmitFileGuid),
8645                     &pTransmitFile, sizeof(pTransmitFile), &num_bytes, NULL, NULL);
8646     if (iret)
8647     {
8648         skip("WSAIoctl failed to get TransmitFile with ret %d + errno %d\n", iret, WSAGetLastError());
8649         goto cleanup;
8650     }
8651     GetSystemWindowsDirectoryA(system_ini_path, MAX_PATH );
8652     strcat(system_ini_path, "\\system.ini");
8653     file = CreateFileA(system_ini_path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_ALWAYS, 0x0, NULL);
8654     if (file == INVALID_HANDLE_VALUE)
8655     {
8656         skip("Unable to open a file to transmit.\n");
8657         goto cleanup;
8658     }
8659     file_size = GetFileSize(file, NULL);
8660 
8661     /* Test TransmitFile with an invalid socket */
8662     bret = pTransmitFile(INVALID_SOCKET, file, 0, 0, NULL, NULL, 0);
8663     err = WSAGetLastError();
8664     ok(!bret, "TransmitFile succeeded unexpectedly.\n");
8665     ok(err == WSAENOTSOCK, "TransmitFile triggered unexpected errno (%d != %d)\n", err, WSAENOTSOCK);
8666 
8667     /* Test a bogus TransmitFile without a connected socket */
8668     bret = pTransmitFile(client, NULL, 0, 0, NULL, NULL, TF_REUSE_SOCKET);
8669     err = WSAGetLastError();
8670     ok(!bret, "TransmitFile succeeded unexpectedly.\n");
8671     ok(err == WSAENOTCONN, "TransmitFile triggered unexpected errno (%d != %d)\n", err, WSAENOTCONN);
8672 
8673     /* Setup a properly connected socket for transfers */
8674     memset(&bindAddress, 0, sizeof(bindAddress));
8675     bindAddress.sin_family = AF_INET;
8676     bindAddress.sin_port = htons(SERVERPORT+1);
8677     bindAddress.sin_addr.s_addr = inet_addr("127.0.0.1");
8678     iret = bind(server, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
8679     if (iret != 0)
8680     {
8681         skip("failed to bind(), error %d\n", WSAGetLastError());
8682         goto cleanup;
8683     }
8684     iret = listen(server, 1);
8685     if (iret != 0)
8686     {
8687         skip("failed to listen(), error %d\n", WSAGetLastError());
8688         goto cleanup;
8689     }
8690     iret = connect(client, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
8691     if (iret != 0)
8692     {
8693         skip("failed to connect(), error %d\n", WSAGetLastError());
8694         goto cleanup;
8695     }
8696     len = sizeof(bindAddress);
8697     dest = accept(server, (struct sockaddr*)&bindAddress, &len);
8698     if (dest == INVALID_SOCKET)
8699     {
8700         skip("failed to accept(), error %d\n", WSAGetLastError());
8701         goto cleanup;
8702     }
8703     if (set_blocking(dest, FALSE))
8704     {
8705         skip("couldn't make socket non-blocking, error %d\n", WSAGetLastError());
8706         goto cleanup;
8707     }
8708 
8709     /* Test TransmitFile with no possible buffer */
8710     bret = pTransmitFile(client, NULL, 0, 0, NULL, NULL, 0);
8711     ok(bret, "TransmitFile failed unexpectedly.\n");
8712     iret = recv(dest, buf, sizeof(buf), 0);
8713     ok(iret == -1, "Returned an unexpected buffer from TransmitFile (%d != -1).\n", iret);
8714 
8715     /* Test TransmitFile with only buffer data */
8716     buffers.Head = &header_msg[0];
8717     buffers.HeadLength = sizeof(header_msg);
8718     buffers.Tail = &footer_msg[0];
8719     buffers.TailLength = sizeof(footer_msg);
8720     bret = pTransmitFile(client, NULL, 0, 0, NULL, &buffers, 0);
8721     ok(bret, "TransmitFile failed unexpectedly.\n");
8722     iret = recv(dest, buf, sizeof(buf), 0);
8723     ok(iret == sizeof(header_msg)+sizeof(footer_msg),
8724        "Returned an unexpected buffer from TransmitFile: %d\n", iret );
8725     ok(memcmp(&buf[0], &header_msg[0], sizeof(header_msg)) == 0,
8726        "TransmitFile header buffer did not match!\n");
8727     ok(memcmp(&buf[sizeof(header_msg)], &footer_msg[0], sizeof(footer_msg)) == 0,
8728        "TransmitFile footer buffer did not match!\n");
8729 
8730     /* Test TransmitFile with only file data */
8731     bret = pTransmitFile(client, file, 0, 0, NULL, NULL, 0);
8732     ok(bret, "TransmitFile failed unexpectedly.\n");
8733     compare_file(file, dest, 0);
8734 
8735     /* Test TransmitFile with both file and buffer data */
8736     buffers.Head = &header_msg[0];
8737     buffers.HeadLength = sizeof(header_msg);
8738     buffers.Tail = &footer_msg[0];
8739     buffers.TailLength = sizeof(footer_msg);
8740     SetFilePointer(file, 0, NULL, FILE_BEGIN);
8741     bret = pTransmitFile(client, file, 0, 0, NULL, &buffers, 0);
8742     ok(bret, "TransmitFile failed unexpectedly.\n");
8743     iret = recv(dest, buf, sizeof(header_msg), 0);
8744     ok(memcmp(buf, &header_msg[0], sizeof(header_msg)) == 0,
8745        "TransmitFile header buffer did not match!\n");
8746     compare_file(file, dest, 0);
8747     iret = recv(dest, buf, sizeof(footer_msg), 0);
8748     ok(memcmp(buf, &footer_msg[0], sizeof(footer_msg)) == 0,
8749        "TransmitFile footer buffer did not match!\n");
8750 
8751     /* Test overlapped TransmitFile */
8752     ov.hEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
8753     if (ov.hEvent == INVALID_HANDLE_VALUE)
8754     {
8755         skip("Could not create event object, some tests will be skipped. errno = %d\n",
8756              GetLastError());
8757         goto cleanup;
8758     }
8759     SetFilePointer(file, 0, NULL, FILE_BEGIN);
8760     bret = pTransmitFile(client, file, 0, 0, &ov, NULL, 0);
8761     err = WSAGetLastError();
8762     ok(!bret, "TransmitFile succeeded unexpectedly.\n");
8763     ok(err == ERROR_IO_PENDING, "TransmitFile triggered unexpected errno (%d != %d)\n",
8764        err, ERROR_IO_PENDING);
8765     iret = WaitForSingleObject(ov.hEvent, 2000);
8766     ok(iret == WAIT_OBJECT_0, "Overlapped TransmitFile failed.\n");
8767     WSAGetOverlappedResult(client, &ov, &total_sent, FALSE, NULL);
8768     ok(total_sent == file_size,
8769        "Overlapped TransmitFile sent an unexpected number of bytes (%d != %d).\n",
8770        total_sent, file_size);
8771     compare_file(file, dest, 0);
8772 
8773     /* Test overlapped TransmitFile w/ start offset */
8774     ov.hEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
8775     if (ov.hEvent == INVALID_HANDLE_VALUE)
8776     {
8777         skip("Could not create event object, some tests will be skipped. errno = %d\n", GetLastError());
8778         goto cleanup;
8779     }
8780     SetFilePointer(file, 0, NULL, FILE_BEGIN);
8781     ov.Offset = 10;
8782     bret = pTransmitFile(client, file, 0, 0, &ov, NULL, 0);
8783     err = WSAGetLastError();
8784     ok(!bret, "TransmitFile succeeded unexpectedly.\n");
8785     ok(err == ERROR_IO_PENDING, "TransmitFile triggered unexpected errno (%d != %d)\n", err, ERROR_IO_PENDING);
8786     iret = WaitForSingleObject(ov.hEvent, 2000);
8787     ok(iret == WAIT_OBJECT_0, "Overlapped TransmitFile failed.\n");
8788     WSAGetOverlappedResult(client, &ov, &total_sent, FALSE, NULL);
8789     ok(total_sent == (file_size - ov.Offset),
8790        "Overlapped TransmitFile sent an unexpected number of bytes (%d != %d).\n",
8791        total_sent, file_size - ov.Offset);
8792     compare_file(file, dest, ov.Offset);
8793 
8794     /* Test overlapped TransmitFile w/ file and buffer data */
8795     ov.hEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
8796     if (ov.hEvent == INVALID_HANDLE_VALUE)
8797     {
8798         skip("Could not create event object, some tests will be skipped. errno = %d\n", GetLastError());
8799         goto cleanup;
8800     }
8801     buffers.Head = &header_msg[0];
8802     buffers.HeadLength = sizeof(header_msg);
8803     buffers.Tail = &footer_msg[0];
8804     buffers.TailLength = sizeof(footer_msg);
8805     SetFilePointer(file, 0, NULL, FILE_BEGIN);
8806     ov.Offset = 0;
8807     bret = pTransmitFile(client, file, 0, 0, &ov, &buffers, 0);
8808     err = WSAGetLastError();
8809     ok(!bret, "TransmitFile succeeded unexpectedly.\n");
8810     ok(err == ERROR_IO_PENDING, "TransmitFile triggered unexpected errno (%d != %d)\n", err, ERROR_IO_PENDING);
8811     iret = WaitForSingleObject(ov.hEvent, 2000);
8812     ok(iret == WAIT_OBJECT_0, "Overlapped TransmitFile failed.\n");
8813     WSAGetOverlappedResult(client, &ov, &total_sent, FALSE, NULL);
8814     ok(total_sent == (file_size + buffers.HeadLength + buffers.TailLength),
8815        "Overlapped TransmitFile sent an unexpected number of bytes (%d != %d).\n",
8816        total_sent, file_size  + buffers.HeadLength + buffers.TailLength);
8817     iret = recv(dest, buf, sizeof(header_msg), 0);
8818     ok(memcmp(buf, &header_msg[0], sizeof(header_msg)) == 0,
8819        "TransmitFile header buffer did not match!\n");
8820     compare_file(file, dest, 0);
8821     iret = recv(dest, buf, sizeof(footer_msg), 0);
8822     ok(memcmp(buf, &footer_msg[0], sizeof(footer_msg)) == 0,
8823        "TransmitFile footer buffer did not match!\n");
8824 
8825     /* Test TransmitFile w/ TF_DISCONNECT */
8826     SetFilePointer(file, 0, NULL, FILE_BEGIN);
8827     bret = pTransmitFile(client, file, 0, 0, NULL, NULL, TF_DISCONNECT);
8828     ok(bret, "TransmitFile failed unexpectedly.\n");
8829     compare_file(file, dest, 0);
8830     closesocket(client);
8831     ok(send(client, "test", 4, 0) == -1, "send() after TF_DISCONNECT succeeded unexpectedly.\n");
8832     err = WSAGetLastError();
8833     todo_wine ok(err == WSAENOTSOCK, "send() after TF_DISCONNECT triggered unexpected errno (%d != %d)\n",
8834                  err, WSAENOTSOCK);
8835 
8836     /* Test TransmitFile with a UDP datagram socket */
8837     client = socket(AF_INET, SOCK_DGRAM, 0);
8838     bret = pTransmitFile(client, NULL, 0, 0, NULL, NULL, 0);
8839     err = WSAGetLastError();
8840     ok(!bret, "TransmitFile succeeded unexpectedly.\n");
8841     ok(err == WSAENOTCONN, "TransmitFile triggered unexpected errno (%d != %d)\n", err, WSAENOTCONN);
8842 
8843 cleanup:
8844     CloseHandle(file);
8845     CloseHandle(ov.hEvent);
8846     closesocket(client);
8847     closesocket(server);
8848 }
8849 
8850 static void test_getpeername(void)
8851 {
8852     SOCKET sock;
8853     struct sockaddr_in sa, sa_out;
8854     SOCKADDR_STORAGE ss;
8855     int sa_len;
8856     const char buf[] = "hello world";
8857     int ret;
8858 
8859     /* Test the parameter validation order. */
8860     ret = getpeername(INVALID_SOCKET, NULL, NULL);
8861     ok(ret == SOCKET_ERROR, "Expected getpeername to return SOCKET_ERROR, got %d\n", ret);
8862     ok(WSAGetLastError() == WSAENOTSOCK,
8863        "Expected WSAGetLastError() to return WSAENOTSOCK, got %d\n", WSAGetLastError());
8864 
8865     sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
8866     ok(sock != INVALID_SOCKET, "Expected socket to return a valid socket\n");
8867     if (sock == INVALID_SOCKET)
8868     {
8869         skip("Socket creation failed with %d\n", WSAGetLastError());
8870         return;
8871     }
8872 
8873     ret = getpeername(sock, NULL, NULL);
8874     ok(ret == SOCKET_ERROR, "Expected getpeername to return SOCKET_ERROR, got %d\n", ret);
8875     ok(WSAGetLastError() == WSAENOTCONN ||
8876        broken(WSAGetLastError() == WSAEFAULT), /* Win9x and WinMe */
8877        "Expected WSAGetLastError() to return WSAENOTCONN, got %d\n", WSAGetLastError());
8878 
8879     memset(&sa, 0, sizeof(sa));
8880     sa.sin_family = AF_INET;
8881     sa.sin_port = htons(139);
8882     sa.sin_addr.s_addr = inet_addr("127.0.0.1");
8883 
8884     /* sendto does not change a socket's connection state. */
8885     ret = sendto(sock, buf, sizeof(buf), 0, (struct sockaddr*)&sa, sizeof(sa));
8886     ok(ret != SOCKET_ERROR,
8887        "Expected sendto to succeed, WSAGetLastError() = %d\n", WSAGetLastError());
8888 
8889     ret = getpeername(sock, NULL, NULL);
8890     ok(ret == SOCKET_ERROR, "Expected getpeername to return SOCKET_ERROR, got %d\n", ret);
8891     ok(WSAGetLastError() == WSAENOTCONN ||
8892        broken(WSAGetLastError() == WSAEFAULT), /* Win9x and WinMe */
8893        "Expected WSAGetLastError() to return WSAENOTCONN, got %d\n", WSAGetLastError());
8894 
8895     ret = connect(sock, (struct sockaddr*)&sa, sizeof(sa));
8896     ok(ret == 0,
8897        "Expected connect to succeed, WSAGetLastError() = %d\n", WSAGetLastError());
8898 
8899     ret = getpeername(sock, NULL, NULL);
8900     ok(ret == SOCKET_ERROR, "Expected getpeername to return SOCKET_ERROR, got %d\n", ret);
8901     ok(WSAGetLastError() == WSAEFAULT,
8902        "Expected WSAGetLastError() to return WSAEFAULT, got %d\n", WSAGetLastError());
8903 
8904     /* Test crashes on Wine. */
8905     if (0)
8906     {
8907         ret = getpeername(sock, (void*)0xdeadbeef, (void*)0xcafebabe);
8908         ok(ret == SOCKET_ERROR, "Expected getpeername to return SOCKET_ERROR, got %d\n", ret);
8909         ok(WSAGetLastError() == WSAEFAULT,
8910            "Expected WSAGetLastError() to return WSAEFAULT, got %d\n", WSAGetLastError());
8911     }
8912 
8913     ret = getpeername(sock, (struct sockaddr*)&sa_out, NULL);
8914     ok(ret == SOCKET_ERROR, "Expected getpeername to return 0, got %d\n", ret);
8915     ok(WSAGetLastError() == WSAEFAULT,
8916        "Expected WSAGetLastError() to return WSAEFAULT, got %d\n", WSAGetLastError());
8917 
8918     sa_len = 0;
8919     ret = getpeername(sock, NULL, &sa_len);
8920     ok(ret == SOCKET_ERROR, "Expected getpeername to return 0, got %d\n", ret);
8921     ok(WSAGetLastError() == WSAEFAULT,
8922        "Expected WSAGetLastError() to return WSAEFAULT, got %d\n", WSAGetLastError());
8923     ok(!sa_len, "got %d\n", sa_len);
8924 
8925     sa_len = 0;
8926     ret = getpeername(sock, (struct sockaddr *)&ss, &sa_len);
8927     ok(ret == SOCKET_ERROR, "Expected getpeername to return 0, got %d\n", ret);
8928     ok(WSAGetLastError() == WSAEFAULT,
8929        "Expected WSAGetLastError() to return WSAEFAULT, got %d\n", WSAGetLastError());
8930     ok(!sa_len, "got %d\n", sa_len);
8931 
8932     sa_len = sizeof(ss);
8933     ret = getpeername(sock, (struct sockaddr *)&ss, &sa_len);
8934     ok(ret == 0, "Expected getpeername to return 0, got %d\n", ret);
8935     ok(!memcmp(&sa, &ss, sizeof(sa)),
8936        "Expected the returned structure to be identical to the connect structure\n");
8937     ok(sa_len == sizeof(sa), "got %d\n", sa_len);
8938 
8939     closesocket(sock);
8940 }
8941 
8942 static void test_sioRoutingInterfaceQuery(void)
8943 {
8944     int ret;
8945     SOCKET sock;
8946     SOCKADDR_IN sin = { 0 }, sout = { 0 };
8947     DWORD bytesReturned;
8948 
8949     sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
8950     ok(sock != INVALID_SOCKET, "Expected socket to return a valid socket\n");
8951     if (sock == INVALID_SOCKET)
8952     {
8953         skip("Socket creation failed with %d\n", WSAGetLastError());
8954         return;
8955     }
8956     ret = WSAIoctl(sock, SIO_ROUTING_INTERFACE_QUERY, NULL, 0, NULL, 0, NULL,
8957                    NULL, NULL);
8958     ok(ret == SOCKET_ERROR && WSAGetLastError() == WSAEFAULT,
8959        "expected WSAEFAULT, got %d\n", WSAGetLastError());
8960     ret = WSAIoctl(sock, SIO_ROUTING_INTERFACE_QUERY, &sin, sizeof(sin),
8961                    NULL, 0, NULL, NULL, NULL);
8962     ok(ret == SOCKET_ERROR && WSAGetLastError() == WSAEFAULT,
8963        "expected WSAEFAULT, got %d\n", WSAGetLastError());
8964     ret = WSAIoctl(sock, SIO_ROUTING_INTERFACE_QUERY, &sin, sizeof(sin),
8965                    NULL, 0, &bytesReturned, NULL, NULL);
8966     ok(ret == SOCKET_ERROR &&
8967        (WSAGetLastError() == WSAEFAULT /* Win98 */ ||
8968         WSAGetLastError() == WSAEINVAL /* NT4 */||
8969         WSAGetLastError() == WSAEAFNOSUPPORT),
8970        "expected WSAEFAULT or WSAEINVAL or WSAEAFNOSUPPORT, got %d\n",
8971        WSAGetLastError());
8972     sin.sin_family = AF_INET;
8973     ret = WSAIoctl(sock, SIO_ROUTING_INTERFACE_QUERY, &sin, sizeof(sin),
8974                    NULL, 0, &bytesReturned, NULL, NULL);
8975     ok(ret == SOCKET_ERROR &&
8976        (WSAGetLastError() == WSAEFAULT /* Win98 */ ||
8977         WSAGetLastError() == WSAEINVAL),
8978        "expected WSAEFAULT or WSAEINVAL, got %d\n", WSAGetLastError());
8979     sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
8980     ret = WSAIoctl(sock, SIO_ROUTING_INTERFACE_QUERY, &sin, sizeof(sin),
8981                    NULL, 0, &bytesReturned, NULL, NULL);
8982     ok(ret == SOCKET_ERROR &&
8983        (WSAGetLastError() == WSAEINVAL /* NT4 */ ||
8984         WSAGetLastError() == WSAEFAULT),
8985        "expected WSAEINVAL or WSAEFAULT, got %d\n", WSAGetLastError());
8986     ret = WSAIoctl(sock, SIO_ROUTING_INTERFACE_QUERY, &sin, sizeof(sin),
8987                    &sout, sizeof(sout), &bytesReturned, NULL, NULL);
8988     ok(!ret || broken(WSAGetLastError() == WSAEINVAL /* NT4 */),
8989        "WSAIoctl failed: %d\n", WSAGetLastError());
8990     if (!ret)
8991     {
8992         ok(sout.sin_family == AF_INET, "expected AF_INET, got %d\n",
8993            sout.sin_family);
8994         /* We expect the source address to be INADDR_LOOPBACK as well, but
8995          * there's no guarantee that a route to the loopback address exists,
8996          * so rather than introduce spurious test failures we do not test the
8997          * source address.
8998          */
8999     }
9000     closesocket(sock);
9001 }
9002 
9003 static void test_sioAddressListChange(void)
9004 {
9005     struct sockaddr_in bindAddress;
9006     struct in_addr net_address;
9007     WSAOVERLAPPED overlapped, *olp;
9008     struct hostent *h;
9009     DWORD num_bytes, error, tick;
9010     SOCKET sock, sock2, sock3;
9011     WSAEVENT event2, event3;
9012     HANDLE io_port;
9013     ULONG_PTR key;
9014     int acount;
9015     BOOL bret;
9016     int ret;
9017 
9018     /* Use gethostbyname to find the list of local network interfaces */
9019     h = gethostbyname("");
9020     if (!h)
9021     {
9022         skip("Cannot test SIO_ADDRESS_LIST_CHANGE, gethostbyname failed with %u\n",
9023              WSAGetLastError());
9024         return;
9025     }
9026     for (acount = 0; h->h_addr_list[acount]; acount++);
9027     if (acount == 0)
9028     {
9029         skip("Cannot test SIO_ADDRESS_LIST_CHANGE, test requires a network card.\n");
9030         return;
9031     }
9032 
9033     net_address.s_addr = *(ULONG *) h->h_addr_list[0];
9034 
9035     sock = socket(AF_INET, 0, IPPROTO_TCP);
9036     ok(sock != INVALID_SOCKET, "socket() failed\n");
9037 
9038     memset(&bindAddress, 0, sizeof(bindAddress));
9039     bindAddress.sin_family = AF_INET;
9040     bindAddress.sin_addr.s_addr = net_address.s_addr;
9041     SetLastError(0xdeadbeef);
9042     ret = bind(sock, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
9043     ok (!ret, "bind() failed with error %d\n", GetLastError());
9044     set_blocking(sock, FALSE);
9045 
9046     memset(&overlapped, 0, sizeof(overlapped));
9047     overlapped.hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
9048     SetLastError(0xdeadbeef);
9049     ret = WSAIoctl(sock, SIO_ADDRESS_LIST_CHANGE, NULL, 0, NULL, 0, &num_bytes, &overlapped, NULL);
9050     error = GetLastError();
9051     ok (ret == SOCKET_ERROR, "WSAIoctl(SIO_ADDRESS_LIST_CHANGE) failed with error %d\n", error);
9052     ok (error == ERROR_IO_PENDING, "expected 0x3e5, got 0x%x\n", error);
9053 
9054     CloseHandle(overlapped.hEvent);
9055     closesocket(sock);
9056 
9057     sock = socket(AF_INET, 0, IPPROTO_TCP);
9058     ok(sock != INVALID_SOCKET, "socket() failed\n");
9059 
9060     SetLastError(0xdeadbeef);
9061     ret = bind(sock, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
9062     ok (!ret, "bind() failed with error %d\n", GetLastError());
9063     set_blocking(sock, TRUE);
9064 
9065     memset(&overlapped, 0, sizeof(overlapped));
9066     overlapped.hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
9067     SetLastError(0xdeadbeef);
9068     ret = WSAIoctl(sock, SIO_ADDRESS_LIST_CHANGE, NULL, 0, NULL, 0, &num_bytes, &overlapped, NULL);
9069     error = GetLastError();
9070     ok (ret == SOCKET_ERROR, "WSAIoctl(SIO_ADDRESS_LIST_CHANGE) failed with error %d\n", error);
9071     ok (error == ERROR_IO_PENDING, "expected 0x3e5, got 0x%x\n", error);
9072 
9073     CloseHandle(overlapped.hEvent);
9074     closesocket(sock);
9075 
9076     sock = WSASocketW(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
9077     ok(sock != INVALID_SOCKET, "socket() failed\n");
9078 
9079     SetLastError(0xdeadbeef);
9080     ret = bind(sock, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
9081     ok (!ret, "bind() failed with error %d\n", GetLastError());
9082     set_blocking(sock, FALSE);
9083 
9084     memset(&overlapped, 0, sizeof(overlapped));
9085     overlapped.hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
9086     SetLastError(0xdeadbeef);
9087     ret = WSAIoctl(sock, SIO_ADDRESS_LIST_CHANGE, NULL, 0, NULL, 0, &num_bytes, &overlapped, NULL);
9088     error = GetLastError();
9089     ok (ret == SOCKET_ERROR, "WSAIoctl(SIO_ADDRESS_LIST_CHANGE) failed with error %d\n", error);
9090     ok (error == ERROR_IO_PENDING, "expected 0x3e5, got 0x%x\n", error);
9091 
9092     CloseHandle(overlapped.hEvent);
9093     closesocket(sock);
9094 
9095     sock = WSASocketW(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
9096     ok(sock != INVALID_SOCKET, "socket() failed\n");
9097 
9098     SetLastError(0xdeadbeef);
9099     ret = bind(sock, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
9100     ok (!ret, "bind() failed with error %d\n", GetLastError());
9101     set_blocking(sock, TRUE);
9102 
9103     memset(&overlapped, 0, sizeof(overlapped));
9104     overlapped.hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
9105     SetLastError(0xdeadbeef);
9106     ret = WSAIoctl(sock, SIO_ADDRESS_LIST_CHANGE, NULL, 0, NULL, 0, &num_bytes, &overlapped, NULL);
9107     error = GetLastError();
9108     ok (ret == SOCKET_ERROR, "WSAIoctl(SIO_ADDRESS_LIST_CHANGE) failed with error %d\n", error);
9109     ok (error == ERROR_IO_PENDING, "expected 0x3e5, got 0x%x\n", error);
9110 
9111     CloseHandle(overlapped.hEvent);
9112     closesocket(sock);
9113 
9114     /* When the socket is overlapped non-blocking and the list change is requested without
9115      * an overlapped structure the error will be different. */
9116     sock = WSASocketW(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
9117     ok(sock != INVALID_SOCKET, "socket() failed\n");
9118 
9119     SetLastError(0xdeadbeef);
9120     ret = bind(sock, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
9121     ok (!ret, "bind() failed with error %d\n", GetLastError());
9122     set_blocking(sock, FALSE);
9123 
9124     SetLastError(0xdeadbeef);
9125     ret = WSAIoctl(sock, SIO_ADDRESS_LIST_CHANGE, NULL, 0, NULL, 0, &num_bytes, NULL, NULL);
9126     error = GetLastError();
9127     ok (ret == SOCKET_ERROR, "WSAIoctl(SIO_ADDRESS_LIST_CHANGE) failed with error %d\n", error);
9128     ok (error == WSAEWOULDBLOCK, "expected 10035, got %d\n", error);
9129 
9130     io_port = CreateIoCompletionPort( (HANDLE)sock, NULL, 0, 0 );
9131     ok (io_port != NULL, "failed to create completion port %u\n", GetLastError());
9132 
9133     set_blocking(sock, FALSE);
9134     memset(&overlapped, 0, sizeof(overlapped));
9135     SetLastError(0xdeadbeef);
9136     ret = WSAIoctl(sock, SIO_ADDRESS_LIST_CHANGE, NULL, 0, NULL, 0, &num_bytes, &overlapped, NULL);
9137     error = GetLastError();
9138     ok (ret == SOCKET_ERROR, "WSAIoctl(SIO_ADDRESS_LIST_CHANGE) failed with error %u\n", error);
9139     ok (error == ERROR_IO_PENDING, "expected ERROR_IO_PENDING got %u\n", error);
9140 
9141     olp = (WSAOVERLAPPED *)0xdeadbeef;
9142     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 0 );
9143     ok(!bret, "failed to get completion status %u\n", bret);
9144     ok(GetLastError() == WAIT_TIMEOUT, "Last error was %d\n", GetLastError());
9145     ok(!olp, "Overlapped structure is at %p\n", olp);
9146 
9147     closesocket(sock);
9148 
9149     olp = (WSAOVERLAPPED *)0xdeadbeef;
9150     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 0 );
9151     ok(!bret, "failed to get completion status %u\n", bret);
9152     ok(GetLastError() == ERROR_OPERATION_ABORTED, "Last error was %u\n", GetLastError());
9153     ok(olp == &overlapped, "Overlapped structure is at %p\n", olp);
9154 
9155     CloseHandle(io_port);
9156 
9157     /* Misuse of the API by using a blocking socket and not using an overlapped structure,
9158      * this leads to a hang forever. */
9159     if (0)
9160     {
9161         sock = WSASocketW(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
9162 
9163         SetLastError(0xdeadbeef);
9164         bind(sock, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
9165 
9166         set_blocking(sock, TRUE);
9167         WSAIoctl(sock, SIO_ADDRESS_LIST_CHANGE, NULL, 0, NULL, 0, &num_bytes, NULL, NULL);
9168         /* hang */
9169 
9170         closesocket(sock);
9171     }
9172 
9173     if (!winetest_interactive)
9174     {
9175         skip("Cannot test SIO_ADDRESS_LIST_CHANGE, interactive tests must be enabled\n");
9176         return;
9177     }
9178 
9179     /* Bind an overlapped socket to the first found network interface */
9180     sock = WSASocketW(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
9181     ok(sock != INVALID_SOCKET, "Expected socket to return a valid socket\n");
9182     sock2 = WSASocketW(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
9183     ok(sock2 != INVALID_SOCKET, "Expected socket to return a valid socket\n");
9184     sock3 = WSASocketW(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
9185     ok(sock3 != INVALID_SOCKET, "Expected socket to return a valid socket\n");
9186 
9187     ret = bind(sock, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
9188     ok(!ret, "bind failed unexpectedly\n");
9189     ret = bind(sock2, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
9190     ok(!ret, "bind failed unexpectedly\n");
9191     ret = bind(sock3, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
9192     ok(!ret, "bind failed unexpectedly\n");
9193 
9194     set_blocking(sock2, FALSE);
9195     set_blocking(sock3, FALSE);
9196 
9197     /* Wait for address changes, request that the user connects/disconnects an interface */
9198     memset(&overlapped, 0, sizeof(overlapped));
9199     overlapped.hEvent = CreateEventA(NULL, FALSE, FALSE, NULL);
9200     ret = WSAIoctl(sock, SIO_ADDRESS_LIST_CHANGE, NULL, 0, NULL, 0, &num_bytes, &overlapped, NULL);
9201     ok(ret == SOCKET_ERROR, "WSAIoctl succeeded unexpectedly\n");
9202     ok(WSAGetLastError() == WSA_IO_PENDING, "Expected pending last error, got %d\n", WSAGetLastError());
9203 
9204     ret = WSAIoctl(sock2, SIO_ADDRESS_LIST_CHANGE, NULL, 0, NULL, 0, &num_bytes, NULL, NULL);
9205     ok(ret == SOCKET_ERROR, "WSAIoctl succeeded unexpectedly\n");
9206     ok(WSAGetLastError() == WSAEWOULDBLOCK, "Expected would block last error, got %d\n", WSAGetLastError());
9207 
9208     event2 = WSACreateEvent();
9209     event3 = WSACreateEvent();
9210     ret = WSAEventSelect (sock2, event2, FD_ADDRESS_LIST_CHANGE);
9211     ok(!ret, "WSAEventSelect failed with %d\n", WSAGetLastError());
9212     /* sock3 did not request SIO_ADDRESS_LIST_CHANGE but it is trying to wait anyway */
9213     ret = WSAEventSelect (sock3, event3, FD_ADDRESS_LIST_CHANGE);
9214     ok(!ret, "WSAEventSelect failed with %d\n", WSAGetLastError());
9215 
9216     trace("Testing socket-based ipv4 address list change notification. Please connect/disconnect or"
9217           " change the ipv4 address of any of the local network interfaces (15 second timeout).\n");
9218     tick = GetTickCount();
9219     ret = WaitForSingleObject(overlapped.hEvent, 15000);
9220     ok(ret == WAIT_OBJECT_0, "failed to get overlapped event %u\n", ret);
9221 
9222     ret = WaitForSingleObject(event2, 500);
9223 todo_wine
9224     ok(ret == WAIT_OBJECT_0, "failed to get change event %u\n", ret);
9225 
9226     ret = WaitForSingleObject(event3, 500);
9227     ok(ret == WAIT_TIMEOUT, "unexpected change event\n");
9228 
9229     trace("Spent %d ms waiting.\n", GetTickCount() - tick);
9230 
9231     WSACloseEvent(event2);
9232     WSACloseEvent(event3);
9233 
9234     closesocket(sock);
9235     closesocket(sock2);
9236     closesocket(sock3);
9237 }
9238 
9239 static void test_synchronous_WSAIoctl(void)
9240 {
9241     HANDLE previous_port, io_port;
9242     WSAOVERLAPPED overlapped, *olp;
9243     SOCKET socket;
9244     ULONG on;
9245     ULONG_PTR key;
9246     DWORD num_bytes;
9247     BOOL ret;
9248     int res;
9249 
9250     previous_port = CreateIoCompletionPort( INVALID_HANDLE_VALUE, NULL, 0, 0 );
9251     ok( previous_port != NULL, "failed to create completion port %u\n", GetLastError() );
9252 
9253     socket = WSASocketW( AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED );
9254     ok( socket != INVALID_SOCKET, "failed to create socket %d\n", WSAGetLastError() );
9255 
9256     io_port = CreateIoCompletionPort( (HANDLE)socket, previous_port, 0, 0 );
9257     ok( io_port != NULL, "failed to create completion port %u\n", GetLastError() );
9258 
9259     on = 1;
9260     memset( &overlapped, 0, sizeof(overlapped) );
9261     res = WSAIoctl( socket, FIONBIO, &on, sizeof(on), NULL, 0, &num_bytes, &overlapped, NULL );
9262     ok( !res, "WSAIoctl failed %d\n", WSAGetLastError() );
9263 
9264     ret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 10000 );
9265     ok( ret, "failed to get completion status %u\n", GetLastError() );
9266 
9267     CloseHandle( io_port );
9268     closesocket( socket );
9269     CloseHandle( previous_port );
9270 }
9271 
9272 #define WM_ASYNCCOMPLETE (WM_USER + 100)
9273 static HWND create_async_message_window(void)
9274 {
9275     static const char class_name[] = "ws2_32 async message window class";
9276 
9277     WNDCLASSEXA wndclass;
9278     HWND hWnd;
9279 
9280     wndclass.cbSize         = sizeof(wndclass);
9281     wndclass.style          = CS_HREDRAW | CS_VREDRAW;
9282     wndclass.lpfnWndProc    = DefWindowProcA;
9283     wndclass.cbClsExtra     = 0;
9284     wndclass.cbWndExtra     = 0;
9285     wndclass.hInstance      = GetModuleHandleA(NULL);
9286     wndclass.hIcon          = LoadIconA(NULL, (LPCSTR)IDI_APPLICATION);
9287     wndclass.hIconSm        = LoadIconA(NULL, (LPCSTR)IDI_APPLICATION);
9288     wndclass.hCursor        = LoadCursorA(NULL, (LPCSTR)IDC_ARROW);
9289     wndclass.hbrBackground  = (HBRUSH)(COLOR_WINDOW + 1);
9290     wndclass.lpszClassName  = class_name;
9291     wndclass.lpszMenuName   = NULL;
9292 
9293     RegisterClassExA(&wndclass);
9294 
9295     hWnd = CreateWindowA(class_name, "ws2_32 async message window", WS_OVERLAPPEDWINDOW,
9296                         0, 0, 500, 500, NULL, NULL, GetModuleHandleA(NULL), NULL);
9297     if (!hWnd)
9298     {
9299         ok(0, "failed to create window: %u\n", GetLastError());
9300         return NULL;
9301     }
9302 
9303     return hWnd;
9304 }
9305 
9306 static void wait_for_async_message(HWND hwnd, HANDLE handle)
9307 {
9308     BOOL ret;
9309     MSG msg;
9310 
9311     while ((ret = GetMessageA(&msg, 0, 0, 0)) &&
9312            !(msg.hwnd == hwnd && msg.message == WM_ASYNCCOMPLETE))
9313     {
9314         TranslateMessage(&msg);
9315         DispatchMessageA(&msg);
9316     }
9317 
9318     ok(ret, "did not expect WM_QUIT message\n");
9319     ok(msg.wParam == (WPARAM)handle, "expected wParam = %p, got %lx\n", handle, msg.wParam);
9320 }
9321 
9322 static void test_WSAAsyncGetServByPort(void)
9323 {
9324     HWND hwnd = create_async_message_window();
9325     HANDLE ret;
9326     char buffer[MAXGETHOSTSTRUCT];
9327 
9328     if (!hwnd)
9329         return;
9330 
9331     /* FIXME: The asynchronous window messages should be tested. */
9332 
9333     /* Parameters are not checked when initiating the asynchronous operation.  */
9334     ret = WSAAsyncGetServByPort(NULL, 0, 0, NULL, NULL, 0);
9335     ok(ret != NULL, "WSAAsyncGetServByPort returned NULL\n");
9336 
9337     ret = WSAAsyncGetServByPort(hwnd, WM_ASYNCCOMPLETE, 0, NULL, NULL, 0);
9338     ok(ret != NULL, "WSAAsyncGetServByPort returned NULL\n");
9339     wait_for_async_message(hwnd, ret);
9340 
9341     ret = WSAAsyncGetServByPort(hwnd, WM_ASYNCCOMPLETE, htons(80), NULL, NULL, 0);
9342     ok(ret != NULL, "WSAAsyncGetServByPort returned NULL\n");
9343     wait_for_async_message(hwnd, ret);
9344 
9345     ret = WSAAsyncGetServByPort(hwnd, WM_ASYNCCOMPLETE, htons(80), NULL, buffer, MAXGETHOSTSTRUCT);
9346     ok(ret != NULL, "WSAAsyncGetServByPort returned NULL\n");
9347     wait_for_async_message(hwnd, ret);
9348 
9349     DestroyWindow(hwnd);
9350 }
9351 
9352 static void test_WSAAsyncGetServByName(void)
9353 {
9354     HWND hwnd = create_async_message_window();
9355     HANDLE ret;
9356     char buffer[MAXGETHOSTSTRUCT];
9357 
9358     if (!hwnd)
9359         return;
9360 
9361     /* FIXME: The asynchronous window messages should be tested. */
9362 
9363     /* Parameters are not checked when initiating the asynchronous operation.  */
9364     ret = WSAAsyncGetServByName(hwnd, WM_ASYNCCOMPLETE, "", NULL, NULL, 0);
9365     ok(ret != NULL, "WSAAsyncGetServByName returned NULL\n");
9366     wait_for_async_message(hwnd, ret);
9367 
9368     ret = WSAAsyncGetServByName(hwnd, WM_ASYNCCOMPLETE, "", "", buffer, MAXGETHOSTSTRUCT);
9369     ok(ret != NULL, "WSAAsyncGetServByName returned NULL\n");
9370     wait_for_async_message(hwnd, ret);
9371 
9372     ret = WSAAsyncGetServByName(hwnd, WM_ASYNCCOMPLETE, "http", NULL, NULL, 0);
9373     ok(ret != NULL, "WSAAsyncGetServByName returned NULL\n");
9374     wait_for_async_message(hwnd, ret);
9375 
9376     ret = WSAAsyncGetServByName(hwnd, WM_ASYNCCOMPLETE, "http", "tcp", buffer, MAXGETHOSTSTRUCT);
9377     ok(ret != NULL, "WSAAsyncGetServByName returned NULL\n");
9378     wait_for_async_message(hwnd, ret);
9379 
9380     DestroyWindow(hwnd);
9381 }
9382 
9383 /*
9384  * Provide consistent initialization for the AcceptEx IOCP tests.
9385  */
9386 static SOCKET setup_iocp_src(struct sockaddr_in *bindAddress)
9387 {
9388     SOCKET src, ret = INVALID_SOCKET;
9389     int iret, socklen;
9390 
9391     src = socket(AF_INET, SOCK_STREAM, 0);
9392     if (src == INVALID_SOCKET)
9393     {
9394         skip("could not create listener socket, error %d\n", WSAGetLastError());
9395         goto end;
9396     }
9397 
9398     memset(bindAddress, 0, sizeof(*bindAddress));
9399     bindAddress->sin_family = AF_INET;
9400     bindAddress->sin_addr.s_addr = inet_addr("127.0.0.1");
9401     iret = bind(src, (struct sockaddr*)bindAddress, sizeof(*bindAddress));
9402     if (iret != 0)
9403     {
9404         skip("failed to bind, error %d\n", WSAGetLastError());
9405         goto end;
9406     }
9407 
9408     socklen = sizeof(*bindAddress);
9409     iret = getsockname(src, (struct sockaddr*)bindAddress, &socklen);
9410     if (iret != 0) {
9411         skip("failed to lookup bind address, error %d\n", WSAGetLastError());
9412         goto end;
9413     }
9414 
9415     if (set_blocking(src, FALSE))
9416     {
9417         skip("couldn't make socket non-blocking, error %d\n", WSAGetLastError());
9418         goto end;
9419     }
9420 
9421     iret = listen(src, 5);
9422     if (iret != 0)
9423     {
9424         skip("listening failed, errno = %d\n", WSAGetLastError());
9425         goto end;
9426     }
9427 
9428     ret = src;
9429 end:
9430     if (src != ret && ret == INVALID_SOCKET)
9431         closesocket(src);
9432     return ret;
9433 }
9434 
9435 static void test_completion_port(void)
9436 {
9437     FILE_IO_COMPLETION_NOTIFICATION_INFORMATION io_info;
9438     HANDLE previous_port, io_port;
9439     WSAOVERLAPPED ov, *olp;
9440     SOCKET src, dest, dup, connector = INVALID_SOCKET;
9441     WSAPROTOCOL_INFOA info;
9442     IO_STATUS_BLOCK io;
9443     NTSTATUS status;
9444     char buf[1024];
9445     WSABUF bufs;
9446     DWORD num_bytes, flags;
9447     struct linger ling;
9448     int iret;
9449     BOOL bret;
9450     ULONG_PTR key;
9451     struct sockaddr_in bindAddress;
9452     GUID acceptExGuid = WSAID_ACCEPTEX;
9453     LPFN_ACCEPTEX pAcceptEx = NULL;
9454     fd_set fds_recv;
9455 
9456     memset(buf, 0, sizeof(buf));
9457     previous_port = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);
9458     ok( previous_port != NULL, "Failed to create completion port %u\n", GetLastError());
9459 
9460     memset(&ov, 0, sizeof(ov));
9461 
9462     tcp_socketpair(&src, &dest);
9463     if (src == INVALID_SOCKET || dest == INVALID_SOCKET)
9464     {
9465         skip("failed to create sockets\n");
9466         goto end;
9467     }
9468 
9469     bufs.len = sizeof(buf);
9470     bufs.buf = buf;
9471     flags = 0;
9472 
9473     ling.l_onoff = 1;
9474     ling.l_linger = 0;
9475     iret = setsockopt (src, SOL_SOCKET, SO_LINGER, (char *) &ling, sizeof(ling));
9476     ok(!iret, "Failed to set linger %d\n", GetLastError());
9477 
9478     io_port = CreateIoCompletionPort( (HANDLE)dest, previous_port, 125, 0 );
9479     ok(io_port != NULL, "Failed to create completion port %u\n", GetLastError());
9480 
9481     SetLastError(0xdeadbeef);
9482 
9483     iret = WSARecv(dest, &bufs, 1, &num_bytes, &flags, &ov, NULL);
9484     ok(iret == SOCKET_ERROR, "WSARecv returned %d\n", iret);
9485     ok(GetLastError() == ERROR_IO_PENDING, "Last error was %d\n", GetLastError());
9486 
9487     Sleep(100);
9488 
9489     closesocket(src);
9490     src = INVALID_SOCKET;
9491 
9492     SetLastError(0xdeadbeef);
9493     key = 0xdeadbeef;
9494     num_bytes = 0xdeadbeef;
9495     olp = (WSAOVERLAPPED *)0xdeadbeef;
9496 
9497     bret = GetQueuedCompletionStatus(io_port, &num_bytes, &key, &olp, 100);
9498     todo_wine ok(bret == FALSE, "GetQueuedCompletionStatus returned %d\n", bret);
9499     todo_wine ok(GetLastError() == ERROR_NETNAME_DELETED, "Last error was %d\n", GetLastError());
9500     ok(key == 125, "Key is %lu\n", key);
9501     ok(num_bytes == 0, "Number of bytes received is %u\n", num_bytes);
9502     ok(olp == &ov, "Overlapped structure is at %p\n", olp);
9503 
9504     SetLastError(0xdeadbeef);
9505     key = 0xdeadbeef;
9506     num_bytes = 0xdeadbeef;
9507     olp = (WSAOVERLAPPED *)0xdeadbeef;
9508 
9509     bret = GetQueuedCompletionStatus(io_port, &num_bytes, &key, &olp, 100);
9510     ok(bret == FALSE, "GetQueuedCompletionStatus returned %d\n", bret );
9511     ok(GetLastError() == WAIT_TIMEOUT, "Last error was %d\n", GetLastError());
9512     ok(key == 0xdeadbeef, "Key is %lu\n", key);
9513     ok(num_bytes == 0xdeadbeef, "Number of bytes transferred is %u\n", num_bytes);
9514     ok(!olp, "Overlapped structure is at %p\n", olp);
9515 
9516     if (dest != INVALID_SOCKET)
9517         closesocket(dest);
9518 
9519     memset(&ov, 0, sizeof(ov));
9520 
9521     tcp_socketpair(&src, &dest);
9522     if (src == INVALID_SOCKET || dest == INVALID_SOCKET)
9523     {
9524         skip("failed to create sockets\n");
9525         goto end;
9526     }
9527 
9528     bufs.len = sizeof(buf);
9529     bufs.buf = buf;
9530     flags = 0;
9531 
9532     ling.l_onoff = 1;
9533     ling.l_linger = 0;
9534     iret = setsockopt (src, SOL_SOCKET, SO_LINGER, (char *) &ling, sizeof(ling));
9535     ok(!iret, "Failed to set linger %d\n", GetLastError());
9536 
9537     io_port = CreateIoCompletionPort((HANDLE)dest, previous_port, 125, 0);
9538     ok(io_port != NULL, "failed to create completion port %u\n", GetLastError());
9539 
9540     set_blocking(dest, FALSE);
9541 
9542     closesocket(src);
9543     src = INVALID_SOCKET;
9544 
9545     Sleep(100);
9546 
9547     num_bytes = 0xdeadbeef;
9548     SetLastError(0xdeadbeef);
9549 
9550     iret = WSASend(dest, &bufs, 1, &num_bytes, 0, &ov, NULL);
9551     ok(iret == SOCKET_ERROR, "WSASend failed - %d\n", iret);
9552     ok(GetLastError() == WSAECONNRESET, "Last error was %d\n", GetLastError());
9553     ok(num_bytes == 0xdeadbeef, "Managed to send %d\n", num_bytes);
9554 
9555     SetLastError(0xdeadbeef);
9556     key = 0xdeadbeef;
9557     num_bytes = 0xdeadbeef;
9558     olp = (WSAOVERLAPPED *)0xdeadbeef;
9559 
9560     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 200 );
9561     ok(bret == FALSE, "GetQueuedCompletionStatus returned %u\n", bret );
9562     ok(GetLastError() == WAIT_TIMEOUT, "Last error was %d\n", GetLastError());
9563     ok(key == 0xdeadbeef, "Key is %lu\n", key);
9564     ok(num_bytes == 0xdeadbeef, "Number of bytes transferred is %u\n", num_bytes);
9565     ok(!olp, "Overlapped structure is at %p\n", olp);
9566 
9567     if (dest != INVALID_SOCKET)
9568         closesocket(dest);
9569 
9570     /* Test IOCP response on successful immediate read. */
9571     tcp_socketpair(&src, &dest);
9572     if (src == INVALID_SOCKET || dest == INVALID_SOCKET)
9573     {
9574         skip("failed to create sockets\n");
9575         goto end;
9576     }
9577 
9578     bufs.len = sizeof(buf);
9579     bufs.buf = buf;
9580     flags = 0;
9581     SetLastError(0xdeadbeef);
9582 
9583     iret = WSASend(src, &bufs, 1, &num_bytes, 0, &ov, NULL);
9584     ok(!iret, "WSASend failed - %d, last error %u\n", iret, GetLastError());
9585     ok(num_bytes == sizeof(buf), "Managed to send %d\n", num_bytes);
9586 
9587     io_port = CreateIoCompletionPort((HANDLE)dest, previous_port, 125, 0);
9588     ok(io_port != NULL, "failed to create completion port %u\n", GetLastError());
9589     set_blocking(dest, FALSE);
9590 
9591     FD_ZERO(&fds_recv);
9592     FD_SET(dest, &fds_recv);
9593     select(dest + 1, &fds_recv, NULL, NULL, NULL);
9594 
9595     num_bytes = 0xdeadbeef;
9596     flags = 0;
9597 
9598     iret = WSARecv(dest, &bufs, 1, &num_bytes, &flags, &ov, NULL);
9599     ok(!iret, "WSARecv failed - %d, last error %u\n", iret, GetLastError());
9600     ok(num_bytes == sizeof(buf), "Managed to read %d\n", num_bytes);
9601 
9602     SetLastError(0xdeadbeef);
9603     key = 0xdeadbeef;
9604     num_bytes = 0xdeadbeef;
9605     olp = (WSAOVERLAPPED *)0xdeadbeef;
9606 
9607     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 200 );
9608     ok(bret == TRUE, "failed to get completion status %u\n", bret);
9609     ok(GetLastError() == 0xdeadbeef, "Last error was %d\n", GetLastError());
9610     ok(key == 125, "Key is %lu\n", key);
9611     ok(num_bytes == sizeof(buf), "Number of bytes transferred is %u\n", num_bytes);
9612     ok(olp == &ov, "Overlapped structure is at %p\n", olp);
9613 
9614     /* Test IOCP response on graceful shutdown. */
9615     closesocket(src);
9616 
9617     FD_ZERO(&fds_recv);
9618     FD_SET(dest, &fds_recv);
9619     select(dest + 1, &fds_recv, NULL, NULL, NULL);
9620 
9621     num_bytes = 0xdeadbeef;
9622     flags = 0;
9623     memset(&ov, 0, sizeof(ov));
9624 
9625     iret = WSARecv(dest, &bufs, 1, &num_bytes, &flags, &ov, NULL);
9626     ok(!iret, "WSARecv failed - %d, last error %u\n", iret, GetLastError());
9627     ok(!num_bytes, "Managed to read %d\n", num_bytes);
9628 
9629     SetLastError(0xdeadbeef);
9630     key = 0xdeadbeef;
9631     num_bytes = 0xdeadbeef;
9632     olp = (WSAOVERLAPPED *)0xdeadbeef;
9633 
9634     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 200 );
9635     ok(bret == TRUE, "failed to get completion status %u\n", bret);
9636     ok(GetLastError() == 0xdeadbeef, "Last error was %d\n", GetLastError());
9637     ok(key == 125, "Key is %lu\n", key);
9638     ok(!num_bytes, "Number of bytes transferred is %u\n", num_bytes);
9639     ok(olp == &ov, "Overlapped structure is at %p\n", olp);
9640 
9641     closesocket(src);
9642     src = INVALID_SOCKET;
9643     closesocket(dest);
9644     dest = INVALID_SOCKET;
9645 
9646     /* Test IOCP response on hard shutdown. This was the condition that triggered
9647      * a crash in an actual app (bug 38980). */
9648     tcp_socketpair(&src, &dest);
9649     if (src == INVALID_SOCKET || dest == INVALID_SOCKET)
9650     {
9651         skip("failed to create sockets\n");
9652         goto end;
9653     }
9654 
9655     bufs.len = sizeof(buf);
9656     bufs.buf = buf;
9657     flags = 0;
9658     memset(&ov, 0, sizeof(ov));
9659 
9660     ling.l_onoff = 1;
9661     ling.l_linger = 0;
9662     iret = setsockopt (src, SOL_SOCKET, SO_LINGER, (char *) &ling, sizeof(ling));
9663     ok(!iret, "Failed to set linger %d\n", GetLastError());
9664 
9665     io_port = CreateIoCompletionPort((HANDLE)dest, previous_port, 125, 0);
9666     ok(io_port != NULL, "failed to create completion port %u\n", GetLastError());
9667     set_blocking(dest, FALSE);
9668 
9669     closesocket(src);
9670     src = INVALID_SOCKET;
9671 
9672     FD_ZERO(&fds_recv);
9673     FD_SET(dest, &fds_recv);
9674     select(dest + 1, &fds_recv, NULL, NULL, NULL);
9675 
9676     num_bytes = 0xdeadbeef;
9677     SetLastError(0xdeadbeef);
9678 
9679     /* Somehow a hard shutdown doesn't work on my Linux box. It seems SO_LINGER is ignored. */
9680     iret = WSARecv(dest, &bufs, 1, &num_bytes, &flags, &ov, NULL);
9681     todo_wine ok(iret == SOCKET_ERROR, "WSARecv failed - %d\n", iret);
9682     todo_wine ok(GetLastError() == WSAECONNRESET, "Last error was %d\n", GetLastError());
9683     todo_wine ok(num_bytes == 0xdeadbeef, "Managed to read %d\n", num_bytes);
9684 
9685     SetLastError(0xdeadbeef);
9686     key = 0xdeadbeef;
9687     num_bytes = 0xdeadbeef;
9688     olp = (WSAOVERLAPPED *)0xdeadbeef;
9689 
9690     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 200 );
9691     todo_wine ok(bret == FALSE, "GetQueuedCompletionStatus returned %u\n", bret );
9692     todo_wine ok(GetLastError() == WAIT_TIMEOUT, "Last error was %d\n", GetLastError());
9693     todo_wine ok(key == 0xdeadbeef, "Key is %lu\n", key);
9694     todo_wine ok(num_bytes == 0xdeadbeef, "Number of bytes transferred is %u\n", num_bytes);
9695     todo_wine ok(!olp, "Overlapped structure is at %p\n", olp);
9696 
9697     closesocket(dest);
9698 
9699     /* Test reading from a non-connected socket, mostly because the above test is marked todo. */
9700     dest = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
9701     ok(dest != INVALID_SOCKET, "socket() failed\n");
9702 
9703     io_port = CreateIoCompletionPort((HANDLE)dest, previous_port, 125, 0);
9704     ok(io_port != NULL, "failed to create completion port %u\n", GetLastError());
9705     set_blocking(dest, FALSE);
9706 
9707     num_bytes = 0xdeadbeef;
9708     SetLastError(0xdeadbeef);
9709     memset(&ov, 0, sizeof(ov));
9710 
9711     iret = WSARecv(dest, &bufs, 1, &num_bytes, &flags, &ov, NULL);
9712     ok(iret == SOCKET_ERROR, "WSARecv failed - %d\n", iret);
9713     ok(GetLastError() == WSAENOTCONN, "Last error was %d\n", GetLastError());
9714     ok(num_bytes == 0xdeadbeef, "Managed to read %d\n", num_bytes);
9715 
9716     SetLastError(0xdeadbeef);
9717     key = 0xdeadbeef;
9718     num_bytes = 0xdeadbeef;
9719     olp = (WSAOVERLAPPED *)0xdeadbeef;
9720 
9721     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 200 );
9722     ok(bret == FALSE, "GetQueuedCompletionStatus returned %u\n", bret );
9723     ok(GetLastError() == WAIT_TIMEOUT, "Last error was %d\n", GetLastError());
9724     ok(key == 0xdeadbeef, "Key is %lu\n", key);
9725     ok(num_bytes == 0xdeadbeef, "Number of bytes transferred is %u\n", num_bytes);
9726     ok(!olp, "Overlapped structure is at %p\n", olp);
9727 
9728     num_bytes = 0xdeadbeef;
9729     closesocket(dest);
9730 
9731     dest = socket(AF_INET, SOCK_STREAM, 0);
9732     if (dest == INVALID_SOCKET)
9733     {
9734         skip("could not create acceptor socket, error %d\n", WSAGetLastError());
9735         goto end;
9736     }
9737 
9738     iret = WSAIoctl(dest, SIO_GET_EXTENSION_FUNCTION_POINTER, &acceptExGuid, sizeof(acceptExGuid),
9739             &pAcceptEx, sizeof(pAcceptEx), &num_bytes, NULL, NULL);
9740     if (iret)
9741     {
9742         skip("WSAIoctl failed to get AcceptEx with ret %d + errno %d\n", iret, WSAGetLastError());
9743         goto end;
9744     }
9745 
9746     /* Test IOCP response on socket close (IOCP created after AcceptEx) */
9747 
9748     if ((src = setup_iocp_src(&bindAddress)) == INVALID_SOCKET)
9749         goto end;
9750 
9751     SetLastError(0xdeadbeef);
9752 
9753     bret = pAcceptEx(src, dest, buf, sizeof(buf) - 2*(sizeof(struct sockaddr_in) + 16),
9754             sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
9755             &num_bytes, &ov);
9756     ok(bret == FALSE, "AcceptEx returned %d\n", bret);
9757     ok(GetLastError() == ERROR_IO_PENDING, "Last error was %d\n", GetLastError());
9758 
9759     io_port = CreateIoCompletionPort((HANDLE)src, previous_port, 125, 0);
9760     ok(io_port != NULL, "failed to create completion port %u\n", GetLastError());
9761 
9762     closesocket(src);
9763     src = INVALID_SOCKET;
9764 
9765     SetLastError(0xdeadbeef);
9766     key = 0xdeadbeef;
9767     num_bytes = 0xdeadbeef;
9768     olp = (WSAOVERLAPPED *)0xdeadbeef;
9769 
9770     bret = GetQueuedCompletionStatus(io_port, &num_bytes, &key, &olp, 100);
9771     ok(bret == FALSE, "failed to get completion status %u\n", bret);
9772     ok(GetLastError() == ERROR_OPERATION_ABORTED, "Last error was %d\n", GetLastError());
9773     ok(key == 125, "Key is %lu\n", key);
9774     ok(num_bytes == 0, "Number of bytes transferred is %u\n", num_bytes);
9775     ok(olp == &ov, "Overlapped structure is at %p\n", olp);
9776     ok(olp && (olp->Internal == (ULONG)STATUS_CANCELLED), "Internal status is %lx\n", olp ? olp->Internal : 0);
9777 
9778     SetLastError(0xdeadbeef);
9779     key = 0xdeadbeef;
9780     num_bytes = 0xdeadbeef;
9781     olp = (WSAOVERLAPPED *)0xdeadbeef;
9782     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 200 );
9783     ok(bret == FALSE, "failed to get completion status %u\n", bret);
9784     ok(GetLastError() == WAIT_TIMEOUT, "Last error was %d\n", GetLastError());
9785     ok(key == 0xdeadbeef, "Key is %lu\n", key);
9786     ok(num_bytes == 0xdeadbeef, "Number of bytes transferred is %u\n", num_bytes);
9787     ok(!olp, "Overlapped structure is at %p\n", olp);
9788 
9789     /* Test IOCP response on socket close (IOCP created before AcceptEx) */
9790 
9791     if ((src = setup_iocp_src(&bindAddress)) == INVALID_SOCKET)
9792         goto end;
9793 
9794     SetLastError(0xdeadbeef);
9795 
9796     io_port = CreateIoCompletionPort((HANDLE)src, previous_port, 125, 0);
9797     ok(io_port != NULL, "failed to create completion port %u\n", GetLastError());
9798 
9799     bret = pAcceptEx(src, dest, buf, sizeof(buf) - 2*(sizeof(struct sockaddr_in) + 16),
9800             sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
9801             &num_bytes, &ov);
9802     ok(bret == FALSE, "AcceptEx returned %d\n", bret);
9803     ok(GetLastError() == ERROR_IO_PENDING, "Last error was %d\n", GetLastError());
9804 
9805     closesocket(src);
9806     src = INVALID_SOCKET;
9807 
9808     SetLastError(0xdeadbeef);
9809     key = 0xdeadbeef;
9810     num_bytes = 0xdeadbeef;
9811     olp = (WSAOVERLAPPED *)0xdeadbeef;
9812 
9813     bret = GetQueuedCompletionStatus(io_port, &num_bytes, &key, &olp, 100);
9814     ok(bret == FALSE, "failed to get completion status %u\n", bret);
9815     ok(GetLastError() == ERROR_OPERATION_ABORTED, "Last error was %d\n", GetLastError());
9816     ok(key == 125, "Key is %lu\n", key);
9817     ok(num_bytes == 0, "Number of bytes transferred is %u\n", num_bytes);
9818     ok(olp == &ov, "Overlapped structure is at %p\n", olp);
9819     ok(olp && (olp->Internal == (ULONG)STATUS_CANCELLED), "Internal status is %lx\n", olp ? olp->Internal : 0);
9820 
9821     SetLastError(0xdeadbeef);
9822     key = 0xdeadbeef;
9823     num_bytes = 0xdeadbeef;
9824     olp = (WSAOVERLAPPED *)0xdeadbeef;
9825     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 200 );
9826     ok(bret == FALSE, "failed to get completion status %u\n", bret);
9827     ok(GetLastError() == WAIT_TIMEOUT, "Last error was %d\n", GetLastError());
9828     ok(key == 0xdeadbeef, "Key is %lu\n", key);
9829     ok(num_bytes == 0xdeadbeef, "Number of bytes transferred is %u\n", num_bytes);
9830     ok(!olp, "Overlapped structure is at %p\n", olp);
9831 
9832     /* Test IOCP with duplicated handle */
9833 
9834     if ((src = setup_iocp_src(&bindAddress)) == INVALID_SOCKET)
9835         goto end;
9836 
9837     SetLastError(0xdeadbeef);
9838 
9839     io_port = CreateIoCompletionPort((HANDLE)src, previous_port, 125, 0);
9840     ok(io_port != NULL, "failed to create completion port %u\n", GetLastError());
9841 
9842     WSADuplicateSocketA( src, GetCurrentProcessId(), &info );
9843     dup = WSASocketA(AF_INET, SOCK_STREAM, 0, &info, 0, WSA_FLAG_OVERLAPPED);
9844     ok(dup != INVALID_SOCKET, "failed to duplicate socket!\n");
9845 
9846     bret = pAcceptEx(dup, dest, buf, sizeof(buf) - 2*(sizeof(struct sockaddr_in) + 16),
9847             sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
9848             &num_bytes, &ov);
9849     ok(bret == FALSE, "AcceptEx returned %d\n", bret);
9850     ok(GetLastError() == ERROR_IO_PENDING, "Last error was %d\n", GetLastError());
9851 
9852     SetLastError(0xdeadbeef);
9853     key = 0xdeadbeef;
9854     num_bytes = 0xdeadbeef;
9855     olp = (WSAOVERLAPPED *)0xdeadbeef;
9856     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 200 );
9857     ok(bret == FALSE, "failed to get completion status %u\n", bret);
9858     ok(GetLastError() == WAIT_TIMEOUT, "Last error was %d\n", GetLastError());
9859     ok(key == 0xdeadbeef, "Key is %lu\n", key);
9860     ok(num_bytes == 0xdeadbeef, "Number of bytes transferred is %u\n", num_bytes);
9861     ok(!olp, "Overlapped structure is at %p\n", olp);
9862 
9863     closesocket(src);
9864     src = INVALID_SOCKET;
9865     closesocket(dup);
9866     dup = INVALID_SOCKET;
9867 
9868     SetLastError(0xdeadbeef);
9869     key = 0xdeadbeef;
9870     num_bytes = 0xdeadbeef;
9871     olp = (WSAOVERLAPPED *)0xdeadbeef;
9872     bret = GetQueuedCompletionStatus(io_port, &num_bytes, &key, &olp, 100);
9873     ok(bret == FALSE, "failed to get completion status %u\n", bret);
9874     ok(GetLastError() == ERROR_OPERATION_ABORTED, "Last error was %d\n", GetLastError());
9875     ok(key == 125, "Key is %lu\n", key);
9876     ok(num_bytes == 0, "Number of bytes transferred is %u\n", num_bytes);
9877     ok(olp == &ov, "Overlapped structure is at %p\n", olp);
9878     ok(olp && olp->Internal == (ULONG)STATUS_CANCELLED, "Internal status is %lx\n", olp ? olp->Internal : 0);
9879 
9880     SetLastError(0xdeadbeef);
9881     key = 0xdeadbeef;
9882     num_bytes = 0xdeadbeef;
9883     olp = (WSAOVERLAPPED *)0xdeadbeef;
9884     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 200 );
9885     ok(bret == FALSE, "failed to get completion status %u\n", bret);
9886     ok(GetLastError() == WAIT_TIMEOUT, "Last error was %d\n", GetLastError());
9887     ok(key == 0xdeadbeef, "Key is %lu\n", key);
9888     ok(num_bytes == 0xdeadbeef, "Number of bytes transferred is %u\n", num_bytes);
9889     ok(!olp, "Overlapped structure is at %p\n", olp);
9890 
9891     /* Test IOCP with duplicated handle (closing duplicated handle) */
9892 
9893     if ((src = setup_iocp_src(&bindAddress)) == INVALID_SOCKET)
9894         goto end;
9895 
9896     SetLastError(0xdeadbeef);
9897 
9898     io_port = CreateIoCompletionPort((HANDLE)src, previous_port, 125, 0);
9899     ok(io_port != NULL, "failed to create completion port %u\n", GetLastError());
9900 
9901     WSADuplicateSocketA( src, GetCurrentProcessId(), &info );
9902     dup = WSASocketA(AF_INET, SOCK_STREAM, 0, &info, 0, WSA_FLAG_OVERLAPPED);
9903     ok(dup != INVALID_SOCKET, "failed to duplicate socket!\n");
9904 
9905     bret = pAcceptEx(dup, dest, buf, sizeof(buf) - 2*(sizeof(struct sockaddr_in) + 16),
9906             sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
9907             &num_bytes, &ov);
9908     ok(bret == FALSE, "AcceptEx returned %d\n", bret);
9909     ok(GetLastError() == ERROR_IO_PENDING, "Last error was %d\n", GetLastError());
9910 
9911     closesocket(dup);
9912     dup = INVALID_SOCKET;
9913 
9914     SetLastError(0xdeadbeef);
9915     key = 0xdeadbeef;
9916     num_bytes = 0xdeadbeef;
9917     olp = (WSAOVERLAPPED *)0xdeadbeef;
9918     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 200 );
9919     ok(bret == FALSE, "failed to get completion status %u\n", bret);
9920     ok(GetLastError() == WAIT_TIMEOUT, "Last error was %d\n", GetLastError());
9921     ok(key == 0xdeadbeef, "Key is %lu\n", key);
9922     ok(num_bytes == 0xdeadbeef, "Number of bytes transferred is %u\n", num_bytes);
9923     ok(!olp, "Overlapped structure is at %p\n", olp);
9924 
9925     SetLastError(0xdeadbeef);
9926     key = 0xdeadbeef;
9927     num_bytes = 0xdeadbeef;
9928     olp = (WSAOVERLAPPED *)0xdeadbeef;
9929     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 200 );
9930     ok(bret == FALSE, "failed to get completion status %u\n", bret);
9931     ok(GetLastError() == WAIT_TIMEOUT, "Last error was %d\n", GetLastError());
9932     ok(key == 0xdeadbeef, "Key is %lu\n", key);
9933     ok(num_bytes == 0xdeadbeef, "Number of bytes transferred is %u\n", num_bytes);
9934     ok(!olp, "Overlapped structure is at %p\n", olp);
9935 
9936     closesocket(src);
9937     src = INVALID_SOCKET;
9938 
9939     bret = GetQueuedCompletionStatus(io_port, &num_bytes, &key, &olp, 100);
9940     ok(bret == FALSE, "failed to get completion status %u\n", bret);
9941     ok(GetLastError() == ERROR_OPERATION_ABORTED, "Last error was %d\n", GetLastError());
9942     ok(key == 125, "Key is %lu\n", key);
9943     ok(num_bytes == 0, "Number of bytes transferred is %u\n", num_bytes);
9944     ok(olp == &ov, "Overlapped structure is at %p\n", olp);
9945     ok(olp && (olp->Internal == (ULONG)STATUS_CANCELLED), "Internal status is %lx\n", olp ? olp->Internal : 0);
9946 
9947     SetLastError(0xdeadbeef);
9948     key = 0xdeadbeef;
9949     num_bytes = 0xdeadbeef;
9950     olp = (WSAOVERLAPPED *)0xdeadbeef;
9951     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 200 );
9952     ok(bret == FALSE, "failed to get completion status %u\n", bret);
9953     ok(GetLastError() == WAIT_TIMEOUT, "Last error was %d\n", GetLastError());
9954     ok(key == 0xdeadbeef, "Key is %lu\n", key);
9955     ok(num_bytes == 0xdeadbeef, "Number of bytes transferred is %u\n", num_bytes);
9956     ok(!olp, "Overlapped structure is at %p\n", olp);
9957 
9958     /* Test IOCP with duplicated handle (closing original handle) */
9959 
9960     if ((src = setup_iocp_src(&bindAddress)) == INVALID_SOCKET)
9961         goto end;
9962 
9963     SetLastError(0xdeadbeef);
9964 
9965     io_port = CreateIoCompletionPort((HANDLE)src, previous_port, 125, 0);
9966     ok(io_port != NULL, "failed to create completion port %u\n", GetLastError());
9967 
9968     WSADuplicateSocketA( src, GetCurrentProcessId(), &info );
9969     dup = WSASocketA(AF_INET, SOCK_STREAM, 0, &info, 0, WSA_FLAG_OVERLAPPED);
9970     ok(dup != INVALID_SOCKET, "failed to duplicate socket!\n");
9971 
9972     bret = pAcceptEx(dup, dest, buf, sizeof(buf) - 2*(sizeof(struct sockaddr_in) + 16),
9973             sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
9974             &num_bytes, &ov);
9975     ok(bret == FALSE, "AcceptEx returned %d\n", bret);
9976     ok(GetLastError() == ERROR_IO_PENDING, "Last error was %d\n", GetLastError());
9977 
9978     closesocket(src);
9979     src = INVALID_SOCKET;
9980 
9981     SetLastError(0xdeadbeef);
9982     key = 0xdeadbeef;
9983     num_bytes = 0xdeadbeef;
9984     olp = (WSAOVERLAPPED *)0xdeadbeef;
9985     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 200 );
9986     ok(bret == FALSE, "failed to get completion status %u\n", bret);
9987     ok(GetLastError() == WAIT_TIMEOUT, "Last error was %d\n", GetLastError());
9988     ok(key == 0xdeadbeef, "Key is %lu\n", key);
9989     ok(num_bytes == 0xdeadbeef, "Number of bytes transferred is %u\n", num_bytes);
9990     ok(!olp, "Overlapped structure is at %p\n", olp);
9991 
9992     closesocket(dup);
9993     dup = INVALID_SOCKET;
9994 
9995     bret = GetQueuedCompletionStatus(io_port, &num_bytes, &key, &olp, 100);
9996     ok(bret == FALSE, "failed to get completion status %u\n", bret);
9997     ok(GetLastError() == ERROR_OPERATION_ABORTED, "Last error was %d\n", GetLastError());
9998     ok(key == 125, "Key is %lu\n", key);
9999     ok(num_bytes == 0, "Number of bytes transferred is %u\n", num_bytes);
10000     ok(olp == &ov, "Overlapped structure is at %p\n", olp);
10001     ok(olp && (olp->Internal == (ULONG)STATUS_CANCELLED), "Internal status is %lx\n", olp ? olp->Internal : 0);
10002 
10003     SetLastError(0xdeadbeef);
10004     key = 0xdeadbeef;
10005     num_bytes = 0xdeadbeef;
10006     olp = (WSAOVERLAPPED *)0xdeadbeef;
10007     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 200 );
10008     ok(bret == FALSE, "failed to get completion status %u\n", bret);
10009     ok(GetLastError() == WAIT_TIMEOUT, "Last error was %d\n", GetLastError());
10010     ok(key == 0xdeadbeef, "Key is %lu\n", key);
10011     ok(num_bytes == 0xdeadbeef, "Number of bytes transferred is %u\n", num_bytes);
10012     ok(!olp, "Overlapped structure is at %p\n", olp);
10013 
10014     /* Test IOCP without AcceptEx */
10015 
10016     if ((src = setup_iocp_src(&bindAddress)) == INVALID_SOCKET)
10017         goto end;
10018 
10019     SetLastError(0xdeadbeef);
10020 
10021     io_port = CreateIoCompletionPort((HANDLE)src, previous_port, 125, 0);
10022     ok(io_port != NULL, "failed to create completion port %u\n", GetLastError());
10023 
10024     closesocket(src);
10025     src = INVALID_SOCKET;
10026 
10027     SetLastError(0xdeadbeef);
10028     key = 0xdeadbeef;
10029     num_bytes = 0xdeadbeef;
10030     olp = (WSAOVERLAPPED *)0xdeadbeef;
10031     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 200 );
10032     ok(bret == FALSE, "failed to get completion status %u\n", bret);
10033     ok(GetLastError() == WAIT_TIMEOUT, "Last error was %d\n", GetLastError());
10034     ok(key == 0xdeadbeef, "Key is %lu\n", key);
10035     ok(num_bytes == 0xdeadbeef, "Number of bytes transferred is %u\n", num_bytes);
10036     ok(!olp, "Overlapped structure is at %p\n", olp);
10037 
10038     /* */
10039 
10040     if ((src = setup_iocp_src(&bindAddress)) == INVALID_SOCKET)
10041         goto end;
10042 
10043     connector = socket(AF_INET, SOCK_STREAM, 0);
10044     if (connector == INVALID_SOCKET) {
10045         skip("could not create connector socket, error %d\n", WSAGetLastError());
10046         goto end;
10047     }
10048 
10049     io_port = CreateIoCompletionPort((HANDLE)src, previous_port, 125, 0);
10050     ok(io_port != NULL, "failed to create completion port %u\n", GetLastError());
10051 
10052     io_port = CreateIoCompletionPort((HANDLE)dest, previous_port, 236, 0);
10053     ok(io_port != NULL, "failed to create completion port %u\n", GetLastError());
10054 
10055     io_info.Flags = FILE_SKIP_COMPLETION_PORT_ON_SUCCESS;
10056     status = pNtSetInformationFile((HANDLE)src, &io, &io_info, sizeof(io_info), FileIoCompletionNotificationInformation);
10057     ok(status == STATUS_SUCCESS || broken(status == STATUS_INVALID_INFO_CLASS) /* XP */,
10058        "expected STATUS_SUCCESS, got %08x\n", status);
10059 
10060     io_info.Flags = FILE_SKIP_COMPLETION_PORT_ON_SUCCESS;
10061     status = pNtSetInformationFile((HANDLE)dest, &io, &io_info, sizeof(io_info), FileIoCompletionNotificationInformation);
10062     ok(status == STATUS_SUCCESS || broken(status == STATUS_INVALID_INFO_CLASS) /* XP */,
10063        "expected STATUS_SUCCESS, got %08x\n", status);
10064 
10065     bret = pAcceptEx(src, dest, buf, sizeof(buf) - 2*(sizeof(struct sockaddr_in) + 16),
10066             sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
10067             &num_bytes, &ov);
10068     ok(bret == FALSE, "AcceptEx returned %d\n", bret);
10069     ok(GetLastError() == ERROR_IO_PENDING, "Last error was %d\n", GetLastError());
10070 
10071     iret = connect(connector, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
10072     ok(iret == 0, "connecting to accepting socket failed, error %d\n", GetLastError());
10073 
10074     closesocket(connector);
10075     connector = INVALID_SOCKET;
10076 
10077     SetLastError(0xdeadbeef);
10078     key = 0xdeadbeef;
10079     num_bytes = 0xdeadbeef;
10080     olp = (WSAOVERLAPPED *)0xdeadbeef;
10081 
10082     bret = GetQueuedCompletionStatus(io_port, &num_bytes, &key, &olp, 100);
10083     ok(bret == TRUE, "failed to get completion status %u\n", bret);
10084     ok(GetLastError() == 0xdeadbeef, "Last error was %d\n", GetLastError());
10085     ok(key == 125, "Key is %lu\n", key);
10086     ok(num_bytes == 0, "Number of bytes transferred is %u\n", num_bytes);
10087     ok(olp == &ov, "Overlapped structure is at %p\n", olp);
10088     ok(olp && (olp->Internal == (ULONG)STATUS_SUCCESS), "Internal status is %lx\n", olp ? olp->Internal : 0);
10089 
10090     io_info.Flags = 0;
10091     status = pNtQueryInformationFile((HANDLE)dest, &io, &io_info, sizeof(io_info), FileIoCompletionNotificationInformation);
10092     ok(status == STATUS_SUCCESS || broken(status == STATUS_INVALID_INFO_CLASS) /* XP */,
10093        "expected STATUS_SUCCESS, got %08x\n", status);
10094     if (status == STATUS_SUCCESS)
10095         ok((io_info.Flags & FILE_SKIP_COMPLETION_PORT_ON_SUCCESS) != 0, "got %08x\n", io_info.Flags);
10096 
10097     SetLastError(0xdeadbeef);
10098     key = 0xdeadbeef;
10099     num_bytes = 0xdeadbeef;
10100     olp = (WSAOVERLAPPED *)0xdeadbeef;
10101     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 200 );
10102     ok(bret == FALSE, "failed to get completion status %u\n", bret);
10103     ok(GetLastError() == WAIT_TIMEOUT, "Last error was %d\n", GetLastError());
10104     ok(key == 0xdeadbeef, "Key is %lu\n", key);
10105     ok(num_bytes == 0xdeadbeef, "Number of bytes transferred is %u\n", num_bytes);
10106     ok(!olp, "Overlapped structure is at %p\n", olp);
10107 
10108     if (dest != INVALID_SOCKET)
10109         closesocket(dest);
10110     if (src != INVALID_SOCKET)
10111         closesocket(dest);
10112 
10113     /* */
10114 
10115     if ((src = setup_iocp_src(&bindAddress)) == INVALID_SOCKET)
10116         goto end;
10117 
10118     dest = socket(AF_INET, SOCK_STREAM, 0);
10119     if (dest == INVALID_SOCKET)
10120     {
10121         skip("could not create acceptor socket, error %d\n", WSAGetLastError());
10122         goto end;
10123     }
10124 
10125     connector = socket(AF_INET, SOCK_STREAM, 0);
10126     if (connector == INVALID_SOCKET) {
10127         skip("could not create connector socket, error %d\n", WSAGetLastError());
10128         goto end;
10129     }
10130 
10131     io_port = CreateIoCompletionPort((HANDLE)src, previous_port, 125, 0);
10132     ok(io_port != NULL, "failed to create completion port %u\n", GetLastError());
10133 
10134     io_port = CreateIoCompletionPort((HANDLE)dest, previous_port, 236, 0);
10135     ok(io_port != NULL, "failed to create completion port %u\n", GetLastError());
10136 
10137     bret = pAcceptEx(src, dest, buf, sizeof(buf) - 2*(sizeof(struct sockaddr_in) + 16),
10138             sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
10139             &num_bytes, &ov);
10140     ok(bret == FALSE, "AcceptEx returned %d\n", bret);
10141     ok(GetLastError() == ERROR_IO_PENDING, "Last error was %d\n", GetLastError());
10142 
10143     iret = connect(connector, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
10144     ok(iret == 0, "connecting to accepting socket failed, error %d\n", GetLastError());
10145 
10146     iret = send(connector, buf, 1, 0);
10147     ok(iret == 1, "could not send 1 byte: send %d errno %d\n", iret, WSAGetLastError());
10148 
10149     Sleep(100);
10150 
10151     closesocket(dest);
10152     dest = INVALID_SOCKET;
10153 
10154     SetLastError(0xdeadbeef);
10155     key = 0xdeadbeef;
10156     num_bytes = 0xdeadbeef;
10157     olp = (WSAOVERLAPPED *)0xdeadbeef;
10158 
10159     bret = GetQueuedCompletionStatus(io_port, &num_bytes, &key, &olp, 100);
10160     ok(bret == TRUE, "failed to get completion status %u\n", bret);
10161     ok(GetLastError() == 0xdeadbeef, "Last error was %d\n", GetLastError());
10162     ok(key == 125, "Key is %lu\n", key);
10163     ok(num_bytes == 1, "Number of bytes transferred is %u\n", num_bytes);
10164     ok(olp == &ov, "Overlapped structure is at %p\n", olp);
10165     ok(olp && (olp->Internal == (ULONG)STATUS_SUCCESS), "Internal status is %lx\n", olp ? olp->Internal : 0);
10166 
10167     SetLastError(0xdeadbeef);
10168     key = 0xdeadbeef;
10169     num_bytes = 0xdeadbeef;
10170     olp = (WSAOVERLAPPED *)0xdeadbeef;
10171     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 200 );
10172     ok(bret == FALSE, "failed to get completion status %u\n", bret);
10173     ok(GetLastError() == WAIT_TIMEOUT, "Last error was %d\n", GetLastError());
10174     ok(key == 0xdeadbeef, "Key is %lu\n", key);
10175     ok(num_bytes == 0xdeadbeef, "Number of bytes transferred is %u\n", num_bytes);
10176     ok(!olp, "Overlapped structure is at %p\n", olp);
10177 
10178     if (src != INVALID_SOCKET)
10179         closesocket(src);
10180     if (connector != INVALID_SOCKET)
10181         closesocket(connector);
10182 
10183     /* */
10184 
10185     if ((src = setup_iocp_src(&bindAddress)) == INVALID_SOCKET)
10186         goto end;
10187 
10188     dest = socket(AF_INET, SOCK_STREAM, 0);
10189     if (dest == INVALID_SOCKET)
10190     {
10191         skip("could not create acceptor socket, error %d\n", WSAGetLastError());
10192         goto end;
10193     }
10194 
10195     connector = socket(AF_INET, SOCK_STREAM, 0);
10196     if (connector == INVALID_SOCKET) {
10197         skip("could not create connector socket, error %d\n", WSAGetLastError());
10198         goto end;
10199     }
10200 
10201     io_port = CreateIoCompletionPort((HANDLE)src, previous_port, 125, 0);
10202     ok(io_port != NULL, "failed to create completion port %u\n", GetLastError());
10203 
10204     io_port = CreateIoCompletionPort((HANDLE)dest, previous_port, 236, 0);
10205     ok(io_port != NULL, "failed to create completion port %u\n", GetLastError());
10206 
10207     bret = pAcceptEx(src, dest, buf, sizeof(buf) - 2*(sizeof(struct sockaddr_in) + 16),
10208             sizeof(struct sockaddr_in) + 16, sizeof(struct sockaddr_in) + 16,
10209             &num_bytes, &ov);
10210     ok(bret == FALSE, "AcceptEx returned %d\n", bret);
10211     ok(GetLastError() == ERROR_IO_PENDING, "Last error was %d\n", GetLastError());
10212 
10213     iret = connect(connector, (struct sockaddr*)&bindAddress, sizeof(bindAddress));
10214     ok(iret == 0, "connecting to accepting socket failed, error %d\n", GetLastError());
10215 
10216     closesocket(dest);
10217     dest = INVALID_SOCKET;
10218 
10219     SetLastError(0xdeadbeef);
10220     key = 0xdeadbeef;
10221     num_bytes = 0xdeadbeef;
10222     olp = (WSAOVERLAPPED *)0xdeadbeef;
10223 
10224     bret = GetQueuedCompletionStatus(io_port, &num_bytes, &key, &olp, 100);
10225     ok(bret == FALSE, "failed to get completion status %u\n", bret);
10226     todo_wine ok(GetLastError() == ERROR_NETNAME_DELETED ||
10227                  GetLastError() == ERROR_OPERATION_ABORTED ||
10228                  GetLastError() == ERROR_CONNECTION_ABORTED ||
10229                  GetLastError() == ERROR_PIPE_NOT_CONNECTED /* win 2000 */,
10230                  "Last error was %d\n", GetLastError());
10231     ok(key == 125, "Key is %lu\n", key);
10232     ok(num_bytes == 0, "Number of bytes transferred is %u\n", num_bytes);
10233     ok(olp == &ov, "Overlapped structure is at %p\n", olp);
10234     todo_wine ok(olp && (olp->Internal == (ULONG)STATUS_LOCAL_DISCONNECT ||
10235                          olp->Internal == (ULONG)STATUS_CANCELLED ||
10236                          olp->Internal == (ULONG)STATUS_CONNECTION_ABORTED ||
10237                          olp->Internal == (ULONG)STATUS_PIPE_DISCONNECTED /* win 2000 */),
10238                          "Internal status is %lx\n", olp ? olp->Internal : 0);
10239 
10240     SetLastError(0xdeadbeef);
10241     key = 0xdeadbeef;
10242     num_bytes = 0xdeadbeef;
10243     olp = (WSAOVERLAPPED *)0xdeadbeef;
10244     bret = GetQueuedCompletionStatus( io_port, &num_bytes, &key, &olp, 200 );
10245     ok(bret == FALSE, "failed to get completion status %u\n", bret);
10246     ok(GetLastError() == WAIT_TIMEOUT, "Last error was %d\n", GetLastError());
10247     ok(key == 0xdeadbeef, "Key is %lu\n", key);
10248     ok(num_bytes == 0xdeadbeef, "Number of bytes transferred is %u\n", num_bytes);
10249     ok(!olp, "Overlapped structure is at %p\n", olp);
10250 
10251 
10252     end:
10253     if (dest != INVALID_SOCKET)
10254         closesocket(dest);
10255     if (src != INVALID_SOCKET)
10256         closesocket(src);
10257     if (connector != INVALID_SOCKET)
10258         closesocket(connector);
10259     CloseHandle(previous_port);
10260 }
10261 
10262 static void test_address_list_query(void)
10263 {
10264     SOCKET_ADDRESS_LIST *address_list;
10265     DWORD bytes_returned, size;
10266     unsigned int i;
10267     SOCKET s;
10268     int ret;
10269 
10270     s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
10271     ok(s != INVALID_SOCKET, "Failed to create socket, error %d.\n", WSAGetLastError());
10272 
10273     bytes_returned = 0;
10274     ret = WSAIoctl(s, SIO_ADDRESS_LIST_QUERY, NULL, 0, NULL, 0, &bytes_returned, NULL, NULL);
10275     ok(ret == SOCKET_ERROR, "Got unexpected ret %d.\n", ret);
10276     if(WSAGetLastError() == WSAEINVAL)
10277     {
10278       win_skip("Windows <= NT4 is not supported in this test\n");
10279       closesocket(s);
10280       return;
10281     }
10282     ok(WSAGetLastError() == WSAEFAULT, "Got unexpected error %d.\n", WSAGetLastError());
10283     ok(bytes_returned >= FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[0]),
10284             "Got unexpected bytes_returned %u.\n", bytes_returned);
10285 
10286     size = bytes_returned;
10287     bytes_returned = 0;
10288     address_list = HeapAlloc(GetProcessHeap(), 0, size * 2);
10289     ret = WSAIoctl(s, SIO_ADDRESS_LIST_QUERY, NULL, 0, address_list, size * 2, &bytes_returned, NULL, NULL);
10290     ok(!ret, "Got unexpected ret %d, error %d.\n", ret, WSAGetLastError());
10291     ok(bytes_returned == size, "Got unexpected bytes_returned %u, expected %u.\n", bytes_returned, size);
10292 
10293     bytes_returned = FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[address_list->iAddressCount]);
10294     for (i = 0; i < address_list->iAddressCount; ++i)
10295     {
10296         bytes_returned += address_list->Address[i].iSockaddrLength;
10297     }
10298     ok(size == bytes_returned, "Got unexpected size %u, expected %u.\n", size, bytes_returned);
10299 
10300     ret = WSAIoctl(s, SIO_ADDRESS_LIST_QUERY, NULL, 0, address_list, size, NULL, NULL, NULL);
10301     ok(ret == SOCKET_ERROR, "Got unexpected ret %d.\n", ret);
10302     ok(WSAGetLastError() == WSAEFAULT, "Got unexpected error %d.\n", WSAGetLastError());
10303 
10304     bytes_returned = 0xdeadbeef;
10305     ret = WSAIoctl(s, SIO_ADDRESS_LIST_QUERY, NULL, 0, NULL, size, &bytes_returned, NULL, NULL);
10306     ok(ret == SOCKET_ERROR, "Got unexpected ret %d.\n", ret);
10307     ok(WSAGetLastError() == WSAEFAULT, "Got unexpected error %d.\n", WSAGetLastError());
10308     ok(bytes_returned == size, "Got unexpected bytes_returned %u, expected %u.\n", bytes_returned, size);
10309 
10310     ret = WSAIoctl(s, SIO_ADDRESS_LIST_QUERY, NULL, 0, address_list, 1, &bytes_returned, NULL, NULL);
10311     ok(ret == SOCKET_ERROR, "Got unexpected ret %d.\n", ret);
10312     ok(WSAGetLastError() == WSAEINVAL, "Got unexpected error %d.\n", WSAGetLastError());
10313     ok(bytes_returned == 0, "Got unexpected bytes_returned %u.\n", bytes_returned);
10314 
10315     ret = WSAIoctl(s, SIO_ADDRESS_LIST_QUERY, NULL, 0, address_list,
10316             FIELD_OFFSET(SOCKET_ADDRESS_LIST, Address[0]), &bytes_returned, NULL, NULL);
10317     ok(ret == SOCKET_ERROR, "Got unexpected ret %d.\n", ret);
10318     ok(WSAGetLastError() == WSAEFAULT, "Got unexpected error %d.\n", WSAGetLastError());
10319     ok(bytes_returned == size, "Got unexpected bytes_returned %u, expected %u.\n", bytes_returned, size);
10320 
10321     HeapFree(GetProcessHeap(), 0, address_list);
10322     closesocket(s);
10323 }
10324 
10325 static DWORD WINAPI inet_ntoa_thread_proc(void *param)
10326 {
10327     ULONG addr;
10328     const char *str;
10329     HANDLE *event = param;
10330 
10331     addr = inet_addr("4.3.2.1");
10332     ok(addr == htonl(0x04030201), "expected 0x04030201, got %08x\n", addr);
10333     str = inet_ntoa(*(struct in_addr *)&addr);
10334     ok(!strcmp(str, "4.3.2.1"), "expected 4.3.2.1, got %s\n", str);
10335 
10336     SetEvent(event[0]);
10337     WaitForSingleObject(event[1], 3000);
10338 
10339     return 0;
10340 }
10341 
10342 static void test_inet_ntoa(void)
10343 {
10344     ULONG addr;
10345     const char *str;
10346     HANDLE thread, event[2];
10347     DWORD tid;
10348 
10349     addr = inet_addr("1.2.3.4");
10350     ok(addr == htonl(0x01020304), "expected 0x01020304, got %08x\n", addr);
10351     str = inet_ntoa(*(struct in_addr *)&addr);
10352     ok(!strcmp(str, "1.2.3.4"), "expected 1.2.3.4, got %s\n", str);
10353 
10354     event[0] = CreateEventW(NULL, TRUE, FALSE, NULL);
10355     event[1] = CreateEventW(NULL, TRUE, FALSE, NULL);
10356 
10357     thread = CreateThread(NULL, 0, inet_ntoa_thread_proc, event, 0, &tid);
10358     WaitForSingleObject(event[0], 3000);
10359 
10360     ok(!strcmp(str, "1.2.3.4"), "expected 1.2.3.4, got %s\n", str);
10361 
10362     SetEvent(event[1]);
10363     WaitForSingleObject(thread, 3000);
10364 
10365     CloseHandle(event[0]);
10366     CloseHandle(event[1]);
10367     CloseHandle(thread);
10368 }
10369 
10370 static void test_WSALookupService(void)
10371 {
10372     char buffer[4096], strbuff[128];
10373     WSAQUERYSETW *qs = NULL;
10374     HANDLE hnd;
10375     PNLA_BLOB netdata;
10376     int ret;
10377     DWORD error, offset, bsize;
10378 
10379     if (!pWSALookupServiceBeginW || !pWSALookupServiceEnd || !pWSALookupServiceNextW)
10380     {
10381         win_skip("WSALookupServiceBeginW or WSALookupServiceEnd or WSALookupServiceNextW not found\n");
10382         return;
10383     }
10384 
10385     qs = (WSAQUERYSETW *)buffer;
10386     memset(qs, 0, sizeof(*qs));
10387 
10388     /* invalid parameter tests */
10389     ret = pWSALookupServiceBeginW(NULL, 0, &hnd);
10390     error = WSAGetLastError();
10391     ok(ret == SOCKET_ERROR, "WSALookupServiceBeginW should have failed\n");
10392 todo_wine
10393     ok(error == WSAEFAULT, "expected 10014, got %d\n", error);
10394 
10395     ret = pWSALookupServiceBeginW(qs, 0, NULL);
10396     error = WSAGetLastError();
10397     ok(ret == SOCKET_ERROR, "WSALookupServiceBeginW should have failed\n");
10398 todo_wine
10399     ok(error == WSAEFAULT, "expected 10014, got %d\n", error);
10400 
10401     ret = pWSALookupServiceBeginW(qs, 0, &hnd);
10402     error = WSAGetLastError();
10403     ok(ret == SOCKET_ERROR, "WSALookupServiceBeginW should have failed\n");
10404 todo_wine
10405     ok(error == WSAEINVAL
10406        || broken(error == ERROR_INVALID_PARAMETER) /* == XP */
10407        || broken(error == WSAEFAULT) /* == NT */
10408        || broken(error == WSASERVICE_NOT_FOUND) /* == 2000 */,
10409        "expected 10022, got %d\n", error);
10410 
10411     ret = pWSALookupServiceEnd(NULL);
10412     error = WSAGetLastError();
10413 todo_wine
10414     ok(ret == SOCKET_ERROR, "WSALookupServiceEnd should have failed\n");
10415 todo_wine
10416     ok(error == ERROR_INVALID_HANDLE, "expected 6, got %d\n", error);
10417 
10418     /* standard network list query */
10419     qs->dwSize = sizeof(*qs);
10420     hnd = (HANDLE)0xdeadbeef;
10421     ret = pWSALookupServiceBeginW(qs, LUP_RETURN_ALL | LUP_DEEP, &hnd);
10422     error = WSAGetLastError();
10423     if(ret && error == ERROR_INVALID_PARAMETER)
10424     {
10425         win_skip("the current WSALookupServiceBeginW test is not supported in win <= 2000\n");
10426         return;
10427     }
10428 
10429 todo_wine
10430     ok(!ret, "WSALookupServiceBeginW failed unexpectedly with error %d\n", error);
10431 todo_wine
10432     ok(hnd != (HANDLE)0xdeadbeef, "Handle was not filled\n");
10433 
10434     offset = 0;
10435     do
10436     {
10437         memset(qs, 0, sizeof(*qs));
10438         bsize = sizeof(buffer);
10439 
10440         if (pWSALookupServiceNextW(hnd, 0, &bsize, qs) == SOCKET_ERROR)
10441         {
10442             error = WSAGetLastError();
10443             if (error == WSA_E_NO_MORE) break;
10444             ok(0, "Error %d happened while listing services\n", error);
10445             break;
10446         }
10447 
10448         WideCharToMultiByte(CP_ACP, 0, qs->lpszServiceInstanceName, -1,
10449                             strbuff, sizeof(strbuff), NULL, NULL);
10450         trace("Network Name: %s\n", strbuff);
10451 
10452         /* network data is written in the blob field */
10453         if (qs->lpBlob)
10454         {
10455             /* each network may have multiple NLA_BLOB information structures */
10456             do
10457             {
10458                 netdata = (PNLA_BLOB) &qs->lpBlob->pBlobData[offset];
10459                 switch (netdata->header.type)
10460                 {
10461                     case NLA_RAW_DATA:
10462                         trace("\tNLA Data Type: NLA_RAW_DATA\n");
10463                         break;
10464                     case NLA_INTERFACE:
10465                         trace("\tNLA Data Type: NLA_INTERFACE\n");
10466                         trace("\t\tType: %d\n", netdata->data.interfaceData.dwType);
10467                         trace("\t\tSpeed: %d\n", netdata->data.interfaceData.dwSpeed);
10468                         trace("\t\tAdapter Name: %s\n", netdata->data.interfaceData.adapterName);
10469                         break;
10470                     case NLA_802_1X_LOCATION:
10471                         trace("\tNLA Data Type: NLA_802_1X_LOCATION\n");
10472                         trace("\t\tInformation: %s\n", netdata->data.locationData.information);
10473                         break;
10474                     case NLA_CONNECTIVITY:
10475                         switch (netdata->data.connectivity.type)
10476                         {
10477                             case NLA_NETWORK_AD_HOC:
10478                                 trace("\t\tNetwork Type: AD HOC\n");
10479                                 break;
10480                             case NLA_NETWORK_MANAGED:
10481                                 trace("\t\tNetwork Type: Managed\n");
10482                                 break;
10483                             case NLA_NETWORK_UNMANAGED:
10484                                 trace("\t\tNetwork Type: Unmanaged\n");
10485                                 break;
10486                             case NLA_NETWORK_UNKNOWN:
10487                                 trace("\t\tNetwork Type: Unknown\n");
10488                         }
10489                         switch (netdata->data.connectivity.internet)
10490                         {
10491                             case NLA_INTERNET_NO:
10492                                 trace("\t\tInternet connectivity: No\n");
10493                                 break;
10494                             case NLA_INTERNET_YES:
10495                                 trace("\t\tInternet connectivity: Yes\n");
10496                                 break;
10497                             case NLA_INTERNET_UNKNOWN:
10498                                 trace("\t\tInternet connectivity: Unknown\n");
10499                                 break;
10500                         }
10501                         break;
10502                     case NLA_ICS:
10503                         trace("\tNLA Data Type: NLA_ICS\n");
10504                         trace("\t\tSpeed: %d\n",
10505                                netdata->data.ICS.remote.speed);
10506                         trace("\t\tType: %d\n",
10507                                netdata->data.ICS.remote.type);
10508                         trace("\t\tState: %d\n",
10509                                netdata->data.ICS.remote.state);
10510                         WideCharToMultiByte(CP_ACP, 0, netdata->data.ICS.remote.machineName, -1,
10511                             strbuff, sizeof(strbuff), NULL, NULL);
10512                         trace("\t\tMachine Name: %s\n", strbuff);
10513                         WideCharToMultiByte(CP_ACP, 0, netdata->data.ICS.remote.sharedAdapterName, -1,
10514                             strbuff, sizeof(strbuff), NULL, NULL);
10515                         trace("\t\tShared Adapter Name: %s\n", strbuff);
10516                         break;
10517                     default:
10518                         trace("\tNLA Data Type: Unknown\n");
10519                         break;
10520                 }
10521             }
10522             while (offset);
10523         }
10524     }
10525     while (1);
10526 
10527     ret = pWSALookupServiceEnd(hnd);
10528     ok(!ret, "WSALookupServiceEnd failed unexpectedly\n");
10529 }
10530 
10531 static void test_WSAEnumNameSpaceProvidersA(void)
10532 {
10533     LPWSANAMESPACE_INFOA name = NULL;
10534     DWORD ret, error, blen = 0, i;
10535     if (!pWSAEnumNameSpaceProvidersA)
10536     {
10537         win_skip("WSAEnumNameSpaceProvidersA not found\n");
10538         return;
10539     }
10540 
10541     SetLastError(0xdeadbeef);
10542     ret = pWSAEnumNameSpaceProvidersA(&blen, name);
10543     error = WSAGetLastError();
10544 todo_wine
10545     ok(ret == SOCKET_ERROR, "Expected failure, got %u\n", ret);
10546 todo_wine
10547     ok(error == WSAEFAULT, "Expected 10014, got %u\n", error);
10548 
10549     /* Invalid parameter tests */
10550     SetLastError(0xdeadbeef);
10551     ret = pWSAEnumNameSpaceProvidersA(NULL, name);
10552     error = WSAGetLastError();
10553 todo_wine
10554     ok(ret == SOCKET_ERROR, "Expected failure, got %u\n", ret);
10555 todo_wine
10556     ok(error == WSAEFAULT, "Expected 10014, got %u\n", error);
10557 
10558     SetLastError(0xdeadbeef);
10559     ret = pWSAEnumNameSpaceProvidersA(NULL, NULL);
10560     error = WSAGetLastError();
10561 todo_wine
10562     ok(ret == SOCKET_ERROR, "Expected failure, got %u\n", ret);
10563 todo_wine
10564     ok(error == WSAEFAULT, "Expected 10014, got %u\n", error);
10565 
10566     SetLastError(0xdeadbeef);
10567     ret = pWSAEnumNameSpaceProvidersA(&blen, NULL);
10568     error = WSAGetLastError();
10569 todo_wine
10570     ok(ret == SOCKET_ERROR, "Expected failure, got %u\n", ret);
10571 todo_wine
10572     ok(error == WSAEFAULT, "Expected 10014, got %u\n", error);
10573 
10574 #ifdef __REACTOS__ /* ROSTESTS-233 */
10575     if (!blen)
10576     {
10577         skip("Failed to get length needed for name space providers.\n");
10578         return;
10579     }
10580 #endif
10581 
10582     name = HeapAlloc(GetProcessHeap(), 0, blen);
10583     if (!name)
10584     {
10585         skip("Failed to alloc memory\n");
10586         return;
10587     }
10588 
10589     ret = pWSAEnumNameSpaceProvidersA(&blen, name);
10590 todo_wine
10591     ok(ret > 0, "Expected more than zero name space providers\n");
10592 
10593     for (i = 0;i < ret; i++)
10594     {
10595         trace("Name space Identifier (%p): %s\n", name[i].lpszIdentifier,
10596               name[i].lpszIdentifier);
10597         switch (name[i].dwNameSpace)
10598         {
10599             case NS_DNS:
10600                 trace("\tName space ID: NS_DNS (%u)\n", name[i].dwNameSpace);
10601                 break;
10602             case NS_NLA:
10603                 trace("\tName space ID: NS_NLA (%u)\n", name[i].dwNameSpace);
10604                 break;
10605             default:
10606                 trace("\tName space ID: Unknown (%u)\n", name[i].dwNameSpace);
10607                 break;
10608         }
10609         trace("\tActive:  %d\n", name[i].fActive);
10610         trace("\tVersion: %d\n", name[i].dwVersion);
10611     }
10612 
10613     HeapFree(GetProcessHeap(), 0, name);
10614 }
10615 
10616 static void test_WSAEnumNameSpaceProvidersW(void)
10617 {
10618     LPWSANAMESPACE_INFOW name = NULL;
10619     DWORD ret, error, blen = 0, i;
10620     if (!pWSAEnumNameSpaceProvidersW)
10621     {
10622         win_skip("WSAEnumNameSpaceProvidersW not found\n");
10623         return;
10624     }
10625 
10626     SetLastError(0xdeadbeef);
10627     ret = pWSAEnumNameSpaceProvidersW(&blen, name);
10628     error = WSAGetLastError();
10629 todo_wine
10630     ok(ret == SOCKET_ERROR, "Expected failure, got %u\n", ret);
10631 todo_wine
10632     ok(error == WSAEFAULT, "Expected 10014, got %u\n", error);
10633 
10634     /* Invalid parameter tests */
10635     SetLastError(0xdeadbeef);
10636     ret = pWSAEnumNameSpaceProvidersW(NULL, name);
10637     error = WSAGetLastError();
10638 todo_wine
10639     ok(ret == SOCKET_ERROR, "Expected failure, got %u\n", ret);
10640 todo_wine
10641     ok(error == WSAEFAULT, "Expected 10014, got %u\n", error);
10642 
10643     SetLastError(0xdeadbeef);
10644     ret = pWSAEnumNameSpaceProvidersW(NULL, NULL);
10645     error = WSAGetLastError();
10646 todo_wine
10647     ok(ret == SOCKET_ERROR, "Expected failure, got %u\n", ret);
10648 todo_wine
10649     ok(error == WSAEFAULT, "Expected 10014, got %u\n", error);
10650 
10651     SetLastError(0xdeadbeef);
10652     ret = pWSAEnumNameSpaceProvidersW(&blen, NULL);
10653     error = WSAGetLastError();
10654 todo_wine
10655     ok(ret == SOCKET_ERROR, "Expected failure, got %u\n", ret);
10656 todo_wine
10657     ok(error == WSAEFAULT, "Expected 10014, got %u\n", error);
10658 
10659 #ifdef __REACTOS__ /* ROSTESTS-233 */
10660     if (!blen)
10661     {
10662         skip("Failed to get length needed for name space providers.\n");
10663         return;
10664     }
10665 #endif
10666 
10667     name = HeapAlloc(GetProcessHeap(), 0, blen);
10668     if (!name)
10669     {
10670         skip("Failed to alloc memory\n");
10671         return;
10672     }
10673 
10674     ret = pWSAEnumNameSpaceProvidersW(&blen, name);
10675 todo_wine
10676     ok(ret > 0, "Expected more than zero name space providers\n");
10677 
10678     for (i = 0;i < ret; i++)
10679     {
10680         trace("Name space Identifier (%p): %s\n", name[i].lpszIdentifier,
10681                wine_dbgstr_w(name[i].lpszIdentifier));
10682         switch (name[i].dwNameSpace)
10683         {
10684             case NS_DNS:
10685                 trace("\tName space ID: NS_DNS (%u)\n", name[i].dwNameSpace);
10686                 break;
10687             case NS_NLA:
10688                 trace("\tName space ID: NS_NLA (%u)\n", name[i].dwNameSpace);
10689                 break;
10690             default:
10691                 trace("\tName space ID: Unknown (%u)\n", name[i].dwNameSpace);
10692                 break;
10693         }
10694         trace("\tActive:  %d\n", name[i].fActive);
10695         trace("\tVersion: %d\n", name[i].dwVersion);
10696     }
10697 
10698     HeapFree(GetProcessHeap(), 0, name);
10699 }
10700 
10701 /**************** Main program  ***************/
10702 
10703 START_TEST( sock )
10704 {
10705     int i;
10706 
10707 /* Leave these tests at the beginning. They depend on WSAStartup not having been
10708  * called, which is done by Init() below. */
10709     test_WithoutWSAStartup();
10710     test_WithWSAStartup();
10711 
10712     Init();
10713 
10714     test_inet_ntoa();
10715     test_inet_pton();
10716     test_set_getsockopt();
10717     test_so_reuseaddr();
10718     test_ip_pktinfo();
10719     test_extendedSocketOptions();
10720 
10721     for (i = 0; i < sizeof(tests)/sizeof(tests[0]); i++)
10722     {
10723         trace ( " **** STARTING TEST %d ****\n", i );
10724         do_test (  &tests[i] );
10725         trace ( " **** TEST %d COMPLETE ****\n", i );
10726     }
10727 
10728     test_UDP();
10729 
10730     test_getservbyname();
10731     test_WSASocket();
10732     test_WSADuplicateSocket();
10733     test_WSAEnumNetworkEvents();
10734 
10735     test_WSAAddressToStringA();
10736     test_WSAAddressToStringW();
10737 
10738     test_WSAStringToAddressA();
10739     test_WSAStringToAddressW();
10740 
10741     test_errors();
10742     test_listen();
10743     test_select();
10744     test_accept();
10745     test_getpeername();
10746     test_getsockname();
10747     test_inet_addr();
10748     test_addr_to_print();
10749     test_ioctlsocket();
10750     test_dns();
10751     test_gethostbyname();
10752     test_gethostbyname_hack();
10753     test_gethostname();
10754 
10755     test_WSASendMsg();
10756     test_WSASendTo();
10757     test_WSARecv();
10758     test_WSAPoll();
10759 
10760     test_events(0);
10761     test_events(1);
10762 
10763     test_ipv6only();
10764     test_TransmitFile();
10765     test_GetAddrInfoW();
10766     test_GetAddrInfoExW();
10767     test_getaddrinfo();
10768     test_AcceptEx();
10769     test_ConnectEx();
10770     test_DisconnectEx();
10771 
10772     test_sioRoutingInterfaceQuery();
10773     test_sioAddressListChange();
10774 
10775     test_WSALookupService();
10776     test_WSAEnumNameSpaceProvidersA();
10777     test_WSAEnumNameSpaceProvidersW();
10778 
10779     test_WSAAsyncGetServByPort();
10780     test_WSAAsyncGetServByName();
10781 
10782     test_completion_port();
10783     test_address_list_query();
10784 
10785     /* this is an io heavy test, do it at the end so the kernel doesn't start dropping packets */
10786     test_send();
10787     test_synchronous_WSAIoctl();
10788 
10789     Exit();
10790 }
10791